classdef LaunchVehicleSensorReport < matlab.mixin.SetGet
    %LaunchVehicleSensorReport Summary of this class goes here
    %   Detailed explanation goes here

    properties
        sensor AbstractSensor
        lvdData LvdData
    end

    methods
        function obj = LaunchVehicleSensorReport(sensor, lvdData)
            obj.sensor = sensor;
            obj.lvdData = lvdData;
        end

        function [filepath, coverageT, azT, elT, rngT, angleToBoresightT] = generateReport(obj, targets, progressBar, busyStatusLabel, sensorNum, totalSensorNum, reportFolder)
            arguments
                obj(1,1) LaunchVehicleSensorReport
                targets(1,:) AbstractSensorTarget
                progressBar(1,1) wt.ProgressBar
                busyStatusLabel(1,1) matlab.ui.control.Label
                sensorNum(1,1) double
                totalSensorNum(1,1) double
                reportFolder(1,1) string
            end

            progressBar.Indeterminate = false;
            progressBar.startProgress('');
            busyStatusLabel.Text = sprintf('Generating Data for Sensor "%s" [%u of %u]', obj.sensor.getListboxStr(), sensorNum, totalSensorNum);

            bodyInfos = obj.lvdData.celBodyData.getAllBodyInfo();
            stateLog = obj.lvdData.stateLog;

            entries = stateLog.getAllEntries();
            times = [entries.time]';
            coverages = cell(1,numel(targets));
            sensorAzs = cell(1,numel(targets));
            sensorEls = cell(1,numel(targets));
            sensorRngs = cell(1,numel(targets));
            sensorAnglesToBoresight = cell(1,numel(targets));
            for(i=1:length(entries))
                entry = entries(i);

                sensorState = entry.getSensorStateForSensor(obj.sensor);
                scElem = entry.getCartesianElementSetRepresentation(false);
                dcm = entry.attitude.dcm;
                frame = entry.centralBody.getBodyCenteredInertialFrame();

                results = obj.sensor.evaluateSensorTargets(sensorState, targets, scElem, dcm, bodyInfos, frame);

                for(j=1:length(results))
                    result = results(j);

                    coverages{j} = vertcat(coverages{j}, result.resultsBool(:)');

                    [az, el, rng, angle] = result.getBoresightRelativeAngles(sensorState, scElem, dcm);

                    sensorAzs{j} = vertcat(sensorAzs{j}, az);
                    sensorEls{j} = vertcat(sensorEls{j}, el);
                    sensorRngs{j} = vertcat(sensorRngs{j}, rng);
                    sensorAnglesToBoresight{j} = vertcat(sensorAnglesToBoresight{j}, angle);
                end

                progressBar.setProgress(i/length(entries), sprintf('%0.3f %%', 100*i/length(entries)));
            end

            progressBar.Indeterminate = true;
            busyStatusLabel.Text = sprintf('Writing Report File for Sensor "%s" [%u of %u]', obj.sensor.getListboxStr(), sensorNum, totalSensorNum);
            progressBar.setProgress(1, '');
            drawnow;

            coverageT = {};
            filename = sprintf('SensorReport_%s_%s.xls', obj.sensor.getListboxStr(),datestr(now, 'YYYYmmDD_HHMMss'));
            filepath = fullfile(reportFolder, filename);
            for(i=1:length(coverages))
                coverage = coverages{i};

                %compute instant and cumulative coverage
                instantCoverage = NaN(height(coverage), 1);
                cumCoverage = NaN(height(coverage), 1);
                for(j=1:height(coverage))
                    subCoverage = coverage(j,:);
                    instantCoverage(j) = sum(subCoverage) / numel(subCoverage);

                    subCoverage = coverage(1:j,:);
                    sumSubCoverage = sum(subCoverage,1);
                    sumSubCoverage(sumSubCoverage >= 1) = 1;
                    cumCoverage(j) = sum(sumSubCoverage) / numel(sumSubCoverage);
                end

                target = targets(i);
                labelStrs = target.getTargetPtLabelStrs();

                %Info worksheet
                sensorNums = sensorNum * ones(numel(targets),1);
                sensorNames = repmat(string(obj.sensor.getListboxStr()), numel(targets), 1);
                targetNums = [1:numel(targets)]'; %#ok<NBRAK>
                for(j=1:length(targets))
                    targetNames(j,1) = string(targets(j).getListboxStr()); %#ok<AGROW>
                end

                varNames = {'Sensor Number', 'Sensor Name', 'Target Number', 'Target Name'};
                data = table(sensorNums, sensorNames, targetNums, targetNames, 'VariableNames',varNames);
                writetable(data, filepath, 'FileType','spreadsheet', 'Sheet','Information');

                %Sensor Coverage
                worksheetName = sprintf('Coverage, Sensor %u Target %u', sensorNum, i);

                header = horzcat('Time [UT sec]', labelStrs, "Instantaneous Coverage Fraction", "Cumulative Coverage Fraction");
                data = horzcat(times, coverage, instantCoverage, cumCoverage);

                coverageT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>

                %Sensor to Target Az
                worksheetName = sprintf('Azimuth, Sensor %u Target %u', sensorNum, i);

                header = horzcat('Time [UT sec]', labelStrs);
                data = horzcat(times, rad2deg(sensorAzs{i}));

                azT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>

                %Sensor to Target El
                worksheetName = sprintf('Elevation, Sensor %u Target %u', sensorNum, i);

                header = horzcat('Time [UT sec]', labelStrs);
                data = horzcat(times, rad2deg(sensorEls{i}));

                elT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>

                %Sensor to Target Range
                worksheetName = sprintf('Range, Sensor %u Target %u', sensorNum, i);

                header = horzcat('Time [UT sec]', labelStrs);
                data = horzcat(times, sensorRngs{i});

                rngT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>

                %Sensor to Target Range
                worksheetName = sprintf('Angle, Sensor %u Target %u', sensorNum, i);

                header = horzcat('Time [UT sec]', labelStrs);
                data = horzcat(times, rad2deg(sensorAnglesToBoresight{i}));

                angleToBoresightT{i} = writeDataTableToXLSFile(data, header, filepath, worksheetName); %#ok<AGROW>
            end
        end
    end
end

function T = writeDataTableToXLSFile(data, header, filename, worksheetName)
    T = array2table(data);
    T.Properties.VariableNames = header;

    userdata.WorksheetName = worksheetName;
    T.Properties.UserData = userdata;

    writetable(T, filename, 'FileType','spreadsheet', 'Sheet',worksheetName);
end


%  Copyright (c) 2014, Karen Simonyan
%  All rights reserved.
%  This code is made available under the terms of the BSD license (see COPYING file).

function [res, extra] = eval(config, scores, gt)

    % predicted labels
    class = 2 * (scores >= config.threshold) - 1;

    % class-n accuracy
    res = mean(class == gt) * 100;

    extra = [];
end


function [X, varX, model, grChek] = svargplvmOptimisePoint(model, vardistx, y, display, iters, varargin)

% SVARGPLVMOPTIMISEPOINT Optimise the postion of one or more latent points
% given observations from 1 or more modalities
% FORMAT
% DESC optimises the location of a group of points in latent space
% given an initialisation and the corresponding observed data point.
% ARG model : the MRD model for which the point will be optimised.
% ARG vardistx : the initialisation of the points in the latent space.
% ARG y : the observed data points for which the latent points are to
% be optimised.
% ARG display : whether or not to display the iterations of the
% optimisation (default: true)
% ARG iters : maximum number of iterations for the optimisation
% (default 2000).
% RETURN x : the optimised means in the latent space.
% RETURN varx : the optimised variances in the latent space.
% RETURN model: the model which is augmented to also include the new test
% points and the quantities that change because of these, as there is
% coupling in the dynamics case.

%
% COPYRIGHT :  Andreas Damianou, 2013
%
% SEEALSO : vargplvmOptimisePoint

% VARGPLVM

grChek = [];

if nargin < 5 || isempty(iters), iters = 2000; end
if nargin < 4 || isempty(display), display = true; end

options = optOptions;
if display
    options(1) = 1;
    % options(9) = 1; % gradchek
end
options(14) = iters;

if isfield(model, 'optimiser')
    optim = str2func(model.optimiser);
else
    optim = str2func('scg');
end

if isfield(model, 'dynamics') && ~isempty(model.dynamics)
    % TODO
    error('Not implemented for dynamical case')
else
    x = vardistExtractParam(vardistx);
end

if ~(isfield(model, 'dynamics') && ~isempty(model.dynamics))
    model.DgtN_test = true;
    for i = model.testModalities
        % Perform precomputations which will result in faster execution. This
        % happens in two stages:
        % a) Precomputing constants only once here, instead in every call of
        % the objective and grad
        % b) Replace model.m with a reduced rank representation, since it only
        % appears in the expression model.m * model.m'. This is the same tricks
        % used in vargplvmCreate for DgtN flag.
        % TODO: Do the same for dynamics case
        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN
            mOrig{i} = model.comp{i}.m;
        end
        model.comp{i}.testPrecomp.indexMissing = find(isnan(y{i}(1,:)));
        indexPresent = setdiff(1:model.comp{i}.d, model.comp{i}.testPrecomp.indexMissing );
        y{i} = y{i}(:,indexPresent);
        P = model.comp{i}.P1 * (model.comp{i}.Psi1' * model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing));
        model.comp{i}.testPrecomp.TrPP = sum(sum(P .* P));
        model.comp{i}.testPrecomp.TrYY = sum(sum(model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing) .* model.comp{i}.m(:,model.comp{i}.testPrecomp.indexMissing)));
        y{i} = y{i} - repmat(model.comp{i}.bias(indexPresent),size(y{i},1),1);
        y{i} = y{i}./repmat(model.comp{i}.scale(indexPresent),size(y{i},1),1);
        mPres = model.comp{i}.m(:, indexPresent);
        mPres = [mPres; y{i}];
        YYT = mPres * mPres'; % NxN
        [U S V]=svd(YYT);
        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN
            model.comp{i}.testPrecomp.mReduced=U*sqrt(abs(S));
        end
        model.comp{i}.testPrecomp.TrYY2 = sum(diag(YYT)); % scalar

        % For grads
        mPresGrad = [y{i}; model.comp{i}.m(:, indexPresent)];
        YYT = mPresGrad * mPresGrad'; % NxN
        [U S V]=svd(YYT);
        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN
            model.comp{i}.testPrecomp.mReducedGrad=U*sqrt(abs(S));
        end
        model.comp{i}.testPrecomp.mY = mPresGrad*y{i}';
        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN
            model.comp{i}.m = []; % Less overhead in passing arguments (pass by value)
        end
    end
else
    model.comp.DgtN_test = false;
end

if length(varargin) == 2
    if strcmp(varargin{1}, 'gradcheck')
        assert(islogical(varargin{2}));
        %options(9) = varargin{2};
        doGradchek = varargin{2};
        if doGradchek
            [gradient, delta] = feval('gradchek', vardistExtractParam(vardistx), @svargplvmPointObjective, @svargplvmPointGradient, model, y);
            deltaf = gradient - delta;
            d=norm(deltaf - gradient)/norm(gradient + deltaf); %%
            d1=norm(deltaf - gradient,1)/norm(gradient + deltaf,1); %%
            grRatio = sum(abs(gradient ./ deltaf)) / length(deltaf);
            fprintf(1,' Norm1 difference: %d\n Norm2 difference: %d\n Ratio: %d\n',d1,d, grRatio);
            grChek = {delta, gradient, deltaf, d, d1};
        else
            grChek = [];
        end
    end
end

if iters > 0
    if strcmp(func2str(optim), 'optimiMinimize')
        % Carl Rasmussen's minimize function
        x = optim('vargplvmPointObjectiveGradient', x, options, model, y);
    else
        % NETLAB style optimization.
        x = optim('svargplvmPointObjective', x,  options, ...
            'svargplvmPointGradient', model, y);
    end
end

if isfield(model, 'dynamics') && ~isempty(model.dynamics)
    if isfield(model.dynamics, 'reoptimise') && model.dynamics.reoptimise   %%% RE-OPT-CODE-NEW
        % Expand and update the model.                                      %%% RE-OPT-CODE-NEW
        % In this case, x is [mu_bar lambda theta_t X_u]                    %%% RE-OPT-CODE-NEW
        [vardistx, model] = vargplvmPartExpand(model, x, 1);                %%% RE-OPT-CODE-NEW
    else %%% RE-OPT-CODE-NEW
        % now separate the variational disribution into the training part and the
        % testing part and update the original training model (only with the new training
        % variational distribution) and the test variational distribution
        % this is doing the expand
        x = reshape(x, vardist.numData, model.dynamics.q*2);
        xtrain = x(1:model.N,:);
        xtest = x(model.N+1:end,:);
        model.dynamics.vardist = vardistExpandParam(model.dynamics.vardist, xtrain);
        vardistx = vardistExpandParam(model.vardistx, xtest);
    end %%% RE-OPT-CODE-NEW
else
    vardistx = vardistExpandParam(vardistx,x);
end

X = vardistx.means;
varX = vardistx.covars;

if ~(isfield(model, 'dynamics') && ~isempty(model.dynamics))
    model = rmfield(model, 'DgtN_test');
    for i=model.testModalities
        model.comp{i} = rmfield(model.comp{i}, 'testPrecomp');
        if isfield(model.comp{i}, 'DgtN') && model.comp{i}.DgtN
            model.comp{i}.m = mOrig{i};
        end
    end
end


function im1 = cropImage(im,center,scale)

w = 200*scale;
h = w;
x = center(1) - w/2;
y = center(2) - h/2;
bbox = [x,y,w,h];
padsize = round(bbox(3:4));
im = padarray(im,padsize,0);
im1 = imcrop(im,[bbox(1:2)+padsize,bbox(3:4)]);
im1 = imresize(im1,[200,200]);


function view = setBrightness(view,val);
%
% view = setBrightness(view,[val]);
%
% Set the brightness of a view, by
% changing the color maps in each
% view mode. Only those parts which
% are used for the anatomical underlay
% image (the first 1:numGrays entries)
% are brightened -- the overlays are
% unchanged.
%
% Val can range from 0 to 1. If omitted,
% it is read off of the view's brightness
% slider (so hopefully, in these circumstances,
% it has one).
%
%
% ras 01/05.
if notDefined('val')
    val = get(view.ui.brightness.sliderHandle,'Value');
end

setSlider(view,view.ui.brightness,val);

numGrays = view.ui.mapMode.numGrays;
cmap = gray(numGrays);

delta = 2*val - 1;
if delta ~= 0
    cmap = brighten(cmap,delta);
end

view.ui.anatMode.cmap = cmap;
view.ui.ampMode.cmap(1:numGrays,:) = cmap;
view.ui.phMode.cmap(1:numGrays,:) = cmap;
view.ui.coMode.cmap(1:numGrays,:) = cmap;
view.ui.mapMode.cmap(1:numGrays,:) = cmap;

view = refreshScreen(view, 1);

return


function [net, info] = cnn_plate()
global datadir;
startup;
if exist(opts.imdbPath,'file')
    imdb=load(opts.imdbPath);
else
    imdb=cnn_plate_setup_data(datadir);
    mkdir(opts.expDir) ;
    save(opts.imdbPath, '-struct', 'imdb') ;
end
net=cnn_plate_init();
net.meta.normalization.averageImage =imdb.images.data_mean ;
opts.train.gpus=1;
[net, info] = cnn_train(net, imdb, getBatch(opts), ...
  'expDir', opts.expDir, ...
  net.meta.trainOpts, ...
  opts.train, ...
  'val', find(imdb.images.set == 3)) ;

function fn = getBatch(opts)
% --------------------------------------------------------------------
    fn = @(x,y) getSimpleNNBatch(x,y) ;
end
function [images, labels]  = getSimpleNNBatch(imdb, batch)
    images = imdb.images.data(:,:,:,batch) ;
    labels = imdb.images.labels(1,batch) ;
    if opts.train.gpus > 0
        images = gpuArray(images) ;
    end
end
end


function obj = addpoints(obj, xyz, varargin)
% Plots points on fmridisplay objects (e.g., montages of slices)
%
% :Usage:
% ::
%
%     newax = addpoints(obj, xyz, varargin)
%
% Registers handles with the object (referred to as obj)
%
% - enter xyz as n x 3 list of coordinates in mm to plot (world space)
% - Points or text labels or both
% - Flexible slice spacing, colors, marker sizes/styles, axis layout (one row/standard square)
% - axial, saggital, or coronal orientation handled automatically
% - Multiple different sets of points can be plotted in different colors/text labels
%
% :Optional Inputs:
%
% Takes all inputs of plot_points_on_slice.  See help for additional
% documentation of options.
%
%   **{'text', 'textcodes'}:**
%        cell array of text values corresponding to points
%
%   **{'condf' 'colorcond'}:**
%        vector of integers to define color conditions
%
%   **'close_enough':**
%        mm within which to plot; defined automatically based on slice distance if not entered
%
%   **'color':**
%        string, 'b', or vector, [1 0 0], to define colors; cell if condf is used, e.g., {'b' 'g'}
%
%   **{'marker', 'MarkerStyle'}:**
%        e.g., 'o', 'v', 's'
%
%   **{'MarkerSize', 'markersize'}:**
%
%   **{'MarkerFaceColor', 'markerfacecolor'}:**
%        see color above
%
% :Examples:
%
% Plot points (i.e., coordinate locations) for xyz coords:
% ::
%
%    o2 = addpoints(o2, DB.xyz, 'MarkerFaceColor', 'b', 'Marker', 'o', 'MarkerSize', 4);
%    o2 = addpoints(o2, DB.xyz, 'text', DB.textcodes, 'condf', DB.condf, 'color', {'b' 'g'});
%    o2 = removepoints(o2);

wh_montage = 1:length(obj.montage); % select which montages; default = all

whm = strcmp(varargin, 'wh_montages') | strcmp(varargin, 'wh_montage') | strcmp(varargin, 'which_montages') | strcmp(varargin, 'which montages');
if any(whm)
    whm = find(whm);
    wh_montage = varargin{whm(1) + 1};
end

% Montages
% -------------------------------------------------------------------------

for i = wh_montage

    if ~isfield(obj.montage{i}, 'plotted_point_handles') || isempty(obj.montage{i}.plotted_point_handles)

        obj.montage{i}.plotted_point_handles = [];

    end

    % Plot it
    pointhan = plotpoints(xyz, obj.montage{i}, varargin{:});

    obj.montage{i}.plotted_point_handles = [obj.montage{i}.plotted_point_handles pointhan];

end

end  % main function

function pointhan = plotpoints(xyz, montagestruct, varargin)

% fixed fields

myview = montagestruct.orientation;
slicemm = montagestruct.slice_mm_coords;
axhan = montagestruct.axis_handles;

% optional inputs

textcodes = [];
texthandles = [];
condf = [];

close_enough = min(diff(slicemm)) ./ 2;
if isempty(close_enough), close_enough = 8; end

color = 'k';
marker = 'o';
markersize = 12;
markerfacecolor = 'k';

% ------------------------------------------------------
% parse inputs
% ------------------------------------------------------

for i = 1:length(varargin)
    if ischar(varargin{i})
        switch varargin{i}
            % reserved keywords

            case {'text', 'textcodes'} % do not pass on to slice plot...
                textcodes = varargin{i + 1};
                varargin{i+1} = [];
                varargin{i} = [];

            case {'condf' 'colorcond'}, condf = varargin{i + 1};

            case 'close_enough', close_enough = varargin{i + 1};

            case {'Color','color'} % do not pass on...
                color = varargin{i+1};
                varargin{i+1} = [];
                varargin{i} = [];

            case {'marker', 'Marker', 'MarkerStyle'}, marker = varargin{i+1}; varargin{i+1} = [];

            case {'MarkerSize', 'markersize'}, markersize = varargin{i+1}; varargin{i+1} = [];

            case {'MarkerFaceColor', 'markerfacecolor'}, markerfacecolor = varargin{i+1}; varargin{i+1} = [];

            otherwise, warning(['Unknown input string option:' varargin{i}]);
        end
    end
end

% SETUP
% -----------------------------------------------

fprintf('Plotting points within %3.2f mm of slices\n', close_enough);

if isempty(condf)
    condf = ones(size(xyz, 1), 1);

    if iscell(color)
        error('Color should not be a cell array.');
    end
    color = {color};

else
    if ~iscell(color)
        error('When entering condf, enter colors cell with same number of entries.');
    end
end

u = unique(condf);
n = length(u);

% Do the work for each slice
% -----------------------------------------------

pointhan = [];

for i = 1:length(axhan)
    axes(axhan(i));

    for j = 1:n % For each color code

        % Select coordinates (2D) for plot
        slicexyz = xyz;

        switch myview
            case 'axial'
                whcol = 3;

            case {'sagg', 'sagittal', 'saggital'}

                whcol = 1;

            case {'cor', 'coronal'}

                whcol = 2;

            otherwise
                error('Unknown slice orientation.')
        end

        wh_to_plot = condf == u(j) & abs(slicexyz(:, whcol) - slicemm(i)) <= close_enough;

        slicexyz = slicexyz(wh_to_plot, :);

        slicexyz(:, whcol) = [];

        if ~isempty(slicexyz)

            if isempty(textcodes)

                pointhan(end + 1) = plot(slicexyz(:, 1), slicexyz(:, 2), '.', 'color', color{j}, 'Marker', marker, 'MarkerSize', markersize, 'MarkerFaceColor', markerfacecolor);

            else
                my_text = textcodes(wh_to_plot);

                pointhan = [pointhan plottext(slicexyz(:, 1), slicexyz(:, 2), my_text, color{j}, myview)];

            end

        end

    end % condition color codes

end % slices

end % function

function texthandles = plottext(x, y, textcodes, color, orientation)

% adjust for font placement
switch orientation
    case 'sagittal'
        xshift = 6;
    case 'axial'
        xshift = -6;

end

texthandles = [];
for j = 1:length(textcodes)
    % text labels

    if ischar(color)

        texthandles(j) = text(x(j) + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');

    else
        texthandles(j) = text(x(j)  + xshift, y(j), textcodes{j},'Color',color,'FontSize',12,'FontWeight','bold');

    end

end

end % plottext


function varargout = spectral_mva(varargin)
% SPECTRAL_MVA M-file for spectral_mva.fig
%      SPECTRAL_MVA is a GUI for running Multivariate analysis of spectroscopic data
%
%      Initially designed for analysis of X-ray Photoelectron spectra, can
%      analys any type of datatables, containing spectra or any other data
%
%      Opens MAT files with or without a variable X
%      Opens VMS files (XPS spectra) either from original vision software or CASAXPS software
%
%      Preprocessing options of SMOOTHING, NORMALIZING, DERIVATIZING and SHIFTING spectra
%
%      Three MVA methods - PCA, SIMPLISMA and MCR
%      PLS_TOOLBOX from Eigenvector is a must
%
%       created by K.Artyushkova
%      kartyush@unm.edu
%      last update -06/21/2007
% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @spectral_mva_OpeningFcn, ...
                   'gui_OutputFcn',  @spectral_mva_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin & isstr(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before spectral_mva is made visible.
function spectral_mva_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to spectral_mva (see VARARGIN)

% Choose default command line output for spectral_mva
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);
plotgui

% UIWAIT makes spectral_mva wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = spectral_mva_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --------------------------------------------------------------------
function open_vms_Callback(hObject, eventdata, handles)
% hObject    handle to open_vms (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename, pathname]=uigetfiles('*.vms','Open vms files');
cd(pathname)
[N,M]=size(filename);
if M==1;
    [BE,data]=vms_sp_read(char(filename(:,1)),0);
else
    [BE, data(:,M)]=vms_sp_read(char(filename(:,1)),0);
     for i=2:M
    [BE, data(:,i-1)]=vms_sp_read(char(filename(:,i)),0);
end
end

handles.or_sp=data;
handles.data=data;
handles.BE=BE;
handles.BE_or=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function open_mat_Callback(hObject, eventdata, handles)
% hObject    handle to open_mat (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=lddlgpls('*','load spectra');
BE=lddlgpls('*','load BE - click cancel if no BE to load')
a=isempty(BE);
    if a==1
    h= warndlg('The Binding energy range is absent and will be generated automaticaly','Opening MAT file');
    pause(3)
    [n,m]=size(data);
    BE=[n:-1:1]';
    axes(handles.axes1)
reverplot(BE,data)
    else

    BE=BE;
    axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
end
    handles.or_sp=data;
    handles.BE_or=BE;
    handles.data=data;
    handles.BE=BE;
guidata(hObject,handles)

% --------------------------------------------------------------------
function save_spectra_Callback(hObject, eventdata, handles)
% hObject    handle to save_spectra (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
datapath = uigetdir;
cd(datapath)
spectra=handles.data;
BE=handles.BE;
[filename, pathname] = uiputfile('*.mat', 'Save images as');
save(filename)

% --- Executes during object creation, after setting all properties.
function spectrum_selection_CreateFcn(hObject, eventdata, handles)
% hObject    handle to spectrum_selection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: slider controls usually have a light gray background, change
%       'usewhitebg' to 0 to use default.  See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
    set(hObject,'BackgroundColor',[.9 .9 .9]);
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

% --- Executes on slider movement.
function spectrum_selection_Callback(hObject, eventdata, handles)
% hObject    handle to spectrum_selection (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Value') returns position of slider
%        get(hObject,'Min') and get(hObject,'Max') to determine range of slider

data=handles.data;
BE=handles.BE;
[n,m]=size(data);

set(handles.Min,'string',1);
set(handles.Max,'string',m);

step=1/m;
slider_step(1)=step;
slider_step(2)=step;
if step==1;
    set(handles.spectrum_selection, 'SliderStep', slider_step, 'Max', 2, 'Min',0,'Value',1)
    i=1;
else
    set(handles.spectrum_selection, 'SliderStep', slider_step, 'Max', m, 'Min',0)
    i=get(hObject,'Value');
    i=round(i);
    if i==0
        i=1;
    elseif i>=m
        i=m;
    else i=i;
    end
end
set(handles.current,'string',i);
axes(handles.axes1)
plot(BE,data(:,i))
set(gca,'Xdir','reverse')
handles.N=i;
%guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function Number_comps_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Number_comps (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function Number_comps_Callback(hObject, eventdata, handles)
% hObject    handle to Number_comps (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Number_comps as text
%        str2double(get(hObject,'String')) returns contents of Number_comps as a double

Npca=str2double(get(hObject,'String')) ;
handles.Npca=Npca;
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function scal_pca_CreateFcn(hObject, eventdata, handles)
% hObject    handle to scal_pca (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

% --- Executes on button press in pca_button.
function pca_button_Callback(hObject, eventdata, handles)
% hObject    handle to pca_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

Npca=handles.Npca;
data=handles.data;
s=preprocess;
options.preprocessing=s;
options.display='off';
options.plots='final';
model=pca(data, Npca,options);
handles.model=model;
guidata(hObject,handles)

% --- Executes on button press in display_loads.
function display_loads_Callback(hObject, eventdata, handles)
% hObject    handle to display_loads (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
model=handles.model;
plotloads(model)

% --- Executes on button press in disp_score_pca.
function disp_score_pca_Callback(hObject, eventdata, handles)
% hObject    handle to disp_score_pca (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
model=handles.model;
plotscores(model)

% --------------------------------------------------------------------
function save_pca_Callback(hObject, eventdata, handles)
% hObject    handle to save_pca (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
model=handles.model;
BE=handles.BE;
scores=model.loads{1};
loads=model.loads{2};
datapath = uigetdir;
cd(datapath)
[filename, pathname] = uiputfile('*.mat', 'Save results as');
save(filename)

% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function Untitled_3_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function normalize_Callback(hObject, eventdata, handles)
% hObject    handle to normalize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=handles.data;
BE=handles.BE;
[m,n]=size(data);
axes(handles.axes1)
plot(data)
[x,y] = gselect('x');
for i=1:n
        K(i)=data(x,i)/100;
        data_n(:,i)=data(:,i)/K(i);
end

data=data_n;
handles.data_n=data;
handles.data=data_n;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function derivatize_Callback(hObject, eventdata, handles)
% hObject    handle to derivatize (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=handles.data;
BE=handles.BE;
[m,n]=size(data);
type=questdlg('Which derivative you wnat to apply?','Derivatization','1st', '2nd', '1st');
N=inputdlg('Enter the width of smoothing window');
N=str2double(N);
if type=='1st'
    for i=1:n
     data_d(i,:) = savgol(data(:,i)',N, 2 ,1);
 end
else
    for i=1:n
     data_d(i,:) = savgol(data(:,i)',N, 2 ,2);
 end
end
data=data_d';
handles.data_d=data;
handles.data=data;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Undo_normalization_Callback(hObject, eventdata, handles)
% hObject    handle to Undo_normalization (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=handles.or_sp;
BE=handles.BE_or;
handles.data=data;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function undo_deriv_Callback(hObject, eventdata, handles)
% hObject    handle to undo_deriv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.or_sp;
BE=handles.BE_or;
handles.data=data;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Untitled_2_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function smooth_Callback(hObject, eventdata, handles)
% hObject    handle to smooth (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
data=handles.data;
BE=handles.BE;
[m,n]=size(data);
N=inputdlg('Enter the odd width of smoothing window > 3 - larger window causes more smoothing');
N=str2double(N);
for i=1:n
     data_s(i,:) = savgol(data(:,i)',N, 2 ,0);
end
data=data_s';
handles.data_s=data;
handles.data=data;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function opencasavms_Callback(hObject, eventdata, handles)
% hObject    handle to opencasavms (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[filename, pathname]=uigetfiles('*.vms','Open vms files');
cd(pathname)
[N,M]=size(filename);
if M==1;
    [BE,data]=vms_sp_read_casa(char(filename(:,1)),0);
else
    [BE, data(:,M)]=vms_sp_read_casa(char(filename(:,1)),0);
     for i=2:M
    [BE, data(:,i-1)]=vms_sp_read_casa(char(filename(:,i)),0);
end
end

handles.or_sp=data;
handles.data=data;
handles.BE=BE;
handles.BE_or=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --- Executes on button press in Plot_gui.
function Plot_gui_Callback(hObject, eventdata, handles)
% hObject    handle to Plot_gui (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data(:,1)=handles.BE;
temp=handles.data;
[n,m]=size(temp);
data(:,2:m+1)=handles.data;
H.Position=[262 118 560 335];
figure(H)
plotgui(data);
set(gca,'Xdir','reverse')
handles.H=H;
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function Nsimp_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Nsimp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function Nsimp_Callback(hObject, eventdata, handles)
% hObject    handle to Nsimp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Nsimp as text
%        str2double(get(hObject,'String')) returns contents of Nsimp as a double
Nsimp=str2double(get(hObject,'String'));
handles.der=0;
handles.Nsimp=Nsimp;
guidata(hObject,handles)

% --- Executes on button press in simplisma_main.
function simplisma_main_Callback(hObject, eventdata, handles)
% hObject    handle to simplisma_main (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
offset=handles.offset;
Nsimp=handles.Nsimp;
der=handles.der;
data=handles.data;
BE=handles.BE;
if der==0
    [purspec,purint,purity_spec]=simplisma(data',BE, offset,Nsimp);
else
   data2=invder(data');
   [purspec,purint,purity_spec]=simplisma(data',BE, offset,Nsimp,data2);
end

model=handles.model;
modelsimp=model;
modelsimp.loads{1}=purspec';
modelsimp.loads{2}=purint;
handles.modelsimp=modelsimp;
guidata(hObject,handles)

% --- Executes on button press in simp_disp_spectr.
function simp_disp_spectr_Callback(hObject, eventdata, handles)
% hObject    handle to simp_disp_spectr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
modelsimp=handles.modelsimp;
plotscores(modelsimp)

% --- Executes on button press in simp_disp_int.
function simp_disp_int_Callback(hObject, eventdata, handles)
% hObject    handle to simp_disp_int (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
modelsimp=handles.modelsimp;
plotloads(modelsimp)

% --- Executes during object creation, after setting all properties.
function simp_offset_CreateFcn(hObject, eventdata, handles)
% hObject    handle to simp_offset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function simp_offset_Callback(hObject, eventdata, handles)
% hObject    handle to simp_offset (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of simp_offset as text
%        str2double(get(hObject,'String')) returns contents of simp_offset as a double

offset=str2double(get(hObject,'String')) ;
handles.offset=offset;
guidata(hObject,handles)

% --- Executes on button press in simpl_2nd.
function simpl_2nd_Callback(hObject, eventdata, handles)
% hObject    handle to simpl_2nd (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of simpl_2nd

der=get(hObject,'Value');
handles.der=der;
guidata(hObject,handles)

% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end

function edit8_Callback(hObject, eventdata, handles)
% hObject    handle to edit8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit8 as text
%        str2double(get(hObject,'String')) returns contents of edit8 as a double

% --- Executes on button press in mcr_main.
function mcr_main_Callback(hObject, eventdata, handles)
% hObject    handle to mcr_main (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.data;
[n,m]=size(data);
opt=questdlg('Which intialization you want to use?','MCR','Random   ', 'PCA      ', 'Simplisma', 'Random   ');
if opt=='Random   ';
    N=inputdlg('Enter the number of components');
    Nmcr=str2double(N);
    c0=rand(Nmcr,n);
elseif opt=='PCA      '
    model=handles.model;
    c0=model.loads{1}';
else
    model=handles.modelsimp;
    c0=model.loads{1}';
end

opt=questdlg('Do you want to apply nonnegativity to Concentrations?','MCR','Yes', 'No ', 'Yes');
if opt=='Yes'
   options.ccon='nonneg';
else
   options.ccon='none';
end

opt=questdlg('Do you want to apply nonnegativity to Spectra?','MCR','Yes', 'No ', 'Yes');
if opt=='Yes'
   options.scon='nonneg';
else
   options.scon='none';
end
options.display='off';
options.plots='final';
modelmcr = mcr(data',c0,options);
handles.modelmcr=modelmcr;
guidata(hObject,handles)

% --- Executes on button press in mcr_disp_sp.
function mcr_disp_sp_Callback(hObject, eventdata, handles)
% hObject    handle to mcr_disp_sp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
modelmcr=handles.modelmcr;
plotscores(modelmcr)

% --- Executes on button press in mcr_disp_int.
function mcr_disp_int_Callback(hObject, eventdata, handles)
% hObject    handle to mcr_disp_int (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
modelmcr=handles.modelmcr;
plotloads(modelmcr)

% --------------------------------------------------------------------
function save_simpl_Callback(hObject, eventdata, handles)
% hObject    handle to save_simpl (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
modelsimp=handles.modelsimp;
BE=handles.BE;
scores=modelsimp.loads{1};
loads=modelsimp.loads{2};
datapath = uigetdir;
cd(datapath)
[filename, pathname] = uiputfile('*.mat', 'Save results as');
save(filename)

% --------------------------------------------------------------------
function save_mcr_Callback(hObject, eventdata, handles)
% hObject    handle to save_mcr (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

modelmcr=handles.modelmcr;
BE=handles.BE;
scores=modelmcr.loads{1};
loads=modelmcr.loads{2};
datapath = uigetdir;
cd(datapath)
[filename, pathname] = uiputfile('*.mat', 'Save results as');
save(filename)

% --------------------------------------------------------------------
function save_Callback(hObject, eventdata, handles)
% hObject    handle to save (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

modelpca=handle.model;
modelsimp=handles.modelsimp;
modelmcr=handles.modelmcr;
data=handles.data
BE=handles.BE;
datapath = uigetdir;
cd(datapath)
[filename, pathname] = uiputfile('*.mat', 'Save results as');
save(filename)

% --------------------------------------------------------------------
function open_casa_Callback(hObject, eventdata, handles)
% hObject    handle to open_casa (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

M = inputdlg('how many txt files to open?');
M=str2double(M);
if M==1;
    [datafile,datapath] = uigetfile('*.*','Choose a vms file');
    cd(datapath)
    [n,BE,data,d]=textread(datafile,'%f%f%f%f','headerlines',4);

else
    prompt={'BE1:','BE2:'};
     def={'295','282'};
     dlgTitle='Enter the starting and enegind BE for the spectra';
     lineNo=1;
     answer=inputdlg(prompt,dlgTitle,lineNo,def);
     N=str2double(answer);
    for i=1:M
      [datafile,datapath] = uigetfile('*.*','Choose a vms file');
      cd(datapath)
     [n,BE,temp,d]=textread(datafile,'%f%f%f%f','headerlines',4);
     [i1,y]=find(BE==N(1));
     [i2,y]=find(BE==N(2));
     data(:,i)=temp(i1:i2);
 end
 BE=BE(i1:i2);
end

handles.or_sp=data;
handles.data=data;
handles.BE=BE;
handles.BE_or=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --- Executes on button press in reverse.
function reverse_Callback(hObject, eventdata, handles)
% hObject    handle to reverse (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

H=handles.H;
figure(1)
set(gca,'Xdir','reverse')

% --- Executes when figure1 window is resized.
function figure1_ResizeFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function Calibrate_Callback(hObject, eventdata, handles)
% hObject    handle to Calibrate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.data;
BE=handles.BE_or;
handles.BE_or_un=BE;
handles.or_sp_un=data;
C=inputdlg('Which binding energy to use for calibration? Example: 285 or 284.8');
C=str2double(C);
[x_sh, y_sh]=shift_spectra(data, BE,C);
data=y_sh;
BE=x_sh;
handles.or_sp=data;
handles.BE_or=BE;
handles.data=data;
handles.BE=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Undo_calibrate_Callback(hObject, eventdata, handles)
% hObject    handle to Undo_calibrate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.or_sp_un;
handles.or_sp=data;
BE=handles.BE_or_un;
handles.data=data;
handles.BE_or=BE;
handles.BE=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function open_vms2_Callback(hObject, eventdata, handles)
% hObject    handle to open_vms2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[filename, pathname]=uigetfiles('*.vms','Open vms files');
cd(pathname)
[N,M]=size(filename);
if M==1;
    [BE,data]=vms_sp_read2(char(filename(:,1)),0);
else
    [BE, data(:,1)]=vms_sp_read2(char(filename(:,1)),0);
    [BE, data(:,M)]=vms_sp_read2(char(filename(:,1)),0);
   for i=2:M
    [BE, data(:,i-1)]=vms_sp_read2(char(filename(:,i)),0);
end
end

handles.or_sp=data;
handles.data=data;
handles.BE=BE;
handles.BE_or=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Untitled_4_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.data;
BE=handles.BE_or;
handles.BE_or_un=BE;
handles.or_sp_un=data;
C=inputdlg('Which binding energy to use for calibration? Example: 285 or 284.8');
C=str2double(C);
[x_sh, y_sh]=shift_spectra_or(data, BE,C);
data=y_sh;
BE=x_sh;
handles.or_sp=data;
handles.BE_or=BE;
handles.data=data;
handles.BE=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Untitled_5_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

[filename, pathname]=uigetfiles('*.vms','Open vms files');
cd(pathname)
[N,M]=size(filename);
if M==1;
    [BE,data]=vms_sp_read_casa2(char(filename(:,1)),0);
else
    [BE, data(:,M)]=vms_sp_read_casa2(char(filename(:,1)),0);
     for i=2:M
    [BE, data(:,i-1)]=vms_sp_read_casa2(char(filename(:,i)),0);
end
end

handles.or_sp=data;
handles.data=data;
handles.BE=BE;
handles.BE_or=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)

% --------------------------------------------------------------------
function Untitled_6_Callback(hObject, eventdata, handles)
% hObject    handle to Untitled_6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

data=handles.data;
BE=handles.BE_or;
handles.BE_or_un=BE;
handles.or_sp_un=data;
[y_sh, x_sh]=shift_spectra_diff(data, BE);
BE=y_sh;
data=x_sh;
handles.or_sp=data;
handles.BE_or=BE;
handles.data=data;
handles.BE=BE;
axes(handles.axes1)
plot(BE,data)
set(gca,'Xdir','reverse')
guidata(hObject,handles)


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


function modelRet = gpsimTest

% GPSIMTEST Test the gradients of the GPSIM model.
% FORMAT
% DESC runs some tests on the code in the GPSIM toolbox to
% test that it is working.
% RETURN model : a cell array of models used for testing.
%
% SEEALSO : modelTest
%
% COPYRIGHT : Neil D. Lawrence, 2005, 2006

% SHEFFIELDML

numGenes = 5;
numProteins = 1;
numData = 4;
times = linspace(0, 5, numData)';
y = randn(numData, numGenes);
yVar = randn(numData, numGenes);
yVar = yVar.*yVar;

numCandGenes = 3;
numCandData = 5;
timesCand = linspace(0, 5, numCandData)';
yCand = randn(numCandData, numCandGenes);
yCandVar = randn(numCandData, numCandGenes);
yCandVar = yCandVar.*yCandVar;

options = gpsimOptions;

model = gpsimCreate(numGenes, numProteins, times, y, yVar, options);

fprintf('Standard Parameter test:\n');
modelGradientCheck(model);

model = gpsimAddCandidate(model, numCandGenes, timesCand, yCand, yCandVar, options);

fprintf('Candidate Parameter test:\n');
model.type = 'gpsimCandidate';
modelGradientCheck(model);
model.type = 'gpsim';

modelRet = model;


function EEG = hlp_icaact(EEG)
% Recompute ica activations
%
% Author: Tim Mullen 2010, SCCN/INC, UCSD.
% Email:  tim@sccn.ucsd.edu

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

EEG.icaact = EEG.icaweights(:,EEG.icachansind)*EEG.icasphere*EEG.data(EEG.icachansind,:);
EEG.icaact = reshape(EEG.icaact, size(EEG.icaact,1), EEG.pnts, EEG.trials);


function planC = copyStructsFromFilesToPlanC(scanFileNames, planC)
% function planC = copyStructsFromFilesToPlanC(scanFileNames, planC)
%
% APA 07/17/2013

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

indexS = planC{end};

[xValsBase, yValsBase, zValsBase] = getScanXYZVals(planC{indexS.scan});

for scanFileIndex = length(scanFileNames)
    scanBasePlanC = loadPlanC(scanFileNames{scanFileIndex},tempdir);
    indexSbaseScan = scanBasePlanC{end};
    annotROIIndV = strcmpi('Annotation ROI',{scanBasePlanC{indexSbaseScan.structures}.structureName});
    annotStrV = find(annotROIIndV);
    [xValsBase1, yValsBase1, zValsBase1] = getScanXYZVals(scanBasePlanC{indexSbaseScan.scan});
    for structIndex = 1:length(annotStrV)
        structNum = annotStrV(structIndex);
        sliceNumsV = [];
        clear pointsC
        for sliceNum = 1:length(scanBasePlanC{indexSbaseScan.structures}(structNum).contour)
            for segNum = 1:length(scanBasePlanC{indexSbaseScan.structures}(structNum).contour(sliceNum).segments)
                points = scanBasePlanC{indexSbaseScan.structures}(structNum).contour(sliceNum).segments(segNum).points;
                if ~isempty(points)
                    zValue = points(1,3);
                    newSliceNum = findnearest(zValsBase,zValue);
                    sliceNumsV = [sliceNumsV newSliceNum];
                    points(:,3) = zValsBase(newSliceNum);
                    pointsC{newSliceNum} = points;
                end
            end
        end

        [sliceNumsV, indUniq] = unique(sliceNumsV);

        % Create Structures segments on sacn slices
        newStructS = newCERRStructure(1, planC);
        for slcNum = 1:length(zValsBase)
            if ismember(slcNum,sliceNumsV)
                newStructS.contour(slcNum).segments(1).points = pointsC{slcNum};
            else
                newStructS.contour(slcNum).segments.points = [];
            end
        end

        newStructNum = length(planC{indexS.structures}) + 1;
        newStructS.structureName = 'Annotation ROI';

        planC{indexS.structures} = dissimilarInsert(planC{indexS.structures}, newStructS, newStructNum);
        planC = getRasterSegs(planC, newStructNum);
        planC = updateStructureMatrices(planC, newStructNum, sliceNumsV);
    end
end


function [G] = spm_lx_phase (P,M)
% Observation function for phase-coupled oscillators
% FORMAT [G] = spm_lx_phase (P,M)
%
% G     Observations y = Gx

Nr=length(P.L);
G=eye(Nr);


function [ cost, grad, numTotal, pred_cell ] = drdae_discrim_joint_kl_obj_gpu( theta, eI, data_cell, targets_cell, mixture_spectrum, fprop_only, pred_out)
% Copyright (c) 2014-present University of Illinois at Urbana-Champaign
% All rights reserved.
%
% Developed by:     Po-Sen Huang, Paris Smaragdis
%                   Department of Electrical and Computer Engineering
%                   Department of Computer Science
%
% discrim. training + joint masking using MATLAB GPU Toolbox
%
%PRNN_OBJ MinFunc style objective for Deep Recurrent Denoising Autoencoder
%   theta is the full parameter vector
%   eI contains experiment / network architecture
%   data_cell is a cell array of matrices. Each a distinct length is a cell
%             entry. Each matrix has a time series example in each column
%   targets_cell is parallel to data, but contains the labels for each time
%   fprop_only is a flag that only computes the cost, no gradient
%   numTotal is total number of frames evaluated
%   pred_out is a binary flag for whether pred_cell is populated
%            pred_cell only filled properly when utterances one per cell

import parallel.gpu.GPUArray

gtheta = gpuArray(theta);

%% Debug: Turns this into an identity-function for debugging rest of system
if isfield(eI, 'objReturnsIdentity') && eI.objReturnsIdentity
    cost = 0; grad = 0; numTotal = 0;
    for l = 1:numel(data_cell)
        numUtterances = size(data_cell{l}, 2);
        original_vector = reshape(data_cell{l}, eI.winSize*eI.featDim, []);
        midPnt = ceil(eI.winSize/2);
        original_vector = original_vector((midPnt-1)*14+1 : midPnt*14, :);
        pred_cell{l} = reshape(original_vector, [], numUtterances);
    end
    return;
end

%if isempty(return_activation),
  return_activation = 0;
%end

%% Load data from globals if not passed in (happens when run on RPC slave)
global g_data_cell;
global g_targets_cell;
isSlave = false;
if isempty(data_cell)
    data_cell = g_data_cell;
    targets_cell = g_targets_cell;
    isSlave = true;
end;
pred_cell = cell(1,numel(data_cell));
act_cell = cell(1,numel(data_cell));
%% default short circuits to false
if ~isfield(eI, 'shortCircuit')
    eI.shortCircuit = 0;
end;

%% default dropout to false
if ~isfield(eI, 'dropout')
  eI.dropout = 0;
end;

%% setup weights and accumulators
[stack, W_t] = rnn_params2stack(gtheta, eI);
cost = 0; numTotal = 0;
outputDim = eI.layerSizes(end);

%% setup structures to aggregate gradients
stackGrad = cell(1,numel(eI.layerSizes));
% W_t_grad = zeros(size(W_t));
if isfield(eI, 'fullRNN') && eI.fullRNN==1
   W_t_grad = cell(1,numel(eI.layerSizes)-1);
    for l = 1:numel(eI.layerSizes)-1
        W_t_grad{l}.W = gpuArray(zeros(size(W_t{l}.W)));
    end
else
   W_t_grad = gpuArray(zeros(size(W_t)));
end

for l = 1:numel(eI.layerSizes)
    stackGrad{l}.W = gpuArray(zeros(size(stack{l}.W)));
    stackGrad{l}.b = gpuArray(zeros(size(stack{l}.b)));
end
if eI.shortCircuit
    stackGrad{end}.W_ss = gpuArray(zeros(size(stack{end}.W_ss)));
end;
%% check options
if ~exist('fprop_only','var')
    fprop_only = false;
end;
if ~exist('pred_out','var')
    pred_out = false;
end;

% DROPOUT: vector of length of hidden layers with 0 or 1
% (to drop or keep activation unit) with prob=0.5
hActToDrop = cell(numel(eI.layerSizes-1),1);
for i=1:numel(eI.layerSizes)-1
 if eI.dropout
   hActToDrop{i} = gpuArray(1/eI.dropout * binornd(1,eI.dropout, eI.layerSizes(i),1));
   %hActToDrop{i} = gpuArray(round(rand(eI.layerSizes(i),1)));
 else
   hActToDrop{i} = gpuArray(ones(eI.layerSizes(i),1));
 end
end

%% loop over each distinct length
for c = 1:numel(data_cell)

    targets = {};
    if ~isempty(targets_cell), targets = targets_cell{c}; end;

    mbsz=min(size(data_cell{c},2), floor(200*1024^2/size(data_cell{c},1)/8)); % 200mb max
    if mbsz==0, continue; end
    nbat = floor(size(data_cell{c},2)/mbsz)+1;

     % convert different mini-bats to GPUs
    for bat=1:nbat

    data = gpuArray(data_cell{c}(:,1+(bat-1)*mbsz: min(size(data_cell{c},2), bat*mbsz)));
    targets = gpuArray(targets_cell{c}(:,1+(bat-1)*mbsz:  min(size(targets_cell{c},2), bat*mbsz)));
    mixtures=gpuArray(mixture_spectrum{c}(:,1+(bat-1)*mbsz: min(size(mixture_spectrum{c},2), bat*mbsz)));

    uttPred = [];
    T =size(data,1) / eI.inputDim;
    % store hidden unit activations at each time instant
    hAct = cell(numel(eI.layerSizes)-1, T);
    for t = 1:T
        %% forward prop all hidden layers
        for l = 1:numel(eI.layerSizes)-1
            if l == 1
                hAct{1,t} = stack{1}.W * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
            else
                hAct{l,t} = stack{l}.W * hAct{l-1,t};
            end;
            hAct{l,t} = hAct{l,t}+ repmat(stack{l}.b, 1, size(hAct{l,t},2));
            % temporal recurrence. limited to single layer for now
            if t > 1
                if isfield(eI, 'fullRNN') && eI.fullRNN==1
                    hAct{l,t} = hAct{l,t} + W_t{l}.W * hAct{l,t-1};
                elseif l == eI.temporalLayer
                    hAct{l,t} = hAct{l,t} + W_t * hAct{l,t-1};
                end
            end;

            % nonlinearity
            if strcmpi(eI.activationFn,'tanh')
                hAct{l,t} = tanh(hAct{l,t});
            elseif strcmpi(eI.activationFn,'logistic')
                hAct{l,t} = 1./(1+exp(-hAct{l,t}));
            elseif strcmpi(eI.activationFn,'RELU')
%                  maxg([ GPUsingle(zeros(size(hAct{1,t}))), hAct{l,t}], hAct{l,t});
%                 hAct{l,t} = maxg(0,hAct{l,t});
                hAct{l,t} = max(0,hAct{l,t});
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
            %dropout (hActToDrop will be all ones if no dropout specified)
            hAct{1,t} = bsxfun(@times, hAct{1,t}, hActToDrop{l});
%              hAct{1,t} = hAct{1,t}.*hActToDrop{l};
        end;
        % forward prop top layer not done here to avoid caching it
    end;
    %% compute cost and backprop through time
    if  eI.temporalLayer
        if isfield(eI, 'fullRNN') && eI.fullRNN==1
            delta_t = cell(1, numel(eI.layerSizes)-1);
            for l = 1:numel(eI.layerSizes)-1
                delta_t{l} = gpuArray(zeros(eI.layerSizes(l),size(data,2)));
            end
        else
            delta_t = gpuArray(zeros(eI.layerSizes(eI.temporalLayer),size(data,2)));
        end
    end;

    y1_dim= 1:outputDim/2;
    y2_dim= outputDim/2+1:outputDim;

    for t = T:-1:1
        l = numel(eI.layerSizes);
        %% forward prop output layer for this timestep
        curPred = bsxfun(@plus, stack{l}.W * hAct{l-1,t}, stack{l}.b);

        if eI.outputnonlinear==1,
           if strcmpi(eI.activationFn,'tanh')
                curPred = tanh(curPred);
           elseif strcmpi(eI.activationFn,'logistic')
                curPred = 1./(1+exp(-curPred));
           elseif strcmpi(eI.activationFn,'RELU')
                curPred = max(0,curPred);
           else
                error('unrecognized activation function: %s',eI.activationFn);
           end
        end

        mixture=mixtures((t-1)*numel(y1_dim)+1:t*numel(y1_dim),:);
        a1 = curPred(y1_dim,:); a2 = curPred(y2_dim,:);

        const=eI.const;%1e-8 ;
        const2=eI.const2;% 1e-3;

        if strcmp(eI.opt,'softlinear'),
            y1= (a1)./((a1)+(a2)+1e-10).* mixture;
            y2= (a2)./((a1)+(a2)+1e-10).* mixture;
        elseif strcmp(eI.opt,'softabs'),
            abs_a1= abs(a1); abs_a2= abs(a2);
            y1= abs_a1./(abs_a1+abs_a2+1e-10).* mixture;
            y2= abs_a2./(abs_a1+abs_a2+1e-10).* mixture;
        elseif strcmp(eI.opt,'softabs_const')|| strcmp(eI.opt,'softabs_kl_const'),
            y1= abs(a1)./(abs(a1)+abs(a2)+const).* mixture;
            y2= abs(a2)./(abs(a1)+abs(a2)+const).* mixture;
        elseif strcmp(eI.opt, 'softquad')
            y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;
            y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-10).* mixture;
        else
        end

        weighted_curPred=[y1; y2];
        % add short circuit to regression prediction if model has it
        if eI.shortCircuit
            weighted_curPred = weighted_curPred + stack{end}.W_ss ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :);
        end;
        if pred_out, uttPred = [weighted_curPred; uttPred]; end;
        % skip loss computation if no targets given
        if isempty(targets), continue; end;

        curTargets = targets((t-1)*outputDim+1:t*outputDim, :);
        curTargets_neg = [curTargets(outputDim/2+1:outputDim,:); curTargets(1:outputDim/2,:)];

        y_t = (1- eI.r) * weighted_curPred + eI.r * curTargets_neg - curTargets;

        ya_ta= y_t(y1_dim,:);
        yb_tb= y_t(y2_dim,:);

        if strcmp(eI.opt,'softlinear'),
            delta_y1 =  (ya_ta-yb_tb).* y2./(a1+a2+1e-10);
            delta_y2 = (-ya_ta+yb_tb) .* y1./ (a1+a2+1e-10);
        elseif strcmp(eI.opt,'softabs'),
            delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+1e-10);
            delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+1e-10);

            delta_y1(a1<0) = -delta_y1(a1<0);
            delta_y2(a2<0) = -delta_y2(a2<0);
        elseif strcmp(eI.opt,'softabs_const'),
             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;
             delta_y1 =  (ya_ta-yb_tb).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1+ ya_ta.* const_div;
             delta_y2 = (-ya_ta+yb_tb) .* y1./ (abs(a1)+abs(a2)+const);
             delta_y2= delta_y2+ yb_tb.* const_div;

             delta_y1(a1<0) =  -delta_y1(a1<0);
             delta_y2(a2<0) =  -delta_y2(a2<0);
        elseif strcmp(eI.opt,'softabs_kl_const'),
             y_target_a = curTargets(y1_dim, :);
             y_target_b = curTargets(y2_dim, :);
             y_target_neg_a = y_target_b;
             y_target_neg_b = y_target_a;

             y_pred_a = weighted_curPred(y1_dim, :);
             y_pred_b = weighted_curPred(y2_dim, :);

             const_div=const./((abs(a1)+abs(a2)+const).^2).* mixture;

             delta_y1 =  (-y_target_a./(y_pred_a+const2) + y_target_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1+  (-y_target_a./(y_pred_a+const2)+1).* const_div;

             delta_y2 =  (y_target_a./(y_pred_a+const2) - y_target_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);
             delta_y2= delta_y2+ (-y_target_b./(y_pred_b+const2)+1) .* const_div;

             % discrim part
             delta_y1 =  delta_y1- eI.r* (-y_target_neg_a./(y_pred_a+const2) + y_target_neg_b./(y_pred_b+const2)).* y2./(abs(a1)+abs(a2)+const);
             delta_y1 = delta_y1-   eI.r* (-y_target_neg_a./(y_pred_a+const2)+1).* const_div;

             delta_y2 = delta_y2- eI.r*(y_target_neg_a./(y_pred_a+const2) - y_target_neg_b./(y_pred_b+const2)).* y1./(abs(a1)+abs(a2)+const);
             delta_y2= delta_y2-  eI.r*(-y_target_neg_b./(y_pred_b+const2)+1) .* const_div;

             delta_y1(a1<0) =  -delta_y1(a1<0);
             delta_y2(a2<0) =  -delta_y2(a2<0);

        elseif strcmp(eI.opt, 'softquad')
            delta_y1 =  (ya_ta-yb_tb).* (2*a1.*y2)./ (a1.^2+a2.^2+1e-10); %  y1= (a1.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;
            delta_y2 =  (-ya_ta+yb_tb).* (2*a2.*y1)./ (a1.^2+a2.^2+1e-10);%         y2= (a2.^2)./((a1.^2)+(a2.^2)+1e-8);%.* mixture;
        else
        end

        delta = [ delta_y1; delta_y2 ];
        if strcmp(eI.opt,'softlinear') || strcmp(eI.opt,'softabs') || strcmp(eI.opt, 'softquad') || strcmp(eI.opt,'softabs_const'),
             cost = cost + 0.5 * ( sum( sum((weighted_curPred - curTargets).*(weighted_curPred - curTargets))) ...
                -  eI.r* sum( sum((weighted_curPred - curTargets_neg).*(weighted_curPred - curTargets_neg))));
        elseif strcmp(eI.opt,'softabs_kl_const'),
             cost = cost +...
             sum(sum( curTargets.*log( curTargets./(weighted_curPred + const2) + const2 )-curTargets+ weighted_curPred +const2))...
            -eI.r* sum(sum( curTargets_neg.*log( curTargets_neg./(weighted_curPred + const2) + const2 )-curTargets_neg+ weighted_curPred +const2));
        else

        end
        if eI.outputnonlinear==1,
             if strcmpi(eI.activationFn,'tanh')
                delta = delta .* (1 -curPred.^2);
            elseif strcmpi(eI.activationFn,'logistic')
                delta = delta .* curPred .* (1 - curPred);
            elseif strcmpi(eI.activationFn,'RELU')
                delta = delta .* double(curPred>0);
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;
        end

        if fprop_only, continue; end;
        %% regression layer gradient and delta
        stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
        stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);
        % short circuit layer
        if eI.shortCircuit
            stackGrad{end}.W_ss = stackGrad{end}.W_ss + delta ...
                * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
        end;
        delta = stack{l}.W' * delta;
        %% backprop through hidden layers
        for l = numel(eI.layerSizes)-1:-1:1
            % aggregate temporal delta term if this is the recurrent layer
            if isfield(eI, 'fullRNN') && eI.fullRNN==1
                delta = delta + delta_t{l};
            elseif l == eI.temporalLayer
                delta = delta + delta_t;
            else
            end
            % push delta through activation function for this layer
            % tanh unit choice assumed
            if strcmpi(eI.activationFn,'tanh')
                delta = delta .* (1 - hAct{l,t}.^2);
            elseif strcmpi(eI.activationFn,'logistic')
                delta = delta .* hAct{l,t} .* (1 - hAct{l,t});
            elseif strcmpi(eI.activationFn,'RELU')
                delta = delta .* gpuArray(hAct{l,t}>0);
            else
                error('unrecognized activation function: %s',eI.activationFn);
            end;

            % gradient of bottom-up connection for this layer
            if l > 1
                stackGrad{l}.W = stackGrad{l}.W + delta * hAct{l-1,t}';
            else
                stackGrad{l}.W = stackGrad{l}.W + delta * data((t-1)*eI.inputDim+1:t*eI.inputDim, :)';
            end;
            % gradient for bias
            stackGrad{l}.b = stackGrad{l}.b + sum(delta,2);

            % compute derivative and delta for temporal connections
            if t > 1
                if isfield(eI, 'fullRNN') && eI.fullRNN==1
                     W_t_grad{l}.W = W_t_grad{l}.W + delta * hAct{l,t-1}';
                     % push delta through temporal weights
                     delta_t{l} = W_t{l}.W' * delta;
                elseif l == eI.temporalLayer
                     W_t_grad = W_t_grad + delta * hAct{l,t-1}';
                     % push delta through temporal weights
                     delta_t = W_t' * delta;
                end;
            end
            % push delta through bottom-up weights
            if l > 1
                delta = stack{l}.W' * delta;
            end;
        end
    end
    pred_cell{c}=double(gather(uttPred));

    % Return the activations for this utterance.
    if return_activation,
      act_cell{c} = cell2mat(hAct);
    end
    % keep track of how many examples seen in total
    numTotal = numTotal + T * size(targets,2);
    end
end

%% stack gradients into single vector and compute weight cost
wCost = numTotal * eI.lambda * sum(gtheta.^2);
grad = rnn_stack2params(stackGrad, eI, W_t_grad, true);
grad = grad + 2 * numTotal * eI.lambda * gtheta;

%% clipping
if isfield(eI,'clip') && eI.clip~=0, % if eI.clip==0, no clip
  if eI.clip > 0 % method one -clip the whole
      norm_grad = norm(grad);
      fprintf('norm_grad:%f\n', norm_grad);
      % avoid numerial problem
      if norm_grad <0 || norm_grad > 1e15 || isnan(norm_grad) || isinf(norm_grad),
          grad = zeros(size(grad));
          fprintf('set gradient to zeros\n');
      end
      if norm_grad > eI.clip
         grad = eI.clip * grad/ norm_grad;
      end
  else % method two - clip each entry
      clip_value = -1*eI.clip;
      grad(grad > clip_value)=clip_value;
      grad(grad < -clip_value)=-clip_value;
  end
end
%%
cost = gather((cost));
grad = gather((grad));
wCost = gather((wCost));

avCost = cost/numTotal;
avWCost = wCost/numTotal;
cost = cost + wCost;

% print output
if ~isSlave && ~isempty(targets_cell)
    fprintf('loss:  %f  wCost:  %f \t',avCost, avWCost);

    if isfield(eI, 'fullRNN') && eI.fullRNN==1
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t{1}.W(:).^2), sum(stack{end}.W(:).^2));
    else
        fprintf('wNorm: %f  rNorm: %f  oNorm: %f\n',sum(stack{1}.W(:).^2),...
            sum(W_t(:).^2), sum(stack{end}.W(:).^2));
    end
end;


function [m] = esvm_mine_train_iteration(m, training_function)
%% ONE ITERATION OF: Mine negatives until cache is full and update the current
% classifier using training_function (do_svm, do_rank, ...). m must
% contain the field m.train_set, which indicates the current
% training set of negative images
% Returns the updated model (where m.mining_queue is updated mining_queue)
%
% Copyright (C) 2011-12 by Tomasz Malisiewicz
% All rights reserved.
%
% This file is part of the Exemplar-SVM library and is made
% available under the terms of the MIT license (see COPYING file).
% Project homepage: https://github.com/quantombone/exemplarsvm

% Start wtrace (trace of learned classifier parameters across
% iterations) with first round classifier, if not present already
if ~isfield(m.model,'wtrace')
  m.model.wtrace{1} = m.model.w;
  m.model.btrace{1} = m.model.b;
end

if length(m.mining_queue) == 0
  fprintf(1,' ---Null mining queue, not mining!\n');
  return;
end

%If the skip is enabled, we just update the model
if m.mining_params.train_skip_mining == 0
  [hn, m.mining_queue, mining_stats] = ...
      esvm_mine_negatives({m}, m.mining_queue, m.train_set, ...
                     m.mining_params);

  m = add_new_detections(m, cat(2,hn.xs{1}{:}), cat(1,hn.bbs{1}{: ...
                   }));
else
  mining_stats.num_visited = 0;
  fprintf(1,'WARNING: train_skip_mining==0, just updating model\n');
end

m = update_the_model(m, mining_stats, training_function);

if isfield(m,'dataset_params') && m.dataset_params.display == 1
  dump_figures(m);
end

function [m] = update_the_model(m, mining_stats, training_function)
%% UPDATE the current SVM, keep max number of svs, and show the results

if ~isfield(m,'mining_stats')
  m.mining_stats{1} = mining_stats;
else
  m.mining_stats{end+1} = mining_stats;
end

m = training_function(m);

% Append new w to trace
m.model.wtrace{end+1} = m.model.w;
m.model.btrace{end+1} = m.model.b;

% if (m.mining_params.dfun == 1)
%   r = m.model.w(:)'*bsxfun(@minus,m.model.svxs,m.model.x(:,1)).^2 - ...
%       m.model.b;
% else
%   r = m.model.w(:)'*m.model.svxs - m.model.b;
% end
% m.model.svbbs(:,end) = r;

function dump_figures(m)

% figure(1)
% clf
% show_cool_os(m)

% if (mining_params.dump_images == 1) || ...
%       (mining_params.dump_last_image == 1 && ...
%        m.iteration == mining_params.train_max_mine_iterations)
%   set(gcf,'PaperPosition',[0 0 10 3]);
%   print(gcf,sprintf('%s/%s.%d_iter=%05d.png', ...
%                     mining_params.final_directory,m.curid,...
%                     m.objectid,m.iteration),'-dpng');
% end

figure(2)
clf
Isv1 = esvm_show_det_stack(m,7);

imagesc(Isv1)
axis image
axis off
iter = length(m.model.wtrace)-1;
title(sprintf('Ex %s.%d.%s SVM-iter=%03d',m.curid,m.objectid,m.cls,iter))
drawnow
snapnow

if (m.mining_params.dump_images == 1) || ...
      (m.mining_params.dump_last_image == 1 && ...
       m.iteration == m.mining_params.train_max_mine_iterations)

  imwrite(Isv1,sprintf('%s/%s.%d_iter_I=%05d.png', ...
                    m.mining_params.final_directory, m.curid,...
                    m.objectid, m.iteration), 'png');
end

function m = add_new_detections(m, xs, bbs)
% Add current detections (xs,bbs) to the model struct (m)
% making sure we prune away duplicates, and then sort by score
%
% Tomasz Malisiewicz (tomasz@cmu.edu)

%First iteration might not have support vector information stored
if ~isfield(m.model, 'svxs') || isempty(m.model.svxs)
  m.model.svxs = [];
  m.model.svbbs = [];
end

m.model.svxs = cat(2,m.model.svxs,xs);
m.model.svbbs = cat(1,m.model.svbbs,bbs);

%Create a unique string identifier for each of the supports
names = cell(size(m.model.svbbs,1),1);
for i = 1:length(names)
  bb = m.model.svbbs(i,:);
  names{i} = sprintf('%d.%.3f.%d.%d.%d',bb(11),bb(8), ...
                             bb(9),bb(10),bb(7));
end

[unames,subset,j] = unique(names);
m.model.svbbs = m.model.svbbs(subset,:);
m.model.svxs = m.model.svxs(:,subset);

[aa,bb] = sort(m.model.w(:)'*m.model.svxs,'descend');
m.model.svbbs = m.model.svbbs(bb,:);
m.model.svxs = m.model.svxs(:,bb);


% This is the testing demo of FFDNet for denoising noisy color images corrupted by
% AWGN with clipping setting. The noisy input is 8-bit quantized.
%
% To run the code, you should install Matconvnet first. Alternatively, you can use the
% function `vl_ffdnet_matlab` to perform denoising without Matconvnet.
%
% "FFDNet: Toward a Fast and Flexible Solution for CNN based Image
% Denoising" 2018/03/23
% If you have any question, please feel free to contact with me.
% Kai Zhang (e-mail: cskaizhang@gmail.com)

% clear; clc;

format compact;
global sigmas; % input noise level or input noise level map
addpath(fullfile('utilities'));

folderModel = 'models';
folderTest  = 'testsets';
folderResult= 'results';
imageSets   = {'CBSD68','Kodak24','McMaster'}; % testing datasets
setTestCur  = imageSets{1};      % current testing dataset

showResult  = 1;
useGPU      = 1;
pauseTime   = 0;

imageNoiseSigma = 25;  % image noise level, 25.5 is the default setting of imnoise( ,'gaussian')
inputNoiseSigma = 25;  % input noise level

folderResultCur       =  fullfile(folderResult, [setTestCur,'_Clip_',num2str(imageNoiseSigma(1)),'_',num2str(inputNoiseSigma(1))]);
if ~isdir(folderResultCur)
    mkdir(folderResultCur)
end

load(fullfile('models','FFDNet_Clip_color.mat'));
net = vl_simplenn_tidy(net);

% for i = 1:size(net.layers,2)
%     net.layers{i}.precious = 1;
% end

if useGPU
    net = vl_simplenn_move(net, 'gpu') ;
end

% read images
ext         =  {'*.jpg','*.png','*.bmp','*.tif'};
filePaths   =  [];
for i = 1 : length(ext)
    filePaths = cat(1,filePaths, dir(fullfile(folderTest,setTestCur,ext{i})));
end

% PSNR and SSIM
PSNRs = zeros(1,length(filePaths));
SSIMs = zeros(1,length(filePaths));

for i = 1:length(filePaths)

    % read images
    label   = imread(fullfile(folderTest,setTestCur,filePaths(i).name));
    [w,h,c] = size(label);

    if c == 3
        [~,nameCur,extCur] = fileparts(filePaths(i).name);
        label = im2single(label);

        % add noise
        randn('seed',0);
        %input = imnoise(label,'gaussian'); % corresponds to imageNoiseSigma = 25.5;
        input = imnoise(label,'gaussian',0,(imageNoiseSigma/255)^2);

        if mod(w,2)==1
            input = cat(1,input, input(end,:,:)) ;
        end
        if mod(h,2)==1
            input = cat(2,input, input(:,end,:)) ;
        end

        % tic;
        if useGPU
            input = gpuArray(input);
        end

        % set noise level map
        sigmas = inputNoiseSigma/255; % see "vl_simplenn.m".

        % perform denoising
        res    = vl_simplenn(net,input,[],[],'conserveMemory',true,'mode','test'); % matconvnet default
        % res    = vl_ffdnet_concise(net, input);    % concise version of vl_simplenn for testing FFDNet
        % res    = vl_ffdnet_matlab(net, input); % use this if you did  not install matconvnet; very slow

        % output = input -res(end).x; % for 'model_color.mat'
        output = res(end).x;

        if mod(w,2)==1
            output = output(1:end-1,:,:);
            input  = input(1:end-1,:,:);
        end
        if mod(h,2)==1
            output = output(:,1:end-1,:);
            input  = input(:,1:end-1,:);
        end

        if useGPU
            output = gather(output);
            input  = gather(input);
        end
        %toc;

        % calculate PSNR, SSIM and save results
        [PSNRCur, SSIMCur] = Cal_PSNRSSIM(im2uint8(label),im2uint8(output),0,0);
        if showResult
            imshow(cat(2,im2uint8(input),im2uint8(label),im2uint8(output)));
            title([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
            %imwrite(im2uint8(output), fullfile(folderResultCur, [nameCur, '_' num2str(imageNoiseSigma(1),'%02d'),'_' num2str(inputNoiseSigma(1),'%02d'),'_PSNR_',num2str(PSNRCur*100,'%4.0f'), extCur] ));
            drawnow;
            pause()
        end
        disp([filePaths(i).name,'    ',num2str(PSNRCur,'%2.2f'),'dB','    ',num2str(SSIMCur,'%2.4f')])
        PSNRs(i) = PSNRCur;
        SSIMs(i) = SSIMCur;

    end
end

disp([mean(PSNRs),mean(SSIMs)]);


classdef CLFQP < Controller
    % This class defines a class of Control Lyapunov Functions (CLFs) that
    % use quadratic programming (QP)
    %
    % @todo implement the CLF-QP controller
    %
    % @author ayonga @date 2016-10-14
    %
    % Copyright (c) 2016, AMBER Lab
    % All right reserved.
    %
    % Redistribution and use in source and binary forms, with or without
    % modification, are permitted only in compliance with the BSD 3-Clause
    % license, see
    % http://www.opensource.org/licenses/bsd-license.php

    properties

    end

    methods

        function obj = CLFQP(name)
            % The controller class constructor function
            %
            % Parameters:
            % name: the controller name @type char

            % call superclass constructor
            obj = obj@Controller(name);
            warning('P matrix from the Ricatti equation not verified for relative degree one outputs and not efficiently computed');
%             error('This class has not been completely defined yet.');

        end

        function u = calcControl(obj, t, x, vfc, gfc, plant, params, logger)
            % Computes the control Lyapunov function based control laws
            % control law for virtual constraints
            %
            % Parameters:
            % t: the time instant @type double
            % x: the states @type colvec
            % vfc: the vector field f(x) @type colvec
            % gfc: the vector field g(x) @type colvec
            % plant: the continuous domain @type DynamicalSystem
            % params: the control parameters @type struct
            % logger: the data logger object @type SimLogger
            %
            % Return values:
            % u: the computed torque @type colvec

            nx = plant.numState;
            if strcmp(plant.Type,'SecondOrder')
                q = x(1:nx);
                dq = x(nx+1:end);
            else
                q = x;
                dq = []; % will not affect any computation
            end

            y = struct2array(plant.VirtualConstraints);
            ny = length(y);
            y_a = cell(ny,1);
            y_d = cell(ny,1);
            tau = cell(ny,1);

            % total dimension of the virtual constraints
            dim_y = sum([y.Dimension]);
            % total dimension of outputs (including relative degrees)
            dim_eta = sum([y.Dimension.*y.RelativeDegree]);
            % some constants required for CLF
            F_mat = zeros(dim_eta);
            G_mat = zeros(dim_eta,dim_y);
            I_mat = eye(dim_eta);
            % partial derivative of the highest order of derivative (y^n-1) w.r.t.
            % the state variable 'x'
            DLfy = zeros(dim_y,length(x));   % A = DLfy*gfc; Lf = DLfy*vfc;
            ddy = zeros(dim_y,1);
            mu = zeros(dim_y,1);    % The derivatives mu = k(1) y + k(2) y' + ... k(n) y^(n-1)
            eta = zeros(dim_eta,1);
            idx = 1; % indexing of outputs
            etaidx = 1; % indexing of eta
            for i=1:ny
                y_i = y(i);

                % returns y, y', y'', y^(n-1), Jy^n-1

                % calculate the actual outputs
                %         [y_a{i}{:}] = calcActual(y_i,q,dq);
                offset_param = y_i.OffsetParamName;
                if y_i.hasOffset
                    offset = params.(offset_param);
                    y_a{i} = calcActual(y_i, q, dq, offset);
                else
                    y_a{i} = calcActual(y_i, q, dq);
                end
                % extract the parameter values

                output_param = y_i.OutputParamName; % desired output parameters
                phase_param  = y_i.PhaseParamName;  % phase variable parameters

                if isfield(params,output_param)
                    a = params.(output_param);
                else
                    error('The parameter %s has not been specified in the ''params'' argument.\n', output_param);
                end

                if ~isempty(phase_param)
                    if isfield(params,phase_param)
                        p = params.(phase_param);
                    else
                        error('The parameter %s has not been specified in the ''params'' argument.\n', phase_param);
                    end
                else
                    p = [];
                end
                % calculate the desired outputs
                y_d{i} = calcDesired(y_i, t, q, dq, a, p);
                % calculate the phase variable
                tau{i} = calcPhaseVariable(y_i, t, q, dq, p);

                % control gain (k0,k1,...kN-1) for the feedback term
                if isfield(params, 'epsilon')
                    ep = params.epsilon;
                    K = ones(1, y_i.RelativeDegree);
                    for l= 1:y_i.RelativeDegree
                        K(l) = nchoosek(y_i.RelativeDegree,l-1)*ep^(y_i.RelativeDegree - l + 1);
                    end

                else
                    error('The control gain %s has not been specified in the ''params'' argument.\n', control_param);
                end

                % stack the partial derivatives of all outputs
                y_indices = idx:idx+y_i.Dimension-1;
                eta_indices = etaidx:etaidx+y_i.Dimension-1;

                G_mat(eta_indices+(y_i.RelativeDegree-1)*numel(eta_indices),y_indices) = eye(y_i.Dimension);

                if y_i.RelativeDegree > 1 % only modify the first degree outputs (0th derivative). not higher derivatives
                    I_mat(eta_indices,eta_indices) = ep*eye(numel(eta_indices));
                end

                if strcmp(y_i.PhaseType, 'TimeBased')
                    DLfy(y_indices,:) = y_a{i}{end};
                    ddy(y_indices) = y_d{i}{end};
                else
                    DLfy(y_indices,:) = y_a{i}{end} - y_d{i}{end};
                end
                for j=1:y_i.RelativeDegree
                    mu(y_indices) = mu(y_indices) + K(j)*(y_a{i}{j}-y_d{i}{j});
                    eta(eta_indices+(j-1)*numel(eta_indices)) = y_a{i}{j} - y_d{i}{j};

                    if j < y_i.RelativeDegree
                        F_mat(eta_indices+(j-1)*numel(eta_indices),eta_indices+j*numel(eta_indices)) = eye(numel(eta_indices));
                    end
                end
                % update the starting index for the next output
                idx = idx+y_i.Dimension;
                etaidx = etaidx+y_i.Dimension*y_i.RelativeDegree;
            end

            %% here is where the CLF based controller is designed
            % decoupling matrix
            A_mat  = DLfy*gfc;
            % feedforward term
            Lf_mat = DLfy*vfc;

            % Lyapunov function
            P = care(F_mat,G_mat,eye(dim_eta));
            Pep = I_mat' * P * I_mat;
            Veta = eta' * Pep * eta;

%             % CLF V for mu
%             LgVetamu = 2*eta'*Pep*G_mat;
%             LfVetamu = eta'*(F_mat'*Pep + Pep*F_mat)*eta + 0.3660*ep*Veta;

            % CLF V for u
            LgVetau = 2*eta'*Pep*G_mat*A_mat;
            LfVetau = eta'*(F_mat'*Pep+Pep*F_mat)*eta+0.3660*ep*Veta+2*eta'*Pep*G_mat*Lf_mat-2*eta'*Pep*G_mat*ddy;

            Hmat = A_mat' * A_mat;

            % feedforward controller
            if strcmp(y_i.PhaseType, 'TimeBased')
                bmat = Lf_mat'*A_mat - ddy'*A_mat;
%                 u_ff = - A_mat \ (Lf_mat - ddy);
            else
                bmat = Lf_mat'*A_mat;
%                 u_ff = - A_mat \ Lf_mat;
            end

            options = optimoptions('quadprog','Algorithm','interior-point-convex','display','off');

%             muqp = quadprog(eye(6),[],LgVetamu,-LfVetamu,[],[],[],[],[],options);
%             disp(max(mu - muqp))
%             mu = muqp;
%             u_fb = A_mat \ mu;
%             u = u_ff + u_fb;

            u = quadprog(Hmat,bmat,LgVetau,-LfVetau,[],[],[],[],[],options);
%             disp(max(u - uqp))
            % feedback controller

            if ~isempty(logger)
                calc = logger.calc;

                calc.mu = mu;

                for i=1:ny
                    y_i = y(i);
                    output_name = y_i.Name;

                    for j=1:y_i.RelativeDegree

                        if j > 1
                            ya_name = ['d' num2str(j-1) 'ya_' output_name];
                            yd_name = ['d' num2str(j-1) 'yd_' output_name];
                            tau_name = ['d' num2str(j-1) 'tau_' output_name];
                        else
                            ya_name = ['ya_' output_name];
                            yd_name = ['yd_' output_name];
                            tau_name = ['tau_' output_name];
                        end
                        calc.(ya_name) = y_a{i}{j};
                        calc.(yd_name) = y_d{i}{j};
                        calc.(tau_name) = tau{i}{j};

                    end

                end
%                 calc.u_ff = u_ff;
%                 calc.u_fb = u_fb;
                calc.u = u;

                logger.calc = calc;
            end

        end
    end

end


hydro = struct();

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


% Copyright (C) 2018  Symeon Symeonidis, Stefanos Tsantilas, Stelios Mitilineos
% simos421@gmail.com, steftsantilas@gmail.com, smitil@gmail.com
% 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.

function CstDefineEfieldMonitor(mws,Efieldname, frequency)

%'@ define monitor: e-field (f=2.25)
% Efieldname is a string

Monitor = invoke(mws,'Monitor');
invoke(Monitor,'Reset');
invoke(Monitor,'Name',Efieldname);
invoke(Monitor,'Dimension','Volume');
invoke(Monitor,'Domain','Frequency');
invoke(Monitor,'FieldType','Efield');
invoke(Monitor,'Frequency',num2str(frequency));
invoke(Monitor,'UseSubvolume','False');
invoke(Monitor,'SetSubvolume','-53.310273111111', '53.310273111111', '-53.310273111111', '53.310273111111', '-33.310273111111', '71.310273111111');
invoke(Monitor,'Create');

end