function g = dnetOutputGrad(model, X)

% DNETOUTPUTGRAD Evaluate derivatives of dnet model outputs with respect to parameters.
% FORMAT
% DESC evaluates the derivates of a density network's
% outputs with respect to the parameters of the mapping function.
% ARG model : the model for which the derivatives are to be
% computed.
% ARG X : the input data locations where the gradients are to be
% computed.
% RETURN g : the gradient of the outputs of the density network
% perceptron with respect to each of the parameters. The size of
% the matrix is number of data x number of parameters x number of
% outputs of the model.
%
% SEEALSO : modelOutputGrad, dnetCreate
%
% COPYRIGHT : Neil D. Lawrence, 2008

% MLTOOLS

  g = modelOutputGrad(model.mapping, X);
  % Add output gradient wrt beta.
  g(:, end+1, :) = 0;


% Remove bad tracking coordinates (position jumps)
%
% A position "jump" correspond to position samples that imply that the rat is
% moving quicker than physical possible.
%
%
function [x, y] = removePosJumps(x, y, threshold, stdThreshold)
    N = length(x);
    % Indexes to position samples that are to be removed
    remInd = zeros(N,1);
    remCounter = 0;

    diffX = diff(x);
    diffY = diff(y);
    diffR = sqrt(diffX.^2 + diffY.^2);
    ind = find(diffR > threshold);

    if isempty(ind)
        return;
    end

    if ind(end) == length(x)
        offset = 2;
    else
        offset = 1;
    end

    for ii = 1:length(ind)-offset
        if ind(ii+1) == ind(ii)+1
            % A single sample position jump, tracker jumps out one sample and
            % then jumps back to path on the next sample. Remove bad sample.
            remCounter = remCounter + 1;
            remInd(remCounter) = ind(ii)+1;
            ii = ii+1;
            continue
        else
            % Not a single jump. 2 possibilities:
            % 1. Tracker jumps out, and stay out at the same place for several
            % samples and then jumps back.
            % 2. Tracker just has a small jump before path continues as normal,
            % unknown reason for this. In latter case the samples are left
            % untouched.
            idx = find(x(ind(ii)+1:ind(ii+1)+1)==x(ind(ii)+1));
            if length(idx) == length(x(ind(ii)+1:ind(ii+1)+1));
                n = ind(ii+1)+1 - ind(ii);
                remInd(remCounter+1:remCounter+n) = (ind(ii)+1:ind(ii+1)+1)';
                remCounter = remCounter + n;
            end
        end
    end

    remInd = remInd(1:remCounter);

    % Remove the samples
    x(remInd) = NaN;
    y(remInd) = NaN;

    % there could be tracking outliers. They are commonly several values between longer list of
    % NaNs. These values lie far away from 'good' points, so discard everything that is
    % further than 2.5*STD
    med(1) = nanmin(x) + (nanmax(x) - nanmin(x))/2; % roughy middle point of the arena, better
    med(2) = nanmin(y) + (nanmax(y) - nanmin(y))/2; % than median or mean since it's less biased
    std = nanstd([x, y]);
    lowerBound = med - (stdThreshold*std);
    upperBound = med + (stdThreshold*std);

    x(x < lowerBound(1)) = nan;
    x(x > upperBound(1)) = nan;

    y(y < lowerBound(2)) = nan;
    y(y > upperBound(2)) = nan;
end


% Scrip: mcgrid.m
% Calculates Magnitude shift map for two specific time periods
% Uses view_mcgrid to plot the results
%
% J. Woessner
% last update: 22.01.04

report_this_filefun(mfilename('fullpath'));

global no1 bo1 inb1 inb2 valeg valeg2 CO valm1

valeg = 1;
valm1 = min(a.Magnitude);
prf = NaN;
if sel == 'in'
    % Set the grid parameter
    %Initial values
    dx = 1;
    dy = 1;
    ni = 150;
    Nmin = 150;
    ra = 50;
    fMaxRadius = 5;
    fSplitTime = 2000.4;

    % cut catalog at mainshock time:
%     l = a.Date > maepi(1,3);
%     a = a.subset(l);

    % cat at selecte magnitude threshold
    l = a.Magnitude < valm1;
    a(l,:) = [];
    newt2 = a;

    ho2=true;
    timeplot
    ho2=false;

    %The definitions in the following line were present in the initial bvalgrid.m file.
    %stan2 = NaN; stan = NaN; prf = NaN; av = NaN;

    % make the interface
    % creates a dialog box to input grid parameters
    %
    figure_w_normalized_uicontrolunits(...
        'Name','Grid Input Parameter',...
        'NumberTitle','off', ...
        'MenuBar','none', ...
        'NextPlot','new', ...
        'units','points',...
        'Visible','off', ...
        'Position',[ wex+200 wey-200 650 250]);
    axis off
%     labelList2=[' Automatic Mcomp (max curvature) | Fixed Mc (Mc = Mmin) | Automatic Mcomp (90% probability) | Automatic Mcomp (95% probability) | Best (?) combination (Mc95 - Mc90 - max curvature) | Constant Mc'];
%     labelPos = [0.2 0.8  0.6  0.08];
%     hndl2=uicontrol(...
%         'Style','popup',...
%         'Position',labelPos,...
%         'Units','normalized',...
%         'String',labelList2,...
%         'Callback','inb2 =get(hndl2,''Value''); ');
%
%     set(hndl2,'value',5);

    % creates a dialog box to input grid parameters
    %

    oldfig_button = uicontrol('BackGroundColor',[.60 .92 .84], ...
        'Style','checkbox','string','Plot in Current Figure',...
        'Position',[.78 .7 .20 .08],...
        'Units','normalized');

    set(oldfig_button,'value',1);

    freq_field=uicontrol('Style','edit',...
        'Position',[.30 .60 .12 .08],...
        'Units','normalized','String',num2str(ni),...
        'Callback','ni=str2double(get(freq_field,''String'')); set(freq_field,''String'',num2str(ni));set(tgl2,''value'',0); set(tgl1,''value'',1)');

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

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

    freq_field3=uicontrol('Style','edit',...
        'Position',[.30 .30 .12 .080],...
        'Units','normalized','String',num2str(dy),...
        'Callback','dy=str2double(get(freq_field3,''String'')); set(freq_field3,''String'',num2str(dy));');

    freq_field4=uicontrol('Style','edit',...
        'Position',[.6 .30 .12 .080],...
        'Units','normalized','String',num2str(fSplitTime),...
        'Callback','fSplitTime=str2double(get(freq_field4,''String'')); set(freq_field4,''String'',num2str(fSplitTime));');

    freq_field7=uicontrol('Style','edit',...
        'Position',[.30 .20 .12 .080],...
        'Units','normalized','String',num2str(Nmin),...
        'Callback','Nmin=str2double(get(freq_field7,''String'')); set(freq_field7,''String'',num2str(Nmin));');

    freq_field8=uicontrol('Style','edit',...
        'Position',[.6 .60 .12 .080],...
        'Units','normalized','String',num2str(fMaxRadius),...
        'Callback','fMaxRadius=str2double(get(freq_field8,''String'')); set(freq_field8,''String'',num2str(fMaxRadius));');

    tgl1 = uicontrol('Style','radiobutton',...
        'string','Number of Events:',...
        'Position',[.05 .60 .2 .0800], 'Callback','set(tgl2,''value'',0)',...
        'Units','normalized');

    set(tgl1,'value',0);

    tgl2 =  uicontrol('Style','radiobutton',...
        'string','OR: Constant Radius',...
        'Position',[.05 .50 .2 .080], 'Callback','set(tgl1,''value'',0)',...
        'Units','normalized');
    set(tgl2,'value',1);

    create_grid =  uicontrol('Style','radiobutton',...
        'string','Calculate a new grid', 'Callback','set(load_grid,''value'',0), set(prev_grid,''value'',0)','Position',[.78 .55 .2 .080],...
        'Units','normalized');

    set(create_grid,'value',1);

    prev_grid =  uicontrol('Style','radiobutton',...
        'string','Reuse the previous grid', 'Callback','set(load_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .45 .2 .080],...
        'Units','normalized');

    load_grid =  uicontrol('Style','radiobutton',...
        'string','Load a previously saved grid', 'Callback','set(prev_grid,''value'',0),set(create_grid,''value'',0)','Position',[.78 .35 .2 .080],...
        'Units','normalized');

    save_grid =  uicontrol('Style','checkbox',...
        'string','Save selected grid to file',...
        'Position',[.78 .22 .2 .080],...
        'Units','normalized');

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

    go_button1=uicontrol('Style','Pushbutton',...
        'Position',[.20 .05 .15 .12 ],...
        'Units','normalized',...
        'Callback','tgl1 =get(tgl1,''Value'');tgl2 =get(tgl2,''Value'');prev_grid = get(prev_grid,''Value'');create_grid = get(create_grid,''Value''); load_grid = get(load_grid,''Value''); save_grid = get(save_grid,''Value''); oldfig_button = get(oldfig_button,''Value''); close,sel =''ca'', mc_grid',...
        'String','Go');

    text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.10 0.98 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.l ,...
        'FontWeight','bold',...
        'String','Please choose an Mc estimation option   ');
    txt3 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.30 0.75 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.l ,...
        'FontWeight','bold',...
        'String',' Grid Parameter');
    txt5 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.1 0.4 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing in x (dx) in deg:');

    txt6 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.1 0.3 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Spacing in y (dy) in deg:');

    txt7 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[-0.1 0.18 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Min. No. of events > Mc:');

    txt9 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.42 0.28 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.s ,...
        'FontWeight','bold',...
        'String','Time window:');

    txt11 = text(...
        'Color',[0 0 0 ],...
        'EraseMode','normal',...
        'Position',[0.42 0.62 0 ],...
        'Rotation',0 ,...
        'FontSize',ZmapGlobal.Data.fontsz.s ,...
        'FontWeight','bold',...
        'String','Max. Radius /[km]:');

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

end   % if nargin ==0

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

if sel == 'ca'

    %In the following line, the program .m is called, which creates a rectangular grid from which then selects,
    %on the basis of the vector ll, the points within the selected poligon.

    % get new grid if needed
    if load_grid == 1
        [file1,path1] = uigetfile(['*.mat'],'previously saved grid');
        if length(path1) > 1
            think
            load([path1 file1])
        end
        plot(newgri(:,1),newgri(:,2),'k+')
    elseif load_grid ==0  &&  prev_grid == 0
        selgp
        if length(gx) < 2  ||  length(gy) < 2
            errordlg('Selection too small! (Dx and Dy are in degreees! ');
            return
        end
    elseif prev_grid == 1
        plot(newgri(:,1),newgri(:,2),'k+')
    end
    %   end

    gll = ll;

    if save_grid == 1

        sFile = ['*.mat'];
        sPath = pwd;
        [file1,path1] = uiputfile([sFile], 'Grid File Name?');
        sSaveFile = [path1 file1];
        save(sSaveFile, 'newgri', 'dx', 'dy', 'gx', 'gy', 'xvect', 'yvect', 'tmpgri', 'll', 'fSplitTime', 'Nmin', 'ra', 'a');
    end

    %   selgp
    itotal = length(newgri(:,1));
%     if length(gx) < 4 | length(gy) < 4
%         errordlg('Selection too small! (Dx and Dy are in degreees! ');
%         return
%     end

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

    % loop over  all points
    %
    i1 = 0.;
    mRes =[];
    mResult = [];
    allcount = 0.;
    wai = waitbar(0,' Please Wait ...  ');
    set(wai,'NumberTitle','off','Name','Rate change grid - percent done');
    drawnow

    % loop over all points
    for i= 1:length(newgri(:,1))
        i/length(newgri(:,1));
        % Grid node point
        x = newgri(i,1);y = newgri(i,2);
        allcount = allcount + 1.;

        % calculate distance from center point and sort with distance
        l = sqrt(((a.Longitude-x)*cos(pi/180*y)*111).^2 + ((a.Latitude-y)*111).^2) ;
        [s,is] = sort(l);
        mCat = a(is(:,1),:) ;       % re-orders matrix to agree row-wise
        % Use Radius to determine grid node catalogs
        l3 = l <= ra;
        mCat = a.subset(l3);      % new data per grid point (mCat) is sorted in distance

        %         % Select earthquakes in non-overlapping rectangles
        %         vSel = (a.Longitude >= (newgri(i,1)-dx/2)) & (a.Longitude < (newgri(i,1)+dx/2)) &...
        %             (a.Latitude >= (newgri(i,2)-dy/2)) & (a.Latitude < (newgri(i,2)+dy/2));
        %         % Select earthquakes in overlapping rectangles
        %         vSel = (a.Longitude >= (newgri(i,1)-dx)) & (a.Longitude < (newgri(i,1)+dx)) &...
        %             (a.Latitude >= (newgri(i,2)-dy)) & (a.Latitude < (newgri(i,2)+dy));
        %         mCat = a.subset(vSel);

        % Initialize
        fMinTime = min(mCat(:,3));
        fMaxTime = max(mCat(:,3));

        % Select data from 2 time periods
        vSelT = mCat(:,3) < fSplitTime;
        mCat1 = mCat(vSelT,:);
        mCat2 = mCat(~vSelT,:);
        % Length of catalog (resolution)
        nNumevents1 = length(mCat1(:,1));
        nNumevents2 = length(mCat2(:,1));

        % Minimum bin: essential for computing difference in FMD
        fMinBin = roundn(min(mCat(:,6)),-1);
        fMaxBin = roundn(max(mCat(:,6)),-1);

        if (length(mCat1(:,1)) >=Nmin & length(mCat2(:,1)) >= Nmin)
            % Compute change in FMD normalized by time period
            % Time periods
            fPeriod1 = max(mCat1(:,3))-min(mCat1(:,3));
            fPeriod2 = max(mCat2(:,3))-min(mCat2(:,3));
            [vFMD1, vBin1] = hist(mCat1(:,6),fMinBin:0.1:fMaxBin);
            [vFMD2, vBin2] = hist(mCat2(:,6),fMinBin:0.1:fMaxBin);
            fChFMD = max(cumsum(abs(vFMD2./fPeriod2-vFMD1./fPeriod1)));
            % Calculate shift
            [fMshift, fProbability, fAICc, mProblikelihood, bH] = calc_loglikelihood_dM2(mCat1, mCat2);
            % Check for validity of model using KS-Test result to produce validated result of magnitude shift
            if (bH == 1 | fMshift == 0)
                fMshift_valid = NaN;
            else
                fMshift_valid = fMshift;
            end
            % Calculate Mc
            [mResult1, fMls1, fMc1, fMu1, fSigma1, mDatPredBest1,...
                    vPredBest1, fBvalue1, fAvalue1, bH1] = calc_McEMR_kstest(mCat1, 0.1);
            [mResult2, fMls2, fMc2, fMu2, fSigma2, mDatPredBest2,...
                    vPredBest2, fBvalue2, fAvalue2, bH2] = calc_McEMR_kstest(mCat2, 0.1);
            % Mc change
            fdMc = fMc2-fMc1;
            if (bH1 ==0  &&  bH2 == 0)
                fdMc_val = fdMc;
            else
                fdMc_val = NaN;
            end
            % Calculate Utsu-Test
            [dA, fProbEqual, fProbDifferent] = calc_Utsu(fBvalue1, fBvalue2, nNumevents1, nNumevents2);
            % Create result matrix
            mResult = [mResult; i fMshift fProbability fAICc bH nNumevents1 nNumevents2 fMshift_valid fChFMD fMc1 fMc2 fdMc fdMc_val dA fProbEqual fProbDifferent bH1 fBvalue1 fAvalue1 bH2 fBvalue2 fAvalue2];
        else
            % Create result matrix
            mResult = [mResult; i NaN NaN NaN NaN nNumevents1 nNumevents2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
        end
        waitbar(allcount/itotal)
    end  % for newgr

    % Save the data to rcval_grid.mat
    save  mcgrid.mat mResult gx gy dx dy par1 tdiff t0b teb a main faults mainfault coastline yvect xvect tmpgri ll bo1 newgri gll ra maepi fSplitTime
    disp('Saving data to mcgrid.mat in current directory')

    close(wai)
    watchoff

    normlap2=ones(length(tmpgri(:,1)),1)*nan;
    % Magnitude shift
    normlap2(ll)= mResult(:,2);
    mMagShift = reshape(normlap2,length(yvect),length(xvect));

    % KS-Test-Value
    normlap2(ll)= mResult(:,5);
    mHkstest = reshape(normlap2,length(yvect),length(xvect));

    %%% Resolution parameters
    % Number of events per grid node in first time period
    normlap2(ll)= mResult(:,6);
    mNumevents1 = reshape(normlap2,length(yvect),length(xvect));

    % Number of events per grid node in first time period
    normlap2(ll)= mResult(:,7);
    mNumevents2 = reshape(normlap2,length(yvect),length(xvect));

    % Validated magnitude shift
    normlap2(ll)= mResult(:,8);
    mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));

    % Absolute FMD difference
    normlap2(ll)= mResult(:,9);
    mChFMD = reshape(normlap2,length(yvect),length(xvect));

    % Mc Periode 1
    normlap2(ll)= mResult(:,10);
    mMc1 = reshape(normlap2,length(yvect),length(xvect));

    % Mc Periode 2
    normlap2(ll)= mResult(:,11);
    mMc2 = reshape(normlap2,length(yvect),length(xvect));

    % Mc change
    normlap2(ll)= mResult(:,12);
    mdMc = reshape(normlap2,length(yvect),length(xvect));

    % Mc change validated by KS-Test
    normlap2(ll)= mResult(:,13);
    mdMc_val = reshape(normlap2,length(yvect),length(xvect));

    % Difference of AIC for Utsu-Test
    normlap2(ll)= mResult(:,14);
    mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));

    % Probability of stationarity (favoring stationarity)
    normlap2(ll)= mResult(:,15);
    mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));

    % Probability of stationarity (favoring non-stationarity)
    normlap2(ll)= mResult(:,16);
    mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));

    % Data to plot first map
    re3 = mMagShift;
    lab1 = 'Magnitude shift';

    % View the map
    view_mcgrid

end   % if sel = na

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

        normlap2=ones(length(tmpgri(:,1)),1)*nan;

        % Magnitude shift
        normlap2(ll)= mResult(:,2);
        mMagShift = reshape(normlap2,length(yvect),length(xvect));

        % KS-Test-Value
        normlap2(ll)= mResult(:,5);
        mHkstest = reshape(normlap2,length(yvect),length(xvect));

        %%% Resolution parameters
        % Number of events per grid node in first time period
        normlap2(ll)= mResult(:,6);
        mNumevents1 = reshape(normlap2,length(yvect),length(xvect));

        % Number of events per grid node in first time period
        normlap2(ll)= mResult(:,7);
        mNumevents2 = reshape(normlap2,length(yvect),length(xvect));

        try
            % Validated magnitude shift
            normlap2(ll)= mResult(:,8);
            mMagShift_valid = reshape(normlap2,length(yvect),length(xvect));

            % Absolute FMD difference
            normlap2(ll)= mResult(:,9);
            mChFMD = reshape(normlap2,length(yvect),length(xvect));
            % Mc Periode 1
            normlap2(ll)= mResult(:,10);
            mMc1 = reshape(normlap2,length(yvect),length(xvect));

            % Mc Periode 2
            normlap2(ll)= mResult(:,11);
            mMc2 = reshape(normlap2,length(yvect),length(xvect));

            % Mc change
            normlap2(ll)= mResult(:,12);
            mdMc = reshape(normlap2,length(yvect),length(xvect));

            % Mc change
            normlap2(ll)= mResult(:,13);
            mdMc_val = reshape(normlap2,length(yvect),length(xvect));

            % Difference of AIC for Utsu-Test
            normlap2(ll)= mResult(:,14);
            mdAIC_Utsu = reshape(normlap2,length(yvect),length(xvect));

            % Probability of stationarity (favoring stationarity)
            normlap2(ll)= mResult(:,15);
            mStationary1_Utsu = reshape(normlap2,length(yvect),length(xvect));

            % Probability of stationarity (favoring non-stationarity)
            normlap2(ll)= mResult(:,16);
            mStationary2_Utsu = reshape(normlap2,length(yvect),length(xvect));

        catch
            disp('Validated magnitude shift map not available');
        end
        % Initial map set to relative rate change
        re3 = mMagShift;
        lab1 = 'Magnitude shift';

        old = re3;
        % Plot
        view_mcgrid;
    else
        return
    end
end


function [t,z] = plotDNLS(prob,opts,xb,confStats,tspan)
%plotDNLS Plot Parameter Estimation Problem

%   Copyright (C) 2013 Jonathan Currie (IPL)

if(nargin < 5), tspan = []; end
if(nargin < 4), confStats = []; end

%Measurement Plot Color
measC = [0.4 0.4 0.4];
%Measurement Plot Style
measS = 'o';
%Initial Condition plot style
icS = 'sq';

%Plot confidence lines if present
if(~isempty(confStats))
    plot(NaN,NaN); %hack to prevent patch removing outer borders
    plotConfReg(confStats);
    hold on;
end

% Insert initial conditions if also solved
ind = isnan(prob.odez0);
if(any(ind))
    len = sum(ind);
    estZ0 = xb(end-len+1:end);
    prob.odez0(ind) = estZ0;
    xb = xb(1:end-len);
end

% Generate smooth plot
dopts = optidynset(opts.dynamicOpts);
if(isempty(tspan))
    tspan = [prob.xdata(1) prob.xdata(end)];
end
ode = @(t,z) prob.ode(t,z,xb);
switch(dopts.integrator)
    case 'ode45'
        [t,z] = ode45(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode15s'
        [t,z] = ode15s(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode23'
        [t,z] = ode23(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode113'
        [t,z] = ode113(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode23t'
        [t,z] = ode23t(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode23tb'
        [t,z] = ode23tb(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode23s'
        [t,z] = ode23s(ode,tspan,prob.odez0,dopts.odeOpts);
    case 'ode15i'
        [t,z] = ode15i(ode,tspan,prob.odez0,dopts.odeOpts);
    otherwise
        optiwarn('OPTI:Plot','Unknown integrator chosen! Using ode45.');
        [t,z] = ode45(ode,tspan,prob.odez0,dopts.odeOpts);
end
if(nargout > 1), return; end %just for evaluating above

%Plot smooth sim
plot(t,z);
title('Dynamic Parameter Estimation Solution');
xlabel('time'); ylabel('z');
hold on;

%Plot Solved Initial Conditions
if(any(ind))
    for i = 1:sum(ind)
        plot(tspan(1),estZ0(i),icS,'Color',measC);
    end
end

%If we have xdata_old, then should be in cell format, plot each cell
if(isfield(prob.misc,'xdata_orig') && ~isempty(prob.misc.xdata_orig))
    if(iscell(prob.misc.xdata_orig) && iscell(prob.misc.ydata_orig))
        for i = 1:length(prob.misc.xdata_orig)
            plot(prob.misc.xdata_orig{i},prob.misc.ydata_orig{i},measS,'Color',measC);
        end
    elseif(~iscell(prob.misc.xdata_orig) && ~iscell(prob.misc.ydata_orig))
        for i = 1:size(prob.misc.ydata_orig,2)
            plot(prob.misc.xdata_orig,prob.misc.ydata_orig(:,i),measS,'Color',measC);
        end
    else
        error('Expected misc.xdata_orig and misc.ydata_orig to be cell arrays');
    end
else
    %Otherwise reshape ydata (always a column in OPTI) and plot
    if(~isempty(dopts.stateIndex))
        nstates = length(prob.odez0(dopts.stateIndex));
    else
        nstates = length(prob.odez0);
    end
    ydata = reshape(prob.ydata,length(prob.xdata),nstates);
    %Plot
    plot(prob.xdata,ydata,measS,'Color',measC);
end

hold off;


function plotRegionOverlapScript

load('~/data/occlusion/labelme/results/result_LM_region_mean_covering.mat');

%% Plot by area
area_vals = [0.0025 0.005 0.01 0.2 0.4 1];

areas = cat(2, cover_occ1.area)';

% assign index for largest area_vals that area is less than or equal to
area_ind = zeros(size(areas));
for k = 1:numel(area_vals)
    area_ind = area_ind + (areas > area_vals(k));
end
area_ind = area_ind+1;

names = {'Pb+ucm', 'globalPb+ucm', 'occ_1', 'occ_{final}'};
area_hist = zeros(numel(area_vals), 4);
ovmax{1} = cat(1, cover_ucm1.maxov);
ovmax{2} = cat(1, cover_ucm2.maxov);
ovmax{3} = cat(1, cover_occ1.maxov);
ovmax{4} = cat(1, cover_occave.maxov);

area_hist = zeros(numel(area_vals), numel(ovmax));
for k = 1:numel(ovmax)
    for k2 = 1:numel(area_vals)
        area_hist(k2, k) = mean(ovmax{k}(area_ind==k2));
    end
end

na = numel(area_vals);
nl = numel(ovmax);
figure(1), hold off;
style = {'--', '--', '-', '-' ,'-'};
markers = {'+', 'x', 'o', '+', 'x'};
for k = 1:numel(ovmax)
    plot(area_hist(:, k), 'LineStyle', style{k}, 'MarkerSize', 12, 'Marker', markers{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/nl, 1, k/nl)); hold on;
end
xlabels = strtokAll(num2str(area_vals), ' ');
xlabels = [[{'0'} ; xlabels(1:end-1)] repmat({'-'}, na, 1)   xlabels(:) [repmat({'|'}, na-1, 1) ; {' '}]]';
axis([1 6 0 1]); set(gca, 'XTick', 1:na, 'XTickLabel', cat(2, xlabels{:}), 'FontSize', 16);
legend(names, 'Location', 'NorthWest')
xlabel('Region Area', 'FontSize', 18); ylabel('Average Overlap', 'FontSize', 18)
print -f1 -depsc ~/data/occlusion/labelme/figs/plots/overlap_comparison_by_area.eps

%% Cumulative overlap
figure(2), hold off,
ind = true(size(areas));
for k = 1:numel(ovmax)
    y = sort(ovmax{k}(ind), 'descend');
    plot((1:numel(y))/numel(y), y, 'LineStyle', style{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/nl, 1, k/nl)); hold on;
end
axis([0 1 0 1]); set(gca, 'XTick', 0:0.1:1, 'FontSize', 16);
legend(names, 'Location', 'NorthEast')
xlabel('Recall', 'FontSize', 18); ylabel('Overlap', 'FontSize', 18)
print -f2 -depsc ~/data/occlusion/labelme/figs/plots/overlap_overall_comparison.eps

%% Cumulative overlap by area
figure(3), hold off,
for k = 1:na-1
    ind = areas>=area_vals(k);
    y = sort(ovmax{end}(ind), 'descend');
    plot((1:numel(y))/numel(y),y, 'LineStyle', style{k}, 'LineWidth', mod(k,3)+2, 'Color', hsv2rgb(k/(na-1), 1, k/(na-1))); hold on;
end
axis([0 1 0 1]); set(gca, 'XTick', 0:0.1:1, 'FontSize', 16);
for k = 1:na-1, lstr{k} = [' >' num2str(area_vals(k))]; end
legend(lstr, 'Location', 'SouthWest')
xlabel('Recall', 'FontSize', 18); ylabel('Overlap', 'FontSize', 18);
print -f3 -depsc  ~/data/occlusion/labelme/figs/plots/overlap_occlusion.eps


function failed_bug2359

% MEM 2gb
% WALLTIME 00:30:00
% DEPENDENCY ft_prepare_mesh ft_prepare_sourcemodel

cd(dccnpath('/home/common/matlab/fieldtrip/data/test/bug2359'));

cortex = ft_read_headshape('cortex_20484.surf.gii');
iskull = ft_read_headshape('iskull_2562.surf.gii');
oskull = ft_read_headshape('oskull_2562.surf.gii');
scalp  = ft_read_headshape('scalp_2562.surf.gii');

figure
ft_plot_mesh(cortex, 'facecolor', 'b');
ft_plot_mesh(iskull, 'facecolor', [0.5 0.5 0.5], 'edgecolor', 'none', 'facealpha', 0.5);

%% PART 1, implement the correction of the cortical sheet by moving points that are too close to the surface inward

% usually the "moveinward" cortex modification would be done for EEG-BEM, but it is
% easier to test it for a MEG singleshell model (for which it is actually not
% needed).

cfg = [];
cfg.method = 'singleshell';
vol = ft_prepare_headmodel(cfg, iskull);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel = cortex;    % this is in mm
cfg.inwardshift = 0;  % this should be expressed in the units consistent with cfg.unit
cfg.moveinward = 0;
gridorig = ft_prepare_sourcemodel(cfg);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel = cortex;      % this is in mm
cfg.inwardshift = -5;  % outward shifted
cfg.moveinward = 0;
gridoutward = ft_prepare_sourcemodel(cfg);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel = cortex;    % this is in mm
cfg.inwardshift = 5; % inward shifted
cfg.moveinward = 0;
gridinward = ft_prepare_sourcemodel(cfg);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel = cortex;    % this is in mm
cfg.inwardshift = 0;  % keep this at the original place
cfg.moveinward = 5;  % dipoles moved inwards
gridcorrect = ft_prepare_sourcemodel(cfg);

assert(isempty(gridorig.outside));
assert(isempty(gridoutward.outside));
assert(~isempty(gridinward.outside)); % this should have a few vertices outside the inward shifted surface
assert(isempty(gridcorrect.outside))

figure
ft_plot_mesh(iskull, 'facecolor', [0.5 0.5 0.5], 'edgecolor', 'none', 'facealpha', 0.5);
ft_plot_mesh(gridorig.pos(gridinward.outside,:), 'vertexcolor', 'b');
ft_plot_mesh(gridcorrect.pos(gridinward.outside,:), 'vertexcolor', 'r');

%% PART 2, implement the spherify of the cortical sheet

mesh = cat(1, iskull, oskull, scalp);

cfg = [];
cfg.method = 'concentricspheres';
vol = ft_prepare_headmodel(cfg, mesh);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel = cortex;    % this is in mm
cfg.spherify = 'yes';
gridsphere = ft_prepare_sourcemodel(cfg);

assert(isempty(gridsphere.outside));

figure
ft_plot_headmodel(vol, 'edgecolor', 'none', 'facecolor', 'skin', 'facealpha', 0.5);
ft_plot_mesh(gridsphere)

%% this is a weird modification, I am just curious to see how it works

cfg = [];
cfg.method = 'singlesphere';
vol = ft_prepare_headmodel(cfg, iskull);

cfg = [];
cfg.headmodel = vol;
cfg.sourcemodel.xgrid = -200:10:200;    % this is in mm
cfg.sourcemodel.ygrid = -200:10:200;    % this is in mm
cfg.sourcemodel.zgrid =  -50:10:150;    % this is in mm
cfg.spherify = 'yes';
gridsphere = ft_prepare_sourcemodel(cfg);

figure
ft_plot_headmodel(vol, 'edgecolor', 'none', 'facecolor', 'skin', 'facealpha', 0.5);
ft_plot_mesh(gridsphere)


function net = res_finetune_init(imdb, n)
net = sprintf('imagenet-resnet-%d-dag', n);

if  ischar(net),
  net_path = fullfile('data','models',[net '.mat']);
  if ~exist(net_path,'file'),
    fprintf('Downloading model (%s) ...', net) ;
    vl_xmkdir(fullfile('data','models')) ;
    urlwrite(fullfile('http://www.vlfeat.org/matconvnet/models', ...
      [net '.mat']), net_path) ;
    fprintf(' done!\n');
  end
  net = dagnn.DagNN.loadobj(load(net_path));
end

net.meta.trainOpts.weightDecay = 0.0001 ;
net.meta.trainOpts.momentum = 0.9;
net.meta.trainOpts.batchSize = 256 ;
net.meta.classes.name = imdb.meta.classes;
net.meta.classes.description = imdb.meta.classes;

% remove 'prob'
net.removeLayer(net.layers(end).name);

[h,w,in,out] = size(zeros(net.layers(end).block.size));
out = numel(net.meta.classes.name);
% remove 'fc'
lName = net.layers(end).name;
net.removeLayer(net.layers(end).name);

pName = net.layers(end).name;
block = dagnn.Conv('size', [h,w,in,out], 'hasBias', true, ...
                   'stride', 1, 'pad', 0);
net.addLayer(lName, block, pName, lName, {[lName '_f'], [lName '_b']});
%net.params(net.layers(end).paramIndexes(1)).value = init_weight(opts, h, w, in, out, 'single');
%net.params(net.layers(end).paramIndexes(2)).value = zeros(out, 1, 'single');
p = net.getParamIndex(net.layers(end).params) ;
params = net.layers(end).block.initParams() ;
params = cellfun(@gather, params, 'UniformOutput', false) ;
[net.params(p).value] = deal(params{:}) ;

lName = net.layers(end).name;
net.addLayer('softmax', dagnn.SoftMax(), lName, 'softmax');
net.addLayer('loss', dagnn.Loss('loss', 'log'), {'softmax', 'label'}, 'loss');
net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'softmax','label'}, 'error') ;
net.addLayer('error5', dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
  {'softmax','label'}, 'error5') ;

net.meta.augmentation.rgbVariance = zeros(0,3) ;
net.meta.augmentation.transformation = 'stretch' ;

end


% VBRFA2011_TESTBED_PLOT - Make the Testbed plots for the VBRFA journal
% paper.

% Last modified 2011-06-15
% Copyright (c) Jaakko Luttinen (jaakko.luttinen@aalto.fi)

function data = vbrfa2011_testbed_plot(model)

% Result files
folder = '/share/climate/jluttine/testbed';
%files = {'testbed_results_ind-t_D=30_20110616'};
files = {'testbed_results_gaussian_D=30_20110617', ...
         'testbed_results_multi-t_D=30_20110617', ...
         'testbed_results_ind-t_D=30_20110617', ...
         'testbed_results_laplace_D=30_20110617'};

% Pick stations from: 12 13 20 21 28 48 57 59
corrupted = [12 13 20 21 28 48 57 59];
stations = [5 corrupted([8 7 6 1 3])];

%
% PLOT DATA OBSERVATIONS
%

data = testbed_loaddata();
data = testbed_preprocess(data);
return
plot_timeseries(data.time, ...
                data.observations(stations,:));
%return

print('-depsc2', '-loose', ...
      '/home/jluttine/papers/rpca_journal/fig_testbed_timeseries_data');
%
% PLOT RESULTS FOR EACH METHOD
%

suffix = {'gaussian', 'multi-t', 'ind', 'laplace'};

% Plot
if nargin < 1
  model = 1:length(files);
end
for n=model
  fprintf('Loading results from file:\n%s\n', files{n});
  Q = load(files{n}, 'W', 'X', 'W_struct');
% $$$   plot_loadings(Q,suffix{n});
  plot_reconstructions(Q,stations,suffix{n});
  %figure, semilogy(Q.W_struct.alpha)
  %fprintf('alpha(%d): %.4e\n', [1:length(Q.w); Q.w(:)']);
end

% $$$ %
% $$$ % PLOT THE STATIONS
% $$$ %
% $$$
% $$$ fig = figure();
% $$$
% $$$ % Plot the research area on the map of Finland
% $$$ hax(1) = subplot(1,2,1);
% $$$ testbed_plot_finland();
% $$$
% $$$ % Plot the stations on a topographic map
% $$$ hax(2) = subplot(1,2,2);
% $$$ set(hax(2), 'FontSize', 9);
% $$$ testbed_plot_topography();
% $$$ hold on;
% $$$ testbed_coast();
% $$$ map_grid();
% $$$ testbed_plot_stations(data.coordinates);
% $$$ hcb = colorbar('peer',hax(2),'FontSize',9);
% $$$
% $$$ % Set layout
% $$$ bottom = 0.07;
% $$$ top = 0.92;
% $$$ set(hax(1), 'Units','Normalized', 'Position',[0.0 bottom 0.22 (top-bottom)]);
% $$$ set(hax(2), 'Units','Normalized', 'Position',[0.27 bottom 0.63 (top-bottom)]);
% $$$ set(hcb, 'Units','Normalized', 'Position',[0.91 bottom 0.02 (top-bottom)]);
% $$$ set_figure_size(15,6.3,fig);
% $$$
% $$$ % $$$ % Print
% $$$ % $$$ print('-depsc2', '-loose', ...
% $$$ % $$$       '/home/jluttine/papers/vbrfa/figures_journal/fig_testbed_stations');
% $$$
% $$$

function plot_timeseries(time,Y)

% Plot timeseries
hax = tsplot(time, Y, 'k');

% Set the range of the x-axis
N = length(hax);
set(hax, 'xlim', [min(time), max(time)]);

% Put date ticks on x-axis
dateticks(hax, 'x', 'mmmyy', 'keeplimits');
set(hax(1:(N-1)), 'xticklabel', []);
set_ticks_fontsize(hax,9);
xtick = get(hax(end), 'xtick');
set(hax, 'xtick', xtick(2:end));

% Remove ticks from y-axis
set(hax, 'ylim', [-50 50], 'yticklabel', [], 'ytick', []);

% Set the layout of the subplots
set_subplot_positions(hax, N, 1, [0.01 0.01 0.01 0.07], [0.02 0.02]);
set_figure_size(15,9)

function plot_reconstructions(Q,stations,suffix)

% Reconstructions
Yh = Q.W(:,stations)' * Q.X;

% Remove time instances with no observations to make the plot more clear
data = load(['/share/climate/jluttine/testbed/' ...
             'testbed_vbrfa2011_traindata']);
% $$$ data = testbed_loaddata();
% $$$ data = testbed_preprocess(data);
ind = sum(~isnan(data.observations),1) == 0;
Yh(:,ind) = nan;

% Plotplotplot
plot_timeseries(data.time, Yh);

% Print figure
print('-depsc2', '-loose', ...
      ['/home/jluttine/papers/rpca_journal/fig_testbed_timeseries_', ...
       suffix]);

function plot_loadings(Q,suffix)

%
% Plot spatial components
%

data = testbed_loaddata();
data = testbed_preprocess(data);

components = 1:4;
hax = testbed_loadings(Q.W(components,:)', ...
                       data.coordinates, ...
                       'resolution', [200 150], ...
                       'method', 'rbf');
% Subplot layout
set_subplot_positions(hax, 2, 2, [0.01 0.01 0.08 0.06], [0.08 0.1]);
% Colorbar layout
colorbars(hax, ...
          'Size', 0.02, ...
          'Separation', 0.0, ...
          'Location', 'EastOutside', ...
          'FontSize', 9);
% X-labels (and layout)
for n=1:numel(components)
  xlabels(hax(n),sprintf('(%d)', components(n)), 'Separation',0.03, 'FontSize', 9);
end
% Print figure
set_figure_size(15,8.5)
% $$$ print('-depsc2', '-loose', ...
% $$$       ['/home/jluttine/papers/vbrfa/figures_journal/fig_testbed_loadings_', ...
% $$$        suffix]);

% Plot reconstructions of problematic stations
%testbed_rcplot(Q, 'stations', [12 13 20 21 28 48 57 59]);


function disp(c)

   % CORRELATION/DISPLAY Command window display of a correlation object
   % See help correlation for fields

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

   disp(' ');
   disp([inputname(1),' = '])
   disp(' ');
   %
   showline('WAVEFORMS', c.traces, 'vector');
   showline('TRIG', c.trig, 'vector');
   showline('CORR', c.corrmatrix, 'square matrix');
   showline('LAG', c.lags, 'square matrix');
   showline('STAT', c.stat, 'matrix');
   showline('LINK', c.link, 'matrix');
   showline('CLUST', c.clust, 'vector');
end

function showline(fname, value, desc)
   fprintf('%11s: %s %s\n',fname, getsizestr(value), desc);
end

function s = getsizestr(val)
   s = num2str(size(val),'%dx');
   s(s == ' ') = [];
   s = s(1:end-1);
end


classdef CumMomentAnalysisWindow < AnalysisWindow
    % CUMMOMENTANALYSISWINDOW shows cumulative moment release
    properties
    end
    methods
        function obj=CumMomentAnalysisWindow(ax)
            obj@AnalysisWindow(ax);
        end

        function prepare_axes(obj)
            % prepare the moment release axes
            if isempty(obj.ax.Tag)
                obj.ax.Tag = 'dvMoment';
            end
            obj.ax.Title.String='Cum Moment Release';
            obj.ax.XLabel.String='time';
            obj.ax.YLabel.String='Cumulative Moment [N m]'; %units as per calc_moment
        end

        function [x,y]=calculate(~,catalog)
            if ~isa(catalog,'ZmapCatalog')
                catalog=catalog.Catalog;
            end
            % return the datetime and cumulative-moment for each event in the catalog
            x=catalog.Date;
            [~, y, ~] = calc_moment(catalog);
        end

    end
end


function [A, b, Aeq, beq, lb, ub] = snd_l_constraints(k, net_load_data, varargin)

    u0_ref = cell2mat(varargin(2));
    f = 1.05;
    g = 0.95;
    p = 1.2;
    A   = []; %A*u<=b
    b   = [];
    Aeq = [1 1 1]; %A*u = b
    beq = net_load_data(k);

    if k ~= 12
        if u0_ref(1,k) * u0_ref(1,k+1) <= 0
            if u0_ref(1,k)>0
                ub = [u0_ref(1,k)*1.05];
                lb = [u0_ref(1,k+1)*1.05];
            else
                ub = [u0_ref(1,k+1)*1.05];
                lb = [u0_ref(1,k)*1.05];
            end
        elseif u0_ref(1,k)>0 && u0_ref(1,k+1)>0
            if u0_ref(1,k)>u0_ref(1,k+1)
                ub = [u0_ref(1,k)*1.05];
                lb = [u0_ref(1,k+1)*0.95];
            else
                ub = [u0_ref(1,k+1)*1.05];
                lb = [u0_ref(1,k)*0.95];
            end
        elseif u0_ref(1,k)<0 && u0_ref(1,k+1)<0
            if u0_ref(1,k)>u0_ref(1,k+1)
                ub = [u0_ref(1,k)*0.95];
                lb = [u0_ref(1,k+1)*1.05];
            else
                ub = [u0_ref(1,k+1)*0.95];
                lb = [u0_ref(1,k)*1.05];
            end
        end
    else
        if u0_ref(1,k) >=0
            ub = [u0_ref(1,k)*1.05];
            lb = [u0_ref(1,k)*0.95];
        else
            ub = [u0_ref(1,k)*0.95];
            lb = [u0_ref(1,k)*1.05];
        end

    end

    if u0_ref(2,k)>0 %
        ub  = [ub, u0_ref(2,k)*1.1,  10];
        lb  = [lb, 0, -10];
    else
        ub  = [ub, 0,  10];
        lb  = [lb, u0_ref(2,k)*1.1, -10];
    end

end


function [coords, data] = dtiRoiGrow2d(data, xformToAcpc, seedAcpc, ax, tol, thick)
%
% [selectedCoords, data] = dtiRoiGrow2d(data, xformToAcpc, seedAcpc, ax, tol, [thick=1])
%
% data is either an image volume (scalar or dt6) or the data struct
% returned after calling this function once (useful if you want to iterate
% with the same image volume, just chaning the tolerance).
%
% seedAcpc: the seed point, in ac-pc coords
%
% ax: the axis to grow in (1,2 or 3). E.g., ax=1 will grow in the slice
% X=seedAcpc(1), ax=2 will grow in Y=seedAcpc(2), and ax=3 in
% Z=seedAcpc(3).
%
% tol: the tolerance (between 0 and 1, with lower values including fewer
% voxels).
%
% thick: the thickness of the resulting coordinates. The algorithm grows in
% a single slice. thick > 1 will replicate the selected coords in adjacent
% slices for you.
%
% E.g.:
% dt = dtiLoadDt6('dti06trilinrt/dt6');
% seedAcpc = [-36 -28 26];
% ax = 3;
% tol = .20;
% [coords, data] = dtiRoiGrow2d(dt.dt6, dt.xformToAcpc, seedAcpc, ax, tol);
% % Show the delta image with the selected coords overlaid
% figure; image(data.x(:), data.y(:), data.img); axis equal tight xy;
% hold on; plot(coords(:,1),coords(:,2),'k.'); hold off;
%
% % do it again with stricter tol and passing the pre-processed data:
% coords = dtiRoiGrow2d(data, dt.xformToAcpc, seedAcpc, ax, 0.10);
% figure; image(data.x(:), data.y(:), data.img); axis equal tight xy;
% hold on; plot(coords(:,1),coords(:,2),'k.'); hold off;
%
% HISTORY
% 2009.08.26 RFD: pulled code from dtiFiberUI so that we can easily scrip it.
%

if(~exist('thick','var')||isempty(thick))
    thick = 1;
end

if(~isstruct(data))
    if(ndims(data)==3)
        [img,x,y,z] = dtiGetSlice(xformToAcpc, data, ax, seedAcpc(ax), [], 'n');
        if(ax==2), yseed = find(x(:,1)>seedAcpc(1)-.5&x(:,1)<=seedAcpc(1)+.5);
        else yseed = find(y(:,1)>seedAcpc(2)-.5&y(:,1)<=seedAcpc(2)+.5); end
        if(ax==3), xseed = find(x(1,:)>seedAcpc(1)-.5&x(1,:)<=seedAcpc(1)+.5);
        else xseed = find(z(1,:)>seedAcpc(3)-.5&z(1,:)<=seedAcpc(3)+.5); end
    elseif(ndims(data)==4)
        % Then it's a dt6 (tensor). We'll create a map of the angle between the
        % seed point PDD and each image voxel PDD.
        [dt6,x,y,z] = dtiGetSlice(xformToAcpc, data, ax, seedAcpc(ax), [], 'n');
        if(ax==2), yseed = find(x(:,1)>seedAcpc(1)-.5&x(:,1)<=seedAcpc(1)+.5);
        else yseed = find(y(:,1)>seedAcpc(2)-.5&y(:,1)<=seedAcpc(2)+.5); end
        if(ax==3), xseed = find(x(1,:)>seedAcpc(1)-.5&x(1,:)<=seedAcpc(1)+.5);
        else xseed = find(z(1,:)>seedAcpc(3)-.5&z(1,:)<=seedAcpc(3)+.5); end
        [eigVec,eigVal] = dtiEig(dt6);
        seedPdd = squeeze(eigVec(yseed,xseed,:,1));
        % dot(eigVec(1,:),[1 0 0]) = eigVec(1,1) and dot(eigVec(1,:),[0 1 0]) = eigVec(1,2)
        img = eigVec(:,:,1,1).*seedPdd(1)+eigVec(:,:,2,1).*seedPdd(2)+eigVec(:,:,3,1).*seedPdd(3);
        img(img>1) = 1; img(img<-1) = -1;
        img = acos(img);
        % Reflect about pi/2 for angles > pi/2 (diffusion is symmetric along the eigenvector axis)
        img(img>pi/2) = pi/2-(img(img>pi/2)-pi/2);
        img = img./(pi/2);
        % FA an MD should matter too, since we usually don't want to grow
        % into regions with very different anisotropy from our seed. But-
        % should it get equal weighting to our angle measure? Maybe make it a
        % parameter?
        [fa,md] = dtiComputeFA(eigVal);
        maxMd = md(yseed,xseed)*3;
        md(md>maxMd) = maxMd;
        md = md./maxMd;
        %img = 0.5*img + 0.5*abs(fa-fa(yseed,xseed));
        img = cat(3, img, abs(fa-fa(yseed,xseed)), abs(md-md(yseed,xseed)));
        %figure;imagesc(img);axis image xy; colormap gray
    end
    clear data;
    data.img = img;
    data.x = x;
    data.y = y;
    data.z = z;
    data.xseed = xseed;
    data.yseed = yseed;
end

binImg = magicwand1(data.img, data.yseed, data.xseed, tol);
ind = find(binImg);
coords = [data.x(ind), data.y(ind), data.z(ind)];
for(ii=[1:thick-1,-1:-1:-(thick-1)])
	newLayer = coords;
    newLayer(:,ax) = newLayer(:,ax)+ii;
    coords = [coords; newLayer];
end
coords = unique(coords, 'rows');
return;


function [lf] = eeg_halfspace_dipole(dippos, elc, vol)

% EEG_HALFSPACE_DIPOLE calculate the leadfield on electrode positions elc
% for a dipole at position dippos. The halfspace solution requires a plane dividing a
% conductive zone (cond > 0), from a non-coductive zone (cond = 0).
%
% Use as
%   [lf] = eeg_halfspace_dipole(dippos, elc, vol)
%
% See also EEG_INFINITE_DIPOLE, EEG_INFINITE_MONOPOLE, EEG_HALFSPACE_MONOPOLE

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

if isfield(vol, 'pos')
  % this is for forward/backward compatibility
  vol.pnt = vol.pos;
  vol = rmfield(vol, 'pos');
end

siz = size(dippos);
if any(siz==1)
  % positions are specified as a single vector
  Ndipoles = prod(siz)/3;
  dippos = dippos(:)'; % ensure that it is a row vector
elseif siz(2)==3
  % positions are specified as a Nx3 matrix -> reformat to a single vector
  Ndipoles = siz(1);
  dippos = dippos';
  dippos = dippos(:)'; % ensure that it is a row vector
else
  ft_error('incorrect specification of dipole locations');
end

Nelc     = size(elc,1);
lf       = zeros(Nelc,3*Ndipoles);

for i=1:Ndipoles
  % this is the position of dipole "i"
  dip1 = dippos((1:3) + 3*(i-1));

  % find the position of a mirror dipole symmetric to the plane
  dip2 = get_mirror_pos(dip1, vol);

  % compute the potential of the original and the mirror dipole
  lf1 = eeg_infinite_dipole(dip1, elc, vol);
  lf2 = eeg_infinite_dipole(dip2, elc, vol);

  % the z-direction of the mirror dipole should be swapped
  lf2(:,3) = -lf2(:,3);

  % take the sum of the two dipoles
  lf = lf1 + lf2;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function P2 = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to pnt with respect to a plane

% define the plane
pnt = vol.pnt;
ori = vol.ori; % already normalized

if abs(dot(P1-pnt,ori))<eps
  ft_warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3)))
  P2 = P1;
else
  % define the plane in parametric form
  % define a non colinear vector vc with respect to the plane normal
  vc = [1 0 0];
  if abs(cross(ori, vc, 2))<eps
    vc = [0 1 0];
  end
  % define plane's direction vectors
  v1 = cross(ori, vc, 2);  v1 = v1/norm(v1);
  v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
  plane = [pnt v1 v2];

  % distance plane-point P1
  d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2));

  % symmetric point
  P2 = P1 + 2*d*ori;
end


classdef select_pairs< dagnn.ElementWise
%   In the first form of label_type, C has dimension H x W x 2 x N and specifies a
%   2 categorical label for each spatial location.   C(:,:,1,:) == ones(H,W,N). C(:,:,2,:)== zeros(H,W,N);
%   In the second form of label_type, C has dimension H x W x 1 x N and specifies a
%   categorical label for each spatial location.

  properties
    label_type = 'form2'
  end

  methods
      % --------------------------------------------------------------------
      function y = zerosLike(obj,x)
          % --------------------------------------------------------------------
          if isa(x,'gpuArray')
              y = gpuArray.zeros(size(x),classUnderlying(x)) ;
          else
              y = zeros(size(x),'like',x) ;
          end
      end
%
      function y = onesLike(obj, x)
          % --------------------------------------------------------------------
          if isa(x,'gpuArray')
              y = gpuArray.ones(size(x),classUnderlying(x)) ;
          else
              y = ones(size(x),'like',x) ;
          end
      end

    function outputs = forward(obj, inputs, params)
        score = inputs{1};
        label = inputs{2};
        ind_pos = label>0;
        ind_neg = label<0;
        ind_pos = ind_pos(:);
        ind_neg = ind_neg(:);
        n_pos = sum(ind_pos);
        n_neg = sum(ind_neg);
        ind_select = ones(n_pos,n_neg)>0;
        pos_use = sum(ind_select,2);
        neg_use = sum(ind_select,1);
%         instance_weight = 1./(pos_use*neg_use+eps);
        instance_weight = ones(n_pos,n_neg);
        n_pairs = sum(ind_select(:));
        sz_in = size(score);
        try
            batch_size = sz_in(4);
        catch
            batch_size = 1;
        end
%         out = 0;
        if isa(score,'gpuArray')
              in0 = gpuArray.zeros([n_pairs,2,batch_size],classUnderlying(score)) ;
              instance_weight =gpuArray(instance_weight );
          else
              in0 = zeros([n_pairs,2,batch_size],'single');
        end

        for i = 1:batch_size
            tmp_s = score(:,:,:,i);
            pos = tmp_s(ind_pos);
            neg = tmp_s(ind_neg);
%             ef1 = exp(pos); ef2 = exp(neg);
            pos_m = repmat(pos,1,n_neg).*instance_weight;
            neg_m = repmat(neg',n_pos,1).*instance_weight;
            pos_v = pos_m(ind_select);
            neg_v = neg_m(ind_select);
            if size(pos_v,1)==1
                pos_v = pos_v'; neg_v = neg_v';
            end
            in0(:,:,i) = [pos_v,neg_v];
        end
        in0 = reshape(in0,[1,n_pairs,2,batch_size]);
%         switch obj.label_type
%             case 'form1'
%         label0 = obj.zerosLike(in0);
%         label0(:,:,1,:) = 1;
%             case 'form2'
%                 label0 = ones(1,n_pairs,1,batch_size,'single');
%             otherwise
%
%         end

        outputs{1} = in0;
%         outputs{2} = label0;
%         sz_in = size(inputs{1});
%         n = prod(sz_in(1:3));
%         ef1 = exp(inputs{1});
%         ef2 = exp(inputs{2});
%         out = 2*(ef2./(ef1+ef2+eps)).^2 ;
%       outputs{1} = sum(out(:))/n;
%       n = obj.numAveraged ;
%       m = n + size(inputs{1},4) ;
%       obj.average = (n * obj.average + gather(outputs{1})) / m ;
%       obj.numAveraged = m ;
    end

    function [derInputs, derParams] = backward(obj, inputs, params, derOutputs)
        score = inputs{1};
        label = inputs{2};
        ind_pos = label>0;
        ind_neg = label<0;
        ind_pos = ind_pos(:);
        ind_neg = ind_neg(:);
        n_pos = sum(ind_pos);
        n_neg = sum(ind_neg);
        ind_select0 = ones(n_pos,n_neg,'single');
        ind_select = ind_select0>0;
        pos_use = sum(ind_select,2);
        neg_use = sum(ind_select,1);
%         instance_weight = 1./(pos_use*neg_use+eps);
        instance_weight = ones(n_pos,n_neg);
        if isa(score,'gpuArray')
            ind_select0 = gpuArray(ind_select0);
            instance_weight =gpuArray(instance_weight );
        end
%         n_pairs = sum(ind_select(:));
        sz_in = size(score);
        try
            batch_size = sz_in(4);
        catch
            batch_size = 1;
        end
        der1 = squeeze(derOutputs{1});

%         out = 0;
        derIn0 = obj.zerosLike(score);
%         derOutputs{1} = derOutputs{1}/n_pairs;
        for i = 1:batch_size
            tmp = obj.zerosLike(ind_select0);
            tmp(ind_select) = der1(:,1,i);
            tmp = tmp .*instance_weight;
            tmp_s = score(:,:,:,i);
            der_tmp = obj.zerosLike(tmp_s);
            der_tmp(ind_pos) = sum(tmp,2);

            tmp = obj.zerosLike(ind_select0);
            tmp(ind_select) = der1(:,2,i);
            tmp = tmp .*instance_weight;
%             der_tmp = obj.zerosLike(tmp_s);
            der_tmp(ind_neg) = sum(tmp,1);
            derIn0(:,:,1,i) = reshape(der_tmp,size(tmp_s));

%             pos = tmp_s(ind_pos);
%             neg = tmp_s(ind_neg);
%             ef1 = exp(pos); ef2 = exp(neg);
%             ef1_m = repmat(ef1,1,n_neg).*ind_select;
%             ef2_m = repmat(ef2',n_pos,1).*ind_select;
%             derIn1 =  -4.*ef2_m.^2./((ef1_m+ef2_m).^3+eps).*derOutputs{1};
%             der_tmp(ind_pos) = sum(derIn1,2);
%             derIn2 = derIn1 *(-1).* ef1_m;
%             der_tmp(ind_neg) = sum(derIn2);
%             derIn0(:,:,1,i) = reshape(der_tmp,size(tmp_s));
        end
        derInputs{1} = derIn0;
        derInputs{2} = [];
%         sz_in = size(inputs{1});
%         n = prod(sz_in(1:3));
%         derOutputs{1} = derOutputs{1}/n;
%         ef1 = exp(inputs{1});
%         ef2 = exp(inputs{2});
%       derInputs{1} = -4.*ef2.^2./((ef1+ef2).^3+eps).*derOutputs{1};
%       derInputs{2} = derInputs{1}*(-1).* ef1;
      derParams = {} ;
    end

%     function reset(obj)
%       obj.average = 0 ;
%       obj.numAveraged = 0 ;
%     end

    function outputSizes = getOutputSizes(obj, inputSizes, paramSizes)
      outputSizes{1} = [1 1 1 inputSizes{1}(4)] ;
    end

    function rfs = getReceptiveFields(obj)
      % the receptive field depends on the dimension of the variables
      % which is not known until the network is run
      rfs(1,1).size = [NaN NaN] ;
      rfs(1,1).stride = [NaN NaN] ;
      rfs(1,1).offset = [NaN NaN] ;
      rfs(2,1) = rfs(1,1) ;
    end

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


function grid = reshapeGrid(~, grid)
%RESHAPEGRID   Add the repeated endpoint to a 1D periodic grid.

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

% Note: We use periodic discretizations in 1D/2D/3D. These discretizatioins
% do not include the repeated endpoints. Before plotting data with
% SPINOPERATOR/INITIALIZEMOVIE, we add these repeated endpoints to the grid.

% Get the points:
xx = grid{1};

% Add the endpoint:
xx = [xx; 2*xx(end) - xx(end-1)];

% Output the new grid:
grid{1} = xx;

end


function u = ldivide(a,b)
%LDIVIDE      Slope elementwise left division  a .\ b
%

% written  11/02/05     S.M. Rump
%

  u = b ./ a;


function [GrainBoundaryX,GrainBoundaryY]=IdentifyGrainBoundary(x,y,state)

count=1;
for i=1:size(x,1)-1
    for j=1:(size(x,1)-1)
        if state(i,j)~=state(i,j+1)
            GrainBoundaryX(1,count)=x(i,j);
            GrainBoundaryY(1,count)=y(i,j);
            count=count+1;
        end
        if state(i,j)~=state(i+1,j)
            GrainBoundaryX(1,count)=x(i,j);
            GrainBoundaryY(1,count)=y(i,j);
            count=count+1;
        end
    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/IdentifyGrainBoundary.m


function [f,g,h] = fminunc_wrapper(x,F,G,H)
% [f,g,h] = fminunc_wrapper( x, F, G, H )
% for use with Matlab's "fminunc"
f = F(x);
if nargin > 2 && nargout > 1
    g = G(x);
end
if nargin > 3 && nargout > 2
    h = H(x);
end


function [  ] = convertPLY( openDir, saveDir )
%CONVERTPLY Summary of this function goes here
%   Detailed explanation goes here

    % For KITTI Dataset

    fileExt = '*.bin';
    files = dir(fullfile(openDir,fileExt));

    for i=0:length(files)-1
        i

        fileID = sprintf('%06d', i);
        fileName = [openDir, fileID, '.bin' ];

        xyz = readVelodyne(fileName);
        xyz = xyz';
        xyz = xyz(:,1:3);

        pt = pointCloud(xyz);

        saveName = [saveDir, num2str(i), '.ply'];
        pcwrite(pt, saveName);

    end

end


function out = chebcoeffs(f, varargin)
%CHEBCOEFFS   Chebyshev polynomial coefficients of a CLASSICFUN.
%   CHEBCOEFFS(F) returns the Chebyshev coefficients of F.ONEFUN.
%
% See also LEGPOLY, TRIGCOEFFS.

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

% Call CHEBCOEFFS() of the .ONEFUN:
out = chebcoeffs(f.onefun, varargin{:});

end


classdef PdeVariableToPrintGetter < handle

    properties (Access = private)
      physicalProblem
    end

    methods (Access = public)

        function obj = PdeVariableToPrintGetter(cParams)
            obj.init(cParams)
        end

        function v = compute(obj)
            p = obj.physicalProblem;
            if isempty(p.variables)
                p.computeChomog();
            end
            v.stress = p.variables.stress;
            v.strain = p.variables.strain;
%             v.u      = obj.splitDisplacement(p.variables.d_u,p.getDimensions().ndimf);
            v.u      = p.variables.d_u;
            v.quad   = p.getQuadrature();
        end

    end

    methods (Access = private)

        function init(obj,cParams)
            obj.physicalProblem = cParams.physicalProblem;
        end

    end

    methods (Access = private, Static)

        function uM = splitDisplacement(u,nu)
            nnode = round(length(u)/nu);
            nodes = 1:nnode;
            uM = zeros(nnode,nu);
            for idim = 1:nu
                dofs = nu*(nodes-1)+idim;
                uM(:,idim) = u(dofs);
            end
        end

    end

end


function plot_time(catalogObject)
    %CATALOG.PLOT_TIME Plot magnitude and depth against time
    %   catalogObject.plot_time()

    % Glenn Thompson 2014/06/01

    symsize = get_symsize(catalogObject);
    timerange = catalogObject.gettimerange();
    xlims = [floor(timerange(1)) ceil(timerange(2))];

    % time-depth
    if all(isnan(catalogObject.depth))
        warning('No depth data to plot');
    else
        figure;
        set(gcf,'Color', [1 1 1]);
        subplot(2,1,1);
        scatter(catalogObject.otime, catalogObject.depth, symsize);
        set(gca, 'XLim', xlims);
        datetick('x');
        xlabel('Date');
        ylabel('Depth (km)');
        set(gca, 'YDir', 'reverse');
        grid on;

        % time-mag
        subplot(2,1,2);
    end
    if all(isnan(catalogObject.mag))
        warning('No magnitude data to plot');
    else
        scatter(catalogObject.otime, catalogObject.mag, symsize);
        %stem(catalogObject.otime, catalogObject.mag);
        set(gca, 'XLim', xlims);
        datetick('x');
        xlabel('Date');
        ylabel('Magnitude');
        grid on;
    end
end


function [map,data] = PhaseMango(spikes,phases,varargin)

%PhaseMango - Compute phase as a function of spike rate and acceleration.
%
% Compute spike phase as a function of spike rate and acceleration, as in
% Harris et al. (2002). The name of the function refers to the aspect of
% the resulting phase plot.
%
%  USAGE
%
%    [map,data] = PhaseMango(spikes,phases,<options>)
%
%    spikes         spike timestamps
%    phases         phase samples (see Phase)
%    <options>      optional list of property-value pairs (see table below)
%
%    =========================================================================
%     Properties    Values
%    -------------------------------------------------------------------------
%     'smooth'      smoothing size in bins (0 = no smoothing, default = 2)
%     'nBins'       number of horizontal and vertical bins (default = [50 50])
%     'limits'      [maxRate minAccel maxAccel] (default = [8 -2 2])
%     'maxGap'      time gaps between successive position samples exceeding
%                   this threshold (e.g. undetects) will not be interpolated
%                   (default = 100 ms)
%     'boundaries'  onset and offset for single-lap phase precession can be
%                   determined either automatically based on spike count
%                   ('count', default) or using explicit firing field
%                   boundaries ([Xstart Xstop], where each X is in [0..1])
%    =========================================================================
%
%  OUTPUT
%
%    map.x                x bins
%    map.y                y bins
%    map.phase            phase map
%    map.count            count map
%
%    data.rate            spike rate for each cycle
%    data.acceleration    spike acceleration for each cycle
%    data.phase           mean spike phase (in radians) for each cycle
%
%  SEE
%
%    See also Phase, PhasePrecession, PlotPhaseMango.

% Copyright (C) 2004-2012 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.

% Default values
maxGap = 0.1;
smooth = 2;
nBins = 50;
limits = [8 -2 2];

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

% Check parameter sizes
if ~isdvector(spikes),
	error('Parameter ''spikes'' is not a vector (type ''help PhaseMango'' for details).');
end
if size(phases,2) ~= 2,
	error('Parameter ''phases'' is not a Nx2 matrix (type ''help PhaseMango'' for details).');
end
isradians(phases(:,2));

% Parse options
for i = 1:2:length(varargin),
	if ~ischar(varargin{i}),
		error(['Parameter ' num2str(i+2) ' is not a property (type ''help PhaseMango'' for details).']);
	end
	switch(lower(varargin{i})),
		case 'smooth',
			smooth = varargin{i+1};
			if ~isdvector(smooth,'>=0') || length(smooth) > 2,
				error('Incorrect value for property ''smooth'' (type ''help PhaseMango'' for details).');
			end
		case 'nbins',
			nBins = varargin{i+1};
			if ~isivector(nBins,'>0') || length(nBins) > 2,
				error('Incorrect value for property ''nBins'' (type ''help PhaseMango'' for details).');
			end
		case 'limits',
			limits = varargin{i+1};
			if ~isivector(limits,'#3') || limits(1) <0 || limits(3) < limits(2),
				error('Incorrect value for property ''limits'' (type ''help PhaseMango'' for details).');
			end
		case 'maxgap',
			maxGap = varargin{i+1};
			if ~isdscalar(maxGap,'>0'),
				error('Incorrect value for property ''maxGap'' (type ''help PhaseMango'' for details).');
			end
		otherwise,
			error(['Unknown property ''' num2str(varargin{i}) ''' (type ''help PhaseMango'' for details).']);
	end
end

% Default values
data.time = [];
data.rate = [];
data.acceleration = [];
data.phase = [];
map.x = [];
map.y = [];
map.phase = [];
map.count = [];

% Compute spike phases
if isempty(spikes), return; end
spikePhases = Interpolate(phases,spikes,'trim','off','type','circular');
spikePhases = exp(j*spikePhases(:,2));
if isempty(spikePhases), return; end

% Determine theta cycles (start/stop)
phases(:,2) = wrap(phases(:,2),1); % in [-pi,pi]
start = phases(ZeroCrossings(phases),1);
stop = start(2:end);
start = start(1:end-1);
data.time = start;

% Determine to which theta cycle each spike belongs
[~,spikeCycles] = InIntervals(spikes,[start stop]);
partialCycles = spikeCycles==0;
spikeCycles(partialCycles) = [];

% Compute number of spikes in each cycle
nSpikes = Accumulate(spikeCycles,1,size(start));

% Compute average phase in each cycle
spikePhases(partialCycles) = [];
data.phase = angle(Accumulate(spikeCycles,spikePhases,size(start))./nSpikes);

phase = Accumulate(spikeCycles,spikePhases,size(start))./nSpikes;
phase(nSpikes==0) = 0;
kernel = ones(7,1)/7;
data.phase = angle(conv(phase,kernel,'same'));

% Estimate spike rate and acceleration in each cycle

% Rate = average number of spikes over 7 surrounding cycles, which can be
% efficiently computed as the convolution of nSpikes with the kernel (1/7,..,1/7)
kernel = ones(7,1)/7;
data.rate = conv(nSpikes,kernel,'same');
% Acceleration = slope of linear regression over 7 surrounding cycles
% The general formula is b = (E[xy]-E[x]E[y]) / (E[x²]-E[x]²)
% To compute this efficiently, we first note that the slope is unchanged
% by translations along x the axis: we choose x in {-3..3}, so that E[x]=0.
% We then compute E[x²] = 4, and end up with b = 1/4 E[xy], which can be
% computed as the convolution of y with the kernel (3,2,1,0,-1,-2,-3)/7.
kernel = (3:-1:-3)/7;
data.acceleration = conv(nSpikes,kernel,'same')/4;

% Number of bins for x and y
nBinsX = nBins(1);
if length(nBins) == 1,
	nBinsY = nBinsX;
	nBins(2) = nBins;
else
	nBinsY = nBins(2);
end

% Min and max speed and acceleration
xLims = [0 limits(1)];
yLims = limits(2:3);

% Bin rate and acceleration
rate = Bin(data.rate,xLims,nBinsX);
acceleration = Bin(data.acceleration,yLims,nBinsY);

% Compute phase map
map.phase = angle(Smooth(Accumulate([rate acceleration],exp(j*data.phase),[nBinsX nBinsY]),smooth))';
map.count = Smooth(Accumulate([rate acceleration],1,[nBinsX nBinsY]),smooth)';

% Bins
map.x = linspace(xLims(1),xLims(2),nBinsX);
map.y = linspace(yLims(1),yLims(2),nBinsY);

%  figure;
%  hold on;
%  PlotXY(phases);
%  PlotTicks(spikes,'size',1,'k');
%  plot(start,nSpikes,'b*');
%  plot(start,data.rate,'r*');


function Psi0 = biasVardistPsi0Compute(biaskern, vardist)

% BIASVARDISTPSI0COMPUTE one line description
% FORMAT
% DESC description
% RETURN Psi0 : description
% ARG biasKern : the kernel structure associated with the white kernel.
% ARG vardist : description
%
%
% SEEALSO : others
%
%
% COPYRIGHT : Michalis K. Titsias, 2009
%

% VARGPLVM

Psi0 = vardist.numData*biaskern.variance;


function option = femoption(option)
%% FEMOPTION provides default options for femPoisson
%
% option = femoption(option)
%
%  - options.elemType:  type of finite element
%  - options.maxIt
%  - options.maxN
%  - options.L0
%  - options.refType    mesh refinement type
%  - options.printlevel
%  - options.plotflag
%  - options.rateflag
%  - options.dispflag
%  - options.tol
%  - options.lumpflag

if ~isfield(option,'elemType')
    option.elemType = 'P1';
end

if ~isfield(option,'maxIt')
    option.maxIt = 4;
end

if ~isfield(option,'maxN')
    option.maxN = 2e5;
end

if ~isfield(option,'L0')
    option.L0 = 0;
end

if ~isfield(option,'refType')
    option.refType = 'red';
end

if ~isfield(option,'printlevel')
    option.printlevel = 1;
end

if ~isfield(option,'plotflag')
    option.plotflag = 1;
end

if ~isfield(option,'rateflag')
    option.rateflag = 1;
end

if ~isfield(option,'dispflag')
    option.dispflag = 1;
end

if ~isfield(option,'tol')
    option.tol = 1e-8;
end

if ~isfield(option,'lumpflag') % mass lumping
    option.lumpflag = 0;       % no mass lumping
end


function make3plots(X1, Y1, Y2, Y3)
%CREATEFIGURE1(X1,Y1,Y2,Y3)
%  X1:  vector of x data
%  Y1:  vector of y data
%  Y2:  vector of y data
%  Y3:  vector of y data

%  Auto-generated by MATLAB on 14-Feb-2007 22:38:36

% Create figure
figure1 = figure;

% Create subplot
subplot1 = subplot(3,1,1,'Parent',figure1,'YGrid','on','XGrid','on');
box('on');
hold('all');

% Create plot
plot(X1,Y1,'Parent',subplot1,'LineWidth',2,'Color',[0 0 0]);

% Create ylabel
ylabel('Plunge (in)','FontWeight','demi','FontSize',12);

% Create title
title('Closed-Loop Response','FontWeight','demi','FontSize',12);

% Create subplot
subplot2 = subplot(3,1,2,'Parent',figure1,'YGrid','on','XGrid','on');
box('on');
hold('all');

% Create plot
plot(X1,Y2,'Parent',subplot2,'LineWidth',2,'Color',[0 0 0]);

% Create ylabel
ylabel('Pitch (deg)','FontWeight','demi','FontSize',12);

% Create subplot
subplot3 = subplot(3,1,3,'Parent',figure1,'YGrid','on','XGrid','on');
box('on');
hold('all');

% Create plot
plot(X1,Y3,'Parent',subplot3,'LineWidth',2,'Color',[0 0 0]);

% Create xlabel
xlabel('Time (s)','FontWeight','demi','FontSize',12);

% Create ylabel
ylabel('TE Pos (deg)','FontWeight','demi','FontSize',12);


function exact = p06_exact ( )

%*****************************************************************************80
%
%% P06_EXACT returns the exact integral for problem 6.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    28 July 2007
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Output, real EXACT, the estimated value of the integral.
%
  exact = 0.00056103711148387120640;

  return
end


% This is material illustrating the methods from the book
% Financial Modelling  - Theory, Implementation and Practice with Matlab
% source
% Wiley Finance Series
% ISBN 978-0-470-74489-5
%
% Date: 02.05.2012
%
% Authors:  Joerg Kienitz
%           Daniel Wetterau
%
% Please send comments, suggestions, bugs, code etc. to
% kienitzwetterau_FinModelling@gmx.de
%
% (C) Joerg Kienitz, Daniel Wetterau
%
% Since this piece of code is distributed via the mathworks file-exchange
% it is covered by the BSD license
%
% This code is being provided solely for information and general
% illustrative purposes. The authors will not be responsible for the
% consequences of reliance upon using the code or for numbers produced
% from using the code.

function createfigure_returns(x,y1, y2, y3,tit,legend1,legend2,legend3)
%CREATEFIGURE(X1,YMATRIX1)
%  x:  vector of xvalue data
%  y1,y2,y3:  vectors of densities yvalue data

% Create figure
figure('PaperSize',[20.98 29.68],...
    'Name',tit,'Color',[1 1 1]);

% Create axes
box('on');
hold('all');

ylow = min(min(y2),min(y3)); ylow = min(ylow,min(y1));
yhigh = max(max(y2),max(y3)); yhigh = max(yhigh, max(y1));

%ylow = -0.1;
%yhigh = 0.1;

subplot(3,1,1); plot(x,y1, 'black','DisplayName',legend1); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend1);
subplot(3,1,2); plot(x,y2, 'black', 'DisplayName',legend2); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend2);
subplot(3,1,3); plot(x,y3, 'black', 'DisplayName',legend3); xlabel('Time'); ylabel('Return Value');ylim([ylow yhigh]);title(legend3);


% Image Reconstruction With Directional Sensors Example
%
% This example demonstrates how the directionality of sensor elements can
% give rise to artefacts in time reversal photoacoustic image
% reconstruction. It builds on the Sensor Element Directivity in 2D and 2D
% Time Reversal Reconstruction For A Line Sensor examples.
%
% author: Bradley Treeby & Ben Cox
% date: 18th January 2010
% last update: 24th August 2014
%
% This function is part of the k-Wave Toolbox (http://www.k-wave.org)
% Copyright (C) 2009-2014 Bradley Treeby and Ben Cox

% This file is part of k-Wave. k-Wave 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.
%
% k-Wave 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 Lesser General Public License
% along with k-Wave. If not, see <http://www.gnu.org/licenses/>.

clear all

% =========================================================================
% SIMULATION
% =========================================================================

% create the computational grid
PML_size = 20;          % size of the PML in grid points
Nx = 128 - 2*PML_size;  % number of grid points in the x (row) direction
Ny = 256 - 2*PML_size;  % number of grid points in the y (column) direction
dx = 0.1e-3;            % grid point spacing in the x direction [m]
dy = 0.1e-3;            % grid point spacing in the y direction [m]
kgrid = makeGrid(Nx, dx, Ny, dy);

% define the properties of the propagation medium
medium.sound_speed = 1500;	% [m/s]

% create initial pressure distribution using makeDisc
disc_magnitude = 5; % [au]
disc_x_pos = 60;    % [grid points]
disc_y_pos = 140;  	% [grid points]
disc_radius = 5;    % [grid points]
disc_2 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);

disc_x_pos = 30;    % [grid points]
disc_y_pos = 110; 	% [grid points]
disc_radius = 8;    % [grid points]
disc_1 = disc_magnitude*makeDisc(Nx, Ny, disc_x_pos, disc_y_pos, disc_radius);

% smooth the initial pressure distribution and restore the magnitude
p0 = smooth(kgrid, disc_1 + disc_2, true);

% assign to the source structure
source.p0 = p0;

% define a four-sided, square sensor
sensor.mask = zeros(kgrid.Nx, kgrid.Ny);
sensor.mask(1, :) = 1;
sensor.mask(end, :) = 1;
sensor.mask(:, 1) = 1;
sensor.mask(:, end) = 1;

% create the time array
[kgrid.t_array, dt] = makeTime(kgrid, medium.sound_speed);

% set the input arguements
input_args = {'PMLInside', false, 'PMLSize', PML_size, 'PlotPML', false, 'Smooth', false};

% run the simulation for omnidirectional detector elements
sensor_data = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});

% define the directionality of the sensor elements
sensor.directivity_angle = zeros(kgrid.Nx, kgrid.Ny);
sensor.directivity_angle(1, :) = 0;    	 % max sensitivity in x direction
sensor.directivity_angle(end, :) = 0;  	 % max sensitivity in x direction
sensor.directivity_angle(:, 1) = pi/2;   % max sensitivity in y direction
sensor.directivity_angle(:, end) = pi/2; % max sensitivity in y direction

% define the directivity size
sensor.directivity_size = 20*kgrid.dx;

% run the simulation with directional elements
sensor_data_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});

% reset the initial pressure
source.p0 = 0;

% assign the time reversal data for the omnidirectional case
sensor.time_reversal_boundary_data = sensor_data;

% run the time reversal reconstruction
p0_recon = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});

% assign the time reversal data for the directional case
sensor.time_reversal_boundary_data = sensor_data_directional;

% run the time reversal reconstruction with directional elements
p0_recon_directional = kspaceFirstOrder2D(kgrid, medium, source, sensor, input_args{:});

% =========================================================================
% VISUALISATION
% =========================================================================

% plot the initial pressure and sensor distribution
figure;
imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0 + sensor.mask*disc_magnitude, [-disc_magnitude disc_magnitude]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
colorbar;

% plot the reconstructed initial pressure
figure;
imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon, [-disc_magnitude disc_magnitude]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
colorbar;

% plot the reconstructed initial pressure with directivity
figure;
imagesc(kgrid.y_vec*1e3, kgrid.x_vec*1e3, p0_recon_directional, [-disc_magnitude disc_magnitude]);
colormap(getColorMap);
ylabel('x-position [mm]');
xlabel('y-position [mm]');
axis image;
colorbar;

% plot a profile for comparison
figure;
plot(kgrid.y_vec*1e3, p0(disc_x_pos, :), 'k-',...
    kgrid.y_vec*1e3, p0_recon(disc_x_pos, :), 'r--',...
    kgrid.y_vec*1e3, p0_recon_directional(disc_x_pos, :), 'b:');
xlabel('y-position [mm]');
ylabel('Pressure');
legend('True', 'Omnidirectional','Directional');
axis tight;
set(gca, 'YLim', [0 5.1]);


function nc2010_plot_compexperiment(flatW, datatype, convergence)

n = 200;
m = 50;
d = 10;

model = 'vbpca';
if flatW
  stringW = 'flatW';
else
  stringW = 'hierW';
end

% SELECT THE SEED
seed = 4132
datasets = 10
% Initialise variables
norottime = zeros(m,datasets);
norotloglike = zeros(m,datasets);
rottime = zeros(m,datasets);
rotloglike = zeros(m,datasets);
for ncomps = 1:m
  for ind = 1:datasets
    rotstring = 'rotate=0';
    norotfilename = sprintf(['/home/jluttine/matlab/neurocomputing2010/' ...
                        'nc2010_%s_compexperiment_%s_subspace=%s_n=%d_m=' ...
                        '%d_d=%d_ncomps=%d_%s_seed=%d_datasetindex=%d.mat'], ...
                            model,stringW,datatype,n,m,d, ncomps, rotstring, ...
                            seed, ind);

    rotstring = 'rotate=1';
    rotfilename = sprintf(['/home/jluttine/matlab/neurocomputing2010/' ...
                        'nc2010_%s_compexperiment_%s_subspace=%s_n=%d_m=' ...
                        '%d_d=%d_ncomps=%d_%s_seed=%d_datasetindex=%d.mat'], ...
                            model,stringW,datatype,n,m,d, ncomps, rotstring, ...
                            seed, ind);
    norot = load(norotfilename, 'duration', 'cost', 'rmse', 'rmse_test');
    rot = load(rotfilename, 'duration', 'cost', 'rmse', 'rmse_test');
    %plot_results(norot, rot,ncomps);

    % Find the point of convergence
    switch 2
     case 1 % by relative change in loglikelihood
      len = length(norot.cost);
      dcost = diff(norot.cost);
      dstep = abs(dcost ./ norot.cost(1:(len-1)));
      norotind = find(dstep < convergence, 1, 'first');
      len = length(rot.cost);
      dcost = diff(rot.cost);
      dstep = abs(dcost ./ rot.cost(1:(len-1)));
      rotind = find(dstep < convergence, 1, 'first');
     case 2 % being inside a threshold compared to converged loglikelihood
      convind = find(~isnan(norot.cost), 1, 'last');
      dif = abs((norot.cost - norot.cost(convind))/norot.cost(convind));
      norotind = find(dif < convergence, 1, 'first');
      convind = find(~isnan(rot.cost), 1, 'last');
      dif = abs((rot.cost - rot.cost(convind))/rot.cost(convind));
      rotind = find(dif < convergence, 1, 'first');
    end

    %  norotind = find(~isnan(norot.cost), 1, 'last');
    %  rotind = find(~isnan(rot.cost), 1, 'last');
    norottime(ncomps,ind) = norot.duration(norotind);
    norotloglike(ncomps,ind) = norot.cost(norotind);
    rottime(ncomps,ind) = rot.duration(rotind);
    rotloglike(ncomps,ind) = rot.cost(rotind);
  end
end

figure
norotmedian = prctile(norottime,50,2);
norot90 = prctile(norottime,100,2);
norot10 = prctile(norottime,0,2);
%norotmean = mean(norottime,2);
%rotmean = mean(rottime,2);
rotmedian = prctile(rottime,50,2);
rot90 = prctile(rottime,100,2);
rot10 = prctile(rottime,0,2);
semilogy(1:ncomps, norotmedian(:), 'r-');
hold on
x = [1:ncomps, ncomps:-1:1]';
y = [rot10(:); rot90(end:-1:1)];
c = [0.75 0.75 0.75];
fill(x,y,c,'EdgeColor',c);
%patch(x,y, [0.6 0.6 0.6]);
% $$$ semilogy(1:ncomps, rot90(:), 'k:', 'linewidth', 1);
% $$$ semilogy(1:ncomps, rot10(:), 'k:', 'linewidth', 1);
semilogy(1:ncomps, norotmedian(:), 'r-');
semilogy(1:ncomps, norot90(:), 'r-');
semilogy(1:ncomps, norot10(:), 'r-');
semilogy(1:ncomps, rotmedian(:), 'k:', 'linewidth', 2);
%semilogy(1:ncomps, rot90(:), 'k:', 'linewidth', 1);
%semilogy(1:ncomps, rot10(:), 'k:', 'linewidth', 1);
%[norotloglike(:) - rotloglike(:)];
xlabel('number of components, D')
ylabel('time (seconds)')
xlim([1 m]);

return

% $$$
% $$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% $$$ function plot_results(norot, rot,ncomps)
% $$$
% $$$ % $$$ norot.cost(norot.cost==-inf) = -1e10;
% $$$ % $$$ rot.cost(rot.cost==-inf) = -1e10;
% $$$ %suffix = sprintf(' (n=%d m=%d d=%d ncomps=%d)',n,m,d,ncomps);
% $$$
% $$$ figure
% $$$ subplot(1,3,1)
% $$$ semilogx([norot.duration(:), rot.duration(:)], -[norot.cost(:), rot.cost(:)])
% $$$ %title(['Negative loglikelihood', suffix]);
% $$$ %filename = sprintf('fig_cost_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);
% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');
% $$$ % $$$ pos = get(gcf, 'position');
% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);
% $$$ % $$$ pos = get(gcf, 'paperposition');
% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])
% $$$
% $$$ %figure
% $$$ subplot(1,3,2)
% $$$ semilogx([norot.duration(:), rot.duration(:)], [norot.rmse(:), rot.rmse(:)])
% $$$ % $$$ %title(['Training set RMSE', suffix]);
% $$$ % $$$ %filename = sprintf('fig_rmse_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);
% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');
% $$$ % $$$ pos = get(gcf, 'position');
% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);
% $$$ % $$$ pos = get(gcf, 'paperposition');
% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])
% $$$
% $$$
% $$$ %figure
% $$$ subplot(1,3,3)
% $$$ semilogx([norot.duration(:), rot.duration(:)], [norot.rmse_test(:), rot.rmse_test(:)])
% $$$ % $$$ %title(['Test set RMSE', suffix]);
% $$$ % $$$ %filename = sprintf('fig_rmsetest_n=%d_m=%d_d=%d_ncomps=%d', n,m,d,ncomps);
% $$$ % $$$ set(gcf, 'units', 'centimeters', 'paperunits', 'centimeters');
% $$$ % $$$ pos = get(gcf, 'position');
% $$$ % $$$ set(gcf, 'position', [pos(1:2), 8,8]);
% $$$ % $$$ pos = get(gcf, 'paperposition');
% $$$ % $$$ set(gcf, 'paperposition', [pos(1:2),8,8])
% $$$
% $$$