function obj = updateQuiver(obj, quiverIndex)

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

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

%-QUIVER DATA STRUCTURE- %
quiver_data = get(obj.State.Plot(quiverIndex).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) ';']);

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

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

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

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

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

%-quiver type-%
obj.data{quiverIndex}.type = 'scatter';

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

%-quiver visible-%
obj.data{quiverIndex}.visible = strcmp(quiver_data.Visible,'on');

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

%-quiver mode-%
obj.data{quiverIndex}.mode = 'lines';

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

%-scatter name-%
obj.data{quiverIndex}.name = quiver_data.DisplayName;

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

%-quiver line color-%
col = 255*quiver_data.Color;
obj.data{quiverIndex}.line.color = ['rgb(' col(1) ',' col(2) ',' col(3) ')'];

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

% check for x/y vectors
if isvector(quiver_data.XData)
    [quiver_data.XData, quiver_data.YData] = meshgrid(quiver_data.XData,quiver_data.YData);
end

%-format data-%
xdata = reshape(quiver_data.XData,1,size(quiver_data.XData,1)*size(quiver_data.XData,1));
ydata = reshape(quiver_data.YData,1,size(quiver_data.YData,1)*size(quiver_data.YData,1));
udata = reshape(quiver_data.UData,1,size(quiver_data.UData,1)*size(quiver_data.UData,1));
vdata = reshape(quiver_data.VData,1,size(quiver_data.VData,1)*size(quiver_data.VData,1));

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

%-quiver x-%
m = 1;
for n = 1:length(xdata)
obj.data{quiverIndex}.x(m) = xdata(n);
obj.data{quiverIndex}.x(m+1) = xdata(n) + 0.1*udata(n);
obj.data{quiverIndex}.x(m+2) = nan;
m = m + 3;
end

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

%-quiver y-%
m = 1;
for n = 1:length(ydata)
obj.data{quiverIndex}.y(m) = ydata(n);
obj.data{quiverIndex}.y(m+1) = ydata(n) + 0.1*vdata(n);
obj.data{quiverIndex}.y(m+2) = nan;
m = m + 3;
end

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

%-quiver barbs-%
if isHG2()
    % 'MaxHeadSize' scalar, matlab clips to 0.2 in r2014b
    maxheadsize = quiver_data.MaxHeadSize;
    % barb angular width, not supported by matlab
    head_width = deg2rad(17.5);
    for n = 1:length(xdata)
        % length of arrow
        l = norm([0.1*udata(n), 0.1*vdata(n)]);

        % angle of arrow
        phi = atan2(vdata(n),udata(n));

        % make barb with specified angular width, length is prop. to arrow
        barb = [...
            [-maxheadsize*l*cos(head_width), maxheadsize*l*sin(head_width)]; ...
            [0, 0]; ...
            [-maxheadsize*l*cos(head_width), -maxheadsize*l*sin(head_width)]; ...
            [nan, nan]; ...
            ]';

        % affine matrix: rotate by arrow angle and translate to end of arrow
        barb_transformation = affine2d([...
            [cos(phi), sin(phi), 0]; ...
            [-sin(phi), cos(phi), 0]; ...
            [xdata(n) + 0.1*udata(n), ydata(n) + 0.1*vdata(n), 1];
            ]);

        % place barb at end of arrow
        barb = transformPointsForward(barb_transformation, barb')';

        % add barb to plot data, inserting is optimized in matlab >2010
        for col = 1:4
            obj.data{quiverIndex}.x(end+1) = barb(1,col); % point 1
            obj.data{quiverIndex}.y(end+1) = barb(2,col);
        end
    end
end

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

%-scatter showlegend-%
leg = get(quiver_data.Annotation);
legInfo = get(leg.LegendInformation);

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

obj.data{quiverIndex}.showlegend = showleg;

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

end


function obj = updateErrorbar(obj, plotIndex)

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

	%-INITIALIZATION-%

	%-get data structures-%
	plotData = get(obj.State.Plot(plotIndex).Handle);

	%-get error data-%
	yPositiveDelta = date2NumData(plotData.YPositiveDelta);
	yNegativeDelta = date2NumData(plotData.YNegativeDelta);

	xPositiveDelta = date2NumData(plotData.XPositiveDelta);
	xNegativeDelta = date2NumData(plotData.XNegativeDelta);

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

	%-set trace-%

	updateLineseries(obj, plotIndex);

	%-errorbar visible-%
	obj.data{plotIndex}.error_y.visible = true;
	obj.data{plotIndex}.error_x.visible = true;

	%-errorbar type-%
	obj.data{plotIndex}.error_y.type = 'data';
	obj.data{plotIndex}.error_x.type = 'data';

	%-errorbar symmetry-%
	obj.data{plotIndex}.error_y.symmetric = false;

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

	%-set errorbar data-%

	obj.data{plotIndex}.error_y.array = yPositiveDelta;
	obj.data{plotIndex}.error_x.array = xPositiveDelta;

	obj.data{plotIndex}.error_x.arrayminus = xNegativeDelta;
	obj.data{plotIndex}.error_y.arrayminus = yNegativeDelta;

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

	%-errorbar thickness-%
	obj.data{plotIndex}.error_y.thickness = plotData.LineWidth;
	obj.data{plotIndex}.error_x.thickness = plotData.LineWidth;

	%-errorbar width-%
	obj.data{plotIndex}.error_y.width = obj.PlotlyDefaults.ErrorbarWidth;
	obj.data{plotIndex}.error_x.width = obj.PlotlyDefaults.ErrorbarWidth;

	%-errorbar color-%
	errorColor = getStringColor(255*plotData.Color);
	obj.data{plotIndex}.error_y.color = errorColor;
	obj.data{plotIndex}.error_x.color = errorColor;

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

end


function model = setFeedingFastingConstraints(model, feedingStatus,fastingValue,storageValue)
% This function sets constraints corresponding either to feeding (i.e.,
% storage reactions are set to have a lower bound of 0 while
% the upper bounds are set to >0 (storage is enabled) or to fasting (i.e.,
% storage reactions are set to have a lower bound of <0 (use of stored metabolites is enabled) while
% the upper bounds are set to 0 (storage is disabled).
%
% function model = setFeedingFastingConstraints(model, feedingStatus,fastingValue,storageValue)
%
% INPUT
% model             model structure
% feedingStatus     'feeding' = default bounds for diet uptake fastingValue for all diet exchanges, use diet script to refine, organ storage is turned on;
%                   'fasting' = all diet uptakes are closed, organ storage release is turned on
% fastingValue      default: fastingValue = -10;
% storageValue      default: storageValue = 10;
%
% OUTPUT
% model             with updated constraints
%
% Ines Thiele, 2015/2016
if ~exist('fastingValue','var')
    fastingValue = -10;
end
if ~exist('storageValue','var')
    storageValue = 10;
end

% load amino acids that can be stored
AAStorage;
storedInLiver={'nad(c)';'nadp(c)';'fad(c)';...
    'thmtp(c)';'pydam(c)';'pydx(c)';'pydxn(c)';...
    'coa(c)';'thf(c)';'btn(c)';'retinol(c)';'retfa(c)';...
    '11_cis_retfa(c)';'9_cis_retfa(c)';'25hvitd2(c)';'vitd3(c)';...
    'avite1(c)';'avite2(c)';'chol(c)';'fe3(c)';'phyQ(c)';...
    'glygn2(c)'};
StoreInKidney = {'ascb_L(c)';'chol(c)';};
StoreInMuscle ={'thmpp(c)';'25hvitd2(c)';'vitd3(c)';'chol(c)';'glygn2(c)'};

StoreInAdi={'25hvitd2(c)';'vitd3(c)';'avite1(c)';'avite2(c)';'phyQ(c)';...
    'hdca(c)';'tmndnc(c)';'lnlc(c)';'tag_hs(c)';...
    'c226coa(c)';'doco13ecoa(c)';'lnlccoa(c)';'lnlncacoa(c)';'lnlncgcoa(c)';...
    'odecoa(c)';'pmtcoa(c)';'stcoa(c)';'tmndnccoa(c)'
    };
if isfield(model,'rxnGeneMat')
    model = rmfield(model,'rxnGeneMat');
end
% set all sinks to 0
for i = 1 : length(model.rxns)
    if length(strfind(model.rxns{i},'sink_'))==1 ...
            && length(strfind(model.rxns{i},'sink_pre_prot(r)'))==0  ...
            && length(strfind(model.rxns{i},'sink_Ser_Gly_Ala_X_Gly(r)'))==0 ...
            && length(strfind(model.rxns{i},'sink_5hpet(c)'))==0
        %&& length(strfind(model.rxns{i},'sink_Tyr_ggn(c)'))==0 % ...
        %% && length(strfind(model.rxns{i},'sink_citr(c)'))==0
        % && length(strfind(model.rxns{i},'sink_Ser_Gly_Ala_X_Gly(r)'))==0 ...
        if isfield(model,'Microbiota') && model.Microbiota(i) ==0 %no microbe sink
            model.lb(i)=0;
        elseif ~isfield(model,'Microbiota')
            model.lb(i)=0;
        end
    end
end

DMs= (find(~cellfun(@isempty,strfind(model.rxns,'DM_'))));
model.lb(DMs) = 0;

% but not at the beginning of the abbr --> leaves in the
% microbe sinks
if 1
    tmp = strmatch('sink_',model.rxns);
    model.lb(tmp)=-10;
end

for i = 1 : length(model.rxns)
    if strfind(model.rxns{i},'sink_')
        model.rxns{i} = regexprep(model.rxns{i},'\[c\]','(c)');
        model.rxns{i} = regexprep(model.rxns{i},'\[r\]','(r)');
        %    model.rxns{i}
    end
end
modelexchanges1 = strmatch('Diet_EX_',model.rxns);
modelexchanges2 = strmatch('Diet_Ex_',model.rxns);
modelexchanges = [modelexchanges1;modelexchanges2];

if strcmp(feedingStatus,'feeding') % storage no sinks
    model.lb(modelexchanges)=fastingValue;
    model.ub(modelexchanges)=0;
elseif strcmp(feedingStatus,'fasting') % storage no sinks
    model.lb(modelexchanges)=0;
    model.ub(modelexchanges)=0;
    % exception for water

end

if strcmp(feedingStatus,'feeding') % storage no sinks
    for i = 1 : length(storedInLiver)
        storedInLiver{i};
        rxnName = strcat('Liver_sink_',storedInLiver{i});
        %   rxnName
        model = changeRxnBounds(model,rxnName,0,'l');
        model = changeRxnBounds(model,rxnName, storageValue,'u');
    end
    for i = 1 : length(StoreInKidney)
        StoreInKidney{i};
        rxnName = strcat('Kidney_sink_',StoreInKidney{i});
        %  rxnName
        model = changeRxnBounds(model,rxnName,0,'l');
        model = changeRxnBounds(model,rxnName, storageValue,'u');
    end
    for i = 1 : length(StoreInMuscle)
        rxnName = strcat('Muscle_sink_',StoreInMuscle{i});
        %  rxnName
        model = changeRxnBounds(model,rxnName,0,'l');
        model = changeRxnBounds(model,rxnName, storageValue,'u');
    end
    for i = 1 : length(storageAA)
        rxnName = strcat('Muscle_',storageAA{i});
        %    rxnName
        model = changeRxnBounds(model,rxnName,0,'l');
        model = changeRxnBounds(model,rxnName, storageValue,'u');
    end
    for i = 1 : length(StoreInAdi)
        rxnName = strcat('Adipocytes_sink_',StoreInAdi{i});
        %   rxnName
        StoreInAdi{i};
        model = changeRxnBounds(model,rxnName,0,'l');
        model = changeRxnBounds(model,rxnName, storageValue,'u');
    end
    rxnName = 'Retina_sink_crvnc(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
    rxnName = 'Heart_sink_chol(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
    rxnName = 'Brain_sink_crvnc(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
    rxnName = 'Brain_sink_chol(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
    rxnName = 'RBC_sink_glygn2(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
    rxnName = 'Skin_sink_vitd3(c)';
    model = changeRxnBounds(model,rxnName,0,'l');
    model = changeRxnBounds(model,rxnName, storageValue,'u');
elseif strcmp(feedingStatus,'fasting')
    for i = 1 : length(storedInLiver)
        rxnName = strcat('Liver_sink_',storedInLiver{i});
        model = changeRxnBounds(model,rxnName,fastingValue,'l');
        model = changeRxnBounds(model,rxnName,0,'u');
    end
    for i = 1 : length(StoreInKidney)
        rxnName = strcat('Kidney_sink_',StoreInKidney{i});
        model = changeRxnBounds(model,rxnName,fastingValue,'l');
        model = changeRxnBounds(model,rxnName,0,'u');
    end
    for i = 1 : length(StoreInMuscle)
        rxnName = strcat('Muscle_sink_',StoreInMuscle{i});
        model = changeRxnBounds(model,rxnName,fastingValue,'l');
        model = changeRxnBounds(model,rxnName,0,'u');
    end
    for i = 1 : length(storageAA)
        rxnName = strcat('Muscle_',storageAA{i});
        model = changeRxnBounds(model,rxnName,fastingValue,'l');
        model = changeRxnBounds(model,rxnName,0,'u');
    end
    for i = 1 : length(StoreInAdi)
        rxnName = strcat('Adipocytes_sink_',StoreInAdi{i});
        model = changeRxnBounds(model,rxnName,fastingValue,'l');
        model = changeRxnBounds(model,rxnName,0,'u');
    end
    rxnName = 'Retina_sink_crvnc(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
    rxnName = 'Heart_sink_chol(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
    rxnName = 'Brain_sink_crvnc(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
    rxnName = 'Brain_sink_chol(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
    rxnName = 'RBC_sink_glygn2(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
    rxnName = 'Skin_sink_vitd3(c)';
    model = changeRxnBounds(model,rxnName,fastingValue,'l');
    model = changeRxnBounds(model,rxnName,0,'u');
end

model.SetupInfo.FeedingStatus = feedingStatus;


%demo_SOFAplotGeometry - Script demonstrating the usage of SOFAplotGeometry.

% #Author: Piotr Majdak
% #Author: Michael Mihocic: header documentation updated (28.10.2021)
%
% Copyright (C) Acoustics Research Institute - Austrian Academy of Sciences
% Licensed under the EUPL, Version 1.2 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "License")
% You may not use this work except in compliance with the License.
% You may obtain a copy of the License at: https://joinup.ec.europa.eu/software/page/eupl
% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing  permissions and limitations under the License.

%% load a SOFA file in SimpleFreeFieldHRIR

SOFAfile=fullfile(SOFAdbPath,'database','widespread','ICO1m_00139.sofa');
disp(['Loading: ' SOFAfile]);
Obj=SOFAload(SOFAfile);

% plot all measurements
SOFAplotGeometry(Obj);
title(['Geometry SimpleFreeFieldHRIR, ' num2str(Obj.API.M) ' position(s)'])
set(gcf, 'Name', mfilename);

% % only show every 45th measurement
index = 1:45:Obj.API.M;
SOFAplotGeometry(Obj,index);
title(['Geometry SimpleFreeFieldHRIR, reduced to ' num2str(size(index,2)) ' position(s)'])
set(gcf, 'Name', mfilename);

% % %% load a SingleRoomDRIR SOFA file (outdated)
% disp(['Loading: ' 'db://' fullfile('database','thk','DRIR_LBS_VSA_1202RS_SBL.sofa')]);
% Obj=SOFAload(['db://' ...
%   fullfile('database','thk','DRIR_LBS_VSA_1202RS_SBL.sofa')]);
%
% % plot SOFA Object with 1202 Receivers
% SOFAplotGeometry(Obj);
% set(gcf, 'Name', mfilename)

% % remove all but one Receiver
Obj.ReceiverPosition = [0 0.09 0];
Obj.ReceiverPosition_Type = 'cartesian';
Obj.Data.IR = Obj.Data.IR(:,1,:);
Obj.Data.Delay = Obj.Data.Delay(:,1,:);
Obj = SOFAupdateDimensions(Obj);

SOFAplotGeometry(Obj);
title(['Geometry SimpleFreeFieldHRIR, ' num2str(Obj.API.R) ' receiver(s), ' num2str(Obj.API.M) ' position(s)'])
set(gcf, 'Name', mfilename);

% %% load a GeneralFIR SOFA file
SOFAfile=fullfile(SOFAdbPath,'database', 'tu-berlin','FABIAN_CTF_modeled.sofa');
Obj = SOFAload(SOFAfile);

SOFAplotGeometry(Obj);
title(['Geometry GeneralFIR, ' num2str(Obj.API.R) ' receiver(s), ' num2str(Obj.API.M) ' position(s)'])
set(gcf, 'Name', mfilename);

% % %% load example with room geometry (outdated)
% disp(['Loading: ' SOFAfile]);
% SOFAfile = fullfile(SOFAdbPath,'sofatoolbox_test', 'Oldenburg_OfficeII.sofa');
% Obj = SOFAload(SOFAfile);
%
% SOFAplotGeometry(Obj);
% set(gcf, 'Name', mfilename)

% %% if exists try plotting SOFA file containing spherical harmonic emitter
% if exist(fullfile(SOFAdbPath,'demo_SHforHRTFs_SH.sofa'))
%    Obj =  SOFAload(fullfile(SOFAdbPath,'demo_SHforHRTFs_SH.sofa'));
%     SOFAplotGeometry(Obj);
% else
%     error('Run demoSHforHRTFS.m first.')
% end


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

%%
clear; close all; clc;

%% Syntax
% |[FLs,VLs,logicAttachFaces,indCurve,Eb]=localRefineMap(FL,VL,V_SLIL_Lunate,distGrow,numGrowStepsRefine,cParSmoothCurve);|

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


function [scores, rects, pts, pts_valid] = detect_img( param, caffe_solver, thres )
    num = length(list);
    test_time = ceil(num / length(param.gpu_id));
    for i = 1 : test_time
        target_scale_now = param.max_img *
        for j = 1 : length(param.gpu_id)
            [ img, scale ] = scale_img_to_target( img, target )
        end
    end

end


function fname_out = savechgtab(fname, chgtab, warnings)
%SAVECHGTAB  Save a change table to a file.
%   SAVECHGTAB(FNAME, CHGTAB)
%   SAVECHGTAB(FNAME, CHGTAB, WARNINGS)
%   FNAME = SAVECHGTAB(FNAME, ...)
%
%   Writes a CHGTAB, suitable for use with APPLY_CHANGES to a file
%   specified by FNAME. If FNAME ends with '.mat' it saves CHGTAB
%   and WARNINGS to a MAT-file as the variables 'chgtab' and 'warnings',
%   respectively. Otherwise, it saves an M-file function that returns
%   the CHGTAB, with the optional WARNINGS in comments.
%
%   Optionally returns the filename, with extension added if necessary.
%
%   Input:
%       FNAME :  name of the file to be saved
%       CHGTAB :  change table suitable for use with APPLY_CHANGES
%       WARNINGS : optional cell array of warning messages (to be
%                   included in comments), such as those returned by
%                   PSSECON2CHGTAB
%
%   Output(s):
%       FNAME :  name of the file, with extention added if necessary

%   MATPOWER
%   Copyright (c) 2017, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%% handle input args
if nargin < 3
    warnings = {};
end

%% define named indices into data matrices
[CT_LABEL, CT_PROB, CT_TABLE, CT_TBUS, CT_TGEN, CT_TBRCH, CT_TAREABUS, ...
    CT_TAREAGEN, CT_TAREABRCH, CT_ROW, CT_COL, CT_CHGTYPE, CT_REP, ...
    CT_REL, CT_ADD, CT_NEWVAL, CT_TLOAD, CT_TAREALOAD, CT_LOAD_ALL_PQ, ...
    CT_LOAD_FIX_PQ, CT_LOAD_DIS_PQ, CT_LOAD_ALL_P, CT_LOAD_FIX_P, ...
    CT_LOAD_DIS_P, CT_TGENCOST, CT_TAREAGENCOST, CT_MODCOST_F, ...
    CT_MODCOST_X] = idx_ct;

%% constant names
bus_cols = {'BUS_I', 'BUS_TYPE', 'PD', 'QD', 'GS', 'BS', 'BUS_AREA', ...
    'VM', 'VA', 'BASE_KV', 'ZONE', 'VMAX', 'VMIN'};
br_cols = {'F_BUS', 'T_BUS', 'BR_R', 'BR_X', 'BR_B', 'RATE_A', ...
    'RATE_B', 'RATE_C', 'TAP', 'SHIFT', 'BR_STATUS', 'ANGMIN', 'ANGMAX'};
gen_cols = {'GEN_BUS', 'PG', 'QG', 'QMAX', 'QMIN', 'VG', 'MBASE', ...
    'GEN_STATUS', 'PMAX', 'PMIN', 'PC1', 'PC2', 'QC1MIN', 'QC1MAX', ...
    'QC2MIN', 'QC2MAX', 'RAMP_AGC', 'RAMP_10', 'RAMP_30', 'RAMP_Q', 'APF'};
gc_cols = {'CT_MODCOST_X', 'CT_MODCOST_F', '0', ...  %% use val+3
    'MODEL', 'STARTUP', 'SHUTDOWN', 'NCOST', 'COST'};
load_cols = {'CT_LOAD_ALL_PQ', 'CT_LOAD_FIX_PQ', 'CT_LOAD_DIS_PQ', ...
    'CT_LOAD_ALL_P', 'CT_LOAD_FIX_P', 'CT_LOAD_DIS_P'};
chgtypes = {'CT_REP', 'CT_REL', 'CT_ADD'};

%% verify valid filename
[pathstr, fcn_name, extension] = fileparts(fname);
if isempty(extension)
    extension = '.m';
end
if regexp(fcn_name, '\W')
    old_fcn_name = fcn_name;
    fcn_name = regexprep(fcn_name, '\W', '_');
    fprintf('WARNING: ''%s'' is not a valid function name, changed to ''%s''\n', old_fcn_name, fcn_name);
end
fname = fullfile(pathstr, [fcn_name extension]);

%% open and write the file
if strcmp(upper(extension), '.MAT')     %% MAT-file
    save(fname, 'chgtab', 'warnings');
else                                %% M-file
    %% open file
    [fd, msg] = fopen(fname, 'wt');     %% print it to an M-file
    if fd == -1
        error(['savechgtab: ', msg]);
    end

    %% function header, etc.
    fprintf(fd, 'function chgtab = %s\n', fcn_name);
    fprintf(fd, '%%%s  Returns a change table suitable for use with APPLY_CHANGES\n', upper(fcn_name));

    if ~isempty(warnings)
        fprintf(fd, '%%\n');
        fprintf(fd, '%% Warnings:\n');
        for k = 1:length(warnings)
            fprintf(fd, '%%     %s\n', warnings{k});
        end
    end

    fprintf(fd, '\ndefine_constants;\n');

    fprintf(fd, '\n%%%% Change Table\n');
    fprintf(fd, '%%\tlabel\tprob\ttable\trow\tcol\tchgtype\tnewval\n');
    fprintf(fd, 'chgtab = [\n');
    for c = 1:size(chgtab, 1)
        fprintf(fd, '\t%d\t%g\t', ...       %% CT_LABEL, CT_PROB
            chgtab(c, CT_LABEL), chgtab(c, CT_PROB)');
        switch chgtab(c, CT_TABLE)          %% CT_TABLE
            case CT_TBUS
                fprintf(fd, '%s\t', 'CT_TBUS');
                col = bus_cols{chgtab(c, CT_COL)};
            case CT_TGEN
                fprintf(fd, '%s\t', 'CT_TGEN');
                col = gen_cols{chgtab(c, CT_COL)};
            case CT_TGENCOST
                fprintf(fd, '%s\t', 'CT_TGENCOST');
                if chgtab(c, CT_COL)+3 > 8
                    col = sprintf('%s+%d', gc_cols{5+3}, chgtab(c, CT_COL)-5);
                else
                    col = gc_cols{chgtab(c, CT_COL)+3};
                end
            case CT_TBRCH
                fprintf(fd, '%s\t', 'CT_TBRCH');
                col = br_cols{chgtab(c, CT_COL)};
            case CT_TLOAD
                fprintf(fd, '%s\t', 'CT_TLOAD');
                col = load_cols{abs(chgtab(c, CT_COL))};
                if chgtab(c, CT_COL) < 0
                    col = ['-' col];
                end
            case CT_TAREABUS
                fprintf(fd, '%s\t', 'CT_TAREABUS');
                col = bus_cols{chgtab(c, CT_COL)};
            case CT_TAREAGEN
                fprintf(fd, '%s\t', 'CT_TAREAGEN');
                col = gen_cols{chgtab(c, CT_COL)};
            case CT_TAREAGENCOST
                fprintf(fd, '%s\t', 'CT_TAREAGENCOST');
                if chgtab(c, CT_COL)+3 > 8
                    col = sprintf('%s+%d', gc_cols{5+3}, chgtab(c, CT_COL)-5);
                else
                    col = gc_cols{chgtab(c, CT_COL)+3};
                end
            case CT_TAREABRCH
                fprintf(fd, '%s\t', 'CT_TAREABRCH');
                col = br_cols{chgtab(c, CT_COL)};
            case CT_TAREALOAD
                fprintf(fd, '%s\t', 'CT_TAREALOAD');
                col = load_cols{abs(chgtab(c, CT_COL))};
                if chgtab(c, CT_COL) < 0
                    col = ['-' col];
                end
        end
        fprintf(fd, '%g\t%s\t%s\t%g;\n', ...%% CT_ROW, %% CT_COL, CT_CHGTYPE, CT_NEWVAL
            chgtab(c, CT_ROW), col, chgtypes{chgtab(c, CT_CHGTYPE)}, chgtab(c, CT_NEWVAL));
    end
    fprintf(fd, '];\n');

    %% close file
    if fd ~= 1
        fclose(fd);
    end
end

if nargout > 0
    fname_out = fname;
end


% function tutorial_phantom_elekta_lcmv(tutorial_dir)
% TUTORIAL_PHANTOM_ELEKTA_LCMV: Script that runs the tests for the Elekta phantom (Mosher's LCMV validation).
%
% CORRESPONDING ONLINE TUTORIAL:
%     https://neuroimage.usc.edu/brainstorm/Tutorials/PhantomElekta
%
% INPUTS:
%     tutorial_dir: Directory where the sample_phantom.zip file has been unzipped

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

%% ========= Parameters ===========
% The important criteria for CAPON is the data included in
% the data covariance calculation. We will test various sets of data for
% use in this calculation

DipNdx = [1:4:32]; % targeted dipoles for testing
% for smaller set used for data covariance calculations
RefDip = [5 13 17 25]; % widely separated and shallow in each quad
% RefDip = [4 12 20 28]; % widely separated and deep in each quad

DipNdx = sort(DipNdx); % other brainstorm routines end up sorting the index, so ensure

% pick one:
%SUBARRAY = 'MEG'; % all sensors
SUBARRAY = 'MEG GRAD';
%SUBARRAY = 'MEG MAG';

% Set the noise and data covariance intervals
Baseline = [-0.1 -0.01];
DataWindow = [0 .150];
sampling_rate = 100; % phantom data is collected at 1000 fs, can resample here
% epochs will be collected from beginning of baseline to end of data window

%% ===== FILES TO IMPORT =====

if ~exist('tutorial_dir','var'),
    tutorial_dir = '/Users/mosher'; % default
end

% Does the sample folder exist
if ~exist(sprintf('%s',fullfile(tutorial_dir,'sample_phantom_elekta')),'dir'),
    error(sprintf('Missing ''sample_phantom_elekta'' folder in the tutorial directory ''%s''',tutorial_dir));
end
% Build the path of the files to import
FifFile{1} = fullfile(tutorial_dir, 'sample_phantom_elekta', 'kojak_all_2000nAm_pp_no_chpi_no_ms_raw.fif');
FifFile{2} = fullfile(tutorial_dir, 'sample_phantom_elekta', 'kojak_all_200nAm_pp_no_chpi_no_ms_raw.fif');
FifFile{3} = fullfile(tutorial_dir, 'sample_phantom_elekta', 'kojak_all_20nAm_pp_no_chpi_no_ms_raw.fif');
% Select which file is processed with this script: 1=2000nAm, 2=200nAm, 3=20nAm
iFile = 2;
% Check if the folder contains the required files
if ~file_exist(FifFile{iFile})
    error(['The folder ' tutorial_dir ' does not contain the data from the file sample_phantom_elekta.zip.']);
end

%%  ===== CREATE PROTOCOL =====
% The protocol name has to be a valid folder name (no spaces, no weird characters...)
ProtocolName = sprintf('TutorialPhantomElekta_LCMV_%.0f',iFile);

% Subject name
SubjectName = 'Kojak';

% Start brainstorm without the GUI
if ~brainstorm('status')
    brainstorm nogui
end
% Delete existing protocol

iProtocol = bst_get('Protocol', ProtocolName);
% If protocol exists
YorN = 'n'; % default to delete an existing protocol

if false, % only if we care to delete
    if ~isempty(iProtocol)
        % Set as current protocol
        gui_brainstorm('SetCurrentProtocol', iProtocol)

        YorN = input(sprintf('Protocol %s already exists, delete and rebuild (y/n): ',ProtocolName),'s');

    end
end

if isempty(iProtocol) || strncmp(YorN,'y',1),
    % build protocol

    if strncmp(YorN,'y',1), % first delete it
        gui_brainstorm('DeleteProtocol', ProtocolName);
    end

    % Create new protocol
    gui_brainstorm('CreateProtocol', ProtocolName, 0, 0);

    % ===== ANATOMY =====

    % Generate the phantom anatomy
    DipTrueFile = generate_phantom_elekta(SubjectName);

else
    % or whatever the true name is from previous run
    DipTrueFile = fullfile(SubjectName,'TrueDipoles','dipoles_160816_1755.mat');

end

% Start a new report
% bst_report('Start');

%% ===== LINK CONTINUOUS FILES =====
% Process: Create link to raw files
sFilesKojak = bst_process('CallProcess', 'process_import_data_raw', [], [], ...
    'subjectname',  SubjectName, ...
    'datafile',     {FifFile{iFile}, 'FIF'}, ...
    'channelalign', 0);

%% ===== READ EVENTS =====
% Process: Read from channel
bst_process('CallProcess', 'process_evt_read', sFilesKojak, [], ...
    'stimchan',  'STI201', ...
    'trackmode', 1, ...  % Value: detect the changes of channel value
    'zero',      0);
% Process: Delete spurious other events unrelated to dipoles
bst_process('CallProcess', 'process_evt_delete', sFilesKojak, [], ...
    'eventname', '256, 768, 1792, 3840, 4096, 6144, 7168, 7680, 7936');
% Process: Rename events to have a leading zero, for proper sorting
for i = 1:9
    bst_process('CallProcess', 'process_evt_rename', sFilesKojak, [], ...
        'src',  sprintf('%.0f',i), ...
        'dest', sprintf('%02.0f',i));
end
% Delete the first event of the first category (there is always an artifact)
LinkFile = file_fullpath(sFilesKojak(1).FileName);
LinkMat = load(LinkFile, 'F');
if ~isempty(LinkMat.F.events) && ~isempty(LinkMat.F.events(1).times)
    LinkMat.F.events(1).times(1)   = [];
    LinkMat.F.events(1).epochs(1)  = [];
    if ~isempty(LinkMat.F.events(1).channels)
        LinkMat.F.events(1).channels(1)= [];
    end
    if ~isempty(LinkMat.F.events(1).notes)
        LinkMat.F.events(1).notes(1) = [];
    end
end
bst_save(LinkFile, LinkMat, 'v6', 1);

%%  ===== IMPORT EVENTS =====
% Process: Import MEG/EEG: Events
%          DC offset correction: [-100ms,-10ms]
%          Resample: 100Hz
sFilesEpochs = bst_process('CallProcess', 'process_import_data_event', sFilesKojak, [], ...
    'subjectname', SubjectName, ...
    'condition',   '', ...
    'eventname',   ['01' sprintf(',%02.0f',2:32)], ...
    'timewindow',  [], ...
    'epochtime',   [Baseline(1), DataWindow(2)], ...
    'createcond',  0, ...
    'ignoreshort', 1, ...
    'usectfcomp',  0, ...
    'usessp',      0, ...
    'freq',        sampling_rate, ...
    'baseline',    Baseline);

%%  Process: Average: By trial group (folder average)
sAvgKojak = bst_process('CallProcess', 'process_average', sFilesEpochs, [], ...
    'avgtype',    5, ...  % By trial group (folder average)
    'avg_func',   1, ...  % Arithmetic average:  mean(x)
    'weighted',   0, ...
    'keepevents', 0);

%% Process: Compute Head Model
bst_process('CallProcess', 'process_headmodel', sAvgKojak, [], ...
    'Comment',     '', ...
    'sourcespace', 2, ...  % MRI volume
    'meg',         3, ...  % Overlapping spheres
    'volumegrid',  struct(...
    'Method',        'isotropic', ...
    'nLayers',       17, ...
    'Reduction',     3, ...
    'nVerticesInit', 4000, ...
    'Resolution',    0.0025, ...
    'FileName',      []));

%% ===== SOURCE ESTIMATION =====

%% First, we use the prestim, to establish a baseline with GLS method

fprintf('\n GLS METHOD Calculating full noise prestim from all %.0f epochs.\n\n',length(sFilesEpochs))

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         1, ...  % Noise covariance     (covariance over baseline time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         2, ...  % Data covariance      (covariance over data time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% and now run the source estimation and display the results

tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'gls',SUBARRAY,DipTrueFile)

%% Now the proper LCMV with same noise and data covariances
% and now run the source estimation and display the results

fprintf('\nResults using all data as covariance\n')

tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'lcmv',SUBARRAY,DipTrueFile)

%% Testing Brainstorm's LCMV vs pseudoLCMV(GLS) routine

fprintf('\n GLS USED TO GENERATE LCMV Calculating the Noise as the full data covariance from all %.0f epochs.\n\n',length(sFilesEpochs))

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       DataWindow, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         1, ...  % Noise covariance     (covariance over baseline time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       DataWindow, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         2, ...  % Data covariance      (covariance over data time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% and now run the source estimation and display the results

fprintf('\nResults using  data as covariances and running as GLS:\n')

tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'gls',SUBARRAY,DipTrueFile)

%% Testing Brainstorm's LCMV vs pseudoLCMV(GLS) routine

fprintf('\n LCMV USED FOR GLS Calculating the Data Covariance as the  noise covariance from all %.0f epochs.\n\n',length(sFilesEpochs))

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', Baseline, ...
    'sensortypes',    'MEG', ...
    'target',         1, ...  % Noise covariance     (covariance over baseline time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', Baseline, ...
    'sensortypes',    'MEG', ...
    'target',         2, ...  % Data covariance      (covariance over data time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% and now run the source estimation and display the results

fprintf('\nResults using prestim as covariance and running as LCMV:\n')

tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'lcmv',SUBARRAY,DipTrueFile)

%% DISABLED: Now estimate the noise covariance from just the selected reference dipoles, to establish again a baseline

if false, % if desired, not really different from full baseline
    % want just the epochs of the Reference Dipole
    EpochNdx = []; % find all of the corresponding epochs
    for i = 1:length(RefDip),
        EpochNdx = [EpochNdx find(strncmp(sprintf('%02.0f',RefDip(i)),{sFilesEpochs.Comment},2))];
    end

    % Set the baseline to the prestim

    fprintf('\nCalculating the prestim baseline from just dipole %.0f for %.0f epochs\n\n',RefDip,length(EpochNdx))

 % Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         1, ...  % Noise covariance     (covariance over baseline time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs, [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         2, ...  % Data covariance      (covariance over data time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

    fprintf('\nBaseline results a few dipole prestims as noise covariance\n')

    tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'gls',SUBARRAY,DipTrueFile)

end

%% Now estimate the data covariance from just the reference dipoles

EpochNdx = []; % find all of the corresponding epochs
for i = 1:length(RefDip),
    EpochNdx = [EpochNdx find(strncmp(sprintf('%02.0f',RefDip(i)),{sFilesEpochs.Comment},2))];
end

fprintf('\nReference Dipole set: %.0f',RefDip(1)), fprintf(', %.0f',RefDip(2:end)), fprintf('\n')
fprintf('Calculating the data covariance from %.0f epochs\n\n',length(EpochNdx))

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs(EpochNdx), [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         1, ...  % Noise covariance     (covariance over baseline time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

% Process: Compute covariance (noise or data)
bst_process('CallProcess', 'process_noisecov', sFilesEpochs(EpochNdx), [], ...
    'baseline',       Baseline, ...
    'datatimewindow', DataWindow, ...
    'sensortypes',    'MEG', ...
    'target',         2, ...  % Data covariance      (covariance over data time window)
    'dcoffset',       1, ...  % Block by block, to avoid effects of slow shifts in data
    'identity',       0, ...
    'copycond',       0, ...
    'copysubj',       0, ...
    'replacefile',    1);  % Replace

fprintf('\nLCMV results a few dipoles for their own data covariance\n\n')

tutorial_phantom_elekta_lcmv_src(sAvgKojak,DipNdx,'lcmv',SUBARRAY,DipTrueFile)

%% Now sum the reference set for a new data set, to show beamformer operation

% use sAvgKojak from above

% which files have the reference dipoles
FileNdx = [];
for ii = 1:length(RefDip),
    STR = sprintf('data_%02.0f',RefDip(ii)); % search string
    for i = 1:length(sAvgKojak),
        if ~isempty(strfind(sAvgKojak(i).FileName,STR)),
            FileNdx = [FileNdx i];
        end
    end
end

sFilesRef = sAvgKojak(FileNdx);

% % Input files
% sFiles = {...
%     'Kojak/kojak_all_200nAm_pp_no_chpi_no_ms_raw/data_05_average_160817_1419.mat', ...
%     'Kojak/kojak_all_200nAm_pp_no_chpi_no_ms_raw/data_13_average_160817_1419.mat', ...
%     'Kojak/kojak_all_200nAm_pp_no_chpi_no_ms_raw/data_17_average_160817_1419.mat', ...
%     'Kojak/kojak_all_200nAm_pp_no_chpi_no_ms_raw/data_25_average_160817_1419.mat'};

% Process: Scale each one by the total number in preparation of "mean"
sFilesRef = bst_process('CallProcess', 'process_scale', sFilesRef, [], ...
    'factor',      length(RefDip), ...
    'sensortypes', '', ...
    'overwrite',   0);

% Process: Average: By folder (subject average). Each signal maintains its
% strength
sFilesRefAvg = bst_process('CallProcess', 'process_average', sFilesRef, [], ...
    'avgtype',    3, ...  % By folder (subject average)
    'avg_func',   1, ...  % Arithmetic average:  mean(x)
    'weighted',   0, ...
    'keepevents', 0);

%%
% Save and display report
%ReportFile = bst_report('Save', []);
%bst_report('Open', ReportFile);


% The COBRAToolbox: testWritePajekNet.m
%
% Purpose:
%     - testwritePajekNet tests the writePajekNet function
%       that transforms a hypergraph into a graph (Pajek format)
%
% Author:
%     - Marouen BEN GUEBILA 09/02/2017

global CBTDIR

% save the current path
currentDir = pwd;

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

model = getDistributedModel('ecoli_core_model.mat');

%test solver packages
solverPkgs = {'tomlab_cplex'};

for k = 1:length(solverPkgs)

    fprintf('   Testing writePajekNet using %s ... ', solverPkgs{k});

    % change the COBRA solver (LP)
    solverOK = changeCobraSolver(solverPkgs{k}, 'LP', 0);

    if solverOK == 1
        %load test data
        fileID = fopen('COBRAmodeltest.net', 'r');
        testData = fscanf(fileID, '%s');
        fclose(fileID);

        %call fucntion
        writePajekNet(model);

        %save produced data
        fileID = fopen('COBRAmodel.net', 'r');
        Data = fscanf(fileID, '%s');
        fclose(fileID);

        %compare with produced data
        assert(isequal(testData, Data));

        %delete data
        delete COBRAmodel.net
    end
end

% change the directory
cd(currentDir)


%  INTERNAL FUNCTION: computes C=A*(BxBx...xB)
%
%


function varargout=polygonwind(varargin)
%
% For calling details please see v_polygonwind.m
%
% This dummy routine is included for backward compatibility only
% and will be removed in a future release of voicebox. Please use
% v_polygonwind.m in future and/or update with v_voicebox_update.m
%
%      Copyright (C) Mike Brookes 2018
%      Version: $Id: polygonwind.m 10863 2018-09-21 15:39:23Z dmb $
%
if nargout
    varargout=cell(1,nargout);
    [varargout{:}]=v_polygonwind(varargin{:});
else
    v_polygonwind(varargin{:});
end


% Upgrades the network object to the most recent format.
% The motivation is the same as the motivation behind vl_simplenn_tidy
% (which is also executed during the call) as it enables NetVLAD code
% to evolve while not breaking backward compatibility

function net= relja_simplenn_tidy(net)

    % --- NetVLAD save values which will be deleted by MatConvNet tidy

    toSave= struct();

    % from v100-v101
    fieldNames= {'netID', 'sessionID', 'epoch'};

    for fieldName_= fieldNames
        fieldName= fieldName_{1};
        if isfield(net, fieldName)
            toSave.(fieldName)= net.(fieldName);
            net= rmfield(net, fieldName);
        end
    end

    % --- MatConvNet tidy

    net= vl_simplenn_tidy(net);

    % --- NetVLAD tidy

    for fieldName_= fieldNames
        fieldName= fieldName_{1};
        if isfield(toSave, fieldName)
            net.meta.(fieldName)= toSave.(fieldName);
            toSave= rmfield(toSave, fieldName);
        end
    end
    assert(isempty(fieldnames(toSave)));

end


% Copyright 2019 Jonas Koenemann, Moritz Diehl, University of Freiburg
% Redistribution is permitted under the 3-Clause BSD License terms. Please
% ensure the above copyright notice is visible in any derived work.
%

function [nFails] = core(testExamples,saveLog,suffix)
  % runTests()
  % runTests(testExamples)
  % runTests(1,1,'computername')
  ocl.utils.checkStartup()

  if nargin < 1
    testExamples = false;
  end
  if nargin <=1
    saveLog = false;
    suffix = '';
  else
    suffix = ['_',suffix];
  end

  testDir = getenv('OPENOCL_TEST');
  oclDir = getenv('OPENOCL_PATH');

  % go to main dir and get current git hash
  cd(oclDir);
  [status,version] = system('git rev-parse HEAD');
  if status~=0
    ocl.utils.info('Could not get git hash, log filename will not include the hash. This is not a problem.')
    version='nogithash';
  end

  if isempty(testDir)
    ocl.utils.error('Test directory not set. Run StartupOCL again.')
  end

  ocl.utils.setTestRun(true)

  tests{1}.name = 'Variable';         tests{end}.file = 'ocl.tests.variable';
  tests{end+1}.name = 'TreeVariable'; tests{end}.file = 'ocl.tests.treeVariable';
  tests{end+1}.name = 'VarStructure'; tests{end}.file = 'ocl.tests.structure';
  tests{end+1}.name = 'ocl.Model';    tests{end}.file = 'ocl.tests.model';
  tests{end+1}.name = 'ocl.Stage';       tests{end}.file = 'ocl.tests.stage';
  tests{end+1}.name = 'ocl.Integrator';   tests{end}.file = 'ocl.tests.integrator';

  if testExamples
    tests{end+1}.name = 'Examples';      tests{end}.file = 'ocl.tests.examples';
    tests{end+1}.name = 'Features';      tests{end}.file = 'ocl.tests.features';
  end

  NTests = length(tests);

  % turn off figures for testing examples
  if testExamples
    close all
    set(0,'DefaultFigureVisible','off');
  end

  %% run all tests
  testResults = cell(1,NTests);
  for k=1:NTests
    test = tests{k};
    testResults{k} = runTest(test.name,str2func(test.file));
  end

  nFails = 0;
  for k=1:NTests
    if testResults{k}.passed == false
      nFails = nFails + 1;
    end
  end

  %% save results
  fileName = [datestr(now,'yyyy-mm-dd_HHMMSS'), '_', version(1:7), suffix,  '.txt'];
  filePath = fullfile(testDir,fileName);
  resultsFile = fopen(filePath,'w');
  fprintf(resultsFile,'Test on %s\nVersion: %s\n\n',datestr(now),version);

  for k=1:NTests
    printResults(testResults{k});
  end

  if nFails >0
    outputString = sprintf('%i Tests failed.\n\n',nFails);
    fprintf(resultsFile,outputString);fprintf(2,outputString);
  else
    outputString = 'All tests passed!\n\n';
    fprintf(resultsFile,outputString);fprintf(outputString);
  end

  fclose(resultsFile);

  if saveLog
    copyfile(filePath,'Log');
  end

  if testExamples
    set(0,'DefaultFigureVisible','on');
  end

  ocl.utils.setTestRun(false);

  function testResult = runTest(testName,scriptHandle)
    testResult = struct;
    testResult.name = testName;
    testResult.passed = true;
    testResult.runtime = 0;
    testResult.exception = '';
    try
      testTic = tic;
      testResult.outputs = cell(nargout(scriptHandle),1);
      [testResult.outputs{:}] = scriptHandle();
      testResult.runtime = toc(testTic);
    catch exception
      testResult.passed = false;
      testResult.exception = exception;
    end
  end

  function printResults(testResult)
    if testResult.passed
    	outputString = sprintf('%s Tests passed\n',testResult.name);
      fprintf(resultsFile,outputString);fprintf(outputString);
      outputString = sprintf('It took %.4f seconds.\n\n',testResult.runtime);
      fprintf(resultsFile,outputString);fprintf(outputString);

      for i=1:length(testResult.outputs)
        out = testResult.outputs{i};
        names = fieldnames(out);
        sum = 0;
        for j=1:length(names)
          val = out.(names{j});
          sum = sum+val;
          outputString = sprintf('Test %i, %s: %.4f seconds.\n', i, names{j}, val);
          fprintf(resultsFile,outputString);fprintf(outputString);
        end
        outputString = sprintf('Test %i, sum: %.4f seconds.\n\n', i, sum);
        fprintf(resultsFile,outputString);fprintf(outputString);
      end

    else
      outputString = sprintf('%s Tests failed\n',testResult.name);
      fprintf(resultsFile,outputString);fprintf(outputString);

      if ocl.utils.isOctave()
        disp(getReportOctave(testResult.exception))  %% OCTAVE
      else
        disp(getReport(testResult.exception))  %% MATLAB
      end
    end
  end
end


function title = p01_title ( )

%*****************************************************************************80
%
%% P01_TITLE returns a title for problem 1.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    15 January 2012
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, string TITLE, a title for the problem.
%
  title = 'The constant function';

  return
end


classdef mme_gen3p_opf < mp.mme_gen3p

%   MATPOWER
%   Copyright (c) 2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MATPOWER.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://matpower.org for more info.

%     properties
%     end

    methods
        function x0 = interior_x0(obj, mm, nm, dm, x0)
        end
    end     %% methods
end         %% classdef


function prevstate = mcolonops(state)
% overload MATLAB colon operator with multi-colon capability
%
% mcolonops(STATE) where STATE is
%   'colon' 'off' 'matlab' : Set to Matlab original COLON mode.
% 	'mcolon' 'on' 'compatible': mcolon "compatible" mode, similar results
%       to Matlab colon returned when invoking with scalar inputs.
% 	'fullmcolon': full mcolon mode, arrays will be generated by MCOLON
%        engine in all configurations.
%
% INQUIRING: prevstate = mcolonops(...) return the current state before
%                                       the new state is set.
%
% See also: colon, mcolon, mcolsettol
%
% Author: Bruno Luong <brunoluong@yahoo.com>
% Last update: 31/December/2010

persistent OVERLOADCOLON_STATE
persistent OVERLOAD_PATH

if isempty(OVERLOADCOLON_STATE)
    OVERLOADCOLON_STATE = 'colon';
end
if nargout>=1 || nargin<1
    prevstate = OVERLOADCOLON_STATE; % Return the previous state
end

if nargin>=1
    if ~isempty(OVERLOAD_PATH)
        try
            rmpath(OVERLOAD_PATH);
        catch %#ok
            warning('mcolon:rmpath', ...
                    'mcolonops can''t remove path %s', OVERLOAD_PATH);
        end
        OVERLOADCOLON_STATE = 'colon';
        OVERLOAD_PATH = '';
    end

    bsxopsroot = fileparts(mfilename('fullpath'));
    switch lower(state)
        case {'c' 'colon' 'off' 'matlab'}
        case {'m' 'mc' 'mcolon' 'on' 'compatible'}
            OVERLOADCOLON_STATE = 'mcolon';
            OVERLOAD_PATH = [bsxopsroot '/overload/compatible'];
            addpath(OVERLOAD_PATH);
        case {'f' 'fullmcolon'}
            OVERLOADCOLON_STATE = 'fullmcolon';
            OVERLOAD_PATH = [bsxopsroot '/overload/fullmcolon'];
            addpath(OVERLOAD_PATH);
        otherwise
            error('mcolonops: unknown state <%s>', state);
    end
end

% Prevent the persistent variable to be cleared
mlock;

end


function plot(c,varargin)

% PLOT(C) plots waveforms stored in a correlation object. Traces are
% aligned by their trigger times. For optimum correlation use ADJUSTTRIG
% first. Trace amplitudes are normalized before plotting.
%
% PLOT(C,'wiggle') plots a wiggle trace (default for < 100 traces)
%
% PLOT(C,'wiggle',SCALE) plots wiggle traces with relative amplitudes
% of SCALE (default SCALE is 1.0 - no overlap for adjacent traces)
%
% PLOT(C,'wiggle',SCALE,PERM) plots the wiggle traces as specified and
% ordered by the PERM vector. PERM may be a subset of the full list of
% trace, a reordering of the traces, or both. The default behavior is to
% plot traces as they appear in the TRIG field. One common use is to use
% the PERM vector to plot traces in the same order they appear in a
% dendrogram plot. For example:
%       [H,tmp,perm] = dendrogram(c, ...);
%       plot(c,'wig',1,perm);
%
% PLOT(C,'raw',...) same as 'wig' option except that traces are not
% normalized to an equal amplitude before plotting. They are scaled to the
% mean of the maximum trace amplitude. Scaling can be further refined
% with the SCALE factor and/or by using the NORM function prior to plotting.
%
% PLOT(C,'shaded',...) plots shaded waveforms. (default for >= 100 traces)
% The 'wiggle' option is not conducive to displays of more than about 100
% traces. The 'shaded' option is recommended for large datasets.  Plot
% colors can be modified with the COLORMAP command. Same options are
% available as for the wiggle plots.
%
% PLOT(C,'overlay',...) overlays the aligned traces on one another. The
% stack of the traces is plotted in bold on top. If traces have not been
% cropped prior to plotting, beware of odd effects toward the ends of the
% stacked traces. Trace amplitudes are not normalized prior to plotting
% (like 'raw'). Use NORM if normalization is necessary prior to plotting.
%
% PLOT(C,'interfer') plot shaded images of the correlation values and/or
% lag times from behind the traces. See HELP INTERFEROGRAM for more
% information on where this data comes from and how it is stored (a bit ad
% hoc). Note that no trace normalization is applied to interferograms. In
% many cases the user will choose to run the NORM command before plotting.
% By default PLOT(C,'interfer') is the same as PLOT(C,'interfer',1,'LAG').
%
% PLOT(C,'interfer',SCALE,'CORR') plots a shaded image of the correlation
% values from the interferogram routine behind the traces. Lag times are
% ignored in this style of plot.
%
% PLOT(C,'interfer',SCALE,'LAG',RANGE) plots traces on a shaded image that
% is a function of both the lag time and the correlation value. The color
% scale ranges from -RANGE to +RANGE seconds. If RANGE is not included, then
% it is set to 0.03 seconds. As the correlation value drops, the colors are
% increasingly faded. Regions of the waveforms that correlate at less than
% 0.6 are considered unreliable and are not colored at all. For example,
% bright red indicates a waveform segment that correlates very well but is
% delayed relative to the reference trace. Faded blue indicates moderate
% correlation and advanced arrival. Yellow is no time shift. White
% signifies poor correlation (in which case the lag time is meaningless).
%
% PLOT(C,'sample',...) same as wiggle plot except that individual sample
% points are plotted. Really this is only useful for debugging.
%
% PLOT(C,'corr') plots an image of the correlation matrix. Requires
% CORR field to be filed.
%
% PLOT(C,'lag') plots an image of the lag matrix. Requires LAG field to be
% filled.
%
% PLOT(C,'stat') plots the delay time statistics for each trace. Requires STAT
% field to be filled. If STAT field is not filled, PLOT(C,'STAT') will call
% GETSTAT. The resulting values will be used for plotting but will *not* be
% saved into C.
%
% PLOT(D,'den') plots a dendrogram image. Requires the LINK field to be
% filled (see correlation/linkage).
%
% PLOT(C,'event') This routine has been deprecated and will be removed in a
% future release. Use the occurence plot routine instead. The event routine
% plots the time evolution of each event cluster together with a stack of
% all of the traces in that cluster. No normalization is applied to the
% traces before stacking. Requires the CLUST property be filled.
%
% PLOT(C,'event',SCALE)
% PLOT(C,'event',SCALE,CLUSTERS)
% Same as above except relative trace amplitudes are scaled by SCALE.
% Default is 1. If specified, CLUSTERS states how many clusters to include
% in the analysis. That is, if CLUSTERS is 5, then the 5 largest clusters
% are included in the plots. The default value of CLUSTERS is 4.
% Example - plot the 3 largest clusters at half the default amplitude.
%       ...
%       c = linkage(c,'average');
%       c = cluster(c,'CUTOFF',.5,'Criterion','distance');
%       plot(c,'event',.5,3);
%
% PLOT(C,'occurrence',SCALE,CLUSTERS) similar to EVENT plot above. Plots a time
% historgram for each event cluster together with a stack of all of the
% traces in that cluster. CLUSTERS specifies the number of each cluster to
% be included. Due to space constraints, no more than 10 clusters can be
% plotted on a single figure. Requires the CLUST property be filled. SCALE
% term is required for consistency but has little impact on the plots.

% Author: Michael West, Geophysical Institute, Univ. of Alaska Fairbanks
% $Date$
% $Revision$

% SET VAR5 (USED ARBITRARILY BY SOME SUBFUNCTIONS)
if length(varargin)>=4
    var5 = varargin{4};
else
    var5 = [];
end;

% SET ORDER AND NUMBER OF TRACES
if length(varargin)>=3
    ord = reshape(varargin{3},1,length(varargin{3}));
else
    ord = 1:length(c.trig);
end;

% SET TRACE SCALE
if length(varargin)>=2
    scale = varargin{2};
else
    scale = 1;
end;

% PLOT SHADED TRACES, NOT WIGGLES
if length(varargin)>=1
    %disp(varargin{1});
    plottype = varargin{1};
else
    if length(ord)>=100
        plottype = 'sha';
    else
        plottype = 'wig';
    end

end;

% MAKE PLOT
if strncmpi(plottype,'SHA',3)
    shadedplot(c,scale,ord);
elseif strncmpi(plottype,'WIG',3)
    wiggleplot(c,scale,ord,1);
elseif strncmpi(plottype,'RAW',3)
    wiggleplot(c,scale,ord,0);
elseif strncmpi(plottype,'OVE',3)
    overlayplot(c,scale,ord);
elseif strncmpi(plottype,'SAM',3)
    sampleplot(c,scale,ord);
elseif strncmpi(plottype,'COR',3)
    corrplot(c);
elseif strncmpi(plottype,'LAG',3)
    lagplot(c);
elseif strncmpi(plottype,'STA',3)
    statplot(c);
elseif strncmpi(plottype,'DEN',3)
    dendrogramplot(c);
elseif strncmpi(plottype,'EVE',3)       % ord field has been co-opted
    admin.deprecated('event plot','occurrence plot')
    if length(ord) > 1
        ord = 4;
    end
    eventplot(c,scale,ord);
elseif strncmpi(plottype,'OCC',3)       % ord field has been co-opted
    occurrenceplot(c,scale,ord);
elseif strncmpi(plottype,'INT',3)   % ord is used as flag for "corr" vs. "lag"
    ord = ord(1);
    if isnumeric(ord)
       ord = 'c';
    end
    if isempty(var5)                % var5 only used for lag plot
        var5 = 0.03;
    end
    wiggleinterferogram(c,scale,ord,0,var5);
else
    disp('Plot type not recognized');
end;