classdef calc_across < ZmapVGridFunction
    % CALC_ACROSS calculate a-value parameters for a cross section

    properties
        mc_auto         McAutoEstimate      = ZmapGlobal.Data.UseAutoEstimate
        aval_method
    end

    properties(Constant)
        PlotTag         = 'calc_across'
        ReturnDetails   = cell2table({ ... VariableNames, VariableDescriptions, VariableUnits
            'a_value','a-value',''...
            }, 'VariableNames', {'Names','Descriptions','Units'})

        CalcFields      = {} % cell array of charstrings, matching into ReturnDetails.Names

        ParameterableProperties = []; % array of strings matching into obj.Properties
        References="";

        aval_methods = {' a(M=0) for fixed b',...
            'a(M=0) for Mc(MaxC) + M(corr)',...
            'a(M=0) for M(EMR)',...
            'a(M=0) by r1 & Mc by r2 '}
    end

    methods
        function obj=calc_across(zap, varargin)
            % CALC_ACROSS
            % obj = CALC_ACROSS() takes catalog, grid, and eventselection from ZmapGlobal.Data
            %
            % obj = CALC_ACROSS(ZAP) where ZAP is a ZmapAnalysisPkg

            obj@ZmapVGridFunction(zap, 'a_value');

            report_this_filefun();
            unimplemented_error()
            obj.parseParameters(varargin);
            obj.StartProcess();
        end

        function InteractiveSetup(obj)
            % create a dialog that allows user to select parameters neccessary for the calculation

            %% make the interface
            zdlg = ZmapDialog();

            zdlg.AddHeader('Choose stuff');
            zdlg.AddMcAutoEstimateCheckbox('mc_auto',obj.mc_auto);
            zdlg.AddPopup('aval_method', 'A-value calculation method', obj.aval_methods,1,...
                'methods used to calculate a value');
            [res,okPressed] = zdlg.Create('Name', 'A-Value Parameters [xsec]');
            if ~okPressed
                return
            end
            obj.SetValuesFromDialog(res);
            obj.doIt()
        end

        function SetValuesFromDialog(obj, res)
            % called when the dialog's OK button is pressed
            obj.mc_auto = res.mc_auto;

            obj.aval_method = res.aval_method;

            tgl1 = tgl1.Value;
            tgl2 = tgl2.Value;
            bRandom = get(chkRandom, 'Value');
            bGridEntireArea = get(chkGridEntireArea, 'Value');
            close,sel ='ca',
            calc_across_orig(sel)

        end

        function results=Calculate(obj)
            % once the properties have been set, either by the constructor or by interactive_setup
            % get the grid-size interactively and calculate the values in the grid by sorting the
            % seismicity and selecting the appropriate neighbors to each grid point

            function out=calculation_function(catalog)
                % calulate values at a single point
            end
        end

        function ModifyGlobals(obj)
        end
    end

    methods(Hidden)
    end
    methods(Static)
        function h = AddMenuItem(parent, zapFcn, varargin)
            % create a menu item
            label = 'a-value [xsec]';
            h = uimenu(parent, 'Label', label,...
                'MenuSelectedFcn', @(~,~)XZfun.calc_across(zapFcn()),...
                varargin{:});
        end
    end
end

function calc_across_orig(sel)
    % The aValue, Mc and a resolution estimation in each
    % volume around a grid point, or defined by a radius
    % (ra for Mc, ri for aValue) containing ni earthquakes
    % will be calculated
    %
    %   This subroutine provides 4 methods for calculation:
    % 1. calculate a-value for const b-value
    % 2. calculate a-value by maxlikelihood (MaxLikelihoodA.m)
    %    of b-value and Mc defined by MaxC
    % 3. calculate a-value by maxlikelihood (MaxLikelihoodA.m)
    %    of b-value and Mc defined by Mc(EMR)
    % 4. calculate a-value within the radius ri and Mc within ra, where ra > ri
    %
    %   This subrouting is based on bcross.m
    %       by Stefan Wiemer 1/95
    %   and was modified
    %       by Thomas van Stiphout 3/2004

    report_this_filefun();

    % Do we have to create the dialogbox?
    if sel == 'in'
        % Set the grid parameter
        % initial values
        %
        ra=10;
        ri=5;
        dd = 1.00;
        dx = 1.00 ;
        ni = 100;
        fFixbValue=0.9
        bv2 = NaN;
        Nmin = 50;
        stan2 = NaN;
        stan = NaN;
        prf = NaN;
        av = NaN;
        nRandomRuns = 1000;
        bGridEntireArea = false;

        % Create the dialog box
        figure_w_normalized_uicontrolunits(...
            'Name','Grid Input Parameter',...
            'NumberTitle','off', ...
            'units','points',...
            'Visible','on', ...
            'Position',[ ZG.welcome_pos + [200, -200], 550, 300], ...
            'Color', [0.8 0.8 0.8]);
        axis off

        % Dropdown list
        labelList2=[' a(M=0) for fixed b | a(M=0) for Mc(MaxC) + M(corr) | a(M=0) for M(EMR) | a(M=0) by r1 & Mc by r2 '];
        hndl2=uicontrol(...
            'Style','popup',...
            'Position',[ 0.2 0.77  0.6  0.08],...
            'Units','normalized',...
            'String',labelList2,...
            'BackgroundColor','w',...
            'callback',@callbackfun_001);

        % Set selection to 'Radius check'
        set(hndl2,'value',1);

        % Edit fields, radiobuttons, and checkbox
        freq_field=uicontrol('Style','edit',...
            'Position',[.30 .60 .12 .06],...
            'Units','normalized','String',num2str(ni),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_002);

        freq_field0=uicontrol('Style','edit',...
            'Position',[.30 .50 .06 .06],...
            'Units','normalized','String',num2str(ra),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_003);

        freq_field1=uicontrol('Style','edit',...
            'Position',[.36 .50 .06 .06],...
            'Units','normalized','String',num2str(ri),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_004);

        freq_field2=uicontrol('Style','edit',...
            'Position',[.30 .40 .06 .06],...
            'Units','normalized','String',num2str(dx),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_005);

        freq_field3=uicontrol('Style','edit',...
            'Position',[.36 .40 .06 .06],...
            'Units','normalized','String',num2str(dd),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_006);

        tgl1 = uicontrol('BackGroundColor', [0.8 0.8 0.8], ...
            'Style','radiobutton',...
            'string','Number of events:',...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'Position',[.02 .60 .28 .06], 'callback',@callbackfun_007,...
            'Units','normalized');

        % Set to constant number of events
        set(tgl1,'value',1);

        tgl2 =  uicontrol('BackGroundColor',[0.8 0.8 0.8],'Style','radiobutton',...
            'string','Constant radius [km]:',...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'Position',[.52 .60 .40 .06], 'callback',@callbackfun_008,...
            'Units','normalized');

        chkRandom = uicontrol('BackGroundColor',[0.8 0.8 0.8],'Style','checkbox',...
            'String', 'Additional random simulation',...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'Position',[.52 .40 .40 .06],...
            'Units','normalized');
        txtRandomRuns = uicontrol('Style','edit',...
            'Position',[.80 .30 .12 .06],...
            'Units','normalized','String',num2str(nRandomRuns),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_009);

        freq_field4 =  uicontrol('Style','edit',...
            'Position',[.30 .30 .12 .06],...
            'Units','normalized','String',num2str(Nmin),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_010);

        freq_field5 =  uicontrol('Style','edit',...
            'Position',[.30 .20 .12 .06],...
            'Units','normalized','String',num2str(fFixbValue),...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'callback',@callbackfun_011);

        chkGridEntireArea = uicontrol('BackGroundColor', [0.8 0.8 0.8], ...
            'Style','checkbox',...
            'string','Create grid over entire area',...
            'FontSize',ZmapGlobal.Data.fontsz.m ,...
            'FontWeight','bold',...
            'Position',[.52 .50 .40 .06], 'Units','normalized', 'Value', 0);

        % Buttons
        uicontrol('BackGroundColor', [0.8 0.8 0.8], 'Style', 'pushbutton', ...
            'Units', 'normalized', 'Position', [.80 .05 .15 .10], ...
            'Callback', @(~,~)close, 'String', 'Cancel');

        % Labels
        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [0.2 1 0], 'HorizontalAlignment', 'left',  ...
            'FontSize', fontsz.l, 'FontWeight', 'bold', 'String', 'Please select a Mc estimation option');

        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [0.3 0.75 0], 'HorizontalAlignment', 'left',  ...
            'FontSize', fontsz.l, 'FontWeight', 'bold', 'String', 'Grid parameters');

        text('Color',[0 0 0], 'Units', 'normalized', ...
            'Position', [-.14 .51 0], 'HorizontalAlignment', 'left',  ...
            'FontSize',ZmapGlobal.Data.fontsz.m, 'FontWeight', 'bold', 'String','Radius ra / ri [km]:');

        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [-0.14 .39 0],  'HorizontalAlignment', 'left', ...
            'FontSize',ZmapGlobal.Data.fontsz.m, 'FontWeight', 'bold', 'String', 'Spacing hor / depth [km]:');

        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [-0.14 .27 0],  'HorizontalAlignment', 'left', ...
            'FontSize',ZmapGlobal.Data.fontsz.m, 'FontWeight', 'bold', 'String', 'Min. number of events:');

        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [-0.14 .15 0],  'HorizontalAlignment', 'left', ...
            'FontSize',ZmapGlobal.Data.fontsz.m, 'FontWeight', 'bold', 'String', 'Fixed b-value:');

        text('Color', [0 0 0], 'Units', 'normalized', ...
            'Position', [0.5 0.27 0],  'HorizontalAlignment', 'left', ...
            'FontSize',ZmapGlobal.Data.fontsz.m, 'FontWeight', 'bold', 'String', 'Number of runs:');

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

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

    if sel == 'ca'
        figure(xsec_fig());
        set(gca,'NextPlot','add')

        if bGridEntireArea % Use entire area for grid
            vXLim = get(gca, 'XLim');
            vYLim = get(gca, 'YLim');
            x = [vXLim(1); vXLim(1); vXLim(2); vXLim(2)];
            y = [vYLim(2); vYLim(1); vYLim(1); vYLim(2)];
            x = [x ; x(1)];
            y = [y ; y(1)];     %  closes polygon
            clear vXLim vYLim;
        else

            set(gca,'NextPlot','add')
            ax=findobj(gcf,'Tag','mainmap_ax');
            [x,y, mouse_points_overlay] = select_polygon(ax);
        end % of if bGridEntireArea

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

        %create a rectangular grid
        xvect=[min(x):dx:max(x)];
        yvect=[min(y):dd:max(y)];
        gx = xvect;gy = yvect;
        tmpgri=zeros((length(xvect)*length(yvect)),2);
        n=0;
        for i=1:length(xvect)
            for j=1:length(yvect)
                n=n+1;
                tmpgri(n,:)=[xvect(i) yvect(j)];
            end
        end
        %extract all gridpoints in chosen polygon
        XI=tmpgri(:,1);
        YI=tmpgri(:,2);

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

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

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

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

        %  make grid, calculate start- endtime etc.  ...
        %
        [t0b, teb] = bounds(newa.Date) ;
        n = newa.Count;
        tdiff = round((teb-t0b)/ZG.bin_dur);
        loc = zeros(3, length(gx)*length(gy));

        % loop over  all points
        %
        i2 = 0.;
        i1 = 0.;
        avg = nan(length(newgri),10);
        allcount = 0.;
        wai = waitbar(0,' Please Wait ...  ');
        set(wai,'NumberTitle','off','Name','a-value grid - percent done');
        drawnow
        %
        % loop

        % overall b-value
        [bv, magco, stan, av] =  bvalca3(newa.Magnitude, obj.mc_auto);
        overall_b_value = bv;
        ZG.overall_b_value = bv;
        no1 = newa.Count;
        %
        globalcatalog = ZG.primeCatalog;
        for i= 1:length(newgri(:,1))
            x = newgri(i,1);y = newgri(i,2);
            allcount = allcount + 1.;
            i2 = i2+1;

            % calculate distance from center point and sort wrt distance
            l = sqrt(((xsecx' - x)).^2 + ((xsecy + y)).^2) ;
            [s,is] = sort(l);
            b = newa(is(:,1),:) ;       % re-orders matrix to agree row-wise

            if tgl1 == 0   % take point within r
                l3 = l <= ra;
                l4 = l <= ri;
                b = globalcatalog.subset(l3);        % new data per grid point (b) is sorted in distance
                bri = globalcatalog.subset(l4);
                rd = ra;
            else
                % take first ni points
                b = b(1:ni,:);      % new data per grid point (b) is sorted in distance
                rd = s(ni);

            end

            % Number of earthquakes per node
            [nX,nY] = size(b);

            %estimate the completeness and b-value
            ZG.newt2 = b;

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

                if obj.aval_method == 1;   % Calculation of a-value by const b-value, and Mc
                    bv2 = fFixbValue;           % read fixed bValue to the bv2
                    magco=calc_Mc(b, Methods.MaxCurvature, 0.1);
                    l = b.Magnitude >= magco-0.05;
                    if length(b(l,:)) >= Nmin   % calculation of the a-value according to determined Mc (magco)
                        faValue = calc_MaxLikelihoodA(b, bv2);
                        stan2 = NaN;
                        bv = NaN;
                    else
                        bv = NaN; bv2 = NaN; magco = NaN; av = NaN; faValue = NaN; stan2 = NaN; stan = NaN;
                    end

                    % a(0) for Mc(MAxCurv) + Mc(Corr)
                elseif obj.aval_method == 2
                    [bv, magco, stan, av, pr] =  bvalca3(b.Magnitude, McAutoEstimate.auto, overall_b_value);
                    magco = magco + 0.2;    % Add 0.2 to Mc (Tobias)
                    l = b.Magnitude >= magco-0.05;
                    if sum(l) >= Nmin
                        [bv2, stan2,  faValue] = calc_bmemag(b.Magnitude(l), 0.1);
                    else
                        bv = NaN; bv2 = NaN, magco = NaN; av = NaN; faValue = NaN;
                    end

                elseif obj.aval_method == 3; % a(0) for Mc(EMR)
                    [magco, bv2, faValue, stan2, stan] = calc_McEMR(b, 0.1);
                    l = b.Magnitude >= magco-0.05;
                    if length(b(l,:)) >= Nmin
                        faValue = calc_MaxLikelihoodA(b, bv2);
                    else
                        bv = NaN; bv2 = NaN, magco = NaN; av = NaN; faValue = NaN;
                    end

                elseif obj.aval_method == 4
                    % a(0) by r1 and Mc by r2
                    if length(b) >= Nmin
                        [bv, magco, stan, av, pr] =  bvalca3(b.Magnitude, McAutoEstimate.auto, overall_b_value);
                        magco = magco + 0.2;    % Add 0.2 to Mc (Tobias)
                        bv2 = fFixbValue;
                        l = bri(:,6) >= magco-0.05;
                        faValue = calc_MaxLikelihoodA(bri(l,:), bv2);
                    else
                        bv = NaN; bv2 = NaN, magco = NaN; av = NaN; faValue = NaN;
                    end
                end

                % Perform random simulation
                if bRandom
                    nNumberPerNode = length(b);
                    %        [fAverageBValue, fAverageStdDev] = calc_RandomBValue(newa, nNumberPerNode, nRandomRuns);
                    [fStdDevB, fStdDevMc, q1, q2] = calc_BootstrapB(b, nRandomRuns, Nmin);
                else
                    fStdDevB = NaN;
                    fStdDevMc = NaN;
                end

            else % of if length(b) >= Nmin
                bv = NaN; bv2 = NaN; stan = NaN; stan2 = NaN; prf = NaN; magco = NaN; av = NaN; faValue = NaN; fStdDevB = NaN; fStdDevMc = NaN;
                b = [NaN NaN NaN NaN NaN NaN NaN NaN NaN];
                nX = NaN;
            end
            mab = max(b.Magnitude) ;
            if isempty(mab); mab = NaN; end
            avg(allcount,:)  = [bv magco x y rd bv2 stan2 av stan faValue ];
            waitbar(allcount/itotal)
        end  % for  newgri

        if bRandom
            clear nNumberPerNode q1 q2 fStdDevB fStdDevMc;
        end
        clear bRandom;
        % save data
        %
        drawnow
        gx = xvect;gy = yvect;

        catsave3('calc_across_orig');
        close(wai)
        watchoff

        save across2.mat ll a tmpgri newgri lat1 lon1 lat2 lon2 ZG.xsec_defaults.WidthKm  avg ra xvect yvect gx gy dx dd ZG.bin_dur newa ;

        % reshape a few matrices
        %

        normlap2=nan(length(tmpgri(:,1)),1)
        normlap2(ll)= avg(:,1);
        bls=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,5);
        reso=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,6);
        bValueMap=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,2);
        MaxCMap=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,7);
        MuMap=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,8);
        avm=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,9);
        SigmaMap=reshape(normlap2,length(yvect),length(xvect));

        normlap2(ll)= avg(:,10);
        aValueMap=reshape(normlap2,length(yvect),length(xvect));

        valueMap = aValueMap;
        kll = ll;
        % View the a-value map
        view_av2

    end

    % Load exist b-grid
    if sel == 'lo'
        [file1,path1] = uigetfile(['*.mat'],'a-value gridfile');
        if length(path1) > 1

            load([path1 file1])
            xsecx = newa(:,end)';
            xsecy = newa(:,7);
            xvect = gx; yvect = gy;
            tmpgri=zeros((length(xvect)*length(yvect)),2);

            normlap2=nan(length(tmpgri(:,1)),1)
            normlap2(ll)= avg(:,1);
            bls=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,5);
            reso=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,6);
            bValueMap=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,2);
            MaxCMap=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,7);
            MuMap=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,8);
            avm=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,9);
            SigmaMap=reshape(normlap2,length(yvect),length(xvect));

            normlap2(ll)= avg(:,10);
            aValueMap=reshape(normlap2,length(yvect),length(xvect));

            valueMap = aValueMap;

            nlammap
            [xsecx xsecy,  inde] =mysect(globalcatalog.Y',globalcatalog.X',globalcatalog.Z,ZG.xsec_defaults.WidthKm,0,lat1,lon1,lat2,lon2);
            % Plot all grid points
            set(gca,'NextPlot','add')
            plot(newgri(:,1),newgri(:,2),'+k')
            view_av2
        else
            return
        end
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ni=str2double(freq_field.String);
        freq_field.String=num2str(ni);
        tgl2.Value=0;
        tgl1.Value=1;
    end

    function callbackfun_003(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ra=str2double(freq_field0.String);
        freq_field0.String=num2str(ra);
        tgl2.Value=1;
        tgl1.Value=0;
    end

    function callbackfun_004(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ri=str2double(freq_field1.String);
        freq_field1.String=num2str(ri);
        tgl2.Value=1;
        tgl1.Value=0;
    end

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        dx=str2double(freq_field2.String);
        freq_field2.String=num2str(dx);
    end

    function callbackfun_006(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        dd=str2double(freq_field3.String);
        freq_field3.String=num2str(dd);
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        tgl2.Value=0;
    end

    function callbackfun_008(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        tgl1.Value=0;
    end

    function callbackfun_009(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        nRandomRuns=str2double(txtRandomRuns.String);
        txtRandomRuns.String=num2str(nRandomRuns);
    end

    function callbackfun_010(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        Nmin=str2double(freq_field4.String);
        freq_field4.String=num2str(Nmin);
    end

    function callbackfun_011(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        fFixbValue=str2double(freq_field4.String);
        freq_field4.String=num2str(fFixbValue);
    end
end


function h = drawLine3d(lin, varargin)
%DRAWLINE3D Draw a 3D line clipped by the current axes.
%
%   drawLine3d(LINE) draws the line LINE on the current axis, by clipping
%   with the current axis.
%
%   drawLine3d(LINE, PARAM, VALUE) accepts parameter/value pairs, like
%   for plot function. Color of the line can also be given as a single
%   parameter.
%
%   drawLine3d(AX,...) plots into AX instead of GCA.
%
%   H = drawLine3d(...) returns a handle to the created line object.
%   If the line is not clipped by the axis, function returns -1.
%
%   Example
%     % draw a sphere together with the three main axes
%     figure; hold on;
%     drawSphere([40 30 20 30]);
%     view(3); axis equal; axis([-20 80 -20 80 -20 80])
%     drawLine3d([0 0 0   1 0 0], 'k');
%     drawLine3d([0 0 0   0 1 0], 'k');
%     drawLine3d([0 0 0   0 0 1], 'k');
%     light;
%
%
%   See also:
%     lines3d, createLine3d, clipLine3d
%

% ---------
% author : David Legland
% INRA - TPV URPOI - BIA IMASTE
% created the 17/02/2005.

% Parse and check inputs
isLine3d = @(x) validateattributes(x,{'numeric'},...
    {'nonempty','nonnan','real','finite','size',[nan,6]});
defOpts.Color = 'b';
[hAx, lin, varargin] = ...
    parseDrawInput(lin, isLine3d, 'line', defOpts, varargin{:});

% extract limits of the bounding box
box = [get(gca, 'xlim') get(gca, 'ylim') get(gca, 'zlim')];

% clip the line with the limits of the current axis
edge = clipLine3d(lin, box);

% draw the clipped line
if sum(isnan(edge)) == 0
    hh = drawEdge3d(hAx, edge);
    if ~isempty(varargin)
        set(hh, varargin{:});
    end
else
    hh = [];
end

% process output
if nargout > 0
    h = hh;
end


%
%		 imgOut = bilateralFilterS(img, imgEdges, sigma_s, sigma_r)
%
%        This function implements a bilateral filter without
%        approximations. Note this function is very slow!
%
%		 Input:
%			-img: is an image to be filtered.
%           -imgEdges: is an edge image, where its edges will be transfered
%           to img. Note set this to [] if you do not want to transfer
%           edges.
%           -sigma_s: is the spatial sigma value.
%           -sigma_r: is the range sigma value.
%
%		 Output:
%			-imgOut: is the filtered image.
%
%     Copyright (C) 2014-18  Francesco Banterle
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
%


%  WaveForm DataBase (WFDB) Toolbox
%
%
%This is a set of MATLAB functions and wrappers for reading, writing, and processing
%files in the formats used by PhysioBank databases (among others).
%The WFDB Toolbox has support for reading public PhysioNet databases directly from
%web. This feature allows your code to analyze a wide range of physiological
%signals available from PhysioBank without the need to download entire
%records and to store them locally. This toolbox is distributed under the LGPL
%license (see LICENSE.txt file in this directory). For more informationa about the
%toolbox please go to: http://www.physionet.org
%
%
%
%
%  Table of Contents (T0C)
% -----------------------
%   ann2rr          - Extract a list of intervals from an annotation file
%   bxb             - ANSI/AAMI-standard beat-by-beat annotation comparator
%   dfa             - Detrended Fluctuation Analysis
%   corrint         - Correlation Integral Analysis
%   edr             - Derives a respiration signal from an ECG signal
%   ecgpuwave       - Estimation of QRS and P waves from ECG signals
%   gqrs            - Estimation of QRS from ECG signals
%   lomb	        - Estimates power spectrum using the Lomb periodogram method
%   mat2wfdb        - Writes a MATLAB variable into a WDFB record file
%   mrgann          - Merge annotation files
%   msentropy       - Multi scale entropy estimation
%   physionetdb     - Get information about all of PhysioNet's available databases and signals
%   pbsearch        - Search PhysioBank from MATLAB's browser for records with specific features.
%   rdann           - Read annotation files for WFDB records
%   rdmat           - Reads a signal into the workspace from a *.mat file generated by WFDB2MAT
%   rdmimic2wave    - Searches MIMIC II matched waveform records within a clinical time range
%   rdsamp          - Read signal files of WFDB records
%   sortann         - Rearrange annotations in canonical order
%   snip            - Copy an excerpt of a WFDB record
%   sqrs            - Finds the QRS complexes of a WFDB ECG record signal
%   surrogate       - Generates amplitude adjusted phase shuffled surrogate time series
%   sumann	        - Summarize the contents of a WFDB annotation file
%   tach            - Calculates instantaneous heart rate of a WFDB ECG record signal
%   visgraph        - Visibility Graph Analysis
%   wfdb            - Prints this help information of the Toolbox
%   wfdb2mat        - Converts a record *.dat file into a *.mat file.
%   wfdbexec        - Executes a system call to any installed native WFDB command.
%   wabp	        - Arterial blood pressure (ABP) pulse detector
%   wfdbdemo        - Demonstration of the WFDB App Toolbox
%   wfdbdesc        - Return signal information for about a WFDB record
%   wfdbloadlib     - Load WFDB library and displays Toolbox configuration.
%   wfdbRecordViewer- GUI for visualizing WFDB records and annotations
%   wfdbtest        - Script to test installation of the Toolbox
%	wfdbtime        - Converts sample index to WFDB Time based on WFDB record information
%	wfdbtool        - Launches PhysioNet's Signal and Annotation Viewer ( LightWave )
%   woody           - Perform signal averaging with alignment
%   wqrs            - Finds the QRS complexes of a WFDB ECG record signal
%   wrann           - Writes annotations for WFDB records into annotation files
%   wrsamp          - Writes signal data into WFDB-compatible records
%
%
%
%   To credit this toolbox, please cite the following references in your work:
%
%   Silva, I, Moody, G.
%   "An Open-source Toolbox for Analysing and Processing PhysioNet Databases in MATLAB and Octave."
%   Journal of Open Research Software 2(1):e27
%   [http://dx.doi.org/10.5334/jors.bi] ;
%   2014 (September 24).
%
%
%   Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh, Mark RG, Mietus JE, Moody GB, Peng CK, Stanley HE.
%   "PhysioBank, PhysioToolkit, and PhysioNet: Components of a New Research Resource for Complex
%   Physiologic Signals."
%   Circulation 101(23):e215-e220
%   [http://circ.ahajournals.org/cgi/content/full/101/23/e215];
%   2000 (June 13).
%   PMID: 10851218; doi: 10.1161/01.CIR.101.23.e215
%
%
%   In addition, some of these functions use binary executables compiled
%   from open-source third-party code contributed to PhysioNet. When using
%   these functions on your work, please look at the help for that function
%   in order find out how to credit the original paper and authors.
%
%   For questions, contributions, and feedback post at our community Forum:
%       http://groups.google.com/forum/#!forum/wfdb-app-toolbox
%
%
%   The source code for the native libraries used in this toolbox can be obtained from PhysioNet under
%   the GNU GPL agreement.
%
%   The original contributors of any open source native code that is available at PhysioNet
%   and is used by the Toolbox are credited in their respective MATLAB wrappers. In addition, the
%   following people have contributed to the development or testing of the MATLAB wrappers
%   and the JVM interface:
%
%   Sahar Alkhairy
%   Fernando Andreotti Lage
%   Joachim Behar
%   Eudald Bogatell
%   Jonas Carlson
%   Gari D. Clifford
%   Michael Craig
%   Mohammad Ghassemi
%   Alistair Johnson
%   Li-wei Lehman
%   Sara Mariani
%   Louis Mayaud
%   Blaž Merela
%   Benjamin Moody
%   George B. Moody
%   Shamin Nemati
%   Piotr Podziemski
%   Erina Katsumata
%   Aled Rowen
%   Kari Schoonbee
%   Daniel J. Scott
%   Ikaro Silva
%   Gabriel Squillace
%   Bryan Tripp
%   Chen Xie
%   Tingting Zhu
%
%
%Created by Ikaro Silva 2012

%endOfHelp


%Ray3D Ray in 3D space
%
% This object represents a ray in 3D space, defined by a point on the ray
% and a direction unit-vector.
%
% Methods::
% intersect    Intersection of ray with plane or ray
% closest      Closest distance between point and ray
% char         Ray parameters as human readable string
% display      Display ray parameters in human readable form
%
% Properties::
% P0    A point on the ray (3x1)
% d     Direction of the ray, unit vector (3x1)
%
% Notes::
% - Ray3D objects can be used in vectors and arrays

% Copyright (C) 1993-2011, by Peter I. Corke
%
% This file is part of The Machine Vision Toolbox for Matlab (MVTB).
%
% MVTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% MVTB 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 Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with MVTB.  If not, see <http://www.gnu.org/licenses/>.
classdef Ray3D
    properties
        P0   % a point on the ray
        d     % direction of the ray
    end

    methods
        function r = Ray3D(P0, d)
        %Ray3D.Ray3D Ray constructor
        %
        % R = Ray3D(P0, D) is a new Ray3D object defined by a point on the ray P0
        % and a direction vector D.
            r.P0 = P0(:);
            r.d = unit(d(:));
        end

        function [x,e] = intersect(r1, r2)
        %Ray3D.intersect Intersetion of ray with line or plane
        %
        % X = R.intersect(R2) is the point on R that is closest to the ray R2.
        % If R is a vector then then X has multiple columns, corresponding to
        % the intersection of R(i) with R2.
        %
        % [X,E] = R.intersect(R2) as above but also returns the closest distance
        % between the rays.
        %
        % X = R.intersect(P) returns the point of intersection between the
        % ray R and the plane P=(a,b,c,d) where aX + bY + cZ + d = 0.
        % If R is a vector then X has multiple columns, corresponding to
        % the intersection of R(i) with P.

            if isa(r2, 'Ray3D')
                % ray intersect ray case
                if length(r1) ~= length(r2)
                    error('can only intersect rays pairwise');
                end

                for i=1:length(r1)
                    alpha = [-r1(i).d r2(i).d cross(r1(i).d,r2(i).d)] \ ...
                        (r1(i).P0-r2(i).P0);
                    x(:,i) = r1(i).P0 + alpha(1)*r1(i).d;
                    e(i) = norm(r1(i).P0 - r2(i).P0 + ...
                        alpha(1)*r1(i).d -alpha(2)*r2(i).d);
                end
            else
                % ray intersect plane case
                % plane is P = (a,b,c,d), P.x = 0

                for i=1:length(r1)
                    n = r2(1:3); d = r2(4);
                    alpha = -(d + dot(n, r1.P0)) / ( dot(n, r1.d) );
                    x(:,i) = r1.P0 + alpha*r1.d;
                end
            end
        end

        % closest distance between point and line
        function [x,e] = closest(r1, P)
        %Ray3D.closest Closest distance between point and ray
        %
        % X = R.closest(P) is the point on the ray R closest to the point P.
        %
        % [X,E] = R.closest(P) as above but also returns the distance E between
        % X and P.
            alpha = dot(P - r.P0, r.d);
            x = r1.P0 + alpha*r1.d;
            e = norm(x-P);
        end

        function display(rays)
        %Ray3D.display Display value
        %
        % R.display() displays a compact human-readable representation of the Ray3D's
        % value.  If R is a vector then the elements are printed one per line.
        %
        % Notes::
        % - This method is invoked implicitly at the command line when the result
        %   of an expression is a Ray3D object and the command has no trailing
        %   semicolon.
        %
        % See also Ray3D.char.
            disp(' ');
            disp([inputname(1), ' = '])
            disp(' ');
            if length(rays) > 20
                fprintf('%d corresponding points (listing suppressed)\n', length(rays));
            else
                disp( char(rays) );
            end
        end % display()

        function s = char(rays)
        %Ray3D.char Convert to string
        %
        % S = R.char() is a compact string representation of the Ray3D's value.
        % If R is a vector then the string has multiple lines, one per element.

            s = '';
            for r=rays
                ss = sprintf('d=(%g, %g, %g), P0=(%g, %g, %g)\n', ...
                    r.d, r.P0);
                s = strvcat(s, ss);
            end
        end

    end
end


function varargout = spm_brainwarp(varargin)
% Part of old nonlinear spatial normalisation - a compiled routine
%_______________________________________________________________________
% [Alpha,Beta,Var] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,...
%                                   dbasX,dbasY,dbasZ,T,fwhm,VW,VW2)
% VG    - Template volume(s) (see spm_vol)
% VF    - Object volume
% Affine    - The affine transformation which maps between the object
%     and template.
% basX  - Basis vectors in X. # rows must eq. VG(1)
% basY  - Basis vectors in Y. # rows must eq. VG(2)
% basZ  - Basis vectors in Z. # rows must eq. VG(3)
% dbasX - Derivatives of basis vectors in X. # rows must eq. VG(1)
% dbasY - Derivatives of basis vectors in Y. # rows must eq. VG(2)
% dbasZ - Derivatives of basis vectors in Z. # rows must eq. VG(3)
% T - The current parameter estimates.
% fwhm  - The approximate smoothness of the images.
% VW    - an optional weighting volume for determining which voxels
%         should be weighted more heavily in the fitting process.
%         This volume should have the same dimensions and position
%         as the volumes in VG.
% VW2   - another optional weighting volume for determining which voxels
%         should be weighted more heavily in the fitting process.
%         This volume should have the same dimensions and position
%         as the volumes in VF.
% Without the weighting volumes, all voxels are assigned weights that
% are uniformly one.
%
% Alpha - A*A - where A is the design matrix
% Beta  - A*b - where f is the object image
% Var   - the approximate chi^2 (corrected for number of resels).
%_______________________________________________________________________
%
% The voxels of g1, g2.. are sampled according to the smoothness of the
% image (fwhm). The corresponding voxels of f are determined according
% to the current parameter estimates and the affine transform.  See
% "spm_write_sn.m" for more details about how this is done.
%
%
%-----------------------------------------------------------------------
%
% The design matrix A is generated internally from:
%
% diag(w)*[diag(df/dx)*B diag(df/dy)*B diag(df/dz)*B ...
%      diag(g1)*[1 x y z] ...
%      diag(g2)*[1 x y z] ...]
%
% where df/dx, df/dy & df/dz are column vectors containing the gradient
%   of image f with respect to displacements in x, y & z
%   (in the space of g).
%
%   B is generated from kron(basZ,kron(basY,BasX)). Each column of
%   B is a basis image.
%
%   g1, g2.. are template images.
%
%   x, y & z are simply the spatial coordinates of the voxels of f.
%
%   s1, s2.. are the current estimates for the required scaling
%   factors. These are derived from T(3*prod(VG(1:3))+1),
%   T(3*prod(VG(1:3))+2)...
%
%       w is an optional vector of weights, where w = 1/(1/w1 + 1/w2)
%       where w1 and w2 are derived from the optional weighting images.
%
% The vector b contains [diag(w)*(f - diag(g1)*s1 - diag(g1)*x*s2 - ...)].
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_brainwarp.m 4923 2012-09-13 15:01:01Z guillaume $

%-This is merely the help file for the compiled routine
error('spm_brainwarp.c not compiled - see Makefile')


%--------------------------------------------------------------------------------------------------------
% The system is created based on the principles described in the following paper
% Jimmy SJ. Ren and Li Xu, "On Vectorization of Deep Convolutional Neural Networks for Vision Tasks",
% The 29th AAAI Conference on Artificial Intelligence (AAAI-15). Austin, Texas, USA, January 25-30, 2015
% email: jimmy.sj.ren@gmail.com
%--------------------------------------------------------------------------------------------------------
addpath applications/image_denoise/
addpath applications/image_denoise/utility/
addpath utils/
addpath cuda/
addpath mem/
addpath layers/
addpath layers_adapters/
addpath optimization/
addpath pipeline/
addpath data/

clearvars -global config;
clearvars -global mem;
clear;
global config mem;
denoise_configure();
init(0);

load('data/denoise/val/val_1');
perm = randperm(size(test_samples, 4));
test_samples = test_samples(:,:,:,perm);
test_labels = test_labels(:,:,:,perm);
test_samples = config.NEW_MEM(test_samples(:,:,:,1:1000));
test_labels = config.NEW_MEM(test_labels(:,:,:,1:1000));

count = 0;
cost_avg = 0;
epoc = 0;
points_seen = 0;
display_points = 1000;
save_points = 10000;
max_grad = 1;
fprintf('%s\n', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));
for pass = 1:10
    for p = 1:11
        load(strcat('data/denoise/train/patches_', num2str(p), '.mat'));
        perm = randperm(10000);
        samples = samples(:,:,:,perm);
        labels = labels(:,:,:,perm);
        train_imgs = config.NEW_MEM(samples);
        train_labels = config.NEW_MEM(labels);

        for i = 1:size(train_labels, 4) / config.batch_size
            points_seen = points_seen + config.batch_size;
            in = train_imgs(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);
            out = train_labels(:,:,:,(i-1)*config.batch_size+1:i*config.batch_size);
            out = out((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...
                      (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :, :);

            % operate the training pipeline
            op_train_pipe(in, out);
            % update the weights
            config.UPDATE_WEIGHTS();

            if(cost_avg == 0)
                cost_avg = config.cost;
            else
                cost_avg = (cost_avg + config.cost) / 2;
            end

            % display point
            if(mod(points_seen, display_points) == 0)
                count = count + 1;
                fprintf('%d ', count);
            end
            % save point
            if(mod(points_seen, save_points) == 0)
                fprintf('\n%s', datestr(now, 'dd-mm-yyyy HH:MM:SS FFF'));
                epoc = epoc + 1;
                test_cost = 0;
                for t = 1:size(test_samples, 4) / config.batch_size
                    t_label = test_labels(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size);
                    t_label = config.NEW_MEM(t_label((size(in, 1) - config.output_size(1)) / 2 + 1:(size(in, 1) - config.output_size(1)) / 2 + config.output_size(1), ...
                                            (size(in, 2) - config.output_size(2)) / 2 + 1:(size(in, 2) - config.output_size(2)) / 2 + config.output_size(2), :));

                    op_test_pipe(test_samples(:,:,:,(t-1)*config.batch_size+1:t*config.batch_size), t_label);
                    test_out = gather(mem.output);
                    test_cost = test_cost + config.cost;
                end
                test_cost = test_cost / size(test_samples, 4);
                fprintf('\nepoc %d, training avg cost: %f, test avg cost: %f\n', epoc, cost_avg, test_cost);

                save_weights(strcat('applications/image_denoise/results/epoc', num2str(epoc), '.mat'));
                cost_avg = 0;
            end
        end
    end
end


% function failed_tutorial_fem

% WALLTIME 01:00:00
% MEM 6gb
% DEPENDENCY ft_volumesegment ft_prepare_mesh ft_prepare_headmodel ft_headmodel_simbio

% this test script is based on the tutorial under development at
% http://www.fieldtriptoolbox.org/development/simbio

cd(dccnpath('/home/common/matlab/fieldtrip/data/ftp/test/ctf'))

mri = ft_read_mri('Subject01.mri');

figure
cfg = [];
ft_sourceplot(cfg, mri);

cfg     = [];
cfg.dim = mri.dim;
mri     = ft_volumereslice(cfg, mri);

figure
cfg = [];
ft_sourceplot(cfg,mri);

cfg           = [];
cfg.output    = {'gray','white','csf','skull','scalp'};
segmentedmri  = ft_volumesegment(cfg, mri);

seg_i            = ft_datatype_segmentation(segmentedmri, 'segmentationstyle', 'indexed');

cfg              = [];
cfg.funparameter = 'seg';
cfg.funcolormap  = lines(6);
cfg.location     = 'center';
cfg.atlas        = seg_i;
ft_sourceplot(cfg, seg_i);

cfg        = [];
cfg.shift  = 0.3;
cfg.method = 'hexahedral';
mesh = ft_prepare_mesh(cfg, segmentedmri);

cfg              = [];
cfg.method       = 'simbio';
cfg.conductivity = [0.33 0.14 1.79 0.01 0.43];           % order follows mesh.tissuelabel
vol = ft_prepare_headmodel(cfg, mesh);
% the call to "ft_prepare_headmodel" took 320 seconds and required the additional allocation of an estimated 501 MB

% you may need to specify the full path to the file
elec = ft_read_sens('standard_1020.elc');

figure
hold on
ft_plot_mesh(mesh,'surfaceonly','yes','vertexcolor','none','edgecolor','none','facecolor',[0.5 0.5 0.5],'face alpha',0.5)
camlight
ft_plot_sens(elec,'style', 'sk');

nas = mri.hdr.fiducial.mri.nas;
lpa = mri.hdr.fiducial.mri.lpa;
rpa = mri.hdr.fiducial.mri.rpa;

vox2head = mri.transform;

nas = ft_warp_apply(vox2head, nas, 'homogenous');
lpa = ft_warp_apply(vox2head, lpa, 'homogenous');
rpa = ft_warp_apply(vox2head, rpa, 'homogenous');

% create a structure similar to a template set of electrodes
fid.chanpos       = [nas; lpa; rpa];       % CTF head coordinates of fiducials
fid.label         = {'Nz','LPA','RPA'};    % use the same labels as those in elec
fid.unit          = 'mm';                  % use the same units as those in mri

% alignment
cfg               = [];
cfg.method        = 'fiducial';
cfg.elec          = elec;                  % the electrodes we want to align
cfg.template      = fid;                   % the template we want to align to
cfg.fiducial      = {'Nz', 'LPA', 'RPA'};  % labels of fiducials in fid and in elec
elec_aligned      = ft_electroderealign(cfg);

figure;
hold on;
ft_plot_mesh(mesh,'surfaceonly','yes','vertexcolor','none','edgecolor','none','facecolor',[0.5 0.5 0.5],'face alpha',0.5)
camlight
ft_plot_sens(elec_aligned,'style','sr');

if false
  % this should only run in interactive mode
  cfg = [];
  cfg.method = 'interactive';
  cfg.elec = elec_aligned;
  cfg.headshape = vol;
  elec_aligned2 = ft_electroderealign(cfg);
else
  % this is more or less the same as the interactive alignment
  transform = [
    1 0 0 15
    0 1 0 0
    0 0 1 -10
    0 0 0 1
    ];
  elec_aligned2 = ft_transform_geometry(transform, elec_aligned);
end

%%%%%%%%%

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel.resolution = 10;
cfg.elec = elec_aligned2;
cfg.sourcemodel.unit = 'mm';
source = ft_prepare_sourcemodel(cfg);


function roidb = fast_rcnn_generate_sliding_windows(conf, imdb, roidb, roipool_in_size)
% [pred_boxes, scores] = fast_rcnn_conv_feat_detect(conf, im, conv_feat, boxes, max_rois_num_in_gpu, net_idx)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------

    regions.images = imdb.image_ids;

    im_sizes = imdb.sizes;
    regions.boxes = cellfun(@(x) generate_sliding_windows_one_image(conf, x, roipool_in_size), num2cell(im_sizes, 2), 'UniformOutput', false);

    roidb = roidb_from_proposal(imdb, roidb, regions);
end

function boxes = generate_sliding_windows_one_image(conf, im_size, roipool_in_size)
    im_scale = prep_im_for_blob_size(im_size, conf.scales, conf.max_size);
    im_size = round(im_size * im_scale);

    x1 = 1:conf.feat_stride:im_size(2);
    y1 = 1:conf.feat_stride:im_size(1);
    [x1, y1] = meshgrid(x1, y1);
    x1 = x1(:);
    y1 = y1(:);
    x2 = x1 + roipool_in_size * conf.feat_stride - 1;
    y2 = y1 + roipool_in_size * conf.feat_stride - 1;

    boxes = [x1, y1, x2, y2];
    boxes = filter_boxes(im_size, boxes);

    boxes = bsxfun(@times, boxes-1, 1/im_scale) + 1;
end

function boxes = filter_boxes(im_size, boxes)
    valid_ind = boxes(:, 1) >= 1 & boxes(:, 1) <= im_size(2) & ...
                boxes(:, 2) >= 1 & boxes(:, 2) <= im_size(1) & ...
                boxes(:, 3) >= 1 & boxes(:, 3) <= im_size(2) & ...
                boxes(:, 4) >= 1 & boxes(:, 4) <= im_size(1);

    boxes = boxes(valid_ind, :);
end


function t = alldifferent(X)
% alldifferent (overloaded)

t = alldifferent(sdpvar(X));


function o = niftistruc
% Create a data structure describing NIFTI headers
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

persistent org;
if ~isempty(org),
    o = org;
    return;
end;
t = struct('conv',{ @char , @uint8 , @int16 , @int32 , @single },...
           'prec',{'uint8', 'uint8', 'int16', 'int32', 'single'},...
           'size',{       1,      1,      2,      4,       4 });
c = t(1);
b = t(2);
s = t(3);
i = t(4);
f = t(5);

table = {...
    i, 1,'sizeof_hdr',348
    c,10,'data_type',[]
    c,18,'db_name',[]
    i, 1,'extents',[]
    s, 1,'session_error',[]
    c, 1,'regular','r'
    b, 1,'dim_info',[]
    s, 8,'dim',[3 0 0 0  1 1 1 1 1]
    f, 1,'intent_p1',0
    f, 1,'intent_p2',0
    f, 1,'intent_p3',0
    s, 1,'intent_code',0
    s, 1,'datatype',2
    s, 1,'bitpix',8
    s, 1,'slice_start',[]
    f, 8,'pixdim',[0 1 1 1]
    f, 1,'vox_offset',0
    f, 1,'scl_slope',1
    f, 1,'scl_inter',0
    s, 1,'slice_end',[]
    b, 1,'slice_code',[]
    b, 1,'xyzt_units',10
    f, 1,'cal_max',[]
    f, 1,'cal_min',[]
    f, 1,'slice_duration',[]
    f, 1,'toffset',[]
    i, 1,'glmax',[]
    i, 1,'glmin',[]
    c,80,'descrip','NIFTI-1 Image'
    c,24,'aux_file',''
    s, 1,'qform_code',0
    s, 1,'sform_code',0
    f, 1,'quatern_b',0
    f, 1,'quatern_c',0
    f, 1,'quatern_d',0
    f, 1,'qoffset_x',0
    f, 1,'qoffset_y',0
    f, 1,'qoffset_z',0
    f, 4,'srow_x',[1 0 0 0]
    f, 4,'srow_y',[0 1 0 0]
    f, 4,'srow_z',[0 0 1 0]
    c,16,'intent_name',''
    c, 4,'magic','ni1'};
org = struct('label',table(:,3),'dtype',table(:,1),'len',table(:,2),...
    'offset',0,'def',table(:,4));
os  = 0;
for j=1:length(org)
    os  = os + org(j).dtype.size*ceil(os/org(j).dtype.size);
    fun = org(j).dtype.conv;
    def = [org(j).def zeros(1,org(j).len-length(org(j).def))];
    org(j).def    = feval(fun,def);
    org(j).offset = os;
    os  = os + org(j).len*org(j).dtype.size;
end;
o = org;
return;


classdef math_model_opf_acci < mp.math_model_opf_acc
%MP.MATH_MODEL_OPF_ACCI  MATPOWER mathematical model for AC optimal power flow (OPF) problem.
%   ?
%
%   MP.MATH_MODEL_OPF_ACCI ... power flow ...
%
%   Properties
%       ? - ?
%
%   Methods
%       ?

%   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.

%     properties
%     end

    methods
        function tag = form_tag(obj)
            tag = 'acci';
        end

        function name = form_name(obj)
            name = 'AC-cartesian-current';
        end

        function add_node_balance_constraints(obj, nm, dm, mpopt)
            %% power balance constraints
            nn = nm.node.N;             %% number of nodes
            fcn_mis = @(x)obj.nodal_current_balance_fcn(x, nm);
            hess_mis = @(x, lam)obj.nodal_current_balance_hess(x, lam, nm);
            obj.add_nln_constraint({'rImis', 'iImis'}, [nn;nn], 1, fcn_mis, hess_mis);
        end

        function [lam_p, lam_q] = node_power_balance_prices(obj, nm)
            %% shadow prices on node power balance
            nne = obj.get_idx('nle');

            %% convert current balance shadow prices to equivalent lam_p and lam_q
            %% P + jQ = (Vr + jVi) * (M - jN)
            %% M = (Vr P + Vi Q) / (Vr^2 + Vi^2)
            %% N = (Vi P - Vr Q) / (Vr^2 + Vi^2)
            %% lam_p = df/dP = df/dM * dM/dP + df/dN + dN/dP
            %% lam_q = df/dQ = df/dM * dM/dQ + df/dN + dN/dQ
            V = nm.soln.v;
            lambda = obj.soln.lambda;
            VV = V ./ (V .* conj(V));   %% V / vm^2
            VVr = real(VV);
            VVi = imag(VV);
            lamM = lambda.eqnonlin(nne.i1.rImis:nne.iN.rImis);
            lamN = lambda.eqnonlin(nne.i1.iImis:nne.iN.iImis);
            lam_p = (VVr.*lamM + VVi.*lamN);
            lam_q = (VVi.*lamM - VVr.*lamN);
        end
    end     %% methods
end         %% classdef


function fig = visualize_apollo_estimation(problem,apollopath,info,showfig)
if nargin < 4
    showfig = false;
end

markerSize = 6;
markerSizeest = 6;
color_detected_keypoints = 'cyan';
color_est_keypoints      = 'yellow';

if size(problem.intrinsicsorg,1) == 1 || size(problem.intrinsicsorg,2) == 1
    problem.intrinsicsorg       = vec_K_to_mat_K(problem.intrinsicsorg);
end
fullshapefname              = sprintf('%s/cad_db_values.mat',apollopath);
load(fullshapefname);
edgesfname                  = sprintf('%s/edges.mat',apollopath);
load(edgesfname);

shapes                      = permute(cad_db_values,[2,3,1]);

if problem.K == 20
    shapeids                    = 1:4:77;
elseif problem.K == 10
    shapeids                    = 1:10;
elseif problem.K == 5
    shapeids                    = 1:5;
else
    error('K can only be 10 or 20.')
end

shapes                      = shapes(:,:,shapeids);

R_est                       = info.R_est_org;
t_est                       = info.t_est_org;
shape_est                   = combine_shapes(shapes,info.c_est_org);
shape_est                   = R_est * shape_est + t_est;

K                           = problem.intrinsicsorg;
kpts2D                      = problem.kpts2D(1:2,:);
shape_homo                  = shape_est ./ shape_est(3,:);

kpts_est                    = K * shape_homo;
kpts_est                    = kpts_est(1:2,:);

imgname                     = sprintf('%s/apollo-train-set/images/%s.jpg',...
                                      apollopath,problem.imgname);
img                         = imread(imgname);

if showfig
    fig = figure;
else
    fig = figure('visible','off');
end
imshow(img,'Border','tight'); hold on;
% plot detected keypoints using squares
plot(kpts2D(1,:),kpts2D(2,:),'s',...
    'markersize',markerSize,...
    'MarkerFaceColor',color_detected_keypoints,...
    'MarkerEdgeColor',color_detected_keypoints);

hold on
plot(kpts_est(1,:),kpts_est(2,:),'o',...
        'markersize',markerSizeest,...
        'MarkerFaceColor',color_est_keypoints,...
        'MarkerEdgeColor',color_detected_keypoints);
hold on
nrEdges  = size(edges,1);
for i = 1:nrEdges
    linei = plot(kpts_est(1,edges(i,:)),kpts_est(2,edges(i,:)),'y-','lineWidth',2);
    linei.Color(4) = 0.6;
end

end


cutoff = 50;
aspectr = 1;
original = 0;

Ds = smooth3(D);

if original
hiso = patch(isosurface(Ds,cutoff),...
    'FaceColor',[1,.75,.65],...
    'EdgeColor','none');

hcap = patch(isocaps(D,cutoff),...
    'FaceColor','interp',...
    'EdgeColor','none');
else
[hiso,hcap] = imagePatch(X,Y,Z,D,[nan coords(1) nan nan nan 40]);
end

view(45,30)
axis tight
daspect([1,1,aspectr])

myLight = lightangle(45,30);
set(gcf,'Renderer','zbuffer'); lighting phong
isonormals(Ds,hiso)
set(hcap,'AmbientStrength',.6)
set(hiso,'SpecularColorReflectance',0,'SpecularExponent',50)

% this is the key to avoiding dark surface head.
[az,el] = view
lightangle(az,el)


function [bnet, Qnodes, Fnodes, Onode] = mk_hhmm(varargin)
% MK_HHMM Make a Hierarchical HMM
% function [bnet, Qnodes, Fnodes, Onode] = mk_hhmm(...)
%
% e.g. 3-layer hierarchical HMM where level 1 only connects to level 2
% and the parents of the observed node are levels 2 and 3.
% (This DBN is the same as Fig 10 in my tech report.)
%
%   Q1 ---------->   Q1
%   |  \            ^ |
%   |   v          /  |
%   |    F2 ------/   |
%   |   ^ ^        \  |
%   |  /  |         \ |
%   | /   |          ||
%   v     |          vv
%   Q2----| --------> Q2
%  /| \   |          ^|
% / |  v  |         / |
% | |   F3 --------/  |
% | |   ^          \  |
% | v  /            v v
% | Q3 ----------->  Q3
% |  |
% \  |
%  v v
%   O
%
%
% Optional arguments in name/value format [default value in brackets]
%
% Qsizes      - sizes at each level [ none ]
% allQ       - 1 means level i connects to all Q levels below, 0 means just to i+1 [0]
% transprob  - transprob{d}(i,k,j) = P(Q(d,t)=j|Q(d,t-1)=i,Q(1:d-1,t)=k)  ['leftright']
% startprob  - startprob{d}(k,j) = P(Q(d,t)=j|Q(1:d-1,t)=k)  ['leftstart']
% termprob   - termprob{d}(k,j) = P(F(d,t)=2|Q(1:d-1,t)=k,Q(d,t)=j) for d>1 ['rightstop']
% selfprop   - prob of a self transition (termprob default = 1-selfprop) [0.8]
% Osize       - size of O node
% discrete_obs - 1 means O is tabular_CPD, 0 means gaussian_CPD [0]
% Oargs       - cell array of args to pass to the O CPD  [ {} ]
% Ops         - Q parents of O [Qnodes(end)]
% F1          - 1 means level 1 can finish (restart), else there is no F1->Q1 arc [0]
% clamp1     - 1 means we clamp the params of the Q nodes in slice 1 (Qt1params) [1]
%   Note: the Qt1params are startprob, which should be shared with other slices.
%   However, in the current implementation, the Qt1params will only be estimated
%   from the initial state of each sequence.
%
% For d=1, startprob{1}(1,j) is only used in the first slice and
% termprob{1} is ignored, since we assume the top level never resets.
% Also, transprob{1}(i,j) can be used instead of transprob{1}(i,1,j).
%
% leftstart means the model always starts in state 1.
% rightstop means the model can only finish in its last state (Qsize(d)).
% unif means each state is equally like to reach any other
% rnd means the transition/starting probs are random (drawn from rand)
%
% Q1:QD in slice 1 are of type tabular_CPD
% Q1:QD in slice 2 are of type hhmmQ_CPD.
% F(2:D-1) is of type hhmmF_CPD, FD is of type tabular_CPD.

args = varargin;
nargs = length(args);

% get sizes of nodes and topology
Qsizes = [];
Osize = [];
allQ = 0;
Ops = [];
F1 = 0;
for i=1:2:nargs
  switch args{i},
   case 'Qsizes', Qsizes = args{i+1};
   case 'Osize',  Osize = args{i+1};
   case 'allQ',   allQ = args{i+1};
   case 'Ops',    Ops = args{i+1};
   case 'F1',     F1 = args{i+1};
  end
end
if isempty(Qsizes), error('must specify Qsizes'); end
if Osize==0, error('must specify Osize'); end
D = length(Qsizes);
Qnodes = 1:D;

if isempty(Ops), Ops = Qnodes(end); end

[intra, inter, Qnodes, Fnodes, Onode] = mk_hhmm_topo(D, allQ, Ops, F1);
ss = length(intra);
names = {};

if F1
  Fnodes_ndx = Fnodes;
else
  Fnodes_ndx = [-1 Fnodes]; % Fnodes(1) is a dummy index
end

% set default params
discrete_obs = 0;
Oargs = {};
startprob = cell(1,D);
startprob{1} = 'unif';
for d=2:D
  startprob{d} = 'leftstart';
end
transprob = cell(1,D);
transprob{1} = 'unif';
for d=2:D
  transprob{d} = 'leftright';
end
termprob = cell(1,D);
for d=2:D
  termprob{d} = 'rightstop';
end
selfprob = 0.8;
clamp1 = 1;

for i=1:2:nargs
  switch args{i},
   case 'discrete_obs', discrete_obs = args{i+1};
   case 'Oargs',        Oargs = args{i+1};
   case 'startprob',    startprob = args{i+1};
   case 'transprob',    transprob = args{i+1};
   case 'termprob',     termprob = args{i+1};
   case 'selfprob',     selfprob = args{i+1};
   case 'clamp1',       clamp1 = args{i+1};
  end
end

ns = zeros(1,ss);
ns(Qnodes) = Qsizes;
ns(Onode) = Osize;
ns(Fnodes) = 2;

dnodes = [Qnodes Fnodes];
if discrete_obs
  dnodes = [dnodes Onode];
end
onodes = [Onode];

bnet = mk_dbn(intra, inter, ns, 'observed', onodes, 'discrete', dnodes, 'names', names);
eclass = bnet.equiv_class;

for d=1:D
  if d==1
    Qps = [];
  elseif allQ
    Qps = Qnodes(1:d-1);
  else
    Qps = Qnodes(d-1);
  end
  Qpsz = prod(ns(Qps));
  Qsz = ns(Qnodes(d));
  if isstr(startprob{d})
    switch startprob{d}
     case 'unif', startprob{d} = mk_stochastic(ones(Qpsz, Qsz));
     case 'rnd', startprob{d} = mk_stochastic(rand(Qpsz, Qsz));
     case 'leftstart', startprob{d} = zeros(Qpsz, Qsz); startprob{d}(:,1) = 1;
    end
  end
  if isstr(transprob{d})
    switch transprob{d}
     case 'unif', transprob{d} = mk_stochastic(ones(Qsz, Qpsz, Qsz));
     case 'rnd', transprob{d} = mk_stochastic(rand(Qsz, Qpsz, Qsz));
     case 'leftright',
      LR = mk_leftright_transmat(Qsz, selfprob);
      temp = repmat(reshape(LR, [1 Qsz Qsz]), [Qpsz 1 1]); % transprob(k,i,j)
      transprob{d} = permute(temp, [2 1 3]); % now transprob(i,k,j)
    end
  end
  if isstr(termprob{d})
    switch termprob{d}
     case 'unif', termprob{d} = mk_stochastic(ones(Qpsz, Qsz, 2));
     case 'rnd', termprob{d} = mk_stochastic(rand(Qpsz, Qsz, 2));
     case 'rightstop',
      %termprob(k,i,t) Might terminate if i=Qsz; will not terminate if i<Qsz
      stopprob = 1-selfprob;
      termprob{d} = zeros(Qpsz, Qsz, 2);
      termprob{d}(:,Qsz,2) = stopprob;
      termprob{d}(:,Qsz,1) = 1-stopprob;
      termprob{d}(:,1:(Qsz-1),1) = 1;
     otherwise, error(['unrecognized termprob ' termprob{d}])
    end
  elseif d>1 % passed in termprob{d}(k,j)
    temp = termprob{d};
    termprob{d} = zeros(Qpsz, Qsz, 2);
    termprob{d}(:,:,2) = temp;
    termprob{d}(:,:,1) = ones(Qpsz,Qsz) - temp;
  end
end

% SLICE 1

for d=1:D
  bnet.CPD{eclass(Qnodes(d),1)} = tabular_CPD(bnet, Qnodes(d), 'CPT', startprob{d}, 'adjustable', clamp1);
end

if F1
  d = 1;
  bnet.CPD{eclass(Fnodes_ndx(d),1)}  = hhmmF_CPD(bnet, Fnodes_ndx(d), Qnodes(d), Fnodes_ndx(d+1), ...
						 'termprob', termprob{d});
end
for d=2:D-1
  if allQ
    Qps = Qnodes(1:d-1);
  else
    Qps = Qnodes(d-1);
  end
  bnet.CPD{eclass(Fnodes_ndx(d),1)}  = hhmmF_CPD(bnet, Fnodes_ndx(d), Qnodes(d), Fnodes_ndx(d+1), ...
						 'Qps', Qps, 'termprob', termprob{d});
end
bnet.CPD{eclass(Fnodes_ndx(D),1)}  = tabular_CPD(bnet, Fnodes_ndx(D), 'CPT', termprob{D});

if discrete_obs
  bnet.CPD{eclass(Onode,1)} = tabular_CPD(bnet, Onode, Oargs{:});
else
  bnet.CPD{eclass(Onode,1)} = gaussian_CPD(bnet, Onode, Oargs{:});
end

% SLICE 2

%for d=1:D
%  bnet.CPD{eclass(Qnodes(d),2)} = hhmmQ_CPD(bnet, Qnodes(d)+ss, Qnodes, d, D, ...
%					    'startprob', startprob{d}, 'transprob', transprob{d}, ...
%					    'allQ', allQ);
%end

d = 1;
if F1
  bnet.CPD{eclass(Qnodes(d),2)} = hhmmQ_CPD(bnet, Qnodes(d)+ss, 'Fself', Fnodes_ndx(d), ...
					    'Fbelow', Fnodes_ndx(d+1), ...
					    'startprob', startprob{d}, 'transprob', transprob{d});
else
    bnet.CPD{eclass(Qnodes(d),2)} = hhmmQ_CPD(bnet, Qnodes(d)+ss, ...
					    'Fbelow', Fnodes_ndx(d+1), ...
					    'startprob', startprob{d}, 'transprob', transprob{d});
end
for d=2:D-1
  if allQ
    Qps = Qnodes(1:d-1);
  else
    Qps = Qnodes(d-1);
  end
  Qps = Qps + ss; % since all in slice 2
  bnet.CPD{eclass(Qnodes(d),2)} = hhmmQ_CPD(bnet, Qnodes(d)+ss, 'Fself', Fnodes_ndx(d), ...
					    'Fbelow', Fnodes_ndx(d+1), 'Qps', Qps, ...
					    'startprob', startprob{d}, 'transprob', transprob{d});
end
d = D;
if allQ
  Qps = Qnodes(1:d-1);
else
  Qps = Qnodes(d-1);
end
Qps = Qps + ss; % since all in slice 2
bnet.CPD{eclass(Qnodes(d),2)} = hhmmQ_CPD(bnet, Qnodes(d)+ss, 'Fself', Fnodes_ndx(d), ...
					  'Qps', Qps, ...
					  'startprob', startprob{d}, 'transprob', transprob{d});


function kern = matern52KernExpandParam(kern, params)

% MATERN52KERNEXPANDPARAM Create kernel structure from MATERN52 kernel's parameters.
% FORMAT
% DESC returns a matern kernel with nu=5/2 kernel structure filled with the
% parameters in the given vector. This is used as a helper function to
% enable parameters to be optimised in, for example, the NETLAB
% optimisation functions.
% ARG kern : the kernel structure in which the parameters are to be
% placed.
% ARG param : vector of parameters which are to be placed in the
% kernel structure.
% RETURN kern : kernel structure with the given parameters in the
% relevant locations.
%
% SEEALSO : matern52KernParamInit, matern52KernExtractParam, kernExpandParam
%
% COPYRIGHT : Neil D. Lawrence, 2006

% KERN

kern.lengthScale = params(1);
kern.variance = params(2);


function Bcol = perform_segmentation_colorization(B)

% perform_segmentation_colorization - return a color image
%
%   Bcol = perform_segmentation_colorization(B);
%
%   Copyright (c) 2007 Gabriel Peyre

C = [[1; 0; 0] [0;1;0] [0;0;1] [1;1;0] [1;0;1] [0;1;1] [.3;.7;1]]';
ncol = size(C,1);
Bcol = C(cat(3,B,B+ncol,B+2*ncol));


function mr = mrLoadAnalyze(pth);
% Load an ANALYZE 7.5-format file as a mrVista mr struct.
%
%  mr = mrLoadAnalyze(pth);
%
%
% ras, 01/06.
mr = mrCreateEmpty;

[mr.data, mr.voxelSize, mr.hdr] = mrReadAnalyzeData(pth);
mr.dims = size(mr.data);

%% check for file with extra fields
[p f ext] = fileparts(pth);
extraFieldsFile = fullfile(p, [f '.mat']);
if exist(extraFieldsFile, 'file')
	tmp = load(extraFieldsFile);
	fields = setdiff(fieldnames(tmp), 'M');
	for i = 1:length(fields)
		field = fields{i};
		if isfield(mr, field)
			% combine the existing and additional info
			mr.(field) = mergeStructures(mr.(field), tmp.(field));
		else
			mr.(field) = tmp.(field);
		end
	end
end

%% add spaces
mr.spaces = mrStandardSpaces(mr);

mr.spaces(end+1).name = 'R|A|S';
mr.spaces(end).xform = mr.hdr.mat;
mr.spaces(end).dirLabels =  {'R <--> L' 'A <--> P' 'S <--> I'};
mr.spaces(end).sliceLabels = {'Sagittal' 'Coronal' 'Axial'};

mr.spaces(end+1) = mr.spaces(end);
mr.spaces(end).name = 'I|P|R';
mr.spaces(end).xform = ras2ipr(mr.spaces(end-1).xform, mr.dims);
mr.spaces(end).dirLabels =  {'S <--> I' 'A <--> P' 'L <--> R'};
mr.spaces(end).sliceLabels = {'Axial' 'Coronal' 'Sagittal'};

return


function r = isfinite(a)
%ISFINITE     Array of 1's for finite components
%
%   r = isfinite(a)
%

% written  08/07/02     S.M. Rump
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
%

  if a.complex
    r = isfinite(a.mid) & isfinite(a.rad) ;
  else
    r = isfinite(a.inf) & isfinite(a.sup) ;
  end


function cs = loadPHL(fname)
%

[pathstr, name, ext] = fileparts(char(fname));

if isempty(ext), ext = '.phl';end
if isempty(pathstr) && ~exist([name,ext],'file')
  pathstr = mtexCifPath;
end

% load file
if ~exist(fullfile(pathstr,[name ext]),'file')
  try
    fname = copyonline(fname);
  catch %#ok<CTCH>
    dir(fullfile(mtexCifPath,'*.phl'))
    error(['I could not find the corresponding phl file.' ...
      'Above you see the list of localy avaible phl files.'])
  end
else
  fname = fullfile(pathstr,[name ext]);
end

cs = {};
doc = xmlread(fname);
root = doc.getDocumentElement();
phaseList = root.getElementsByTagName('ClassInstance');

for i = 1:phaseList.getLength

  thisPhase = phaseList.item(i-1);
  if ~strcmp(thisPhase.getAttribute('Type'),'TEBSDExtPhaseEntry'), continue; end

  mineral = char(thisPhase.getAttribute('Name'));
  phaseEntry = thisPhase.getElementsByTagName('TEBSDPhaseEntry').item(0);

  %SG = phaseEntry.getElementsByTagName('SG').item(0).getFirstChild.getNodeValue;
  IT = str2num(phaseEntry.getElementsByTagName('IT').item(0).getFirstChild.getNodeValue);
  density = str2num(phaseEntry.getElementsByTagName('DENSITY').item(0).getFirstChild.getNodeValue);
  abc = str2num(phaseEntry.getElementsByTagName('Dim').item(0).getFirstChild.getNodeValue);
  angles = str2num(phaseEntry.getElementsByTagName('Angles').item(0).getFirstChild.getNodeValue);

  cs{end+1} = crystalSymmetry('spaceId',IT,abc,angles,'density',density,'mineral',mineral);

end

% fname = '/home/hielscher/mtex/master/data/cif/crystal.phl';
%


function test_old_ft_topoplotTFR

% MEM 2gb
% WALLTIME 00:20:00

% DEPENDENCY_FT_TOPOPLOTTFR
% This script tests the ft_topoplotTFR function and should display a figure
% with the ctf275 layout showing power decreases at the parietal lobes

% load time-frequency data
datadir = dccnpath('/home/common/matlab/fieldtrip/data/test/');
fprintf('loading data\n');
%load observe_comm_moves_freqmtmconvol.mat
load(fullfile(datadir,'observe_comm_moves_freqmtmconvol.mat'));

% topoplot a low frequency band
figure;
cfg              = [];
cfg.baselinetype = 'relchange';
cfg.baseline     = [-2 -.5];
cfg.xlim         = [.5 3];
cfg.ylim         = [8 12];
cfg.zlim         = [-1 1];
ft_topoplotTFR(cfg, obs_lo);

% topoplot a high frequency band
figure;
cfg              = [];
cfg.baselinetype = 'relchange';
cfg.baseline     = [-2 -.5];
cfg.xlim         = [.5 3];
cfg.ylim         = [30 40];
cfg.zlim         = [-1 1];
ft_topoplotTFR(cfg, obs_hi);