function computePredictionCT_batchHN(pathWORK,fSetName,outcomes,freedomMat,maxOrder,nBoot,imbalance,nBatch,matlabPATH)
% -------------------------------------------------------------------------
% function computePredictionCT_batchHN(pathWORK,fSetName,outcomes,freedomMat,maxOrder,nBoot,imbalance,nBatch,matlabPATH)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function computes prediction performance estimation for the 'CT'
% feature set only and for all outcomes. See ref. [1,2] for more details.
% Goal: comparison with the "Radiomics signature" of (Aerts et al., Nat Commun, 2014)
% -------------------------------------------------------------------------
% REFERENCE:
% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the
%     early prediction of different tumour outcomes in head and neck cancer.
%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy.
%     doi:
% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and
%     MRI texture features for the prediction of lung metastases in soft-tissue
%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14),
%     5471-5496. doi:10.1088/0031-9155/60/14/5471
% -------------------------------------------------------------------------
% INPUTS:
% - pathWORK: Full path to the HN WORKSPACE directory.
% - fSetName: Cell of strings specifying the name of the type of feature
%             set analyzed (e.g., {'PET', 'SEPARATE', 'FUSED'})
% - outcomes: Structure specifying the status (1 or 0) for different
%             outcomes in HN cancer. Contains: outcomes.Failure,
%             outcomes.Locoregional, outcomes.Distant, outcomes.Death. See
%             ref.[1] for more details.
% - freedomMat:  Cell vector of matrices of row vectors of 1's and 0's to
%                specify the degree of freedom on texture extraction
%                parameters for all experiments. For example, for an nth
%                experiment of an ith scan where extraction parameters 1, 2
%                and 4 in paramCell are allowed to vary, use
%                freedomMat{i}(n,:) = [1,1,0,1].
% - maxOrder: Integer specifying the maximal multivariable model order
%             to construct.
% - nBoot: Number of bootstrap samples to use.
% - imbalance: String specifying the type of imbalance-adjustement strategy
%              employed. Either 'IABR' for imbalance-adjusted bootstrap
%              resampling (see ref.[2]), or 'IALR' for imbalance-adjusted
%              logistic regression (see ref.[1]).
% - nBatch: Number of parallel batch.
% - matlabPATH: Full path to the MATLAB excutable on the system.
% -------------------------------------------------------------------------
% OUTPUTS: Prediction performance results are saved in a folder named
%          'RESULTS' in the HN WORKSPACE.
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: July 2015
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015  Martin Vallieres
%
%    This package 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 package is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this package.  If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------

startpath = pwd;
cd(pathWORK), cd('RESULTS')
nameOutcomes = fieldnames(outcomes);
nOutcomes = length(nameOutcomes);
outcomeSep = cell(1,nOutcomes);
for o = 1:nOutcomes
    temp.(nameOutcomes{o}) = outcomes.(nameOutcomes{o});
    outcomeSep{o} = temp;
    temp = [];
end
nType = length(fSetName);
[param] = batchExperiments(nType,outcomes,nBatch); nBatch = length(param);
cd('SCRIPTS'), pathScripts = pwd;
time = 60; % Number of seconds to wait before checking if parallel computations are done

% PRODUCE BATCH COMPUTATIONS
save('workspace'), pause(5);
for i = 1:nBatch
    nameScript = ['Script_PredPerfEst_CT',num2str(i),'.m'];
    fid = fopen(nameScript,'w');
    fprintf(fid,'load(''workspace'')\n');
    for j = 1:size(param{i},1)
        fprintf(fid,['computeAllPrediction_HN(pathWORK,fSetName{param{',num2str(i),'}(',num2str(j),',1)},outcomeSep{param{',num2str(i),'}(',num2str(j),',2)},freedomMat{param{',num2str(i),'}(',num2str(j),',1)},maxOrder,nBoot,imbalance,',num2str(i),')\n']);
    end
    fprintf(fid,'clear all');
    fclose(fid);
    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);
end

% WAITING LOOP
nameVerif = {};
for i = 1:nType
    nExp = size(freedomMat{i},1);
    nParam = size(freedomMat{i},2);
    for j = 1:nExp
        temp = ['RESULTS_',fSetName{i},'_'];
        for k = 1:nParam
            temp = [temp,num2str(freedomMat{i}(j,k))];
        end
        nameVerif = [nameVerif;temp];
    end
end
nVerif = numel(nameVerif);
while 1
    pause(time);
    check = zeros(nVerif,1);
    for o = 1:nOutcomes
        cd([pathWORK,'/RESULTS/',nameOutcomes{o}])
        for i = 1:nVerif
            check(i) = check(i) + exist([nameVerif{i},'.mat']);
        end
    end
    if sum(check) == nVerif*nOutcomes*2
        break
    end
end

cd(pathScripts)
delete('workspace.mat')
cd(startpath)
end


% This file is part of the project NILM-Eval (https://github.com/beckel/nilm-eval).
% Licence: GPL 2.0 (http://www.gnu.org/licenses/gpl-2.0.html)
% Copyright: ETH Zurich, 2014
% Author: Romano Cicchetti

function [threshold] = get_evaluation_threshold(appliance, household)

  thresholdMatrix = [15 15 0 15 15 15;        %fridge
                     15 15 0 15 15 15;        %freezer
                     15 15 0 50 50 15;        %microwave
                     15 15 0 15 15 15;        %dishwasher
                     15 15 0 15 15 15;        %entertainment
                     15 15 0 15 15 15;        %water kettle
                     15 15 0 15 15 15;        %cooker
                     15 15 0 15 15 15;        %coffee machine
                     15 15 0 15 15 15;        %washing machine
                     15 15 0 15 15 15;        %dryer
                     15 15 0 15 15 15;        %lamp
                     15 15 0 15 15 15;        %pc
                     15 15 0 15 15 15;        %laptop
                     15 15 0 15 15 15;        %tv
                     15 15 0 15 15 15;        %stereo
                     15 15 0 15 15 15;        %tablet
                     15 15 0 15 15 15;        %router
                     15 15 0 15 15 15];       %illuminated fountain

    threshold = thresholdMatrix(appliance, household);

end


function [f, g] = hsvargplvmObjectiveGradient(params, model)

% SVARGPLVMOBJECTIVEGRADIENT Wrapper function for shared VARGPLVM objective and gradient.
% FORMAT
% DESC returns the negative log likelihood of a Gaussian process
% model given the model structure and a vector of parameters. This
% allows the use of NETLAB minimisation functions to find the model
% parameters.
% ARG params : the parameters of the model for which the objective
% will be evaluated.
% ARG model : the model structure for which the objective will be
% evaluated.
% RETURN f : the negative log likelihood of the SVARGPLVM model.
% RETURN g : the gradient of the negative log likelihood of the SVARGPLVM
% model with respect to the parameters.
%
% SEEALSO : minimize, svargplvmModelCreate, svargplvmGradient, svargplvmLogLikelihood, svargplvmOptimise
%
% COPYRIGHT :  Andreas C. Damianou, 2011

% SVARGPLVM

% Check how the optimiser has given the parameters
if size(params, 1) > size(params, 2)
  % As a column vector ... transpose everything.
  transpose = true;
  model = hsvargplvmExpandParam(model, params');
else
  transpose = false;
  model = hsvargplvmExpandParam(model, params);
end

f = - hsvargplvmLogLikelihood(model);
% fprintf(1,'# F: %.13f\n',f); %%% DEBUG
if nargout > 1
  g = - hsvargplvmLogLikeGradients(model);
%  fprintf(1,'# G: %.13f .\n',sum(abs(g))); %%% DEBUG
end
if transpose
  g = g';
end


function [img,cropVals] = mrAnatAutoCrop(img, borderPix, thresh)
%
% img = mrAnatAutoCrop(img, [borderPix=1], [thresh=0])
%
% 2008.02.27 RFD: wrote it.

if(~exist('borderPix','var')||isempty(borderPix))
    borderPix = 1;
end
if(~exist('thresh','var')||isempty(thresh))
    thresh = 0;
end

sz = size(img);
m = img>thresh;
if(numel(sz)>2)
    tmp = sum(m,3);
    x = find(sum(tmp,1)); x = [x(1) x(end)];
    y = find(sum(tmp,2)); y = [y(1) y(end)];
    tmp = squeeze(sum(m,1));
    z = find(sum(tmp,1)); z = [z(1) z(end)];
    clear tmp;
    pad = [-borderPix borderPix];
    x = x+pad; y = y+pad; z = z+pad;
    x(1) = max(1,x(1)); y(1) = max(1,y(1)); z(1) = max(1,z(1));
    x(2) = min(sz(2),x(2)); y(2) = min(sz(1),y(2)); z(2) = min(sz(3),z(2));
    img = img(y(1):y(2),x(1):x(2),z(1):z(2));
    cropVals = [x; y; z];
else
    x = find(sum(~isnan(img)&img~=0,1)); x = [x(1) x(end)];
    y = find(sum(~isnan(img)&img~=0,2)); y = [y(1) y(end)];
    pad = [-borderPix borderPix];
    x = x+pad; y = y+pad;
    x(1) = max(1,x(1)); y(1) = max(1,y(1));
    x(2) = min(sz(2),x(2)); y(2) = min(sz(1),y(2));
    img = img(y(1):y(2),x(1):x(2));
    cropVals = [x; y; 1,1];
end
return;


function val = rmGetVoxelData(param, vw, roi, varargin)
% rmGetVoxelData - Get Retinotopy Model data for a selected set of voxels.
%
% val = rmGetVoxelData(param, [view or RM model], [voxels=cur ROI], [options]);
%
%
% INPUTS:
%   param: name of the parameter to get for each voxel. Possible values:
%       'prf', 'rf': constructed 2D population receptive fields for each voxel.
%       If several voxels are specified, returns a 3D matrix in which the
%       slices correspond to the pRF for each voxel.
%
%		'prfvector', 'rfvector': same as 'prf', but each voxel's RF is
%		provided in a single vector format. The resulting matrix is size
%		pixels (in visual space) x voxels.
%
%       'x', 'x0': X position center of the pRF for the voxel.
%
%       'y', 'y0': Y position center of the pRF for the voxel.
%
%		'ecc', eccentricity of pRF center.
%
%		'pol', polar angle of pRF center.
%
%       'sigma', 'sigmamajor': pRF size of the first/only Gaussian.
%
%       'sigmaminor': pRF size of the second Gaussian, if it exists.
%
%       'theta': relative rotation of the major/minor axes.
%
%       'sig', 'log10p': significance level (-log10(p)) for the model for
%        each voxel.
%
%       'beta': scaling coefficient ("beta value") for the Gaussian pRF for
%       each voxel.
%
%		'amp': amplitude of the response. This is the scale factor
%		necessary to take a predicted response for each voxel, and fit it
%		to the time series. (This is the "beta value" for a GLM, constructed
%		from a pRF-derived esign matrix).
%
%
%   model: can either be a retinotopy model struct, or a mrVista view.
%   If the latter, grabs the first model loaded into the view (prompting
%   the user to select and RM file if none are loaded). Can also be
%   a number, indexing into loaded model structs. [Default: cur view
%   model]
%
%   voxels: ROI specification. Can be a numeric index into the view's ROIs
%   field, the ROI struct itself, a 3xN set of coordinates relative to the
%   view, or the ROI name of a loaded ROI. (Uses tc_roiStruct to
%   disambiguate these possibilities.) [Default: cur ROI of cur view]
%
% options include:
%   'rot', [value]: rotate RF params clockwise by [value] degrees. Ths will
%                   happen if the stimulus specification doesn't quite
%                   match the actual presentation regime. (Shouldn't
%                   happen, I know, but it seems to for some data sets, to
%                   a small degree.)
%   'xRange', [value]: range of X values for estimating the pRF. Defaults
%                   to -14:.2:14.
%   'yRange', [value]: same as for xRange, but along the Y axis.
%
%
% ras, 10/2006.
if notDefined('param'),     error('Need to specify param name.');	end
if notDefined('vw'),        vw = getCurView;						end
if notDefined('roi'),       roi = viewGet(vw, 'curROI');            end

% params/defaults
rot = 0;

% parse options
varargin = unNestCell(varargin); % allow recursive passing of options
for i = 1:length(varargin)
    if ischar(varargin{i})
        switch lower(varargin{i})
            case 'rot', rot = varargin{i+1};
            case 'x', X = varargin{i+1};
            case 'y', Y = varargin{i+1};
            case 'rmparams', rmParams = varargin{i+1};
        end
    end
end

% test for a view struct being passed in
if ~isfield(vw, 'x0') && isfield(vw, 'viewType')
    if ~checkfields(vw, 'rm', 'retinotopyModels')
        vw = rmSelect(vw, 1);
    end
    rmParams = vw.rm.retinotopyParams;
    model = vw.rm.retinotopyModels{1};
else
    % this is messy, need to reorganize...
    model = vw;
    vw = getCurView;
end

% disambiguate ROI sepecification
if ~isstruct(roi), roi = tc_roiStruct(vw, roi); end

% get indices of coords which correspond to selected voxels
if ismember(roi.viewType, {'Volume' 'Gray'})
    % get the indices corresponding to the ROI, preserving the voxel order
    % (this may take some time and memory for large ROIs)
    I = roiIndices(vw, roi.coords, 1);

    ok = find( ~isnan(I) );

else
    % not yet implemented for other view types
    error('Sorry, Not Yet Implemented.')
end

% plural/singular flexibility: ignore any 's' at the end of the param name
if lower(param(end))=='s'
    param = param(1:end-1);
end

% get the relevant value for the specified parameter
val = NaN(1, length(I));
switch lower(param)
    case {'amp' 'voxelamplitude' 'voxamp' 'glmbeta'}
        % compute the scale factor which maps from a normalized (-1 - 1
        % range) prediction to the fitted data. This runs a GLM for each
        % voxel in the ROI.
        %
        % I'm going to go ahead and assume vw is a view structure; it's too
        % hard to do this otherwise.
        [tSeries coords] = voxelTSeries(vw, roi.coords, [], 0, 0);

        pred = rmGetVoxelData('predictedtseries', vw, roi, varargin);

        % we called voxelTSeries with the preserveCoords flag set to zero.
        % This means the tSeries will have some voxels discarded (if
        % there's no data), and the coord order shuffled. Make sure the
        % order of predictions matches this order.
        [coords ok map2roi] = intersectCols(roi.coords, coords); %#ok<*ASGLU>
        pred = pred(:,ok);

        % take the prediction and make a design matrix (add trends terms)
        trends = rmMakeTrends(rmParams, prefsVerboseCheck);

        % initialize an empty output value
        val = NaN(1, length(I));

        % run a GLM for each non-NaN voxel, returning the scale factor
        for v = 1:length(ok)
            p = pred(:,v);
            if all(p==0) || all( isnan(p) )
                continue
            end
            p = p ./ abs(max(p));
            X = [p trends];
            [t df RSS B] = rmGLM(tSeries(:,v), X);

            % because of the sorting we introduced in voxelTSeries, the
            % order of tSeries may not match the order of our output amps
            % value. Map this back to the original order of the ROI coords.
            whichVoxel = map2roi(v);
            val(whichVoxel) = B(1);
        end

    case {'pred' 'prediction' 'predictedtserie'}
        % predicted time series of response based on the pRF for each voxel
        % and the stimulus.

        % we need pRF params for each voxel
        X = rmParams.analysis.X;
        Y = rmParams.analysis.Y;
        x0 = zeros(1, length(I));
        y0 = x0;
        sigma = x0;
        beta = x0;
        x0(ok) = model.x0(I(ok));
        y0(ok) = model.y0(I(ok));
        sigma(ok) = model.sigma.major(I(ok));
        beta(ok) = model.beta(1,I(ok),1);

        % rotation compensation if selected
        if rot ~= 0
            R = sqrt(x0.^2 + y0.^2);
            theta = atan2(y0, x0);
            theta = theta - deg2rad(rot);
            theta = mod(theta, 2*pi);
            x0 = R .* cos(theta);
            y0 = R .* sin(theta);
        end

        % initalize an empty output matrix
        nFrames = size(rmParams.analysis.allstimimages, 1);
        val = NaN(nFrames, length(I));

        for v = ok
            pRF = rfGaussian2D(X, Y, sigma(v), sigma(v), 0, x0(v), y0(v));
            val(:,v) = rmParams.analysis.allstimimages * pRF;
        end

    case {'prf' 'rf' 'prfs' 'rfs'}
        % we need to find a sampling grid for the pRF.
        if notDefined('X') || notDefined('Y')
            [X Y] = prfSamplingGrid(rmParams);
        end

        x0 = zeros(1, length(I));
        y0 = x0;
        sigma = x0;
        beta = x0;
        x0(ok) = model.x0(I(ok));
        y0(ok) = model.y0(I(ok));
        sigma(ok) = model.sigma.major(I(ok));
        beta(ok) = model.beta(1,I(ok),1);

        % rotation compensation if selected
        if rot ~= 0
            R = sqrt(x0.^2 + y0.^2);
            theta = atan2(y0, x0);
            theta = theta - deg2rad(rot);
            theta = mod(theta, 2*pi);
            x0 = R .* cos(theta);
            y0 = R .* sin(theta);
        end

        % re-initialize the return value as a matrix of NaNs
        val = NaN(size(X, 1), size(X, 2), length(I));

        for v = ok
            pRF = rfGaussian2D(X, Y, sigma(v), sigma(v), 0, x0(v), y0(v));
            val(:,:,v) = pRF;
        end

    case {'prfvector' 'rfvector' 'prfsvector' 'rfsvector' 'prfvectors' 'rfvectors'}
        % we need to find a sampling grid for the pRF.
        if notDefined('X') || notDefined('Y')
            [X Y] = prfSamplingGrid(rmParams);
        end

        x0 = zeros(1, length(I));
        y0 = x0;
        sigma = x0;
        beta = x0;
        x0(ok) = model.x0(I(ok));
        y0(ok) = model.y0(I(ok));
        sigma(ok) = model.sigma.major(I(ok));
        beta(ok) = model.beta(1,I(ok),1);

        % rotation compensation if selected
        if rot ~= 0
            R = sqrt(x0.^2 + y0.^2);
            theta = atan2(y0, x0);
            theta = theta - deg2rad(rot);
            theta = mod(theta, 2*pi);
            x0 = R .* cos(theta);
            y0 = R .* sin(theta);
        end

        % re-initialize the return value as a matrix of NaNs
        val = NaN(numel(X), length(I));

        for v = ok
            pRF = rfGaussian2D(X(:), Y(:), sigma(v), sigma(v), 0, x0(v), y0(v));
            val(:,v) = pRF;
        end

    case {'x' 'x0'}, val(ok) = model.x0(I(ok));

    case {'y' 'y0'}, val(ok) = model.y0(I(ok));

    case {'sigma' 'sigmamajor'}, val(ok) = model.sigma.major(I(ok));

    case {'sigmaminor'}, val(ok) = model.sigma.minor(I(ok));

    case {'theta'}, val(ok) = model.sigma.theta(I(ok));

    case {'beta'}, val(ok) = model.beta(1,I(ok),1);

    case {'sig' 'log10p' 'logp'}
        allsig = rmGet(model, 'log10p');
        val(ok) = allsig(I(ok));

    otherwise,
        try
            allvals = rmGet(model, param);
            val(ok) = allvals(I(ok));
        catch %#ok<*CTCH>
            fprintf('[%s] Unknown parameter name %s \n', mfilename, param);
        end

end

return


classdef ThrottlePolyModel < AbstractThrottleModel
    %AbstractSteeringModel Summary of this class goes here
    %   Detailed explanation goes here

    properties
        throttleModel(1,1) PolynominalModel = PolynominalModel(0,0,0,0);
    end

    methods
        function throttle = getThrottleAtTime(obj, ut, ~, ~, ~, ~, ~, ~, ~, ~, ~, ~)
            throttle = obj.throttleModel.getValueAtTime(ut);

            if(throttle < 0)
                throttle = 0.0;
            elseif(throttle > 1)
                throttle = 1.0;
            end
        end

        function enum = getThrottleModelTypeEnum(~)
            enum = ThrottleModelEnum.PolyModel;
        end

        function initThrottleModel(obj, initialStateLogEntry)
            t0 = initialStateLogEntry.time;
            obj.setT0(t0)

            if(obj.throttleContinuity)
                throttle = initialStateLogEntry.throttle;
                obj.throttleModel.constTerm = throttle;
            end
        end

        function setInitialThrottleFromState(obj, stateLogEntry, tOffsetDelta)
            t0 = stateLogEntry.time;
            obj.setT0(t0);

            obj.throttleModel.tOffset = obj.throttleModel.tOffset + tOffsetDelta;
        end

        function t0 = getT0(obj)
            t0 = obj.throttleModel.t0;
        end

        function setT0(obj, newT0)
            obj.throttleModel.t0 = newT0;
        end

        function setPolyTerms(obj, const, linear, accel)
            obj.throttleModel.constTerm = const;
            obj.throttleModel.linearTerm = linear;
            obj.throttleModel.accelTerm = accel;
        end

        function setTimeOffsets(obj, timeOffset)
            obj.throttleModel.tOffset = timeOffset;
        end

        function optVar = getNewOptVar(obj)
            optVar = SetPolyThrottleModelActionOptimVar(obj);
        end

        function optVar = getExistingOptVar(obj)
            optVar = obj.optVar;
        end

        function [addActionTf, throttleModel] = openEditThrottleModelUI(obj, lv, useContinuity)
            output = AppDesignerGUIOutput({false});
            lvd_EditActionSetThrottleModelGUI_App(obj, lv, useContinuity, output);
            addActionTf = output.output{1};
            throttleModel = output.output{2};
        end
    end

    methods(Access=private)
        function obj = ThrottlePolyModel(throttleModel)
            obj.throttleModel = throttleModel;
        end
    end

    methods(Static)
        function model = getDefaultThrottleModel()
            throttlePoly = PolynominalModel(0,0,0,0);
            model = ThrottlePolyModel(throttlePoly);
        end
    end
end


function O = cluster_cutaways(clusters,textprefix,mycolor,whichcuts,varargin)

% groups clusters to image on brains by the first letter in whichcuts
%
% :Usage:
% ::
%
%    O = cluster_cutaways(clusters,textprefix,mycolor,whichcuts,[coords for center of cuts],[revx])
%
% ..
% groups clusters to image on brains by the first letter in whichcuts
% therefore, if you enter 'y' for whichcuts, the program will select
% clusters with similar y values (w/i 15 mm) and image them on the same
% brain. you need files called brain_render_T1.img/hdr on the path
% these should be scalped anatomicals for the brain image.
%
% you would also need 'brain_render_T1.mat' for the
% transparent brain surface, if you changed this script to get
% the transparent brain surface.
%
% if it cuts from the wrong side, try 'revx' as input into tor_3d.m
% or enter anything as 2nd var arg.
%
%
%
% :Inputs:
%
%   **clusters:**
%        cluster object to display on brain cuts
%
%   **textprefix:**
%        prefix for saving images to files
%
%     **mycolor:**
%         cluster colors - 3 el. vector, single letter, or string of letters
%        enter letter or letter string in single quotes. e.g., O.clcol = 'yrgb';
%
%     **whichcuts:**
%         letter string (no quotes) - which axes to cut along - xyz are choices
%
% :Optional Inputs:
%
%     **bestc**
%     best cut, 3-element vector of coordinates, default [0 0 0]
%
%     **revx**
%     text string to reverse x cut direction, enter 1 to do it.
%
%
% :Outputs:
%
%   **O:**
%        output returned from renderCluster_ui.m
%
%
% :Examples:
% ::
%
%    O = cluster_cutaways(clusters,'myoutname','y','yzx',[0 0 0],[revx])
%
% Uses renderCluster_ui.m
%
% ..
%    by Tor Wager, Jan 2003
% ..

mm = cat(1,clusters.mm_center);
d = tril(dist(mm(:,2)') < 15);  %distances
bestc = [0 0 0];
revx = 0;

done = zeros(1,length(clusters));

if length(varargin) > 0, bestc = varargin{1}; else bestc = [0 0 0]; end
if length(varargin) > 1, revx = varargin{2}; else revx = 0; end

clind = 1;
while any(~done)

    whclust = (d(:,clind));
    whclust(find(done)) = 0;
    whclust = find(whclust);
    done(whclust) = 1;

        if ~isempty(whclust)
            figure('Color','w');
            O = struct('dohead','y','dobrain','n','get_from','workspace', ...
                'clusters',clusters, ...
            'which_cl',whclust,'whichc',whichcuts,'bestCoords',bestc,'clcol',mycolor,'addtext','n', ...
            'head','brain_render_T1','revx',revx);

            O = renderCluster_ui(O); set(O.headp(1:2:end),'FaceColor',[.5 .5 .5]);material dull
            h = findobj('Type','Light');delete(h)

            if whichcuts(1) == 'y', view(171,6),[az,el] = view; hh = lightangle(az,el); %hh = lightangle(az,el);
            elseif whichcuts(1) == 'z', view(0,70);[az,el] = view; hh = lightangle(az,el);
            elseif whichcuts(1) == 'x', view(90,10);[az,el] = view; hh = lightangle(az,el);
            end

            %h = findobj('Type','Light');delete(h),h(1) = camlight(90,0); h(2) = camlight(270,0); h(3) = camlight(270,0);

            if clusters(clind).numVox < 20 & clusters(clind).numVox > 1,
                %hold on, plot3(clusters(1).XYZmm(1,:),clusters(1).XYZmm(2,:),clusters(1).XYZmm(3,:),'o','Color',mycolor,'MarkerFaceColor',mycolor,'MarkerSize',10)
            end

            saveas(gcf,[textprefix '_' whichcuts '_group' num2str(clind)],'tif');
            saveas(gcf,[textprefix '_' whichcuts '_group' num2str(clind)],'fig');
            close
        end

        clind = clind+1;
 end

 return


function [ patches, pdm, clmParams ] = Load_CLNF_general()
%LOAD_CLNF_GENERAL Summary of this function goes here
%   Detailed explanation goes here
    clmParams = struct;

    clmParams.window_size = [25,25; 23,23; 21,21];
    clmParams.numPatchIters = size(clmParams.window_size,1);

    [patches] = Load_Patch_Experts( '../models/general/', 'ccnf_patches_*_general.mat', [], [], clmParams);

    % the default PDM to use
    pdmLoc = ['../models/pdm/pdm_68_aligned_wild.mat'];
    load(pdmLoc);

    pdm = struct;
    pdm.M = double(M);
    pdm.E = double(E);
    pdm.V = double(V);

    % the default model parameters to use
    clmParams.regFactor = [35, 27, 20];
    clmParams.sigmaMeanShift = [1.25, 1.375, 1.5];
    clmParams.tikhonov_factor = [2.5, 5, 7.5];

    clmParams.startScale = 1;
    clmParams.num_RLMS_iter = 10;
    clmParams.fTol = 0.01;
    clmParams.useMultiScale = true;
    clmParams.use_multi_modal = 1;
    clmParams.multi_modal_types  = patches(1).multi_modal_types;

end


function [posr, trir, texr] = refine(pos, tri, method, varargin)

% REFINE a 3D surface that is described by a triangulation
%
% Use as
%   [pos, tri]          = refine(pos, tri)
%   [pos, tri]          = refine(pos, tri, 'banks')
%   [pos, tri, texture] = refine(pos, tri, 'banks', texture)
%   [pos, tri]          = refine(pos, tri, 'updown', numtri)
%
% If no method is specified, the default is to refine the mesh globally by bisecting
% each edge according to the algorithm described in Banks, 1983.
%
% The Banks method allows the specification of a subset of triangles to be refined
% according to Banks' algorithm. Adjacent triangles will be gracefully dealt with.
%
% The alternative 'updown' method refines the mesh a couple of times
% using Banks' algorithm, followed by a downsampling using the REDUCEPATCH
% function.
%
% If the textures of the vertices are specified, the textures for the new
% vertices are computed
%
% The Banks method is a memory efficient implementation which remembers the
% previously inserted vertices. The refinement algorithm executes in linear
% time with the number of triangles. It is mentioned in
% http://www.cs.rpi.edu/~flaherje/pdf/fea8.pdf, which also contains the original
% reference.

% Copyright (C) 2002-2014, 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/>.
%

if nargin<3
  method = 'banks';
end

texture = [];
numtri  = [];

if nargin>3
  switch lower(method)
    case 'banks'
      texture = varargin{1};
    case 'updown'
      numtri = varargin{1};
  end % switch
end

switch lower(method)
  case 'banks'
    if ~isempty(texture)
      npnt   = size(pos,1);
      ntri   = size(tri,1);
      ntex   = size(texture,1);

      assert(ntex==npnt, 'invalid size of texture');

      insert = spalloc(3*npnt,3*npnt,3*ntri);
      trir  = zeros(4*ntri,3);      % allocate memory for the new triangles
      posr  = zeros(npnt+3*ntri,3); % allocate memory for the maximum number of new vertices
      texr  = zeros(ntex+3*ntri,2);
      posr(1:npnt,:) = pos;         % insert the original vertices
      texr(1:ntex,:) = texture;
      current = npnt;

      for i=1:ntri

        if ~insert(tri(i,1),tri(i,2))
          current = current + 1;
          posr(current,:) = (pos(tri(i,1),:) + pos(tri(i,2),:))/2;
          texr(current,:) = (texture(tri(i,1),:) + texture(tri(i,2),:))/2;
          insert(tri(i,1),tri(i,2)) = current;
          insert(tri(i,2),tri(i,1)) = current;
          v12 = current;
        else
          v12 = insert(tri(i,1),tri(i,2));
        end

        if ~insert(tri(i,2),tri(i,3))
          current = current + 1;
          posr(current,:) = (pos(tri(i,2),:) + pos(tri(i,3),:))/2;
          texr(current,:) = (texture(tri(i,2),:) + texture(tri(i,3),:))/2;
          insert(tri(i,2),tri(i,3)) = current;
          insert(tri(i,3),tri(i,2)) = current;
          v23 = current;
        else
          v23 = insert(tri(i,2),tri(i,3));
        end

        if ~insert(tri(i,3),tri(i,1))
          current = current + 1;
          posr(current,:) = (pos(tri(i,3),:) + pos(tri(i,1),:))/2;
          texr(current,:) = (texture(tri(i,3),:) + texture(tri(i,1),:))/2;
          insert(tri(i,3),tri(i,1)) = current;
          insert(tri(i,1),tri(i,3)) = current;
          v31 = current;
        else
          v31 = insert(tri(i,3),tri(i,1));
        end

        % add the 4 new triangles with the correct indices
        trir(4*(i-1)+1, :) = [tri(i,1) v12 v31];
        trir(4*(i-1)+2, :) = [tri(i,2) v23 v12];
        trir(4*(i-1)+3, :) = [tri(i,3) v31 v23];
        trir(4*(i-1)+4, :) = [v12 v23 v31];

      end
      posr = posr(1:current, :);
      texr = texr(1:current, :);

    else
      % there is no texture

      npnt   = size(pos,1);
      ntri   = size(tri,1);
      insert = spalloc(3*npnt,3*npnt,3*ntri);

      trir  = zeros(4*ntri,3);      % allocate memory for the new triangles
      posr  = zeros(npnt+3*ntri,3); % allocate memory for the maximum number of new vertices
      posr(1:npnt,:) = pos;         % insert the original vertices
      current = npnt;

      for i=1:ntri

        if ~insert(tri(i,1),tri(i,2))
          current = current + 1;
          posr(current,:) = (pos(tri(i,1),:) + pos(tri(i,2),:))/2;
          insert(tri(i,1),tri(i,2)) = current;
          insert(tri(i,2),tri(i,1)) = current;
          v12 = current;
        else
          v12 = insert(tri(i,1),tri(i,2));
        end

        if ~insert(tri(i,2),tri(i,3))
          current = current + 1;
          posr(current,:) = (pos(tri(i,2),:) + pos(tri(i,3),:))/2;
          insert(tri(i,2),tri(i,3)) = current;
          insert(tri(i,3),tri(i,2)) = current;
          v23 = current;
        else
          v23 = insert(tri(i,2),tri(i,3));
        end

        if ~insert(tri(i,3),tri(i,1))
          current = current + 1;
          posr(current,:) = (pos(tri(i,3),:) + pos(tri(i,1),:))/2;
          insert(tri(i,3),tri(i,1)) = current;
          insert(tri(i,1),tri(i,3)) = current;
          v31 = current;
        else
          v31 = insert(tri(i,3),tri(i,1));
        end

        % add the 4 new triangles with the correct indices
        trir(4*(i-1)+1, :) = [tri(i,1) v12 v31];
        trir(4*(i-1)+2, :) = [tri(i,2) v23 v12];
        trir(4*(i-1)+3, :) = [tri(i,3) v31 v23];
        trir(4*(i-1)+4, :) = [v12 v23 v31];
      end
      % remove the space for the vertices that was not used
      posr = posr(1:current, :);
    end

  case 'updown'
    ntri = size(tri,1);
    while ntri<numtri
      % increase the number of triangles by a factor of 4
      [pos, tri] = refine(pos, tri, 'banks');
      ntri = size(tri,1);
    end
    % reduce number of triangles using MATLAB function
    [trir, posr] = reducepatch(tri, pos, numtri);

  otherwise
    ft_error('unsupported method "%s"', method);
end


%%%%%%%%%%%%%%%%%%%%%%%
% Compute features for a set of video files from datasets
%
close all;
clear;
warning('off','all');
addpath(genpath('./lib/vqm/TLVQM_naive_release'));

%%
% parameters
algo_name = 'TLVQM_naive';
data_name = 'KONVID_1K';

%% *You need to customize here*
if strcmp(data_name, 'TEST_VIDEOS')
    data_path = 'videos'; % dataset video path
elseif strcmp(data_name, 'KONVID_1K')
    data_path = '/media/ztu/Seagate-ztu-ugc/KONVID_1K/KoNViD_1k_videos';
elseif strcmp(data_name, 'LIVE_VQC')
    data_path = '/media/ztu/Seagate-ztu-ugc/LIVE_VQC/VideoDatabase';
elseif strcmp(data_name, 'YOUTUBE_UGC')
    data_path = '/media/ztu/Seagate-ztu-ugc/YT_UGC/original_videos';
elseif strcmp(data_name, 'LIVE_VQA')
    data_path = '/media/ztu/Seagate-ztu/LIVE_VQA/videos';
end

video_tmp = './video_tmp';
if ~exist(video_tmp, 'dir'), mkdir(video_tmp); end
feat_path = './mos_feat_files';
filelist_csv = fullfile(feat_path, [data_name,'_metadata.csv']);
filelist = readtable(filelist_csv);
num_videos = size(filelist,1);
if ~exist(feat_path, 'dir'), mkdir(feat_path); end
out_feat_name = fullfile(feat_path, [data_name,'_',algo_name,'_feats.mat']);
feats_mat = zeros( num_videos, 75 );
%===================================================

tic
for i = 1:num_videos
% get video full path and decoded video name
	if strcmp(data_name, 'TEST_VIDEOS')
	    video_name = fullfile(data_path,  filelist.video_name{i});
	    yuv_name = fullfile(video_tmp, [filelist.video_name{i}, '.yuv']);
	elseif strcmp(data_name, 'KONVID_1K')
	    video_name = fullfile(data_path,  [num2str(filelist.flickr_id(i)),'.mp4']);
	    yuv_name = fullfile(video_tmp, [num2str(filelist.flickr_id(i)), '.yuv']);
	elseif strcmp(data_name, 'LIVE_VQC')
	    video_name = fullfile(data_path, filelist.File{i});
	    yuv_name = fullfile(video_tmp, [filelist.File{i}, '.yuv']);
	elseif strcmp(data_name, 'YOUTUBE_UGC')
	    video_name = fullfile(data_path, filelist.category{i},...
		[num2str(filelist.resolution(i)),'P'],[filelist.vid{i},'.mkv']);
	    yuv_name = fullfile(video_tmp, [filelist.vid{i}, '.yuv']);
	elseif strcmp(data_name, 'LIVE_VQA')
	    strs = strsplit(filelist.filename{i}, '_');
	    video_name = fullfile(data_path, [strs{1}(1:2), '_Folder'], filelist.filename{i});
	    yuv_name = video_name;
	end
	fprintf('\n---\nComputing features for %d-th sequence: %s\n', i, video_name);
    % decode video and store in video_tmp dir
    if ~strcmp(video_name, yuv_name)
    cmd = ['ffmpeg -loglevel error -y -i ', video_name, ' -pix_fmt yuv420p -vsync 0 ', yuv_name];
    system(cmd);
    end

    % get video meta data
    width = filelist.width(i);
    height = filelist.height(i);
    framerate = round(filelist.framerate(i));
    nb_frames = filelist.nb_frames(i);

    % calculate video features
    tic
    feats_mat(i,:) = compute_nrvqa_features(yuv_name, [width, height], framerate);
    toc
    delete(yuv_name)
end
toc
save(out_feat_name, 'feats_mat');


% This subroutine assigns creates a grid with
% spacing dx,dy (in degreees). The size will
% be selected interactiVELY. The Dvalue in each
% volume around a grid point containing ni earthquakes
% will be calculated. This code is called from dcparain.m.
%
%   Stefan Wiemer 1/95

global no1 bo1 inb1 inb2 eq0p

% the new data vector to be analysed is called Da, relative to the conter of the x-section and already in km
% D = [x,y,z ]
Da = [eq0p(1,:)' eq0p(2,:)' a.Date a.Date.Month a.Date.Day a.Magnitude a.Depth];
Da0 = find(Da(:,7) > 0);
Da = Da.subset(Da0);
clear Da0;

if sel == 'in'
    % get the grid parameter
    % initial values
    %
    dd = 1.00;
    dx = 1.00 ;
    ni = 600;
    Nmin = 600; %on line 303 it has been replaced by ni
    stan2 = nan;
    stan = nan;
    prf = nan;
    av = nan;

    % make the interface
    %
    figure_w_normalized_uicontrolunits(...
        'Name','Grid Parameters',...
        'NumberTitle','off', ...
        'MenuBar','none', ...
        'units','points',...
        'Visible','on', ...
        'Position',[ 100 200 500 200]);
    axis off
    % Francesco ...

    % creates a dialog box to input grid parameters
    %
    freq_field=uicontrol('Style','edit',...
        'Position',[.32 .57 .12 .08],...
        'Units','normalized','String',num2str(ni),...
        'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');

    freq_field0=uicontrol('Style','edit',...
        'Position',[.80 .57 .12 .08],...
        'Units','normalized','String',num2str(ra),...
        'Callback','ra=str2double(get(freq_field0,''String'')); set(freq_field0,''String'',num2str(ra)) ; set(tgl2,''value'',1); set(tgl1,''value'',0)');

    freq_field2=uicontrol('Style','edit',...
        'Position',[.32 .44 .12 .08],...
        'Units','normalized','String',num2str(dx),...
        'Callback','dx=str2double(get(freq_field2,''String'')); set(freq_field2,''String'',num2str(dx));');

    freq_field3=uicontrol('Style','edit',...
        'Position',[.32 .31 .12 .08],...
        'Units','normalized','String',num2str(dd),...
        'Callback','dd=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dd));');

    tgl1 = uicontrol('Backgroundcolor', [0.8 0.8 0.8], 'Fontweight','bold',...
        'FontSize', 10, 'Style','checkbox',...
        'string','Number of Events:',...
        'Position',[.05 .56 .2 .10],...
         'Callback','set(tgl2,''value'',0, ''ForegroundColor'', ''w''); set(tgl1, ''ForegroundColor'', ''k'')',...
        'Units','normalized');

    set(tgl1,'value',1);

    tgl2 =  uicontrol('BackGroundColor', [0.8 0.8 0.8],'Style','checkbox',...
        'string','Constant Radius:','Fontweight','bold','FontSize', 10,...
        'Position',[.55 .56 .2 .1],...
         'Callback','set(tgl1,''value'',0,''ForegroundColor'', ''w''); set(tgl2, ''ForegroundColor'', ''k'')',...
        'Units','normalized');

    set(tgl2, 'ForegroundColor', 'w');

    close_button=uicontrol('Style','Pushbutton',...
        'Position',[.45 .05 .15 .13 ],...
        'Units','normalized','Callback','close;done','String','Cancel');

    help_button=uicontrol('Style','Pushbutton',...
        'Position',[.70 .05 .15 .13 ],...
        'Units','normalized','Callback','close;done','String','Help');

    go_button1=uicontrol('Style','Pushbutton',...
        'Position',[.20 .05 .15 .13 ],...
        'Units','normalized',...
        'Callback','tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');close; sel = ''ca''; rdwstest; ',...
        'String','Go');

    txt3 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.35 0.9 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.l ,...
        'FontWeight','bold',...
        'String',' Grid Parameters');
    txt5 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.07 0.46 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Horizontal Spacing [km]:');

    txt6 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.07 0.30 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Depth spacing [km]:');

    txt7 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.45 0.62 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'Color', 'r',...
        'String','OR');

    set(gcf,'visible','on');
    watchoff

end   % if sel == in

% get the grid-size interactively and
% calculate the b-value in the grid by sorting
% the seimicity and selectiong the ni neighbors
% to each grid point

if sel == 'ca'

    figure_w_normalized_uicontrolunits(xsec_fig)
    hold on

    messtext=...
        ['To select a polygon for a grid.       '
        'Please use the LEFT mouse button of   '
        'or the cursor to the select the poly- '
        'gon. Use the RIGTH mouse button for   '
        'the final point.                      '
        'Mac Users: Use the keyboard "p" more  '
        'point to select, "l" last point.      '
        '                                      '];

    zmap_message_center.set_message('Select Polygon for a grid',messtext);

    figure;
    ax=plot(Da(:,1),-Da(:,7),'o');
    xlabel('Distance in [km]')
    ylabel('Depth in [km]')

    hold on
    %ax = findobj('Tag','main_map_ax');
    [x,y, mouse_points_overlay] = select_polygon(ax);
    zmap_message_center.set_info('Message',' Thank you .... ')

    plos2 = plot(x,y,'b-','era','xor', 'Color', 'r');        % plot outline
    sum3 = 0.;
    pause(0.3)

    %create a rectangular grid
    xvect=[min(x):dx:max(x)];
    yvect=[min(y):dd:max(y)];
    gx = xvect;gy = yvect;
    tmpgri=zeros((length(xvect)*length(yvect)),2);
    n=0;

    for i=1:length(xvect)
        for j=1:length(yvect)
            n=n+1;
            tmpgri(n,:)=[xvect(i) yvect(j)];
        end
    end

    %extract all gridpoints in chosen polygon
    XI=tmpgri(:,1);
    YI=tmpgri(:,2);

    ll = polygon_filter(x,y, XI, YI, 'inside');
    %grid points in polygon
    newgri=tmpgri(ll,:);

    % Plot all grid points
    plot(newgri(:,1),newgri(:,2),'+k','era','back')

    if length(xvect) < 2  ||  length(yvect) < 2
        errordlg('Selection too small! (not a matrix)');
        return
    end

    itotal = length(newgri(:,1));
    if length(gx) < 4  ||  length(gy) < 4
        errordlg('Selection too small! ');
        return
    end

    zmap_message_center.set_info(' ','Running... ');think
    %  make grid, calculate start- endtime etc.  ...
    %
    t0b = min(newa.Date)  ;
    n = newa.Count;
    teb = newa(n,3) ;
    tdiff = round((teb - t0b)*365/par1);
    loc = zeros(3, length(gx)*length(gy));

    % loop over  all points
    %
    i2 = 0.;
    i1 = 0.;
    wai = waitbar(0,' Please Wait ...  ');
    set(wai,'NumberTitle','off','Name','D-value grid - percent done', 'position', [250 80 270 50]);
    drawnow;
    %
    %
    %
    sdrd = [];
    k = 1;
    for ni = 50:50:1000

        rdtest = [];

        for i= 1:length(newgri(:,1))
            x = newgri(i,1);y = newgri(i,2);
            %allcount = allcount + 1.;
            i2 = i2+1;

            % calculate distance from center point and sort wrt distance
            % Francesco: please check if the distance  l is right

            l = sqrt(((Da(:,1) - x)).^2 + ((Da(:,7) + y)).^2 + (Da(:,2).^2)) ;
            [s,is] = sort(l);
            b = Da(is(:,1),:) ;       % re-orders matrix to agree row-wise

            if tgl1 == 0   % take point within r
                l3 = l <= ra;
                b = Da.subset(l3);      % new data per grid point (b) is sorted in distanc
                rd = ra;
            else
                % take first ni points
                b = b(1:ni,:);      % new data per grid point (b) is sorted in distance
                l2 = sort(l);
                rd = l2(ni);

            end

            %estimate the completeness and b-value, and take the zero depth events away.
            %newt2 = [b(:,1) b(:,2) zeros(size(b,1),1) zeros(size(b,1),1) zeros(size(b,1),1) zeros(size(b,1),1) b(:,3)];
            %
            newt2  = b;
            E = newt2;

            if length(b) >= ni  % enough events?

                rdtest = [rdtest; rd];

            end %if length >= ni

        end  % for  newgri

        mrd = sum(rdtest,2)/size(rdtest,2);
        vrd = var(rdtest);
        %varrd1 = (rdtest-mrd).^2;
        %varrd = sum(varrd1, 1)*1/size(rdtest,1);
        stdevrd = vrd.^(1/2);
        sdrd = [sdrd; stdevrd];

        waitbar((1/20)*k);
        k = k+1;
    end %for ni

    clear mrd vrd
    close(wai)

    sdrd
    radius1 = find(min(sdrd));
    radius = (radius1*50) + 50

    clear radius1

end %if sel = ca


% SquareRoot is the dagnn wrapper which performs square root normalization
% for the input features at each location

% Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji.
% All rights reserved.
%
% This file is part of the BCNN. It uses MATCONVNET package and is made
% available under the terms of the BSD license (see the COPYING file).

classdef SquareRoot < dagnn.ElementWise
  properties
    param = 1e-8;
  end

  methods
    function outputs = forward(obj, inputs, params)
      outputs{1} = vl_nnsqrt(inputs{1}, obj.param) ;
    end

    function [derInputs, derParams] = backward(obj, inputs, param, derOutputs)
      derInputs{1} = vl_nnsqrt(inputs{1}, obj.param, derOutputs{1}) ;
      derParams = {} ;
    end

    function rfs = getReceptiveFields(obj)
      rfs.size = [1 1] ;
      rfs.stride = [1 1] ;
      rfs.offset = [1 1] ;
    end

    function obj = SquareRoot(varargin)
      obj.load(varargin) ;
    end
  end
end


% The COBRAToolbox: testGapFind.m
%
% Purpose:
%     - testGapFind tests the validity of gapFind.
%
% Authors:
%     - Original file: Thomas Pfau Sept 2017
%

% save the current path
currentDir = pwd;

% initialize the test
fileDir = fileparts(which('testGapFind'));
cd(fileDir);

testModel = createToyModelForgapFind();
%test solver packages
solverPkgs = {'tomlab_cplex', 'ibm_cplex', 'gurobi', 'glpk'};

for k = 1:length(solverPkgs)

    solverOK  = changeCobraSolver(solverPkgs{k}, 'MILP', 0);

    if solverOK
        fprintf( 'Testing gapFind with solver %s ...\n',solverPkgs{k});
        %The Basic function should find exactly one Metabolite (H) as gapped
        %The Cycle goes undetected as it can carry flux and I is blocked but not
        %gapped.
        [allGaps, rootGaps, downstreamGaps] = gapFind(testModel);

        assert(isempty(downstreamGaps))
        assert(isequal(allGaps,{'H'}));
        assert(isequal(rootGaps,{'H'}));

        %Now, we change this to also find No Consumption gaps, It now detects I
        %alng H and does still not detect anything downstream.
        [allGaps, rootGaps, downstreamGaps] = gapFind(testModel,true);
        assert(isempty(downstreamGaps))
        assert(isequal(allGaps,{'H';'I'}));
        assert(isequal(rootGaps,{'H';'I'}));

        %Finally, we eliminate the cycle. This should yield E as additional Gap
        %(starting point of the disconnected part) and F and G as downstream Gaps.
        testModelWOCycle = removeRxns(testModel,'R6');
        [allGaps, rootGaps, downstreamGaps] = gapFind(testModelWOCycle);
        dsGaps = {'F';'G'};
        rGaps = {'E';'H'};
        aGaps = union(dsGaps,rGaps);
        assert(isequal(downstreamGaps,dsGaps))
        assert(isequal(allGaps,aGaps));
        assert(isequal(rootGaps,rGaps));

        %Only test for one solver (testing multiple solvers is a waste of
        %time)

        break
    end

end
if exist('MILPProblem.mat','file')
    delete('MILPProblem.mat')
end
if exist('MILPProblem.mat','file')
    delete('MILPProblem.mat')
end


%kvnconddil 'N times (with respect to the composition) the conditional dilation'
% This MatLab function was automatically generated by a converter (KhorosToMatLab) from the Khoros vnconddil.pane file
%
% Parameters:
% InputFile: i1 'Input Image #1', required: 'first input image'
% InputFile: i2 'Input Image #2', required: 'second input image'
% InputFile: str 'Struct Element', required: 'Structuring Element'
% Integer: n 'Number of Dilations', default: 5: 'number of cond. dilations'
% OutputFile: o 'Output Image ', required: 'resulting output image'
%
% Example: o = kvnconddil({i1, i2, str}, {'i1','';'i2','';'str','';'n',5;'o',''})
%
% Khoros helpfile follows below:
%
%  PROGRAM
% vnconddil - N times (with respect to the composition) the conditional dilation
%
%  DESCRIPTION
% .I vnconddil
% will do N sucessive cond. dilations of the first input image by a set structuring element, using the second input image as a conditional image.
%
% The two input images must be of the same size and have the same
% number of data bands.  The input
% images may be of the same or different data types.  If the input
% images are of different data types, then all input images will be
% upcast to the highest input image data type.  The output
% image data type will be the same as that of the highest data type
% of the input images.
%
%
%
%  EXAMPLES
% vnconddil -i1 ball.xv -i2 feath.xv -str b272.str -n 5 -o outimage.xv
%
% Will do 5 sucessive cond. dilations of image 1 "ball.xv" by the structuring set b272.str using "feath.xv" as a conditional image, with the resulting image written to "outimage.xv".
%
%  "SEE ALSO"
%
%  RESTRICTIONS
% .I vnconddil
% can be defined for all data types supported by Khoros, but at the moment it has been implemented just for the bit and unsigned char types.
% The structuring elements are subsets of the 3x3 matrix and the origin is always at the center of this matrix.
%
%  REFERENCES
%
%  COPYRIGHT
% Copyright (C) 1993-1997 Junior Barrera, Roberto Lotufo.  All rights reserved.
%

function varargout = kvnconddil(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,..] = kvnconddil(Inputs,arglist).');
end
if size(arglist,2)~=2
  error('arglist must be of form {''ParameterTag1'',value1;''ParameterTag2'',value2}')
 end
narglist={'i1', '__input';'i2', '__input';'str', '__input';'n', 5;'o', '__output'};
maxval={0,0,0,2,0};
minval={0,0,0,2,0};
istoggle=[0,0,0,0,0];
was_set=istoggle * 0;
paramtype={'InputFile','InputFile','InputFile','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 'vnconddil"  '],Inputs,narglist);


function [c1,c2]=lox(p1,p2,bounds,genInfo,ops)
% Linearorder crossover takes two parents P1,P2 and performs linear order
% crossover for permutation strings.
%
% function [c1,c2] = linearOrderXover(p1,p2,bounds,Ops)
% p1      - the first parent ( [solution string function value] )
% p2      - the second parent ( [solution string function value] )
% bounds  - the bounds matrix for the solution space
% Ops     - Options matrix for simple crossover [gen #SimpXovers].

% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 C.R. Houck, J.A. Joines, M.G. Kay
%
% C.R. Houck, J.Joines, and M.Kay. A genetic algorithm for function
% optimization: A Matlab implementation. ACM Transactions on Mathmatical
% Software, Submitted 1996.
%
% 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 1, 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. A copy of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
sz=size(p1,2)-1;
c1=p1(1:sz);%zeros(1,sz);
c2=p2(1:sz);%zeros(1,sz);
cut1=round(rand*(sz-1)+1.5);
cut2=round(rand*(sz-1)+1.5);
while cut2 == cut1
   cut2 = round(rand*sz + 0.5);
end
if cut1 > cut2
   t = cut1; cut1 = cut2; cut2 = t;
end
for i=cut1:cut2
  c1=strrep(c1,p2(i),-1);
  c2=strrep(c2,p1(i),-1);
end
g1=find(c1>-1);
g2=find(c2>-1);
c1=[c1(g1(1:(cut1-1))) p2(cut1:cut2) c1(g1(cut1:end)) p1(end)];
c2=[c2(g2(1:(cut1-1))) p1(cut1:cut2) c2(g2(cut1:end)) p2(end)];


%% generate eye inf.
% author: Shuang Wang
% email: shw070@ucsd.edu
% Division of Biomedical Informatics, University of California, San Diego.
function a = eyeInf(len)
    a = zeros(len);
    a(1:length(a)+1:numel(a)) = Inf;
end


function grafica2000frame
%%%%%%%%%%%%%%%%%%           SAP2000 v14           %%%%%%%%%%%%%%%%%%%%%
%programa registrado por MECAVIL ingenieria-ciencia
%bresler_lin@hotmail.com
%numera los frames
%clf
graficaTRIDIMENSIONAL

[frini frfin elmprp ielmprp conecc inud nud]=frame3dsap2000longitud;
%%%%%%%%%%%%%%%%%%%%%%
%enumeracion frames%%%
%%%%%%%%%%%%%%%%%%%%%%
M=(frfin(:,[2 3 4])+frini(:,[2 3 4]))./2;
axis('equal')
figure(1),hold on
for i=1:1:ielmprp
 text(M(i,1),M(i,2),M(i,3),[{'\color{blue}'} [,int2str( conecc(i,1) ),]],'FontSize',7)
end
hold off


function pos = ApproxMedianFilter_RB_LED(file)

% This code tests an approximate median filter for separating out the red
% and blue leds mounted on top of the subjects head
% I was using the DataMax system, which was synced using a red LED. Hence,
% I am tracking the x,y position of the animal as well as when the sync
% light comes on.

%file       = 'Mouse12-120808-01.mpg';
%[~,name,~] = fileparts(file);
% Create Text file for writing out LED locations and sync trigger
%fid        = fopen(sprintf('%s.pos',name),'w+');
% Creater readerobj of file
readerobj  = VideoReader(file);
width      = readerobj.Width;
height     = readerobj.Height;
threshF    = 110;    % threshold on foreground pixel intensity
% Initial frame
Fint       = 1;

% Initialize grid for locating centroid of LED
[X,Y] = meshgrid(1:width,1:height);

% Initialize background as a grayscale image of the first frame
bg_bw     = rgb2gray(read(readerobj,Fint));
pos
% Initialize foreground image and difference image
fg          = zeros(size(bg_bw));
fr_diff     = zeros(size(bg_bw));

% Initialize color mask
mask  = zeros(height,width,3,'uint8');

% Initialize fr in case first frame reading returns error
fr  = zeros(height,width,3,'uint8');

% Initialize pos matrix
pos = zeros(readerobj.NumberOfFrames,4);

for i = Fint:readerobj.NumberOfFrames
    %fprintf('%i',i);

    % Access frame of interest - if error (mostly for the last frames,
    % don't know why), will analyze previous frame...
    try
        fr    = read(readerobj,i);
    end
    % convert frame to grayscale
    fr_bw = rgb2gray(fr);
%     keyboard
    %%% Label Color Mask
    label         = repmat(logical(fr_bw>threshF),[1 1 3]);
    mask(label)   = fr(label);
    mask(~label)  = 0;

    %%% Find centroid of remaining pixels %%%
    bw_mask = rgb2gray(mask);
    [L,Nl]  = bwlabel(double(bw_mask));
    ids     = [];

    % Initialize red and blue LEDS as missing (=> -1)
    Rr = [-1 -1];
    Br = [-1 -1];

    % Update centroid if connected components are found
    if Nl > 0
        a = regionprops(L,'PixelList');

        for ii = 1:Nl
            % Skip single pixels
            if size(a(ii).PixelList,1)<2
                continue
            end

            % Access color information and calculate means
            R  = mask(a(ii).PixelList(:,2),a(ii).PixelList(:,1),1);
            mR = mean(R(R>0));
            B  = mask(a(ii).PixelList(:,2),a(ii).PixelList(:,1),3);
            mB = mean(B(B>0));

            if mR > mB && mR > 200
                ids = [ids; a(ii).PixelList];
                Rr   = round(mean(a(ii).PixelList,1));
            elseif mR < mB && mB > 200
                ids = [ids; a(ii).PixelList];
                Br   = round(mean(a(ii).PixelList,1));
            else
                continue
            end

        end
    end

    pos(i,:) = [Rr(1),Rr(2),Br(1),Br(2)];

    % End processing time
    if mod(i,100)==0 & i<1000
        h = waitbar(i/readerobj.NumberOfFrames);
        if 1
            ixr = pos(i-99:i,1);
            ixr = ixr>-1;
            ixb = pos(i-99:i,3);
            ixb = ixb>-1;
            figure(1),clf,
            subplot(3,1,1);imshow(uint8(fr));title('If looks wrong, Ctrl+C and change threshold \!!')
            subplot(3,1,2),imshow(uint8(bw_mask));title('Mask')
            subplot(3,1,3)
                plot(pos(ixr,1),pos(ixr,2),'r')
                hold on
                plot(pos(ixb,3),pos(ixb,4),'b')
            fprintf('Detection of Red LED failed %i times (%i times for the blue LED) in the last 100 frames\n',sum(~ixr),sum(~ixb));
        end
    elseif mod(i,1000)==0
        h = waitbar(i/readerobj.NumberOfFrames);
    end

end
close(h)


function [s,Ori_s,Unmix_s,SetupStruc] = readData(Angle,SetupStruc,channel)
Num = length(Angle);
SetupStruc.Angle = Angle;
T60 = SetupStruc.T60;
Sign_compared = SetupStruc.Sign_compared;
Channel_Num = SetupStruc.Channel_Num;
Len = zeros(Num,1);
if(~exist('channel','var'))
    channel = 1;
end
if(SetupStruc.Sign_Mid==1)
    channel_line = 0:Channel_Num-1;
else
    channel_line = 1:Channel_Num;
end
for n = 1:Num
    if(SetupStruc.Height==1)
        dataPath = 'simu_data/DifferentHeight/T60_';
    else
        dataPath = 'simu_data/SameHeight/T60_';
    end
    for i = channel_line%0:Channel_Num-1
        wavName =strcat(dataPath,num2str(T60),'/',num2str(Angle(n)),'/Mic',num2str(i),'.wav');
        if(SetupStruc.Sign_Mid==1)
            eval(strcat('[s_temp', num2str(n), '(:,', num2str(i), '+1),fs] = audioread(''', wavName, ''');'));
        else
            eval(strcat('[s_temp', num2str(n), '(:,', num2str(i), '),fs] = audioread(''', wavName, ''');'));
        end
    end
    eval(strcat('Len(n) = size(s_temp', num2str(n),',1);'));
end
SetupStruc.fs = fs;
len = min(Len);
s = s_temp1(1:len,:);
Unmix_s(:,:,1) = s;
if(Num>1)
    Ori_s = zeros(len,Num);
    Ori_s(:,1) = s_temp1(1:len,channel);
else
    Ori_s = zeros(len,2);
    Ori_s_temp = audioread(strcat(dataPath,'0/',num2str(Angle(1)),'/Mic0.wav'));
    Ori_s(:,1) = Ori_s_temp(1:len);
    Ori_s(:,2) = s_temp1(1:len,channel);
end
for n = 2:Num
    eval(strcat('s_temp = s_temp', num2str(n), ';'));
    s = s+s_temp(1:len,:);
    Unmix_s(:,:,n) = s_temp(1:len,:);
    Ori_s(:,n) = s_temp(1:len,channel);
end
if(Sign_compared<0 && Num>1)
    for i = 1:Num
        %%%% In the last version, if Sign_compared>-1, choose the signal in
        %%%% the T60=0s, else in the select T60
%         Ori_s_temp = audioread(strcat(dataPath,'0/',num2str(Angle(i)),'/Mic',num2str(Sign_compared),'.wav'));
        %%%% In this version, if Sign_compared<0, chosse the original
        %%%% signal, else choose the select T60
        Ori_s_temp = audioread(strcat('simu_data/oral/',num2str(Angle(i)),'.wav'));
        Ori_s(:,i) = Ori_s_temp(1:len);
    end
end
if(SetupStruc.AddNoiseFlag==1)
    av_pow = mean( sum(s.^2,1)/len );       % Average mic power across all received signals.
    sigma_noise = sqrt( av_pow/(10^(SetupStruc.NoiseSNR/10)) );		% st. dev. of white noise component to achieve desired SNR.
    s = s + sigma_noise*randn(size(s));      % Add some random noise
end
% autoPlot(Ori_s,fs,-1);   %%%the 3rd parameter is used to control whether adjusting the range of y axis when equal -1
% autoPlot(s(:,1),fs);
return;


function[h]=regionplot(varargin)
%REGIONPLOT  Plots a simple box indicating a latitude / longitude region.
%
%   REGIONPLOT(REGION) draws a latitude / longitue box indicated by REGION
%   on the current axes.
%
%   REGION is an array with the format [WEST EAST SOUTH NORTH]. Longitudes
%   may either be specified on the interval [-180, 180] or on [0, 360].
%
%   By default, longitudes will be converted to [-180,180] unless the
%   region overlaps the dateline, in which case [0,360] will be used.
%
%   The current axes will be held as the box is plotted, then returned to
%   its previous HOLD state.
%
%   REGION can also be a cell array of N arrays, each with the format
%   REGION{N}=[WEST EAST SOUTH NORTH].  All N regions will then be plotted.
%
%   REGIONPLOT is compatible with the M_MAP toolbox, as described below.
%
%   H=REGIONPLOT outputs the line handle H to the plotted box.
%   __________________________________________________________________
%
%   Additional options
%
%   H=REGIONPLOT returns the graphics handle to the plotted box.
%
%   REGIONPLOT(REGION,STY) uses style string STY, in the LINESTYLE format,
%   with a default value of STY='k'.
%
%   REGIONPLOT(REGION,'M_MAP') will work with Rich Pawlowicz's M_MAP
%   package by calling M_PLOT.
%
%   The additional input parameters can be input together in either order,
%   i.e. REGIONPLOT(REGION,STY,'M_MAP') or REGIONPLOT(REGION,'M_MAP',STY).
%   __________________________________________________________________
%
%   See also INREGION, TRAJEXTRACT, TOPOPLOT.
%
%   'regionplot --f' generates some sample figures.
%
%   Usage: regionplot(region);
%          h=regionplot(region,'m_map');
%          h=regionplot(region,'m_map','2k');
%   __________________________________________________________________
%   This is part of JLAB --- type 'help jlab' for more information
%   (C) 2013--2016 J.M. Lilly --- type 'help jlab_license' for details

if strcmpi(varargin{1}, '--f')
    type makefigs_regionplot
    makefigs_regionplot;
    return
end
region=varargin{1};
varargin=varargin(2:end);
sty='k';
str='matlab';
for i=1:2
    if length(varargin)>=1
        if ischar(varargin{1})
            if strfind(lower(varargin{1}),'m_m')
                str=lower(varargin{1});
            else
                sty=varargin{1};
            end
            varargin=varargin(2:end);
        end
    end
end

if ~iscell(region)
    h=regionplot_one(region,str,sty);
    set(h,'visible','on')
    %set(h(~isnan(h)),'visible','on')
else
    bhold=ishold;
    set(gca,'visible','off')
    hold on
    storestate=get(gcf,'BackingStore');
    set(gcf,'BackingStore','off')
    for i=1:length(region)
         h(i)=regionplot_one(region{i},str,sty);
    end
    linestyle(h,'default');
    set(h,'visible','on')
    %set(h(~isnan(h)),'visible','on')

    set(gcf,'BackingStore',storestate)
    if ~bhold
        hold off
    end
     set(gca,'visible','on')
end

if nargout==0
    clear h
end

function[h]=regionplot_one(region,str,sty)

west=region(1);
east=region(2);
south=region(3);
north=region(4);

ax=axis;
if ax(1)>180 || deg180(west)>deg180(east)
    west=deg360(west);
    east=deg360(east);
else
    %west=deg180(west);
    %east=deg180(east);
end

bhold=ishold;
hold on
if strcmpi(str(1:3),'m_m')
     h=m_plot([west east east west west],[south south north north south],'visible','off');
else
     h=plot([west east east west west],[south south north north south],'visible','off');
end
linestyle(h,sty);
if ~bhold,
    hold off
end

%use ebasnfloats
%%Region shifted to be greater than 180
%region=[-30+250 -21+250 24 35];
%%Region shifted to overlap dateline
%region=[-30+205 -21+205 24 35];
%figure,cellplot(celladd(205,lon),lat),latratio,regionplot(region),axis tight
%title('Floats from Eastern Basin experiment')
%xlabel('Longitude'),ylabel('Latitude'),boxon
%ax=axis;

%reporttest('REGIONPLOT',aresame())


%==============================================================================
% 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/
%==============================================================================
% Images from a histologial serial sectioning,
% data courtesy Oliver Schmitt, Institute of Anatomy, University of Rostock, Germany
%==============================================================================

checkDataFile
if expfileExists, return; end;
viewPara = {'viewImage','viewImage2D','colormap','gray(256)'};
expfile = jpgs2data('','HNSP-T.jpg','HNSP-R.jpg','omega',[0,2,0,1],'viewPara',viewPara,'m',[512,256]);
checkDataFile
%==============================================================================


%% Summarize Text Using Transformers
% This example shows how to summarize a piece of text using GPT-2.
%
% Transformer networks such as GPT-2 can be used to summarize a piece of
% text. The trained GPT-2 transformer can generate text given an initial
% sequence of words as input. The model was trained on comments left on
% various web pages and internet forums.
%
% Because lots of these comments themselves contain a summary indicated by
% the statement "TL;DR" (Too long, didn't read), you can use the
% transformer model to generate a summary by appending "TL;DR" to the input
% text. The |generateSummary| function takes the input text, automatically
% appends the string |"TL;DR"| and generates the summary.

%% Load Transformer Model
% Load the GPT-2 transformer model using the |gpt2| function.

mdl = gpt2;

%% Load Data
% Extract the help text for the |eigs| function.

inputText = help('eigs')

%% Generate Summary
% Summarize the text using the |generateSummary| function.

rng('default')
summary = generateSummary(mdl,inputText)


% STD_CLUSTMAXELEC - function to find the electrode with maximum absolute projection
%                  for each component of a cluster
% Usage:
%     >> [eleclist, setlist, complist] = std_clustmaxelec(STUDY, ALLEEG, clustind);
%
% Inputs:
%   STUDY        - STUDY set structure containing (loaded) EEG dataset structures
%   ALLEEG       - ALLEEG vector of EEG structures, else a single EEG dataset.
%   clustind     - (single) cluster index
%
% Outputs:
%   eleclist     - [cell] electrode list
%   setlist      - [integer] set indices for the cluster
%   complist     - [integer] component indices for the cluster
%
% Authors: Claire Braboszcz & Arnaud Delorme , CERCO, UPS/CRNS, 2011

% Copyright (C) Claire Braboszcz, CERCO, UPS/CRNS, 2011
%
% This file is part of EEGLAB, see http://www.eeglab.org
% for the documentation and details.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%
% 1. Redistributions of source code must retain the above copyright notice,
% this list of conditions and the following disclaimer.
%
% 2. Redistributions in binary form must reproduce the above copyright notice,
% this list of conditions and the following disclaimer in the documentation
% and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
% THE POSSIBILITY OF SUCH DAMAGE.

function std_clustmaxelec(STUDY, ALLEEG, clusterind);

if nargin < 1
    help findicmaxelec;
    return;
end

fprintf('Finding electrodes with max weight for cluster %d\n', clusterind);
fprintf('-------------------------------------------------\n');

for index = 1:length(STUDY.cluster(clusterind).comps)
    set  = STUDY.cluster(clusterind).sets(1,index);
    comp = STUDY.cluster(clusterind).comps( index);

    [tmp maxelec] = max( abs(ALLEEG(set).icawinv(:, comp)) );
    indelec = ALLEEG(set).icachansind(maxelec);
    maxallelec{index} = ALLEEG(set).chanlocs(indelec).labels;
    allelec = unique_bc(maxallelec);

    fprintf('The electrode with the max weight for component %d of dataset %d is "%s"\n', comp, set, maxallelec{index});
end

for indelec=1:length(allelec)
    nbelec{indelec} = length(find(strcmp(allelec{indelec}, maxallelec) == 1));

    fprintf('Number of occurrence of electrode %s: %d\n', allelec{indelec}, nbelec{indelec});
end


function imo = cnn_get_batch(images, varargin)
% Modified from CNN_IMAGENET_GET_BATCH
%
% - added `pad` option
% - deals with images of types other than jpeg

opts.imageSize = [227, 227] ;
opts.border = [29, 29] ;
opts.pad = 0;  % [TOP BOTTOM LEFT RIGHT]
opts.keepAspect = true ;
opts.numAugments = 1 ;
opts.transformation = 'none' ;
opts.averageImage = [] ;
opts.rgbVariance = zeros(0,3,'single') ;
opts.interpolation = 'bilinear' ;
opts.numThreads = 1 ;
opts.prefetch = false ;
opts = vl_argparse(opts, varargin);

% if only one value is given, apply the same amount of padding to all borders
if numel(opts.pad)==1, opts.pad = repmat(opts.pad,[1 4]); end
if numel(opts.border)==1, opts.border = repmat(opts.border,[1 2]); end

% fetch is true if images is a list of filenames (instead of
% a cell array of images)
fetch = numel(images) >= 1 && ischar(images{1}) ;

% isjpg is true if all images to fetch are of jpeg format
isjpg = fetch && strcmpi(images{1}(end-3:end),'.jpg');

if opts.prefetch
  if isjpg, vl_imreadjpeg(images, 'numThreads', opts.numThreads, 'prefetch'); end
  imo = [] ;
  return ;
end

if fetch
  if isjpg,
    im = vl_imreadjpeg(images,'numThreads', opts.numThreads) ;
  else
    im = cell(size(images));
  end
else
  im = images ;
end

tfs = [] ;
switch opts.transformation
  case 'none'
    tfs = [
      .5 ;
      .5 ;
       0 ] ;
  case 'f5'
    tfs = [...
      .5 0 0 1 1 .5 0 0 1 1 ;
      .5 0 1 0 1 .5 0 1 0 1 ;
       0 0 0 0 0  1 1 1 1 1] ;
  case 'f25'
    [tx,ty] = meshgrid(linspace(0,1,5)) ;
    tfs = [tx(:)' ; ty(:)' ; zeros(1,numel(tx))] ;
    tfs_ = tfs ;
    tfs_(3,:) = 1 ;
    tfs = [tfs,tfs_] ;
  case 'stretch'
  otherwise
    error('Uknown transformations %s', opts.transformation) ;
end
[~,transformations] = sort(rand(size(tfs,2), numel(images)), 1) ;

if ~isempty(opts.rgbVariance) && isempty(opts.averageImage)
  opts.averageImage = zeros(1,1,3) ;
end
if numel(opts.averageImage) == 3
  opts.averageImage = reshape(opts.averageImage, 1,1,3) ;
end

imo = zeros(opts.imageSize(1), opts.imageSize(2), 3, ...
            numel(images)*opts.numAugments, 'single') ;

si = 1 ;
for i=1:numel(images)

  % acquire image
  if isempty(im{i})
    imt = imread(images{i}) ;
    imt = single(imt) ; % faster than im2single (and multiplies by 255)
  else
    imt = im{i} ;
  end
  if size(imt,3) == 1
    imt = cat(3, imt, imt, imt) ;
  end

  % pad
  if ~isempty(opts.pad) && any(opts.pad>0),
    imtt = imt;
    imt = 255*ones(size(imtt,1)+sum(opts.pad(1:2)), ...
      size(imtt,2)+sum(opts.pad(3:4)), 3, 'like', imtt);
    imt(opts.pad(1)+(1:size(imtt,1)), opts.pad(3)+(1:size(imtt,2)),:) = imtt;
  end

  % resize
  w = size(imt,2) ;
  h = size(imt,1) ;
  factor = [(opts.imageSize(1)+opts.border(1))/h ...
            (opts.imageSize(2)+opts.border(2))/w];

  if opts.keepAspect
    factor = max(factor) ;
  end
  if any(abs(factor - 1) > 0.0001)
    imt = imresize(imt, ...
                   'scale', factor, ...
                   'method', opts.interpolation) ;
  end

  % crop & flip
  w = size(imt,2) ;
  h = size(imt,1) ;
  for ai = 1:opts.numAugments
    switch opts.transformation
      case 'stretch'
        sz = round(min(opts.imageSize(1:2)' .* (1-0.1+0.2*rand(2,1)), [h;w])) ;
        dx = randi(w - sz(2) + 1, 1) ;
        dy = randi(h - sz(1) + 1, 1) ;
        flip = rand > 0.5 ;
      otherwise
        tf = tfs(:, transformations(mod(ai-1, numel(transformations)) + 1)) ;
        sz = opts.imageSize(1:2) ;
        dx = floor((w - sz(2)) * tf(2)) + 1 ;
        dy = floor((h - sz(1)) * tf(1)) + 1 ;
        flip = tf(3) ;
    end
    sx = round(linspace(dx, sz(2)+dx-1, opts.imageSize(2))) ;
    sy = round(linspace(dy, sz(1)+dy-1, opts.imageSize(1))) ;
    if flip, sx = fliplr(sx) ; end

    if ~isempty(opts.averageImage)
      offset = opts.averageImage ;
      if ~isempty(opts.rgbVariance)
        offset = bsxfun(@plus, offset, reshape(opts.rgbVariance * randn(3,1), 1,1,3)) ;
      end
      imo(:,:,:,si) = bsxfun(@minus, imt(sy,sx,:), offset) ;
    else
      imo(:,:,:,si) = imt(sy,sx,:) ;
    end
    si = si + 1 ;
  end
end


%%*****************************************************************
%% HSDsqlpmisc:
%% produce infeasibility certificates if appropriate
%%
%% Input: X,y,Z are the original variables, not the HSD variables.
%%*****************************************************************
%% SDPT3: version 4.0
%% Copyright (c) 1997 by
%% Kim-Chuan Toh, Michael J. Todd, Reha H. Tutuncu
%% Last Modified: 16 Sep 2004
%%*****************************************************************

   function [X,y,Z,resid,reldist,param,msg] = HSDsqlpmisc(blk,At,C,b,X,y,Z,permZ,param);

   obj         = param.obj;
   relgap      = param.relgap;
   prim_infeas = param.prim_infeas;
   dual_infeas = param.dual_infeas;
   ZpATynorm   = param.ZpATynorm;
   inftol      = param.inftol;
   m0          = param.m0;
   indeprows   = param.indeprows;
   termcode    = param.termcode;
   AX          = param.AX;
   normX0      = param.normX0;
   normZ0      = param.normZ0;
   printlevel  = param.printlevel;
%%
   resid = []; reldist = []; msg = [];
   Anorm = ops(At,'norm'); xnorm = ops(X,'norm'); ynorm = norm(y);
%%
   if (termcode <= 0)
      %%
      %% To detect near-infeasibility when the algorithm provides
      %% a "better" certificate of infeasibility than of optimality.
      %%
      err = max([prim_infeas,dual_infeas,relgap]);
      iflag = 0;
      if (obj(2) > 0)
         homRd = ZpATynorm/obj(2);
         if (homRd < 1e-2*sqrt(err*inftol))
            iflag = 1;
            termcode = 1;
            param.termcode = 1;
         end
      elseif (obj(1) < 0)
         homrp = norm(AX)/(-obj(1));
         if (homrp < 1e-2*sqrt(err*inftol))
            iflag = 1;
            termcode = 2;
            param.termcode = 2;
         end
      end
   end
   if (termcode == 1)
      rby = 1/(b'*y); y = rby*y; Z = ops(Z,'*',rby);
      resid = ZpATynorm * rby;
      reldist = ZpATynorm/(Anorm*ynorm);
      msg = 'Stop: primal problem is suspected of being infeasible';
      if (printlevel); fprintf('\n  %s',msg); end
   end
   if (termcode == 2)
      tCX = blktrace(blk,C,X);
      X = ops(X,'*',1/(-tCX));
      resid = norm(AX) /(-tCX);
      reldist = norm(AX)/(Anorm*xnorm);
      msg = 'Stop: dual problem is suspected of being infeasible';
      if (printlevel); fprintf('\n  %s',msg); end
   end
   if (termcode == 3)
      maxblowup = max(ops(X,'norm')/normX0,ops(Z,'norm')/normZ0);
      msg = sprintf('Stop: primal or dual is diverging, %3.1e',maxblowup);
      if (printlevel); fprintf('\n  %s',msg); end
   end
   [X,Z] = unperm(blk,permZ,X,Z);
   if ~isempty(indeprows)
      ytmp = zeros(m0,1);
      ytmp(indeprows) = y;
      y = ytmp;
   end
%%*****************************************************************************
%% unperm: undo the permutations applied in validate.
%%
%% [X,Z,Xiter,Ziter] = unperm(blk,permZ,X,Z,Xiter,Ziter);
%%
%% undoes the permutation introduced in validate.
%% can also be called if Xiter and Ziter have not been set as
%%
%% [X,Z] = unperm(blk,permZ,X,Z);
%%
%% SDPT3: version 3.0
%% Copyright (c) 1997 by
%% K.C. Toh, M.J. Todd, R.H. Tutuncu
%% Last modified: 2 Feb 01
%%*****************************************************************************

  function [X,Z] = unperm(blk,permZ,X,Z);
%%
  for p = 1:size(blk,1)
     if (strcmp(blk{p,1},'s') & ~isempty(permZ{p}))
        per = permZ{p};
        X{p} = X{p}(per,per);
        Z{p} = Z{p}(per,per);
     end
  end
%%*****************************************************************************


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

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

    methods
        %% Default settings of the problem
        function Setting(obj)
            config.name = 'nb201';
            config.args.fidelity = 200;
            config.args.objs = ['err&params&flops&edgegpu_latency&' ...
                'edgegpu_energy&eyeriss_latency&eyeriss_energy&' ...
                'eyeriss_arithmetic_intensity'];
            config.args.dataset = 'cifar10';
            config.args.normalized_objectives = true;
            obj.Setting@EvoXBenchProblem(config);
        end
    end
end


function img=minimizeTV(img,varargin)
%MINIMIZETV MATLAB wrapper for the CUDA stepest descend minimization of TV
% norm. Note that this does not minimize the TV noise, using the ROF model,
% this minimizes the TV alone, using gradient desced.
% Infinite iterations of this code will lead to a flat image.
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% This file is part of the TIGRE Toolbox
%
% Copyright (c) 2015, University of Bath and
%                     CERN-European Organization for Nuclear Research
%                     All rights reserved.
%
% License:            Open Source under BSD.
%                     See the full license at
%                     https://github.com/CERN/TIGRE/blob/master/LICENSE
%
% Contact:            tigre.toolbox@gmail.com
% Codes:              https://github.com/CERN/TIGRE/
% Coded by:           Ander Biguri
%--------------------------------------------------------------------------
if nargin >= 5
    [gpuids] = parse_inputs(varargin{3:length(varargin)});
else
    gpuids = GpuIds();
end
if nargin==1
    dtvg=1;
    ng=30;
else
    if nargin == 5
        dtvg=varargin{1};
        ng=varargin{2};
    else
        error('Wrong amount of inputs, 1 or 5 expected');
    end
end

img=minTV(img,dtvg,ng,gpuids.devices);

end

function [gpuids]=parse_inputs(varargin)
    %fprintf('parse_inputs0(varargin (%d))\n', length(varargin));
    if isempty(varargin)
        gpuids = GpuIds();
    else
        % create input parser
        p=inputParser;
        % add optional parameters
        addParameter(p,'gpuids', GpuIds());
        %execute
        parse(p,varargin{:});
        %extract
        gpuids=p.Results.gpuids;
    end
end


function [scan3M,dose3mC,strMaskC,xyzGridC,strColorC] = ...
    getScanDoseStrVolumes(scanNum,doseNumV,structNamC,planC)
% function [scan3M,dose3mC,strMaskC] = ...
% getScanDoseStr(scanNum,doseNumV,structnamC,planC)
%
% This function returns volumetric matrices for scan, dose and structure
% masks on the original scan grid.
%
% Example usage
% cerrFileName = 'L:\Data\RTOG0617\CERR_files_tcia_registered_0617-489880_09-09-2000-50891\0617-489880_09-09-2000-50891.mat';
% scanNum = 1;
% doseNum = 1;
% structNamC = {'DL_HEART_MT','DL_AORTA','DL_LA','DL_LV','DL_RA',...
%       'DL_RV','DL_IVC','DL_SVC','DL_PA'};
%
% % Load planC from file
% planC = loadPlanC(cerrFileName,tempdir);
% planC = updatePlanFields(planC);
% planC = quality_assure_planC(cerrFileName,planC);
% % Get scan,dose, struct volumes
% [scan3M,dose3M,strMaskC] = getScanDoseStr(scanNum,doseNum,structnamC,planC);
%
% APA, 11/2/2020

indexS = planC{end};

% Extract scan grid
[xValsV, yValsV, zValsV] = getScanXYZVals(planC{indexS.scan}(1));
xyzGridC = {xValsV, yValsV, zValsV};

% Extract scan
scan3M = double(planC{indexS.scan}(scanNum).scanArray);
ctOffset = double(planC{indexS.scan}(scanNum).scanInfo(1).CTOffset);
scan3M = scan3M - ctOffset;

% Extract Dose on scan grid
scanType = 'normal';
for iDose = 1:length(doseNumV)
    doseNum = doseNumV(iDose);
    dose3mC{iDose} = getDoseOnCT(doseNum, scanNum, scanType, planC);
end

% Extract structure
numStructs = length(structNamC);
strC = {planC{indexS.structures}.structureName};
strMaskC = cell(1,numStructs);
strColorC = cell(1,numStructs);
for iStr = 1:numStructs
    strNum = getMatchingIndex(structNamC{iStr},strC,'exact');
    strMask3M = getStrMask(strNum,planC);
    strMaskC{iStr} = strMask3M;
    strColorC{iStr} = planC{indexS.structures}(strNum).structureColor;
end


% The COBRAToolbox: testGeneMCS.m
%
% Purpose:
%     - Check the function of geneMCS using different solvers
%
% Authors:
%     - Luis V. Valcarcel 2017-11-17
%

global CBTDIR
requiredSolvers = {'ibm_cplex'};
prepareTest('requiredSolvers',requiredSolvers);

% save the current path
currentDir = pwd;

% initialize the test
testDir = fileparts(which('testGeneMCS'));
cd(testDir);

% define the solver packages to be used to run this test
solverPkgs = {'ibm_cplex', 'glpk', 'gurobi'};

% Load Toy Example
fileName = [CBTDIR filesep 'tutorials' filesep 'analysis' filesep 'gMCS' filesep 'gMCStoyExample.mat'];
if 0
    %TODO gMCStoyExample.mat needs to be made compatible with
%     testGeneMCS.m:
%     Error using readCbModel (line 232)
%     There were no valid models in the mat file.
%     Please load the model manually via ' load /home/rfleming/work/sbgCloud/code/fork-cobratoolbox/tutorials/analysis/gMCS/gMCStoyExample.mat' and check it with verifyModel() to validate it.
%     Try using convertOldStyleModel() before verifyModel() to bring the model structure up to date.
%     Error in testGeneMCS (line 25)
%     model = readCbModel([CBTDIR filesep 'tutorials' filesep 'analysis' filesep 'gMCS' filesep 'gMCStoyExample.mat']);
    model = readCbModel(fileName);
else
    load(fileName)
end
% expected solution
true_gmcs = cell(3,1);
true_gmcs{1} = {'g5'}';
true_gmcs{2} = {'g1' 'g4'}';
true_gmcs{3} = {'g2' 'g3' 'g4'}';

for k = 1:length(solverPkgs)
    fprintf(' -- Running testGeneMCS using the solver interface: %s ... ', solverPkgs{k});

    solverLPOK = changeCobraSolver(solverPkgs{k}, 'MILP', 0);

    if solverLPOK
        % Eliminate G-matrix if it exist
        if exist([currentDir filesep 'G_toy_example_gMCS.mat'], 'file')
            delete G_toy_example_gMCS.mat
        end

        % Check errors when missing argument
        assert(verifyCobraFunctionError('calculateGeneMCS', 'inputs', {model, 20, 5}));
        assert(verifyCobraFunctionError('calculateGeneMCS', 'inputs', {'toy_example_gMCS', [], 20,5}));
        assert(verifyCobraFunctionError('calculateGeneMCS', 'inputs', {'toy_example_gMCS', model, [],5}));
        assert(verifyCobraFunctionError('calculateGeneMCS', 'inputs', {'toy_example_gMCS', model, 20}));

        % Calculate GMCS
        [gmcs, gmcs_time] = calculateGeneMCS('toy_example_gMCS', model, 20,5);

        % Check if the solution obtained is the same as the expected
        % solution
        gmcsIsTrue = zeros(size(true_gmcs));
        for i = 1:numel(gmcs)
            for j=1:numel(true_gmcs)
                aux1 = gmcs{i};
                aux2 = true_gmcs{j};
                if isequal(aux1,aux2)
                    gmcsIsTrue(j) = gmcsIsTrue(j)+1;
                    break
                end
            end
        end
        assert(sum(~logical(gmcsIsTrue))==0);
        %Now, test with a gene_set
        options = struct();
%         options.gene_set = model.genes([1 2 4 5 6]);
        [gmcs, gmcs_time] = calculateGeneMCS('toy_example_gMCS', model, 20, 5, 'gene_set', model.genes([1 2 4 5 6]));
            % Check the gMCS
        [IsCutSet, IsMinimal, geneNotMinimal] = checkGeneMCS(model, gmcs);
        assert(all(IsMinimal));
        assert(all(IsCutSet));
        %Assert that all correct solutions are there
        assert(all(cellfun(@(x) any(cellfun(@(y) isempty(setxor(x,y)),gmcs)), {{'g5'},{'g1','g4'}})))
        %and, that there are no surplus solutions
        assert(all(cellfun(@(x) any(cellfun(@(y) isempty(setxor(x,y)),{{'g5'},{'g1','g4'}})), gmcs)))
        %Finally test this for gMCS containing a specific knockout.
        options.KO = 'g5';
        [gmcs, gmcs_time] = calculateGeneMCS('toy_example_gMCS', model, 20, 5, options);
        assert(isequal(gmcs,{{'g5'}}));
        % Check the gMCS
        [IsCutSet, IsMinimal, geneNotMinimal] = checkGeneMCS(model, gmcs);
        assert(IsMinimal);
        assert(IsCutSet);
        %assert using one worker
        options = struct();
        options.numWorkers = 1;
        assert(~verifyCobraFunctionError('calculateGeneMCS', 'inputs', {'toy_example_gMCS', model, 20, 5, options}));
    else
        warning('The test testGeneMCS cannot run using the solver interface: %s. The solver interface is not installed or not configured properly.\n', solverPkgs{k});
    end

    % Eliminate generated files
    if exist([testDir filesep 'G_toy_example_gMCS.mat'], 'file')
        delete G_toy_example_gMCS.mat
    end
    if exist([testDir filesep 'CobraMILPSolver.log'], 'file')
        delete CobraMILPSolver.log
    end
    if exist([testDir filesep 'MILPProblem.mat'], 'file')
        delete MILPProblem.mat
    end
    if exist([testDir filesep 'tmp.mat'], 'file')
        delete tmp.mat
    end

    % output a success message
    fprintf('Done.\n');
end

% change the directory
cd(currentDir)


function M = xfm_read(fname)
% M = xfm_read(fname)

%
% xfm_read.m
%
% Original Author: Bruce Fischl
% CVS Revision Info:
%    $Author: nicks $
%    $Date: 2011/03/02 00:04:13 $
%    $Revision: 1.4 $
%
% Copyright © 2011 The General Hospital Corporation (Boston, MA) "MGH"
%
% Terms and conditions for use, reproduction, distribution and contribution
% are found in the 'FreeSurfer Software License Agreement' contained
% in the file 'LICENSE' found in the FreeSurfer distribution, and here:
%
% https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
%
% Reporting: freesurfer@nmr.mgh.harvard.edu
%

fid = fopen(fname) ;
if (fid < 0)
	error(sprintf('could not open file %s', fname));
end

tline = fgetl(fid) ;
while ((length(tline) > 0) & (tline(1) == '%'))
	tline = fgetl(fid) ;
end

tok = strtok(tline);
while (strcmp(tok, 'Linear_Transform') ~= 1)
	tline = fgetl(fid) ;
	tok = strtok(tline);
end

M = zeros(4,4) ; M(4,4) = 1;
for row=1:3
	tline = fgetl(fid) ;  % one row of matrix
	tmp = sscanf(tline, '%f');
	 M(row,:) = tmp';
end

fclose(fid) ;


function obj = updateHistogram(obj,histIndex)

% x:...[DONE]
% y:...[DONE]
% histnorm:...[DONE]
% name:...[DONE]
% autobinx:...[DONE]
% nbinsx:...[DONE]
% xbins:...[DONE]
% autobiny:...[DONE]
% nbinsy:...[DONE]
% ybins:...[DONE]
% text:...[NOT SUPPORTED IN MATLAB]
% error_y:...[HANDLED BY ERRORBARSERIES]
% error_x:...[HANDLED BY ERRORBARSERIES]
% opacity: --- [TODO]
% xaxis:...[DONE]
% yaxis:...[DONE]
% showlegend:...[DONE]
% stream:...[HANDLED BY PLOTLYSTREAM]
% visible:...[DONE]
% type:...[DONE]
% orientation:...[DONE]

% MARKER:
% color: ...[DONE]
% size: ...[NA]
% symbol: ...[NA]
% opacity: ...[TODO]
% sizeref: ...[NA]
% sizemode: ...[NA]
% colorscale: ...[NA]
% cauto: ...[NA]
% cmin: ...[NA]
% cmax: ...[NA]
% outliercolor: ...[NA]
% maxdisplayed: ...[NA]

% MARKER LINE:
% color: ...[DONE]
% width: ...[DONE]
% dash: ...[NA]
% opacity: ...[TODO]
% shape: ...[NA]
% smoothing: ...[NA]
% outliercolor: ...[NA]
% outlierwidth: ...[NA]

%-------------------------------------------------------------------------%

%-AXIS INDEX-%
axIndex = obj.getAxisIndex(obj.State.Plot(histIndex).AssociatedAxis);

%-HIST DATA STRUCTURE- %
hist_data = get(obj.State.Plot(histIndex).Handle);

%-CHECK FOR MULTIPLE AXES-%
[xsource, ysource] = findSourceAxis(obj,axIndex);

%-AXIS DATA-%
eval(['xaxis = obj.layout.xaxis' num2str(xsource) ';']);
eval(['yaxis = obj.layout.yaxis' num2str(ysource) ';']);

%-------------------------------------------------------------------------%

%-hist xaxis-%
obj.data{histIndex}.xaxis = ['x' num2str(xsource)];

%-------------------------------------------------------------------------%

%-hist yaxis-%
obj.data{histIndex}.yaxis = ['y' num2str(ysource)];

%-------------------------------------------------------------------------%

%-hist type-%
obj.data{histIndex}.type = 'histogram';

%-------------------------------------------------------------------------%

%-HIST XAXIS-%
obj.data{histIndex}.histfunc= 'count';

%-------------------------------------------------------------------------%

orientation = histogramOrientation(hist_data);

switch orientation
    case 'v'

        %-hist x data-%
        xdata = mean(hist_data.XData(2:3,:));

        %-------------------------------------------------------------------------%

        %-hist y data-%
        xlength = 0;
        for d = 1:length(xdata)
            obj.data{histIndex}.x(xlength + 1: xlength + hist_data.YData(2,d)) = repmat(xdata(d),1,hist_data.YData(2,d));
            xlength = length(obj.data{histIndex}.x);
        end

        %-------------------------------------------------------------------------%

        %-hist autobinx-%
        obj.data{histIndex}.autobinx = false;

        %-------------------------------------------------------------------------%

        %-hist xbins-%
        xbins.start = hist_data.XData(2,1);
        xbins.end = hist_data.XData(3,end);
        xbins.size = diff(hist_data.XData(2:3,1));
        obj.data{histIndex}.xbins = xbins;

        %-------------------------------------------------------------------------%

    case 'h'

        %-hist y data-%
        ydata = mean(hist_data.YData(2:3,:));

        %-------------------------------------------------------------------------%

        %-hist y data-%
        ylength = 0;
        for d = 1:length(ydata)
            obj.data{histIndex}.y(ylength + 1: ylength + hist_data.XData(2,d)) = repmat(ydata(d),1,hist_data.XData(2,d));
            ylength = length(obj.data{histIndex}.y);
        end

        %-------------------------------------------------------------------------%

        %-hist autobiny-%
        obj.data{histIndex}.autobiny = false;

        %-------------------------------------------------------------------------%

        %-hist ybins-%
        ybins.start = hist_data.YData(2,1);
        ybins.end = hist_data.YData(3,end);
        ybins.size = diff(hist_data.YData(2:3,1));
        obj.data{histIndex}.ybins = ybins;

        %-------------------------------------------------------------------------%

end

%-------------------------------------------------------------------------%

%-hist name-%
obj.data{histIndex}.name = hist_data.DisplayName;

%-------------------------------------------------------------------------%

%-layout barmode-%
obj.layout.barmode = 'group';

%-------------------------------------------------------------------------%

%-layout bargap-%
obj.layout.bargap = (hist_data.XData(3,1)-hist_data.XData(2,2))/(hist_data.XData(3,1)-hist_data.XData(2,1));

%-------------------------------------------------------------------------%

%-hist line width-%
obj.data{histIndex}.marker.line.width = hist_data.LineWidth;

%-------------------------------------------------------------------------%

%-hist opacity-%
if ~ischar(hist_data.FaceAlpha)
    obj.data{histIndex}.opacity = hist_data.FaceAlpha;
end

%-------------------------------------------------------------------------%

%-hist marker-%
obj.data{histIndex}.marker = extractPatchFace(hist_data);

%-------------------------------------------------------------------------%

%-hist visible-%
obj.data{histIndex}.visible = strcmp(hist_data.Visible,'on');

%-------------------------------------------------------------------------%

%-hist showlegend-%
leg = get(hist_data.Annotation);
legInfo = get(leg.LegendInformation);

switch legInfo.IconDisplayStyle
    case 'on'
        showleg = true;
    case 'off'
        showleg = false;
end

obj.data{histIndex}.showlegend = showleg;

%-------------------------------------------------------------------------%

end


function save_joint_pair_stats( expidx )

p = exp_params(expidx);

pwIdxsAllrel = build_joint_pairs(p);

num_relations = length(pwIdxsAllrel);

graph = zeros(num_relations, 2);

for k = 1:num_relations
    graph(k, :) = pwIdxsAllrel{k};
end

graph = [graph; graph(:,2), graph(:,1)];

save_dir = fullfile(p.exp_dir, 'data');
load(fullfile(save_dir, 'all_pairs_stats'), 'means', 'std_devs');

means = [means; -means];
std_devs = [std_devs; std_devs];

input_file = fullfile(save_dir, 'all_stats.txt');

fid = fopen(input_file, 'wt');
write_text_matrix(fid, graph, 'graph');
write_text_matrix(fid, means, 'means');
write_text_matrix(fid, std_devs, 'std_devs');
fclose(fid);

save(fullfile(save_dir, 'all_pairs_stats_all'), 'means', 'std_devs', 'graph');

end