function varargout = gtrack(newVarName,titleFmt)
% default format for printing coordinates in title
if nargin<2,	titleFmt = '%3.5f';		end

% === mouse states ===
global mouseButton; % 'down' or 'up'

% track mouseMovement
global mouseMotion; % 'moving' or 'stationary'
global mouseMoveDirection; % 'N', 'S', 'E', 'W'; 'NW', 'NE', 'SW', 'SE', 'stationary'
global whichMouseButton; % 'left' or 'right'
global currentLocation; % x, y coordinates
global previousLocation; % x, y coordinates

previousLocation = 'unassigned';

% get current figure event functions
currFcn = get(gcf, 'windowbuttonmotionfcn');
currFcn2 = get(gcf, 'windowbuttondownfcn');
currTitle = get(get(gca, 'Title'), 'String');

% add data to figure handles
handles = guidata(gca);
if (isfield(handles,'ID') & handles.ID==1)
	disp('gtrack is already active.');
	return;
else
	handles.ID = 1;
end
handles.currFcn = currFcn;
handles.currFcn2 = currFcn2;
handles.currTitle = currTitle;
handles.theState = uisuspend(gcf);
guidata(gca, handles);

% set event functions
set(gcf,'Pointer','crosshair');
set(gcf, 'windowbuttonmotionfcn', @gtrack_OnMouseMove);
set(gcf, 'windowbuttondownfcn', @gtrack_OnMouseDown);
set(gcf, 'windowbuttonupfcn', @gtrack_OnMouseUp);

% declare variables
xInd = 0;
yInd = 0;
clickData = [];

% set output mode
if nargout,
	uiMode = 'uiwait';		% use UIWAIT and return to clickData
	uiwait;
elseif nargin && isvarname(newVarName)	% dont'e use UIWAIT and assign in caller
	uiMode = 'nowait';				% workspace to variable newVarName
else
	uiMode = 'noreturn';	% dont't use UIWAIT and don't return results (print only)
end

%% --- nested functions ---------------------------------------------------

%% mouse move callback
function gtrack_OnMouseMove(src,evnt)

% get mouse position
pt = get(gca, 'CurrentPoint');
xInd = pt(1, 1);
yInd = pt(1, 2);
currentLocation = [xInd yInd];

if (~strcmp(previousLocation, 'unassigned'))
    changesInVectoralDistance = currentLocation - previousLocation;

    xDelta = changesInVectoralDistance(1, 1);
    yDelta = changesInVectoralDistance(1, 2);

    % degreesInMovement = NaN, if there is no movement
    degreesInMovement = atan(yDelta/xDelta)*(180/pi);

    if (xDelta == 0) && (yDelta == 0)
        mouseMoveDirection = 'stationary';
        mouseMotion = 'stationary';
    elseif (xDelta == 0) && (yDelta > 0)
        mouseMoveDirection = 'N';
        mouseMotion = 'moving';
    elseif (xDelta == 0) && (yDelta < 0)
        mouseMoveDirection = 'S';
        mouseMotion = 'moving';
    elseif (xDelta > 0) && (yDelta == 0)
        mouseMoveDirection = 'E';
        mouseMotion = 'moving';
    elseif (xDelta < 0) && (yDelta == 0)
        mouseMoveDirection = 'W';
        mouseMotion = 'moving';
        degreesInMovement = degreesInMovement + 180;
    elseif (xDelta > 0) && (yDelta > 0)
        mouseMoveDirection = 'NE';
        mouseMotion = 'moving';
    elseif (xDelta < 0) && (yDelta > 0)
        mouseMoveDirection = 'NW';
        mouseMotion = 'moving';
        degreesInMovement = degreesInMovement + 180;
    elseif (xDelta < 0) && (yDelta < 0)
        mouseMoveDirection = 'SW';
        mouseMotion = 'moving';
        degreesInMovement = degreesInMovement + 180;
    elseif (xDelta > 0) && (yDelta < 0)
        mouseMoveDirection = 'SE';
        mouseMotion = 'moving';
    end

    distanceMoved = sqrt((xDelta^2)+(yDelta^2));
    polarCoordinates = [distanceMoved degreesInMovement];

    fprintf('Mouse moved in the direction of %s at %s degrees. Distance: %s\n', ...
        mouseMoveDirection, num2str(degreesInMovement), num2str(distanceMoved));
end

% check if its within axes limits
xLim = get(gca, 'XLim');
yLim = get(gca, 'YLim');
if xInd < xLim(1) | xInd > xLim(2)
	title('Out of X limit');
	return;
end
if yInd < yLim(1) | yInd > yLim(2)
	title('Out of Y limit');
	return;
end

% update figure title
try
	title(['X = ' num2str(xInd,titleFmt) ', Y = ' num2str(yInd,titleFmt)]);
% possibility of wrong format strings...
catch
	gtrack_Off()
	error('TRACK: Error printing coordinates. Check that you used a valid format string.')
end

% update the location
previousLocation = currentLocation;

end

%% mouse click callback
function gtrack_OnMouseDown(src,evnt)
whichMouseButton = get(gcf,'SelectionType');
if strcmp(whichMouseButton,'alt')
	% gtrack_Off % if left button, terminate
    %return
    whichMouseButton = 'right';
end

if strcmp(whichMouseButton,'normal')
	% gtrack_Off
	%return
    whichMouseButton = 'left';
end

% else add click to clickData
clickData(end+1).x = xInd;
clickData(end).y = yInd;
fprintf('%s Mouse Button Down at X = %f   Y = %f\n',whichMouseButton, xInd, yInd); % update mouse position

if (strcmp(mouseMotion, 'moving'))
    fprintf('Mouse is dragged.\n\n');
end

end

function gtrack_OnMouseUp(src,evnt)
whichMouseButton = get(gcf,'SelectionType');
if strcmp(whichMouseButton,'alt')
	% gtrack_Off % if left button, terminate
	%return
    whichMouseButton = 'right';
end

if strcmp(whichMouseButton,'normal')
	% gtrack_Off
	%return
    whichMouseButton = 'left';
end

% else add click to clickData
clickData(end+1).x = xInd;
clickData(end).y = yInd;
fprintf('%s Mouse Button Up at X = %f   Y = %f\n',whichMouseButton, xInd, yInd); % update mouse position

end

%% terminate callback
function gtrack_Off(src,evnt)

% restore default figure properties
handles = guidata(gca);
set(gcf, 'windowbuttonmotionfcn', handles.currFcn);
set(gcf, 'windowbuttondownfcn', handles.currFcn2);
set(gcf,'Pointer','arrow');
title(handles.currTitle);
uirestore(handles.theState);
handles.ID=0;
guidata(gca,handles);

% if there are outputs to assign do so
switch uiMode
	case 'uiwait'	% data return as output argument (clickData)
		varargout{1} = clickData;
		uiresume,
	case 'nowait'	% data assigned in base workspace as new variable
		assignin('base',newVarName,clickData);
		fprintf('Variable %s assigned with click data.\n',newVarName);
	case 'noreturn'
					% nothing to return
end

end

%% --- end nested functions -----------------------------------------------

end % end everything

% improved version of GTRACK
%
% GTRACK Track mouse position and show coordinates in figure title.
%
% 	GTRACK Activates GTRACK. Once it is active the mouse position is
% 	constantly tracked and printed on the figure title. A left-click will
% 	print the coordinates in the command line and store them. Clicking the
% 	mouse right button deactivates GTRACK.
%
% USAGE
% 	gtrack() tracks the mouse and prints coordinates in the command line.
%
% 	clickData = gtrack() will return the click positions in clickData using
% 	UIWAIT. Matlab will be in wait mode until the user finishes clicking.
%
% 	gtrack('newVar') tracks the mouse and creates a new variable in the
% 	base workspace called 'newVar' with the click coordinates. This mode
% 	does not use UIWAIT.
%
%	gtrack([],titleFormat) uses titleFormat as the format string for
%	printing the mouse coordinates in the title.
%


function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,tolFun,tolX,method,...
    corrections,c1,c2,LS_init,LS,cgSolve,qnUpdate,cgUpdate,initialHessType,...
    HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,...
    DerivativeCheck,Damped,HvFunc,bbType,cycle,...
    HessianIter,outputFcn,useMex,useNegCurv,precFunc] = ...
    minFunc_processInputOptions(o)

% Constants
SD = 0;
CSD = 1;
BB = 2;
CG = 3;
PCG = 4;
LBFGS = 5;
QNEWTON = 6;
NEWTON0 = 7;
NEWTON = 8;
TENSOR = 9;

verbose = 1;
verboseI= 1;
debug = 0;
doPlot = 0;
method = LBFGS;
cgSolve = 0;

o = toUpper(o);

if isfield(o,'DISPLAY')
    switch(upper(o.DISPLAY))
        case 0
            verbose = 0;
            verboseI = 0;
        case 'FINAL'
            verboseI = 0;
        case 'OFF'
            verbose = 0;
            verboseI = 0;
        case 'NONE'
            verbose = 0;
            verboseI = 0;
        case 'FULL'
            debug = 1;
        case 'EXCESSIVE'
            debug = 1;
            doPlot = 1;
    end
end

LS_init = 0;
c2 = 0.9;
LS = 4;
Fref = 1;
Damped = 0;
HessianIter = 1;
if isfield(o,'METHOD')
    m = upper(o.METHOD);
    switch(m)
        case 'TENSOR'
            method = TENSOR;
        case 'NEWTON'
            method = NEWTON;
        case 'MNEWTON'
            method = NEWTON;
            HessianIter = 5;
        case 'PNEWTON0'
            method = NEWTON0;
            cgSolve = 1;
        case 'NEWTON0'
            method = NEWTON0;
        case 'QNEWTON'
            method = QNEWTON;
            Damped = 1;
        case 'LBFGS'
            method = LBFGS;
        case 'BB'
            method = BB;
            LS = 2;
            Fref = 20;
        case 'PCG'
            method = PCG;
            c2 = 0.2;
            LS_init = 2;
        case 'SCG'
            method = CG;
            c2 = 0.2;
            LS_init = 4;
        case 'CG'
            method = CG;
            c2 = 0.2;
            LS_init = 2;
        case 'CSD'
            method = CSD;
            c2 = 0.2;
            Fref = 10;
            LS_init = 2;
        case 'SD'
            method = SD;
            LS_init = 2;
    end
end

maxFunEvals = getOpt(o,'MAXFUNEVALS',1000);
maxIter = getOpt(o,'MAXITER',500);
tolFun = getOpt(o,'TOLFUN',1e-5);
tolX = getOpt(o,'TOLX',1e-9);
corrections = getOpt(o,'CORR',100);
c1 = getOpt(o,'C1',1e-4);
c2 = getOpt(o,'C2',c2);
LS_init = getOpt(o,'LS_INIT',LS_init);
LS = getOpt(o,'LS',LS);
cgSolve = getOpt(o,'CGSOLVE',cgSolve);
qnUpdate = getOpt(o,'QNUPDATE',3);
cgUpdate = getOpt(o,'CGUPDATE',2);
initialHessType = getOpt(o,'INITIALHESSTYPE',1);
HessianModify = getOpt(o,'HESSIANMODIFY',0);
Fref = getOpt(o,'FREF',Fref);
useComplex = getOpt(o,'USECOMPLEX',0);
numDiff = getOpt(o,'NUMDIFF',0);
LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1);
DerivativeCheck = getOpt(o,'DERIVATIVECHECK',0);
Damped = getOpt(o,'DAMPED',Damped);
HvFunc = getOpt(o,'HVFUNC',[]);
bbType = getOpt(o,'BBTYPE',0);
cycle = getOpt(o,'CYCLE',3);
HessianIter = getOpt(o,'HESSIANITER',HessianIter);
outputFcn = getOpt(o,'OUTPUTFCN',[]);
useMex = getOpt(o,'USEMEX',1);
useNegCurv = getOpt(o,'USENEGCURV',1);
precFunc = getOpt(o,'PRECFUNC',[]);
end

function [v] = getOpt(options,opt,default)
if isfield(options,opt)
    if ~isempty(getfield(options,opt))
        v = getfield(options,opt);
    else
        v = default;
    end
else
    v = default;
end
end

function [o] = toUpper(o)
if ~isempty(o)
    fn = fieldnames(o);
    for i = 1:length(fn)
        o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
    end
end
end


classdef IN1KMOP6 < 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 = 'transformer';
            config.args.objs = 'err&params&flops';
            config.args.normalized_objectives = false;
            obj.Setting@EvoXBenchProblem(config);
        end
    end
end


function tbxStruct  = demos

% DEMOS Demo list for the ANN Library.

% Version 1.1
% Giampiero Campa, West Virginia University
% 1-June-2007

if nargout == 0, demo blockset; return; end

tbxStruct.Name='Adaptive Neural Networks';
tbxStruct.Type='Blockset';

tbxStruct.Help={

   'The Adaptive Neural Networks Library (BANN) consists in a collection'
   'of blocks that implement several adaptive neural networks in simulink.'
};

 tbxStruct.DemoList = { ' Adaptive Neural Network Library',       'ann';
                        ' Main Demo File ',          'anndemo' };


% prtBrvMc - Bayesian Random Variable Monte Carlo

classdef prtBrvMcmc

    methods (Abstract)
        [self, training, samples] = mcmc(self, x);
    end

    properties
        mcmcTotalIterations = 2e3; % Total number of iterations
        mcmcDiscardIterations = 1e3; % The first mcmcDiscardIterations will be removed
        mcmcRetainEveryOtherItation = 5; % Draw 1:mcmcRetainEveryOtherItation:end will be retained
        mcmcVerboseText = false; % display text
        mcmcVerbosePlot = false; % plot after each iteration
        mcmcVerboseMovie = false; % make a movie with each frame of plotting
        mcmcVerboseMovieFrames = []; % Where we store the frames
    end
end


function [S] = readSEL(filename)
  % READSEL read selection from .sel file (as used by Mario Botsch and Olga
  % Sorkine in the accompanying data to their survey "On linear variational
  % surface deformation methods"
  % http://igl.ethz.ch/projects/deformation-survey/
  %
  % Input:
  %   filename  path to .sel file
  % Output:
  %   S #V list of ids:
  %     0  fixed boundary (silver, completely fixed handle-region)
  %     1  interior (blue, "solved-for", "free" region)
  %     2  handle boundary (gold, re-arrangable handle-region)
  %
  % Example:
  %  S = readSEL(filename);
  %  % Swap 0 (fixed boundary) with 1 (interior) so that selection mask
  %  % functions as handle ids (with 0 meaning interior)
  %  R = (S<1).*1 + (S==1).*0 + (S>1).*S;
  %

  fp = fopen(filename,'r');
  % read initial comments
  C = textscan(fp, '#%[^\n]');
  % remaining lines contain one integer per line
  S = fscanf(fp,'%d');
  % clean up file
  fclose(fp);
end


% read bboxes from txt file given by the MOTChallege
function bboxes = read_bboxes(file_name)

fid = fopen(file_name, 'r');
% <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>
line = textscan(fid, '%d %d %f %f %f %f %f %f %f %f', 'Delimiter', ',');
fclose(fid);

% build the bboxes structure for detections
bboxes.fr = line{1};
bboxes.id = line{2};
bboxes.x = line{3};
bboxes.y = line{4};
bboxes.w = line{5};
bboxes.h = line{6};
bboxes.r = line{7};


function [tests,pass,perf]=test_rdsamp(varargin)

inputs={'verbose'};
verbose=0;
for n=1:nargin
    if(~isempty(varargin{n}))
        eval([inputs{n} '=varargin{n};']);
    end
end

%Test the examples
test1_str=['[signal,Fs,tm]=rdsamp(''mghdb/mgh001'', [1 3 5],1000,[]);'];
test2_str=['[signal,Fs,tm]=rdsamp(''mghdb/mgh001'', [1 3 5],1000,[],2);'];
test3_str=['[signal,Fs,tm]=rdsamp(''challenge/2013/set-a/a01'',[],1000);'...
    'plot(tm,signal(:,1));close all'];
test4_str=['[sig,Fs,tm] = rdsamp(''drivedb/drive02'',[1],[],[],[],1);'];

%test3_str=['[tm2,sig2]=rdsamp(''mimic2wdb/30/3003521/3003521_0001'',[2 4 5], 30499638,30484638);'];
%test4_str=['[tm2,sig2]=rdsamp(''mimic2wdb/30/3003521/3003521_0001'',[2 4 5],[],[],2);'];
%For now avoid these test conditions from above, which still need to be
%fixed. This looks like it is an issue with reading large multi-record
%signals with N and N0 defined.

test_string={test1_str,test2_str,test3_str,test4_str};

clean_up={[''],[''],[''],['']};
[tests,pass,perf]=test_wrapper(test_string,clean_up,verbose);


function payment_calc

%PAYMENT_CALC Example loan payment calculator using Swing and MATLAB.
% note: uses financial toolbox

% make the swing class names appear as functions to MATLAB.
% see http://java.sun.com/j2se/1.3/docs/api/javax/swing/package-summary.html
import javax.swing.*;

% make the java.awt class names appear as functions to MATLAB.
% see http://www.javasoft.com/products/jdk/1.1/docs/api/Package-java.awt.html
import java.awt.*;

% create a swing window with this title
frame = JFrame('Loan Payment Calculator');
frame.setSize( 300,200)

% put the dialog in the center of the screen
% ** default sizes are approximate since we use pack below
defXSize = 300;
defYSize = 200;
% get screensize from MATLAB
ss = get(0,'ScreenSize');

% calculate x and y start points
xloc = ss(3) / 2 - defXSize / 2;
yloc = ss(4) / 2 - defYSize / 2;

% create Labels, Text Fields/Areas, and Buttons
LabelLoan   = JLabel('Amount of Loan');
LabelYears  = JLabel('Number of Years');
LabelRate   = JLabel('Interest Rate');
TextLoan    = JTextField(9);
TextYears   = JTextField(3);
BoxRate    = JComboBox({' ','9.25','9.0','8.75',...
        '8.5','8.25','8.0','7.75',...
        '7.5','7.25','7.0','6.75',...
        '6.5','6.25'});
ButtonCalc  = JButton('Calculate');
ButtonClear = JButton('Clear');
ButtonQuit = JButton('Quit');

LabelPayment = JLabel('Monthly Payment');
TextPayment  = JTextField(8);
LabelIntPaid = JLabel('Total Interest Paid');
TextIntPaid  = JTextField(9);

% create layout
MainPanel = JPanel( GridLayout(1,2) );
InPanel   = JPanel( BoxLayout.Y_AXIS );
OutPanel  = JPanel( BoxLayout.Y_AXIS );

% add the labels to the input panel
InPanel.add( LabelLoan );
InPanel.add( TextLoan );
InPanel.add( LabelYears );
InPanel.add( TextYears );
InPanel.add( LabelRate );
InPanel.add( BoxRate );
InPanel.add( ButtonCalc );
InPanel.add( ButtonClear );

% add the labels to the output panel
OutPanel.add( LabelPayment );
OutPanel.add( TextPayment );
OutPanel.add( LabelIntPaid );
OutPanel.add( TextIntPaid );
OutPanel.add( ButtonQuit );

% add the Input and Output panels to the main panel
MainPanel.add( InPanel );
MainPanel.add( OutPanel );

% add the main panel to the main frame (a.k.a. window)
frame.getContentPane.add( MainPanel );

% force dialog location
frame.setLocation(Point(xloc,yloc));

% make dialog visible
frame.show;

set( InPanel, 'UserData', [0 0 0]);
set( frame,'WindowClosingCallback', ...
    {@Callback, InPanel},...
    'Name','quit');
set( BoxRate, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','rate');
set( ButtonCalc, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','calc');
set( ButtonClear, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','clear');
set( ButtonQuit, 'ActionPerformedCallback',...
    {@Callback, InPanel}, ...
    'Name','quit');
set( TextLoan, 'ActionPerformedCallback',{@Callback, InPanel}, ...
    'FocusLostCallback',{@Callback, InPanel},...
    'HorizontalAlignment',[4], ... %right justified
    'Name','loan');
set( TextYears, 'ActionPerformedCallback',{@Callback, InPanel}, ...
    'FocusLostCallback',{@Callback, InPanel},...
    'HorizontalAlignment',[4], ... %right justified
    'Name','year');
set( TextPayment, 'HorizontalAlignment',[4], ... %right justified
    'Editable','off',...
    'Background',[1 1 1]);
set( TextIntPaid, 'HorizontalAlignment',[4], ... %right justified
    'Editable','off',...
    'Background',[1 1 1]);

while ~(exist('STOP'))
    waitfor(InPanel,'ApplicationData')

    result = getappdata(InPanel,'QuestionAppData');

    if ~isnumeric(result)
        if (strcmp(result,'calc'))      % write out answers in text fields
        UData = get( ButtonCalc, 'UserData');
        set( TextPayment , 'Text', cur2str( UData(1) ));
        set( TextIntPaid , 'Text', cur2str( UData(2) ));
        elseif (strcmp(result,'clear')) % clear out text fields
        set( TextPayment , 'Text', '');
        set( TextIntPaid , 'Text', '');
        set( TextYears, 'Text', '' );
        set( TextLoan, 'Text', '' );
        set( BoxRate, 'SelectedItem',' ' );
        else                            % end application and close
            STOP = 1;
        end
    end

    rmappdata(InPanel,'QuestionAppData'); % clear application data
end

% close the java window
frame.dispose;

%
% since this function is called via a function handle
% The args are eventSrc (the handle of object which threw
% the event), eventData (unused in release 12), and panel
% (nargin are when the callback is created).
%
function Callback( eventSrc, eventData, panel )

UData = get( panel, 'UserData');

name = get(eventSrc,'Name');

switch name
case 'rate'    % get rate selected and save in panel
    Srate = get( eventSrc, 'SelectedItem' );
    result = str2num(Srate);
    UData = [UData(1) UData(2) result];
case 'year'    % get number of years and save in panel
    Syear = get( eventSrc, 'Text' );
    if (strcmp(Syear,''))
        result = 1;
    else
        result = str2num(Syear);
    end
    UData = [ UData(1) result UData(3)];
case 'loan'    % get amount of loan and save in panel
    Sloan = get( eventSrc, 'Text' );
    if (strcmp(Sloan,''))
        result = 0;
    else
        result = str2num(Sloan);
    end
    UData = [ result UData(2) UData(3)];
case 'calc'    % calculate payments and interest
    [PRINP,INTP,BAL,P] = amortize(UData(3)/1200,UData(2)*12,UData(1));
    set( eventSrc, 'UserData', [ P sum(INTP) ]);
    result = 'calc';
case 'clear'   % send command to clear text fields
    result = 'clear';
case 'quit'    % send command to stop waiting and close application
    result = 'quit';
end
set( panel, 'UserData', UData );
setappdata( panel, 'QuestionAppData', result );


function g = real(f)
%REAL Real part of a BALLFUN.
%   REAL(F) is the real part of the BALLFUN F.
%
% See also IMAG.

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

g = compose( f, @real );

end


function [trx,timestamps] = ReadMWTContours(contournames,ids,varargin)

[dotransposeimage] = myparse(varargin,'dotransposeimage',false);

ncontours = numel(contournames);
% read everthing in from the contour files
trx = [];
for i = 1:ncontours,

  trk = struct('id',ids(i),'xcontour',{{}},'ycontour',{{}});
  timestamps = [];
  fid = fopen(contournames{i},'r');
  j = 1;
  while true,
    s = fgetl(fid);
    if ~ischar(s),
      break;
    end
    d = sscanf(s,'%f');
    if numel(d) < 3,
      warning('Contour line %s length < 3, skipping this line',s);
      continue;
    end
    if mod(numel(d),2) ~= 1,
      warning('Contour line %s length is not odd, skipping this line',s);
      continue;
    end
    d = d';
    timestamp = d(1);
    x = d(2:2:end-1);
    y = d(3:2:end);
    if dotransposeimage,
      trk.xcontour{j} = x+1;
      trk.ycontour{j} = y+1;
    else
      trk.xcontour{j} = y+1;
      trk.ycontour{j} = x+1;
    end
    timestamps(j) = timestamp; %#ok<*AGROW>
    j = j + 1;
  end
  fclose(fid);
  trk.timestamp = timestamps;
  trx = structappend(trx,trk);
end

% make all the timestamps agree with each other
fnsmerge = {'xcontour','ycontour'};
fnscopy = {};
[trx,timestamps] = MergeMWTData(trx,fnsmerge,fnscopy);


clear all;
%%%====== Settings ======%%%
model = 'Multi-purpose CNN'; % 'Deep SR-ITM' (ICCV'19) or 'Multi-purpose CNN' (ACCV'18)
SDR_file = './data/test/testset_SDR.mat'; % input .mat file
HDR_file = './data/test/testset_HDR.mat'; % GT .mat file
scale = 2; % scale factor for SR
pred_file = sprintf('./pred/pred_x%d.mat', scale); % result .mat file
%%%======================%%%
addpath('utils');
% load data
disp(['Testing for scale ', num2str(scale), '...'])
disp('Loading file...')
SDR = load(SDR_file);
HDR = load(HDR_file);
data = SDR.SDR;
label = HDR.HDR;

% initialize
psnr_all = zeros(1, size(data, 4));
ssim_all = zeros(1, size(data, 4));
mpsnr_all = zeros(1, size(data, 4));
msssim_all = zeros(1, size(data, 4));
pred = single(zeros(size(data)));

% load net
disp('Loading net...')
if strcmp(model, 'Deep SR-ITM')
    netstruct = load(sprintf('./net/x%d.mat', scale));
elseif strcmp(model, 'Multi-purpose CNN')
    netstruct = load(sprintf('./net/Multi-purpose_CNN_x%d.mat', scale));
end
if strcmp(model, 'Deep SR-ITM')
    netstruct.net.layers(172).type='dagnn.SubPixel_Conv_cpu';
elseif strcmp(model, 'Multi-purpose CNN')
    netstruct.net.layers(37).type='dagnn.SubPixel_Conv_cpu';
end
net = dagnn.DagNN.loadobj(netstruct.net);
move(net,'cpu');
net.mode = 'test' ;
pred_index = net.getVarIndex('pred');
net.conserveMemory = true;

% test
disp('Testing starts...')
for fr = 1:size(data, 4)
    % read frames
    SDR_YUV = single(data(:, :, :, fr));
    HDR_YUV = single(label(:, :, :, fr));
    % normalize
    SDR_YUV = SDR_YUV/255;
    HDR_YUV = HDR_YUV/1023;
    % create LR data
    SDR_LR_YUV = imresize(SDR_YUV, 1/scale);
    % prediction
    net.eval({'input', SDR_LR_YUV});
    pred_fr = net.vars(pred_index).value;
    pred(:, :, :, fr) = min(max(pred_fr, 0), 1);

    %%% Evaluation %%% (comment or uncomment appropriate lines)
    % *some metrics may be slow*
    psnr_all(fr) = psnr(HDR_YUV, pred(:, :, :, fr), 1); % PSNR
%     ssim_all(fr) = ssim(HDR_YUV, pred(:, :, :, fr)); % SSIM
%     mpsnr_all(fr) = mPSNR_HDR(HDR_YUV, pred(:, :, :, fr), -3, 3); % mPSNR
%     msssim_all(fr) = msssim(HDR_YUV*1023, pred(:, :, :, fr)*1023, 1023);

    disp(['#', num2str(fr), ' PSNR: ', num2str(psnr_all(fr)), ' dB'])
%     disp(['#', num2str(fr), ' PSNR: ', num2str(psnr_all(fr)), ' dB', ' SSIM: ', num2str(ssim_all(fr)),...
%         ' mPSNR: ', num2str(mpsnr_all(fr)), ' dB', ' MS-SSIM: ', num2str(msssim_all(fr))]);
end
disp(['Average PSNR: ', num2str(mean(psnr_all)), ' dB'])
% disp(['Avg PSNR: ', num2str(mean(psnr_all)), ' dB', ' Avg SSIM: ', num2str(mean(ssim_all)),...
%     ' Avg mPSNR: ', num2str(mean(mpsnr_all)), ' dB', ' Avg MS-SSIM: ', num2str(mean(msssim_all))]);
% REFERENCE x2: Avg PSNR: 35.5966 dB Avg SSIM: 0.9833 Avg mPSNR: 38.0449 dB Avg MS-SSIM: 0.9843
% REFERENCE x4: Avg PSNR: 33.69 dB Avg SSIM: 0.9657 Avg mPSNR: 36.13 Avg MS-SSIM: 0.9754

% save as .mat file
disp('Saving...')
save(pred_file, 'pred', '-v7.3');
disp('Done!')


function spy( prob, reduce )
if nargin < 2 || ~reduce,
    A = extract( prob );
else
    A = eliminate( prob );
end
spy( A' );

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


% EDGELINK - Link edge points in an image into lists
%
% Usage: [edgelist edgeim] = edgelink3(im, minlength, location)
%
% Arguments:  im         - Binary edge image, it is assumed that edges
%                          have been thinned.
%             minlength  - Minimum edge length of interest
%             location   - Optional complex valued image holding subpixel
%                          locations of edge points. For any pixel the
%                          real part holds the subpixel row coordinate of
%                          that edge point and the imaginary part holds
%                          the column coordinate.  See NONMAXSUP.  If
%                          this argument is supplied the edgelists will
%                          be formed from the subpixel coordinates,
%                          otherwise the the integer pixel coordinates of
%                          points in 'im' are used.
%
% Returns:  edgelist - a cell array of edge lists in row,column coords in
%                      the form
%                     { [r1 c1   [r1 c1   etc }
%                        r2 c2    ...
%                        ...
%                        rN cN]   ....]
%
%           edgeim   - Image with pixels labeled with edge number.
%
%
% This function links edge points together into chains.  Where an edge
% diverges at a junction the function simply tracks one of the branches.
% The other branch is eventually processed as another edge.  These `broken
% branches' can be remerged by MERGESEG after a call to LINESEG.
%
% See also:  DRAWEDGELIST, LINESEG, MAXLINEDEV, MERGESEG, DRAWSEG, NONMAXSUP

% Acknowledgement:
% This code is inspired by David Lowe's Link.c function from the Vista image
% processing library developed at the University of British Columbia
%    http://www.cs.ubc.ca/nest/lci/vista/vista.html

% Copyright (c) 2001-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.

% February  2001 - Original version
% September 2004 - Revised to allow subpixel edge data to be used
% January   2006 - Edited for TF Peaks by Luke Rankine
% March     2006 - Modified to handle images with no components
%                - Corrected the nearest neighbour set for IF estimation

function [edgelist, edgeim] = edgelink3(im, minlength, location)

global EDGEIM;      % Some global variables to avoid passing (and
% copying) of arguments, this improves speed.
global ROWS;
global COLS;

elist = {};

EDGEIM = im ~= 0;                     % make sure image is binary.

%   EDGEIM = bwmorph(EDGEIM,'thin',Inf);  % make sure edges are thinned.
%   show(EDGEIM,1)

EDGEIM = double(EDGEIM);
[ROWS, COLS] = size(EDGEIM);
edgeNo = 1;

% Perform raster scan through image looking for edge points.  When a
% point is found trackedge is called to find the rest of the edge
% points.  As it finds the points the edge image pixels are labeled
% with the -ve of their edge No

edgelist = {}; % Modified, Luke. Initializing variable so it can be returned
for r = 1:ROWS
    for c = 1:COLS
        if EDGEIM(r,c) == 1
            edgepoints = trackedge(r,c, edgeNo, minlength);
            if ~isempty(edgepoints)
                edgelist{edgeNo} = edgepoints;
                edgeNo = edgeNo + 1;
            end
        end
    end
end

% Modified, Luke. Checking to see if any components were linked
if isempty(edgelist) == 1
    edgeim = zeros(ROWS,COLS);
    return
else

    edgeim = -EDGEIM;  % Finally negate image to make edge encodings +ve.

    % If subpixel edge locations are supplied upgrade the integer precision
    % edgelists that were constructed with data from 'location'.
    if nargin == 3
        for I = 1:length(edgelist)
            ind = sub2ind(size(im),edgelist{I}(:,1),edgelist{I}(:,2));
            edgelist{I}(:,1) = real(location(ind))';
            edgelist{I}(:,2) = imag(location(ind))';
        end
    end

    %   show(edgeim,2), colormap(flag);
end

%----------------------------------------------------------------------
% TRACKEDGE
%
% Function to track all the edge points associated with a start point.  From
% a given starting point it tracks in one direction, storing the coords of
% the edge points in an array and labelling the pixels in the edge image
% with the -ve of their edge number.  When no more connected points are
% found the function returns to the start point and tracks in the opposite
% direction.  Finally a check for the overall number of edge points found is
% made and the edge is ignored if it is too short.
%
% Note that when a junction is encountered along an edge the function
% simply tracks one of the branches.  The other branch is eventually
% processed as another edge.  These `broken branches' can be remerged by
% MERGESEG.
%
% Usage:   edgepoints = trackedge(rstart, cstart, edgeNo, minlength)
%
% Arguments:   rstart, cstart   - row and column No of starting point
%              edgeNo           - the current edge number
%              minlength        - minimum length of edge to accept
%
% Returns:     edgepoints       - Nx2 array of row and col values for
%                                 each edge point.
%                                 An empty array is returned if the edge
%                                 is less than minlength long.

function edgepoints = trackedge(rstart, cstart, edgeNo, minlength)

global EDGEIM;
global ROWS;
global COLS;

edgepoints = [rstart cstart];      % Start a new list for this edge.
EDGEIM(rstart,cstart) = -edgeNo;   % Edge points in the image are
% encoded by -ve of their edgeNo.

[thereIsAPoint, r, c] = nextpoint(rstart,cstart); % Find next connected
% edge point.

while thereIsAPoint
    edgepoints = [edgepoints             % Add point to point list
        r    c   ];
    EDGEIM(r,c) = -edgeNo;               % Update edge image
    [thereIsAPoint, r, c] = nextpoint(r,c);
end

edgepoints = flipud(edgepoints);  % Reverse order of points

% Now track from original point in the opposite direction

[thereIsAPoint, r, c] = nextpoint(rstart,cstart);

while thereIsAPoint
    edgepoints = [edgepoints
        r    c   ];
    EDGEIM(r,c) = -edgeNo;
    [thereIsAPoint, r, c] = nextpoint(r,c);
end

% Reject short edges
Npoints = size(edgepoints,1);
if Npoints < minlength
    for i = 1:Npoints   % Clear pixels in the edge image
        EDGEIM(edgepoints(i,1), edgepoints(i,2)) = 0;
    end
    edgepoints = [];    % Return empty array
end

%----------------------------------------------------------------------
%
% NEXTPOINT
%
% Function finds a point that is 8 connected to an existing edge point
%

function [thereIsAPoint, nextr, nextc] = nextpoint(rp,cp)

global EDGEIM;
global ROWS;
global COLS;

% Modified by Luke Rankine, Jan. 2006
% row and column offsets for the 10(originally eight) neighbours of a
% point starting with those that are semi 4-connected.
%     roff = [1  0 -1  0  1  1 -1 -1  2 -2 -2  2];
%     coff = [0  1  0 -1  1 -1 -1  1  1  1 -1 -1];
roff = [0  0 1  1 2  2 -1 -1 -2 -2];
coff = [1 -1 1 -1 1 -1  1 -1  1 -1];

r = rp+roff;
c = cp+coff;

% Search through neighbours and return first connected edge point
for i = 1:length(roff)
    if r(i) >= 1 & r(i) <= ROWS & c(i) >= 1 & c(i) <= COLS
        if EDGEIM(r(i),c(i)) == 1
            nextr = r(i);
            nextc = c(i);
            thereIsAPoint = 1;
            return;             % break out and return with the data
        end
    end
end

% If we get here there was no connecting next point.
nextr = 0;
nextc = 0;
thereIsAPoint = 0;


function dfupdatexlim(newminmax,updateplots)
%DFUPDATEXLIM Update the stored x axis min/max values

%   $Revision: 1.1.6.5 $  $Date: 2004/01/24 09:36:03 $
%   Copyright 2003-2004 The MathWorks, Inc.

minmax = [];                     % to become new x limits
oldminmax = dfgetset('xminmax'); % previous limits
ftype = dfgetset('ftype');
if nargin==0
   newminmax = [];
end

if isempty(newminmax) && isequal(ftype, 'icdf')
   % Default limits span most of the probability range
   minmax = [.01 .99];
elseif isempty(newminmax)
   % Update limits from datasets with a plotting flag on
   dsdb = getdsdb;
   ds = down(dsdb);
   while(~isempty(ds))
      if ds.plot == 1
         minmax = combineminmax(minmax,ds.xlim);
      end
      ds = right(ds);
   end

   % Update from fits with a plotting flag on
   fitdb = getfitdb;
   ft = down(fitdb);
   while(~isempty(ft))
      if ft.plot == 1
         minmax = combineminmax(minmax,xlim(ft));
      end
      ft = right(ft);
   end
else
   minmax = newminmax;
end

% Now update plot
dffig = dfgetset('dffig');
if ~isempty(minmax) && isequal(zoom(dffig,'getmode'),'off')
   ax = get(dffig,'CurrentAxes');
   islinscale = isequal(get(ax,'XScale'),'linear');
   if ~islinscale && any(minmax<=0)
      warning('stats:dfupdatexlim:NegativeDataIgnored',...
              'Negative data ignored.');
      minmax = [1e-6 1] * max(abs(minmax));
   end
   if isempty(newminmax) && ~isequal(ftype, 'icdf')
      % Adjust axis limits to include a margin around plotted points
      if islinscale
         dx = diff(minmax) * 0.01 * [-1 1];
         if all(dx==0), dx = [-1 1]; end
      else
         dlogx = .01 * diff(log(minmax));
         if dlogx==0, dlogx = 1; end
         dx = [minmax(1) * exp(-dlogx),  minmax(2) * exp(dlogx)] - minmax;
      end
   elseif minmax(1)==minmax(2)
      if islinscale
         dx = [-1 1];
      else
         dx = [minmax(1)/2, 2*minmax(1)];
      end
   else
      % Don't adjust the limits that were passed in or computed
      dx = 0;
   end
   oldxlim = get(ax,'XLim');
   newxlim = minmax + dx;
   if ~isequal(oldxlim,newxlim)
      set(ax,'XLim',newxlim);
      if nargin<2 || updateplots
         dfupdateallplots(false,true);
      end
   end
end
dfgetset('xminmax',minmax);

% ------------ Helper to combine old and new minmax values
function bothmm = combineminmax(oldmm,newmm)

if isempty(oldmm)
   bothmm = newmm;
elseif isempty(newmm)
   bothmm = oldmm;
else
   bothmm = [min(oldmm(1),newmm(1)) max(oldmm(2),newmm(2))];
end


function [c1,c2]= singlePtX(p1,p2,bounds,Ops)
% function [c1,c2] = singlePtXover(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;
cut = round(rand*(sz-1)+0.5); %Generate random cut point U(1,n-1)
pm1=p1(1:sz);
pm2=p2(1:sz);
c1=p1;
c2=p2;
c1(1:cut)=p1(1:cut);
c2(1:cut)=p2(1:cut);
for i=1:cut
  pm1=strrep(pm1,p2(i),-1);
  pm2=strrep(pm2,p1(i),-1);
end
c1((cut+1):sz)=p2(find(pm2>0));
c2((cut+1):sz)=p1(find(pm1>0));


% The COBRAToolbox: testConvertCNAModelToCbModel.m
%
% Purpose:
%     - convert a CNA model to a COBRA model and vice versa
%

% save the current path
currentDir = pwd;

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

% check if CNA is properly installed
statusCNA = checkCNAinstallation();

if statusCNA
    model = getDistributedModel('ecoli_core_model.mat');

    % load reference data
    load('refData_cnaModel.mat')

    % convert a COBRA model to a CNA model
    cnaModel_new = convertCbModelToCNAModel(model);

    % assert if the cnaModel_new is equal to the reference CNA model
    if 0
        assert(isequaln(cnaModel_new, cnaModel));
    else
        % function [cnap, errval]= CNAgenerateMFNetwork(cnap,nodisp) in CellNetAnalyzer: API function CNAgenerateMFNetwork
        % has been updated to include new default fields, that do not
        % match, so remove them. Probably cnaModel_new needs to be updated.
        if isfield(cnaModel_new,'color1')
            cnaModel_new= rmfield(cnaModel_new,{'color1','color2','color3','color4','textColor','macroSynthColor','specBoxColor','unsaved_changes'});
        end
        assert(isequaln(cnaModel_new, cnaModel));
    end

    % convert the reference CNA model to the COBRA model
    model_new = convertCNAModelToCbModel(cnaModel);

    assert(isequal(model_new.rxns, model.rxns));
    assert(isequal(model_new.mets, model.mets));
    assert(isequal(model_new.S, model.S));
    assert(isequal(model_new.lb, model.lb));
    assert(isequal(model_new.ub, model.ub));
    %Osense is no longer a model field, so we need to check, whether the
    %generated LPproblems are the same (or we have to make a lot of if
    %statements...)
    LPproblemA = buildLPproblemFromModel(model_new);
    LPproblemB = buildLPproblemFromModel(model);
    assert(isequal(LPproblemA.osense*LPproblemA.c, LPproblemB.osense*LPproblemB.c));
    assert(isequal(model_new.metNames, model.metNames));
    assert(isequal(model_new.b, model.b));
    % Note: rxnNames is different
end

% change the directory
cd(currentDir)


function t_most_spuc(quiet, create_plots, create_pdfs, savedir)
%T_MOST_SPUC  Tests of single-period unit commitment optimizations
%
%   T_MOST_SPUC(QUIET, CREATE_PLOTS, CREATE_PDFS, SAVEDIR)
%   Can generate summary plots and save them as PDFs in a directory of
%   your choice.
%   E.g. t_most_spuc(0, 1, 1, '~/Downloads/spuc_plots')

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

if nargin < 4
    savedir = '.';              %% save in current working directory by default
    if nargin < 3
        create_pdfs = 0;        %% do NOT save plots to PDF files
        if nargin < 2
            create_plots = 0;   %% do NOT create summary plots of results
            if nargin < 1
                quiet = 0;      %% verbose by default
            end
        end
    end
end

solvers = {'CPLEX', 'GLPK', 'GUROBI', 'MOSEK', 'OT'};
fcn = {'cplex', 'glpk', 'gurobi', 'mosek', 'intlinprog'};
% solvers = {'OT'};
% fcn = {'intlinprog'};
% solvers = {'GUROBI'};
% fcn = {'gurobi'};
% solvers = {'GLPK'};
% fcn = {'glpk'};
ntests = 144;
t_begin(ntests*length(solvers), quiet);

if quiet
    verbose = 0;
else
    verbose = 0;
end
% verbose = 2;

casefile = 'ex_case3b';
mpopt = mpoption;
mpopt = mpoption(mpopt, 'out.gen', 1);
mpopt = mpoption(mpopt, 'verbose', verbose);
% mpopt = mpoption(mpopt, 'opf.violation', 1e-6, 'mips.gradtol', 1e-8, ...
%         'mips.comptol', 1e-8, 'mips.costtol', 1e-8);
mpopt = mpoption(mpopt, 'model', 'DC');
mpopt = mpoption(mpopt, 'sopf.force_Pc_eq_P0', 0);
mpopt = mpoption(mpopt, 'most.price_stage_warn_tol', 10);

%% solver options
if have_feature('cplex')
    %mpopt = mpoption(mpopt, 'cplex.lpmethod', 0);       %% automatic
    %mpopt = mpoption(mpopt, 'cplex.lpmethod', 1);       %% primal simplex
    mpopt = mpoption(mpopt, 'cplex.lpmethod', 2);       %% dual simplex
    %mpopt = mpoption(mpopt, 'cplex.lpmethod', 3);       %% network simplex
    %mpopt = mpoption(mpopt, 'cplex.lpmethod', 4);       %% barrier
    mpopt = mpoption(mpopt, 'cplex.opts.mip.tolerances.mipgap', 0);
    mpopt = mpoption(mpopt, 'cplex.opts.mip.tolerances.absmipgap', 0);
    mpopt = mpoption(mpopt, 'cplex.opts.threads', 2);
end
if have_feature('glpk')
    mpopt = mpoption(mpopt, 'glpk.opts.mipgap', 0);
    mpopt = mpoption(mpopt, 'glpk.opts.tolint', 1e-10);
    mpopt = mpoption(mpopt, 'glpk.opts.tolobj', 1e-10);
end
if have_feature('gurobi')
    %mpopt = mpoption(mpopt, 'gurobi.method', -1);       %% automatic
    %mpopt = mpoption(mpopt, 'gurobi.method', 0);        %% primal simplex
    mpopt = mpoption(mpopt, 'gurobi.method', 1);        %% dual simplex
    %mpopt = mpoption(mpopt, 'gurobi.method', 2);        %% barrier
    mpopt = mpoption(mpopt, 'gurobi.threads', 2);
    mpopt = mpoption(mpopt, 'gurobi.opts.MIPGap', 0);
    mpopt = mpoption(mpopt, 'gurobi.opts.MIPGapAbs', 0);
end
if have_feature('mosek')
    sc = mosek_symbcon;
    %mpopt = mpoption(mpopt, 'mosek.lp_alg', sc.MSK_OPTIMIZER_FREE);            %% default
    %mpopt = mpoption(mpopt, 'mosek.lp_alg', sc.MSK_OPTIMIZER_INTPNT);          %% interior point
    %mpopt = mpoption(mpopt, 'mosek.lp_alg', sc.MSK_OPTIMIZER_PRIMAL_SIMPLEX);  %% primal simplex
    mpopt = mpoption(mpopt, 'mosek.lp_alg', sc.MSK_OPTIMIZER_DUAL_SIMPLEX);     %% dual simplex
    %mpopt = mpoption(mpopt, 'mosek.lp_alg', sc.MSK_OPTIMIZER_FREE_SIMPLEX);    %% automatic simplex
    %mpopt = mpoption(mpopt, 'mosek.opts.MSK_DPAR_MIO_TOL_X', 0);
    mpopt = mpoption(mpopt, 'mosek.opts.MSK_IPAR_MIO_NODE_OPTIMIZER', sc.MSK_OPTIMIZER_DUAL_SIMPLEX);
    mpopt = mpoption(mpopt, 'mosek.opts.MSK_IPAR_MIO_ROOT_OPTIMIZER', sc.MSK_OPTIMIZER_DUAL_SIMPLEX);
    mpopt = mpoption(mpopt, 'mosek.opts.MSK_DPAR_MIO_TOL_ABS_RELAX_INT', 1e-9);
    %mpopt = mpoption(mpopt, 'mosek.opts.MSK_DPAR_MIO_TOL_REL_RELAX_INT', 0);
    mpopt = mpoption(mpopt, 'mosek.opts.MSK_DPAR_MIO_TOL_REL_GAP', 0);
    mpopt = mpoption(mpopt, 'mosek.opts.MSK_DPAR_MIO_TOL_ABS_GAP', 0);
end
if have_feature('intlinprog')
    %mpopt = mpoption(mpopt, 'linprog.Algorithm', 'interior-point');
    %mpopt = mpoption(mpopt, 'linprog.Algorithm', 'active-set');
    %mpopt = mpoption(mpopt, 'linprog.Algorithm', 'simplex');
    mpopt = mpoption(mpopt, 'linprog.Algorithm', 'dual-simplex');
    %mpopt = mpoption(mpopt, 'intlinprog.RootLPAlgorithm', 'primal-simplex');
    mpopt = mpoption(mpopt, 'intlinprog.RootLPAlgorithm', 'dual-simplex');
    mpopt = mpoption(mpopt, 'intlinprog.TolCon', 1e-9);
    mpopt = mpoption(mpopt, 'intlinprog.TolGapAbs', 0);
    mpopt = mpoption(mpopt, 'intlinprog.TolGapRel', 0);
    mpopt = mpoption(mpopt, 'intlinprog.TolInteger', 1e-6);
    %% next line is to work around a bug in intlinprog
    % (Technical Support Case #01841662)
    mpopt = mpoption(mpopt, 'intlinprog.LPPreprocess', 'none');
end
if ~verbose
    mpopt = mpoption(mpopt, 'out.all', 0);
end
% mpopt = mpoption(mpopt, 'out.all', -1);

%% define named indices into data matrices
[PQ, PV, REF, NONE, BUS_I, BUS_TYPE, PD, QD, GS, BS, BUS_AREA, VM, ...
    VA, BASE_KV, ZONE, VMAX, VMIN, LAM_P, LAM_Q, MU_VMAX, MU_VMIN] = idx_bus;
[GEN_BUS, PG, QG, QMAX, QMIN, VG, MBASE, GEN_STATUS, PMAX, PMIN, ...
    MU_PMAX, MU_PMIN, MU_QMAX, MU_QMIN, PC1, PC2, QC1MIN, QC1MAX, ...
    QC2MIN, QC2MAX, RAMP_AGC, RAMP_10, RAMP_30, RAMP_Q, APF] = idx_gen;
[F_BUS, T_BUS, BR_R, BR_X, BR_B, RATE_A, RATE_B, RATE_C, ...
    TAP, SHIFT, BR_STATUS, PF, QF, PT, QT, MU_SF, MU_ST, ...
    ANGMIN, ANGMAX, MU_ANGMIN, MU_ANGMAX] = idx_brch;
[PW_LINEAR, POLYNOMIAL, MODEL, STARTUP, SHUTDOWN, NCOST, COST] = idx_cost;
[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;

%% load base case file
mpc = loadcase(casefile);
mpc.gencost(:, STARTUP) = 0;
mpc.gencost(:, SHUTDOWN) = 0;

%%-----  contingencies  -----
contab = loadgenericdata('ex_contab', 'array');
pp = [1-sum(contab(:,2)); contab(1,2); contab(2,2)];

xgd = loadxgendata('ex_xgd_uc', mpc);
[iwind, mpc, xgd] = addwind('ex_wind_uc', mpc, xgd);
mpc.reserves.zones = [mpc.reserves.zones 0];
mpc = scale_load(499, mpc, [], struct('scale', 'QUANTITY'));
mpc0 = mpc;
xgd0 = xgd;

%% data structures for results for plotting
if create_plots
    j = 1;
    Pg   = NaN(5, 7);
    Rp   = NaN(5, 7);
    Rm   = NaN(5, 7);
    lamP = NaN(3, 7);
    muF  = zeros(3, 7);
end

for s = 1:length(solvers)
    if ~have_feature(fcn{s})    %% check if we have the solver
        t_skip(ntests, sprintf('%s not installed', solvers{s}));
    else
        mpopt = mpoption(mpopt, 'opf.dc.solver', solvers{s});
        mpopt = mpoption(mpopt, 'most.solver', mpopt.opf.dc.solver);

%%-----  economic dispatch (no network)  -----
if verbose
    fprintf('\n\n');
    fprintf('--------------------------------------------\n');
    fprintf('-----  economic dispatch (no network)  -----\n');
    fprintf('--------------------------------------------\n');
end
t = sprintf('%s : economic dispatch (no network) : runopf ', solvers{s});
mpc = mpc0;
mpc.branch(:, RATE_A) = 0;
r = runuopf(mpc, mpopt);
t_ok(r.success, [t 'success']);
t_is(r.f, -488030, 7, [t 'f']);
t_is(r.gen(:, PG), [200; 199; 0; -499; 100], 7, [t 'Pg']);
t_is(r.gen(:, GEN_STATUS), [1; 1; 0; 1; 1], 7, [t 'u']);
t_is(r.bus(:, LAM_P), [30; 30; 30], 7, [t 'lam P']);

%% most
t = sprintf('%s : economic dispatch (no network) : most   ', solvers{s});
mpc = mpc0;
mpc.gen(1, GEN_STATUS) = 0;
mpc.gen(2, GEN_STATUS) = 0;
% xgd = xg
mpopt = mpoption(mpopt, 'most.dc_model', 0);
mdi = loadmd(mpc, [], xgd);
mdo = most(mdi, mpopt);
rr = mdo.flow(1,1,1).mpc;
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -488030, 7, [t 'f']);
t_is(rr.gen(:, PG), [200; 199; 0; -499; 100], 7, [t 'Pg']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 0; 1; 1], 7, [t 'u']);
% rr.gen(:, GEN_STATUS)
t_is(rr.bus(:, LAM_P), [30; 30; 30], 7, [t 'lam P']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = 0;
    Rm(:, j) = 0;
    lamP(:, j) = rr.bus(:, LAM_P);
    j = j + 1;
end

%%-----  DC OPF  -----
if verbose
    fprintf('\n\n');
    fprintf('--------------------------------------------\n');
    fprintf('-----              DC OPF              -----\n');
    fprintf('--------------------------------------------\n');
end
t = sprintf('%s : DC OPF : runopf ', solvers{s});
mpc = mpc0;
% mpc = scale_load(500, mpc, [], struct('scale', 'QUANTITY'));
r = runuopf(mpc, mpopt);
t_ok(r.success, [t 'success']);
t_is(r.f, -486040, 7, [t 'f']);
t_is(r.gen(:, PG), [200; 0; 199; -499; 100], 7, [t 'Pg']);
t_is(r.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(r.bus(:, LAM_P), [40; 40; 40], 7, [t 'lam P']);
t_is(r.branch(:, MU_SF) + r.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow']);

%% most
t = sprintf('%s : DC OPF : most   ', solvers{s});
mpc = mpc0;
% mpc = scale_load(500, mpc, [], struct('scale', 'QUANTITY'));
mpopt = mpoption(mpopt, 'most.dc_model', 1);
mdi = loadmd(mpc, [], xgd);
mdo = most(mdi, mpopt);
rr = mdo.flow(1,1,1).mpc;
if verbose
    printpf(rr, [], mpopt);
end
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -486040, 7, [t 'f']);
t_is(rr.gen(:, PG), [200; 0; 199; -499; 100], 6, [t 'Pg']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
% rr.gen(:, GEN_STATUS)
t_is(rr.bus(:, LAM_P), [40; 40; 40], 7, [t 'lam P']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = 0;
    Rm(:, j) = 0;
    lamP(:, j) = rr.bus(:, LAM_P);
    muF(:, j)  = rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
    j = j + 1;
end

%%-----  economic dispatch (w/reserves)  -----
if verbose
    fprintf('\n\n');
    fprintf('--------------------------------------------\n');
    fprintf('-----  economic dispatch (w/reserves)  -----\n');
    fprintf('--------------------------------------------\n');
end
t = sprintf('%s : economic dispatch (w/reserves) : runopf ', solvers{s});
mpc = mpc0;
mpc.branch(:, RATE_A) = 0;
mpc = toggle_reserves(mpc, 'on');
r = runuopf(mpc, mpopt);
t_ok(r.success, [t 'success']);
t_is(r.f, -486802, 5, [t 'f']);
t_is(r.gen(:, PG), [200; 139; 60; -499; 100], 7, [t 'Pg']);
t_is(r.gen(:, GEN_STATUS), [1; 1; 1; 1; 1], 7, [t 'u']);
t_is(r.bus(:, LAM_P), [32; 32; 32], 7, [t 'lam P']);
t_is(r.reserves.R, [0; 61; 89; 0; 0], 7, [t 'R']);
t_is(r.reserves.prc, [5; 5; 5; 0; 0], 7, [t 'reserve prc']);
t_is(r.reserves.mu.Pmax + r.gen(:, MU_PMAX), [7; 2; 0; 0; 32], 7, [t 'reserve muPmax']);

%% most
t = sprintf('%s : economic dispatch (w/reserves) : most   ', solvers{s});
mpc = mpc0;
% mpc = scale_load(350.8, mpc, [], struct('scale', 'QUANTITY'));
mpopt = mpoption(mpopt, 'most.dc_model', 0);
mdi = loadmd(mpc, [], xgd);
mdi.FixedReserves = mpc.reserves;
mdo = most(mdi, mpopt);
rr = mdo.flow(1,1,1).mpc;
if verbose
    printpf(rr, [], mpopt);
end
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -486802, 5, [t 'f']);
t_is(rr.gen(:, PG), [200; 139; 60; -499; 100], 7, [t 'Pg']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 1; 1; 1], 7, [t 'u']);
% rr.gen(:, GEN_STATUS)
t_is(rr.bus(:, LAM_P), [32; 32; 32], 7, [t 'lam P']);
t_is(rr.reserves.R, [0; 61; 89; 0; 0], 7, [t 'R']);
t_is(rr.reserves.prc, [5; 5; 5; 0; 0], 7, [t 'reserve prc']);
t_is(rr.reserves.mu.Pmax + rr.gen(:, MU_PMAX), [7; 2; 0; 0; 32], 7, [t 'reserve muPmax']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = rr.reserves.R;
    Rm(:, j) = 0;
    lamP(:, j) = rr.bus(:, LAM_P);
    j = j + 1;
end

%%-----  DC OPF  -----
if verbose
    fprintf('\n\n');
    fprintf('--------------------------------------------\n');
    fprintf('-----        DC OPF (w/reserves)       -----\n');
    fprintf('--------------------------------------------\n');
end
t = sprintf('%s : DC OPF (w/reserves) : runopf ', solvers{s});
mpc = mpc0;
r = runopf_w_res(mpc, mpopt);
t_ok(r.success, [t 'success']);
t_is(r.f, -485656, 5, [t 'f']);
t_is(r.gen(:, PG), [156; 65; 178; -499; 100], 7, [t 'Pg']);
t_is(r.gen(:, GEN_STATUS), [1; 1; 1; 1; 1], 7, [t 'u']);
t_is(r.bus(:, LAM_P), [29; 40; 51], 7, [t 'lam P']);
t_is(r.branch(:, MU_SF) + r.branch(:, MU_ST), [0; 33; 0], 7, [t 'mu flow']);
t_is(r.reserves.R, [44; 100; 6; 0; 0], 7, [t 'R']);
t_is(r.reserves.prc, [5; 5; 5; 0; 0], 7, [t 'reserve prc']);
t_is(r.reserves.mu.Pmax + r.gen(:, MU_PMAX), [4; 0; 0; 0; 40], 7, [t 'reserve muPmax']);

%% most
t = sprintf('%s : DC OPF (w/reserves) : most   ', solvers{s});
mpc = mpc0;
% mpc = scale_load(350.8, mpc, [], struct('scale', 'QUANTITY'));
mpopt = mpoption(mpopt, 'most.dc_model', 1);
mdi = loadmd(mpc, [], xgd);
mdi.FixedReserves = mpc.reserves;
mdo = most(mdi, mpopt);
rr = mdo.flow(1,1,1).mpc;
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -485656, 5, [t 'f']);
t_is(rr.gen(:, PG), [156; 65; 178; -499; 100], 6, [t 'Pg']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 1; 1; 1], 7, [t 'u']);
% rr.gen(:, GEN_STATUS)
t_is(rr.bus(:, LAM_P), [29; 40; 51], 6, [t 'lam P']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 33; 0], 7, [t 'mu flow']);
t_is(rr.reserves.R, [44; 100; 6; 0; 0], 6, [t 'R']);
t_is(rr.reserves.prc, [5; 5; 5; 0; 0], 7, [t 'reserve prc']);
t_is(rr.reserves.mu.Pmax + rr.gen(:, MU_PMAX), [4; 0; 0; 0; 40], 7, [t 'reserve muPmax']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = rr.reserves.R;
    Rm(:, j) = 0;
    lamP(:, j) = rr.bus(:, LAM_P);
    muF(:, j)  = rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
    j = j + 1;
end

t = sprintf('%s : Secure DC OPF (w/cont,res,ramp) : c3sopf ', solvers{s});
mpc = mpc0;
mpc = scale_load(350, mpc, [], struct('scale', 'QUANTITY'));
xgd_table.colnames = {
    'PositiveActiveReservePrice', ...
            'PositiveActiveReserveQuantity', ...
                    'NegativeActiveReservePrice', ...
                            'NegativeActiveReserveQuantity', ...
                                    'PositiveActiveDeltaPrice', ...
                                            'NegativeActiveDeltaPrice', ...
};
xgd_table.data = [
    5       250     10      0       1e-9    1e-9;
    1e-8    100     2e-8    0       1e-9    1e-9;
    1.5     600     3       0       1e-9    1e-9;
    1e-8    800     2e-8    0       1e-9    1e-9;
    1e-8    200     2e-8    0       1e-9    1e-9;
];
% xgd = loadxgendata(xgd_table, mpc);
xgd.PositiveActiveReserveQuantity(2) = 100;
xgd.PositiveActiveReserveQuantity(4) = 800;
xgd.NegativeActiveReserveQuantity(:) = 0;
xgd.PositiveActiveReservePrice([1;3]) = [5; 1.5];
xgd.NegativeActiveReservePrice([1;3]) = [10; 3];

mpc1 = mpc;
mpc1.gen(2, GEN_STATUS) = 0;
r = c3sopf(mpc1, xgd_table.data, contab, mpopt);
% r
% r.opf_results
% r.opf_results.f
t_ok(r.success, [t 'success']);
t_is(r.opf_results.f, -340850, 4, [t 'f']);
rr = r.base;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [190; 0; 60; -350; 100], 6, [t 'Pg base']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [25; 25; 25], 7, [t 'lam P base']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow base']);
rr = r.cont(1);
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_ok(isempty(rr.gen), [t 'Pg 1']);
t_ok(isempty(rr.bus), [t 'lam P 1']);
t_ok(isempty(rr.branch), [t 'mu flow 1']);
rr = r.cont(2);
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [190; 0; 60; -300; 50], 5, [t 'Pg 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 40], 7, [t 'lam P 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 40], 7, [t 'mu flow 2']);

t = sprintf('%s : Secure DC OPF (w/cont,res,ramp) : most ', solvers{s});
mdi = loadmd(mpc, [], xgd, [], contab);
mdo = most(mdi, mpopt);
% mdo
% mdo.QP
% mdo.QP.f
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -340850, 5, [t 'f']);
rr = mdo.flow(1,1,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [190; 0; 60; -350; 100], 6, [t 'Pg base']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
% t_is(rr.bus(:, LAM_P), [20; 20; 20], 7, [t 'lam P base']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow base']);
if create_plots
    lamP(:, j) = rr.bus(:, LAM_P);
    muF(:, j)  = rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr1 = rr;
rr = mdo.flow(1,1,2).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [190; 0; 60; -350; 100], 5, [t 'Pg 1']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr1.bus(:, LAM_P) + rr.bus(:, LAM_P), [25; 25; 25], 7, [t 'lam P base + lam P 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow 1']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,1,3).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [190; 0; 60; -300; 50], 5, [t 'Pg 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 40], 7, [t 'lam P 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 40], 7, [t 'mu flow 2']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = mdo.results.Rpp + mdo.results.Pc - mdo.results.ExpectedDispatch;
    Rm(:, j) = mdo.results.Rpm - mdo.results.Pc + mdo.results.ExpectedDispatch;
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
    j = j + 1;
end

t = sprintf('%s : Stochastic DC OPF (w/wind,res) : c3sopf ', solvers{s});
nt = 1;
nj = 3;
% transmat = transmatnormalpersistent(nt, nj);
transmat = {[0.158655253931457; 0.682689492137086; 0.158655253931457]};
profiles = getprofiles(uniformwindprofile(nt, nj), iwind);

pp = transmat{1};
%% contingency table
% label probty  type            row             column          chgtype newvalue
contab0 = [
    1   pp(1)   profiles.table  profiles.rows   profiles.col    profiles.chgtype  profiles.values(1)/profiles.values(2);
    3   pp(3)   profiles.table  profiles.rows   profiles.col    profiles.chgtype  profiles.values(3)/profiles.values(2);
];
mpc1 = mpc;
mpc1.gen(iwind, PMAX) = mpc1.gen(iwind, PMAX) * profiles.values(2);
mpc1.gen(3, GEN_STATUS) = 0;
wind = loadgenericdata('ex_wind_uc', 'struct', 'gen', 'wind');
offers = [xgd_table.data; wind.xgd_table.data(:, [3:8])];
% mpopt.verbose = 2;
% mpopt.out.all = -1;
r = c3sopf(mpc1, offers, contab0, mpopt);
t_ok(r.success, [t 'success']);
t_is(r.opf_results.f, -341928.605134, 5, [t 'f']);
rr = r.cont(1);
% rr.gen(:, PG)
% rr.bus(:, LAM_P)
% rr.branch(:, MU_SF) + rr.branch(:, MU_ST)
t_is(rr.gen(:, PG), [200; 150; 0; -350; 0], 7, [t 'Pg 1']);
t_is(rr.bus(:, LAM_P), [4.7596576; 4.7596576; 4.7596576], 7, [t 'lam P 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow 1']);
rr = r.base;
t_is(rr.gen(:, PG), [200; 100; 0; -350; 50], 5, [t 'Pg 2']);
t_is(rr.bus(:, LAM_P), [20.4806848; 20.4806848; 20.4806848], 6, [t 'lam P 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 2']);
rr = r.cont(2);
t_is(rr.gen(:, PG), [200; 65; 0; -350; 85], 5, [t 'Pg 3']);
t_is(rr.bus(:, LAM_P), [0; 0; 0], 6, [t 'lam P 3']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow 3']);

t = sprintf('%s : Stochastic DC OPF (w/wind,res) : most ', solvers{s});
mdi = loadmd(mpc, transmat, xgd, [], [], profiles);
mdo = most(mdi, mpopt);
% mdo
% mdo.QP
% mdo.QP.f
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -341928.605134, 6, [t 'f']);
rr = mdo.flow(1,1,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 150; 0; -350; 0], 7, [t 'Pg 1']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 0; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [4.7596576; 4.7596576; 4.7596576], 7, [t 'lam P 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow 1']);
if create_plots
    lamP(:, j) = rr.bus(:, LAM_P);
    muF(:, j)  = rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,2,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 100; 0; -350; 50], 7, [t 'Pg 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 0; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [20.4806848; 20.4806848; 20.4806848], 6, [t 'lam P 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 2']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,3,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 65; 0; -350; 85], 5, [t 'Pg 3']);
t_is(rr.gen(:, GEN_STATUS), [1; 1; 0; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 0], 6, [t 'lam P 3']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 7, [t 'mu flow 3']);
if create_plots
    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = mdo.results.Rpp + mdo.results.Pc - mdo.results.ExpectedDispatch;
    Rm(:, j) = mdo.results.Rpm - mdo.results.Pc + mdo.results.ExpectedDispatch;
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
    j = j + 1;
end
% keyboard;

t = sprintf('%s : Secure Stochastic DC OPF (w/wind,cont,res,ramp) : most ', solvers{s});
mdi = loadmd(mpc, transmat, xgd, [], contab, profiles);
mdo = most(mdi, mpopt);
% mdo
% mdo.QP
% mdo.QP.f
t_ok(mdo.QP.exitflag > 0, [t 'success']);
t_is(mdo.QP.f, -338857.9224447, 4, [t 'f']);
% fprintf('%.7f\n', mdo.QP.f);

rr = mdo.flow(1,1,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 150; -350; 0], 7, [t 'Pg 1 base']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
% t_is(rr.bus(:, LAM_P), [7.2115891; 7.2115891; 7.2115891], 6, [t 'lam P 1 base']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 2, [t 'mu flow 1 base']);
if create_plots
    lamP(:, j) = rr.bus(:, LAM_P);
    muF(:, j)  = rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr1 = rr;
rr = mdo.flow(1,1,2).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 150; -350; 0], 4, [t 'Pg 1 1']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
% t_is(rr.bus(:, LAM_P), [0.3807726; 0.3807726; 0.3807726], 7, [t 'lam P 1 1']);
t_is(rr1.bus(:, LAM_P) + rr.bus(:, LAM_P), [7.5923617; 7.5923617; 7.5923617], 7, [t 'lam P 1 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 1 1']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,1,3).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 100; -300; 0], 4, [t 'Pg 1 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0.2538484; 0.2538484; 6.3462102], 6, [t 'lam P 1 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 6.0923618], 6, [t 'mu flow 1 2']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,2,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 100; -350; 50], 6, [t 'Pg 2 base']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [24.5768217; 24.5768217; 24.5768217], 6, [t 'lam P 2 base']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 2 base']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,2,2).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 100; -350; 50], 6, [t 'Pg 2 1']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [1.6384548; 1.6384548; 1.6384548], 6, [t 'lam P 2 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 2 1']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,2,3).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 60; -300; 40], 6, [t 'Pg 2 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 27.3075797], 5, [t 'lam P 2 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 27.3075797], 6, [t 'mu flow 2 2']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,3,1).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 60; -350; 90], 6, [t 'Pg 3 base']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 0], 6, [t 'lam P 3 base']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 5, [t 'mu flow 3 base']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,3,2).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 60; -350; 90], 6, [t 'Pg 3 1']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 0], 6, [t 'lam P 3 1']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 0], 6, [t 'mu flow 3 1']);
if create_plots
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
end

rr = mdo.flow(1,3,3).mpc;
% fprintf('[%.7f; %.7f; %.7f; %.7f; %.7f]\n', rr.gen(:, PG));
% fprintf('[%d; %d; %d; %d; %d]\n', rr.gen(:, GEN_STATUS));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.bus(:, LAM_P));
% fprintf('[%.7f; %.7f; %.7f]\n', rr.branch(:, MU_SF) + rr.branch(:, MU_ST));
t_is(rr.gen(:, PG), [200; 0; 60; -300; 40], 4, [t 'Pg 3 2']);
t_is(rr.gen(:, GEN_STATUS), [1; 0; 1; 1; 1], 7, [t 'u']);
t_is(rr.bus(:, LAM_P), [0; 0; 6.3462102], 5, [t 'lam P 3 2']);
t_is(rr.branch(:, MU_SF) + rr.branch(:, MU_ST), [0; 0; 6.3462102], 6, [t 'mu flow 3 2']);
% keyboard;
end

if create_plots
    create_plots = 0;   %% don't do them again

    Pg(:, j) = mdo.results.ExpectedDispatch;
    Rp(:, j) = mdo.results.Rpp + mdo.results.Pc - mdo.results.ExpectedDispatch;
    Rm(:, j) = mdo.results.Rpm - mdo.results.Pc + mdo.results.ExpectedDispatch;
    lamP(:, j) = lamP(:, j) + rr.bus(:, LAM_P);
    muF(:, j)  = muF(:, j) + rr.branch(:, MU_SF) + rr.branch(:, MU_ST);
%    R(4:5, :) = NaN;
    R = Rp + Rm;

    labels = {'Economic Dispatch'; 'DC OPF'; 'Economic Dispatch w/reserves'; 'DC OPF w/reserves'; 'secure DC OPF'; 'stochastic DC OPF'; 'secure stochastic DC OPF'};

    figure(1);

    subplot(4, 1, 1);
    bar(abs(Pg([1:3 5],:)'),'stacked');
    title('Generation');
    ylabel('MW');
    h = gca;
    h.XTickLabel = labels;
    h.XTickLabelRotation = 20;

    subplot(4, 1, 2);
    bar(abs(R([1:3 5],:)'),'stacked');
    title('Reserves');
    ylabel('MW');
    h = gca;
    h.XTickLabel = labels;
    h.XTickLabelRotation = 20;

    subplot(4, 1, 3);
    plot(lamP');
    title('Nodal Prices');
    ylabel('$/MW');
    h = gca;
    h.XTickLabel = {'', labels{:}, ''}';
    h.XTickLabelRotation = 20;
    h = [0 8 0 100];
    axis(h);

    subplot(4, 1, 4);
    plot(muF');
    title('Flow Constraint Shadow Prices');
    ylabel('$/MW');
    h = gca;
    h.XTickLabel = {'', labels{:}, ''}';
    h.XTickLabelRotation = 20;
    h = [0 8 0 60];
    axis(h);

    if create_pdfs
        fname = 'single-period-uc';
        h = gcf;
        set(h, 'PaperSize', [11 8.5]);
        set(h, 'PaperPosition', [0.25 0.25 10.5 8]);
        print('-dpdf', fullfile(savedir, fname));
    end

    for j = 1:7;
        figure(j+1);
        if create_pdfs
            fname = sprintf('single-period-uc-%d', j);
        else
            fname = '';
        end
        plot_case(labels{j}, Pg([1:3 5], j), Rp([1:3 5], j), Rm([1:3 5], j), lamP(:, j), muF(:, j), 250, 100, savedir, fname);
    end
end
end

t_end;

function h = plot_case(label, Pg, Rp, Rm, lamP, muF, maxq, maxp, mypath, fname)

subplot(1, 3, 1);
h = bar([Pg-Rm Rm Rp], 'stacked');
set(h(2), 'FaceColor', [0 0.35 0.33]);
ah1 = gca;
title('Generation & Reserves');
ylabel('MW');
xlabel('Gen');
set(gca, 'FontSize', 14);

if nargin < 6
    maxq = ah1.YLim(2);
end
ah1.YLim(2) = maxq;
ah1.YLim(1) = 0;

subplot(1, 3, 2);
bar(lamP);
ah3 = gca;
title('Nodal Prices');
ylabel('$/MW');
xlabel('Bus');
set(gca, 'FontSize', 14);

subplot(1, 3, 3);
bar(muF);
ah4 = gca;
title('Flow Constraint Shadow Prices');
ylabel('$/MW');
xlabel('Line');
set(gca, 'FontSize', 14);

if nargin < 7
    maxp = max(ah3.YLim(2), ah4.YLim(2));
end
ah3.YLim(1) = 0;
ah4.YLim(1) = 0;
ah3.YLim(2) = maxp;
ah4.YLim(2) = maxp;

[ax,h] = suplabel(label, 't');
set(h, 'FontSize', 18)

if nargin > 7 && ~isempty(fname)
    h = gcf;
    set(h, 'PaperSize', [11 8.5]);
    set(h, 'PaperPosition', [0.25 0.25 10.5 8]);
    print('-dpdf', fullfile(mypath, fname));
end


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

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'PAC: Z-score with surrogate';
    sProcess.FileTag     = '';
    sProcess.Category    = 'Custom';
    sProcess.SubGroup    = 'Standardize';%{'Frequency','Time-resolved Phase-Amplitude Coupling'};
    sProcess.Index       = 1020;
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'timefreq'};
    sProcess.OutputTypes = {'timefreq'};
    sProcess.nInputs     = 2;
    sProcess.nMinFiles   = 1;
    sProcess.isPaired    = 1;
    sProcess.isSeparator = 0;

%     % === ANALYSIS TO BE DONE
%     sProcess.options.label.Comment = 'Analysis:';
%     sProcess.options.label.Type    = 'label';
%     sProcess.options.analyze_type.Comment = {'Mean (Over sources)', ...
%         'Median (Over sources)','Z-score on time (If no negative time, on total recording)', ...
%         'Mean (Over time)'};
%     sProcess.options.analyze_type.Type    = 'radio';
%     sProcess.options.analyze_type.Value   = 1;

    % === Label
    sProcess.options.label.Comment = 'Mean on sources: Files A Z-scored with respect to Files B

';
    sProcess.options.label.Type    = 'label';
    % === Using phase
    sProcess.options.usePhase.Comment = 'Use phase in averaging (mean)';
    sProcess.options.usePhase.Type    = 'checkbox';
    sProcess.options.usePhase.Value   = 0;

end

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

%% ===== RUN =====
function sOutput = Run(sProcess, sInputsA, sInputsB)  %#ok<DEFNU>
%     sOutput = sInputsA;
%     % Colormap
%     sOutput.ColormapType = 'stat2';
%     % Time-frequency: Change the measure type
%     if strcmpi(sInputsA(1).FileType, 'timefreq')
%         sOutput.Measure = 'other';
%     end

    usePhase = sProcess.options.usePhase.Value;
    tag = '|sur-zscore';

%     % Load first TF file
%     tpacMat = in_bst_timefreq(sInputs(1).FileName, 0);
%     % Error
%     if isempty(tpacMat)
%         bst_report('Error', sProcess, sInput, Messages);
%         return;
%     end

    N = length(sInputsA);
    for iFile = 1:N
        tpac = in_bst_timefreq(sInputsA(iFile).FileName, 0);
        tpac_sur = in_bst_timefreq(sInputsB(iFile).FileName, 0);
        if usePhase
            tmp1 = abs(mean(tpac.sPAC.DynamicPAC.*exp(1i*tpac.sPAC.DynamicPhase),1));
            tmp2 = abs(mean(tpac_sur.sPAC.DynamicPAC.*exp(1i*tpac_sur.sPAC.DynamicPhase),1));
        else
            tmp1 = abs(mean(tpac.sPAC.DynamicPAC,1));
            tmp2 = abs(mean(tpac_sur.sPAC.DynamicPAC,1));
        end

        tpac.sPAC.DynamicPAC  = (tmp1 - mean(tmp2,4))./std(tmp2, [],4);
        if usePhase
            tpac.sPAC.DynamicPhase  = angle(mean(tpac.sPAC.DynamicPAC.*exp(1i*tpac.sPAC.DynamicPhase),1));
        else
            tpac.sPAC.DynamicPhase  = [];
        end

        tpac.TF = tpac.sPAC.DynamicPAC;
        %Saving the files
        tpac.Comment = [tpac.Comment, ' ', tag];
        % Output filename: add file tag
        FileTag = strtrim(strrep(tag, '|', ''));
        pathName = file_fullpath(sInputsA(iFile).FileName);
        sOutput{1} = strrep(pathName, '.mat', ['_' FileTag '.mat']);
        sOutput{1} = file_unique(sOutput{1});
        % Save file
        bst_save(sOutput{1}, tpac, 'v6');
        % Add file to database structure
        db_add_data(sInputsA(iFile).iStudy, sOutput{1}, tpac);
    end

end


function [mesh, edge_to_vertex, edge_to_face] = geodesic_new_mesh(points, tri)

global geodesic_library
if ~libisloaded(geodesic_library)
    hfile = 'geodesic_matlab_api.h';
    loadlibrary([geodesic_library '.so'], hfile);
end

dim = find(size(points) == 3);
if dim == 1
    p = points(:);
else
    p = points';
    p = p(:);
end;

dim = find(size(tri) == 3);
if dim == 1
    t = tri(:) - 1;
else
    t = tri';
    t = t(:) - 1;
end;

tmp = libpointer('doublePtrPtr');
[id, tmp1, tmp2, num_edges, edges] = calllib(geodesic_library, 'new_mesh', length(p)/3, p, length(t)/3, t, 1, tmp);
setdatatype(edges, 'doublePtr', 4, num_edges);

mesh.id = id;
mesh.object_type = 'mesh';
edge_to_vertex = (edges.Value(1:2,:) + 1)';
edge_to_face = (edges.Value(3:4,:) + 1)';


function test_tutorial_clusterpermutationfreq(dataset, datadir)

% MEM 3gb
% WALLTIME 00:10:00
% DEPENDENCY ft_freqanalysis ft_multiplotTFR ft_singleplotTFR ft_freqstatistics ft_topoplotTFR ft_clustTFRplot ft_megplanar ft_combineplanar

if nargin==0
  dataset = dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf/Subject01.ds');
  datadir = dccnpath('/home/common/matlab/fieldtrip/data/ftp/tutorial/cluster_permutation_freq');
end

%% PREprocessing
% find the interesting segments of data
cfg = [];                                    % empty configuration
cfg.dataset                 = dataset;       % name of CTF dataset
cfg.trialdef.eventtype      = 'backpanel trigger';
cfg.trialdef.prestim        = 1;
cfg.trialdef.poststim       = 2;
cfg.trialdef.eventvalue     = 3;                    % event value of FIC
cfg = ft_definetrial(cfg);

% remove the trials that have artifacts from the trl
cfg.trl([15, 36, 39, 42, 43, 49, 50, 81, 82, 84],:) = [];

% preprocess the data
cfg.channel   = {'MEG', '-MLP31', '-MLO12'};        % read all MEG channels except MLP31 and MLO12
cfg.demean    = 'yes';                              % do baseline correction with the complete trial

dataFIC = ft_preprocessing(cfg);

% find the interesting segments of data
cfg = [];                                           % empty configuration
cfg.dataset                 = dataset;       % name of CTF dataset
cfg.trialdef.eventtype      = 'backpanel trigger';
cfg.trialdef.prestim        = 1;
cfg.trialdef.poststim       = 2;
cfg.trialdef.eventvalue     = 9;                    % event value of FC
cfg = ft_definetrial(cfg);

% remove the trials that have artifacts from the trl
cfg.trl([2, 3, 4, 30, 39, 40, 41, 45, 46, 47, 51, 53, 59, 77, 85],:) = [];

% preprocess the data
cfg.channel   = {'MEG', '-MLP31', '-MLO12'};        % read all MEG channels except MLP31 and MLO12
cfg.demean    = 'yes';                              % do baseline correction with the complete trial

dataFC = ft_preprocessing(cfg);

%% planar gradient and TFA
cfg = [];
cfg.planarmethod = 'sincos';
% prepare_neighbours determines with what sensors the planar gradient is computed
cfg_neighb.method    = 'distance';
cfg.neighbours       = ft_prepare_neighbours(cfg_neighb, dataFC);

dataFIC_planar = ft_megplanar(cfg, dataFIC);
dataFC_planar  = ft_megplanar(cfg, dataFC);

cfg = [];
cfg.output     = 'pow';
cfg.channel    = 'MEG';
cfg.method     = 'mtmconvol';
cfg.taper      = 'hanning';
cfg.foi        = 20;
cfg.toi        = [-1:0.05:2.0];
cfg.t_ftimwin  = 7./cfg.foi; %7 cycles
cfg.keeptrials = 'yes';

freqFC_planar  = ft_freqanalysis(cfg, dataFC_planar);
freqFIC_planar = ft_freqanalysis(cfg, dataFIC_planar);

cfg = [];
freqFIC_planar_cmb = ft_combineplanar(cfg, freqFIC_planar);
freqFC_planar_cmb = ft_combineplanar(cfg, freqFC_planar);

freqFIC_planar_cmb.grad = dataFIC.grad;
freqFC_planar_cmb.grad = dataFC.grad;

%% Permutation test
cfg = [];
cfg.channel          = {'MEG'};
cfg.latency          = 'all';
cfg.frequency        = 20;
cfg.method           = 'montecarlo';
cfg.statistic        = 'ft_statfun_indepsamplesT';
cfg.correctm         = 'cluster';
cfg.clusteralpha     = 0.05;
cfg.clusterstatistic = 'maxsum';
cfg.minnbchan        = 2;
cfg.tail             = 0;
cfg.clustertail      = 0;
cfg.alpha            = 0.025;
cfg.numrandomization = 500;
% prepare_neighbours determines what sensors may form clusters
cfg_neighb.method    = 'distance';
cfg.neighbours       = ft_prepare_neighbours(cfg_neighb, dataFC);

design = zeros(1,size(freqFIC_planar_cmb.powspctrm,1) + size(freqFC_planar_cmb.powspctrm,1));
design(1,1:size(freqFIC_planar_cmb.powspctrm,1)) = 1;
design(1,(size(freqFIC_planar_cmb.powspctrm,1)+1):(size(freqFIC_planar_cmb.powspctrm,1)+...
  size(freqFC_planar_cmb.powspctrm,1))) = 2;

cfg.design           = design;
cfg.ivar             = 1;

[stat] = ft_freqstatistics(cfg, freqFIC_planar_cmb, freqFC_planar_cmb);

%% Plotting the results
cfg = [];
cfg.jackknife = 'no';
freqFIC_planar_cmb = ft_freqdescriptives(cfg, freqFIC_planar_cmb);
freqFC_planar_cmb  = ft_freqdescriptives(cfg, freqFC_planar_cmb);

stat.raweffect = freqFIC_planar_cmb.powspctrm - freqFC_planar_cmb.powspctrm;
cfg = [];
cfg.alpha  = 0.025;
cfg.parameter = 'raweffect';
cfg.zlim   = [-1e-27 1e-27];
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg, stat);

%% Prepropcessing and freqanalysis on planar data
cfg = [];
cfg.toilim = [-1.0 0];
dataFIC_baseline = ft_redefinetrial(cfg, dataFIC);

cfg = [];
cfg.toilim = [0.6 1.6];
dataFIC_activation = ft_redefinetrial(cfg, dataFIC);

dataFIC_baseline.time = dataFIC_activation.time;

cfg = [];
cfg.planarmethod = 'sincos';
% prepare_neighbours determines with what sensors the planar gradient is computed
cfg_neighb.method    = 'distance';
cfg.neighbours       = ft_prepare_neighbours(cfg_neighb, dataFIC_activation);
dataFIC_activation_planar = ft_megplanar(cfg, dataFIC_activation);
dataFIC_baseline_planar   = ft_megplanar(cfg, dataFIC_baseline);

cfg = [];
cfg.output = 'pow';
cfg.channel = 'MEG';
cfg.method = 'mtmconvol';
cfg.taper = 'hanning';
cfg.foi = 20;
cfg.toi = [0.6:0.05:1.6];
cfg.t_ftimwin = 7./cfg.foi; %7 cycles
cfg.keeptrials = 'yes';

freqFIC_activation_planar = ft_freqanalysis(cfg, dataFIC_activation_planar);
freqFIC_baseline_planar   = ft_freqanalysis(cfg, dataFIC_baseline_planar);

cfg = [];
freqFIC_baseline_planar_cmb   = ft_combineplanar(cfg,freqFIC_baseline_planar);
freqFIC_activation_planar_cmb = ft_combineplanar(cfg,freqFIC_activation_planar);

freqFIC_baseline_planar_cmb.grad   = dataFIC.grad;
freqFIC_activation_planar_cmb.grad = dataFIC.grad;

%% Permutation test
cfg = [];
cfg.channel          = {'MEG', '-MLP31', '-MLO12'};
cfg.channel          = {'MEG'};
cfg.latency          = [0.8 1.4];
cfg.method           = 'montecarlo';
cfg.frequency        = 20;
cfg.statistic        = 'ft_statfun_actvsblT';
cfg.correctm         = 'cluster';
cfg.clusteralpha     = 0.05;
cfg.clusterstatistic = 'maxsum';
cfg.minnbchan        = 2;
cfg.tail             = 0;
cfg.clustertail      = 0;
cfg.alpha            = 0.025;
cfg.numrandomization = 500;
% prepare_neighbours determines what sensors may form clusters
cfg_neighb.method    = 'distance';
cfg.neighbours       = ft_prepare_neighbours(cfg_neighb, freqFIC_activation_planar_cmb);

ntrials = size(freqFIC_activation_planar_cmb.powspctrm,1);
design  = zeros(2,2*ntrials);
design(1,1:ntrials) = 1;
design(1,ntrials+1:2*ntrials) = 2;
design(2,1:ntrials) = [1:ntrials];
design(2,ntrials+1:2*ntrials) = [1:ntrials];

cfg.design   = design;
cfg.ivar     = 1;
cfg.uvar     = 2;

[stat] = ft_freqstatistics(cfg, freqFIC_activation_planar_cmb, freqFIC_baseline_planar_cmb);

%% Plotting the results
cfg = [];
cfg.alpha  = 0.05;
cfg.parameter = 'stat';
cfg.zlim   = [-4 4];
cfg.layout = 'CTF151.lay';
ft_clusterplot(cfg, stat);

%% Within subjects experiment

load(fullfile(datadir, 'GA_TFR_orig.mat'));

cfg = [];
cfg.channel          = {'MEG'};
cfg.latency          = [0 1.8];
cfg.frequency        = 20;
cfg.method           = 'montecarlo';
cfg.statistic        = 'ft_statfun_depsamplesT';
cfg.correctm         = 'cluster';
cfg.clusteralpha     = 0.05;
cfg.clusterstatistic = 'maxsum';
cfg.minnbchan        = 2;
cfg.tail             = 0;
cfg.clustertail      = 0;
cfg.alpha            = 0.025;
cfg.numrandomization = 500;
% specifies with which sensors other sensors can form clusters
cfg_neighb.method    = 'distance';
cfg.neighbours       = ft_prepare_neighbours(cfg_neighb, GA_TFRFC);

subj = 10;
design = zeros(2,2*subj);
for i = 1:subj
  design(1,i) = i;
end
for i = 1:subj
  design(1,subj+i) = i;
end
design(2,1:subj)        = 1;
design(2,subj+1:2*subj) = 2;

cfg.design   = design;
cfg.uvar     = 1;
cfg.ivar     = 2;

failed = true;
for i=1:100 % this can fail sometime, like every second iteration or so, 100 is a *really* conservative number here
  [stat] = ft_freqstatistics(cfg, GA_TFRFIC, GA_TFRFC);

  % Plotting the results
  pcfg = [];
  pcfg.alpha  = 0.025;
  pcfg.parameter = 'stat';
  pcfg.zlim   = [-4 4];
  pcfg.layout = 'CTF151.lay';
  try
    ft_clusterplot(pcfg, stat);
    failed = false;
    break;
  end
end

if failed
  error('ft_clusterplot fails cause p was too high');
end


function res = Profile_Horn_res(p,  doseProfile1, xIndexStart, xIndexEnd, yIndex, s, ICsigma, hornOffAxis, fractionEF, varargin)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR 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.
%
% CERR 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 CERR.  If not, see <http://www.gnu.org/licenses/>.

% p(1) := calibration constant = 25. (to scale DPM dose to 1cGy/MU at
% depth = 1.5cm for field size 10x10cm2, at 100SSD.

% p(2) := horn at atan( 2.5/100);
% p(3) := horn at atan( 5.0/100);
% p(4) := horn at atan( 7.5/100);
% p(5) := horn at atan(10.0/100);
% p(6) := horn at atan(15.0/100);
% p(7) := horn at atan(20.0/100);
% p(8) := horn at atan(28.5/100);

if length(varargin) == 2
    IM = varargin{1};
    FS = varargin{2};
else
    % When called by 'fimsearch(FUN, x0)', varargin's elements turns into cell from struct.
    IM = varargin{1}{1};
    FS = varargin{1}{2};
end

% Get the horn based on
hornCoef = [0, p(2:end)];
offAxis = [0:0.1:28.5];
test = interp1(hornOffAxis, hornCoef, offAxis);

% get off-axis-distance at 100 cm SSD.
PBOffAxis = sqrt(IM.beams.xPBPosV.^2 + IM.beams.yPBPosV.^2);
w_field = 1 + interp1(offAxis, test, PBOffAxis);
% Correction for isotropic derive
% IM2isoCorrection = (cos(atan(PBOffAxis/IM.beams.isodistance)).^2);
% w_field = w_field .* IM2isoCorrection;

% Now this is only Primary photon contribution.
IM.beamlets = IM.beamletsPrimary;
tic; [dose3D] = getIMDose(IM, w_field, 1); toc
% Use Issam's code to do the denoising.
% Denoising part.
%! dose3D = max(dose3D(:))*anisodiff3d_miao_exp(dose3D/max(dose3D(:)), 0.03, 4);

 % Get the Extra-focal contribution.
IM.beamlets = IM.beamletsFF;
tic; [dose3D_FF] = getIMDose(IM,[], 1); toc
% Denoising.
%! dose3D_FF = max(dose3D_FF(:))*anisodiff3d_miao_exp(dose3D_FF/max(dose3D_FF(:)), 0.03, 4);

% Add dose3D and dose3D_FF together.
dose3D = dose3D + fractionEF * dose3D_FF;

% Scale dose up by p(1) to match with the measurements.
doseProfile1_DPM = p(1)*dose3D(yIndex, xIndexStart:xIndexEnd, int16(s));

%Start the function.
%Calculate the residue of the PDD and dose profile difference between DPM and the measurement.
diffsqr = sum((doseProfile1 - doseProfile1_DPM).^2);
res = sqrt(diffsqr)
return;


function cascade_data(model, data_year, pca_dim)
% cascade_data(model, data_year, pca)
%
% Compute score statistics for filters and deformation models
% using the model and training data associated with the model
% and dataset year 'data_year'.  If PCA is given a value > 0, then
% the score statistics are computed using a PCA projection of the
% model and training data.
%
% The score statistics are written in to the file
% class_year_cascade_data_{no_pca,pca_<pca_dim>}_data_year.mat,
% which is used by cascade_model.m.
%
% model      Object model
% data_year  Dataset year as a string (e.g., '2007')
% pca_dim    Number of PCA components to use

% AUTORIGHTS
% -------------------------------------------------------
% Copyright (C) 2009-2012 Ross Girshick
%
% This file is part of the voc-releaseX code
% (http://people.cs.uchicago.edu/~rbg/latent/)
% and is available under the terms of an MIT-like license
% provided in COPYING. Please retain this notice and
% COPYING if you use this file (or a portion of it) in
% your project.
% -------------------------------------------------------

conf = voc_config();
cscdir = conf.cascade.data_dir;

model.interval = conf.training.interval_fg;

% get training data
pos = pascal_data(model.class, model.year);

%[model, pca_model] = project_model_adapt(model, pca_dim);
% Loads <coeff>
load('pca.mat');
[model, pca_model] = project_model(model, coeff, pca_dim);

numpos  = length(pos);
pixels  = model.minsize * model.sbin / 2;
minsize = prod(pixels);
pars    = cell(1, numpos);

% compute latent filter locations and record target bounding boxes
parfor i = 1:numpos
  pars{i}.scores           = [];
  pars{i}.pca_scores       = [];
  pars{i}.total_scores     = [];
  pars{i}.total_pca_scores = [];
  fprintf('%s %s: cascade data: %d/%d\n', procid(), model.class, i, numpos);
  bbox = pos(i).boxes;
  % skip small examples
  if (bbox(3)-bbox(1)+1)*(bbox(4)-bbox(2)+1) < minsize
    continue;
  end
  % get example
  im = imreadx(pos(i));
  [im, bbox] = croppos(im, bbox);
  [pyra, model_dp] = gdetect_pos_prepare(im, model, bbox, 0.5);
  [ds, bs, trees] = gdetect_pos(pyra, model_dp, 1, 1, 0.5);
  if ~isempty(ds)
    % collect cascade score statistics
    pars{i}.scores = get_block_scores(pyra, model, trees);
    pars{i}.total_scores = ds(1,end);

    % Valid root location for the PCA model
    t = tree_mat_to_struct(trees{1});
    valid = [];
    valid.c = t(1).rule_index;
    valid.y = t(1).y;
    valid.x = t(1).x;
    valid.l = t(1).l;

    % Get detection with PCA model restricted to the root filter being placed
    % exactly where the original model's root filter was placed
    [pca_pyra, pca_model_dp] = gdetect_pos_prepare_c(im, pca_model, valid);
    [ds, bs, trees] = gdetect_pos_c(pca_pyra, pca_model_dp, valid);

    % Sanity check
    t = tree_mat_to_struct(trees{1});
    assert(valid.c == t(1).rule_index);
    assert(valid.y == t(1).y);
    assert(valid.x == t(1).x);
    assert(valid.l == t(1).l);

    pars{i}.pca_scores = get_block_scores(pca_pyra, pca_model, trees);
    pars{i}.total_pca_scores = ds(1,end);
  end
end
% Collate
pars = cell2mat(pars);
scores = cat(1, pars(:).scores);
pca_scores = cat(1, pars(:).pca_scores);

% Sanity check that detection scores match sum of block scores
% computed in get_block_scores
total_scores = cat(1, pars(:).total_scores);
total_pca_scores = cat(1, pars(:).total_pca_scores);
assert(max(abs(scores(:,1) - total_scores)) < 1e-5);
assert(max(abs(pca_scores(:,1) - total_pca_scores)) < 1e-5);

% Save cascade score statistics
class_year = [model.class '_' model.year];
file     = [cscdir class_year '_cascade_data_no_pca_' model.year];
pca_file = [cscdir class_year '_cascade_data_pca_' num2str(pca_dim) ...
            '_' model.year];
save(file, 'scores');
save(pca_file, 'pca_scores');