function XML=mat2xml(MAT,VARNAME)

% MAT2XML converts structured variable MAT into XML string
%
%Syntax XML=mat2xml(MAT,VARNAME)
%
%Description
%  MAT : structured varable
%  VARNAME : variable name (string)
%  XML : xml version of structured variable (string)
%
% See Also: XML2MAT
%
% Jonas Almeida, almeidaj@musc.edu, 20 Aug 2002, XML4MAT Tbox

if nargin<2;VARNAME='ans';end % if not provided make it a matlab answer variable
w=whos('MAT');w.name=VARNAME;

XML=['<',w.name,' class="',w.class,'" size="',num2str(w.size),'">'];
if strcmp(w.class,'char')
    XML=[XML,spcharin(MAT(:)')];
elseif strcmp(w.class,'struct')
    names=fieldnames(MAT);
    %struct_fields=[' fields="',names{1}];for j=2:length(names);struct_fields=[struct_fields,' ',names{j}];end;struct_fields=[struct_fields,'">'];XML=[XML(1:(end-1)),struct_fields];
    for i=1:prod(w.size)
        for j=1:length(names)
            XML=[XML,mat2xml(eval(['MAT(i).',names{j}]),names{j})];
        end
    end
elseif strcmp(w.class,'cell')
    for i=1:prod(w.size)
        XML=[XML,mat2xml(MAT{i},'cell')];
    end
else %if strcmp(w.class,'double')|strcmp(w.class,'single')
    XML=[XML,num2str(MAT(:)')];
end
XML=[XML,'</',w.name,'>'];
XML=regexprep(XML,'\s{2,}',' ');


function y = LSQRwrapper(x,transp,A,At)
% y = LSQRwrapper(x,trans,A,At)
% NESTA Version 1.1

% Stephen Becker, 11/12/09

if strcmpi(transp,'transp')
    y = At(x);
elseif strcmpi(transp,'notransp')
    y = A(x);
end


%kgtubeness 'Replace Lines with Tesselated Cylinders'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros gtubeness.pane file
%
% Parameters:
% InputFile: i 'Input Geometry ', required: 'Input geometry object.'
% Double: scale 'Radius Scale', default: 0.1: 'A scalar which indicates the radius of the tube.'
% Integer: subdivisions 'Subdivisions', default: 3: 'The number of sides for each tube will be 2^(subdivisions - 1).'
% OutputFile: o 'Output Geometry', required: 'Tube-ified geometry object'
%
% Example: o = kgtubeness(i, {'i','';'scale',0.1;'subdivisions',3;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% gtubeness - Replace Lines with Tesselated Cylinders
%
%  DESCRIPTION
% Filter for geometry objects in which line segments will be replaced with
% tubes.  Non-line-segment primitives will be passed through unchanged.
%
% Currently the only "cap_style" options that work are "None" and "Round caps".
%
%
%
%  EXAMPLES
%
%  "SEE ALSO"
%
%  RESTRICTIONS
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1996,1997 , The Regents of the University of California.  All rights reserved.
%

function varargout = kgtubeness(varargin)
if nargin ==0
  Inputs={};arglist={'',''};
elseif nargin ==1
  Inputs=varargin{1};arglist={'',''};
elseif nargin ==2
  Inputs=varargin{1}; arglist=varargin{2};
else error('Usage: [out1,..] = kgtubeness(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i', '__input';'scale', 0.1;'subdivisions', 3;'o', '__output'};
maxval={0,1,6,0};
minval={0,1,2,0};
istoggle=[0,1,1,0];
was_set=istoggle * 0;
paramtype={'InputFile','Double','Integer','OutputFile'};
% identify the input arrays and assign them to the arguments as stated by the user
if ~iscell(Inputs)
Inputs = {Inputs};
end
NumReqOutputs=1; nextinput=1; nextoutput=1;
  for ii=1:size(arglist,1)
  wasmatched=0;
  for jj=1:size(narglist,1)
   if strcmp(arglist{ii,1},narglist{jj,1})  % a given argument was matched to the possible arguments
     wasmatched = 1;
     was_set(jj) = 1;
     if strcmp(narglist{jj,2}, '__input')
      if (nextinput > length(Inputs))
        error(['Input ' narglist{jj,1} ' has no corresponding input!']);
      end
      narglist{jj,2} = 'OK_in';
      nextinput = nextinput + 1;
     elseif strcmp(narglist{jj,2}, '__output')
      if (nextoutput > nargout)
        error(['Output nr. ' narglist{jj,1} ' is not present in the assignment list of outputs !']);
      end
      if (isempty(arglist{ii,2}))
        narglist{jj,2} = 'OK_out';
      else
        narglist{jj,2} = arglist{ii,2};
      end

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


% Labels 64ths of imagae and saves to file
numImages = length(dir('C:\Users\brend_000\Documents\MATLAB\Machine Learning\Ghost Target\Images\cambride')) - 2;
for imageNum = 1:5
    imgLabel = cell(8,8);
    image = imread(['C:\Users\brend_000\Documents\MATLAB\Machine Learning\Ghost Target\Images\cambridge\img',num2str(imageNum),'.jpg']);
    image = nxel(8,image);
    for i = 1:8
        for j = 1:8
            imshow(image{i,j})
            imgLabel{i,j} = input('Label?','s');
        end
    end
    save(['Images\cambridge_labels\img',num2str(imageNum),'.mat'],'imgLabel')
end


function hhh=tapas_uniqc_hline(y,in1,in2)
% function h=hline(y, linetype, label)
%
% Draws a horizontal line on the current axes at the location specified by 'y'.  Optional arguments are
% 'linetype' (default is 'r:') and 'label', which applies a text label to the graph near the line.  The
% label appears in the same color as the line.
%
% The line is held on the current axes, and after plotting the line, the function returns the axes to
% its prior hold state.
%
% The HandleVisibility property of the line object is set to "off", so not only does it not appear on
% legends, but it is not findable by using findobj.  Specifying an output argument causes the function to
% return a handle to the line, so it can be manipulated or deleted.  Also, the HandleVisibility can be
% overridden by setting the root's ShowHiddenHandles property to on.
%
% h = tapas_uniqc_hline(42,'g','The Answer')
%
% returns a handle to a green horizontal line on the current axes at y=42, and creates a text object on
% the current axes, close to the line, which reads "The Answer".
%
% tapas_uniqc_hline also supports vector inputs to draw multiple lines at once.  For example,
%
% tapas_uniqc_hline([4 8 12],{'g','r','b'},{'l1','lab2','LABELC'})
%
% draws three lines with the appropriate labels and colors.
%
% By Brandon Kuczenski for Kensington Labs.
% brandon_kuczenski@kensingtonlabs.com
% 8 November 2001

if length(y)>1  % vector input
    for I=1:length(y)
        switch nargin
        case 1
            linetype='r:';
            label='';
        case 2
            if ~iscell(in1)
                in1={in1};
            end
            if I>length(in1)
                linetype=in1{end};
            else
                linetype=in1{I};
            end
            label='';
        case 3
            if ~iscell(in1)
                in1={in1};
            end
            if ~iscell(in2)
                in2={in2};
            end
            if I>length(in1)
                linetype=in1{end};
            else
                linetype=in1{I};
            end
            if I>length(in2)
                label=in2{end};
            else
                label=in2{I};
            end
        end
        h(I)=tapas_uniqc_hline(y(I),linetype,label);
    end
else
    switch nargin
    case 1
        linetype='r:';
        label='';
    case 2
        linetype=in1;
        label='';
    case 3
        linetype=in1;
        label=in2;
    end

    g=ishold(gca);
    hold on

    x=get(gca,'xlim');
    h=plot(x,[y y],linetype);
    if ~isempty(label)
        yy=get(gca,'ylim');
        yrange=yy(2)-yy(1);
        yunit=(y-yy(1))/yrange;
        if yunit<0.2
            text(x(1)+0.02*(x(2)-x(1)),y+0.02*yrange,label,'color',get(h,'color'))
        else
            text(x(1)+0.02*(x(2)-x(1)),y-0.02*yrange,label,'color',get(h,'color'))
        end
    end

    if g==0
    hold off
    end
    set(h,'tag','hline','handlevisibility','off') % this last part is so that it doesn't show up on legends
end % else

if nargout
    hhh=h;
end


function test_suite = test_parametrize
%TESTPARAMETRIZE  One-line description here, please.
%
%   output = testParametrize(input)
%
%   Example
%   testParametrize
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-05-27,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testSquare(testCase) %#ok<*DEFNU>
% Tests with a square of perimeter 40
p1 = [10 10];
p2 = [20 10];
p3 = [20 20];
p4 = [10 20];
square = [p1;p2;p3;p4];
exp = [0;10;20;30];

testCase.assertEqual(exp, parametrize(square));

function testSquare3d(testCase)
% Tests with a square of perimeter 40
p1 = [10 10 0];
p2 = [20 10 0];
p3 = [20 20 0];
p4 = [10 20 0];
square = [p1;p2;p3;p4];
exp = [0;10;20;30];

testCase.assertEqual(exp, parametrize(square));

function testSquareNormaized(testCase) %#ok<*DEFNU>
% Tests with a square of perimeter 40
p1 = [10 10];
p2 = [20 10];
p3 = [20 20];
p4 = [10 20];
square = [p1;p2;p3;p4;p1];
exp = [0;.25;.5;.75;1];

testCase.assertEqual(exp, parametrize(square, 'normalize', true));


function kern = linardKernExpandParam(kern, params)

% LINARDKERNEXPANDPARAM Create kernel structure from LINARD kernel's parameters.
% FORMAT
% DESC returns a automatic relevance determination linear kernel structure filled with the
% parameters in the given vector. This is used as a helper function to
% enable parameters to be optimised in, for example, the NETLAB
% optimisation functions.
% ARG kern : the kernel structure in which the parameters are to be
% placed.
% ARG param : vector of parameters which are to be placed in the
% kernel structure.
% RETURN kern : kernel structure with the given parameters in the
% relevant locations.
%
% SEEALSO : linardKernParamInit, linardKernExtractParam, kernExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

kern.variance = params(1);
kern.inputScales = params(2:end);


classdef TensorRepresentation < RepresentationDescriptor

    properties (Access = protected)
        dim
    end

    methods (Access = public)

        function d = getDimension(obj)
            d = obj.dim;
        end
    end

    methods (Access = protected)

        function obj = TensorRepresentation()
            obj.loadDimensionValue()
        end

        function loadRepresentationVariable(obj)
            obj.representation = 'tensor';
        end
    end

    methods (Access = private)

        function loadDimensionValue(obj)
            tensSize = obj.getTensorSize();
            obj.dim = tensSize(1);
        end

    end
end


function rxnsOut = plotPredictedExchange(predictedFluxes, otherFluxes, extraFluxes, param)
% plot a comparison of experimental and predicted exchange reaction rates
%
% INPUT
% predictedFluxes:   table with the following variables
%           * .rxns:    k x 1 cell array of reaction identifiers
%           * .v:       k x 1 double of predicted mean flux
%           * .lb:      k x 1 double lower bound on reaction flux
%           * .ub:      k x 1 double upper bound on reaction flux
%           * .labels:  k x 1 cell array of labels to display on y axis
%           * .Properties.Description: string describing the data, used in plot legend
%
% OPTIONAL INPUT
% otherFluxes:  table with the following variables
%           * .rxns:    k x 1 cell array of reaction identifiers
%           * .Properties.Description: sring describing the data, used in plot legend
%           * .labels:  k x 1 cell array of labels to display on y axis
%   and
%           * .mean:    k x 1 double of measured mean flux
%           * .SD:      k x 1 double standard deviation of the measured flux
%
%   or
%           * .v:       k x 1 double of predicted mean flux
%           * .lb:      k x 1 double lower bound on reaction flux
%           * .ub:      k x 1 double upper bound on reaction flux
%
%
% param: paramters structure with the following fields
%           * .rxns: subset of reactions to plot
%           * .measuredFluxes  {(1),0} set to zero to not display experimental fluxes
%
%           * .labelType determines which y axes lables to display
%                       'metabolitePlatform' = platform left and metabolite name right
%                       'metabolite'         = metabolite only right  (default)
%                       'platform'           = platform only left
%           * .expOrder {(1),0}
%                       1  = order reactions by value of experimental flux
%                       0  = order reactions by value of predicted flux (predictedFluxes) for each reaction corresponding to an experimental flux
%           * .saveFigures = 1 saves figure as .fig and .png to current directory
%           * .plotTitle: title of the plot

if exist('predictedFluxes','var')
    predDescription = predictedFluxes.Properties.Description;
else
    error('predictedFluxes missing: must provide a predicted solution');
end
if exist('otherFluxes','var') && ~isempty(otherFluxes)
    otherDescription = otherFluxes.Properties.Description;
else
    otherFluxes = [];
    otherDescription = '';
end
if exist('extraFluxes','var') && ~isempty(extraFluxes)
    extraDescription = extraFluxes.Properties.Description;
else
    extraFluxes = [];
    extraDescription = '';
end
if ~exist('param','var')
    param = struct();
end
if ~isfield(param,'labelType')
    param.labelType = 'metabolite';
end
if ~isfield(param,'saveFigures')
    param.saveFigures = 0;
end
if ~isfield(param,'expOrder')
    param.expOrder = 1;
end
if ~isfield(param,'plotTitle')
    param.plotTitle = [];
end
if ~isfield(param,'measuredBounds')
    param.measuredBounds = 1;
end
if ~isfield(param,'predictedBounds')
    param.predictedBounds = 1;
end
if ~isfield(param,'otherBounds')
    param.otherBounds = 1;
end
if ~isfield(param,'extraBounds')
    param.extraBounds = 1;
end
if ~isfield(param,'exchangesOnly')
    param.exchangesOnly = 1;
end
if ~isvar(predictedFluxes,'labels')
    if isvar(predictedFluxes,'metNames')
        predictedFluxes.labels = predictedFluxes.metNames;
    end
end
if isvar(predictedFluxes,'rxns')
    predictedFluxes.rxns = predictedFluxes.rxns;
end
if ~isempty(otherFluxes)
    if isvar(otherFluxes,'rxns')
        otherFluxes.rxns = otherFluxes.rxns;
    end
    if ~isvar(otherFluxes,'rxns')
        error('otherFluxes.rxns missing - needed to map to other variables')
    end
end
if ~isempty(extraFluxes)
    if isvar(extraFluxes,'rxns')
        extraFluxes.rxns = extraFluxes.rxns;
    end
    if ~isvar(extraFluxes,'rxns')
        error('extraFluxes.rxns missing - needed to map to other variables')
    end
end

%restrict to a subset of fluxes
if isfield(param,'rxns')
    if isempty(param.rxns)
        fprintf('%s\n','plotPredictedExchange: param.rxns is empty, nothing to plot')
        return
    else
        %hack
        predictedFluxes = predictedFluxes(ismember(predictedFluxes.rxns,param.rxns) & ~ismember(predictedFluxes.labels,'Facilitated Diffusion'),:);
    end
end

% for i=1:length(predictedFluxes.labels)
%     labels2 = strrep(predictedFluxes.labels{i},' for ', ' of ');
%     predictedFluxes.labels{i} = [predictedFluxes.labels{i} ', ' labels2];
% end

%order the predicted exchanges
predictedFluxes.zerobool = (predictedFluxes.v-1e-5)<=0 & (predictedFluxes.v+1e-5)>=0;
predictedFluxes.posbool = sign(predictedFluxes.v)==1 & ~predictedFluxes.zerobool;
predictedFluxes.negbool = sign(predictedFluxes.v)==-1 & ~predictedFluxes.zerobool;
predictedFluxes.uptakeProbability = normcdf(0,predictedFluxes.v,abs(predictedFluxes.v)/10);

toRankOrder = zeros(length(predictedFluxes.v),1);
toRankOrder(predictedFluxes.zerobool) = predictedFluxes.uptakeProbability(predictedFluxes.zerobool);
toRankOrder(predictedFluxes.posbool) =  predictedFluxes.v(predictedFluxes.posbool)+1;
toRankOrder(predictedFluxes.negbool)=predictedFluxes.v(predictedFluxes.negbool);

if 1
    [sortedUptakeProbability,xi] = sort(toRankOrder);
else
    [sortedUptakeProbability,xi] = sort(predictedFluxes.uptakeProbability,'descend');
end
predictedFluxes = predictedFluxes(xi,:);
zerobool = predictedFluxes.zerobool;
posbool = predictedFluxes.posbool;
negbool = predictedFluxes.negbool;

%use log modulus transformation
v = logmod(predictedFluxes.v,10);
if isvar(predictedFluxes,'lb') && isvar(predictedFluxes,'ub')
    vl = logmod(predictedFluxes.lb,10);
    vl = v - vl;
    vu = logmod(predictedFluxes.ub,10);
    vu = vu - v;
else
    xl = logmod(measuredFluxes.mean - measuredFluxes.SD,10);
    xl = x - xl;
    xu = logmod(measuredFluxes.mean + measuredFluxes.SD,10);
    xu = xu - x;
end

if isempty(otherFluxes)
    min_v = min(v);
    max_v = max(v);
    bool=~isnan(v);
else
    %place the other fluxes in the same order as the predictions
    otherFluxes = mapAontoB(otherFluxes.rxns,predictedFluxes.rxns, otherFluxes);

    if isvar(otherFluxes,'v') && isvar(otherFluxes,'lb') && isvar(otherFluxes,'ub')
        %use log modulus transformation
        v2 = logmod(otherFluxes.v,10);
        v2l = logmod(otherFluxes.lb,10);
        v2l = v2 - v2l;
        v2u = logmod(otherFluxes.ub,10);
        v2u = v2u - v2;
    elseif isvar(otherFluxes,'mean') && isvar(otherFluxes,'SD')
        %use log modulus transformation
        v2 = logmod(otherFluxes.mean,10);
        v2l = logmod(otherFluxes.mean - otherFluxes.SD,10);
        v2l = v2 - v2l;
        v2u = logmod(otherFluxes.mean + otherFluxes.SD,10);
        v2u = v2u - v2;
    else
        error('Unrecognised input: otherFluxes')
    end

    %limits
    min_v = min([v;v2]);
    max_v = max([v;v2]);

    bool=~isnan(v) & ~isnan(v2);
end

if isempty(extraFluxes)
    if isempty(otherFluxes)
        min_v = min(v);
        max_v = max(v);
        bool=~isnan(v);
    else
        min_v = min([v;v2]);
        max_v = max([v;v2]);
        bool=~isnan(v) & ~isnan(v2);
    end
else
    %place the other fluxes in the same order as the predictions
    extraFluxes = mapAontoB(extraFluxes.rxns,predictedFluxes.rxns, extraFluxes);

    if isvar(extraFluxes,'v') && isvar(extraFluxes,'lb') && isvar(extraFluxes,'ub')
        %use log modulus transformation
        v3 = logmod(extraFluxes.v,10);
        v3l = logmod(extraFluxes.lb,10);
        v3l = v3 - v3l;
        v3u = logmod(extraFluxes.ub,10);
        v3u = v3u - v3;
    elseif isvar(extraFluxes,'mean') && isvar(extraFluxes,'SD')
        %use log modulus transformation
        v3 = logmod(extraFluxes.mean,10);
        v3l = logmod(extraFluxes.mean - extraFluxes.SD,10);
        v3l = v3 - v3l;
        v3u = logmod(extraFluxes.mean + extraFluxes.SD,10);
        v3u = v3u - v3;
    else
        error('Unrecognised input: extraFluxes')
    end

    min_v = min([v;v2;v3]);
    max_v = max([v;v2;v3]);

    bool=~isnan(v) & ~isnan(v2) & ~isnan(v3);
end

%figure('Renderer', 'painters', 'Position', [10 10 900 1500])
%figure('units','normalized','outerposition',[0 0 1 1])
figure('units','normalized','Position',[0 0 0.5 1.5])
hold on

%patch in the background
X = [min_v max_v max_v min_v];

Y = [nnz(negbool & bool)+nnz(zerobool & bool)+0.5 nnz(negbool & bool)+nnz(zerobool & bool)+0.5 length(predictedFluxes.v(bool))+0.5 length(predictedFluxes.v(bool))+0.5];

patch(X,Y,[221/255, 192/255, 237/255],'FaceAlpha',0.5)

if any(zerobool)
    Y = [nnz(negbool & bool)+0.5 nnz(negbool & bool)+0.5 nnz(negbool & bool)+nnz(zerobool & bool)+0.5 nnz(negbool & bool)+nnz(zerobool & bool)+0.5];
    patch(X,Y,[192/255, 237/255, 207/255],'FaceAlpha',0.5)
end

Y = [0 0 nnz(negbool & bool)+0.5 nnz(negbool & bool)+0.5];
patch(X,Y,[192/255, 233/255, 237/255],'FaceAlpha',0.9)

if param.predictedBounds
    %predicted fluxes
    errorbar(v(bool),(1:length(v(bool))),vl(bool),vu(bool),'horizontal','dk','LineWidth',1.5,'MarkerSize',10)%,'MarkerFaceColor',[1 1 1])
else
    %predicted fluxes
    plot(v(bool),1:length(v(bool)),'dk','MarkerSize',12)%,'MarkerFaceColor',[1 1 1])
end

%x & y limits
ylim([0,length(predictedFluxes.v(bool))+0.5])

%other fluxes
if ~isempty(otherFluxes)
    if param.otherBounds
        errorbar(v2(bool),(1:length(v2(bool)))-0.2,v2l(bool),v2u(bool),'horizontal','o','LineWidth',1.5,'MarkerSize',10, 'MarkerEdgeColor','red','MarkerFaceColor',[1 .6 .6])%,'MarkerFaceColor',[1 1 1])
    else
        %other fluxes
        plot(v2(bool),(1:length(v2(bool)))-0.2,'o','MarkerSize',10,'MarkerEdgeColor','red','MarkerFaceColor',[1 .6 .6])
    end

    xlim([min_v max_v])
    %xlim([-0.5 0.5])
else
    xlim([min_v max_v])
    %xlim([-0.5 0.5])
    %title(['Comparison of \color{blue}measured \color{black}and \color{red}predicted \color{black}net exchange reaction rates. (Objective ' solution1 ')'])
end

%extra fluxes
if ~isempty(extraFluxes)
    if param.extraBounds
        errorbar(v3(bool),(1:length(v3(bool)))-0.4,v3l(bool),v3u(bool),'horizontal','x','LineWidth',1.5,'MarkerSize',10, 'MarkerEdgeColor','magenta','MarkerFaceColor',[1 .6 .6])%,'MarkerFaceColor',[1 1 1])
    else
        %extra fluxes
        plot(v3(bool),(1:length(v3(bool)))-0.4,'x','MarkerSize',10,'MarkerEdgeColor','magenta','MarkerFaceColor',[1 .6 .6])
    end

    xlim([min_v max_v])
    %xlim([-0.5 0.5])
else
    xlim([min_v max_v])
    %xlim([-0.5 0.5])
    %title(['Comparison of \color{blue}measured \color{black}and \color{red}predicted \color{black}net exchange reaction rates. (Objective ' solution1 ')'])
end

if isempty(param.plotTitle)
    %title(['Predicted net reaction rates: ' predDescription ' vs ' otherDescription])
else
    title(param.plotTitle);
end

if param.exchangesOnly
    if any(zerobool)
        firstLegendNames = {'secretion','unchanged','uptake'};
    else
        firstLegendNames = {'secretion','uptake'};
    end
else
    if any(zerobool)
        firstLegendNames = {'secretion/forward flux','unchanged/zero','uptake/negative flux'};
    else
        firstLegendNames = {'secretion/forward flux','uptake/negative flux'};
    end
end

if isempty(otherFluxes)
    legend([firstLegendNames, predDescription],'location','northwest');
else
    if isempty(extraFluxes)
        legend([firstLegendNames,predDescription,otherDescription],'location','northwest');
    else
         legend([firstLegendNames,predDescription,otherDescription,extraDescription],'location','northwest');
    end
end
xlabel('Net flux (uMol/gDW/hr) on $\log_{10}$ scale: $\textrm{sign}(x) \times \log_{10}(1+x)$','interpreter','latex');

%labels
ax = gca;

%xtick=[-100:10:100];
%xticklab = cellstr(num2str(sign(xtick).*log10(1+abs(xtick)), '%d'));
%set(gca,'XTick',xtick,'XTickLabel',xticklab,'TickLabelInterpreter','tex')

ax.YTick = 1:length(predictedFluxes.v(bool));
ax.YTickLabel = predictedFluxes.labels(bool);
rxnsOut = predictedFluxes.rxns(bool);
%hack to fix some metabolite lables

ax.YTickLabel = strrep(ax.YTickLabel,'Acetyl Isoleucine (Chemspider Id: 9964364)','Acetyl Isoleucine');
ax.YTickLabel = strrep(ax.YTickLabel,'3, 4-dihydroxy','3,4-dihydroxy');
ax.YTickLabel = strrep(ax.YTickLabel,'N-Acetyl-Tyrosine','N-Acetyl-L-tyrosine');
ax.YTickLabel = strrep(ax.YTickLabel,'Oxugen','Oxygen');
ax.YTickLabel = strrep(ax.YTickLabel,'Excahnge of ','');
ax.YTickLabel = strrep(ax.YTickLabel,'CYOR_u10mi','Oxidative phosphorylation (CYOR_u10mi)');
ax.YTickLabel = strrep(ax.YTickLabel,'NADH2_u10mi','NADH Dehydrogenase, Mitochondrial (NADH2_u10m)');

if param.exchangesOnly
    ax.YTickLabel = strrep(ax.YTickLabel,'Exchange of ','');
    ax.YTickLabel = strrep(ax.YTickLabel,' demand','');
end

ax.TickLabelInterpreter='none';
ax.FontSize = 14;
switch param.labelType
    case 'metabolitePlatform'
        ax.YAxisLocation = 'right';
    case 'metabolite'
        ax.YAxisLocation = 'right';
    case 'platform'
        ax.YAxisLocation = 'left';
end

%         %right labels
%         plot(v,1:nnz(predictedExLOCB),'*r')
%         axL = gca;
%         axL.YAxisLocation = 'right';
%         axL.Color = 'none';
%         axL.Box = 'off';
%         yticks(1:length(measuredFluxes.mean))
%         axL.TickLabelInterpreter='latex';
%         axL.YColor ='black';
%         axL.FontSize = 10;
%         yt = yticks;
%         yticklabels(measuredFluxes.labelsR)

grid on
ax = gca;
ax.GridColor = [0 .5 .5];
ax.GridLineStyle = '--';
ax.GridAlpha = 0.5;
ax.Layer = 'top';

if 0
    xlim([-0.25 0.15])
    ylim([15.5 69.5])
    zoomed = 'zoom';
else
    zoomed = '';
end
if isempty(otherFluxes)
    descriptions = predDescription;
else
    descriptions = [predDescription '_vs_' otherDescription];
end

%%%% TODO %%% take the model name from the model structure
%     savefig(['iDN1_measured_vs_predicted_exchanges_' names '_' labelType zoomed])
%     saveas(gcf,['iDN1_measured_vs_predicted_exchanges_' names '_' labelType zoomed],'png')
if param.saveFigures
    savefig(['predicted_exchanges_' names '_' param.labelType zoomed])
    saveas(gcf,['predicted_exchanges_' names '_' param.labelType zoomed],'png')
end


disp('================================== transform ==============================')
transform

disp('================================== trajectory ==============================')
trajectory

disp('================================== jacobian ==============================')
jacobian

disp('================================== kinematics ==============================')
kinematics

disp('================================== dynamics ==============================')
dynamics

disp('================================== demos ==============================')
pause off
rttrdemo
rtfkdemo
rtikdemo
rttgdemo
rtandemo
rtjademo
rtfddemo
rtidemo


function turkRemainingHITs(input_csv_fname, result_csv_fname, output_csv_fname, uniqueColumn)
% this function take a turk input.csv file and result.csv file
% and output a file remaining_input.csv
% for the HITs that haven't been done
% based on a specific column
%{
%example:
input_csv_fname    = '/data/vision/torralba/gigaSUN/inputTurk/c/cybercafe.csv';
result_csv_fname   = '/data/vision/torralba/gigaSUN/resultTurk/c/cybercafe.csv';
output_csv_fname   = '/data/vision/torralba/gigaSUN/inputTurk/c/cybercafe_2nd.csv';
uniqueColumn = 'sunID';
%}

input_csv  = readCSVfromMTurk(input_csv_fname);
result_csv = readCSVfromMTurk(result_csv_fname);

uniqueColumnIDinput = find(ismember(input_csv(1,:),uniqueColumn));
uniqueColumnIDresult = find(ismember(result_csv(1,:),['Input.' uniqueColumn]));

good_input_row = [];
for row = 2:size(input_csv,1)
    if ~any(find(ismember(result_csv(2:end,uniqueColumnIDresult)',input_csv{row,uniqueColumnIDinput})))
        good_input_row(end+1) = row;
    end
end

fp = fopen(output_csv_fname,'w');
if ~isempty(good_input_row)

    fid = fopen(input_csv_fname,'r');
    tline = fgetl(fid);
    fprintf(fp,'%s\n',tline);
    for row = 2:size(input_csv,1)
        tline = fgetl(fid);
        if ~isempty(find(good_input_row, row))
            fprintf(fp,'%s\n',tline);
        end
    end
    fclose(fid);
end
fclose(fp);


function sParams = rmStimTemplate(vw, nScans)
% Defines the retinotopy model stimulus slot
%
%    sParams = rmStimTemplate(vw, nScans)
%
% This routine defines all of the parameters in a rm stimulus.  If you ever
% change the default, you must edit this function

n = viewGet(vw,'nscans');
if notDefined('nScans'), nScans = n; end

sParams = struct;

for ii=1:nScans

    sParams(ii).stimType   = '8Bars';
    sParams(ii).stimSize   =  14;
    sParams(ii).stimWidth  =  45;
    sParams(ii).stimStart  =  0;
    sParams(ii).stimDir    =  0;
    sParams(ii).nCycles    =  6;
    sParams(ii).nStimOnOff =  0;
    sParams(ii).nUniqueRep =  1;
    sParams(ii).prescanDuration = 8;
    sParams(ii).nDCT = 0;
    sParams(ii).hrfType =  'one gamma (Boynton style)';  % 'two gammas (SPM style)'
    sParams(ii).hrfParams = {[1.68 3 2.05],[5.4 5.2 10.8 7.35 0.35]};

    %If we are within the number scans in the dataTYPES, get frame
    %parameters from the view struct
    if ii <= n,
        sParams(ii).framePeriod = viewGet(vw,'framePeriod',ii);
        sParams(ii).nFrames     = viewGet(vw,'nFrames',ii);
    % Otherwise copy them from the previous scan
    else
        sParams(ii).framePeriod = sParams(ii-1).framePeriod;
        sParams(ii).nFrames     = sParams(ii-1).nFrames;
    end

    sParams(ii).fliprotate = [0 0 0];
    sParams(ii).imFile      = 'None';
    sParams(ii).jitterFile  = 'None';
    sParams(ii).paramsFile  = 'None';
    sParams(ii).imFilter    = 'None';

end


function test_suite=test_assert_greater_than()
    try % assignment of 'localfunctions' is necessary in Matlab >= 2016
        test_functions=localfunctions();
    catch % no problem; early Matlab versions can use initTestSuite fine
    end
    initTestSuite;

function test_assert_greater_than_exceptions
    assertExceptionThrown(@()assertGreaterThan([1 2],[1,2,3]),...
                          'assertGreaterThan:sizeNotEqual');
    assertExceptionThrown(@()assertGreaterThan([1,1],[0;0]),...
                          'assertGreaterThan:sizeNotEqual');
    assertExceptionThrown(@()assertGreaterThan([1],'a'), ...
                          'assertGreaterThan:classNotEqual');
    assertExceptionThrown(@()assertGreaterThan(1,1), ...
                          'assertGreaterThan:notGreaterThan');
    assertExceptionThrown(@()assertGreaterThan([2,3,3],[1,2,3]), ...
                          'assertGreaterThan:notGreaterThan');
    assertExceptionThrown(@()assertGreaterThan(nan,nan), ...
                          'assertGreaterThan:notGreaterThan');
    assertExceptionThrown(@()assertGreaterThan(nan,1), ...
                          'assertGreaterThan:notGreaterThan');
    assertExceptionThrown(@()assertGreaterThan(1,nan), ...
                          'assertGreaterThan:notGreaterThan');
    assertExceptionThrown(@()assertGreaterThan(ones(2,2,2,2),ones(2,2,2,2)*nan), ...
                          'assertGreaterThan:notGreaterThan');

    a = zeros(2,2,2,2);
    assertExceptionThrown(@()assertGreaterThan(a,ones(2,2,2,2)), ...
                          'assertGreaterThan:notGreaterThan');
    a(1,1,1,1) = 1;
    assertExceptionThrown(@()assertGreaterThan(a,ones(2,2,2,2)), ...
                          'assertGreaterThan:notGreaterThan');

function test_assert_greater_than_passes
    assertGreaterThan(1,0);
    assertGreaterThan([1,1],[0,0]);
    assertGreaterThan(ones(2,2,2,2),zeros(2,2,2,2));


function out_fem_msh(FemMat, OutputFile)
% OUT_FEM_MSH Write tetrahedral mesh to DGF file (used by GMSH)
%
% INPUT:
%    - TessMat    : Brainstorm FEM head model mesh (tetrahedral)
%    - OutputFile : Full path to output file
%
% DOCUMENTATION:
%    - http://www.ensta-paristech.fr/~kielbasi/docs/gmsh.pdf

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

% Check the format of the mesh
if (size(FemMat.Elements,2) ~= 4)
    error('This function handles only tetrahedral meshes.');
end
% Ensure end of lines are always represented by \r\n
if ispc
    EndLine = '\n';
else
    EndLine = '\r\n';
end
% Open file
[fid, message] = fopen(OutputFile, 'wt');
if (fid < 0)
    error(['Could not create file: ' message]);
end

% Write header
fprintf(fid, ['%s' EndLine], '$MeshFormat');
fprintf(fid, ['%s' EndLine], '2.2 0 8');
fprintf(fid, ['%s' EndLine], '$EndMeshFormat');
% Write nodes
nNodes = size(FemMat.Vertices,1);
fprintf(fid, ['%s' EndLine], '$Nodes');
fprintf(fid, ['%i' EndLine], nNodes);
fprintf(fid, ['%i %i %i %i' EndLine], [1:nNodes; FemMat.Vertices']);
fprintf(fid, ['%s' EndLine], '$EndNodes');
% Write elements
nElem = size(FemMat.Elements,1);
fprintf(fid, EndLine);
fprintf(fid, ['%s' EndLine], '$Elements');
fprintf(fid, ['%i' EndLine], nElem);
fprintf(fid, ['%i %i %i %i %i %i %i %i %i' EndLine],...
    [1:nElem; ...             % elm?number: Element index
     4 * ones(1,nElem); ...   % elm?type: 4 nodes per element (tetrahedral mesh)
     2 * ones(1,nElem); ...   % number?of?tags: Two tags per element (tissue index and unused value)
     FemMat.Tissue' - 1; ...  % Tag #1: Tissue index
     zeros(1,nElem); ...      % Tag #2: Unused
     FemMat.Elements']);      % Tetrahedral elements
fprintf(fid, ['%s' EndLine], '$EndElements');

% Close file
fclose(fid);

% % LATER: If we need to visualize data within gmsh
% % bloc physical Names
% fprintf(fid,'%s' EndLine],'$PhysicalNames');
% fprintf(fid,'%i ' EndLine],length(unique(newelem(:,6))));
% fprintf(fid,'%i %i %s' EndLine],'1 1 toto1');
% fprintf(fid,'%i %i %s' EndLine],'2 2 toto2');
% fprintf(fid,'%i %i %s' EndLine],'3 3 toto3');
% fprintf(fid,'%i %i %s' EndLine],'4 4 toto4');
% fprintf(fid,'%s' EndLine],'$EndPhysicalNames');
%
% % $NodeData
% % http://geuz.org/gmsh/doc/texinfo/gmsh.html#SEC62
% fprintf(fid,'%s' EndLine],'$NodeData');
% fprintf(fid,'%i ' EndLine],1); % one string tag:
% fprintf(fid,'%s' EndLine],'"A scalar view"');
% fprintf(fid,'%i' EndLine],1); %one real tag:
% fprintf(fid,'%i' EndLine],0.0); %the time value (0.0)
% fprintf(fid,'%i' EndLine],3); % three integer tags:
% fprintf(fid,'%i' EndLine],0); %the time step (0; time steps always start at 0)
% fprintf(fid,'%i' EndLine],1); % 1-component (scalar) field
% fprintf(fid,'%i' EndLine],length(newnode)); % nb associated nodal values
% fprintf(fid,'%i %i ' EndLine],[nn,Vn']');
% fprintf(fid,'%s' EndLine],'$End$NodeData');


%% RRT*FN Toolbox Examples
%
%
RRT Examples

%

%
	2D Mobile point-like robot

%
	6 DOF Planar Redundant Manipulator

%
	3 DOF Mobile rectangular robot

%

%

%
RRT* Examples

%

%
	2D Mobile point-like robot

%
	6 DOF Planar Redundant Manipulator

%
	3 DOF Mobile rectangular robot

%

%

%
RRT*FN Examples

%

%
	2D Mobile point-like robot

%
	6 DOF Planar Redundant Manipulator

%
	3 DOF Mobile rectangular robot

%

%