% Visualize all the inception_4c filters in bvlc_googlenet.
% Because of the size, I splitted the visualization map into 32*16 grids,
% with each grid contains visualization of 4 filters.
% This code is messay, I will refactor it in the future.
% Based on paper:
% Feng Wang, Haijun Liu, Jian Cheng,
% Visualizing Deep Neural Network by Alternately Image Blurring and Deblurring
caffe.reset_all();
caffe.set_mode_gpu();
gpu_id = 0;  % we will use the first gpu in this demo
caffe.set_device(gpu_id);
original_prototxt = 'D:\deepLearning\caffe-windows\models\bvlc_googlenet\googlenet.prototxt';
net_weights = 'D:\deepLearning\caffe-windows\models\bvlc_googlenet\thinned.caffemodel';
layer_name = 'inception_4c/output';
pattern_index=400;
channels = 512;
initial_size = [400 400];
[field_size, field_stride] = getReceptiveField(original_prototxt, net_weights, layer_name, pattern_index, initial_size);
field_size = ceil(field_size ./ field_stride) .* field_stride;
border = field_stride(1);
map_border = border ./ field_stride;
if max(field_size) > 224
%     error('field_size:(%d,%d),field_stride:(%d,%d), please increase the initial size.',field_size(1),field_size(2),field_stride(1),field_stride(2));
    field_size = [224 224];
    field_size = ceil(field_size ./ field_stride) .* field_stride;
    map_stride = ceil((field_size + border) ./ field_stride);
else
    map_stride = ceil((field_size + border) ./ field_stride);
end;

vert_num = 32;
hori_num = 16;
total_map = reshape(1:vert_num*hori_num,hori_num,vert_num)';
vert_split = vert_num/16;
hori_split = hori_num/8;
for vert_ind = 1:16
for hori_ind = 1:8
%     disp([layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png']);
%     if exist([layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png'],'file')
%         continue;
%     end;
% vert_ind = 2;
% hori_ind = 2;
caffe.reset_all();
current_map = total_map((vert_ind-1)*vert_split+1:vert_ind*vert_split,(hori_ind-1)*hori_split+1:hori_ind*hori_split)';

height = vert_split * (field_size(1)+border(1)) + border(1);
width = hori_split * (field_size(2)+border(1)) + border(1);

vgg_mean =  [103.939, 116.779, 123.68];
mean_image = permute(repmat(vgg_mean',[1,width,height]),[2,3,1]);
input_data = randn(width, height, 3, 1, 'single')*50;

for need_negative=1:1
original_net_model = fileread(original_prototxt);
original_net_model = strrep(original_net_model,'negative_slope:0#4c','negative_slope:1#4c');

visualize_prototxt = strrep(original_prototxt,'.prototxt','_visualize.prototxt');

fid = fopen(visualize_prototxt,'w');
proto_txt{1} = 'name: "Visualize"';
proto_txt{2} = 'input: "data"';
proto_txt{3} = 'input_dim: 1';
proto_txt{4} = 'input_dim: 3';
proto_txt{5} = ['input_dim: ' num2str(height)];
proto_txt{6} = ['input_dim: ' num2str(width)];
for i=1:6
    fprintf(fid,'%s\r\n',proto_txt{i});
end;

fprintf(fid,'%s\r\n',original_net_model);
fclose(fid);

if need_negative == 0
    input_data = randn(width, height, 3, 1, 'single')*50;
end;
all_grad = zeros(width, height, 3, 1, 'single');

visualize_net = caffe.Net(visualize_prototxt,net_weights,'test');
visualize_net.blobs(visualize_net.inputs{1}).set_data(input_data);
visualize_net.forward_to(layer_name);
target_blob = visualize_net.blob_vec(visualize_net.name2blob_index(layer_name));
output_data = target_blob.get_data();
backward_mask = zeros(size(output_data,1), size(output_data,2),'uint16');
backward_label = zeros(size(output_data,1), size(output_data,2),'uint16');
backward_data = zeros(size(output_data,1), size(output_data,2),channels, 'uint16');
label_mat = repmat(1:channels,size(output_data,1) * size(output_data,2),1)';
if map_stride(1) > 0
    backward_mask(ceil(map_stride(1)/2+map_border(1)):map_stride(1):end, ceil(map_stride(2)/2+map_border(2)):map_stride(2):end) = 1;
    backward_label(backward_mask==1) = current_map(:);
    for i=1:channels
        backward_data(:,:,i) = (backward_label == i);
    end;
else
    backward_mask(floor(size(backward_mask,1)/2),floor(size(backward_mask,2)/2)) = 1;
end;
item_num = sum(backward_mask(:));
target_blob = visualize_net.blob_vec(visualize_net.name2blob_index(layer_name));
data_blob = visualize_net.blob_vec(visualize_net.name2blob_index('data'));
for i=1:channels
    if i>384 && i<=448
    backward_data(:,:,i) =  backward_data(:,:,i) * 2;
    end;
end;

weight_decay = 0;
use_color_prior = false;
num_cluster=6;
color_prior = 0.5;
long_size = 512;
if need_negative==0
    tv_norm = 0;
    use_image_blur = false;
    use_image_deblur = false;
else
    tv_norm = 0;
    use_image_blur = true;
    use_image_deblur = true;
end;

if need_negative==0
    lr = 10;
else
    lr=200;
end;
max_lr = 50;
momentum = 0.8;
momentum2 = 0.99;
lastgrad = zeros(size(mean_image));
lastgrad2 = zeros(size(mean_image));
last_cost = -9999999999999;
blurred = false;
numLast = 0;

for iter = 1:1000
    bak_data = input_data;
    bak_grad = lastgrad;
    visualize_net.blobs(visualize_net.inputs{1}).set_data(input_data);
    visualize_net.forward_to(layer_name);
    output_data = target_blob.get_data();
    output_data(backward_data==0) = -999;
    output_map = max(output_data,[],3);
    min_cost = min(output_map(backward_mask==1));
    if min_cost>300 && need_negative==0
        disp(min_cost);
        break;
    end;
    cost = sum(output_map(backward_mask==1)) / item_num;
    if need_negative == 0
        for i=1:channels
            if output_map(backward_label == i) > 300
                backward_data(:,:,i) = 0;
                backward_mask(backward_label == i) = 0;
            end;
        end;
        fprintf('iter=%d,lr=%f,this_cost=%f,last_cost=%f,min_cost=%f,min_num=%d\n',iter,lr,cost, last_cost,min_cost,sum(sum(backward_mask==1)));
    else
        fprintf('iter=%d,lr=%f,this_cost=%f,last_cost=%f,image_norm=%f,min_cost=%f\n',iter,lr,cost, last_cost,norm(input_data(:)),min_cost);
    end;
%     output_data(:) = 0;
%     output_data(:,:,pattern_index) = backward_mask;
    target_blob.set_diff(backward_data);
    visualize_net.backward_from(layer_name);
    grad = data_blob.get_diff();
    all_grad = all_grad + grad;
    if iter==20
        input_data(all_grad==0) = 0;
    end;

    if tv_norm > 0
        I = input_data(:,:,:,1);
        Gx = (I(2:end-1,:,:) - I(1:end-2,:,:)) - (I(3:end,:,:) - I(2:end-1,:,:));
        Gx = [(I(1,:,:) - I(2,:,:)); Gx; (I(end,:,:) - I(end-1,:,:))];
        Gy = (I(:,2:end-1,:) - I(:,1:end-2,:)) - (I(:,3:end,:) - I(:,2:end-1,:));
        Gy = [(I(:,1,:) - I(:,2,:)) Gy (I(:,end,:) - I(:,end-1,:))];
        grad = grad - tv_norm * (Gx+Gy);
    end;

    if weight_decay > 0
        grad = grad - weight_decay * I;
    end;

    if use_color_prior
        gmm_prior = gaussian_net.forward({input_data});
        sum_gp = zeros(size(mean_image,1),size(mean_image,2));
        sum_prob_gradient = zeros(size(mean_image));
        for i=1:num_cluster
            gp = bsxfun(@minus,input_data(:,:,:,1),reshape(colorObj.mu(i,:),[1 1 3])) .* gmm_prior{1}(:,:,(i-1)*3+1:i*3);
            gp = sum(gp,3);
            gp = colorObj.PComponents(i) * exp(-gp);
            sum_prob_gradient = sum_prob_gradient + bsxfun(@times,gp,gmm_prior{1}(:,:,(i-1)*3+1:i*3));
            sum_gp = sum_gp + gp;
        end;
        sum_prob_gradient = bsxfun(@rdivide,sum_prob_gradient,sum_gp);
        sum_prob_gradient(isnan(sum_prob_gradient)) = 0;
        input_data(:,:,:,1) = input_data(:,:,:,1) - lr * color_prior * sum_prob_gradient;
    end;
    if need_negative==1
        %%%%%%%%%%%%%%%%%%%%%%%%gd linear search
        lastgrad = (1 - momentum) * lr * grad   + momentum * lastgrad;%/ norm(res(:))
        input_data(:,:,:,1) = input_data(:,:,:,1) + lastgrad;
    else
        %%%%%%%%%%%%%%%%%%%%%%%%adam
        lastgrad = (1 - momentum) * grad   + momentum * lastgrad;%/ norm(res(:))
        lastgrad2 = (1 - momentum2) * grad.^2 + momentum2 * lastgrad2;%/ norm(res(:))
        lg_correct = lastgrad ./ (1 - momentum^iter);
        lg2_correct = lastgrad2 ./ (1 - momentum2^iter);
        input_data(:,:,:,1) = input_data(:,:,:,1) + lr * lg_correct ./ (sqrt(lg2_correct) + 1e-8);
    end;
%     input_data(:,:,:,1) = input_data(:,:,:,1) / norm(input_data(:));

    k = mod(iter,10);
    if k==1
        H = fspecial('gaussian',[7 7],1.2);
        if use_image_blur
            input_data(:,:,:,1) = imfilter(input_data(:,:,:,1),H,'same');
            blurred = true;
        end
    end;
    if k==6
        H = fspecial('gaussian',[7 7],1);
        if use_image_deblur
            input_data(:,:,:,1) = deconvlucy(input_data(:,:,:,1), H);
            blurred = false;
        end;
    end;

    if (need_negative==1 && cost>last_cost)
        last_cost = cost;
        numLast = 0;
    else
        numLast = numLast + 1;
    end;
    if (need_negative==0 && min_cost>last_cost)
        last_cost = min_cost;
        numLast = 0;
    else
        numLast = numLast + 1;
    end;
    if numLast>100
        break;
    end;
    if lr<1e-5
        break;
    end;

    %%%%%%%%%%%%%%%%%%%%%%gd

    if mod(iter,100)==0
        output = mean_image + input_data(:,:,:,1);
        output = output(:, :, [3, 2, 1]);
        output = permute(output, [2 1 3]);
        figure(3);
        imshow(uint8(output));
%         title('generated image');
        I = output;
    end;
end;
end;
% imwrite(uint8(output),[layer_name '_' num2str(vert_ind) num2str(hori_ind) '.png']);
end;
end;


function planC = createExpandedStructure2D(structNum, margin, planC)
% function createExpandedStructure2D(structNum, margin, planC)
%
% APA, 09/09/2014
% AI, 09/19/17 Updated to allow margin<0

if ~exist('planC','var')
    global planC
end

global stateS

indexS = planC{end};

scanNum = getStructureAssociatedScan(structNum,planC);

newStructNum = length(planC{indexS.structures}) + 1;

%newStructS = newCERRStructure(scanNum, planC, newStructNum);

rasterSegs = getRasterSegments(structNum, planC);

% Get Rastersegments +/- margin, thus creating an halo
if margin>0
halo = structMargin(rasterSegs, margin, scanNum, planC);
rasterSegsExpanded = structUnion(halo, rasterSegs, scanNum, planC); % Expand rastersegments by margin
else
halo = structMargin(rasterSegs, -margin, scanNum, planC);
rasterSegsExpanded = structDiff(rasterSegs, halo, scanNum, planC); % Shrink rastersegments by margin
end

% Get Contours from rasterSegs
contourS = rasterToPoly(rasterSegsExpanded, scanNum, planC);

% Generate Structure Name
strName = planC{indexS.structures}(structNum).structureName;
strName = [strName,' + 2D_',num2str(margin)];

% Create New structure
%Make an empty structure, assign name/contour.
newstr = newCERRStructure(scanNum, planC, newStructNum);
newstr.contour = contourS;
newstr.structureName = strName;
newstr.associatedScan = scanNum;
newstr.assocScanUID = planC{indexS.scan}(scanNum).scanUID;
numStructs = length(planC{indexS.structures});

%Append new structure to planC.
if ~isempty(planC{indexS.structures})
    planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newstr, numStructs+1, []);
else
    planC{indexS.structures} = newstr;
end

%Update uniformized data.
planC = updateStructureMatrices(planC, numStructs+1);

% Refresh View
if ~isempty(stateS) && isfield(stateS,'handle') && isfield(stateS.handle,'CERRSliceViewer') && isnumeric(stateS.handle.CERRSliceViewer)
    stateS.structsChanged = 1;
    CERRRefresh
end


function out = convert_caffe2img( out )
    assert(length(size(out)) <= 4, 'Only support at most 4-D data for convert.');
    out = single(permute(out(:,:,end:-1:1,:), [2 1 3 4]));
end


function gasConst = getIdealGasConstant()
    gasConst = 8.31447; %m^3*Pa/(K*mol)
end


function a = eq( x, y )

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

evalin( 'caller', 'cvx_verify' );
b = cvx_pushcnstr( x, y, '==' );
if nargout, a = b; end

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


function y = choosvd(n, d)

if n <= 100
    if d / n <= 0.02
        y = 1;
    else
        y = 0;
    end
elseif n <= 200
    if d / n <= 0.06
        y = 1;
    else
        y = 0;
    end
elseif n <= 300
    if d / n <= 0.26
        y = 1;
    else
        y = 0;
    end
elseif n <= 400
    if d / n <= 0.28
        y = 1;
    else
        y = 0;
    end
elseif n <= 500
    if d / n <= 0.34
        y = 1;
    else
        y = 0;
    end
else
    if d / n <= 0.38
        y = 1;
    else
        y = 0;
    end
end


function coeffVar = compute_coeff_var(this, varargin)
% computes standard deviation image (coeff_var) over 4th dimension of MrImage
% NOTE: short-cut for compute_stat_image('coeff_var')
%
%   Y = MrImage()
%   coeffVar = Y.compute_coeff_var('PropertyName', PropertyValue)
%
% This is a method of class MrImage.
%
% IN
%   'PropertyName'
%               'selectedVolumes'       [1,nVols] vector of selected
%                                       volumes for statistical calculation
% OUT
%   coeffVar         MrImage holding voxel-wise coefficient of variation
%                     image (coeff_var), i.e. 1./snr
%                     (with thresholding to avoid Inf-values)
%
% EXAMPLE
%   Y = MrImage()
%   coeffVar = Y.compute_coeff_var('selectedVolumes', [6:100])
%
%   See also MrImage compute_stat_image

% Author:   Saskia Klein & Lars Kasper
% Created:  2014-07-06
% Copyright (C) 2014 Institute for Biomedical Engineering
%                    University of Zurich and ETH Zurich
%
% This file is part of the TAPAS UniQC Toolbox, which is released
% under the terms of the GNU General Public Licence (GPL), version 3.
% You can redistribute it and/or modify it under the terms of the GPL
% (either version 3 or, at your option, any later version).
% For further details, see the file COPYING or
%  <http://www.gnu.org/licenses/>.

coeffVar = this.compute_stat_image('coeff_var', varargin{:});


function [R, t] = read4PCSResults(filename)

 M = dlmread(filename);
 R = M(1:3, 1:3);
 t = M(1:3, 4);

end


function rtk = detslip_gf_L1L5(rtk,obsr,obsb,nav)

sat=obsr.sat;

g1=gfobs_L1L5(obsr,obsb,nav.lam(sat,:));
if rtk.opt.nf<=2||g1==0,return;end

g0=rtk.sat(sat).gf2;
rtk.sat(sat).gf2=g1;

if g0~=0&&abs(g1-g0)>rtk.opt.csthres(1)
    rtk.sat(sat).slip(1)=bitor(rtk.sat(sat).slip(1),1);
    rtk.sat(sat).slip(3)=bitor(rtk.sat(sat).slip(3),1);
end

return


% eegplotgold() - display EEG data in a clinical format
%
% Usage:
% >> eegplotgold('dataname', samplerate, 'chanfile', 'title', yscaling, range)
%
% Inputs:
%   'dataname' - quoted name of a desktop global variable (see Ex. below)
%   samplerate - EEG sampling rate in Hz (0 -> default 256 Hz)
%   'chanfile' - file of channel info in topoplot() style
%                                        (0 -> channel numbers)
%   'title'    - plot title string       (0 -> 'eegplotgold()')
%   yscaling   - initial y scaling factor (0 - default is 300)
%   range      - how many seconds to display in window (0 -> 10)
%
% Note: this version of eegplotgold() reguires that your data matrix
%       be defined as a global variable before running this routine.
%
% Example:  >> global dataname
%           >> eegplotgold('dataname')
%
% Author: Colin Humphries, CNL, Salk Institute, La Jolla, 3/97
%
% See also: eegplot(), eegplotold(), eegplotsold()

% Copyright (C) Colin Humphries, CNL, Salk Institute 3/97 from eegplotold()
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

% 4-4-97 shortened name to eegplotgold() -sm
% 5-20-97 added read of icadefs.m for MAXEEGPLOTCHANS -sm
% 8-10-97 Clarified chanfile type -sm
% 01-25-02 reformated help & license, added links -ad

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function y = eegplotold(dataname, samplerate, channamefile, titleval, yscaling, range)

eval (['global ',dataname])

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define defaults
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% set initial spacing

eval(['DEFAULT_SPACING = max(max(',dataname,''')-min(',dataname,'''));'])

%  spacing_var/20 = microvolts/millimeter with 21 channels
%  for n channels: 21/n * spacing_var/20 = microvolts/mm
%  for clinical data.

DEFAULT_SAMPLERATE = 256;	% default rate in Hz.
DEFAULT_PLOTTIME = 10;		% default 10 second window
DEFAULT_TITLE = 'eegplotgold()';
errorcode=0;			    % initialize error indicator

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Allow for different numbers of arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 6
   PLOT_TIME = DEFAULT_PLOTTIME;
else
   PLOT_TIME = range;
end
if nargin < 5
   spacing_var = DEFAULT_SPACING;
else
   spacing_var = yscaling;
end
if spacing_var == 0
   spacing_var = DEFAULT_SPACING;
end

if nargin < 4
   titleval = DEFAULT_TITLE;
end
if titleval == 0
   titleval = DEFAULT_TITLE;
end
if nargin < 3
	channamefile = 0;
end
if nargin < 2
   samplerate = DEFAULT_SAMPLERATE;
end
if samplerate == 0,
	samplerate = DEFAULT_SAMPLERATE;
end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define internal variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

SAMPLE_RATE = samplerate;
time = 0;
eval(['[chans,frames] = size(',dataname,');'])		%size of data matrix

maxtime = frames / samplerate;       %size of matrix in seconds

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read the channel names
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

  if channamefile ~=0,		% read file of channel names
	chid = fopen(channamefile,'r');
	if chid <3,
		fprintf('plotdata: cannot open file %s.\n',channamefile);
		errorcode=2;
		channamefile = 0;
	else
		fprintf('Chan info file %s opened\n',channamefile);
	end;

    icadefs;   % read MAXEEGPLOTCHANS from icadefs.m
	if errorcode==0,
		channames = fscanf(chid,'%s',[6 MAXEEGPLOTCHANS]);
		channames = channames';
    	[r c] = size(channames);
		for i=1:r
			for j=1:c
				if channames(i,j)=='.',
					channames(i,j)=' ';
				end;
			end;
		end;
		% fprintf('%d channel names read from file.\n',r);
		if (r>chans)
			fprintf('Using first %d names.\n',chans);
			channames = channames(1:chans,:);
		end;
		if (r<chans)
			fprintf('Only %d channel names read.\n',r);
		end;
	end;
  end
  if channamefile ==0, % plot channel numbers
	channames = [];
	for c=1:chans
		if c<10,
			numeric = ['   ' int2str(c)];	% four-character fields
		else
			numeric = ['  '  int2str(c)];
		end
		channames = [channames;numeric];
	end;
  end; % setting channames

channames = str2mat(channames, ' ');	% add padding element to Y labels

Xlab = num2str(time);
for j = 1:1:PLOT_TIME
   Q = num2str(time+j);
   Xlab = str2mat(Xlab, Q);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set Graph Characteristics
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
   figure;				% plot a new figure
   fighandle = gcf;
   orient landscape		% choose landscape printer mode
   hold on;
   set(gcf,'NumberTitle','off')
   set(gcf,'Name',['EEGPLOTOLD #',num2str(gcf)])
   set (gca, 'xgrid', 'on')				%Xaxis gridlines only
   set (gca, 'GridLineStyle','-')			%Solid grid lines
   set (gca, 'XTickLabels', Xlab)			%Use Xlab for tick labels
   set (gca, 'Box', 'on')
   set (gca, 'XTick', time*samplerate:1.0*samplerate:PLOT_TIME*samplerate)
   set (gca, 'Ytick', 0:spacing_var:chans*spacing_var)  % ytickspacing on channels
   set (gca, 'TickLength', [0.001 0.001])
   title(titleval)					% title is titleval
   axis([0 PLOT_TIME*samplerate 0 (chans+1)*spacing_var]);       % set axis values
   set (gca, 'YTickLabels', flipud(channames))   	% write channel names

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot the selected EEG data epoch
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for i = 1:chans
   if (maxtime-time>PLOT_TIME)
      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(time+PLOT_TIME*samplerate));'])
   else
      eval(['F = ',dataname,'(chans-i+1,(time*samplerate)+1:(maxtime*samplerate));'])
   end
   F = F - mean(F) + i*spacing_var;
   plot (F,'clipping','off')
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot Scaling I
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

line([(PLOT_TIME+.3)*samplerate,(PLOT_TIME+.3)*samplerate],[1.5*spacing_var 2.5*spacing_var],'clipping','off','color','w')
line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[2.5*spacing_var,2.5*spacing_var],'clipping','off','color','w')
line([(PLOT_TIME+.3)*samplerate-10,(PLOT_TIME+.3)*samplerate+10],[1.5*spacing_var,1.5*spacing_var],'clipping','off','color','w')
text((PLOT_TIME+.5)*samplerate,2*spacing_var,num2str(round(spacing_var)),'clipping','off')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% User Control Routines
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

   slider_position = [.125 .030 .3 .024];   % position of user-controlled slider
   edit_position = [.65 .025 .1 .05];       % position of edit box
   slider_position2 = [.8 .03 .1 .024];
   b1_position = [.175 .022 .09 .047];
   b2_position = [.29 .022 .09 .047];
   b3_position = [.125 .022 .045 .047];
   b4_position = [.385 .022 .045 .047];

   Max_Space = 1;
   Min_Space = DEFAULT_SPACING*2;
%   User_Data_Mat = [data;zeros(1,length(data))];

axhandle = gca;
   User_Data_Mat(1) = samplerate;
   User_Data_Mat(2) = PLOT_TIME;
   User_Data_Mat(3) = spacing_var;
   User_Data_Mat(4) = time;
   User_Data_Mat(5) = maxtime;
   User_Data_Mat(6) = axhandle;
   User_Data_Mat(7) = 1;  % color
   User_Data_Mat(8) = frames;
   User_Data_Mat(9) = chans;
   User_Data_Mat(12) = 1;

   tstring1 = 'data1973 = get(gcf,''UserData'');';
   tstring2 = 'set(gcf,''UserData'',data1973);';
   tstring3 = 'eegdrawgv(gcf);';

   TIMESTRING = [tstring1,'if (data1973(4)-data1973(2))<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - data1973(2);','end;',tstring2,tstring3,'clear data1973'];

   hb = uicontrol('Style','PushButton','Units','Normalized','position',b1_position,'String','PREV','Callback',TIMESTRING);

   TIMESTRING = [tstring1,'if (data1973(4)+data1973(2))>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + data1973(2);','end;',tstring2,tstring3,'clear data1973'];

   hf = uicontrol('Style','PushButton','Units','Normalized','position',b2_position,'String','NEXT','Callback',TIMESTRING);

   TIMESTRING = [tstring1,'if (data1973(4)-1)<0;','data1973(4) = 0;','else;','data1973(4) = data1973(4) - 1;','end;',tstring2,tstring3,'clear data1973'];

   hbos = uicontrol('Style','PushButton','Units','Normalized','position',b3_position,'String','<<','Callback',TIMESTRING);

   TIMESTRING = [tstring1,'if (data1973(4)+1)>=data1973(5);','data1973(4)=data1973(4);','else;','data1973(4) = data1973(4) + 1;','end;',tstring2,tstring3,'clear data1973'];

   hfos = uicontrol('Style','PushButton','Units','Normalized','position',b4_position,'String','>>','Callback',TIMESTRING);

   TIMESTRING = [tstring1,'time1973 = get(gco,''string'');','time1973 = str2num(time1973);','data1973(4) = time1973;',tstring2,tstring3,'clear time1973 data1973'];

   w=uicontrol('style','edit','units','normalized','HorizontalAlignment','left','position',edit_position,'UserData',axhandle,'callback',TIMESTRING);

TIMESTRING = [tstring1,'data1973(3) = get(gco,''value'');',tstring2,tstring3,'clear time1973 data1973'];

u=uicontrol('style','slider','units','normalized','position',slider_position2,'Max',Max_Space,'Min',Min_Space,'value',spacing_var,'UserData',axhandle,'callback',TIMESTRING);

%%%%%%%%%%%%%%%%%%%%%%%%%
%Set up ui menus
%%%%%%%%%%%%%%%%%%%%%%%%%

%Window menu:

TIMESTRING = ['fighand1973 = gcf;','delete(fighand1973);','clear fighand1973;'];

fm1 = uimenu('Label','Window');
fm2 = uimenu(fm1,'Label','Close ','UserData',fighandle,'Callback',TIMESTRING);

%Display menu:

TIMESTRING = [tstring1,'out1973 = gettext(''Input new windowlength(sec).'');','if isempty(out1973);','out1973 = 0;','else;','data1973(2) = str2num(out1973);',tstring2,tstring3,'end;','clear data1973 out1973'];

dm1 = uimenu('Label','Display');
dm2 = uimenu(dm1,'Label',' Window Length','Interruptible','yes','Callback',TIMESTRING);
dm3 = uimenu(dm1,'Label',' Color');

TIMESTRING = [tstring1,'data1973(7) = 1;',tstring2,tstring3,'clear data1973;'];

dm4 = uimenu(dm3,'Label','Yellow ','UserData',axhandle,'Interruptible','yes','Callback',TIMESTRING);

TIMESTRING = [tstring1,'data1973(7) = 2;',tstring2,tstring3,'clear data1973;'];

dm5 = uimenu(dm3,'Label','White ','UserData',axhandle,'Interruptible','yes','Callback',TIMESTRING);

TIMESTRING = ['label1973 = gettext(''Enter new title.'');','if isempty(label1973);','label1973 = 0;','else;','title(label1973);','end;','clear label1973;'];

dm6 = uimenu(dm1,'Label','Title ','Interruptible','yes','Callback',TIMESTRING);

TIMESTRING = [tstring1,'Check1973 = get(data1973(10),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(10),''Checked'',''off'');','set(data1973(6),''XGrid'',''off'');','else;','set(data1973(10),''Checked'',''on'');','set(data1973(6),''XGrid'',''on'');','end;','clear data1973 Check1973;'];

dm7 = uimenu(dm1,'Label','Grid','Checked','on','Callback',TIMESTRING);

User_Data_Mat(10) = dm7;

TIMESTRING = [tstring1,'Check1973 = get(data1973(11),''checked'');','if (Check1973(1:2) == ''on'');','set(data1973(11),''Checked'',''off'');','data1973(12)= 0;','else;','set(data1973(11),''Checked'',''on'');','data1973(12) = 1;','end;',tstring2,tstring3,'clear data1973 Check1973;'];

dm8 = uimenu(dm1,'Label','Scaling I','Checked','on','Callback',TIMESTRING);

User_Data_Mat(11) = dm8;

%Settings menu:

sm1 = uimenu('Label','Settings');

TIMESTRING = [tstring1,'Srate1973 = gettext(''Enter new samplerate'');','if isempty(Srate1973);','Srate1973 = 0;','else;','data1973(1) = str2num(Srate1973);','data1973(5) = data1973(8)/data1973(1);','data1973(4) = 0;',tstring2,tstring3,'end;','clear Srate1973 data1973'];

sm2 = uimenu(sm1,'Label','Samplerate','Interruptible','yes','Callback',TIMESTRING);

%Electrodes menu:

em1 = uimenu('Label','Electrodes');

TIMESTRING = [tstring1,'ChanNamefile1973 = gettext(''Enter Electrode file to load.'');','if isempty(ChanNamefile1973);','ChanNamefile1973=0;','else;','ChanNames1973 = loadelec(ChanNamefile1973);','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNamefile1973 ChanNames1973'];

em2 = uimenu(em1,'Label','Load Electrode File ','Interruptible','yes','Callback',TIMESTRING);

TIMESTRING = [tstring1,'ChanNames1973 = makeelec(data1973(9));','if isempty(ChanNames1973);','ChanNames1973=0;','else;','set(data1973(6),''YTickLabels'',flipud(ChanNames1973));','end;','clear data1973 ChanNames1973'];

em3 = uimenu(em1,'Label','Make Electrode File ','Interruptible','yes','Callback',TIMESTRING);

set(axhandle,'UserData',dataname)
set(fighandle,'UserData',User_Data_Mat)


function [output, layerOut] = FeatureTree2(visible, para, layer)
% remove target and cost function nodes if any
for i=1:length(layer)
    if strcmpi(layer{i}.name, 'target') || strcmpi(layer{i}.name, 'cross_entropy') || strcmpi(layer{i}.name, 'mse') || strcmpi(layer{i}.name, 'logistic')
        layer{i}.name = 'ignore';
    end
    if i > max(para.out_layer_idx)  % we don't compute layers that is after the last output layer
        layer{i}.name = 'ignore';
    end
end
para.NET.sentenceMinibatch = 1;
[minibatch] = MinibatchPackaging_tree4(visible, para);

output = {};
for utt_i = 1:minibatch.nBatch
    PrintProgress(utt_i, minibatch.nBatch, 100);
    batch_data = GetMinibatch2(minibatch, para, utt_i);

    % Use mode=3 to generate network output only
    if nargout>1
        [~, layerOut{utt_i}, output{utt_i}] = DNN_Cost10(layer, batch_data, para,3);
    else
        [~, ~, output{utt_i}] = DNN_Cost10(layer, batch_data, para,3);
    end
end
end


% JN Kather 2018

function [lgraph,imageInputSize,networkType] = getAndModifyNet(nnmodel,hyperparam,numOutputClasses)

% load pre-trained network model for transfer learning
switch nnmodel
    case 'vgg19'
        rawnet = vgg19;
        networkType = 'series';
    case 'vgg16'
        rawnet = vgg16;
        networkType = 'series';
    case 'alexnet'
        rawnet = alexnet;
        networkType = 'series';
    case 'inceptionv3'
        rawnet = inceptionv3;
        networkType = 'DAG';
        layersForRemoval = {'predictions', 'predictions_softmax','ClassificationLayer_predictions'};
        layersForReconnection = {'avg_pool','fc'};
    case 'googlenet'
        rawnet = googlenet;
        networkType = 'DAG';
        layersForRemoval = {'loss3-classifier','prob','output'};
        layersForReconnection = {'pool5-drop_7x7_s1','fc'};
    case 'resnet18'
        rawnet = resnet18;
        networkType = 'DAG';
        layersForRemoval = {'fc1000', 'prob','ClassificationLayer_predictions'};
        layersForReconnection = {'pool5','fc'};
    case 'resnet50'
        rawnet = resnet50;
        networkType = 'DAG';
        layersForRemoval = {'ClassificationLayer_fc1000', 'fc1000_softmax','fc1000'};
        layersForReconnection = {'avg_pool','fc'};
    case 'resnet101'
        rawnet = resnet101;
        networkType = 'DAG';
        layersForRemoval = {'fc1000', 'prob','ClassificationLayer_predictions'};
        layersForReconnection = {'pool5','fc'};
    case 'squeezenet'
        rawnet = squeezenet;
        networkType = 'DAG';
        layersForRemoval = {'pool10', 'prob','ClassificationLayer_predictions'};
        layersForReconnection = {'relu_conv10','fc'};
    case 'inceptionresnetv2'
        rawnet = inceptionresnetv2;
        networkType = 'DAG';
        layersForRemoval = {'predictions', 'predictions_softmax','ClassificationLayer_predictions'};
        layersForReconnection = {'avg_pool','fc'};
    otherwise
        error('wrong network model specified');
end

% prune and rewire network
switch networkType
    case 'series' % e.g. alexnet
        lgraph = rawnet.Layers;
        % freeze shallow layers
        freezeIndex = 1:(numel(lgraph)-hyperparam.hotLayers);
        lgraph(freezeIndex) = freezeWeights(lgraph(freezeIndex));
        % overwrite penultimate and last layer
        lgraph(end-2) = fullyConnectedLayer(numOutputClasses,'Name','fc',...
            'WeightLearnRateFactor',hyperparam.learnRateFactor,...
            'BiasLearnRateFactor',hyperparam.learnRateFactor);
        lgraph(end) = classificationLayer;
        imageInputSize = lgraph(1).InputSize(1:2);
    case 'DAG' % e.g. googlenet
        % freeze shallow layers
        lgraph = layerGraph(rawnet); % convert network to layer graph
        layers = lgraph.Layers;      % extract layers
        connections = lgraph.Connections; % exctract connections
        freezeIndex = 1:(numel(layers)-hyperparam.hotLayers);
        layers(freezeIndex) = freezeWeights(layers(freezeIndex));
        lgraph = createLgraphUsingConnections(layers,connections);
        % remove old layers
        lgraph = removeLayers(lgraph,layersForRemoval);
        % add new layers and connect
        newLayers = [
            fullyConnectedLayer(numOutputClasses,'Name','fc',...
            'WeightLearnRateFactor', hyperparam.learnRateFactor,...
            'BiasLearnRateFactor', hyperparam.learnRateFactor),...
            softmaxLayer('Name','softmax'),...
            classificationLayer('Name','classoutput')];
        lgraph = addLayers(lgraph,newLayers);
        lgraph = connectLayers(lgraph,layersForReconnection{1},layersForReconnection{2});
        imageInputSize = lgraph.Layers(1).InputSize(1:2);
    otherwise, error('undefined network type');
end
end


hydro = struct();

hydro = readNEMOH(hydro,'../Ellipsoid/');
% hydro = readWAMIT(hydro,'../../WAMIT/Ellipsoid/ellipsoid.out',[]);
% hydro = combineBEM(hydro); % Compare to WAMIT
hydro = radiationIRF(hydro,10,[],[],[],[]);
hydro = radiationIRFSS(hydro,[],[]);
hydro = excitationIRF(hydro,15,[],[],[],[]);
writeBEMIOH5(hydro)
plotBEMIO(hydro)


% SPM5 UPDATE 23/11/07
% Sets the default values for the FieldMap toolbox
%
% FORMAT pm_defaults_Trio_eFoV_dn
%_______________________________________________________________________
%
% This file is intended for use with the Siemens fieldmap sequence
% on the Trio scanner at the AMRIG/FIL and the eFoV EPI sequences with
% PE blips=+1:
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Chloe Hutton and Jesper Andersson
% $Id: pm_defaults_Trio_eFoV_dn.m 5015 2012-10-24 13:40:07Z guillaume $

global pm_def

% Defaults for creating field map. (See pm_make_fieldmap.m and
%                                   FieldMap.man for more info.)
%=======================================================================
pm_def.INPUT_DATA_FORMAT = 'PM';      % 'RI' = load two real and
                                      % imaginary image pairs
                                      % 'PM' = load one or two
                                      % phase and magnitude image
                                      % pairs.
pm_def.SHORT_ECHO_TIME = 10.0;        % Short echo time in ms for Trio
pm_def.LONG_ECHO_TIME = 12.46;        % Long echo time in ms for Trio
pm_def.MASKBRAIN = 1;                 % Do brain masking (1 or 0,
                      % 0 for EPI fieldmaps)

% Defaults for unwrapping options. (See pm_make_fieldmap.m and
%                                   FieldMap.man for more info.)
%=======================================================================
pm_def.UNWRAPPING_METHOD = 'Mark3D';  % Unwrapping options are:
                                      % 'Huttonish', 'Mark3D' or 'Mark2D'
pm_def.FWHM = 10;                     % FWHM of Gaussian filter used to
                                      % implement weighted smoothing of
                                      % unwrapped maps.
pm_def.PAD = 0;                       % Size of padding kernel if required.
pm_def.WS = 1;                        % Weighted or normal smoothing.

% Flags for brain extraction
%=======================================================================
pm_def.MFLAGS.TEMPLATE = fullfile(spm('Dir'),'toolbox','FieldMap','T1.nii');
pm_def.MFLAGS.FWHM = 5;     % In mm
pm_def.MFLAGS.NERODE = 2;   % In voxels
pm_def.MFLAGS.NDILATE = 4;  % In voxels
pm_def.MFLAGS.THRESH = 0.5;
pm_def.MFLAGS.REG = 0.02;   % A larger value helps segmentation to converge
pm_def.MFLAGS.GRAPHICS = 0; % A larger value helps segmentation to converge

% Defaults for converting field map to voxel displacement map.
%=======================================================================
pm_def.EPI_BASED_FIELDMAPS = 0;         % EPI=1, other=0.
pm_def.K_SPACE_TRAVERSAL_BLIP_DIR = +1; % +ve k-space = 1, -ve = -1.
pm_def.TOTAL_EPI_READOUT_TIME = 37.0;   % Trio eFoV EPI RO time

% Defaults for Unwarping.
%=======================================================================
pm_def.DO_JACOBIAN_MODULATION = 0;    % Do jacobian modulation to adjust
                                      % for compression or stretching
                                      % No = 0, Yes = 1


%%  Virtual Painter 1
%% discription
% Virtual Painter - this software allows you to draw a picture on the screen
% By following the red color
%
% Have the option to choose what color to paint by moving the red color to the desired color:
% Red, green, blue.
%
% To close the program, have received faint image on the screen
%
% Note: In order to achieve optimal results have run the program in the light of fluorescent lamp.
% % Operating Instructions
% To paint the color red object we vote to act as follows:
%% Play and exit:
%
% * To start the video: click on the Play button.
% * To exit from the function: Display to the camera very dark image ,
%    for example you can cover the camera with your hand,
%    Or turn off the light in the room.After doing so
%    The Camera and function should be closed automatically.
%% Notes
%  The identification of red objects in the picture depends on the lighting of the room.
%  Lighting Fluorescent light is the most appropriate lighting to this function to identify red objects.
%
%  first edited  in 8/06/2013 Saturday .
%  by Oren berkovich.

function virtualpaint()

%% creat figure and uicontrol
      figure('menubar','none')

    ply= uicontrol('style','togg','units','normalized',...
        'position',[0.1 0.1 0.1 0.1],'str','Play','callback',{@PlayvideoLive});

    uicontrol('style','text','str' ,'exit- cover the eye of the camera ',...
        'units','normalized','position',[0.2 0.1 0.5 0.05])

    %% main function
    function PlayvideoLive(~,~)

        set(ply,'enable','off');
        pause(0.5);

        try
    imaqreset
    vid = videoinput('winvideo', 1, 'YUY2_160x120');
    vid.ReturnedColorspace = 'rgb';
    set(vid,'framesperTrigger',10,'TriggerRepeat',Inf);

      color='y';
      x=[];
      y=[];
      Eraser='non';
      %
        tic

    start(vid);
        catch ex
            err=errordlg(ex.message);
            uiwait(err)
            close gcf
            return
        end

      while islogging(vid)

    tv=getdata(vid,1);

    r=tv(:,:,1,1);
    g=tv(:,:,2,1);
    b=tv(:,:,3,1);

    flushdata(vid);

    %% Find the differences of each object

rg=r-g;
gb=g-b;
rggb=rg-gb;

%% build the color filters

filter=rggb>26;
filter=uint8(filter);
F=filter.*rggb;

%% Remove objects less than the pixel size prescribing function

 bw=imfill(F,'holes');

 bw=bwareaopen(bw,50);
 %%

 %% Identify the position of the marked
 W=regionprops(bw,'Centroid');
 if isempty(W)==0
     %axis([0 160 0 120])

 x=horzcat(x,W(1).Centroid(1));
 y=horzcat(y,W(1).Centroid(2));

  elseif length(W)==2
     hold on
     line([W(1).Centroid(1) W(2).Centroid(1)],[W(1).Centroid(2) W(2).Centroid(2)],'color','r','linew',2)

 end
  %% erse mode
      if length(x)==100
          Eraser='era';
      end

      if eq(Eraser,'era')==1
           x=x(2:length(x));
           y=y(2:length(y));
           if  isempty(x)==1
               Eraser='non';
           end
      end
      %%
 hold on

 if isempty(x)==0
color=rgbcolor(x(length(x)),y(length(y)),color);
plot(x,y,'color',color,'linew',4)
 end

 %% Rebuild the RGB image, if the part has been lightened

    figure(gcf)
    hold off
    imshow(tv(:,:,:,1))

    state =mean2(r);
    if state<20&&toc>20;
       break
    end

      end
      % after you exit the loop
       stop(vid)
       imaqreset

       close gcf
       clc
       disp('good by')
    end

    end


function IM = generateQIBInfluence(IM, structROIV, sampleRateV)
%"generateQIBInfluence"
%   Uses the QIB engine to populate the beamlet fields of an IM structure.
%   StructROIV is the list of structures, sampleRateV is a vector of sample
%   rates, one for each structROIV.
%   The doses are stored in sparse format.
%   The stored index is with respect to the structure mask registered to the
%   uniformized CT scan.
%
%   This code was broken out of a function by JOD and CZ.
%
%JRA  26 Aug 2004
%LM:  14 Sept 05, JOD, fixed bug in call to mtoxyz
%     17 Dec  05, JOD, fixed bug in un-downsampled ROI
%                      definition; added comments to clarify calculation, and a small speedup change.
%     05 Jul  06, JJW, added missing inverse square law; added sigma_100
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%-----------Generate influence matrices---------------------%
%Loop over structures (i.e. goal terms)

global planC
global stateS
indexS = planC{end};

%obtain associated scanNum for structures. It is assumed that all the
%structures are associated to same scan (which is checked in IMRTP.m)
scanNum = getStructureAssociatedScan(structROIV(1));

for i = 1 : length(structROIV)

    if sampleRateV(i) ~= 1

        %Ensures that interpolative downsampling won't miss edge points:
        maskSingle3D = getSurfaceExpand(structROIV(i),0.5,1);
        if rem(log2(sampleRateV(i)),1) ~= 0
            error('Sample factor must (currently) be a power of 2.')
        end
        maskSample3D = getDown3Mask(maskSingle3D, sampleRateV(i), 1);
        %Get a mask of where to sample points
        tmp = logical(maskSample3D) & maskSingle3D;
        clear maskSample3D, maskSingle3D;

    else

        tmp = getUniformStr(structROIV(i));

    end

    scanIndV = find(tmp(:));  %Indices with respect to the uniformized scan.
    [rowV, colV, sliceV] = find3d(tmp); clear tmp;     %returns locations of mask voxels

    %[xV,yV,zV] = mtoxyz(rowV,colV,sliceV,1,planC,'uniform'); change by
    %JOD.
    [xV,yV,zV] = mtoxyz(rowV,colV,sliceV,scanNum,planC,'uniform');

    doseV = zeros(size(xV));

    numPts = length(xV);

    pM = [xV(:),yV(:),zV(:)];   %Location of dose calc points, downsampled.

    PBCounter = 1;

    QIBDataS = loadPBData;

    for j = 1 : length(IM.beams)

        disp(['Compute doses to structure number ' num2str(structROIV(i)) ' for beam ' num2str(j) '.'])

        %Get beamlet data for this beam and this structure

        sourceM = repmat([IM.beams(j).x, IM.beams(j).y, IM.beams(j).z],numPts,1);

        pRelM = pM - sourceM;    %get relative vector direction from source to dose calc points.

        RTOGPBVectorsM = IM.beams(j).RTOGPBVectorsM;

        str = int2str(size(RTOGPBVectorsM,1));

        disp(['numPBs = ' str])

        PBM = [];
        for PBNum = 1 : size(RTOGPBVectorsM,1)

            if mod(PBNum, 25) == 0 | (PBNum == size(RTOGPBVectorsM,1))
                disp(['Computed ' int2str(PBNum) ' out of ' str]); pause(0.003);
                try
                    IMRTPGui('status', j, length(IM.beams), structROIV(i), PBNum, size(RTOGPBVectorsM,1));
                end
            end

            PBV = RTOGPBVectorsM(PBNum,:);

            distSamplePts = IM.beams(j).CTTraceS(PBNum).distSamplePts;
            cumDensity    = IM.beams(j).CTTraceS(PBNum).cumDensityRay;

            distV = pRelM * PBV';    %Each row is the dot product of (the un-normalized) source-to-calc point
                                     %direction and the PB unit vector.
                                     %Hence, this is the distance along the PB ray line for each dose calc point.

            qM = sourceM + distV * PBV;  %The last term gives the vector i, j, and k components of
                                         %distance to the depth of closest approach.
                                         %Each row of sourceM is the i,j,k position of the source.
                                         %So vector sum locates the positions of closest approach
                                         %to the dose calc points.

            rM  = pM - qM;    %Each row of pM is the x, y, z location of a dose calc point.
                              %rM is then the vector pointing from the dose calc point to the point
                              %at which the PB vector makes closest approach.

            %Trap points which are too far away to need dose calcs
            %Uses sepsq if possible, much faster.
            try
                rDistVSquared = sepsq([0 0 0]', rM');  %mex file speedup
                goV = rDistVSquared < (IM.params.cutoffDistance^2);
            catch
                rDistV = (rM(:,1).^2 + rM(:,2).^2 + rM(:,3).^2);    %if mex not there
                goV = rDistV < IM.params.cutoffDistance^2;         %Mod by JOD to speedup, Dec 05.
            end

            rGoM = rM(goV,:);
            %       rGoDistV = rDistV(goV);
            distGoV = distV(goV);

            %We ignore the slight tilt of PB cross-sections with respect to the longitudinal axis.

            [gantryVectorsM] = RTOGVectors2Gantry(rGoM, IM.beams(j).gantryAngle);
            Xb = gantryVectorsM(:,1);
            Yb = gantryVectorsM(:,2);

            tmpV=clip(distGoV,0.001,max(distSamplePts) - 0.001,'limits');

            %get cum density at that point
            radDepthV = interp1([0, distSamplePts],[0, cumDensity],tmpV);

            %Get the widths of the PBs at that distance
            PBWidth_YbV = IM.beams(j).beamletDelta_y * distGoV/IM.beams(j).isodistance; %This is the width 'out-of-plane'
            PBWidth_XbV = IM.beams(j).beamletDelta_x * distGoV/IM.beams(j).isodistance; %This is the width 'in-plane'

            %compute dose using QIB
            [A_zV, a_zV, B_zV, b_zV] = GetPBConsts(radDepthV, IM.beams(j).beamEnergy, QIBDataS, 'nearest');

            doseFlag = IM.params.DoseTerm;

            sigmaVal_100 = IM.beams(j).sigma_100;

            doseV = getQIBDose([Xb,Yb], radDepthV, PBWidth_XbV, PBWidth_YbV, ...
                QIBDataS, A_zV, a_zV, B_zV, b_zV, IM.beams(j).beamEnergy, doseFlag, sigmaVal_100, distGoV);

            % apply inverse square law:
            % (divide by depth dependent area of beamlet scaled to isocenter distance)
            doseV = IM.beams(j).beamletDelta_x * IM.beams(j).beamletDelta_y * doseV ./ (PBWidth_XbV .* PBWidth_YbV);

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    %This function selectively eliminates some scatter components, if invoked.
            doseV = applyIMRTCompression(IM.params, doseV);
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

            %-----------Construct the dose matrix---------------------%

            indNZV = [doseV == 0];
            whereV = goV;     %First trap on distance
            ind0V = find(whereV);
            whereV(ind0V(indNZV)) = 0;    %zero out indices where dose was not computed from within QIB routine.
            [indV] = find(whereV);        %indV returns locations where dose is non-zero.
            doseV(indNZV) = [];           %eliminate dose entries which were zero.

            beamlet = createIMBeamlet(doseV, scanIndV(indV), j, length(goV));

            IM.beamlets(structROIV(i),PBCounter) = beamlet;
            IM.beamlets(structROIV(i),PBCounter).structureName = planC{planC{end}.structures}(structROIV(i)).structureName;
            IM.beamlets(structROIV(i),PBCounter).sampleRate = sampleRateV(i);

            PBCounter = PBCounter + 1;
        end

    end

    clear xV yV zV sourceM pM pRelM qM rM rDistV rGoM rowV sliceV;

end


function s1 = resize_scales(s0,dim,args)
% Resize scalefactors
% _________________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

%
% $Id$

dim = [dim ones(1,max(numel(args)-numel(dim),0))];
args1 = cell(1,numel(args));
for i=1:numel(args),
    if max(args{i})>dim(i) || min(args{i})<1,
        error('Index exceeds matrix dimensions (1).');
    end;

    if size(s0,i)==1,
        args1{i} = ones(size(args{i}));
    else
        args1{i} = args{i};
    end;
end;

s1 = s0(args1{:});


%% Example script to visualize the aircraft simulation data
% Add the path of the aircraft_3d_animation function
addpath('../src/');
% path of the *.mat file containing the 3d model information
model_info_file = '../3d_models/x15_3d_model.mat';
% Load the simulation data
% load('scissors_maneuver.mat')
% load('breakaway_maneuver.mat')
% load('split_s_maneuver.mat')
% load('departure.mat')
load('departure2.mat')
% define the reproduction speed factor
speedx = 1;
% Do you want to save the animation in a mp4 file? (0.No, 1.Yes)
isave_movie = 1;
% Movie file name
movie_file_name = 'departure2.mp4';

% -------------------------------------------------------------------------
% The frame sample time shall be higher than 0.02 seconds to be able to
% update the figure (CPU/GPU constraints)
frame_sample_time = max(0.02, tout(2)-tout(1));
% Resample the time vector to modify the reproduction speed
t_new   = tout(1):frame_sample_time*(speedx):tout(end);
% Resample the recorded data
act     = interp1(tout, act, t_new','linear');
stick   = interp1(tout, stick, t_new','linear');
y_new   = interp1(tout, yout, t_new','linear');
% We have to be careful with angles with ranges
y_new(:, 7)  = atan2(interp1(tout, sin(yout(:, 7)), t_new','linear'), interp1(tout, cos(yout(:, 7)), t_new','linear')) * 180 / pi;
y_new(:, 8)  = atan2(interp1(tout, sin(yout(:, 8)), t_new','linear'), interp1(tout, cos(yout(:, 8)), t_new','linear')) * 180 / pi;
y_new(:, 9)  = atan2(interp1(tout, sin(yout(:, 9)), t_new','linear'), interp1(tout, cos(yout(:, 9)), t_new','linear')) * 180 / pi;
% Assign the data
heading_deg           =  y_new(:, 7);
pitch_deg             =  y_new(:, 8);
bank_deg              =  y_new(:, 9);
roll_command          = -stick(:, 2);
pitch_command         = -stick(:, 1);
angle_of_attack_deg   =  y_new(:, 2) * 180 / pi;
angle_of_sideslip_deg =  y_new(:, 3) * 180 / pi;
fligh_path_angle_deg  =  y_new(:, 22) * 180 / pi;
mach                  =  y_new(:, 21);
altitude_ft           = -y_new(:, 12);
nz_g                  =  y_new(:, 19);
% Flight control surfaces
dr     = -act(:, 8);
df1    =  act(:, 6);
df2    =  act(:, 5);
df3    =  act(:, 4);
df4    =  act(:, 3);
% Control array assignation
% (modify the order according to your particular 3D model)
controls_deflection_deg = [ 0.25 * (df1(:) + df2(:) - df3(:) - df4(:)), ...
                           -0.25 * (df1(:) + df2(:) - df3(:) - df4(:)), ...
                            0.25 * (df1(:) + df2(:) + df3(:) + df4(:)), ...
                            0.25 * (df1(:) + df2(:) + df3(:) + df4(:)), ...
                            df1(:) * 0, ...
                            df1(:) * 0, ...
                            dr(:)];

%% Run aircraft_3d_animation function
% -------------------------------------------------------------------------
aircraft_3d_animation(model_info_file,...
    heading_deg, ...            Heading angle [deg]
    pitch_deg, ...              Pitch angle [deg]
    bank_deg, ...               Roll angle [deg]
    roll_command, ...           Roll  stick command [-1,+1] [-1 -> left,            +1 -> right]
    pitch_command, ...          Pitch stick command [-1,+1] [-1 -> full-back stick, +1 -> full-fwd stick]
    angle_of_attack_deg, ...    AoA [deg]
    angle_of_sideslip_deg, ...  AoS [deg]
    fligh_path_angle_deg, ...   Flight path angle [deg]
    mach, ...                   Mach number
    altitude_ft, ...            Altitude [ft]
    nz_g,  ...                  Vertical load factor [g]
    controls_deflection_deg, ...Flight control deflection (each column is a control surface)
    frame_sample_time, ...      Sample time [sec]
    speedx, ...                 Reproduction speed
    isave_movie, ...            Save the movie? 0-1
    movie_file_name);           % Movie file name


%% Example of using KST class for interfacing with KUKA iiwa robots

% soft real-time control of the KUKA robot with
% impedence
% Moving the joints of the robot using a sinusoidal function

% The external torques are plotted in real-time during the test
% the feedback from the measured torques can be used to for a closed loop
% control

% First start the server on the KUKA iiwa controller
% Then run this script using Matlab

% This code was tested using Matlab 2013b

% This example works with Sunrise application version KST_1.7  and higher.
% Copyright Mohammad SAFEEA, 26th-June-2018

close all;clear;clc;
warning('off')
%% Create the robot object
ip='172.31.1.147'; % The IP of the controller
arg1=KST.LBR7R800; % choose the robot iiwa7R800 or iiwa14R820
arg2=KST.Medien_Flansch_elektrisch; % choose the type of flange
Tef_flange=eye(4); % transofrm matrix of EEF with respect to flange
iiwa=KST(ip,arg1,arg2,Tef_flange); % create the object

%% Start a connection with the server
flag=iiwa.net_establishConnection();
if flag==0
return;
end
pause(1);
disp('Doing some stuff')

%% Move point to point to an initial position
jPos={0,0,0,-pi/2,0,pi/2,0};
relVel=0.15;
iiwa.movePTPJointSpace(jPos, relVel); % move to initial configuration

%% Pause for 3 seocnds
pause(3);

%% Tool/Impedance parameters
massOfTool=0.5; % the mass of the tool attached to flange in Kg
cOMx=0; % X coordinate of the center of mass of the tool in (mm)
cOMy=0; % Y coordinate of the center of mass of the tool in (mm)
cOMz=40; % Z coordinate of the center of mass of the tool in (mm)
cStiness=900; % cartizian stifness
rStifness=80; % rotational stifness
nStifness=50; % null space stifness

% Start the soft realtime control with impedance
iiwa.realTime_startImpedanceJoints(massOfTool,cOMx,cOMy,cOMz,...
cStiness,rStifness,nStifness);

w=0.6; % motion constants, frequency rad/sec
A=0.2; % motion constants, amplitude of motion

a=datevec(now);
t0=a(6)+a(5)*60+a(4)*60*60; % calculate initial time

dt=0;
tstart=t0;
counter=0;
duration=0.5*60; %0.5 minutes

%% Control loop
% real time plot handles
 colors={'k','b','r','g','c','m','y'};
 figureHandle=figure('Units','inches','Position',[0 0 5 3.75]);
 numOfSamples=120; % number of samples to show in the plot
 timeVec=1:numOfSamples;
 tawVec=zeros(7,numOfSamples);
 plotHandle=[];
 for i=1:7
    plotHandle=[plotHandle,plot(timeVec,tawVec(i,:),colors{i},'LineWidth',2)];
    hold on;
 end
% format the plot
ylim([0,8]);
temp=title('External torques');
set(temp,'FontSize',16);
temp=xlabel('Time (seconds)');
set(temp,'FontSize',14);
temp=ylabel('Distance (m)');
set(temp,'FontSize',14);

while(dt<duration)
 %% perform trajectory calculation here
  a=datevec(now);
  time=a(6)+a(5)*60+a(4)*60*60;
  dt=time-t0;

  temp=A*(1-cos(w*dt));
    for dacount=1:7
        jPosCommand{dacount}=jPos{dacount}+temp;
    end
  counter=counter+1;
  %% Send joint positions to robot
  taw=iiwa.sendJointsPositionsExTorque(jPosCommand);

  tawTemp=zeros(7,1);
  for i=1:7
      tawTemp(i)=taw{i};
      torque_array(i,counter)=taw{i};
  end
  % delete first measurment
  tawVec(:,1)=[];
  % add new measurment to end of arrays
  tawVec=[tawVec,tawTemp];
  % update plots data
  for i=1:6
    set(plotHandle(i),'YData',tawVec(i,:));
  end
  set(plotHandle(7),'YData',tawVec(i,:));
  % show plot data
  set(figureHandle,'Visible','on');

end

%% Stop the realtime control with impedence motion
iiwa.realTime_stopImpedanceJoints();
fprintf('\n Motion stopped \n');
pause(2);

%% turn off the server
iiwa.net_turnOffServer();

warning('on')


function f = sinh( f )
%SINH   Hyperbolic sine of a SEPARABLEAPPROX.

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

% Empty check:
if ( isempty( f ) )
    return
end

f = compose( f, @sinh );

end


function y = guard_interval(Ng,Nfft,NgType,ofdmSym)
if NgType==1
  y=[ofdmSym(Nfft-Ng+1:Nfft) ofdmSym(1:Nfft)];
elseif NgType==2
  y=[zeros(1,Ng) ofdmSym(1:Nfft)];
end


% Script: call_Omorifit.m
% -----------------------
% Script to input parameters for a modified Omori law fit and calculate fit to data
% Calculation is done in function plot_llkstest
% The function works on the catalog newt2!!!
% J.Woessner
% last update: 19.08.03

report_this_filefun(mfilename('fullpath'));
% Get input parameters
prompt  = {,'Enter length of learning period (days)','Enter number of bootstraps:'};
title   = 'Parameters ';
lines= 1;
if exist('time') &&  exist('bootloops')
    time = num2str(time);
    bootloops = num2str(bootloops);
    def     = {time,bootloops};
    answer  = inputdlg(prompt,title,lines,def);
    time = str2double(answer{1});
    timef = 1;
    bootloops = str2double(answer{2});

else
    def     = {'50','50'};
    answer  = inputdlg(prompt,title,lines,def);
    time = str2double(answer{1});
    timef = 1;
    bootloops = str2double(answer{2});
end

% maepi is the mainshock of sequence
plot_llkstest(newt2,time,timef,bootloops,maepi);


function rtk=udpos_rtkins(rtk,tt) %#ok

ins=rtk.ins;
rtk.x(1:15)=0;
rtk.P(1:15,1:15)=0;

% lever arm correction
pos=ins.pos+ins.Mpv*ins.Cnb*ins.lever;
vel=ins.vel+ins.Cnb*askew(ins.web)*ins.lever;

rtk.x(1:15)=[ins.att;vel;pos;ins.bg;ins.ba];
rtk.P(1:15,1:15)=ins.P;

return


function [data, labels, imind] = mcmcGenerateRandomSegments3(imsegs, imdir, ...
            adjlist, spdata, edata, vclassifierSP, hclassifierSP, eclassifier)
% Generate random segments for training good (1) vs. bad (-1) segments
% segment, where good segments consist entirely of one label

nimages = numel(imsegs);
nfeatures = 36;

nsegments = 60000;

disp(num2str(nimages))

data = zeros(nsegments, nfeatures);

labels = zeros(nsegments, 1);

imind = zeros(nsegments, 1);

count = 0;

for f = 1:nimages

    disp([num2str(f) ': ' imsegs(f).imname])

    im = im2double(imread([imdir '/' imsegs(f).imname]));
    %imdata = mcmcComputeImageData(im, imsegs(f)) ;

    segimage = imsegs(f).segimage;

    %features{f} = mcmcGetSegmentFeatures(imsegs(f), spfeatures{f}, imdata,
    %gtmaps{f}, [1:max(gtmaps{f})]);

    [pvSP, phSP, pE, smap] = mcmcInitialize(spdata{f}, edata{f}, ...
        adjlist{f}, imsegs(f), vclassifierSP, hclassifierSP, eclassifier, 'labels');

    origmap = smap;

    while count < round(nsegments*(f/nimages))

        %figure(1), hold off, imshow(label2rgb(origmap(segimage)))
        [smap, newseg, origseg, segadjmat] =  ...
            mcmcGenerateProposals(pE, adjlist{f}, smap, im, segimage);

        % display segments
        %figure(2), hold off, imagesc(label2rgb(smap(segimage)));
        %figure(1), displaySegmentGraph(im, smap(segimage), segadjmat);

        neighborseg = [newseg find(segadjmat(newseg, :))];

        % keep all potential segments as data points
        sind = find(smap==newseg);
        for ni = neighborseg
            smap2 = smap;
            smap2(sind) = ni;
            if ni~=newseg
                sind2 = find(smap2 > newseg);
                smap2(sind2) = smap2(sind2) - 1;
                if ni > newseg
                    ni = ni - 1;
                end
            end
            count = count + 1;

            data(count, :) = mcmcGetSegmentationFeatures(pvSP, phSP, pE, adjlist{f}, imsegs(f).npixels, smap2, ni);
            %data(count, :) = mcmcGetSegmentFeatures(imsegs(f), spdata{f}, imdata, smap2, ni);

            labels(count) = getMixUniLabel(imsegs(f), smap2, ni); % 0 for mix, 1 for uni

            imind(count) = f;

            if count == nsegments
                break;
            end

        end

        % remove possibility of returning to previous state
        if numel(neighborseg)>1
            neighborseg(find(neighborseg==origseg)) = [];
        end

        % randomly select neighbor
        nn = numel(neighborseg);
        goodind = find(labels((count-nn+1):count)); % good neighbors
        w = 0.25*ones(nn, 1);
        w(goodind) = 0.5; % so that a uniform segment is twice as likely to be picked
        w = cumsum(w / sum(w));
        ri = find(rand(1) < w);

        ni = neighborseg(ri(1)); % get neighbor segment

        % attach segment newseg to segment ni (unless newseg==ni)
        smap(sind) = ni;
        if ni~=newseg
            sind2 = find(smap > newseg);
            smap(sind2) = smap(sind2) - 1;
        end
        %figure(3), hist(smap, [1:max(smap)])

%         mask = zeros([size(im, 1) size(im, 2)]);
%         mask(find(smap(segimage)==ni)) = 1;
%         disp(num2str([max(smap) labels(count-nn+ri(1))]))
%         figure(2), hold off, imagesc(im .* repmat(mask, [1 1 3])), axis image
    end

    disp(num2str(mean(labels(1:count)==1)))

end

% remove segments that are not clearly good or bad
ind = find(labels==0);
labels(ind) = [];
data(ind, :) = [];
imind(ind) = [];
% end mcmcGenerateRandomSegments3

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function label = getMixUniLabel(imsegs, smap, si)
% returns -1 for mixed; 0 for neither; 1 for uniform

lcount = zeros(numel(imsegs.label_names), 1);
sind = find(smap==si);

for k = sind'
    slab = imsegs.labels(k);
    if slab > 0
        lcount(slab) = lcount(slab) + imsegs.npixels(k);
    end
end
npix = sum(lcount);

if npix > 0
    lcount = lcount / npix;
else
    label = 0;
    return;
end

label = 0;
if max(lcount) < 0.95 || ((1-max(lcount))*npix > 500)
    label = -1;
elseif max(lcount) > 0.99
    label = 1;
end


function [poly,poly_idx,opendat,boudat] = extract_boundary(v_start,v_end,bnde,pts,order,opendat,boudat,type,type2)
% DESCRIPTION: Given a set of boundary edges and a starting and ending index
%              of a singly- or multi-polygonal region, organize them in a
%              winding order and/or add them to an existing opendat/boudat
%              structure. The program breaks up the boundary so that it
%              will never exceed 100,000 nodes to avoid memory allocation
%              issues adcprep.
%
% INPUTS:
%      v_start: the starting index of the boundary you want to trace
%        v_end: the ending index of the boundary you want to trace.
%         bnde: the indices of each boundary edge as a nbnde x 2 matrix
%         pts:  the x,y locations of all the points in the region
%               stored as an np x 2 matrix.
%         order:the order in which the traversal takes place
%               counter-clockwise (0) or clockwise (1).
%         opendat: open boundary information from a pre-existing grid
%          boudat: land boundary information from a pre-exist
% OUTPUTS:
%          poly: the boundary of each enclosing polygon sorted in winding-order
%                poly is returned as a cell-array of length number of polys.
%      poly_idx: indices of the polygon coordinates in the same format as
%                poly
%       opendat: open boundary information with appened open bou
%       boudat: land boundary information with appended land bou
%         type: flux(1) or elevation (2) type bc
%        type2: if flux, zero flux (20) or non-zero flux river (22) bc
%
% kjr,UND,CHL,2017
%
%                                           TRAVERSAL METHOD
% Pick any unvisited edge segment [v_start,v_next] and add these vertices to the polygon loop.
% Find the unvisited edge segment [v_i,v_j] that has either v_i = v_next or v_j = v_next and add the other vertex (the one not equal to v_next) to the polygon loop.
% Reset v_next as this newly added vertex, mark the edge as visited and continue from 2.
% Traversal is done when we get back to v_start.
% NOTE: that the signed area will be positive if the vertices are
% oriented counterclockwise, and will be negative if it is oriented clockwise
bnde= unique(bnde,'rows');
active = true(size(bnde,1),1);
p = 0;
exceed = 50e3; %100e3;

[rt,~] = find(v_start==bnde);
if isempty(rt), disp('v_start does not exist on boundary, check numbering'); return; end
r  = rt(order+1); % change this only here to from 1 to 2 or 2 to 1 to go left or right
tsel = bnde(r,:);
sel  = tsel(tsel~=v_start);
v_next = sel;
active(r) = 0;
% cut up boundary so land boundary never exceeds 100k nodes.
cut = true;
while cut
    p = p + 1;
    if(p > 1 )
        [rt,~] = find(v_next==bnde & active);
        r  = rt(1);
        tsel = bnde(r,:);
        sel  = tsel(tsel~=v_next);
        v_next = sel;
        active(r) = 0;
    end

    temp = [];
    temp2= [];

    temp  = pts(bnde(r,:)',:);
    temp2 = bnde(r,:)';
    if v_next ~= temp2(2)
      % swap
      temp = flipud(temp);
      temp2 = flipud(temp2);
    end

    k = 2;
    while v_next~=v_end % terminates when we reach v_end
        rt= (v_next==bnde(:,1) | v_next==bnde(:,2)) &  active;
        r = find(rt,1);
        tsel = bnde(r,:);
        sel=tsel(tsel~=v_next);
        k = k + 1;
        temp(k,:)= pts(sel,:);
        temp2(k,:)= sel;
        active(r) = 0;
        v_next = sel;
        % exceeded max xize, break
        if (k > exceed),disp('exceed'); break, end
        % reached ending vertex, break
        if(v_next==v_end), cut=false; disp('reached ending'); end
        % exhausted all edges and couldn't connect
        if(~any(active)), cut=false; disp('coudln''t conntect'); break, end
    end
    if length(temp) == 2
        cut = false;
    end
    poly{p}     = temp;
    poly_idx{p} = temp2;
    [area] = parea(poly{p}(:,1),poly{p}(:,2));
    if order == 0 % ccw
        if sign(area)<0
            poly{p} = flipud(poly{p});
            poly_idx{p} = flipud(poly_idx{p});
        end
    else % cw
        if sign(area)>0
            poly{p} = flipud(poly{p});
            poly_idx{p} = flipud(poly_idx{p});
        end
    end
end
for ii = 1 : p
    hold on; plot(poly{ii}(:,1),poly{ii}(:,2),'r-','linewi',2);
end

if ~exist('type','var')
   type = input('What kind of boundary is this, 1 (flux) or 2 (elevation)?');
end

% if populated
if ~isempty(boudat)
    if(type==1)
        nbou = boudat.nbou;
        nvel = boudat.nvel;
        nvell= boudat.nvell;
        nbvv = boudat.nbvv;
        ibtype = boudat.ibtype;
        if ~exist('type2','var')
           type2 = input('What kind of flux boundary is it, 20 (Mainland), 21 (Island), 22 (River)?');
        end
        for ii = 1 : length(poly)
            nbou = nbou + 1;
            nvell(nbou) = length(poly{ii}(:,1));
            nvel = nvel + nvell(nbou);
            nbvv(1:nvell(nbou),nbou) = int32(poly_idx{ii}(:));
            ibtype(nbou) = type2;
        end
        boudat.nbou = nbou ;
        boudat.nvel = nvel ;
        boudat.nvell = nvell ;
        boudat.ibtype = ibtype ;
        boudat.nbvv = nbvv ;
    end
end

% if populated
if ~isempty(opendat)
    if type==2
        nope = opendat.nope;
        nvdll= opendat.nvdll;
        neta = opendat.neta;
        ibtype=opendat.ibtype;
        nbdv  = opendat.nbdv;

        for ii = 1 : length(poly)
            nope = nope + 1;
            nvdll(nope) = length(poly_idx{ii}(:,1));
            neta = neta + nvdll(nope);
            ibtype(nope) = 0;
            nbdv(1:nvdll(nope),nope) = poly_idx{ii}(:,1);
        end
        % ocean boundary
        opendat.nope = nope ;
        opendat.neta = neta ;
        opendat.nvdll = nvdll ;
        opendat.ibtype = ibtype ;
        opendat.nbdv = nbdv ;

    end
end

% if empty
if isempty(opendat)
    if(type==2)
        % nothing populated
        nope = 0 ;
        nvdll = []  ;
        neta = 0 ;
        nbdv = [] ;
        for ii = 1 : length(poly)
            nope = nope + 1;
            nvdll(nope) = length(poly_idx{ii}(:,1));
            neta = neta + nvdll(nope);
            ibtype(nope) = 0;
            nbdv(1:nvdll(nope),nope) = poly_idx{ii}(:,1);
        end
        % ocean boundary
        opendat.nope = nope ;
        opendat.neta = neta ;
        opendat.nvdll = nvdll ;
        opendat.ibtype = ibtype ;
        opendat.nbdv = nbdv ;
    end
end

% if empty
if isempty(boudat)
    if type==1
        nbou = 0; nvel = 0; nvell = []; nbbv = [] ;
        if ~exist('type2','var')
           type2 = input('What kind of flux boundary is it, 20(island),22(River)?');
        end
        for ii = 1 : length(poly)
            nbou = nbou + 1;
            nvell(nbou) = length(poly{ii}(:,1));
            nvel = nvel + nvell(nbou);
            nbvv(1:nvell(nbou),nbou) = poly_idx{ii}(:);
            ibtype(nbou) = type2;
        end
        boudat.nbou = nbou ;
        boudat.nvel = nvel ;
        boudat.nvell = nvell ;
        boudat.ibtype = ibtype ;
        boudat.nbvv = nbvv ;
    end
end

end
% helper function, computes area of polygon
function [area]=parea(x,y)
n    = length(x);
xp   = [x; x(1)];
yp   = [y; y(1)];
area = 0;
for i = 1:n
    area = area + det([xp(i), xp(i+1); yp(i), yp(i+1)]);
end
area = 1/2*area;
end


%evaluate on the val2 set from imagenet2013
%use the default parameters as used in the demo:
%% load pre-trained edge detection model and set opts (see edgesDemo.m)
addpath(genpath('../'));

model=load('models/forest/modelBsds'); model=model.model;
model.opts.multiscale=0; model.opts.sharpen=2; model.opts.nThreads=4;

%% set up opts for edgeBoxes (see edgeBoxes.m)
opts = edgeBoxes;
opts.alpha = .65;     % step size of sliding window search
opts.beta  = .75;     % nms threshold for object proposals
opts.minScore = .01;  % min score of boxes to detect
opts.maxBoxes = 1e4;  % max number of boxes to detect

%config specifies the image location location to save output etc.
config=createConfig();
imageLoc=config.path.imageLoc;
saveLoc=config.path.outputLoc;
ext=config.opts.imageExt;

imageExt=config.opts.imageExt;
images=dir([imageLoc '*' imageExt]);

for i=1:length(images)

	imageName=images(i).name;
	im=imread([imageLoc imageName]);
	if(size(im, 3) == 1)
		im=repmat(im,[1,1,3]);
	end
	bbs=edgeBoxes(im,model,opts);
	if(isfield((config.opts),'numProposals'))
		numProposals=config.opts.numProposals;
	        if(size(bbs,1)>=numProposals)
        	        bbs=bbs(1:numProposals);
        	else
                	fprintf('Only %d proposals were generated for image: %s\n',size(bbs,1),imageName);
        	end
	end
 	%edges boxes produces baoxes as "[x y w, h]"
	%we convert to [x y x+w y+h]==[xmin ymin xmax ymax]
        boxes=bbs(:,1:4);
	boxes=[boxes(:,1) boxes(:,2) boxes(:,1)+ boxes(:,3) boxes(:,2)+boxes(:,4)];
	proposals.boxes= boxes;
	proposalFileName=strrep(imageName,imageExt,'.mat');

	save([saveLoc proposalFileName], 'proposals');
end


function wt = wfbtput(d,k,w,wt,forceStr)
%WFBTPUT  Put node to the filterbank tree
%   Usage:  wt = wfbtput(d,k,w,wt);
%           wt = wfbtput(d,k,w,wt,'force');
%
%   Input parameters:
%           d   : Level in the tree (0 - root).
%           k   : Index (array of indexes) of the node at level *d* (starting at 0).
%           w   : Node, basic wavelet filterbank.
%           wt  : Wavelet filterbank tree structure (as returned from
%                 |wfbtinit|).
%
%   Output parameters:
%           wt : Modified filterbank structure.
%
%   `wfbtput(d,k,w,wt)` puts the basic filterbank *w* to the filter
%   tree structure *wt* at level *d* and index(es) *k*. The output is a
%   modified tree structure. *d* and *k* have to specify unconnected output
%   of the leaf node. Error is issued if *d* and *k* points to already
%   existing node. For possible formats of parameter *w* see help of |fwt|.
%   Parameter *wt* has to be a structure returned by |wfbtinit|.
%
%   `wfbtput(d,k,w,wt,'force')` does the same but replaces node at *d* and *k*
%   if it already exists. If the node to be replaced has any children,
%   the number of outputs of the replacing node have to be equal to number of
%   outputs of the node beeing replaced.
%
%   Examples:
%   ---------
%
%   This example shows magnitude frequency responses of a tree build from
%   the root:::
%
%      % Initialize empty struct
%      wt = wfbtinit();
%      % Put root node to the empty struct
%      wt1 = wfbtput(0,0,'db8',wt);
%      % Connect a different nodes to both outputs of the root
%      wt2 = wfbtput(1,[0,1],'db10',wt1);
%      % Connect another nodes just to high-pass outputs of nodes just added
%      wt3 = wfbtput(2,[1,3],'db10',wt2);
%      % Add another node at level 3
%      wt4 = wfbtput(3,1,'db16',wt3);
%
%      % Create identical filterbanks
%      [g1,a1] = wfbt2filterbank(wt1,'freq');
%      [g2,a2] = wfbt2filterbank(wt2,'freq');
%      [g3,a3] = wfbt2filterbank(wt3,'freq');
%      [g4,a4] = wfbt2filterbank(wt4,'freq');
%
%      % Plot frequency responses of the growing tree. Linear scale
%      % (both axis) is used and positive frequencies only are shown.
%      subplot(4,1,1);
%      filterbankfreqz(g1,a1,1024,'plot','linabs','posfreq');
%      subplot(4,1,2);
%      filterbankfreqz(g2,a2,1024,'plot','linabs','posfreq');
%      subplot(4,1,3);
%      filterbankfreqz(g3,a3,1024,'plot','linabs','posfreq');
%      subplot(4,1,4);
%      filterbankfreqz(g4,a4,1024,'plot','linabs','posfreq');
%

% AUTHOR: Zdenek Prusa

if nargin<4
   error('%s: Too few input parameters.',upper(mfilename));
end

%if isfield(wt,'dualnodes')
%    error('%s: Cannot modify the dual-tree struct.',upper(mfilename));
%end

do_force = 0;
if nargin==5
    if ~ischar(forceStr)
        error('%s: Fifth parameter should be a string.',upper(mfilename));
    end
    if strcmpi(forceStr,'force')
        do_force = 1;
    end
end

% This was replaced. Calling ltfatargheler was too slow.
%definput.flags.force = {'noforce','force'};
%[flags,kv]=ltfatarghelper({},definput,varargin);

node = fwtinit(w);

oldnodecount = numel(wt.nodes);
nodeschanged = [];

[nodeNoArray,nodeChildIdxArray] = depthIndex2NodeNo(d,k,wt);

for ii=1:numel(nodeNoArray)
 nodeNo = nodeNoArray(ii);
 nodeChildIdx = nodeChildIdxArray(ii);
if(nodeNo==0)
    % adding root
    if(~isempty(find(wt.parents==0,1)))
        if(do_force)
           rootId = find(wt.parents==0,1);
           % if root has children, check if the new root has the same
           % number of them
           if(~isempty(find(wt.children{rootId}~=0,1)))
              if(length(w.g)~=length(wt.nodes{rootId}.g))
                 error('%s: The replacing root have to have %d filters.',mfilename,length(wt.nodes{rootId}.g));
              end
           end
        else
            error('%s: Root already defined. Use FORCE option to replace.',mfilename);
        end
        wt.nodes{rootId} = node;
        nodeschanged(end+1) = rootId;

        if isfield(wt,'dualnodes')
            wt.dualnodes{rootId} = node;
        end
        continue;
    end
    wt.nodes{end+1} = node;
    wt.parents(end+1) = nodeNo;
    wt.children{end+1} = [];

    if isfield(wt,'dualnodes')
        wt.dualnodes{end+1} = node;
    end
    continue;
end

childrenIdx = find(wt.children{nodeNo}~=0);
found = find(childrenIdx==nodeChildIdx,1);
if(~isempty(found))
   if(do_force)
     %check if childrenIdx has any children
     tmpnode = wt.children{nodeNo}(found);
     if(~isempty(find(wt.children{tmpnode}~=0, 1)))
         if length(node.g)~=length(wt.nodes{tmpnode}.g)
            error('%s: The replacing node must have %d filters.',mfilename,length(wt.nodes{tmpnode}.g));
         end
     end
     wt.nodes{tmpnode} = node;
     nodeschanged(end+1) = tmpnode;
     if isfield(wt,'dualnodes')
         wt.dualnodes{tmpnode} = node;
     end
     % Since we are replacing a node, all links are already correct
     continue;
   else
       error('%s: Such node (depth=%d, idx=%d) already exists. Use FORCE option to replace.',mfilename,d,k);
   end
end

wt.nodes{end+1} = node;
wt.parents(end+1) = nodeNo;
wt.children{end+1} = [];
wt.children{nodeNo}(nodeChildIdx) = numel(wt.parents);

if isfield(wt,'dualnodes')
    wt.dualnodes{end+1} = node;
end

end

% We have to correctly shuffle filters in the just added (or modified) filters
% if the tree was already defined as frequency ordered.
if wt.freqOrder
      wt = nat2freqOrder(wt,[nodeschanged,oldnodecount+1:numel(wt.nodes)]);
end


% dipfit_erpeeg - fit multiple component dipoles using DIPFIT
%
% Usage:
%         >> [ dipole model EEG] = dipfit_erpeeg(data, chanlocs, 'key', 'val', ...);
%
% Inputs:
%  data      - input data [channel x point]. One dipole per point is
%              returned.
%  chanlocs  - channel location structure (returned by readlocs()).
%
% Optional inputs:
%  'settings'  - [cell array] dipfit settings (arguments to the
%                pop_dipfit_settings() function). Default is none.
%  'dipoles'   - [1|2] use either 1 dipole or 2 dipoles contrain in
%                symetry. Default is 1.
%  'dipplot'   - ['on'|'off'] plot dipoles. Default is 'off'.
%  'plotopt'   - [cell array] dipplot() 'key', 'val' options. Default is
%                'normlen', 'on', 'image', 'fullmri'
%
% Outputs:
%  dipole      - dipole structure ('posxyz' field is the position; 'momxyz'
%                field is the moment and 'rv' the residual variance)
%  model       - structure containing model information ('vol.r' field is
%                radius, 'vol.c' conductances, 'vol.o' the 3-D origin and
%                'chansel', the selected channels).
%  EEG         - faked EEG structure containing erp activation at the place
%                of ICA components but allowing to plot ERP dipoles.
%
% Note: residual variance is set to NaN if Dipfit does not converge
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Nov. 2003

% Copyright (C) 10/2003 Arnaud Delorme, SCCN/INC/UCSD, arno@sccn.ucsd.edu
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function [dipoles, model, EEG] = dipfit_erpeeg(DATA, chanlocs, varargin);

    if nargin < 1
        help dipfit_erpeeg;
        return;
    end;

    ncomps = size(DATA,2);
    if size(DATA,1) ~= length(chanlocs)
        error('# of row in ''DATA'' must equal # of channels in ''chanlocs''');
    end;

    % faking an EEG dataset
    % ---------------------
    EEG          = eeg_emptyset;
    EEG.data     = rand(size(DATA,1), 1000);
    EEG.nbchan   = size(DATA,1);
    EEG.pnts     = 1000;
    EEG.trials   = 1;
    EEG.chanlocs = chanlocs;
    EEG.icawinv    = [ DATA DATA ];
    EEG.icaweights = zeros(size([ DATA DATA ]))';
    EEG.icasphere  = zeros(size(DATA,1), size(DATA,1));
    %EEG            = eeg_checkset(EEG);
    EEG.icaact     = EEG.icaweights*EEG.icasphere*EEG.data(:,:);
    EEG.icaact     = reshape( EEG.icaact, size(EEG.icaact,1), size(EEG.data,2), size(EEG.data,3));

    % uses mutlifit to fit dipoles
    % ----------------------------
    EEG            = pop_multifit(EEG, [1:ncomps], varargin{:});

    % process outputs
    % ---------------
    dipoles = EEG.dipfit.model;
    if isfield(dipoles, 'active')
        dipoles = rmfield(dipoles, 'active');
    end;
    if isfield(dipoles, 'select')
        dipoles = rmfield(dipoles, 'select');
    end;
    model   = EEG.dipfit;
    if isfield(model, 'model')
        model   = rmfield(model, 'model');
    end;
    return;


% StackExchange Signal Processing Q79314
% https://dsp.stackexchange.com/questions/79314
% Image Segmentation Using Deep Learning
% References:
%   1.
% Remarks:
%   1.  B
% TODO:
% 	1.  C
% Release Notes
% - 1.0.000     27/11/2021
%   *   First release.

%% General Parameters

subStreamNumberDefault = 79;

run('InitScript.m');

figureIdx           = 0;
figureCounterSpec   = '%04d';

generateFigures = ON;

%% Simulation Parameters

imageSetFolderName  = 'ImageSet';
maskSetFolderName   = 'MaskSet';

resizePostName = 'Resize';

numRows     = 64;
numCols     = 64;

%% Generate Data

sFiles = dir(strcat(imageSetFolderName, resizePostName, FILE_SEP, '*.jpg'));
for ii = 1:length(sFiles)
    mI = imread(strcat(sFiles(ii).folder, FILE_SEP, sFiles(ii).name));
    assert(size(mI, 1) == numRows);
    assert(size(mI, 2) == numCols);
    assert(size(mI, 3) == 3);
end

sFiles = dir(strcat(maskSetFolderName, resizePostName, FILE_SEP, '*.png'));
for ii = 1:length(sFiles)
    mI = imread(strcat(sFiles(ii).folder, FILE_SEP, sFiles(ii).name));
    assert(size(mI, 1) == numRows);
    assert(size(mI, 2) == numCols);
    assert(size(mI, 3) == 1);
end

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);


% subsref() - index eegdata class
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, Nov. 2008

% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function res = subsref(obj,s)

    if strcmpi(s(1).type, '.')
        res = builtin('subsref', obj, s);
        return;
    end;

    tmpMMO = memmapfile(obj.dataFile, 'writable', obj.writable, 'format', { 'single' obj.dimensions 'x' });

    subs = s(1).subs;
    finaldim = cellfun('length', subs);

    % one dimension input
    % -------------------
    if length(s) > 1 || ~strcmpi(s(1).type, '()')
        error('MMO can only map single array data files');
    end;

    % deal with transposed data
    % -------------------------
    if obj.transposed, s = transposeindices(obj, s); end;

    % convert : to real sizes
    % -----------------------
    lastdim = length(subs);
    if isstr(subs{end}) && ndims(obj) > lastdim
        for index = lastdim+1:ndims(obj)
            if index > length(obj.dimensions)
                subs{index} = 1;
            else
                subs{index} = [1:obj.dimensions(index)];
            end;
        end;
    end;
    for index = 1:length(subs)
        if isstr(subs{index}) % can only be ":"
            if index > length(obj.dimensions)
                subs{index} = 1;
            else
                subs{index} = [1:obj.dimensions(index)];
            end;
        end;
    end;
    finaldim = cellfun(@length, subs);
    finaldim(lastdim) = prod(finaldim(lastdim:end));
    finaldim(lastdim+1:end) = [];

    % non-transposed data
    % -------------------
    res = tmpMMO.data.x(subs{:});
    if length(finaldim) == 1, finaldim(2) = 1; end;
    res = reshape(res, finaldim);
    if obj.transposed
        if finaldim(end) == 1, finaldim(end) = []; end;
        if length(finaldim) <= 2, res = res';
        else
            res = reshape(res, [finaldim(1)*finaldim(2) finaldim(3)])';
            res = reshape(res, [finaldim(3) finaldim(1) finaldim(2)]);
        end;
    end;


classdef GradientVariationWithRadiusExperiment < handle

    properties (Access = private)
       iMesh
       gExperiment
    end

    properties (Access = private)
       nameCase
       inputFiles
       outputFolder
       levelSetParams
    end

    methods (Access = public)

        function obj = GradientVariationWithRadiusExperiment(s)
            obj.init(s);
        end

        function compute(obj)
            for im = 1:numel(obj.inputFiles)
                obj.iMesh = im;
                obj.createGradientVariationExperiment();
                obj.computeGradientVariationWithRadius();
            end
        end
    end

    methods (Access = private)

        function init(obj,cParams)
            obj.nameCase       = cParams.nameCase;
            obj.inputFiles     = cParams.inputFiles;
            obj.outputFolder   = cParams.outputFolder;
            obj.levelSetParams = cParams.levelSetParams;
        end

        function createGradientVariationExperiment(obj)
            s.inputFile = obj.inputFiles{obj.iMesh};
            s.iMesh     = obj.iMesh;
            s.levelSetParams = obj.levelSetParams;
            g = GradientVariationExperiment(s);
            obj.gExperiment = g;
        end

        function computeGradientVariationWithRadius(obj)
            s.mesh                 = obj.gExperiment.backgroundMesh;
            s.regularizedPerimeter = obj.gExperiment.regularizedPerimeter;
            s.inputFile            = obj.inputFiles{obj.iMesh};
            s.nameCase             = obj.nameCase;
            s.outputFolder         = obj.outputFolder;
            s.domainLength         = obj.gExperiment.domainLength();
            gComputer = GradientVariationWithRadiusComputer(s);
            gComputer.compute();
        end

    end

end


function [warnings,errors] = svargplvmCheckSNR(SNR, errLimit, warLimit, throwError,displ)
% SVARGPLVMCHECKSNR Check Signal to Noise Ratio after
% optimisation, to ensure that the trivial local minimum
% of learning only noise is avoided.
% DESC Check SNR of optimised model
% FORMAT
% ARG SNR: the SNR of optiomised model in a cell array (one cell per
% modality)
% ARG errLimit: Optional, the limit below which an error message
% is printed
% ARG warLimit: Optional, the limit below which a warning message
% is printed
% RETURN warnings: in an array, representing all modalities where
% the SNR is low enough to be considered a warning
%
% COPYRIGHT: Andreas C. Damianou, 2013
%
% VARGPLVM

if nargin < 5 || isempty(displ), displ = true; end
if nargin < 4 || isempty(throwError), throwError = true; end
if nargin < 3 || isempty(warLimit), warLimit = 10; end
if nargin < 2 || isempty(errLimit), errLimit = 2; end
if nargin < 1, error('Not enough arguments given'); end

errStr = sprintf(['\nThis means that a bad local minimum has been reached\n', ...
    'where everything is explained by noise. Please try a different\n', ...
    'initialisation and/or consult the manual.\n']);
warStr = sprintf(['\nThis means that a bad local minimum has been reached\n', ...
    'where most signal is explained by noise. Consider trying a different\n', ...
    'initialisation and/or consult the manual.\n']);

errors = [];
warnings = [];
for i = 1:length(SNR)
    if ~isempty(SNR{i}) && SNR{i} <= errLimit
        errors = [errors i];
    end
end

if ~isempty(errors)
    errMsg = 'Error! Low SNR in modalities: ';
    errMsg = [errMsg num2str(errors)];
    errMsg = [errMsg errStr];
    if displ
        for j=1:length(SNR)
            fprintf('# SNR%d = %.6f\n', j, SNR{j})
        end
    end
    if throwError
        error(errMsg);
    end
else
    for i = 1:length(SNR)
        if ~isempty(SNR{i}) && SNR{i} <= warLimit
            warnings = [warnings i];
        end
    end
end

if ~isempty(warnings) && displ
    warMsg = 'WARNING! Low SNR in modalities: ';
    warMsg = [warMsg num2str(warnings)];
    warMsg = [warMsg warStr];
    warning(warMsg);
end


function incircle()
    %   Matlab script to input initial parameters for circle0 routine
    %   in main Map Window
    % turned into function by Celso G Reyes 2017

    error('replaced by circle_select_dlg');
    ZG=ZmapGlobal.Data; % used by get_zmap_globals

    %                                                R. Zuniga, 6/94

    report_this_filefun();
    %
    if isempty(ZG.newcat),
        ZG.newcat = copy(ZG.primeCatalog);
    end   % verify whether to start with
    % original catalogue
    % make the interface for input
    %
    fig=figure('ToolBar','none');
    clf;
    cla;
    set(fig,'Name','Circle-Map Control Panel');
    %  set(gcf,'visible','off');
    set(gca,'visible','off');
    set(fig,'pos',[ 0.22  0.4 0.30 0.30])

    %
    freq_field1=uicontrol('Style','edit',...
        'Position',[.80 .70 .15 .10],...
        'Units','normalized','String',num2str(ZG.ni),...
        'callback',@callbackfun_001);

    freq_field2=uicontrol('Style','edit',...
        'Position',[.80 .55 .15 .10],...
        'Units','normalized','String',num2str(rad),...
        'callback',@callbackfun_002);

    freq_field3=uicontrol('Style','edit',...
        'Position',[.70 .40 .22 .10],...
        'Units','normalized','String',num2str(ya0,5),...
        'callback',@callbackfun_003);

    freq_field4=uicontrol('Style','edit',...
        'Position',[.70 .25 .22 .10],...
        'Units','normalized','String',num2str(xa0,6),...
        'callback',@callbackfun_004);

    close_button=uicontrol('Style','Pushbutton',...
        'Position',[.05 .85 .15 .1 ],...
        'Units','normalized','Callback',@(~,~)close(),'String','Cancel');

    button1=uicontrol('Style','Pushbutton',...
        'Position',[.35 .15 .3 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_005,...
        'String','Center by Cursor');

    button2=uicontrol('Style','Pushbutton',...
        'Position',[.10 .05 .2 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_006,...
        'String','Fix Radius');

    button3=uicontrol('Style','Pushbutton',...
        'Position',[.70 .05 .3 .1 ],...
        'Units','normalized',...
        'callback',@callbackfun_007,...
        'String','ni Closest Events');

    txt5 = text(...
        'Position',[0. 0.75 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Number of events (ni):');

    txt4 = text(...
        'Position',[0. 0.58 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Radius (km):');

    txt3 = text(...
        'Position',[0. 0.41 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Latitude of center:');

    txt2 = text(...
        'Position',[0. 0.24 0 ],...
        'FontSize',ZmapGlobal.Data.fontsz.m ,...
        'FontWeight','bold',...
        'String','Longitude of center:');

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

    function callbackfun_001(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ZG.ni=str2double(mysrc.String);
    end

    function callbackfun_002(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        rad=str2double(mysrc.String);
    end

    function callbackfun_003(mysrc,myevt)

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

    function callbackfun_004(mysrc,myevt)

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

    function callbackfun_005(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 1;
        circle0;
    end

    function callbackfun_006(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 2;
        circle0;
    end

    function callbackfun_007(mysrc,myevt)

        callback_tracker(mysrc,myevt,mfilename('fullpath'));
        ic = 3;
        circle0;
    end
    function circle0()
        %   "circle0"  selects events by :
        %   the Ni closest earthquakes to the center
        %   the maximum radius of a circle.
        %   the center point can be interactively selected or fixed by given
        %   coordinates (as given by incircle).
        %   Resets ZG.newcat and ZG.newt2.     Operates on the map window on  "primeCatalog".
        %                                                  R.Z. 6/94
        %
        % turned into function by Celso G Reyes 2017

        ZG=ZmapGlobal.Data; % used by get_zmap_globals

        report_this_filefun();

        delete(findobj('Tag','plos1'));
        new = a;
        figure(mess);
        clf
        set(gca,'visible','off')

        if ic == 1 | ic == 0
            te = text(0.01,0.90,'\newlinePlease use the LEFT mouse button or the cursor to \newlineselect the center point. The coordinates of the center \newlinewill be displayed on the control window.\newline \newlineOperates on the main subset of the catalogue. \newlineEvents selected form the new subset to operate on (ZG.newcat).');
            set(te,'FontSize',12);

            % Input center of circle with mouse
            %
            axes(h1)

            [xa0,ya0]  = ginput(1);

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];
            stri = stri1;
            pause(0.1)
            set(gcf,'Pointer','arrow')
            plot(xa0,ya0,'+c');
            incircle

        elseif ic == 2
            figure(map);
            axes(h1)
            ZG.newt2 = ZG.primeCatalog.selectRadius(ya0, xa0, rad,'kilometer');
            %
            % plot events on map as 'x':

            set(gca,'NextPlot','add')
            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');
            set(gcf,'Pointer','arrow')

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6) '; R = ' num2str(rad) ' km'];
            stri = stri1;
            ZG.newt2.sort('Date');
            ZG.newcat = ZG.newt2;                   % resets ZG.newcat and ZG.newt2
            ctp=CumTimePlot(ZG.newt2);
            ctp.plot();

            ic = 1;

        elseif ic == 3
            figure(map);
            axes(h1)
            %  calculate distance for each earthquake from center point
            [ZG.newt2, max_km] = ZG.primeCatalog.selectClosestEvents(ya0, xa0, [], ni);
            messtext = ['Radius of selected Circle: ' num2str(max_km)  ' km' ];
            disp(messtext)

            % plot events on map as 'x':

            set(gca,'NextPlot','add')
            plot(ZG.newt2.Longitude,ZG.newt2.Latitude,'xk','Tag','plos1');
            set(gcf,'Pointer','arrow')

            ZG.newcat = ZG.newt2;                   % resets ZG.newcat

            stri1 = [ 'Circle: ' num2str(xa0,6) '; ' num2str(ya0,6)];
            stri = stri1;
            ctp=CumTimePlot(ZG.newt2);
            ctp.plot();

            ic = 1;

        end      % if ic
    end

end


function WriteMhaFile(filename, img_size, resolution, data_type, offset)
% WRITEMHAFILE  Write the header part of a MetaImage file (.mha)
%
% WRITEMHAFILE(FILENAME, IMG_SIZE, RESOLUTION, DATA_TYPE, OFFSET)
%
%   FILENAME is the path and name of the file to be written, e.g.
%   'foo.mha'.
%
%   IMG_SIZE is a 3-vector with the size of the output volume.
%
%   RESOLUTION is a 3-vector with the voxel size in the 3 directions.
%
%   DATA_TYPE is a string with the data type as given my Matlab, e.g.
%   'uint8', 'short', 'uint16'.
%
%   OFFSET is a vector with the real world coordinates in metres (not index
%   coordinates) of the first voxel in the volume. For example,
%   OFFSET=[0.014552, 0.010486, 0.00142]. By default, OFFSET=[0 0 0].
%
%   See also: WriteRawFile, writemetaimagefile.

% Author(s): Ramon Casero <rcasero@gmail.com> and Vicente Grau
% Copyright © 2009-2012 University of Oxford
% Version: 0.1.1
%
% University of Oxford means the Chancellor, Masters and Scholars of
% the University of Oxford, having an administrative office at
% Wellington Square, Oxford OX1 2JD, UK.
%
% This file is part of Gerardus.
%
% 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. The offer of this
% program under the terms of the License is subject to the License
% being interpreted in accordance with English Law and subject to any
% action against the University of Oxford being under the jurisdiction
% of the English Courts.
%
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>.

% check arguments
error(nargchk(4, 5, nargin, 'struct'));
error(nargoutchk(0, 0, nargout, 'struct'));

% defaults
if (nargin < 5 || isempty(offset))
    offset = [0.0 0.0 0.0];
end

[path, name] = fileparts(filename);

% open file for writing
fid=fopen(filename, 'w');
if(fid<=0)
    fprintf('Impossible to open file %s\n', filename);
end

ndims=numel(resolution);

if(ndims == 3)
    fprintf(fid, 'NDims = 3\n');

    fprintf(fid, 'DimSize = %d %d %d\n', img_size(2), img_size(1), img_size(3));

    if(strcmp(data_type, 'uint8'))
        fprintf(fid, 'ElementType = MET_UCHAR\n');
    elseif(strcmp(data_type, 'short'))
        fprintf(fid, 'ElementType = MET_SHORT\n');
    elseif (strcmp(data_type, 'uint16'))
        fprintf(fid, 'ElementType = MET_USHORT\n');
    else
        error('Not implemented data type')
    end

    fprintf(fid, 'Offset = %1.6f %1.6f %1.6f\n', ...
        offset(1), offset(2), offset(3));

    fprintf(fid, 'ElementSpacing = %1.12f %1.12f %1.12f\n', resolution(1), resolution(2), resolution(3));

elseif(ndims==4)
    fprintf(fid, 'NDims = 4\n');

    fprintf(fid, 'DimSize = %d %d %d %d\n', img_size(2), img_size(1), img_size(3), img_size(4));

    if(strcmp(data_type, 'uint8'))
        fprintf(fid, 'ElementType = MET_UCHAR\n');
    elseif(strcmp(data_type, 'short'))
        fprintf(fid, 'ElementType = MET_SHORT\n');
    elseif (strcmp(data_type, 'uint16'))
        fprintf(fid, 'ElementType = MET_USHORT\n');
    else
        error('Not implemented data type')
    end

    fprintf(fid, 'Offset = %1.6f %1.6f %1.6f\n', ...
        offset(1), offset(2), offset(3));

    fprintf(fid, 'ElementSpacing = %1.12f %1.12f %1.12f %1.12f\n', resolution(1), resolution(2), resolution(3), resolution(4));

end

fprintf(fid, 'ElementByteOrderMSB = False\n');

fprintf(fid, 'ElementDataFile = %s\n', [name, '.raw']);

fclose(fid);