function varargout = pwq_yalmip(varargin)
%PWQ_YALMIP Defines a piecewise quadratic function using data from MPT
%
%Only intended for internal use in YALMIP
%
% Currently only a container for PWQ functions. Can not be
% used in actual optmization problem.

switch class(varargin{1})

    case {'struct','cell'} % Should only be called internally

        if isa(varargin{2},'double')
            % Called from YALMIP to get double
            pwastruct = varargin{1};
            x = varargin{2};
            index = varargin{5};

            val = inf;
            for i = 1:length(pwastruct)
                [ii,jj] = isinside(pwastruct{i}.Pn,x);
                if ii
                    for k = 1:length(jj)
                        Q = pwastruct{i}.Ai{jj(k)};
                        if index>1 | min(size(pwastruct{i}.Bi{jj(k)}))>1
                            % FIX: Why?? Where is this feature used
                            val = min(val,x'*Q*x + reshape(pwastruct{i}.Bi{jj(k)}(index,:),1,[])*x+pwastruct{i}.Ci{jj(k)}(index));
                        else
                            val = min(val,x'*Q*x + reshape(pwastruct{i}.Bi{jj(k)},1,[])*x+pwastruct{i}.Ci{jj(k)});
                        end
                    end
                end
            end
            if isinf(val)
                val = nan;
            end
            varargout{1} = min(val);
            return
        end

        if nargin<3
            pwaclass = 'general'
        end

        if isa(varargin{1},'struct')
            varargin{1} = {varargin{1}};
        end

        % Put in standard format
        if ~isfield(varargin{1}{1},'Bi')
            if ~isfield(varargin{1}{1},'Fi')
                error('Wrong format on input to PWQ (requires Bi or Fi)');
            else
                for i = 1:length(varargin{1})
                    varargin{1}{1}.Ai = cell(1, varargin{1}{i}.Fi);
                    varargin{1}{i}.Bi = varargin{1}{i}.Fi
                    varargin{1}{i}.Ci = varargin{1}{i}.Gi
                end
            end
        end

        if ~isfield(varargin{1}{1},'Pfinal')
            error('Wrong format on input to PWQ (requires field Pn)');
        end

        % This will be a container for binary variables in the furture
        varargin{end+1} = binvar(length(varargin{1}{1}.Pn),1);

        % Create one variable for each row
        % Inefficient but the only way currently in YALMIP
        varargout{1} = [];
        varargin{end+1} = 1;

        for i = 1:length(varargin{1}{1}.Ci{1})
            varargin{end} = i;
            varargout{1} = [varargout{1};yalmip('define',mfilename,varargin{:})];
        end

    case 'char' % YALMIP sends 'model' when it wants the epigraph or hypograph

        switch varargin{1}

            case 'graph'

                varargout{1} = [];
                varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none');
                varargout{3} = [];

            case {'integer','exact'}

                % FIX : Should create case for overlapping convex PWAs,
                % used in a nonconvex fashion...

                % Can only generate the first class of PWA functions
                t     = varargin{2};     % The YALMIP variables modelling this pwa
                pwq_struct = varargin{3};% MPT structure
                x     = varargin{4};     % Argument
                flag  = varargin{5};     % Type of PWA function
                d     = varargin{6};     % Binary for nonconvex cases
                index = varargin{7};     % Which row in Bix+Ci

                switch flag

                    case {'general','convex'}

                        if length(d)==1
                            % Don't introduce any binary variables when
                            % there is only one quadratic cost
                            F = ([]);
                            cost = x'*pwq_struct{1}.Ai{1}*x+pwq_struct{1}.Bi{1}*x+pwq_struct{1}.Ci{1};
                        else
                            n = length(x);
                            m = length(d);
                            z = sdpvar(n,m,'full');
                            F = (sum(d) == 1);
                            cost = 0;
                            [Mm,mm] = derivebounds(x);
                            try
                                [aux,mx,Mx] = bounding_box(pwq_struct{1}.Pfinal);
                            catch
                                Mx = 10000*ones(length(x),1);
                                mx = -10000*ones(length(x),1);
                            end
                            Mx = min([Mx Mm],[],2);
                            mx = max([mx mm],[],2);
                            for i = 1:m
                                %    bounds(z(:,i),mx,Mx);
                                F = F + (-(Mx-mx)*(1-d(i)) <= z(:,i)-x <= (Mx-mx)*(1-d(i)));
                                F = F + (mx*d(i) <= z(:,i) <= Mx*d(i));
                                [H,K] = double(pwq_struct{1}.Pn(i));
                                [M,m]  = derivebounds(H*x-K);
                                F = F + (H*x-K <= M*(1-d(i)));
                                cost = cost + z(:,i)'*pwq_struct{1}.Ai{i}*z(:,i)+pwq_struct{1}.Bi{i}(:)'*z(:,i)+d(i)*pwq_struct{1}.Ci{i};
                            end
                        end

                        varargout{1} = F;
                        varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none','model','integer');
                        varargout{2}.replacer = cost;
                        varargout{3} = x;

                    case {'convexoverlapping'}

                        n = length(x);
                        cost = 0;
                        r = binvar(length(pwq_struct),1);
                        d = {};

                        % Derive bounds from polytopes
                        [aux,mx,Mx] = bounding_box(pwq_struct{1}.Pfinal);
                        for i = 2:length(pwq_struct)
                            [aux,L,U] = bounding_box(pwq_struct{i}.Pfinal);
                            Mx = max([Mx U],[],2);
                            mx = min([mx L],[],2);
                        end
                        bounds(x,mx,Mx);

                        % Some overlapping function is active
                        % (it will automatically be the smallest one)
                        F = (sum(r) == 1);
                        for j = 1:length(pwq_struct)

                            if length(pwq_struct{j}.Pn) == 1
                                d{j} = r(j);
                            else
                                d{j} = binvar(length(pwq_struct{j}.Pn),1);
                                F = F + (sum(d{j}) == r(j));
                            end
                            m = length(d{j});
                            z = sdpvar(n,m,'full');

                            for i = 1:m
                                bounds(z(:,i),mx,Mx);
                                F = F + (-(Mx-mx)*(1-d{j}(i)) <= z(:,i)-x <= (Mx-mx)*(1-d{j}(i)));
                                F = F + (mx*d{j}(i) <= z(:,i) <= Mx*d{j}(i));
                                [H,K] = double(pwq_struct{j}.Pn(i));
                                [M,m]  = derivebounds(H*x-K);
                                F = F + (H*x-K <= M*(1-d{j}(i)));
                                cost = cost + z(:,i)'*pwq_struct{j}.Ai{i}*z(:,i)+pwq_struct{j}.Bi{i}*z(:,i)+d{j}(i)*pwq_struct{j}.Ci{i};
                            end
                        end

                        varargout{1} = F;
                        varargout{2} = struct('convexity','none','monotoncity','none','definiteness','none','model','integer');
                        varargout{2}.replacer = cost;
                        varargout{3} = x;

                    otherwise

                        varargout{1} = [];
                        varargout{2} = struct('convexity','convex','monotoncity','none','definiteness','none');
                        varargout{3} = [];
                        return
                end

            otherwise
                error('PWA_YALMIP called with CHAR argument?');
        end

    otherwise
        error('Strange type on first argument in PWQ_YALMIP');
end


function calcAllSeparateTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,scale_mat,algo_cell,Ng_mat,nBatch,matlabPATH)
% -------------------------------------------------------------------------
% function calcAllSeparateTextures_batchHN(pathData,pathText,namePT,nameCT,nameROI,outcomes,featType,scale_mat,Ng_mat,nBatch,matlabPATH)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function computes SEPARATE texture features for all patients, for
% all different combinations of the following texture extraction parameters:
% - Scale: Resolution at which the ROI is isotropically resampled.
% - Quantization algorith: Type of quantization algorithm used.
% - Ng: Number of gray-levels in the quantization process.
%
% Different extraction parameters are passed as arrays or cells in the
% function in order to test all possible combinations. This function is
% used for SEPARATE scans specifically. See Ref. [1,2] and 'prepareVolume.m'
% for more details.
%
% Texture features are computed for all head and neck (HN) DICOM imaging
% data downloaded from The Cancer Imaging Archive (TCIA) website at:
% <http://dx.doi.org/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>, and first organized
% in a 'DATA' directory using the function readAllDICOM_HN.m.  Results are
% then saved in a folder 'TEXTURES' in the HN WORKSPACE.
% -------------------------------------------------------------------------
% REFERENCES:
% [1] Vallieres, M. et al. (2015). FDG-PET/CT radiomics models for the
%     early prediction of different tumour outcomes in head and neck cancer.
%     The Journal of Nuclear Medicine, aa(bb), xxx-yyy.
%     doi:
% [2] Vallieres, M. et al. (2015). A radiomics model from joint FDG-PET and
%     MRI texture features for the prediction of lung metastases in soft-tissue
%     sarcomas of the extremities. Physics in Medicine and Biology, 60(14),
%     5471-5496. doi:10.1088/0031-9155/60/14/5471
% -------------------------------------------------------------------------
% INPUTS:
% 1. pathData: Full path to the HN sData files directory.
%              --> Ex: '/myProject/WORKSPACE/DATA'
% 2. pathText: Full path to the HN non texture features directory.
%              --> Ex: '/myProject/WORKSPACE/FEATURES/TEXTURES'
% 3. namePT: Cell of strings of all PET sData files to read
%            --> Ex: {'HGJ_001_PT.PTscan.mat';'HGJ_022_PT.PTscan.mat'}
% 4. namePT: Cell of strings of all CT sData files to read
%            --> Ex: {'HGJ_001_CT.CTscan.mat';'HGJ_022_CT.CTscan.mat'}
% 5. nameROI: Cell of strings specifying the ROI names to analyze for the
%             patients defined by "namePT" and "nameCT"
%             --> Ex: {'GTV';'GTV-P'}
% 6. outcomes: Structure specifying the status (1 or 0) for different
%              outcomes in HN cancer. Contains: outcomes.Failure,
%              outcomes.Locoregional, outcomes.Distant. See ref.[1] for
%              more details.
% 7. featType: Either 'GTVp' for primary GTV, or 'GTVtot' for primaty GTV +
%              nodal GTVs
%              --> Ex: 'GTVp'
% 8. scale_mat: Array vector specifying the different 'Scale' values to test.
%               --> Ex: [1,2,3,4,5]
% 9. Ng_mat: Array vector specifying the different 'Ng' values to test.
%            --> Ex: [8,16,32,64]
% 10. nBatch: Number of parallel batch.
%             --> Ex: 8
% 11.  matlabPATH: Full path to the MATLAB excutable on the system.
%      --> Ex: 'matlab' (symbolic link)
% -------------------------------------------------------------------------
% AUTHOR(S): Martin Vallieres <mart.vallieres@gmail.com>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: March 2016
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015  Martin Vallieres
%
%    This package is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This package is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this package.  If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------

startpath = pwd;
ind = strfind(namePT{1},'_'); cohortID = namePT{1}(1:ind-1);
cd(pathText), mkdir(['batchLog_',cohortID,'_',featType,'_SepText']), cd(['batchLog_',cohortID,'_',featType,'_SepText']), pathBatch = pwd;
time = 60; % Number of seconds to wait before checking if parallel computations are done
nameOutcomes = fieldnames(outcomes); nOutcomes = numel(nameOutcomes);
scans = {'PT','CT'}; nScans = numel(scans);

% PRODUCE BATCH COMPUTATIONS
nPatient = numel(namePT); valid = ones(nPatient,1);
for i = 1:nPatient
    if isempty(nameROI{i})
        valid(i) = 0;
    end
end
indValid = find(valid); nPatient = numel(indValid);
if nPatient < nBatch
    nBatch = nPatient;
end
[patients] = batchPatients(nPatient,nBatch);
save('workspace','pathData','pathText','namePT','nameCT','nameROI','patients','indValid','featType','scale_mat','algo_cell','Ng_mat'), pause(5);
for i = 1:nBatch
    nameScript = ['batch',num2str(i),'_script.m'];
    fid = fopen(nameScript,'w');
    fprintf(fid,'load(''workspace'')\n');
    fprintf(fid,['calcAllSeparateTextures_HN(pathData,pathText,namePT(indValid(patients{',num2str(i),'})),nameCT(indValid(patients{',num2str(i),'})),nameROI(indValid(patients{',num2str(i),'})),featType,scale_mat,algo_cell,Ng_mat)\n']);
    fprintf(fid,['system(''touch batch',num2str(i),'_end'');\n']);
    fprintf(fid,'clear all');
    fclose(fid);
    system([matlabPATH,' -nojvm -nodisplay -nodesktop -nosplash < ',nameScript,' >& ',nameScript(1:end-1),'log &']);
end

% WAITING LOOP
waitBatch(pathBatch,time,nBatch)
delete('workspace.mat')

% GROUPING RESULTS FROM ALL BATCH
nPatient = numel(namePT);
names = {namePT,nameCT};
for scan = 1:nScans
    cd(pathText)
    if exist(['HGJ_001_',scans{scan},'_',featType,'_text.mat'],'file')
        temp = load(['HGJ_001_',scans{scan},'_',featType,'_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields
    else
        temp = load(['HGJ_001_',scans{scan},'_','GTVp','_text']); temp = struct2cell(temp); temp = temp{1}; % In order to get the necessary 'nameType' and 'nameFeature' fields
    end
    nameType = fieldnames(temp.Experiment1); nameType(end) = []; nType = numel(nameType); % All texture types are the same
    text = cell(numel(scale_mat),numel(algo_cell),numel(Ng_mat));
    tempText = cell(1,nPatient); % Cell used to load patient textures only once
    for p = 1:nPatient
        ind = strfind(names{scan}{p},'.'); namePatientScan = names{scan}{p}(1:ind(1)-1);
        if exist([namePatientScan,'_',featType,'_text.mat'],'file')
            load([namePatientScan,'_',featType,'_text']) % Variable 'textures' is now in MATLAB workspace
        else
            load([namePatientScan,'_','GTVp','_text']) % Variable 'textures' is now in MATLAB workspace
        end
        tempText{p} = textures;
    end
    experiment = 0;
    for s = 1:numel(scale_mat)
        for a = 1:numel(algo_cell)
            for n = 1:numel(Ng_mat)
                text{s,a,n} = struct;
                experiment = experiment + 1;
                strExperiment = ['Experiment',num2str(experiment)];
                for t = 1:nType
                    nameFeature = fieldnames(temp.(strExperiment).(nameType{t})); nFeature = numel(nameFeature);
                    for f = 1:nFeature
                        data = zeros(nPatient,1);
                        for p = 1:nPatient
                            data(p,1) = tempText{p}.(strExperiment).(nameType{t}).(nameFeature{f});
                        end
                        text{s,a,n}.(nameType{t}).(nameFeature{f}).Data = data;
                        for o = 1:nOutcomes
                            [text{s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).rs,text{s,a,n}.(nameType{t}).(nameFeature{f}).Spearman.(nameOutcomes{o}).p] = corr(data,outcomes.(nameOutcomes{o}),'type','Spearman');
                        end
                    end
                end
            end
        end
    end
    cd .., save(['text_',cohortID,'_',scans{scan},'_',featType],'text')
end

cd(startpath)
end


function [Data, para, vocab] = LoadWavLabel_CHiME4(para, step, dataset)
switch lower(dataset)
    case {'dt05','et05'}
        wavlist = ['../Kaldi/data/' dataset '_multi_noisy/wav.scp'];
        ali_file = [para.local.aliDir '_dt05/ali.txt'];
    case 'tr05'
        wavlist = ['../Kaldi/data/' dataset '_multi_noisy/wav.scp'];
        ali_file = [para.local.aliDir '/ali.txt'];
end

[ali, vocab] = LoadKaldiFrameLabel(ali_file);
wavlist = my_cat(wavlist);
wavlist = wavlist(step:step:end);

wavreader.name = 'wavfile';
wavreader.array = 1;
wavreader.multiArrayFiles = 1;

nCh = 6;
fs = 16000;
frame_size = fs*0.025;
frame_shift = fs*0.01;

% Load data file list
wav_noisy = {};  label = {};
for si = 1:length(wavlist)
    words = ExtractWordsFromString_v2(wavlist{si});
    curr_uttID = words{1};
    wavfile = words{2};
    PrintProgress(si, length(wavlist), 100, curr_uttID);

    % get alignment
    if ~strcmpi(para.local.data, 'mixed') && isempty(regexp(lower(curr_uttID), para.local.data))
        continue;
    end

    words = ExtractWordsFromString_v2(curr_uttID, '_');
    curr_uttID2 = [words{2} '_' words{3}(1:3) '_' words{4}];
    fieldname = ['U_' curr_uttID2];
    if ~isfield(ali, fieldname); continue; end    % if there is no label for current utterance, skip it.
    curr_label = ali.(fieldname);
    curr_label = curr_label(:)'+1;  % convert to row vector and the index starts with 1

    % read in the waveform
    % for the two channel track, we may choose a random pair, or use all
    % the channel pairs.
    if length(para.topology.useChannel)==1
        if para.topology.useChannel==6
            ch_idx = randperm(6);
        elseif para.topology.useChannel==5
            ch_idx = randperm(6);
            ch_idx(ch_idx==2) = [];     % we don't use channel 2
        elseif strcmpi(para.local.pair, 'randPair')
            ch_idx = randperm(nCh);
            ch_idx(ch_idx==2) = [];     % we don't use channel 2
            ch_idx = sort(ch_idx(1:para.topology.useChannel));
        elseif strcmpi(para.local.pair, 'allPair')
            ch_idx = [1 3; 1 4; 1 5; 1 6; 3 4; 3 5; 3 6; 4 5; 4 6; 5 6];
        end
    else
        ch_idx = para.topology.useChannel;
    end
    words = ExtractWordsFromString_v2(wavfile, '/');
    wavfileRoot = [para.local.wavroot_noisy '/' words{end-1} '/' words{end}(1:end-5)];

    for pi = 1:size(ch_idx,1)   % add all channel pairs to the training data
        clear wavfileArray
        for i=1:size(ch_idx,2)
            wavfileArray{i} = [wavfileRoot num2str(ch_idx(pi,i)) '.wav'];
        end
        [wav] = InputReader(wavfileArray, wavreader);
        wav = StoreWavInt16(wav);

        % synchronize the length of label and wav
        nFr_feat = enframe_decide_frame_number(size(wav,2), frame_size, frame_shift);
        nFr_label = length(curr_label);
        if nFr_feat>=nFr_label
            requiredLen = DecideWavLen4XFrames(nFr_label, frame_size, frame_shift);
            wav(:,requiredLen+1:end) = [];
        elseif nFr_feat<nFr_label
            curr_label = curr_label(1:nFr_feat);
        end

        if para.local.useFileName
            for i=1:size(ch_idx,2)
                wavfileArray{i} = sprintf('%s 0 %2.3f', wavfileArray{i}, size(wav,2)/fs);
            end
            wav_noisy{end+1} = wavfileArray;
        else
            wav_noisy{end+1} = wav;
        end
        label{end+1} = curr_label;
    end
end

Data(1).data = wav_noisy;
Data(2).data = label;

para.IO.inputFeature = [1 1];
para.IO.DataSyncSet{1} = [];
para.IO.frame_rate = [16000 100];
para.IO.isTensor = [1 1];
if para.local.useFileName
    para.IO.inputFeature(1) = 0;
    wavreader.precision = 'int16';
    para.IO.fileReader(1) = wavreader;
    para.IO.fileReader(2).name = '';
end
end


function maskM = getStructureMask(structNum, sliceNum, dim, planC)
%"getStructureMask"
%   Returns structure's mask on a specified slice number via uniformized
%   data.
%
%   structNum is the number of the requested structure
%   sliceNum is the slice NUMBER we want the structure on (not coordinate)
%   dim is the dimension (1,2,3 = x,y,z) that the slice should be taken
%   from.
%   planC is the plan (optional parameter: global is used if not passed)
%
%   WARNING: This function uses only uniformized data even if dim is 3 (for
%            zSlices).  In order to get the structure mask on a CT slice
%            via rasterSegments, use getRasterSegments and rasterToMask.
%
% JRA 11/14/03
%
%Usage:
%   function maskM = getStructureMask(structNum, sliceNum, dim, planC)
%
% 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/>.

if ~exist('planC')
    global planC
end
indexS = planC{end};

[scanNum, relStructNum] = getStructureAssociatedScan(structNum, planC);

[indicesC, structBitsC, planC] = getUniformizedData(planC, scanNum);
[arraySize] = getUniformScanSize(planC{indexS.scan}(scanNum));

switch dim
	case 2
         rowDim = 3;    colDim = 2;     sliceDim = 1;
    case 1
         rowDim = 3;    colDim = 1;     sliceDim = 2;
    case 3
         rowDim = 1;    colDim = 2;     sliceDim = 3;
    otherwise
        warning('Valid Dimensions are 1,2,3 (x,y,z respectively.');
        return;
end

maskM = repmat(logical(0), [arraySize(rowDim) arraySize(colDim)]);
if relStructNum <= 52
    cellNum = 1;
else
    cellNum = ceil((relStructNum-52)/8)+1;
end
indicesM    = indicesC{cellNum};
structBitsM = structBitsC{cellNum};
sliceIndices = (indicesM(:,sliceDim) == sliceNum);
sliceXYZ = indicesM(sliceIndices,:);
if relStructNum <= 52
    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum));
else
    sliceBits = logical(bitget(structBitsM(sliceIndices), relStructNum-52-8*(cellNum-2)));
end
structXYZ = sliceXYZ(sliceBits,:);

for i=1:size(structXYZ,1)
    maskM(structXYZ(i,rowDim), structXYZ(i,colDim)) = logical(1);
end


function sv_startSchuster(mCatalog, hFigure, bMap, rContainer)
% function sv_startSchuster(mCatalog, hFigure, bMap, rContainer)
% ------------------------------------------------------
% Starts seismicity variation analysis toolbox: Schuster Test on Mc
%
% Input parameters:
%   mCatalog      Earthquake catalog to be analyzed
%   hFigure       Handle of figure where the user should select the grid (i.e. the seismicity map)
%   bMap          Map/cross-section switch. If the testing is carried out on a map set bMap = 1,
%                 on a cross-section set bMap = 0
%   rContainer    Just a container (structure proposed) to store any variables
%
% J. Woessner; woessner@seismo.ifg.ethz.ch
% April 4, 2003

global bDebug;
if bDebug
    report_this_filefun(mfilename('fullpath'));
end

% Launch GUI
hMenuFig = sv_gridSchuster(1);

% Set up parameter struct and store input parameters
params.mCatalog = mCatalog;
params.bMap = bMap;
params.rContainer = rContainer;

% Analyze Output
if ~ishandle(hMenuFig)
    answer = 0;
else
    handles = guidata(hMenuFig);
    answer = handles.answer;
    % OK pressed
    if answer == 1
        % Get the values from figure
        %params.bNumber = get(handles.radNumber, 'Value');   % deprecated
        if get(handles.radNumber, 'Value') == 1
            params.nGriddingMode = 0;   % Constant number
        elseif get(handles.radRadius, 'Value') == 1
            params.nGriddingMode = 1;   % Constant radius
        else
            params.nGriddingMode = 2;   % Rectangle mode
        end
        % Setting up the params struct array with variables
        params.nNumberEvents = str2double(get(handles.txtNumber, 'String'));
        params.fMaxRadius = str2double(get(handles.txtMaxRadius, 'String'));
        params.fRadius = str2double(get(handles.txtRadius, 'String'));
        params.bGridEntireArea = get(handles.chkGridEntireArea, 'Value');
        params.fSpacingHorizontal = str2double(get(handles.txtSpacingHorizontal, 'String')); % Grid spacing variable
        params.fSpacingDepth = str2double(get(handles.txtSpacingDepth, 'String'));           % Grid spacing variable
        params.fSizeRectHorizontal = str2double(get(handles.txtSizeRectHorizontal, 'String')); % Rectangular selection instead radius params.fRadius
        params.fSizeRectDepth = str2double(get(handles.txtSizeRectDepth, 'String'));           % Rectangular selection instead radius params.fRadius
        params.nMinimumNumber = str2double(get(handles.txtMinimumNumber, 'String'));
        params.bTimePeriod = get(handles.chkTimePeriod,'Value');
        params.fTimePeriod = str2double(get(handles.txtTimePeriod,'String')); % Period lengths to be compared in days
        params.bTstart = get(handles.chkTstart,'Value'); % Check for starting time of temporal mapping
        params.fTstart = str2double(get(handles.txtTstart,'String')); % Starting time for temporal mapping
        params.bBstnum = get(handles.chkBstnum,'Value'); % Check for boostrap sampling
        params.fBstnum = str2double(get(handles.txtBstnum,'String')); % Number of bootstrap samples
        params.fBinning = str2double(get(handles.txtBinsize,'String')); % Bin size for magnitude binning
        params.fStartMag = str2double(get(handles.txtStartMag,'String')); % Lower magnitude to perform Schuster test
        params.fEndMag = str2double(get(handles.txtEndMag,'String')); % Last magnitude to perform Schuster test
        params.sComment = get(handles.txtComment, 'String'); % Comment on calculation

        %%%%%%%%%%%%%%%%%%%%%%%%%% Check variable settings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %
        %  if ~params.bMinMagMc
        %      params.fMinMag = str2double(get(handles.txtMinMag, 'String'));
        %    else
        %      params.fMinMag = 1;
        %    end
        %    params.fMaxMag = str2double(get(handles.txtMaxMag, 'String'));
        bSaveParameter = get(handles.chkSaveParameter, 'Value');
        if bSaveParameter
            sSaveParameter = get(handles.lblSaveParameter, 'String');
        end

        % Remove figure from memory
        delete(hMenuFig);

        % Select grid
        [params.mPolygon, params.vX, params.vY, params.vUsedNodes] = ex_selectgrid(hFigure, params.fSpacingHorizontal, params.fSpacingDepth, params.bGridEntireArea);

        % Validate polygonsize
        if length(params.vX) < 4  ||  length(params.vY) < 4
            errordlg('Selection is too small. Please select a larger polygon.');
            return;
        end

        % Add parameter to params.sComment
        params.sComment = [params.sComment ' Spacing ' num2str(params.fSpacingHorizontal) ' deg.'...
                    ', Time period ' num2str(params.fTimePeriod) ' d'];
        if bSaveParameter
            % Save paramters
            save(sSaveParameter, 'params');
        else
            % General calculations

            % Create Indices to catalog
            [params.caNodeIndices] = ex_CreateIndexCatalog(params.mCatalog, params.mPolygon, params.bMap, params.nGriddingMode, ...
                params.nNumberEvents, params.fRadius, params.fSizeRectHorizontal, params.fSizeRectDepth);

            %%%%% Temporarily calculations for %%%%%%%%%%%%%%%%%%%%%%%%%%%%
            % Perform the calculation
            [params] = sv_calcSchuster(params);

            sv_result(params);
        end
    else
        delete(hMenuFig);
    end
end


function [data,indices] = bz_GetWidebandData(channels,varargin)

% bz_GetWidebandData - Get local field potentials.
%
%  Load wide band data from disk (unlike spikes or positions, raw data is way
%  too large to keep in memory).
%
%  USAGE
%
%    [data,indices] = bz_GetWidebandData(channels,<options>)
%
%    channels       optional list of channels to load (default = all)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'restrict'    list of time intervals to read from the data file
%     'intervals'   same as 'restrict' (for backwards compatibility)
%     'select'      select channel by ID ('id', counted from 0 a la NeuroScope)
%                   or by number ('number', counted from 1 a la Matlab)
%                   (default = 'id')
%    =========================================================================
%
%  OUTPUT
%
%    data           list of (time,voltage1,...,voltageN) tuples
%    indices        for each tuple, the index of the interval it falls in
%
%  EXAMPLES
%
%    % channel ID 5 (= # 6), from 0 to 120 seconds
%    data = bz_GetWidebandData(5,'intervals',[0 120]);
%    % same, plus from 240.2 to 265.23 seconds
%    data = bz_GetWidebandData(5,'intervals',[0 120;240.2 265.23]);
%    % multiple channels
%    data = bz_GetWidebandData([1 2 3 4 10 17],'intervals',[0 120]);
%    % channel # 3 (= ID 2), from 0 to 120 seconds
%    data = bz_GetWidebandData(3,'intervals',[0 120],'select','number');

% Copyright (C) 2004-2011 by Michaël Zugaro
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 3 of the License, or
% (at your option) any later version.

global DATA;
if isempty(DATA),
	error('No session defined (did you forget to call SetCurrentSession? Type ''help Data'' for details).');
end

% Default values
intervals = [0 Inf];
select = 'id';

% Optional parameter
if ischar(channels),
	varargin = {channels,varargin{:}};
	channels = []; % all
end

if nargin < 1 | mod(length(varargin),2) ~= 0,
  error('Incorrect number of parameters (type ''help bz_GetWidebandData'' for details).');
end

% Parse parameter list
for i = 1:2:length(varargin),
  if ~ischar(varargin{i}),
    error(['Parameter ' num2str(i+1) ' is not a property (type ''help bz_GetWidebandData'' for details).']);
  end
  switch(lower(varargin{i})),
    case {'intervals','restrict'},
      intervals = varargin{i+1};
      if ~isdmatrix(intervals) || size(intervals,2) ~= 2,
        error('Incorrect value for property ''intervals'' (type ''help bz_GetWidebandData'' for details).');
      end
    case 'select',
      select = lower(varargin{i+1});
      if ~isstring_FMAT(select,'id','number'),
        error('Incorrect value for property ''select'' (type ''help bz_GetWidebandData'' for details).');
      end
    otherwise,
      error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help bz_GetWidebandData'' for details).']);
  end
end

filename = [DATA.session.path '/' DATA.session.basename '.dat'];
nChannels = DATA.nChannels;
if isempty(channels),
	channels = 1:nChannels;
elseif strcmp(select,'id'),
	channels = channels + 1;
end

nIntervals = size(intervals,1);
data = [];
indices = [];
for i = 1:nIntervals,
	duration = (intervals(i,2)-intervals(i,1));
	start = intervals(i,1);
	% Load data
	d = bz_LoadBinary(filename,'duration',duration,'frequency',DATA.rates.wideband,'nchannels',nChannels,'start',start,'channels',channels);
	% The following two lines compensate for annoying numerical precision errors in Matlab, whereby the number of samples
	% read with LoadBinary is not always exactly that expected, depending on how accurately 'duration' is coded internally
	n = size(d,1);
	t = linspace(start,start+n/DATA.rates.wideband,n)';
	data = [data ; t d];
	indices = [indices ; i*ones(size(t))];
end


function fileOffsets = dtiAppendPathwaysToPDB(fg, filename)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% dtiAppendDatabasePathways(toAppend, filename)
%
% toAppend: the pathway database we want to append to this file
% fileOffsets: an array of file offsets for each pathway.
%
% Author: DA
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

numstats = 0; % xxx
algoType = 0; % xxx

fid = fopen (filename, 'rb');
% figure out where num paths is, read it in
offset = fread (fid, 1, 'uint');
%fprintf ('Seeking to %d\n', offset);
fseek (fid, offset, -1);
[oldNumPaths, count] = fread (fid, 1, 'uint');
fclose (fid);
if count == 0
    %fprintf ('First time!');
    oldNumPaths = 0;
end
newNumPaths = oldNumPaths + length(fg.fibers);
fid = fopen (filename, 'r+b');
fseek (fid, offset, -1);
fwrite (fid, newNumPaths, 'uint');
fclose(fid);
fid = fopen (filename, 'ab');
fseek (fid, 0, 1);
fileOffsets = zeros(length(fg.fibers),1);

for p = 1:length(fg.fibers)
    fileOffsets(p) = ftell(fid);
    path_offset = 3 * 4  + numstats*8; % 3 int, numstats double
    fwrite(fid,path_offset,'int');

    nn = size(fg.fibers{p}, 2);

    fwrite(fid,nn,'int');
    fwrite(fid,algoType,'int'); % algo type
    fwrite(fid,0,'int'); % seedpointindex ???

    fwrite(fid,fg.fibers{p}(:), 'double');
    % Stats
    %for as = 1:numstats
     %   fwrite(fid,toAppend.pathways(p).path_stat_vector(as),'double');
    %end

    % Writing path nodes
    %fwrite(fid,[holdingchains(p).xpos*mmPerVox(1); holdingchains(p).ypos*mmPerVox(2); holdingchains(p).zpos*mmPerVox(3)],'double');
    %pos = asMatrixStruct(toAppend.pathways(p));
    % Change from 0 based to 1 based positions
    %pos = pos - repmat(toAppend.mm_scale(:),1,size(pos,2));
    %fwrite(fid,pos,'double');

    % Writing stats values per position
    %for as = 1:numstats
    %    if( toAppend.pathway_statistic_headers(as).is_computed_per_point )
    %        fwrite(fid,toAppend.pathways(p).point_stat_array(as,:),'double');
    %    end
    %end
end

%disp('Appended pathways to database.');
fclose(fid);


function D = spm_eeg_inv_fmripriors(S)
% Generate fMRI priors for the M/EEG source reconstruction
% FORMAT D = spm_eeg_inv_fmripriors(S)
%
% S        - optional input struct
% (optional) fields of S:
%  .D      - MEEG object or filename of M/EEG mat-file
%  .fmri   - filename of prior (SPM) image to be used
%  [.gm    - filename of grey matter (GM) image] {unused}
%  .space  - native (0) or MNI (1) space (must be same for SPM and GM images)
%  .hthr   - height threshold of prior image [defaults: 0.5]
%  .ethr   - extent threshold of clusters in prior image [default: 1]
%  .ncomp  - maximal number of priors component to be extracted [default: Inf]
%  .smooth - variance of the smoothing kernel onto the surface [default: 0.2] {unused}
%  .disp   - whether to display priors on mesh [default: 0]
%
% D.inv{D.val}.inverse.fmri.priors   - MAT filename containing a variable 'pQ' that
%            is a [ncomp] cell array of [nb vertices] vectors describing spatial priors
% D.inv{D.val}.inverse.fmri.texture  - GIfTI texture filename containing all
%            spatial priors
% D.inv{D.val}.inverse.fmri.clusters - image filename containing clusters as labels
%__________________________________________________________________________
%
% Reference:
%
% A Parametric Empirical Bayesian framework for fMRI-constrained MEG/EEG
% source reconstruction. Henson R, Flandin G, Friston K & Mattout J.
% Human Brain Mapping (in press).
%__________________________________________________________________________
% Copyright (C) 2008-2015 Wellcome Trust Centre for Neuroimaging

% Guillaume Flandin and Rik Henson
% $Id: spm_eeg_inv_fmripriors.m 6301 2015-01-12 17:23:08Z guillaume $

%-Get MEEG object
%--------------------------------------------------------------------------
try
    D = S.D;
catch
    [D, sts]   = spm_select(1, 'mat', 'Select M/EEG mat file');
    if ~sts, D = []; return; end
    S.D = D;
end

[D, val] = spm_eeg_inv_check(D);

%-Input parameters
%--------------------------------------------------------------------------
try
    S.fmri;
catch
    [S.fmri, sts] = spm_select(1,'image','Select prior (eg thresholded SPM) image...');
    if ~sts, return; end
end

% try
%     S.gm;
% catch
%     [S.gm, sts] = spm_select([0 1],'image','Select grey matter (GM) image...');
% end

try
    space = S.space;   % 0 = native, 1 = MNI
catch
    space = spm_input('Image space','+1','b',{'Native|MNI'},[0 1],1);
end

if space
    try
        m = D.inv{val}.mesh.tess_mni;
        %fprintf('Note: assuming SPM and GM images are in MNI space...\n');
    catch
        error('This D structure has no MNI cortical mesh stored.');
    end
else
    try
        m = export(gifti(D.inv{val}.mesh.tess_ctx),'spm');
        %fprintf('Note: assuming SPM and GM images are in subject''s native MRI space...\n');
    catch
        error('This D structure has no cortical mesh stored.');
    end
end

try
    S.hthr;
catch
    S.hthr = 0.5; % assume binary prior
end

try
    S.ethr;
catch
    S.ethr = 1; % no threshold on extent
end

try
    S.ncomp;
catch
    S.ncomp = Inf; % all components
end

try
    S.bincomp;
catch
    S.bincomp = 1; % default to binary priors
end

try
    S.varcomp;
catch
    S.varcomp = 1; % default to variance priors (vectors)
end

% try
%     S.smooth;
% catch
%     S.smooth = 0.2;
% end

try
    S.disp;
catch
    S.disp = 0;
end

%-Extracting clusters from functional image
%==========================================================================
V     = spm_vol(S.fmri);
prior = spm_read_vols(V);

%-Height threshold
%--------------------------------------------------------------------------
prior = prior > S.hthr;

%-Connected Component labelling
%--------------------------------------------------------------------------
[l2, num] = spm_bwlabel(double(prior),26);
if ~num
    fprintf('No suprathreshold clusters available.\n');
    return
end

%-Extent threshold, and sort clusters according to their extent
%--------------------------------------------------------------------------
[n, ni] = sort(histc(l2(:),0:num), 1, 'descend');
l  = zeros(size(l2));
n  = n(2:end);      ni = ni(2:end)-1;
ni = ni(n>=S.ethr); n  = n(n>=S.ethr);
S.ncomp = min(S.ncomp, length(n));
for i=1:S.ncomp
    l(l2==ni(i)) = i;
end
clear l2 ni
fprintf('Selected %d clusters (out of %d) in prior image.\n',S.ncomp,num);

%-Projecting volumetric clusters on surface mesh
%==========================================================================
q = zeros(S.ncomp, size(m.vert,1));
for i=1:S.ncomp
    q(i,:) = spm_mesh_project(m.vert,struct('dat',double(l==i),'mat',V.mat),'nn');
end
q(~any(q,2),:) = [];
fprintf('After projection, %d clusters remaining.\n',size(q,1));
if isempty(q), return; end

%-Smooth, binarize and save in output variable
%--------------------------------------------------------------------------
pQ = cell(1,size(q,1));
for i = 1:size(q,1)
    qq    = q(i,:)';
    %qq   = spm_mesh_smooth(struct('faces',double(m.face),'vertices',m.vert),qq, S.smooth);
    qq    = qq .* (qq > exp(-8));
    if S.bincomp
        pQ{i} =  double(qq > 0)';  % binarise
    end
end

%-Display and export clusters
%==========================================================================
if S.disp
    for i=1:numel(pQ)
        spm_eeg_render(struct('faces',double(m.face),'vertices',m.vert),...
            struct('texture',pQ{i}));
    end
end

%-Save clusters as an image of labels
%--------------------------------------------------------------------------
[pth,name] = fileparts(S.fmri);
D.inv{val}.inverse.fmri.clusters = fullfile(pth,['cluster_' name spm_file_ext]);
V = struct('fname',   D.inv{val}.inverse.fmri.clusters, ...
           'dim',     V.dim, ...
           'dt',      [spm_type('uint16') spm_platform('bigend')], ...
           'mat',     V.mat, ...
           'pinfo',   [1 0 0]', ...
           'descrip', 'clusters');
V = spm_write_vol(V,l);

%-Save spatial priors vectors as GIfTI file
%--------------------------------------------------------------------------
[pth,name] = fileparts(D.fname);
D.inv{val}.inverse.fmri.texture = fullfile(pth,['priors_' name '_' num2str(val) '.func.gii']);
G          = gifti;
G.cdata    = cat(1, pQ{:})';
save(G,D.inv{val}.inverse.fmri.texture);

%-Save spatial priors vectors as MAT-file
%--------------------------------------------------------------------------
[pth,name] = fileparts(D.fname);
D.inv{val}.inverse.fmri.priors = fullfile(pth,['priors_' name '_' num2str(val) '.mat']);
if ~S.varcomp
    pQ = pQ*pQ';
end

save(D.inv{val}.inverse.fmri.priors,'pQ', spm_get_defaults('mat.format'));

%-Save D structure
%--------------------------------------------------------------------------
%D.save;


function increaseHumanGEMVersion(bumpType)
% increaseHumanGEMVersion
%   Increase version for the humanGEM respositories
%
% Input:
%   bumpType      the value has to be one selected among 'major', 'minor' or 'patch'
%
% Usage: increaseHumanGEMVersion(bumpType)
%

%Check if in main:
currentBranch = git('rev-parse --abbrev-ref HEAD');
if ~strcmp(currentBranch,'main')
    error('ERROR: not in main')
end

%Get model path
[ST, I]=dbstack('-completenames');
modelPath=fileparts(fileparts(fileparts(ST(I).file)));

%Bump version number:
versionFile=fullfile(modelPath,'version.txt');
fid = fopen(versionFile,'r');
    oldVersion = fscanf(fid, '%s');
fclose(fid);
oldVersion = str2double(strsplit(oldVersion,'.'));
newVersion = oldVersion;
switch bumpType
    case 'major'
        newVersion(1) = newVersion(1) + 1;
        newVersion(2) = 0;
        newVersion(3) = 0;
    case 'minor'
        newVersion(2) = newVersion(2) + 1;
        newVersion(3) = 0;
    case 'patch'
        newVersion(3) = newVersion(3) + 1;
    otherwise
        error('ERROR: invalid input. Use either "major", "minor" or "patch"')
end
newVersion = num2str(newVersion,'%d.%d.%d');

%Check if history has been updated:
%fid     = fopen('../../history.md','r');
%history = fscanf(fid,'%s');
%fclose(fid);
%if ~contains(history,['human' newVersion ':'])
%    error('ERROR: update history.md first')
%end
%To be included

%Load model:
ymlFile=fullfile(modelPath,'model','Human-GEM.yml');
ihuman = importYaml(ymlFile);

%Include tag and save model:
ihuman.version = newVersion;

%Export model to multiple formats
exportHumanGEM(ihuman,'Human-GEM',modelPath,{'mat', 'txt', 'xml', 'yml', 'xlsx'});

%Update version file:
fid = fopen(versionFile,'wt');
fprintf(fid,newVersion);
fclose(fid);

%Update readme file:
readmeFile=fullfile(modelPath,'README.md');
content = fileread(readmeFile);
content = strrep(content,'{{DATE}}',datestr(now,29));
content = strrep(content,'{{nRXN}}',num2str(length(ihuman.rxns)));
content = strrep(content,'{{nMET}}',num2str(length(ihuman.mets)));
content = strrep(content,'{{nGENE}}',num2str(length(ihuman.genes)));
fid = fopen(readmeFile,'wt');
fwrite(fid,content);
fclose(fid);

end


function gX = whitehKernGradX(kern, X, X2)

% WHITEHKERNGRADX Gradient of WHITEH kernel with respect to input locations.
% FORMAT
% DESC computes the gradident of the whiteh noise
% kernel with respect to the input positions where both the row
% positions and column positions are provided separately.
% ARG kern : kernel structure for which gradients are being
% computed.
% ARG x1 : row locations against which gradients are being computed.
% ARG x2 : column locations against which gradients are being computed.
% RETURN g : the returned gradients. The gradients are returned in
% a matrix which is numData2 x numInputs x numData1. Where numData1 is
% the number of data points in X1, numData2 is the number of data
% points in X2 and numInputs is the number of input
% dimensions in X.
%
% SEEALSO whitehKernParamInit, kernGradX, whitehKernDiagGradX
%
% COPYRIGHT : Neil D. Lawrence, 2004, 2005, 2006

% KERN

if nargin<3
    X2 = X;
end

gX = zeros(size(X2, 1), size(X2, 2), size(X, 1));


function rtf(plot_frq,flag_save)

close all
evalin('base','stop=0;');

%=========SET THE BASIC FIGURE=================
fig = figure('Position',[500,500,800,600],...
        'NumberTitle','off',...
        'Name','Scope',...
        'doublebuffer','on',...
        'HandleVisibility','on',...
        'KeyPressFcn', @keypress, ...
        'Renderer', 'openGL');
%=============================================

%=============OPEN THE DEVICE FOR RECORD======
sample_frequency = 44100;
samples_per_frame = 1024;
%plot_frq=10;
record_time=600;
samples_to_acquire = record_time * sample_frequency;

%PREPARE    THE    DEVICE
ai = analoginput('winsound');
chan = addchannel( ai, 1 );
set( ai, 'SampleRate', sample_frequency )
set( ai, 'SamplesPerTrigger', samples_to_acquire )
set(ai, 'StopFcn', @stop_dev)

sample_frequency = get( ai, 'SampleRate' );

%SETTING CALL BACK FUNCTIONS:
%The first for capture   the
%second     for      display
set(ai, 'SamplesAcquiredFcnCount',samples_per_frame);
set(ai, 'SamplesAcquiredFcn',@flag);
set(ai, 'TimerPeriod',(1/plot_frq));
set(ai, 'TimerFcn',@disply);

%=============SAVE THE CONFIGURATION======
plot_ref=plot(zeros(10,1));
fid=-1;

%SAVE THE CURRENT PARAMETERS:
name_of_file=sprintf('%s-%d','real-anal',(round(sample_frequency/samples_per_frame)));
remark={1,...
        zeros(samples_per_frame*20,1)',...
        0,...
        plot_ref,...
        plot_frq,...
        cputime,...
        flag_save,...
        -1,...
        name_of_file
        };

set(ai, 'UserData',remark)

%=============START TO RECORD================
fprintf ('To stop the program set <stop=1> or press q in the figure window\n');
start (ai)

%=============================================
%=========THE MAIN PROGRAM====================
%=============================================
%                   *
%                  ***
%                 *****
%                  ***
%                  ***
%                  ***
%                  ***
%                  ***
%                 *****
%                  ***
%                   *
%=============================================
%==========CALLBACK FUNCTIONS=================
%=============================================

%=========Keypress callback===========
function keypress(src, e)
  keypressed=get(gcf,'CurrentCharacter');

  % ignore raw control, shift, alt keys
  if keypressed
    % Quit
    if strcmp( keypressed, 'q')
        evalin('base','stop=1;');
    end
  end
return

%============FLAG FUNCTION===================
%This function activated when we capture
%certain    amount  of          samples
function flag(obj,event)

  % CHECK FOR STOP SIGNAL
  if  evalin('base','stop')
      stop(obj)
  end

% GET THE OLD DATA
 remark=get(obj,'UserData');
 flag_write=remark{1};  %Do I have to
 buffer=remark{3};      %What is the old picture
 flag_save=remark{7};   %Are we in saving mode?
 fid=remark{8};         %What file descriptor to save

 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %IN CASE - DELETE/SAVE THE OLD DATA

 if flag_write>20

     % IN CASE WE HAVE TO SAVE - CLOSE THE OLD FILE AND MAKE A NEW
     if flag_save>0
        fclose(fid);
        name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));
        fid=fopen(name_of_data,'w');
    end

      %DELETE OLD DATA
     flag_write=1;
     buffer=[];
     remark{1}=flag_write; % SET THE POSITION OF THE READING SHIFT
 end

 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 % TAKE THE NEW DATA

 samples_per_frame=get(obj,'SamplesAcquiredFcnCount');
 data=(getdata(obj,samples_per_frame))';

 % IN CASE - WRITE THE DATA
 if flag_save>0
     if fid==-1
         name_of_data=sprintf('%s-%d.dat','dat',(round(cputime*1000)));
         fid=fopen(name_of_data,'w');
     end
     fwrite(fid,(data*10000),'short');
     remark{8}=fid;
 end

 % Add to buffer
 buffer=[buffer data];
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 remark{3}=buffer;
 set(obj,'UserData',remark);

return

function stop_dev(obj,event)

     remark=get(obj,'UserData');
     if (remark{8}>0)                 %FID>0 == There is open file
         fclose (remark{8});
     end
     close all

     fprintf('\n\nThanks for using Erlich Real-Time scope\n');
     save (remark{9},'remark');

     delete(obj)
     clear obj
return

function disply(obj,event)

  sample_frequency=get(obj,'SampleRate');
  remark=get(obj,'UserData');
  refresh_frq=remark{5};
  read_shift=remark{1};

  ring=remark{2};
  buffer=remark{3};

  end_shift=min((read_shift+round(sample_frequency/refresh_frq)),length(buffer));
  new_data=buffer(read_shift:end_shift);
  ring=[ring new_data];
  ring(1:length(new_data))=[];
  remark{1}=end_shift;
  remark{2}=ring;

  start_display(ring,remark{4})

  set(obj,'UserData',remark);
return


function [ama] = loadama(filename);

% LOADAMA read an inverted A-matrix and associated geometry information
% from an ama file that was written by Tom Oostendorp's DIPOLI
%
% Use as
%   [ama] = loadama(filename)
%
% See also LOADTRI, LOADMAT

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

fid = fopen(filename, 'rb', 'ieee-le');

version = fread(fid, 1, 'int');
if version~=10
  error(sprintf('%s is either not an inverted A matrix, or one of an old version', filename));
end

mode = fread(fid, 1, 'int');
ngeo = fread(fid, 1, 'int');

totpnt = 0;
totdhk = 0;
nrow   = 0;

% read the boundaries
geo  = [];
for i=1:ngeo
  geo(i).name    = char(fread(fid, [1 80], 'uchar'));
  geo(i).npnt    = fread(fid, 1, 'int');
  geo(i).pnt     = fread(fid, [3 geo(i).npnt], 'float')';
  geo(i).ndhk    = fread(fid, 1, 'int');
  geo(i).dhk     = fread(fid, [3 geo(i).ndhk], 'int')' + 1;  % Matlab indexing starts at 1
  geo(i).sigmam  = fread(fid, 1, 'float');
  geo(i).sigmap  = fread(fid, 1, 'float');
  geo(i).geocon  = fread(fid, ngeo, 'int');
  geo(i).deflat  = fread(fid, ngeo, 'float');
  totpnt = totpnt + geo(i).npnt;
  totdhk = totdhk + geo(i).ndhk;
end

% read the electrodes
if mode~=1
  elec.name    = char(fread(fid, [1 80], 'uchar'));
  elec.npnt    = fread(fid, 1, 'int');
  for i=1:(elec.npnt+1)
    elec.el(i).dhk  = fread(fid, 1, 'int') + 1; % Matlab indexing starts at 1
    elec.el(i).la   = fread(fid, 1, 'float');
    elec.el(i).mu   = fread(fid, 1, 'float');
    elec.el(i).name = char(fread(fid, [1 10], 'char'));
    % the ELECTRODE c-structure is padded to word boundaries, i.e. to 4 bytes
    dum = fread(fid, 2, 'char');
  end
  elec.vertex  = fread(fid, 1, 'int');
  elec.surface = fread(fid, 1, 'int');
  nrow = nrow + elec.npnt;
else
  elec = [];
end

% read the gradiometers
if mode~=0
  error('gradiometers not yet implemented');
else
  grad = [];
end

% read the inverted A-matrix
bi = fread(fid, [totpnt nrow], 'float')';

% read the isolated source compartment information, if present
iso_sur    = fread(fid, 1, 'int') + 1;  % Matlab indexing starts at 1
inner_only = fread(fid, 1, 'int');
if iso_sur~=0
  iso_totpnt = geo(iso_sur).npnt;
  iso_b      = fread(fid, [iso_totpnt iso_totpnt], 'float')';
else
  iso_b = [];
end

fclose(fid);

% put all local variables into a structure, this is a bit unusual programming style
% the output structure is messy, but contains all relevant information
tmp = whos;
ama = [];
for i=1:length(tmp)
  if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'}))
    ama = setfield(ama, tmp(i).name, eval(tmp(i).name));
  end
end


function [clpot, seppot] = init_pot(engine, clqs, pots, pot_type, onodes, ndx)
% INIT_POT Initialise potentials with evidence (jtree_inf)
% function [clpot, seppot] = init_pot(engine, clqs, pots, pot_type, onodes)

cliques = engine.cliques;
bnet = bnet_from_engine(engine);
% Set the clique potentials to all 1s
C = length(cliques);
clpot = cell(1,C);
for i=1:C
  clpot{i} = mk_initial_pot(pot_type, cliques{i}, bnet.node_sizes(:), bnet.cnodes(:), onodes);
end

% Multiply on specified potentials
for i=1:length(clqs)
  c = clqs(i);
  clpot{c} = multiply_by_pot(clpot{c}, pots{i});
end

seppot = cell(C,C); % implicitely initialized to 1


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

function TestSetup
setenv('ISDISPLAY','0') % go faster! Fit only 2 voxels in FitData.m
setenv('ISCITEST','1')

function test_Sim
disp('===========================================')
disp('Running simulation test for qmt_sirfse');
disp('testing Simulation Single Voxel Curve...');

Model = str2func('qmt_sirfse'); Model = Model();
savedModel_fname = fullfile(fileparts(which('qMRLab')),'Test','MoxUnitCompatible','static_savedModelsforRetrocompatibility',['qmt_sirfse.qmrlab.mat']);
if ~exist(savedModel_fname,'file')
Model.saveObj(savedModel_fname);
else
Model = Model.loadObj(savedModel_fname);
end

disp(class(Model))
try Opt = button2opts(Model.Sim_Single_Voxel_Curve_buttons,1); end
try st = Model.st; catch, try st = mean([Model.lb(:),Model.ub(:)],2); catch, st = ones(length(Model.xnames),1); end; end
if exist('Opt','var') && length(Opt)>1
[Opt(:).SNR] = deal(1000);
else
Opt.SNR=1000;
end
for iopt=1:length(Opt) % Test all simulation options
disp(['Testing ' class(Model) ' simulation option:'])
disp(Opt(iopt))
FitResults = Model.Sim_Single_Voxel_Curve(st,Opt(iopt));
% Compare inputs and outputs
fnm=fieldnames(FitResults);
FitResults = rmfield(FitResults,fnm(~ismember(fnm,Model.xnames))); fnm=fieldnames(FitResults);
[~,FitResults,GroundTruth]=comp_struct(FitResults,mat2struct(st,Model.xnames),[],[],.30);
assertTrue(isempty(FitResults) & isempty(GroundTruth),evalc('FitResults, GroundTruth'))
end
disp ..ok

function TestTeardown
setenv('ISDISPLAY','') % go faster! Fit only 2 voxels in FitData.m
setenv('ISCITEST','')


function rendering = spm_cfg_render
% SPM Configuration file for Render
%__________________________________________________________________________
% Copyright (C) 2013-2016 Wellcome Trust Centre for Neuroimaging

% $Id: spm_cfg_render.m 6925 2016-11-09 17:23:40Z guillaume $

%==========================================================================
% Extract
%==========================================================================

%--------------------------------------------------------------------------
% data Data
%--------------------------------------------------------------------------
data         = cfg_files;
data.tag     = 'data';
data.name    = 'Data';
data.help    = {'Images to create rendering/surface from (usually grey and white matter segmentations).'};
data.filter  = 'image';
data.ufilter = '.*';
data.num     = [1 Inf];

%--------------------------------------------------------------------------
% mode Output
%--------------------------------------------------------------------------
mode        = cfg_menu;
mode.tag    = 'mode';
mode.name   = 'Output';
mode.help   = {'Operation mode.'};
mode.labels = {'Save Rendering'
               'Save Extracted Surface'
               'Save Rendering and Surface'}';
mode.values = {1 2 3};
mode.val    = {3};

%--------------------------------------------------------------------------
% thresh Surface isovalue(s)
%--------------------------------------------------------------------------
thresh         = cfg_entry;
thresh.tag     = 'thresh';
thresh.name    = 'Surface isovalue(s)';
thresh.help    = {...
    'Enter one or more values at which isosurfaces through the input images will be computed.'
    'This is only relevant for extracting surfaces, not rendering.'};
thresh.strtype = 'r';
thresh.val     = {0.5};
thresh.num     = [1 Inf];

%--------------------------------------------------------------------------
% extract Extract Surface
%--------------------------------------------------------------------------
extract      = cfg_exbranch;
extract.tag  = 'extract';
extract.name = 'Extract Surface';
extract.val  = {data mode thresh};
extract.help = {'Surface extraction.'};
extract.prog = @spm_surf;
extract.vout = @vout_extract;

%==========================================================================
% Render
%==========================================================================

%--------------------------------------------------------------------------
% spmmat Select SPM.mat
%--------------------------------------------------------------------------
spmmat         = cfg_files;
spmmat.tag     = 'spmmat';
spmmat.name    = 'Select SPM.mat';
spmmat.help    = {'Select the SPM.mat file that contains the design specification.'};
spmmat.filter  = 'mat';
spmmat.ufilter = '^SPM\.mat$';
spmmat.num     = [1 1];

%--------------------------------------------------------------------------
% contrasts Contrast(s)
%--------------------------------------------------------------------------
contrasts         = cfg_entry;
contrasts.tag     = 'contrasts';
contrasts.name    = 'Contrast(s)';
contrasts.help    = {'Index of contrast(s). If more than one number is entered, analyse a conjunction hypothesis.'};
contrasts.strtype = 'n';
contrasts.num     = [1 Inf];

%--------------------------------------------------------------------------
% threshdesc Threshold type
%--------------------------------------------------------------------------
threshdesc        = cfg_menu;
threshdesc.tag    = 'threshdesc';
threshdesc.name   = 'Threshold type';
threshdesc.help   = {''};
threshdesc.labels = {'FWE' 'none' 'FDR'};
threshdesc.values = {'FWE' 'none' 'FDR'};
threshdesc.val    = {'FWE'};

%--------------------------------------------------------------------------
% thresh Threshold
%--------------------------------------------------------------------------
thresh         = cfg_entry;
thresh.tag     = 'thresh';
thresh.name    = 'Threshold';
thresh.help    = {''};
thresh.strtype = 'r';
thresh.num     = [1 1];
thresh.val     = {0.05};

%--------------------------------------------------------------------------
% extent Extent (voxels)
%--------------------------------------------------------------------------
extent         = cfg_entry;
extent.tag     = 'extent';
extent.name    = 'Extent (voxels)';
extent.help    = {''};
extent.strtype = 'w';
extent.num     = [1 1];
extent.val     = {0};

%--------------------------------------------------------------------------
% contrasts Contrast(s)
%--------------------------------------------------------------------------
contrasts1         = cfg_entry;
contrasts1.tag     = 'contrasts';
contrasts1.name    = 'Contrast(s)';
contrasts1.help    = {'Index of contrast(s) for masking - leave empty for no masking.'};
contrasts1.strtype = 'n';
contrasts1.num     = [1 Inf];

%--------------------------------------------------------------------------
% thresh Mask threshold
%--------------------------------------------------------------------------
thresh1         = cfg_entry;
thresh1.tag     = 'thresh';
thresh1.name    = 'Mask threshold';
thresh1.help    = {''};
thresh1.strtype = 'r';
thresh1.num     = [1 1];
thresh1.val     = {0.05};

%--------------------------------------------------------------------------
% mtype Nature of mask
%--------------------------------------------------------------------------
mtype        = cfg_menu;
mtype.tag    = 'mtype';
mtype.name   = 'Nature of mask';
mtype.help   = {''};
mtype.labels = {'Inclusive' 'Exclusive'};
mtype.values = {0 1};

%--------------------------------------------------------------------------
% mask Mask definition
%--------------------------------------------------------------------------
mask      = cfg_branch;
mask.tag  = 'mask';
mask.name = 'Mask definition';
mask.val  = {contrasts1 thresh1 mtype};
mask.help = {''};

%--------------------------------------------------------------------------
% generic Masking
%--------------------------------------------------------------------------
generic1        = cfg_repeat;
generic1.tag    = 'generic';
generic1.name   = 'Masking';
generic1.help   = {''};
generic1.values = {mask};
generic1.num    = [0 1];

%--------------------------------------------------------------------------
% conspec Contrast query
%--------------------------------------------------------------------------
conspec      = cfg_branch;
conspec.tag  = 'conspec';
conspec.name = 'Contrast query';
conspec.val  = {spmmat contrasts threshdesc thresh extent generic1};
conspec.help = {''};

%--------------------------------------------------------------------------
% generic Contrasts
%--------------------------------------------------------------------------
generic        = cfg_repeat;
generic.tag    = 'generic';
generic.name   = 'Contrasts';
generic.help   = {''};
generic.values = {conspec};
generic.num    = [1 3];

%--------------------------------------------------------------------------
% rendfile Render File
%--------------------------------------------------------------------------
rendfile         = cfg_files;
rendfile.tag     = 'rendfile';
rendfile.name    = 'Render File';
rendfile.help    = {'File containing the images to render on to.'};
rendfile.filter  = {'mat','mesh'};
rendfile.ufilter = '.*';
rendfile.num     = [1 1];

%--------------------------------------------------------------------------
% render Display Surface
%--------------------------------------------------------------------------
render      = cfg_exbranch;
render.tag  = 'display';
render.name = 'Display Surface';
render.val  = {rendfile generic};
render.help = {'Surface rendering.'};
render.prog = @run_render;

%==========================================================================
% rendering Rendering
%==========================================================================
rendering        = cfg_choice;
rendering.tag    = 'render';
rendering.name   = 'Rendering';
rendering.help   = {'Rendering utilities.'};
rendering.values = {extract render};

%==========================================================================
function run_render(job)
for i=1:numel(job.conspec)
    xSPM.swd       = spm_file(job.conspec(i).spmmat{1},'fpath');
    xSPM.Ic        = job.conspec(i).contrasts;
    xSPM.u         = job.conspec(i).thresh;
    xSPM.Im        = [];
    if ~isempty(job.conspec(i).mask)
        xSPM.Im    = job.conspec(i).mask.contrasts;
        xSPM.pm    = job.conspec(i).mask.thresh;
        xSPM.Ex    = job.conspec(i).mask.mtype;
    end
    xSPM.thresDesc = job.conspec(i).threshdesc;
    xSPM.k         = job.conspec(i).extent;
    %xSPM.n        = 1; % conjunction
    xSPM.units     = {'mm' 'mm' 'mm'};
    [SPM, xSPM]    = spm_getSPM(xSPM);
    dat(i) = struct('XYZ', xSPM.XYZ,...
                    't',   xSPM.Z',...
                    'mat', xSPM.M,...
                    'dim', xSPM.DIM);
end
% Force non-interactive mode...
global prevrend
prevrend = struct('rendfile',job.rendfile{1}, 'brt',1, 'col',eye(3));
spm_render(dat,1,job.rendfile{1});

%==========================================================================
function dep = vout_extract(job)

cdep = 1;
if any(job.mode==[1 3])
    dep(cdep)            = cfg_dep;
    dep(cdep).sname      = 'Render .mat File';
    dep(cdep).src_output = substruct('.','rendfile');
    dep(cdep).tgt_spec   = cfg_findspec({{'filter','mat','strtype','e'}});
    cdep = cdep + 1;
end

if any(job.mode==[2 3])
    for k=1:numel(job.thresh)
        dep(cdep)            = cfg_dep;
        dep(cdep).sname      = sprintf('Surface .gii File (thr=%.02f)', ...
            job.thresh(k));
        dep(cdep).src_output = substruct('.','surffile', '()',{k});
        dep(cdep).tgt_spec   = cfg_findspec({{'filter','mesh','strtype','e'}});
        cdep = cdep + 1;
    end
end


function test_bug1637

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY megplanar_sincos channelconnectivity ft_prepare_neighbours ft_channelselection

% this function checks whether megplanar_sincos relies on a fixed channel
% order or whether this can be totally mixed up (it should be able to deal
% with that!)
%
% http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=1637

% load neighbours
cfg = [];
cfg.method = 'template';
cfg.template = 'CTF275_neighb';
neighbours = ft_prepare_neighbours(cfg);

cd(dccnpath('/home/common/matlab/fieldtrip/data/test'))
load bug1637_hdr.mat
load bug1637_grad.mat

d = pwd;
ftPath = fileparts(mfilename('fullpath')); % get path, strip away 'ft_defaults'
ftPath = strrep(ftPath, '\', '\\');

cd(fullfile(ftPath, '..', 'private'));
errored = false;
try
  cfg = [];
  cfg.neighbours = neighbours;
  cfg.channel    = ft_channelselection('MEG', hdr.label);
  [neighbsel] = match_str({cfg.neighbours.label}, cfg.channel);
  cfg.neighbours = cfg.neighbours(neighbsel);
  cfg.neighbsel = channelconnectivity(cfg);

  montage_other = megplanar_sincos(cfg, hdr.grad);

  montage = [];
  montage{1} = megplanar_sincos(cfg, grad);

  [sel12, sel22] = match_str(montage{1}.labelold, montage_other.labelold);
  [sel11, sel21] = match_str(montage{1}.labelnew, montage_other.labelnew);
  if ~isequal(montage{1}.tra(sel11, sel12), montage_other.tra(sel21, sel22))
    warning('tra matrix differs - but that''s because the montage_other.tra consists of nans - checking whether nonzero elements are the same')
    idx1 = montage{1}.tra(sel11, sel12)~=0;
    idx2 = montage_other.tra(sel21, sel22)~=0;
    if ~isequal(idx1, idx2)
      errored = true;
      error('tra matrix qualitatively differ!');
    else
      disp('...passed!')
    end
  elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage_other.labelold(sel22))))
    errored = true;
    error('labelold mismatch');
  elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage_other.labelnew(sel21))))
    errored = true;
    error('labelnew mismatch');
  end

  for i=1:10 % 10 is an arbitrary number here, just do it for some time
    labperm = randperm(numel(grad.label));
    % permute everything
    grad.chanori    = grad.chanori(labperm, :);
    grad.chanpos    = grad.chanpos(labperm, :);
    grad.chantype   = grad.chantype(labperm, :);
    grad.chanunit   = grad.chanunit(labperm, :);
    grad.coiloriri  = grad.coilori(labperm, :);
    grad.coilpos    = grad.coilpos(labperm, :);
    grad.label      = grad.label(labperm, :);
    grad.tra        = grad.tra(labperm, :);

    montage{2} = megplanar_sincos(cfg, grad);

    % since we now reordered everything according to cfg.channel, the
    % following should not be necessary - but hey!
    [sel12, sel22] = match_str(montage{1}.labelold, montage{2}.labelold);
    [sel11, sel21] = match_str(montage{1}.labelnew, montage{2}.labelnew);
    if ~(isequal(montage{1}.tra(sel11, sel12), montage{2}.tra(sel21, sel22)))
      errored = true;
      error('tra matrix differs')
    elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage{2}.labelold(sel22))))
      errored = true;
      error('labelold mismatch');
    elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage{2}.labelnew(sel21))))
      errored = true;
      error('labelnew mismatch');
    end
  end

  for i=1:10 % 10 is an arbitrary number here, just do it for some time
    labperm = randperm(numel(grad.label));
    % permute everything
    grad.chanori    = hdr.grad.chanori(labperm, :);
    grad.chanpos    = hdr.grad.chanpos(labperm, :);
    grad.chantype   = hdr.grad.chantype(labperm, :);
    grad.chanunit   = hdr.grad.chanunit(labperm, :);
    grad.coiloriri  = hdr.grad.coilori(labperm, :);
    grad.coilpos    = hdr.grad.coilpos(labperm, :);
    grad.label      = hdr.grad.label(labperm, :);
    grad.tra        = hdr.grad.tra(labperm, :);

    montage{2} = megplanar_sincos(cfg, hdr.grad);

    % since we now reordered everything according to cfg.channel, the
    % following should not be necessary - but hey!
    [sel12, sel22] = match_str(montage{1}.labelold, montage{2}.labelold);
    [sel11, sel21] = match_str(montage{1}.labelnew, montage{2}.labelnew);
    idx1 = montage{1}.tra(sel11, sel12)~=0;
    idx2 = montage_other.tra(sel21, sel22)~=0;
    if ~isequal(idx1, idx2)
      errored = true;
      error('tra matrix qualitatively differ!');
    elseif ~(all(cellfun(@isequal, montage{1}.labelold(sel12), montage_other.labelold(sel22))))
      errored = true;
      error('labelold mismatch');
    elseif ~(all(cellfun(@isequal, montage{1}.labelnew(sel11), montage_other.labelnew(sel21))))
      errored = true;
      error('labelnew mismatch');
    end
  end

end
cd(d)

if errored
  error('channelorder matters whereas it should not!');
end


% plotcurve() - plot curve(s) with optional significance highlighting.
%
% Usage: >> plotcurve(times, data, 'key1', 'val1', 'key2', val2' ...);
%
% Required inputs:
%   times - [float] vector of time indices
%   data  - [float] data array, size of [n x times]. If n>1 several
%           curves are plotted (unless 'plotmean' option is used).
%
% Optional inputs:
%  'maskarray' = Input bootstrap limits. Can be 1-D [min max], 2-D (min
%                and max for all ordinate) or 3-D (min and max for all
%                ordinates at all time points).
%  'val2mask'  = Value to use for generating mask. By default use data.
%  'plotmean' = ['on'|'off'] For 'curve' plots only. Average all
%                frequencies given as input. Default: 'on'.
%  'highlightmode'  = ['background'|'bottom'] For 'curve' plots only,
%                display significant time regions either in the plot
%                background or underneatht the curve.
%  'xlabel'    = [string] x label
%  'ylabel'    = [string] y label
%  'legend'    = [cell] legend. Cell array of string, with one string
%                per curve.
%  'ylim'      = [min max] or [min] limits for the ordinate axis.
%  'title'     = Optional figure title. If two conditions are given
%                as input, title can be a cell array with two text
%                string elements {none}
%  'vert'      = Latencies to mark with a dotted vertical line   {none}
%  'linewidth' = Line width for marktimes traces (thick=2, thin=1) {2}
%  'chanlocs'  = channel location structure.
%  'plottopo'  = [min max] plot topography within the time limits defined
%                in this function. If several lines are given as input, one
%                scalp map is plot for each line.
%
% Authors: Arnaud Delorme, 2004, Bhaktivedanta Institute

% Copyright (C) 2004  Arnaud Delorme
%
% 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 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function plotcurve( times, R, varargin);

	if nargin < 2
        help plotcurve;
        return;
	end;
	g = finputcheck( varargin, { 'maskarray' ''        []       [];
                             'val2mask'      'real'    []           R;
                             'highlightmode' 'string'  { 'background' 'bottom' } 'background';
                             'plotmean'      'string'  { 'on' 'off' }            'off';
                             'plotindiv'     'string'  { 'on' 'off' }            'on';
                             'logpval'       'string'  { 'on' 'off' }            'off';
                             'title'         'string'  []                        '';
                             'xlabel'        'string'  []                        '';
                             'plotmode'      'string'  {'single' 'topo'}         'single';
                             'ylabel'        'string'  []                        '';
                             'legend'        'cell'    []                        {};
                             'colors'        'cell'    []                        {};
                             'plottopotitle' 'cell'    []                        {};
                             'chanlocs'      'struct'  []                        struct;
                             'ylim'          'real'    []                        [];
                             'vert'          'real'    []                        [];
                             'plottopo'      'real'    []                        [];
                             'linewidth'     'real'    []                        2;
                             'marktimes'     'real'    []                        [] });
   if isstr(g), error(g); end;
  % keyboard;
   if isempty(g.colors), g.colors = { 'r' 'g' 'b' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ...
                   'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' }; end;
   if strcmpi(g.plotindiv, 'off'), g.plotmean = 'on'; end;

   if ~any(length(times) == size(R))
       try,
           R = reshape(R, length(times), length(R)/length(times))';
       catch, error('Size of time input and array input does not match');
       end;
   end;

   % regions of significance
   % -----------------------
   if ~isempty(g.maskarray)
       if length(unique(g.maskarray)) < 4
          Rregions = g.maskarray;
       else
          Rregions = ones(size(g.val2mask));
          switch dims(g.maskarray)
               case 3, Rregions  (find(g.val2mask > g.maskarray(:,:,1) & (g.val2mask < g.maskarray(:,:,2)))) = 0;
               case 2, if size(g.val2mask,2) == size(g.maskarray,2)
                           Rregions  (find(g.val2mask < g.maskarray)) = 0;
                       elseif size(g.val2mask,1) == size(g.maskarray,1)
                           Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ...
                             & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0;
                       else
                           Rregions(find((g.val2mask > repmat(g.maskarray(:,1),[1 length(times)])) ...
                             & (g.val2mask < repmat(g.maskarray(:,2),[1 length(times)])))) = 0;
                       end;
               case 1, Rregions  (find(g.val2mask < repmat(g.maskarray(:),[1 size(g.val2mask,2)]))) = 0;
           end;
           Rregions = sum(Rregions,1);
       end;
   else
       Rregions = [];
   end

  % plotting
  % --------
  if size(R,1) == length(times), R = R'; end;
  if strcmpi(g.plotmean, 'on') | strcmpi(g.plotindiv, 'off')
      if strcmpi(g.plotindiv, 'on')
          R = [ R; mean(R,1) ];
      else
          R = mean(R,1);
      end;
  end;
  ax = gca;
  if ~isempty(g.maskarray) & strcmpi(g.highlightmode, 'bottom')
      pos = get(gca, 'position');
      set(gca, 'position', [ pos(1)+pos(3)*0.1 pos(2)+pos(4)*0.1 pos(3)*0.9 pos(4)*0.85 ]);
  end;

  % plot topographies
  % -----------------
  if ~isempty(g.plottopo)
      tmpax = gca;
      pos = get(gca, 'position');
      set(gca, 'position', [ pos(1) pos(2) pos(3) pos(4)/2 ]);

      for index = 1:size(g.plottopo)
          axes('position', [ (index-1)*pos(3)/size(g.plottopo,1)+pos(1) pos(2)+pos(4)/2 pos(3)/size(g.plottopo,1) pos(4)/2 ]);
          %topoplot(g.plottopo(index,:), g.chanlocs, 'maplimits', 'minmax');
          topoplot(g.plottopo(index,:), g.chanlocs);
          if ~isempty(g.plottopotitle)
              title(g.plottopotitle{index}, 'interpreter', 'none');
          end;
      end;

      axes(tmpax);
  end;

  for ind = 1:size(R,1)
      if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1
           plot(times,R(ind,:), 'k', 'linewidth', 2);
      elseif ~isempty(g.colors),
           tmp = plot(times,R(ind,:), 'k');
           set(tmp, 'color', g.colors{mod(ind-1, length(g.colors))+1});

           % change the line style when number of plots exceed number of colors in g.colors
           lineStyles = {'-', '--',':','-.'};
           set(tmp,'LineStyle',lineStyles{min(ceil(ind/length(g.colors)),length(lineStyles))});

           hold on;
      else plot(times,R(ind,:));
      end;
  end;

  % ordinate limits
  % ---------------
  if isempty(g.ylim),
      yll = min(reshape(R, [1 prod(size(R))]));
      ylh = max(reshape(R, [1 prod(size(R))]));
      yll2 = yll - (ylh-yll)/10;
      ylh2 = ylh + (ylh-yll)/10;
      if ~isnan(yll), g.ylim = [yll2 ylh2]; end;
  end;
  if ~isempty(g.ylim) & length(g.ylim) == 2
      if any(g.ylim)
          ylim(g.ylim);
      else
          ylim([0 1]);
          axis off;
          box off;
      end;
  elseif ~isempty(g.ylim)
      yl = ylim;
      ylim([g.ylim yl(2)]);
  end
  yl = ylim;

  % highlight regions
  % -----------------
  if ~isempty(g.maskarray)
      axsignif = highlight(ax, times, Rregions, g.highlightmode, g.xlabel);

      % replot data (above highlighted regions)
      % ---------
      axes(ax);
      for ind = 1:size(R,1)
          if ind == size(R,1) & strcmpi(g.plotmean, 'on') & size(R,1) > 1
               plot(times,R(ind,:), 'k', 'linewidth', 2);
          elseif ~isempty(g.colors),
              tmp = plot(times,R(ind,:), 'k'); set(tmp, 'color', g.colors{mod(ind-1, length(g.colors))+1} ); hold on;
          else plot(times,R(ind,:));
          end;
      end;
      if strcmpi(g.highlightmode, 'bottom'), xlabel(''); set(ax, 'xtick', []); end;
  end;
  box on;

  ylim(yl);
  if strcmpi(g.logpval, 'on')
      set(gca, 'ytickmode', 'manual', 'yticklabel', round(10.^-get(gca, 'ytick')*1000)/1000, 'ydir', 'reverse');
  end;

  % vertical lines
  % --------------
  hold on
  xl = xlim;
  if ~isnan(g.marktimes) % plot marked time
      for mt = g.marktimes(:)'
          plot([mt mt],[yl(1) yl(2)],'--k','LineWidth',g.linewidth);
      end
  end
  hold off
  if ~isempty(g.vert)
      for index = 1:length(g.vert)
          line([g.vert(index), g.vert(index)], [yl(1) yl(2)], 'linewidth', 1, 'color', 'm');
      end;
  end;
  xlim([times(1) times(end)]);

  % title and legend
  % ----------------
  if strcmpi(g.plotmode, 'topo') % plot in scalp array
      NAME_OFFSETX = 0.1;
      NAME_OFFSETY = 0.2;
      xx = xlim; xmin = xx(1); xdiff = xx(2)-xx(1); xpos = double(xmin+NAME_OFFSETX*xdiff);
      yy = ylim; ymax = yy(2); ydiff = yy(2)-yy(1); ypos = double(ymax-NAME_OFFSETY*ydiff);
      t=text(xpos, ypos,g.title);
      axis off;
      line([0 0], [yl(1) yl(2)], 'linewidth', 1, 'color', 'k');
      line([xl(1) xl(2)], [0 0], 'linewidth', 1, 'color', 'k');
      set(ax, 'userdata', { g.xlabel g.ylabel g.legend });
  else
      title(g.title, 'interpreter', 'none')
      if ~isempty(g.legend)
          hh = legend(g.legend(:));
          set(hh, 'unit', 'pixels', 'interpreter', 'none')
      end;
      if isempty(g.maskarray)
          xlabel(g.xlabel);
      end;
      ylabel(g.ylabel)
  end;

% -----------------
% highlight regions
% -----------------
function axsignif = highlight(ax, times, regions, highlightmode, myxlabel);
color1 = [0.75 0.75 0.75];
color2 = [0 0 0];
yl  = ylim;
yl(1) = yl(1)-max(abs(yl));
yl(2) = yl(2)+max(abs(yl));

if ~strcmpi(highlightmode, 'background')
    pos = get(ax, 'position');
    set(gca, 'xtick', []);
    axsignif = axes('position', [pos(1) pos(2)-pos(4)*0.05 pos(3) pos(4)*0.05 ]);
    plot(times, times, 'w');
    set(axsignif, 'ytick', []);
    yl2 = ylim;
    yl2(1) = yl2(1)-max(abs(yl2));
    yl2(2) = yl2(2)+max(abs(yl2));
    xlim([times(1) times(end)]);
    xlabel(myxlabel);
else
    axsignif = [];
    xlabel(myxlabel);
end;

if ~isempty(regions)
    axes(ax);
    in_a_region = 0;
    for index=1:length(regions)
        if regions(index) & ~in_a_region
            tmpreg(1) = times(index);
            in_a_region = 1;
        end;
        if (~regions(index) | index == length(regions)) & in_a_region
            tmpreg(2) = times(index);
            in_a_region = 0;
            if strcmpi(highlightmode, 'background')
                tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ...
                    [yl(1) yl(1) yl(2) yl(2)], color1); hold on;
                set(tmph, 'edgecolor', color1);
            else
                oldax = ax;
                axes(axsignif);
                tmph = patch([tmpreg(1) tmpreg(2) tmpreg(2) tmpreg(1)], ...
                    [yl2(1) yl2(1) yl2(2) yl2(2)], color2); hold on;
                set(tmph, 'edgecolor', color2);
                axes(oldax);
            end;
        end;
    end;
    ylim(yl);
end;

  function res = dims(array)
    res = min(ndims(array), max(size(array,2),size(array,3)));


function mrk= mrk_appendMarkers(mrk1, mrk2, Tmsec)
%MRK_APPENDMARKERS - Append (timewise) two marker structures
%
%Synopsis:
%  MRK= mrk_appendMarkers(MRK1, MRK2, TMSEC)
%  MRK= mrk_appendMarkers(MRK1, MRK2, CNT)
%
%Arguments:
%  MRK1, MRK2: marker structures (or empty [])
%  TMSEC:      duration of first data set in msec
%  CNT:        struct (like cnt) with fields T (duration of first data set
%              in samples) and fs (sampling rate).
%
%Returns:
%  mrk:        marker structure

misc_checkType(mrk1, 'STRUCT(time)');
misc_checkType(mrk2, 'STRUCT(time)');
misc_checkType(Tmsec, '!DOUBLE[1]|struct(T fs)');

if isempty(mrk1),
  mrk= mrk2;
  return;
end

if isstruct(Tmsec),
  cnt= Tmsec;
  Tmsec= sum(cnt.T)*1000/cnt.fs;
end

mrk2.time= mrk2.time + Tmsec;
if isempty(mrk1),
  mrk= mrk2;
  return;
end

if isfield(mrk1, 'event') && isfield(mrk1.event, 'blkno') && ...
    isfield(mrk2, 'event') && isfield(mrk2.event, 'blkno'),
  offset= max(mrk1.event.blkno) - min(mrk2.event.blkno) + 1;
  mrk2.event.blkno= mrk2.event.blkno + offset;
end

mrk= mrk_mergeMarkers(mrk1, mrk2);


%TRUNCQUAD_MODES  Compute colour modes for a truncated quadratic kernel
%
%   [modes depth energy inliers] = truncquad_modes(I, thresh[, use_variance[, search_width]])
%
% Computes the colour modes for each set of input vectors, using the
% truncated quadratic kernel.
%
% IN:
%   I - CxLxM array of L input colour vectors with C channels at M depths.
%   thresh - scalar cost truncation threshold.
%   use_variance - 0: sum cost over all input vectors; 1: sum cost over
%                  inlying input vectors / num_inliers; 2: sum cost over
%                  inliers / (num_inliers - 1). Default: 0.
%   search_width - scalar indicating depths above and below current depth
%                  to search for modes within. Default: M.
%
% OUT:
%   modes - CxN matrix of colour modes.
%   depth - 1xN list of indices of depth for each mode.
%   energy - 1xN list of costs for each mode.
%   inliers - LxN logical array indicating inliers used to calculate the
%             colour of each mode.

% $Id: truncquad_modes.m,v 1.2 2008/11/17 11:27:35 ojw Exp $

function varargout = truncquad_modes(varargin)
funcName = mfilename;
sourceList = {[funcName '.cxx']}; % Cell array of source files
vgg_mexcompile_script; % Compilation happens in this script
return


% Wrapper for BilinearSampler block:
% (c) 2016 Ankush Gupta

classdef BilinearSampler < dagnn.Layer
  methods
    function outputs = forward(obj, inputs, params)
      outputs = vl_nnbilinearsampler(inputs{1}, inputs{2});
      outputs = {outputs};
    end

    function [derInputs, derParams] = backward(obj, inputs, param, derOutputs)
      [dX,dG] = vl_nnbilinearsampler(inputs{1}, inputs{2}, derOutputs{1});
      derInputs = {dX,dG};
      derParams = {};
    end

    function outputSizes = getOutputSizes(obj, inputSizes)
      xSize = inputSizes{1};
      gSize = inputSizes{2};
      outputSizes = {[gSize(1), gSize(2), xSize(3), xSize(4)]};
    end

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


function varargout = det_internal(varargin)

switch class(varargin{1})

    case 'double'
        X = varargin{1};
        X = reshape(X,sqrt(length(X)),[]);
        varargout{1} = det(X);

    case 'char' % YALMIP send 'model' when it wants the epigraph or hypograph

        operator = struct('convexity','none','monotonicity','none','definiteness','none','model','callback');
        operator.range = [-inf inf];

        varargout{1} = [];
        varargout{2} = operator;
        varargout{3} = varargin{3};

    otherwise
end


function [c, ceq] = findEarliestArrivalNonlconFun(arrivalUT, departUT, dvFunc, maxDV)
    dv = dvFunc(arrivalUT, departUT);
    c(1) = dv - maxDV;
%     c(2) = -(arrivalUT-departUT);

    ceq = [];
end


% demo_e2s2_full()
%
% Trains and tests a Region-based semantic segmentation with end-to-end training on SIFT Flow.
% Requires the version of VGG-16 pretrained with MatConvNet's beta16, and does not
% work with beta20. This is most likely due to exploding gradients, although the architecture is identical.
%
% Copyright by Holger Caesar, 2016

% Add folders to path
setup();

% Settings
global glFeaturesFolder; % Define global variables to be used in all scripts
labelingsFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', sprintf('%s_e2s2_run1_exp2', 'SiftFlow'), 'labelings-test-epoch25');

% Download dataset
downloadSiftFlow();

% Download base network
downloadNetwork('version', 'beta16');

% Download Selective Search
downloadSelectiveSearch();

% Extract region proposals and labels
setupE2S2Regions();

% Train and test network
e2s2_wrapper_SiftFlow_full();

% Show example segmentation
fileList = dirSubfolders(labelingsFolder);
image = imread(fullfile(labelingsFolder, fileList{1}));
figure();
imshow(image);


classdef ParallelToFrameAtTimeCoordSystem < AbstractGeometricCoordSystem
    %ParallelToFrameCoordSystem Summary of this class goes here
    %   Detailed explanation goes here

    properties
        frame AbstractReferenceFrame
        time(1,1) double = 0;

        name(1,:) char
        lvdData LvdData
    end

    methods
        function obj = ParallelToFrameAtTimeCoordSystem(frame, time, name, lvdData)
            obj.frame = frame;
            obj.time = time;

            obj.name = name;
            obj.lvdData = lvdData;
        end

        function [rotMatToInertial] = getCoordSysAtTime(obj, ~, vehElemSet, ~)
            [~, ~, ~, rotMatToInertial] = obj.frame.getOffsetsWrtInertialOrigin(obj.time, vehElemSet);
        end

        function name = getName(obj)
            name = obj.name;
        end

        function setName(obj, name)
            obj.name = name;
        end

        function listboxStr = getListboxStr(obj)
            listboxStr = sprintf('%s (Parallel To "%s" at UT = %0.3f sec)', obj.getName(), obj.frame.getNameStr(), obj.time);
        end

        function useTf = openEditDialog(obj)
            output = AppDesignerGUIOutput({false});
            lvd_EditParallelToFrameAtTimeCoordSysGUI_App(obj, obj.lvdData, output);
            useTf = output.output{1};
        end

        function tf = isVehDependent(obj)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.isVehDependent();
            else
                tf = false;
            end
        end

        function tf = usesGroundObj(obj, groundObj)
            tf = obj.frame.usesGroundObj(groundObj);
        end

        function tf = usesGeometricPoint(obj, point)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricPoint(point);
            else
                tf = false;
            end
        end

        function tf = usesGeometricVector(obj, vector)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricVector(vector);
            else
                tf = false;
            end
        end

        function tf = usesGeometricCoordSys(obj, coordSys)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricCoordSys(coordSys);
            else
                tf = false;
            end
        end

        function tf = usesGeometricRefFrame(obj, refFrame)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricRefFrame(refFrame);
            else
                tf = false;
            end
        end

        function tf = usesGeometricAngle(obj, angle)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricAngle(angle);
            else
                tf = false;
            end
        end

        function tf = usesGeometricPlane(obj, plane)
            if(obj.frame.typeEnum == ReferenceFrameEnum.UserDefined)
                tf = obj.frame.geometricFrame.usesGeometricPlane(plane);
            else
                tf = false;
            end
        end

        function tf = isInUse(obj, lvdData)
            tf = lvdData.usesGeometricCoordSys(obj);
        end
    end
end


function obj = G_func_pTop_new(in1,in2,in3,in4)
coef_f0_q_sym2 = in1(:,2);
coef_f0_q_sym3 = in1(:,3);
coef_f0_q_sym4 = in1(:,4);
coef_f0_q_sym11 = in1(:,11);
coef_f1_q_sym1 = in2(:,1);
coef_f1_q_sym5 = in2(:,5);
coef_f1_q_sym6 = in2(:,6);
coef_f1_q_sym7 = in2(:,7);
coef_f0_q_sym18 = in1(:,18);
coef_f1_q_sym8 = in2(:,8);
coef_f1_q_sym9 = in2(:,9);
coef_f2_q_sym1 = in3(:,1);
coef_f0_q_sym22 = in1(:,22);
coef_f0_q_sym24 = in1(:,24);
coef_f2_q_sym5 = in3(:,5);
coef_f2_q_sym6 = in3(:,6);
coef_f2_q_sym7 = in3(:,7);
coef_f2_q_sym8 = in3(:,8);
coef_f2_q_sym9 = in3(:,9);
coef_f3_q_sym1 = in4(:,1);
coef_f3_q_sym5 = in4(:,5);
coef_f3_q_sym6 = in4(:,6);
coef_f3_q_sym7 = in4(:,7);
coef_f3_q_sym8 = in4(:,8);
coef_f3_q_sym9 = in4(:,9);
coef_f1_q_sym10 = in2(:,10);
coef_f1_q_sym11 = in2(:,11);
coef_f1_q_sym18 = in2(:,18);
coef_f1_q_sym22 = in2(:,22);
coef_f1_q_sym24 = in2(:,24);
coef_f2_q_sym10 = in3(:,10);
coef_f2_q_sym11 = in3(:,11);
coef_f2_q_sym18 = in3(:,18);
coef_f2_q_sym22 = in3(:,22);
coef_f2_q_sym24 = in3(:,24);
coef_f3_q_sym10 = in4(:,10);
coef_f3_q_sym11 = in4(:,11);
coef_f3_q_sym18 = in4(:,18);
coef_f3_q_sym22 = in4(:,22);
coef_f3_q_sym24 = in4(:,24);
t2 = coef_f1_q_sym1.*2.0;
t3 = coef_f2_q_sym1.*2.0;
t4 = coef_f3_q_sym1.*2.0;
obj = reshape([coef_f0_q_sym11-coef_f1_q_sym18,-coef_f2_q_sym18,-coef_f3_q_sym18,-coef_f1_q_sym22,coef_f0_q_sym11-coef_f2_q_sym22,-coef_f3_q_sym22,-coef_f1_q_sym24,-coef_f2_q_sym24,coef_f0_q_sym11-coef_f3_q_sym24,coef_f0_q_sym2-coef_f1_q_sym5+coef_f0_q_sym18+coef_f1_q_sym11+t2,-coef_f2_q_sym5+coef_f2_q_sym11+t3,-coef_f3_q_sym5+coef_f3_q_sym11+t4,coef_f0_q_sym3-coef_f1_q_sym6+coef_f0_q_sym22,coef_f0_q_sym2+coef_f0_q_sym18-coef_f2_q_sym6,-coef_f3_q_sym6,coef_f0_q_sym4-coef_f1_q_sym7+coef_f0_q_sym24,-coef_f2_q_sym7,coef_f0_q_sym2+coef_f0_q_sym18-coef_f3_q_sym7,-coef_f1_q_sym8+coef_f1_q_sym11+t2,coef_f0_q_sym3+coef_f0_q_sym22-coef_f2_q_sym8+coef_f2_q_sym11+t3,-coef_f3_q_sym8+coef_f3_q_sym11+t4,-coef_f1_q_sym9,coef_f0_q_sym4+coef_f0_q_sym24-coef_f2_q_sym9,coef_f0_q_sym3+coef_f0_q_sym22-coef_f3_q_sym9,-coef_f1_q_sym10+coef_f1_q_sym11+t2,-coef_f2_q_sym10+coef_f2_q_sym11+t3,coef_f0_q_sym4+coef_f0_q_sym24-coef_f3_q_sym10+coef_f3_q_sym11+t4],[3,9]);


function IESMnew = IESMwithNewFlippedStateQPOTTS(IESM,Q)

IESMnew = IESM;

for count=1:100000000
    IESMnew(2,2)=floor(1+Q*rand);
    if IESMnew(2,2)~=IESM(2,2)
        break
    end
end

github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34784-monte-carlo-simulation-of-two-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 2D square-lattice - microstructure/IESMwithNewFlippedStateQPOTTS.m


function rtk=update_stat(rtk,obs,sol_stat)

global glc
opt=rtk.opt;
nobs=size(obs,1);

rtk.sol.time=timeadd(obs(1).time,-rtk.x(rtk.ic+1)/glc.CLIGHT);
rtk.sol.ns=0;
for i=1:nobs
    for j=1:opt.nf
        sat=obs(i).sat;
        if rtk.sat(sat).vsat(j)==0,continue;end
        rtk.sat(sat).lock(j)=rtk.sat(sat).lock(j)+1;
        rtk.sat(sat).outc(j)=0;
        if j==1,rtk.sol.ns=rtk.sol.ns+1;end
    end
end

if rtk.sol.ns<4
    rtk.sol.stat=0;
else
    rtk.sol.stat=sol_stat;
end

if rtk.sol.stat==glc.SOLQ_FIX

else
    rtk.sol.pos=rtk.x(1:3)';
    rtk.sol.posP(1)=rtk.P(1,1);
    rtk.sol.posP(2)=rtk.P(2,2);
    rtk.sol.posP(3)=rtk.P(3,3);
    rtk.sol.posP(4)=rtk.P(1,2);
    rtk.sol.posP(5)=rtk.P(2,3);
    rtk.sol.posP(6)=rtk.P(1,3);
end

% clk
rtk.sol.dtr(1)=rtk.x(rtk.ic+1)/glc.CLIGHT;
% isb
rtk.sol.dtr(2)=rtk.x(rtk.ic+2)/glc.CLIGHT;
rtk.sol.dtr(3)=rtk.x(rtk.ic+3)/glc.CLIGHT;
rtk.sol.dtr(4)=rtk.x(rtk.ic+4)/glc.CLIGHT;
rtk.sol.dtr(5)=rtk.x(rtk.ic+5)/glc.CLIGHT;

for i=1:nobs
    for j=1:rtk.opt.nf
        rtk.sat(obs(i).sat).snr(j)=obs(i).S(j);
    end
end

for i=1:glc.MAXSAT
    for j=1:rtk.opt.nf
        if bitand(rtk.sat(i).slip(j),3)
            rtk.sat(i).slip(j)=rtk.sat(sat).slip(j)+1;
        end
        if rtk.sat(i).fix(j)==2&&sol_stat~=glc.SOLQ_FIX
            rtk.sat(i).fix(j)=1;
        end
    end
end

return


function varargout = run_opf(varargin)
%run_opf  Run an optimal power flow.
%
%   run_opf(d, mpopt)
%   run_opf(d, mpopt, ...)
%   task = run_opf(...)
%
%   See also run_mp.

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

[varargout{1:nargout}] = run_mp(@mp.task_opf, varargin{:});


function a = eq( x, y )

%Disciplined convex programming information for EQ (==):
%   Both the left- and right-hand sides of an equality constraint must
%   be affine (or constant). If either side of the constraint is complex,
%   then the real and imaginary portions are constrained separately.
%
%Disciplined geometric programming information for EQ (>):
%   Both the left- and right-hand sides of an equality constraint must
%   be log-affine, which includes positive constants and monomials.

b = newcnstr( evalin( 'caller', 'cvx_problem', '[]' ), x, y, '==' );
if nargout, a = b; end

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