function test_ft_sourceanalysis

% WALLTIME 00:10:00
% MEM 2gb
% DEPENDENCY ft_sourceanalysis
% DATATYPE comp timelock freq

fs = 500;
nchan = 32;
start_time = -1; % seconds
end_time = 2.5; % seconds
nsamples = (end_time - start_time) * fs + 1;

data = [];
data.time{1} = linspace(start_time, end_time, nsamples);
data.trial{1} = randn(nchan,nsamples);
data.sampleinfo = [1 nsamples];
data.label = cellstr(num2str((1:nchan).'));

% construct a set of electrodes randomly distributed over the upper hemisphere
data.elec.label = data.label;
data.elec.unit = 'cm';
data.elec.tra = eye(nchan);
data.elec.elecpos = randn(nchan,3);
data.elec.elecpos(:,3) = abs(data.elec.elecpos(:,3));
for i=1:nchan
  data.elec.elecpos(i,:) = 10*data.elec.elecpos(i,:)/norm(data.elec.elecpos(i,:));
end
data.elec.chanpos = data.elec.elecpos;

% make an explicit geometry with 4 surfaces
% the radius of each follows the BESA defaults
geometry = [];
geometry(1).pos  = data.elec.elecpos*71/85; % brain
geometry(1).unit = data.elec.unit;
geometry(2).pos  = data.elec.elecpos*72/85; % csf
geometry(2).unit = data.elec.unit;
geometry(3).pos  = data.elec.elecpos*79/85; % skull
geometry(3).unit = data.elec.unit;
geometry(4).pos  = data.elec.elecpos*85/85; % scalp
geometry(4).unit = data.elec.unit;

% fit a 4-sphere concentric model to the geometry
headmodel = ft_headmodel_concentricspheres(geometry, 'conductivity', [0.33 1.00 0.042 0.33]);

% test for comp type
cfg = [];
cfg.updatesens = 'no';
comp = ft_componentanalysis(cfg,data);
ft_checkdata(comp, 'datatype', 'comp');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.component = [1 2 5];
cfg.headmodel = headmodel;
cfg.method = 'rv';
sourceout = ft_sourceanalysis(cfg, comp);

% test for timelock type
cfg = [];
timelock = ft_timelockanalysis(cfg, data);
ft_checkdata(timelock, 'datatype', 'timelock');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.latency = [0 1];
cfg.headmodel = headmodel;
sourceout = ft_sourceanalysis(cfg, timelock);

% test for freq type
cfg = [];
cfg.method = 'mtmfft';
cfg.taper = 'dpss';
cfg.tapsmofrq = 2;
cfg.output = 'fourier';
freq = ft_freqanalysis(cfg, data);
ft_checkdata(freq, 'datatype', 'freq');

cfg = [];
cfg.xgrid = 'auto';
cfg.ygrid = 'auto';
cfg.zgrid = 'auto';
cfg.resolution = 1; % cm
cfg.frequency = 10; % Hz
cfg.headmodel = headmodel;
sourceout = ft_sourceanalysis(cfg, freq);


function data = metoffice_get_data(dataset, anomalies, remove_val)

if nargin < 3 || isempty(remove_val)
    remove_val = 1;
end

%
% Load the data and remove land areas
%

% $$$ logname = getenv('LOGNAME');
% $$$ if strcmp( logname, 'alexilin' ) || strcmp( logname, 'hadia' )
% $$$     jaakkopath
% $$$ end
% $$$
% $$$ os = system_dependent('getos');
% $$$ infinland = ~isempty(strfind(os,'Ubuntu')) || ~isempty(strfind(os,'Linux'));
% $$$ if infinland
% $$$     datapath = '/share/climate/data/UK_Met_Office/RecTest/DATASETS';
% $$$     % Folder for saving the results
% $$$     if strcmp( logname, 'alexilin' )
% $$$         folder = '/share/climate/data/UK_Met_Office/RecTest/RESULTS';
% $$$     else
% $$$         folder = '/share/work/jluttine/metoffice/rectest';
% $$$     end
% $$$ else
% $$$     datapath = '/net/home/h03/hadia/data/RecTest/';
% $$$     folder = '/net/home/h03/hadia/data/RecTest/RESULTS';
% $$$ end

datapath = metoffice_get_path();

switch dataset
case {'hadsst2d1','hadsst2d2','mohsst5d1','mohsst5d2'}
    datafile = [ datapath, dataset ];
    maskfile = 'mask';
case {'aari','aari8'}
    datafile = [ datapath, dataset ];
    maskfile = 'mask_seaice';
otherwise
    error(sprintf('Unknown dataset %s',dataset));
end

data = load(datafile);

[LON,LAT] = meshgrid(data.lon,data.lat);
data.coordinates = double(metoffice_remove_mask([LON(:),LAT(:)], dataset))';
%data.coordinates = double(metoffice_remove_bins([LON(:),LAT(:)],maskfile))';

%if isempty( findstr( maskfile, 'seaice' ) )

    % SST
    Itrain = ~isnan(data.sst);
    if remove_val
        Ival = metoffice_get_valset( remove_val, data.time, Itrain );
        %Ival = get_valset( remove_val, data.time, Itrain );
        data.sst(Ival) = NaN;
        fprintf( 'Validation set %d removed\n', remove_val )
    end

    % Remove land areas
    %data.data = double(metoffice_remove_bins(data.sst,maskfile));
    data.data = double(metoffice_remove_mask(data.sst, dataset));
    data = rmfield( data, 'sst' );

% $$$ else
% $$$
% $$$     % Sea ice
% $$$     % Remove areas
% $$$     data.data = double(metoffice_remove_bins(data.sice,maskfile));
% $$$     data = rmfield( data, 'sice');
% $$$
% $$$ end

data.clim = double(metoffice_remove_mask(data.clim, dataset));
data.gridsize = metoffice_remove_mask(cosd(LAT(:)), dataset);
% $$$ data.clim = double(metoffice_remove_bins(data.clim,maskfile));
% $$$ data.gridsize = metoffice_remove_bins(cosd(LAT(:)),maskfile);

if anomalies==true
  % Remove climatological monthly averages
  dv = datevec( data.time ); month = dv(:,2);

  data.data = data.data - data.clim(:,month);
  clear month dv

end


function [out1,out2] = spline_scale_function(varargin)
out2 = linspace(varargin{1:3});        % wavelet support.
out1 = spline_function(out2);


classdef VARtypeSpecificFAVARsettings < bear.settings.favar.FAVARsettings

    properties
        onestep (1,1) logical = 1; % Bayesian estimation of factors and the model in an one-step estimation (1=yes, 0=no (two-step))
        % thining of Gibbs draws
        thin = 1; % (=1 default, no thinning)
        % priors on factor equation
        % Loadings L~N(0,L0*eye)
        L0 = 1; %BBE set-up
        % Covariance Sigma~IG(a,b)
        a0 = 3; %BBE set-up
        b0 = 0.001; %BBE set-up
    end

end


function [vs, output, v0] = computeRatioConfidenceInterval(v0, expdata, model, max_score, ratio)

% v0 - set of flux vectors to be used as initial guesses.  They may be
% valid or not.
% expdata - experimental data.
% model - The standard model.  Additional field .N (= null(S)) should also
% be provided.  This is a basis of the flux space.
% max score - maximum allowable data fit error.
% ratio - which reactions to take the ratio of.  positive values indicate
% reactions in the numerator and negative values, reactions in the
% denominator.

majorIterationLimit = 2000;  %max number of iterations
minorIterationLimit = 1e7;   % essentially infinity
diffInterval = 1e-5;         %gradient step size.
feasibilityTolerance = max_score/20; % how close you need to be to the max score.

x0 = model.N\v0; % back substitute
numpoints = size(v0,2);
numratios = size(ratio,2);

scores = zeros(numpoints,1);

tProb.user.expdata = expdata;
tProb.user.model = model;
for i = 1:numpoints
    scores(i) = errorComputation2(x0(:,i),tProb);
end

v0(:,scores > max_score) = fitC13Data(v0(:,scores > max_score),expdata,model);

if ~isfield(model, 'N')
   model.N = null(model.S);
end

x0 = model.N\v0; % back substitute

% safety check:
if (max(abs(model.S*v0))> 1e-6)
    display('v0 not quite in null space');
    pause;
end
if(max(abs(model.N*x0 - v0)) > 1e-6)
    display('null basis is weird');
    pause;
end

nalpha = size(model.N, 2);
x_L = -1000*ones(nalpha,1);
x_U = 1000*ones(nalpha,1);
Name = 't2';
[A, b_L, b_U] = defineLinearConstraints(model);

scores = zeros(numpoints,1);
% compute scores for all points.
for i = 1:numpoints
    scores(i) = errorComputation2(x0(:,i),tProb);
end
valid_index = scores < max_score + feasibilityTolerance;
fprintf('found %d valid points\n', sum(valid_index));

c = 'errorComputation2';
c_L = 0; c_U = max_score;

dc = 'errorComputation2_grad';
d2c = []; ConsPattern = [];
%pSepFunc = [];
x_min = []; x_max = []; f_opt = []; x_opt = [];
H = [];  HessPattern = []; pSepFunc = [];  fLowBnd = [];
Solver = 'snopt';

outputminv = 222*ones(numratios, numpoints);
outputminexitflag = -222*ones(numratios, numpoints);
outputminfinalscore = -222*ones(numratios, numpoints);
outputmaxv = -222*ones(numratios, numpoints);
outputmaxexitflag = -222*ones(numratios, numpoints);
outputmaxfinalscore = -222*ones(numratios, numpoints);
outputminstruct = cell(numratios, numpoints);
outputmaxstruct = cell(numratios, numpoints);

%iterate through directions
for i = 1:numratios
%for i = 10:200
    for j = -1:2:1 % max and min
        ration = zeros(size(objective_coefficient(1,model)));
        ratiod = zeros(size(objective_coefficient(1,model)));
        for m = 1:size(ratio,1);
            if(ratio(m,i) > 0)
                ration = ration + objective_coefficient(m,model)*j;
            elseif(ratio(m,i) < 0)
                ratiod = ratiod + objective_coefficient(m,model);
            end
        end

        % initialize temp variables to make parfor work.
        v = j*222*ones(1,numpoints);
        exitflag = -222*ones(1,numpoints);
        finalscore = 222*ones(1,numpoints);
        ostruct = cell(1,numpoints);

        for k = 1:numpoints
            if exist('ttt.txt', 'file')
                fprintf('quitting due to file found\n');
                continue;
            end
            xinitial = x0(:,k);
%                 Prob  = lpconAssign(d, x_L, x_U, Name, xinitial,...
%                                       A, b_L, b_U,...
%                                       c, dc, d2c, ConsPattern, c_L, c_U,...
%                                       fLowBnd, x_min, x_max, f_opt,
%                                       x_opt);

            Prob = conAssign('ratioScore', 'ratioScore_grad', H, HessPattern, x_L, x_U, Name, xinitial, ...
                            pSepFunc, fLowBnd, ...
                            A, b_L, b_U, c, dc, d2c, ConsPattern, c_L, c_U, ...
                            x_min, x_max, f_opt, x_opt);
            %Prob.NumDiff = 2; % central diff
            %Prob.optParam.CentralDiff = 1e-5;
            %pause;
            Prob.user.expdata = expdata;
            Prob.user.model = model;
            Prob.user.ration = ration;
            Prob.user.ratiod = ratiod;

            Prob.user.max_error = max_score;
            Prob.user.diff_interval = diffInterval;
            Prob.user.useparfor = true;

            Prob.optParam.IterPrint = 0;
            %Prob.optParam.cTol = .1*feasibilityTolerance;

            Prob.PriLevOpt = 1;
            Prob.SOL.PrintFile = strcat('temp/snoptp', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt');
            Prob.SOL.SummFile = strcat('temp/snopts', num2str(i), 'x', num2str(j), 'x', num2str(k),'.txt');
            Prob.SOL.optPar(35) = majorIterationLimit; %This is major iteration count.
            Prob.SOL.optPar(30) = minorIterationLimit; %total iteration limit;
            %Prob.SOL.optPar(11) = feasibilityTolerance; % feasibility tolerance

            Result = tomRun(Solver, Prob, 5);
            tscore = errorComputation2(Result.x_k, tProb);
            tbest = Result.f_k;

            fprintf('reaction %d (%d), x %d; x=%f (%f); score=%f (%f)\n', i,length(model.lb),j, tbest,fLowBnd, tscore, max_score)

            v(k) = j*tbest;
            exitflag(k) = Result.Inform;
            finalscore(k) = tscore;
            ostruct{k} = Result;
        end
        if (j > 0) %minimizing
            outputminv(i,:) = v; % multiply by j to correct sign.
            outputminexitflag(i,:) = exitflag;
            outputminfinalscore(i,:) = finalscore;
            outputminstruct(i,:) = ostruct;
        else
            outputmaxv(i,:) = v; % multiply by j to correct sign.
            outputmaxexitflag(i,:) = exitflag;
            outputmaxfinalscore(i,:) = finalscore;
            outputmaxstruct(i,:) = ostruct;
        end
    end
end

output.minv = outputminv;
output.maxv = outputmaxv;
output.minexitflag = outputminexitflag;
output.maxexitflag = outputmaxexitflag;
output.minfinalscore = outputminfinalscore;
output.maxfinalscore = outputmaxfinalscore;
output.minstruct = outputminstruct;
output.maxstruct = outputmaxstruct;

vs = zeros(numratios, 2);
for i = 1:numratios
    validindex = output.minfinalscore(i,:) < max_score + feasibilityTolerance;
    if any(validindex)
        vs(i,1) = min(output.minv(i,validindex));
    else
        vs(i,1) = 222;
    end
    validindex = output.maxfinalscore(i,:) < max_score + feasibilityTolerance;
    if any(validindex)
        vs(i,2) = max(output.maxv(i,validindex));
    else
        vs(i,2) = -222;
    end
end

return;

% function that returns the proper objective coefficient for each reaction
% takes into account the reversibility of reactinos etc.
function [d] =  objective_coefficient(i, model)
d = zeros(length(model.lb),1);
d(i) = 1;
if (model.match(i))
    d(model.match(i)) = -1;
end
d = (d'*model.N)'; % transform to null space;
return


%--------------------------------------------------------------------------------------------------------
% The system is created based on the principles described in the following paper
% Jimmy SJ. Ren, Li Xu, Qiong Yan, Wenxiu Sun, "Shepard Convolutional Neural Networks",
% Advances in Neural Information Processing Systems (NIPS 2015)
% email: jimmy.sj.ren@gmail.com
%--------------------------------------------------------------------------------------------------------
addpath applications/Shepard_CNN/Shepard_super_res/
addpath applications/Shepard_CNN/utility/
addpath applications/image_denoise/utility/
addpath utils/
addpath cuda/
addpath mem/
addpath layers/
addpath layers_adapters/
addpath pipeline/

clearvars -global config;
clearvars -global mem;
clear gen_mask_patch_cat_idx_for_super_res;
clear;
global config;

% set5
% -- baby bird butterfly head woman
I = im2double(imread('applications/Shepard_CNN/Shepard_super_res/images/Set5/butterfly_GT.bmp'));
% set 14
% -- baboon barbara bridge coastguard comic face flowers foreman lenna man monarch pepper ppt3 zebra
%I = im2double(imread('applications/Shepard_CNN/Shepard_super_res/images/Set14/pepper.bmp'));
if(size(I,3) == 3)
    I = rgb2ycbcr(I);
end

I = modcrop(I, 3);
I = padarray(I, [3 3], 'replicate');

% downsample the image
D3chs = imresize(I, [size(I,1)/3 size(I,2)/3], 'bicubic');
D = D3chs(:,:,1);

% super-resolution x3
U = imresize(D, [size(I,1) size(I,2)], 'nearest');
prepare_sr_net(size(U, 1), size(U, 2), 'applications/Shepard_CNN/Shepard_super_res/results/shepard_layer_x3/sr_x3.mat');
mask = config.NEW_MEM([1 0 0; ...
                       0 0 0; ...
                       0 0 0]);
mask = repmat(mask, size(U, 1)/3, size(U, 2)/3, 1);

final_output = apply_net_with_mask(config.NEW_MEM(U) .* mask, mask);
final_output = gather(final_output);
D3chs = imresize(D3chs, [size(final_output,1),size(final_output,2)]);
final_output = shave(final_output, [3 3]);
D3chs = shave(D3chs, [3 3]);

final_output = cat(3, final_output, D3chs(:,:,2:3));
final_output = ycbcr2rgb(double(final_output));
I_bicubic = ycbcr2rgb(D3chs);

figure('name', 'bicubic'), imshow(I_bicubic);
figure('name', 'Sheperd CNN'), imshow(final_output);
drawnow();


function x = emailFeatures(word_indices)
%EMAILFEATURES takes in a word_indices vector and produces a feature vector
%from the word indices
%   x = EMAILFEATURES(word_indices) takes in a word_indices vector and
%   produces a feature vector from the word indices.

% Total number of words in the dictionary
n = 1899;

% You need to return the following variables correctly.
x = zeros(n, 1);

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return a feature vector for the
%               given email (word_indices). To help make it easier to
%               process the emails, we have have already pre-processed each
%               email and converted each word in the email into an index in
%               a fixed dictionary (of 1899 words). The variable
%               word_indices contains the list of indices of the words
%               which occur in one email.
%
%               Concretely, if an email has the text:
%
%                  The quick brown fox jumped over the lazy dog.
%
%               Then, the word_indices vector for this text might look
%               like:
%
%                   60  100   33   44   10     53  60  58   5
%
%               where, we have mapped each word onto a number, for example:
%
%                   the   -- 60
%                   quick -- 100
%                   ...
%
%              (note: the above numbers are just an example and are not the
%               actual mappings).
%
%              Your task is take one such word_indices vector and construct
%              a binary feature vector that indicates whether a particular
%              word occurs in the email. That is, x(i) = 1 when word i
%              is present in the email. Concretely, if the word 'the' (say,
%              index 60) appears in the email, then x(60) = 1. The feature
%              vector should look like:
%
%              x = [ 0 0 0 0 1 0 0 0 ... 0 0 0 0 1 ... 0 0 0 1 0 ..];
%
%

for loc = word_indices,
  x(loc) = 1;
endfor

% =========================================================================

end


function aistats2012_run_comparison

%
% Theta
%

% Cholesky

nips2011_comparison(3, 1, true, false);
nips2011_comparison(3.5, 1, true, false);
nips2011_comparison(4, 1, true, false);
nips2011_comparison(4.5, 1, true, false);
nips2011_comparison(5, 1, true, false);

% Kronecker

% $$$ nips2011_comparison(3, 1, true, true);
% $$$ nips2011_comparison(3.5, 1, true, true);
% $$$ nips2011_comparison(4, 1, true, true);
% $$$ nips2011_comparison(4.5, 1, true, true);
% $$$ nips2011_comparison(5, 1, true, true);
% $$$ nips2011_comparison(6, 1, true, true);
nips2011_comparison(7, 1, true, true);

%
% F
%

% Kronecker

% $$$ nips2011_comparison(3, 1, false, true);
% $$$ nips2011_comparison(3.5, 1, false, true);
% $$$ nips2011_comparison(4, 1, false, true);
% $$$ nips2011_comparison(4.5, 1, false, true);
% $$$ nips2011_comparison(5, 1, false, true);
% $$$ nips2011_comparison(5.5, 1, false, true);
% $$$ nips2011_comparison(6, 1, false, true);
% $$$ nips2011_comparison(7, 1, false, true);
% $$$ nips2011_comparison(8, 1, false, true);

% Cholesky

nips2011_comparison(3, 1, false, false);
nips2011_comparison(3.5, 1, false, false);
nips2011_comparison(4, 1, false, false);
nips2011_comparison(4.5, 1, false, false);
nips2011_comparison(5, 1, false, false);
nips2011_comparison(5.5, 1, false, false);


%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( abhishek.jaiantilal@colorado.edu )
%* License: GPLv2
%* Version: 0.02
%
% Calls Regression Random Forest
% A wrapper matlab file that calls the mex file
% This does prediction given the data and the model file
%**************************************************************

function Y_hat = regRF_predict(X,model)
    %function Y_hat = regRF_predict(X,model)
    %requires 2 arguments
    %X: data matrix
    %model: generated via regRF_train function
	if nargin~=2
		error('need atleast 2 parameters,X matrix and model');
	end

	Y_hat = mexRF_predict(X',model.lDau,model.rDau,model.nodestatus,model.nrnodes,model.upper,model.avnode,model.mbest,model.ndtree,model.ntree);

    if ~isempty(find(model.coef)) %for bias corr
        Y_hat = model.coef(1) + model.coef(2)*Y_hat;
    end
	clear mexRF_predict


function strat = beatTheBookie_timeseries(dat_dir, files, bet, marg, nValidOdds, hours, discard_games_randomly, prop2discard)

% loop through hours
% apply formula
% keep all bookies and time when the criteria is met
% place bet only for 1 or the three options for all the bookies
% available. Discard the other options

money = 0;
accuracy = [];
m = 2; % counter for the money
acc = 1; % counter for accuracy
st2 = 1;
st = 1;
z = 0;

for fi = 1 : length(files)

    if mod(fi,1000) == 0
        fprintf('Game #%d \n', fi);
    end

    fid = fopen([dat_dir files(fi).name], 'r');
    C = textscan(fid, repmat('%f ' , [1,72*3]), 'delimiter', ',');
    fclose(fid);

    data = cell2mat(C);

    % sanity check: games with no bets
    if sum(isnan(data(:))) == (32 * 216)
        fprintf('Game number %d, %s, has only nans \n', fi, files(fi).name);
        z = z + 1;
        continue;
    end

    % get result of the game
    name = strrep(files(fi).name, '.txt', '');
    C = strsplit(name, '_');
    score_home = str2double(C{end-1});
    score_away = str2double(C{end});

    if score_home > score_away
        result = 1;
    elseif score_home == score_away
        result = 2;
    else
        result = 3;
    end

    possible_earn = 0;

    for h = 1 : length(hours{1})

        avg_home = nanmean(data(:,hours{1}(h)));[max_home, bk_home_id] = nanmax(data(:, hours{1}(h)));
        avg_draw = nanmean(data(:,hours{2}(h)));[max_draw, bk_draw_id] = nanmax(data(:, hours{2}(h)));
        avg_away = nanmean(data(:,hours{3}(h)));[max_away, bk_away_id] =  nanmax(data(:, hours{3}(h)));

        averages = [avg_home avg_draw avg_away];
        maximums = [max_home max_draw max_away];
        bookies = [bk_home_id bk_draw_id bk_away_id];

        % check that there is at least one valid bet. If the bets are still not
        % online for this time, continue to the next game
        if isnan(avg_home) || isnan(avg_draw) || isnan(avg_away)
            continue
        end

        if isnan(max_home) && isnan(max_draw) && isnan(max_away)
            continue
        end

        % Apply formula and decide whether to bet
        earn_margin(1) = ((1 ./ avg_home - marg) * max_home - 1) * (sum(~isnan(data(:,hours{1}(h)))) > nValidOdds);
        earn_margin(2) = ((1 ./ avg_draw - marg) * max_draw - 1) * (sum(~isnan(data(:,hours{2}(h)))) > nValidOdds) ;
        earn_margin(3) = ((1 ./ avg_away - marg) * max_away - 1) * (sum(~isnan(data(:,hours{3}(h)))) > nValidOdds);

        if sum(earn_margin > 0) >= 1

            [~, id] = max(earn_margin);
            possible_earn = bet  * (maximums(id) - 1);
            break;
        end

    end

    % If match did not reach the criteria for betting, move to the next
    % match
    %if sum(bets_id(:)) == 0
    if possible_earn == 0
        continue
    end

    % Artibtrarily skip some games to simulate a real situation of betting
    % where we miss some of the games
    if discard_games_randomly
        num = rand(1);
        if num < prop2discard
            continue
        end
    end

    % Decide where to place the bet: home, draw or away
    if possible_earn > 0
        aux_possible_earn = possible_earn;
        bet_result = id;

        % There is an error in one of the odds: it was set to 126. I fix this here
        % I set a maximum earning of 15 for the bets
        if aux_possible_earn > 750
            continue
        end

        % calculate loss / earning
        if isequal(bet_result, result)
            money(m) = money(m-1) + aux_possible_earn;
            m = m + 1;
            accuracy(acc) = 1;
            ids(acc) = id;
            max_odds(acc) = maximums(id);
            mean_odds(acc) = averages(id);
            acc = acc + 1;
        else
            money(m) = money(m-1) - bet;
            m = m + 1;
            accuracy(acc) = 0;
            ids(acc) = id;
            max_odds(acc) = maximums(id);
            mean_odds(acc) = averages(id);
            acc = acc + 1;
        end

    end

    clear data bets_id possible_earn
end

strat.money = money;
strat.name = 'BeatTheBookies';
strat.accuracy = accuracy;
strat.ids = ids;
strat.max_odds = max_odds;
strat.mean_odds = mean_odds;

end


function varargout = quickvis(varargin)
% VL_QUICKVIS Create an edge image from a Quickshift segmentation.
%   IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge
%   stability image from a Quickshift segmentation. RATIO controls the tradeoff
%   between color consistency and spatial consistency (See VL_QUICKSEG) and
%   KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,
%   VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which
%   increase the density.
%
%   VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at
%   most MAXCUTS segmentations. The edges between regions in each of these
%   segmentations are labeled in IEDGE, where the label corresponds to the
%   largest DIST which preserves the edge.
%
%   [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also
%   returns the DIST thresholds that were chosen.
%
%   IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS
%   specified
%
%   [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)
%   also returns the MAP and GAPS from VL_QUICKSHIFT.
%
%   See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().
[varargout{1:nargout}] = vl_quickvis(varargin{:});


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   PARAMETERS Returns a data structure containing the parameters of the
%   ADEPT eCobra 600.
%
% The authors of this script are:
%   Arturo Gil Aparicio
%   Adrian Peidro Vidal
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Copyright (C) 2012, by Arturo Gil Aparicio
%
% This file is part of ARTE (A Robotics Toolbox for Education).
%
% ARTE is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% ARTE is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with ARTE.  If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function robot = parameters()

robot.name= 'ADEPT_eCobra_600';

%Path where everything is stored for this robot
robot.path = 'robots/adept/eCobra_600';

robot.DH.theta= '[q(1) q(2) 0 q(4)]';
robot.DH.d='[0.342 0 q(3)+0.165 0]';
robot.DH.a='[0.325 0.275 0 0]';
robot.DH.alpha= '[0 pi 0 0]';

robot.J=[];

robot.inversekinematic_fn = 'inversekinematic_ecobra_600(robot, T)';
robot.directkinematic_fn = 'directkinematic(robot, q)';

%number of degrees of freedom
robot.DOF = 4;

%rotational: 0, translational: 1
robot.kind=['R' 'R' 'P' 'R'];

%minimum and maximum rotation angle in rad
robot.maxangle =[deg2rad(-170) deg2rad(170); %Axis 1, minimum, maximum
                deg2rad(-190) deg2rad(45); %Axis 2, minimum, maximum
                deg2rad(-29) deg2rad(256); %Axis 3
                deg2rad(-190) deg2rad(190); %Axis 4: Unlimited (400? default)
                ]; %Axis 6: Really Unlimited to (800? default)

%maximum absolute speed of each joint rad/s or m/s
robot.velmax = [deg2rad(250); %Axis 1, rad/s
                deg2rad(250); %Axis 2, rad/s
                deg2rad(250); %Axis 3, rad/s
                deg2rad(375); %Axis 4, rad/s
                ];%Axis 6, rad/s

robot.accelmax=robot.velmax/0.1; % 0.1 is here an acceleration time

% end effectors maximum velocity
robot.linear_velmax = 7.6; %m/s

%base reference system
robot.T0 = eye(4);

%INITIALIZATION OF VARIABLES REQUIRED FOR THE SIMULATION
%position, velocity and acceleration
robot=init_sim_variables(robot);
robot.path = pwd;

% GRAPHICS
robot.graphical.has_graphics=1;
robot.graphical.color = [255 102 51]./255;
%for transparency
robot.graphical.draw_transparent=0;%0.5;
%draw DH systems
robot.graphical.draw_axes=0;
%DH system length and Font size, standard is 1/10. Select 2/20, 3/30 for
%bigger robots
robot.graphical.axes_scale=1;
%adjust for a default view of the robot
robot.axis=[-0.8 0.8 -0.8 0.8 0 1];
%read graphics files
robot = read_graphics(robot);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DYNAMIC PARAMETERS
%   WARNING! These parameters do not correspond to the actual VIPER 850
%   robot. They have been introduced to demonstrate the necessity of
%   simulating the robot and should be used only for educational purposes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
robot.has_dynamics=1;

%consider friction in the computations
robot.dynamics.friction=0;

%link masses (kg)
robot.dynamics.masses=[10.0840645443765 7.99763638499999 7.82396742420414 6.79135586560867 2.69519416947469 0.582726761463460 0.0250548498725116];

%COM of each link with respect to own reference system
robot.dynamics.r_com=[  37.34e-3	 -7.59e-3	 291.45e-3;     %(rx, ry, rz) link 1
                       8.82e-3	 158.89e-3	     -116.12e-3; %(rx, ry, rz) link 2
                       45.72e-3      -60.41e-3       6.77e-3;     %(rx, ry, rz) link 3
                        0.65e-3       5.18e-3      304.45e-3;     %(rx, ry, rz) link 4
                        0        -16.20e-3        -0.43e-3;  %(rx, ry, rz) link 5
                        0        0.10e-3     102.45e-3]; %(rx, ry, rz) link 6

%Inertia matrices of each link with respect to its D-H reference system.
% Ixx	Iyy	Izz	Ixy	Iyz	Ixz, for each row
robot.dynamics.Inertia=[725041607.30e-9     742053235.46e-9   58888719.46e-9    -4612005.75e-9    -20201400.03e-9  100257432.34e-9;
                        473299566.08e-9    122717629.66e-9	   374750563.05e-9	   12544273.08e-9	  -140558617.88e-9	  -8394816.58e-9;
                        73135068.37e-9	    43626156.19e-9	   96299686.97e-9	   -34759300.78e-9	  -1593782.48e-9	 1209250.25e-9;
                        262441613.90e-9     261164434.73e-9    5256188.91e-9	  15725.91e-9	  4591746.99e-9	 471721.51e-9;
                        869212.45e-9        370702.33e-9       939398.99e-9	  4.39e-9	  -4.96e-9	 3.05e-9;
                        280731.23e-9	     284457.82e-9	   6143.16e-9	  0	   217.96e-9	 0];

%robot.motors=load_motors([5 5 5 4 4 4]);
%Speed reductor at each joint
%robot.motors.G=[300 300 300 300 300 300];


function dat= proc_commonMedianReference(dat, refChans, rerefChans)
%PROC_COMMONMEDIANREFERENCE - rereference signals to common median reference
%
%Synopsis:
% dat= proc_commonMedianReference(dat, <refChans, rerefChans>)
%
%
%Arguments:
%      dat        - data structure of continuous or epoched data
%      refChans   - channels used as average reference, see util_chanind for format,
%                   default util_scalpChannels(dat)
%      rerefChans - those channels are rereferenced, default refChans
%
%Returns:
%      dat        - updated data structure
%
% SEE util_scalpChannels, util_chanind

% Author: Benjamin Blankertz
dat = misc_history(dat);

if ~exist('refChans','var') || isempty(refChans),
  refChans= util_scalpChannels(dat);
end
if ~exist('rerefChans','var') || isempty(rerefChans), rerefChans= refChans; end

misc_checkType(dat, 'STRUCT(x clab)');
misc_checkType(refChans, 'CELL{CHAR}|CHAR');
misc_checkType(rerefChans, 'CELL{CHAR}|CHAR');

rc= util_chanind(dat, refChans);
rrc= util_chanind(dat, rerefChans);
car= median(dat.x(:,rc,:), 2);
%% this might consume too much memory:
%car= repmat(car, [1 length(rrc) 1]);
%dat.x(:,rrc,:)= dat.x(:,rrc,:) - car;

for cc= rrc,
  dat.x(:,cc,:)= dat.x(:,cc,:) - car;
  dat.clab{cc}= [dat.clab{cc} ' car'];
end


clear all; close all; clc

%% folder setup
saveFigFlag = 1;

outputDir = GetOutputDataDir;
saveDir1 = fullfile(outputDir,'multimotor_0228');
% saveDir2 = fullfile(outputDir,'motor_map_seed');
if ~exist(saveDir1, 'dir'), mkdir(saveDir1), end;
% if ~exist(saveDir2, 'dir'), mkdir(saveDir2), end;

%% init

hfig = figure;
InitializeAppData(hfig);
ResetDisplayParams(hfig);
% i_fish = 8;
% setappdata(hfig,'isMotorseed',0);

%% run fish
range_fish = GetFishRange;%[1:3,5:18];
% M_thres_reg = zeros(3,18);
% M_numTopCorr = zeros(1,18);
% M_motorseedRegs = cell(1,18);
% M_compareMotorCellNumber = zeros(2,18);

%%
stimflag = 'P';
ClusterIDs = [6,2];

% stimflag = []; % for default set
% ClusterIDs = [6,1];
M_stimrange = GetStimRange(stimflag);

range_fish_valid = [];
for i_fish = range_fish
    if ~isempty(M_stimrange{i_fish})
       range_fish_valid = [range_fish_valid,i_fish];
    end
end

tscriptstart = tic;
for i_fish = range_fish_valid
    %% load data for chosen stim range
    stimrange = M_stimrange{i_fish};
    [cIX,gIX_load,M,stim,behavior,M_0] = LoadSingleFishDefault(i_fish,hfig,ClusterIDs,stimrange);

    %% Method 1: stim+motor regression
    fishset = getappdata(hfig,'fishset');
    [~,~,reg_sens] = GetStimRegressor(stim,fishset,i_fish);
    [~,~,reg_motor] = GetMotorRegressor(behavior,i_fish);

    % cell based
    gIX = (1:length(cIX))';
    tic
    [stimcorr,motorcorr] = MotorSourceCorrelation(M,reg_sens,reg_motor);
    toc
    [fig1,fig2] = MultiMotorVisuals(hfig,stimcorr,motorcorr,cIX,gIX);

    saveDir = fullfile(saveDir1,'motor rank - cell based - 2D');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig1);

    saveDir = fullfile(saveDir1,'motor rank - cell based - anat');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig2);

    %% cluster based
    % plot 1
%     setappdata(hfig,'isMotorseed',0);
%     %     setappdata(hfig,'stimrange',1:2);
%
%     UpdateTimeIndex(hfig);
%     behavior = getappdata(hfig,'behavior');
%     [~,~,reg_motor] = GetMotorRegressor(behavior,i_fish);

    gIX = gIX_load;
    C = FindClustermeans(gIX,M);
    tic
    [stimcorr,motorcorr] = MotorSourceCorrelation(C,reg_sens,reg_motor);
    toc
    [fig1,fig2] = MultiMotorVisuals(hfig,stimcorr,motorcorr,cIX,gIX);

%     % plot 2
%     setappdata(hfig,'isMotorseed',1);
%     %     setappdata(hfig,'stimrange',1:2);
%
%     UpdateTimeIndex(hfig);
%     behavior = getappdata(hfig,'behavior');
%     [~,~,reg_motor] = GetMotorRegressor(behavior,i_fish);
%
%     gIX = gIX_load;
%     C = FindClustermeans(gIX,M);
%     tic
%     [stimcorr,motorcorr] = MotorSourceCorrelation(C,reg_sens,reg_motor);
%     toc
%     [fig3,fig4] = MultiMotorVisuals(hfig,stimcorr,motorcorr,cIX,gIX);
    %%
    saveDir = fullfile(saveDir1,'motor rank - cluster based - 2D');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig1);

    saveDir = fullfile(saveDir1,'motor rank - cluster based - anat');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig2);
    %%

% %  saveas(gcf, fn, 'png');
% %
% % %%
% %     [rawmotorcorr,IX] = max(corr(reg_motor',M'),[],1);
% %     thres_reg = 0.5;
% %     ix = find(rawmotorcorr>thres_reg);
    %% Method 2: stimAvr+motor regression
    % cluster based;
    gIX = gIX_load;
    C = FindClustermeans(gIX,M);
    reg_sens = GetStimAvrClusmean(hfig,C);
    [~,~,reg_motor] = GetMotorRegressor(behavior,i_fish);

    nUnit = size(C,1);
    stimcorr = zeros(nUnit,1);
    motorcorr = zeros(nUnit,1);
    tic
    for i = 1:size(C,1)
    [stimcorr(i),motorcorr(i)] = MotorSourceCorrelation(C(i,:),reg_sens(i,:),reg_motor);
    end
    toc

    [fig1,fig2] = MultiMotorVisuals(hfig,stimcorr,motorcorr,cIX,gIX);

    saveDir = fullfile(saveDir1,'stimAvr rank - cluster based - 2D');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig1);

    saveDir = fullfile(saveDir1,'stimAvr rank - cluster based - anat');
    figName = ['Fish' num2str(i_fish)];
    SaveFigureHelper(saveFigFlag, saveDir, figName,fig2);

end
toc(tscriptstart)


% Genralized Sentiment Analysis
%

clc;
close all;
clear all;

tic;
%
 fid = fopen('data\english.stop');

 stopwords = textscan(fid, '%s');
 stopwords = stopwords{1,1};
 fclose(fid);

% params
% n:minimum appearances of a stem
n=30;

% reading the data file
% xls is easier to read than csv
[num,txt,raw] = xlsread('C:\MatlabNLP\examples\gsa\data\final104.xls');

% reading the description of each shoe
descriptions = raw(2:size(raw,1),2);
style_ratings = num(1:size(num,1),1);
comfort_ratings = num(1:size(num,1),4);
overal_ratings = num(1:size(num,1),5);

% only take m data points

m=50;
m = length(descriptions);
descriptions = descriptions(1:m);
style_ratings = style_ratings(1:m);
comfort_ratings = comfort_ratings(1:m);
overal_ratings = overal_ratings(1:m);
g = containers.Map();
toc;

for i = 1:size(descriptions,1)
    comment = descriptions{i};
    comment = SanitizeComment(comment);
    comment = lower(comment);
    r=regexp(comment,' ','split');
    for j =1:size(r,2)
        word = porterStemmer(cell2mat(r(j)));
        tfflag = ~isStopWord(word, stopwords);
        if isKey(g, word) && tfflag
            g(word) = g(word)+1;
        elseif tfflag
            g(word) = 1;
        end

    end

end
toc;
selectedheaders =containers.Map();
gkeys = keys(g);

for i=1:size(gkeys,2)
    if g(gkeys{i})>=n

        selectedheaders(gkeys{i})=1;

    end

end
headers = keys(selectedheaders);

outputMatrix = zeros(m,length(headers));
for i = 1:size(descriptions,1)
    comment = descriptions{i};
    comment = SanitizeComment(comment);
    comment = lower(comment);

    r=regexp(comment,' ','split');
    comment = [];
    for j =1:size(r,2)
        word = porterStemmer(cell2mat(r(j)));

        comment = [comment,' ',word];
    end
    outputMatrix(i,:) = term_count(comment, headers);

    if mod(i,300)==0
        a = sprintf('%d', i);
        disp(a)
    end

end

toc;
csvwrite('forWeka_featuresonly.csv', outputMatrix);

outputmatrix_all = [style_ratings,comfort_ratings,overal_ratings, outputMatrix];
outputmatrix_all = [ones(1,size(outputmatrix_all,2));outputmatrix_all];
csvwrite('forWeka_everything.csv', outputmatrix_all);


function [ state ] =movePTPArcXY_AC(t,theta,c,vel)
%% This function is used for moving the endeffector on an arc in the XY plane, for the KUKA iiwa 7 R 800.

%% Syntax:
% [ state ] =movePTPArcXY_AC(t,theta,c,vel)

%% About:
% This function is used to move the end-effector on an arc in the XY plane,

%% Arreguments:
% t: is the TCP/IP connection
% theta: is the arc angle, in radians
% c: the XY coordinates of the center of the circle, it is 1x2 vector.
% vel : is a double, defines the motion velocity mm/sec.

% Copyright, Mohammad SAFEEA, 9th of May 2017

    k=[0;0;1];
    pos=getEEFPos( t );
    c=colVec(c);
    c1=[c;pos{3}];
    state=movePTPArc_AC(t,theta,c1,k,vel);

end

function [ y ] = colVec( v)
% Convert a vector to a column vector:
    if(size(v,2)==1)
        y=v;
    else
        y=v';
    end
end


function c8vec_uniform_01_test ( )

%*****************************************************************************80
%
%% C8VEC_UNIFORM_01_TEST tests C8VEC_UNIFORM_01.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    29 June 2006
%
%  Author:
%
%    John Burkardt
%
  seed = 123456789;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'C8VEC_UNIFORM_01_TEST\n' );
  fprintf ( 1, '  C8VEC_UNIFORM_01 computes pseudorandom complex values\n' );
  fprintf ( 1, '  in the unit circle.\n' );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The initial seed is %d\n', seed );

  n = 10;

  [ x, seed ] = c8vec_uniform_01 ( n, seed );

  for i = 1 : n
    fprintf ( 1, '  %6d  ( %f, %f )\n', i, real ( x(i) ), imag ( x(i) ) );
  end

  return
end


function [ymu,ys2,fmu,fs2,dymu,dys2,dfmu,dfs2] = gpgrad(x0,gpstruct,method,dx)
%GPGRAD Gradient of Gaussian process mean prediction

if nargin < 3 || isempty(method); method = 'central'; end
if nargin < 4 || isempty(dx); dx = 1e-6; end

D = size(x0,2);
Nhyp = length(gpstruct.hyp);

% Initialize variables
ymu = zeros(Nhyp,1);
fmu = zeros(Nhyp,1);
ys2 = zeros(Nhyp,1);
fs2 = zeros(Nhyp,1);

if nargout > 4
    dymu = zeros(Nhyp,D);
    dfmu = zeros(Nhyp,D);
    dys2 = zeros(Nhyp,D);
    dfs2 = zeros(Nhyp,D);
end

% Compute predictions and derivatives for each hyperparameter sample
for i = 1:Nhyp

    try
        if nargout > 4
            [dy,y0] = fgrad(@(xi_) gpfunc(xi_,gpstruct,gpstruct.hyp(i)),x0,method,'Vectorized','Step',dx);
        else
            y0 = gpfunc(x0,gpstruct,gpstruct.hyp(i));
        end
    catch
        y0 = NaN(1,4);
        if nargout > 4; dy = NaN(4,D); end
        warning('bads:gpGradFail', 'Error in computing the GP derivative.');
    end

    ymu(i) = y0(1);
    ys2(i) = y0(2);
    fmu(i) = y0(3);
    fs2(i) = y0(4);

    if nargout > 4
        dymu(i,:) = dy(1,:);
        dfmu(i,:) = dy(2,:);
        dys2(i,:) = dy(3,:);
        dfs2(i,:) = dy(4,:);
    end

end

%--------------------------------------------------------------------------

function yy = gpfunc(xi,gpstruct,hyp)
    if gpstruct.gpmlext
        % Pre-computed Laplace approximation at MAP
        if isfield(gpstruct,'hypSigma') && ~isempty(gpstruct.hypSigma)
            hyp.Sigma = gpstruct.hypSigma;
        end

        if isfield(gpstruct,'post') && ~isempty(gpstruct.post)
        %    [ymuib,ys2ib,fmuib,fs2ib] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...
        %gpstruct.lik,gpstruct.x,gpstruct.post,xi);

            [ymui,ys2i,fmui,fs2i] = mgp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...
        gpstruct.lik,gpstruct.x,gpstruct.post,xi);

            %[fmuib(:) - fmui(:), sqrt(fs2ib(:)) - sqrt(fs2i(:))]

        else
            [ymui,ys2i,fmui,fs2i] = mgp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...
        gpstruct.lik,gpstruct.x,gpstruct.y,xi);
        end
        yy = [ymui,ys2i,fmui,fs2i];
    else

        if isfield(gpstruct,'post') && ~isempty(gpstruct.post)
            [ymui,ys2i,fmui,fs2i] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...
        gpstruct.lik,gpstruct.x,gpstruct.post,gpstruct.s,xi);
        else
            [ymui,ys2i,fmui,fs2i] = mygp(hyp,gpstruct.inf,gpstruct.mean,gpstruct.cov, ...
        gpstruct.lik,gpstruct.x,gpstruct.y,gpstruct.s,xi);
        end

        if 1
            % [~, ymui, ys2i] = feval(gpstruct.lik{:}, hyp.lik, [], fmui, fs2i);

            lik = hyp.lik; lik(end) = -Inf;
            % fmuiold = fmui; fs2iold = fs2i;
            [~, fmui, fs2i] = feval(gpstruct.lik{:}, lik, [], [], fmui, fs2i);
        end

        yy = [ymui,ys2i,fmui,fs2i];
        % [ymui,sqrt(ys2i),fmui,sqrt(fs2i),fmuiold,sqrt(fs2iold)]
    end


function [p] = get_line_xyz(h)
% File:      get_line_xyz.m
% Author:    Ioannis Filippidis, jfilippidis@gmail.com
% Date:      2012.06.15
% Language:  MATLAB R2012a
% Purpose:   get line point coordinates and fix z if empty
% Copyright: Ioannis Filippidis, 2012-

% get defined data-points
x = get(h, 'XData');
y = get(h, 'YData');
z = get(h, 'ZData');

% 2d line ?
if isempty(z)
    z = zeros(size(x) );
end

p = [x; y; z];


function [tc,relres,iter,xrec] = gabgrouplasso(x,g,a,M,lambda,varargin)
%GABGROUPLASSO  Group LASSO regression in Gabor domain
%   Usage: [tc,xrec] = gabgrouplasso(x,g,a,M,group,lambda,C,maxit,tol)
%
%   `gabgrouplasso` has been deprecated. Please use |franagrouplasso| instead.
%
%   A call to `gabgrouplasso(x,g,a,M,lambda)` can be replaced by ::
%
%     F=frame('dgt',g,a,M);
%     tc=franagrouplasso(F,lambda);
%
%   Any additional parameters passed to `gabgrouplasso` can be passed to
%   |franagrouplasso| in the same manner.
%
%   See also: frame, franagrouplasso

warning(['LTFAT: GABGROUPLASSO has been deprecated, please use FRANAGROUPLASSO ' ...
          'instead. See the help on FRANAGROUPLASSO for more details.']);

F=newframe('dgt',[],g,a,M);
[tc,relres,iter,xrec] = framegrouplasso(F,lambda,varargin{:});


function test_bug1249

% MEM 2gb
% WALLTIME 00:10:00
% DEPENDENCY ft_componentanalysis ft_rejectcomponent

load(dccnpath('/home/common/matlab/fieldtrip/data/test/latest/raw/meg/preproc_ctf275.mat'));

cfg = [];
cfg.method = 'fastica';
cfg.numcomponent = 20;
cfg.channel = 'MEG';
comp = ft_componentanalysis(cfg, data);

cfg = [];
cfg.component = 1:5;
datanew = ft_rejectcomponent(cfg, comp);

if size(datanew.grad.chanpos,1)~=numel(datanew.grad.label)
  error('labels in the grad structure are inconsistent with the chanpos');
end


classdef L1_Magic < handle
    % L1_Magic: using modified total variation of L1-magic package
    %
    % (c) Thomas Kuestner
    % ---------------------------------------------------------------------

    properties
%         oversampling % oversampling along space directions
        type % reconstruction type
        solver % define which optimization problem should be solved
        measPara % struct containing all measurement parameters (dim, dimension, ...)
%         dimension % 2D (x-y or x-y-t), 3D (x,y,z) or 4D (x,y,z,t) problem
%         dim % nPha x nFreq x nZ x nTime x nCha
        fullMask % mask of acquired data points
        trafo % struct of (tight frame) transformation in sparse basis
        epsilon % relaxation parameter
        lbtol % log barrier algorithm terminates when the duality gap <= lbtol
        mu % increase of barrier constant at each iteration
        cgtol % tolerance for Conjugate Gradients
        cgmaxiter % maximum number of iterations for Conjugate Gradients
        pdmaxiter % maximum number of iterations for primal dual algorithm
        pf % partial fourier parameters
        window % cut out window options
        kernelSize % kernel window dimension for convolution with calibration data
        currSlice % current slice, just needed for 2D with several slices
        currCha % current channel, just needed for 2D/3D with several channels
        lSense % apply SENSE mask for channel weighting
        kSpace % store kSpace in object
        espresso % ESPReSSo parameter
        dRecontime % recon time
    end

    methods
        function obj = L1_Magic(solver, measPara, epsilon, lbtol, mu, cgtol, cgmaxiter, pdmaxiter, espresso)
            obj.measPara = measPara;
            obj.epsilon = epsilon;
            obj.lbtol = lbtol;
            obj.mu = mu;
            obj.cgtol = cgtol;
            obj.cgmaxiter = cgmaxiter;
            obj.pdmaxiter = pdmaxiter;
            obj.solver = solver;
            obj.espresso = espresso;
            obj.type = 'L1_Magic';
        end
    end

end


function model  = modelSetOutputWeights(model, W, b)

% MODELSETOUTPUTWEIGHTS Wrapper function to return set output weight and bias matrices.
% FORMAT
% DESC sets the output weight and bias matrices for any mapping model
% that can be interpreted as a generalised linear model (e.g. rbf
% networks, kernel based regressions, multi layer perceptrons, linear).
% RETURN model : the model with updated weights and bias matrices.
% ARG model : the mapping model.
% ARG W : the output weight matrix.
% ARG b : the output biases.
%
% SEEALSO : mlpCreate, rbfCreate, kbrCreate, linearCreate
%
% COPYRIGHT : Neil D. Lawrence, 2008

% MLTOOLS

switch model.type
 case 'mlp'
  model.w2 = W;
  model.b2 = b;
 case 'rbf'
  model.w2 = W;
  model.b2 = b;
 case 'kbr'
  model.A = W;
  model.bias = b;
 case 'linear'
  model.W = W;
  model.b = b;
 otherwise
  error('Model has no implementation of output weights and biases.');
end


function [lstmStates, attnData, attnInfos] = rnnLayerForward(W_rnn, W_emb, prevState, input, masks, params, rnnFlags, attnData, model)
% Running Multi-layer RNN for one time step.
% Input:
%   W_rnn: recurrent connections of multiple layers, e.g., W_rnn{ll}.
%   prevState: previous hidden state, e.g., for LSTM, prevState.c{ll}, prevState.h{ll}.
%   input: indices for the current batch
%   isTest: 1 -- don't store intermediate results in each state
%   isAttn: for attention, require attnData to be non-empty, has
%     attnData.srcHidVecsOrig and attnData.srcLens.
%   isDecoder: 0 -- encoder, 1 -- decoder
% Output:
%   nextState
%
% Thang Luong @ 2015, <lmthang@stanford.edu>

T = size(input, 2);
lstmStates = cell(T, 1);

% attention
attnInfos = cell(T, 1);
if rnnFlags.attn && rnnFlags.decode == 0 % encoder
  assert(T <= params.numSrcHidVecs);
  attnData.srcHidVecsOrig = zeroMatrix([params.lstmSize, params.curBatchSize, params.numSrcHidVecs], params.isGPU, params.dataType);
end

for tt=1:T % time
  % local monotonic alignment
  if params.attnLocalMono
    attnData.tgtPos = tt;
  end

  % multi-layer RNN
  [prevState, attnInfos{tt}] = rnnStepLayerForward(W_rnn, W_emb(:, input(:, tt)), prevState, masks(:, tt), params, rnnFlags, attnData, model);

  % encoder, attention
  if rnnFlags.attn && rnnFlags.decode == 0
    attnData.srcHidVecsOrig(:, :, tt) = prevState{end}.h_t;
  end

  % store all states
  lstmStates{tt} = prevState;
end


function chrpak_test006 ( )

%*****************************************************************************80
%
%% TEST006 tests BINARY_TO_I4 and I4_TO_BINARY.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    09 June 2007
%
%  Author:
%
%    John Burkardt
%
  test_num = 4;

  i4_test = [ 21, -32, 2, 128 ];

  fprintf ( 1, '\n' );
  fprintf ( 1, 'TEST006\n' );
  fprintf ( 1, '  BINARY_TO_I4 converts a binary to an integer.\n' );
  fprintf ( 1, '  I4_TO_BINARY converts an integer to binary,\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  I4 ==> BINARY ==> I4\n' );
  fprintf ( 1, '\n' );

  for test = 1 : test_num

    i4 = i4_test(test);
    s = i4_to_binary ( i4 );
    j4 = binary_to_i4 ( s );

    fprintf ( 1, '  %8d  %8s  %8d\n', i4, s, j4 );

  end

  return
end


function Y=sparse(varargin)
%SPARSE (overloaded)

if nargin < 3
    error('At-least 3 arguments needed');
end

data = varargin{3};
ns = varargin{1}(:);
ms = varargin{2}(:);

if length(ns)~=length(ms) | length(ms)~=length(data)
    error('Length of first 3 arguments must be equal');
end

if min(size(data))>1
    error('Third argument should be a vector');
end

if nargin < 4
    n = max(ns);
else
    n = varargin{4};
end
if nargin < 5
    m = max(ms);
else
    m = varargin{5};
end

if any(ms>m)
    error('Dimension mismatch')
end

if any(ns>n)
    error('Dimension mismatch')
end

Y = data;
Y.dim(1) = n;
Y.dim(2) = m;
[i1,j1,s1] = find(data.basis);
ind = ns+(ms-1)*n;
Y.basis = sparse(ind(i1),j1,s1,n*m,1+length(Y.lmi_variables));
% Reset info about conic terms
Y.conicinfo = [0 0];
Y = flush(Y);


function job = clusterVariantGraph(job,varargin)
% the MCL algorithm generalized to hyper graphs
%
% Syntax
%
%   job.calcVariantGraph
%   job.clusterVariantGraph
%   job.calcParentFromVote('minProb',0.5)
%
% Input
%  job - @parentGrainReconstructor
%
% Output
%  job.votes - computed parent votes
%
% Options
%  inflationPower - inflation power of the MCL algorithm (default=1.05)
%  numIter        - number of iterations (default=10)
%  cutOff         - default 0.0001
%  withDiagonal   -
%  keepGraph      - do not kill graph after clustering
%  includeSimilar - similarly oriented variants share probability
%  includeTwins   - potential twins share probability
%  minCluster     - minimum cluster size (default 4)
%
% References
%
% * <https://arxiv.org/abs/2201.02103 The variant graph approach to
% improved parent grain reconstruction>, arXiv, 2022
%

% ensure we have a variant graph
if isempty(job.graph), job.calcVariantGraph(varargin{:}); end

% extract parameters
p = get_option(varargin,'inflationPower', 1.05);
numIter = get_option(varargin,'numIter', 10);
cutOff = get_option(varargin,'cutOff',0.0001);

% some constants
A = job.graph;
nVG = size(A,1); % size of the variant graph
job.graph = [];
p2cV = variants(job.p2c,'parent');
numV = length(p2cV);

% indices to the variant graph
isCP = job.isChild | job.isParent; % only child and parent phases go into the variant graph

% rep2VG - how often it repeats to fit in the variant graph [numV numV 1 numV 0 1 numV ...]
rep2VG = numV * job.isChild + job.isParent;

% VG2ind - variant graph index -> grain index
VG2ind = 1:length(job.grains);
VG2ind = repelem(VG2ind(isCP), rep2VG(isCP));

% indeces of the pseudo diagonal
if check_option(varargin,'noPseudoDiagonal')

  % position of variant 1 of each child grain in the Matrix
  indV1 = [0;cumsum(rep2VG)];
  indV1(end) = [];
  indV1 = indV1(job.isChild);

  % a numV x numV matrix without diagonal
  [i,j] = meshgrid(1:numV,1:numV);
  i(eye(numV)==1) = [];
  j(eye(numV)==1) = [];

  pseudoDiag = sparse(indV1 + i(:).',indV1 + j(:).',true,size(A,1),size(A,2));
end

normalize

% this is an adaptation of the MCL algorithm
for iter = 1:numIter

  % expansion
  A = A * A;

  % remove pseudo diagonal entries, i.e., A(j+k,j+l)
  if exist('pseudoDiag','var'), A(pseudoDiag) = 0; end

  % inflation by Hadamard potentiation
  A = A.^p;

  % prune elements of A that are below minval
  %A = (A > cutOff) .* A;
  A = spfun(@(x) (x > cutOff) .* x,A);

  if check_option(varargin,'sym')
    A = sqrt(A.' .* A);
    normalize
  end

  % column re-normalisation
  normalize

  if check_option(varargin,'test2')
    A = sqrt(diag(diag(A)) * A);
    normalize
  end

  if check_option(varargin,'verbose'), disp(nnz(A)); end
end

if check_option(varargin,'test1')
  A = diag(diag(A)) * A;
  normalize
end

if check_option(varargin,'sym')
  A = sqrt(A.' .* A);
  normalize
end

% create a table of probabilities for the different parentIds of each child
% grains
if p>1
  s = full(sum(A,2)); % sum columns
else
  s = full(sum(A,2) - diag(A)); % sum columns
end

% ensure minimum cluster size
minCluster = get_option(varargin,'minCluster',4);
s = s .* (full(sum(A>0,2))>=minCluster);

% store in numGrains x numVariant matrix
isVGChild = job.isChild(VG2ind); % isChild in variant graph
pIdP = nan(length(job.grains),numV);
pIdP(job.isChild,:) = reshape(s(isVGChild),numV,[]).';

% some post processing
if check_option(varargin,'includeTwins')

  % define theoretical twinning of the packet
  tp2cV = p2cV(:) .* orientation.byAxisAngle(round(p2cV \ Miller(0,1,1,p2cV.SS),'maxHKL',1),60*degree);

  M = 0.5*triu(angle_outer(p2cV,tp2cV,'noSym2') < 5 * degree);

  M(~sum(M),~sum(M)) = eye(nnz(~sum(M)));
  pIdP = pIdP * M;
end

if check_option(varargin,'includeSimilar')
  %M = triu(angle_outer(job.p2c.variants('parent'),job.p2c.variants('parent'),'noSym2')<5*degree);
  %M(:,sum(M)==1) = 0;

  M = angle_outer(p2cV,p2cV,'noSym2')<5*degree;
  M = 0.9*M + 0.1*eye(size(M));

  pIdP = pIdP * M;

elseif check_option(varargin,'mergeSimilar')

  M = angle_outer(p2cV,p2cV,'noSym2')<5*degree;
  pIdP = pIdP * M;

end

% sort the table and store the highest probabilities in the job class
[pIdP,pId] = sort(pIdP,2,'descend');
job.votes = table(pId,pIdP,'VariableNames',{'parentId','prob'});

if check_option(varargin,'keepGraph')
  job.graph = A;
end

  function normalize2

    % column re-normalisation
    % sum over all targets
    s = full(sum(A));

    % sum over all variants
    s = accumarray(VG2ind.',s);
    s = repelem(s,rep2VG(isPC));

    % create sparse diagonal matrix for
    dinv = spdiags(1./s,0,nVG,nVG);
    A = A * dinv;

  end
  function normalize

    % column re-normalisation
    % sum over all targets
    s = full(sum(A,2)).';

    % sum over all variants
    s = accumarray(VG2ind.',s);
    s = repelem(s(isCP),rep2VG(isCP));

    % create sparse diagonal matrix for
    dinv = spdiags(1./s,0,nVG,nVG);
    A = dinv * A;

  end
end


function [bn,burstiness,mburstf,mibsn,mbl,mibfr,mibif,burstf,ibsn,burstlen,ibfr,ibif,bp,normbnbdiff,burst,burstspikes,nonburstspikes] = burst_cls_kmeans(segspikes,sro)

% K-means clustering of ISIs
tivs = cell(1,size(segspikes,2));
ivnum = zeros(1,size(segspikes,2));
segfirstiv = zeros(1,size(segspikes,2));
seglastiv = zeros(1,size(segspikes,2));
for b1 = 1 : size(segspikes,2)
    tivs{b1} = diff(segspikes{b1});
    ivnum(b1) = length(tivs{b1});
    if b1 == 1
        seglastiv(b1) = ivnum(b1);
    else
        seglastiv(b1) = sum(ivnum(1 : b1 - 1)) + ivnum(b1);
    end
    if b1 == 1
        segfirstiv(b1) = 1;
    else
        segfirstiv(b1) = seglastiv(b1 - 1) + 1;
    end
end
ivs = cat(2,tivs{:});

%k-means starts
if length(ivs) > 49
    replino = 5;
    maxclust = 5;
    qual = zeros(1,maxclust);
    clustid = zeros(length(ivs),maxclust);
    for kmc1 = 2 : maxclust
        clustid(:,kmc1) = kmeans(ivs,kmc1,'emptyaction','drop','replicates',replino);
        qual(kmc1) = mean(silhouette(ivs',clustid(:,kmc1)));
    end
    ici = find(qual == max(qual));
    idealclust = clustid(:,ici);
    isiclusters = cell(1, ici);
    isiclustmean = zeros(1,ici);
    for kmc2 = 1 : ici
        isiclusters{kmc2} = ivs(idealclust == kmc2);
        isiclustmean(kmc2) = mean(isiclusters{kmc2});
    end
    ibclust = isiclusters{isiclustmean == min(isiclustmean)};
%k-means ends

%bf
    if isempty(ibclust) == 0
        firstspikes = cell(1,size(segspikes,2));
        lastspikes = cell(1,size(segspikes,2));
        segburstivs = cell(1,size(segspikes,2));
        for li1 = 1 : size(segspikes,2)
            segburstivs{li1} = find(tivs{li1} <= max(ibclust));
            sbiv1 = diff(segburstivs{li1});
            sbiv2 = find(sbiv1 > 1);
            firstspikes{li1} = segspikes{li1}(segburstivs{li1}(sbiv2 + 1));
            lastspikes{li1} = segspikes{li1}(segburstivs{li1}(sbiv2) + 1);
            firstspikes{li1} = [segspikes{li1}(1) firstspikes{li1}];
            lastspikes{li1} = [lastspikes{li1} segspikes{li1}(end)];
        end
        burst = [cat(2,firstspikes{:});cat(2,lastspikes{:})];
        burstlen = (burst(2,:) - burst(1,:)) / (sro / 1000); %length of bursts in ms
        burst(:,burstlen > 400) = [];
        burstlen(burstlen > 400) = [];
%bf

% maxthetacycle = 400;
% nonbursts = burst(:,bli >= maxthetacycle);
% burst(:,bli >= maxthetacycle) = [];

%Selection of burst and non-burst spikes
        spktm = cat(2,segspikes{:});
        burstspikes = cell(1,size(burst,2));
        ibsn = zeros(1,size(burst,2));
        for bj = 1 : size(burst,2)
            burstspikes{bj} = spktm(spktm >= burst(1,bj) & spktm <= burst(2,bj));
            ibsn(bj) = length(burstspikes{bj});
        end
        burstspkvect = cat(2,burstspikes{:});
        nbs = zeros(1,length(spktm));
        for nbi = 1 : length(spktm)
            for nbj = 1 : length(burstspkvect)
                if spktm(nbi) == burstspkvect(nbj)
                nbs(nbi) = 1;
                end
            end
        end
        nonburstspikes = spktm(nbs == 0);
%selection of burst & non-burst intervals
        nbss = zeros(1,length(ivs));
        for ni = 1 : length(ivs)
            for nj = 1 : length(ibclust)
                if ivs(ni) == ibclust(nj)
                    nbss(ni) = 1;
                end
            end
        end
        nbivs = ivs(nbss ~= 1);

%Comparison of burst and non-burst intervals
        if length(nbivs) >= 5
            bp = ranksum(ibclust,nbivs,0.01,'tail','both'); %ranksum test for burst - non-burst intervals
        else
            bp = -1;
        end
        normbnbdiff = (median(nbivs) - median(ibclust)) / (median(nbivs) + median(ibclust)); %normalized diff of burst - non-burst intervals

%burst parameter definitions
        mbl = median(burstlen); %median burst length
        ibif = 1./ibclust * sro; %intraburst inst.frequency
        mibif = median(1./ibclust*sro); %median intraburst inst.frequency
        ibfr = (ibsn ./ (burstlen/1000)); %intraburst firing rate per burst
        mibfr = median(ibfr); %median intraburst firing rate
        burstiness = (size(burstspkvect,2) / size(cat(2,segspikes{:},2),2)) * 100; %proportion of burst spikes
        covibsi = std(ibclust) / mean(ibclust); %COV of intraburst intervals
        first_isis = diff(cat(2,firstspikes{:})); %inter-firstspike intervals
        mfisis = median(first_isis) / (sro / 1000); % median interburst interval (ms)
        burstf = (1./first_isis)*sro; %inter-firstspike IF
        mburstf = median(burstf); %burst occurrence frequency
        bn = size(burst,2); %number of bursts
        mibsn = median(ibsn); %median intraburst spike number
    else
        bn = NaN;
        burstiness = NaN;
        mburstf = NaN;
        mibsn = NaN;
        mbl = NaN;
        mibfr = NaN;
        mibif = NaN;
        burstf = NaN;
        ibsn = NaN;
        burstlen = NaN;
        ibfr = NaN;
        ibif = NaN;
        bp = NaN;
        normbnbdiff = NaN;
        burst = NaN;
        burstspikes = NaN;
        nonburstspikes = NaN;
    end
else
    bn = NaN;
    burstiness = NaN;
    mburstf = NaN;
    mibsn = NaN;
    mbl = NaN;
    mibfr = NaN;
    mibif = NaN;
    burstf = NaN;
    ibsn = NaN;
    burstlen = NaN;
    ibfr = NaN;
    ibif = NaN;
    bp = NaN;
    normbnbdiff = NaN;
    burst = NaN;
    burstspikes = NaN;
    nonburstspikes = NaN;
end


function [coords] = GetSquare(x1,x2,x3,x4)

% This function draws a square defined by vertices

% Sanity check
assert(numel(x1) <= 3,"Coordinates can have upto three dimensions.");
assert(iscolumn(x1) == iscolumn(x2) == iscolumn(x3) == iscolumn(x3),"The coordinate vectors must be the same length.");

coords = zeros(5,3);
for i = 1:numel(x1)
    coords(:,i) = [x1(i);x2(i);x3(i);x4(i);x1(i)];
end

end


function  [s_idx, seg]    =  Proc_cls_idx( cls_idx )

[idx  s_idx]    =  sort(cls_idx);

idx2   =  idx(1:end-1) - idx(2:end);
seq    =  find(idx2);

seg    =  [0; seq; length(cls_idx)];


function aistats2012_slides_gp

randn('state', 1);

plot_gp(true, 0.2, 0.4, 100, false, ...
        '/home/jluttine/papers/aistats2012/slides/fig_short', ...
        8, 8);
plot_gp(true, 1.5, 0.4, 100, false, ...
        '/home/jluttine/papers/aistats2012/slides/fig_long', ...
        8, 8);
plot_gp(false, 1, 0.2, 6, 5, ...
        '/home/jluttine/papers/aistats2012/slides/fig_gp', ...
        6, 4);

function plot_gp(noisy, lengthscale, noise, N_all, samples, filename, width, height);
xmin = 0;
xmax = 10;

Nh = 1000;
xh = linspace(xmin, xmax, Nh);

x_all = linspace(xmin+0.5, xmax-0.5, N_all);
%x_all = unifrnd(xmin, xmax, 1, N_all);

% Generate data
covfunc_all = gp_cov_sum(gp_cov_se(sq_dist(x_all), ...
                                 'lengthscale', lengthscale), ...
                       gp_cov_scale(gp_cov_delta(N_all), ...
                                    'scale', noise));

K_y = covfunc_all([]);
L_y = chol(K_y + 1e-6*eye(N_all), 'lower');
y_all = L_y * randn(N_all,1);

for N = [N_all]
  x = x_all(:,1:N);
  y = y_all(1:N);

  covfunc_y = gp_cov_sum(gp_cov_se(sq_dist(x), ...
                                   'lengthscale', lengthscale), ...
                         gp_cov_scale(gp_cov_delta(N), ...
                                      'scale', noise));
  covfunc_yf = gp_cov_se(sq_dist(x,xh), ...
                         'lengthscale', lengthscale);
  if noisy
    covfunc_f = gp_cov_sum(gp_cov_se(zeros(Nh,1), ...
                                     'lengthscale', lengthscale), ...
                           gp_cov_scale(gp_cov_wrap(ones(Nh,1)), ...
                                        'scale', 0.3));
  else
    covfunc_f = gp_cov_se(zeros(Nh,1), ...
                          'lengthscale', lengthscale);
  end

  K_y = covfunc_y([]);
  K_yf = covfunc_yf([]);
  k_f = covfunc_f([]);

  [fh_mean, fh_var] = gp_predict(y, K_y, K_yf, k_f);
  figure
  errorplot(xh, fh_mean, sqrt(fh_var))
  hold on
  plot(x, y, 'r+')
  set(gca, 'xtick', [], 'ytick', []);
  set(gca, 'box', 'off');
  set_figure_size(width,height);
  print('-dpdf', [filename, '.pdf'])
  yl = get(gca, 'ylim');

  if samples
    covfunc_f = gp_cov_se(sq_dist(xh), ...
                          'lengthscale', lengthscale);
    K_f = covfunc_f([]);
    K_post = K_f - K_yf'*(K_y\K_yf) + 1e-6*eye(Nh);
    L_post = chol(K_post, 'lower');
    f = bsxfun(@plus, ...
               K_yf'*(K_y\y), ...
               L_post*randn(Nh,samples));
    figure
    plot(xh, f);
    hold on
    plot(x, y, 'k+');
    set(gca, 'xtick', [], 'ytick', []);
    set(gca, 'box', 'off');
    set(gca, 'ylim', yl);
    set_figure_size(width,height);
    print('-dpdf', [filename, '_samples.pdf'])
  end

end


function [dP_dV, dP_dlam] = cpf_p_jac(parameterization, z, V, lam, Vprv, lamprv, pv, pq)
%CPF_P_JAC Computes partial derivatives of CPF parameterization function.
%   [DP_DV, DP_DLAM ] = CPF_P_JAC(PARAMETERIZATION, Z, V, LAM, ...
%                                                   VPRV, LAMPRV, PV, PQ)
%
%   Computes the partial derivatives of the continuation power flow
%   parameterization function w.r.t. bus voltages and the continuation
%   parameter lambda.
%
%   Inputs:
%       PARAMETERIZATION : Value of cpf.parameterization option.
%       Z : normalized tangent prediction vector from previous step
%       V : complex bus voltage vector at current solution
%       LAM : scalar lambda value at current solution
%       VPRV : complex bus voltage vector at previous solution
%       LAMPRV : scalar lambda value at previous solution
%       PV : vector of indices of PV buses
%       PQ : vector of indices of PQ buses
%
%   Outputs:
%       DP_DV : partial of parameterization function w.r.t. voltages
%       DP_DLAM : partial of parameterization function w.r.t. lambda
%
%   See also CPF_PREDICTOR, CPF_CORRECTOR.

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

if parameterization == 1        %% natural
    npv = length(pv);
    npq = length(pq);
    dP_dV = zeros(1, npv+2*npq);
    if lam >= lamprv
        dP_dlam = 1.0;
    else
        dP_dlam = -1.0;
    end
elseif parameterization == 2    %% arc length
    Va = angle(V);
    Vm = abs(V);
    Vaprv = angle(Vprv);
    Vmprv = abs(Vprv);
    dP_dV = 2*([Va([pv; pq]); Vm(pq)] - [Vaprv([pv; pq]); Vmprv(pq)])';
    if lam == lamprv    %% first step
        dP_dlam = 1.0;  %% avoid singular Jacobian that would result
                        %% from [dP_dV, dP_dlam] = 0
    else
        dP_dlam = 2*(lam-lamprv);
    end
elseif parameterization == 3    %% pseudo arc length
    nb = length(V);
    dP_dV = z([pv; pq; nb+pq])';
    dP_dlam = z(2*nb+1);
end


function varargout = getsamples(filename, varargin)
% Read samples from acq file
%   filename - acq file
%   varargin - channel names
% Returns column vectors of all channel data samples of requested channels.
% Example:
%   [SourceR, EMG_L, EMG_R] = getsamples('myfile.acq', 'SourceR', 'EMG_L', 'EMG_R');
% Note:
% Developed and tested for version 3.5 AcqKnowledge files, but should
% probably work with other versions as well.
% Multiple sampling rates are not supported.
% No copyright. Feel free to use this code snippet in any way you want.

n = length(varargin);        % Number of channels to read

% Step through each file section until Channel Data Section is reached.
fp = fopen(filename, 'r');
% Graph Header Section
fseek(fp, 6, 'bof');
lExtItemHeaderLen = fread(fp, 1, 'int32');
nChannels = fread(fp, 1, 'int16');
% Per Channel Data Section
sectionstart = lExtItemHeaderLen;
fseek(fp, sectionstart, 'bof');
lChanHeaderLen = fread(fp, 1, 'int32');
fseek(fp, sectionstart+88, 'bof');
lBufLength = fread(fp, 1, 'int32');     % Number of samples, same for all channels
for i=1:nChannels
    sectionstart = lExtItemHeaderLen + (i-1)*lChanHeaderLen;
    fseek(fp, sectionstart+6, 'bof');
    szCommentText(i,1:40) = fscanf(fp, '%40c', 1);  % This is the channel label
    fseek(fp, sectionstart+92, 'bof');
    dAmplScale(i) = fread(fp, 1, 'double');
    dAmplOffset(i) = fread(fp, 1, 'double');
end
% Foreign Data Section
fseek(fp, lExtItemHeaderLen+lChanHeaderLen*nChannels, 'bof');
nLength = fread(fp, 1, 'int16');
% Per Channel Data Types Section
sectionstart = lExtItemHeaderLen + lChanHeaderLen*nChannels + nLength;
fseek(fp, sectionstart, 'bof');
for i=1:nChannels
    nSize(i) = fread(fp, 1, 'int16');
    nType(i) = fread(fp, 1, 'int16');
end
choffset = cumsum([0 nSize(1:end-1)]);  % Interleave offset
% Channel Data Section
% First find indexes of channels to read by searching channel labels, ...
for k=1:n
    for i=1:nChannels
        chlabel = char(varargin{k});
        if strncmp(chlabel, szCommentText(i,:), length(chlabel))
            chindex(k) = i;
            break;
        end
    end
end
% ...then read samples, one channel at a time.
sectionstart = lExtItemHeaderLen + lChanHeaderLen*nChannels + nLength + 4*nChannels;
fseek(fp, sectionstart, 'bof');
blocksize = sum(nSize);
for k=1:n
    fseek(fp, sectionstart + choffset(chindex(k)), 'bof');
    switch nType(chindex(k))
        case 1  % double
            varargout(k) = {fread(fp, lBufLength, 'double', blocksize-8)};
        case 2  % int
            varargout(k)= {dAmplScale(chindex(k)) * fread(fp, lBufLength, 'int16', blocksize-2) + ...
                                    dAmplOffset(chindex(k))};
    end
end

fclose(fp);


function d =  generate(a)

 if ~isa(a.child,'cell') r=[]; r{1}=a.child; a.child=r; end;

 ps=a.prior;
 for j=1:length(ps)
   ps(j)=sum(ps(1:j));
   a.child{j}.l=1;
 end
 ps=[0 ps];

 k=length(a.child);

 xs=[]; ys=[];
 for i=1:a.l
   p=rand; j=max(find(p>ps)); %% choose class
   x=get_x(test(a.child{j})); %% generate data with that class
   y=-ones(1,k); y(j)=1;
   xs=[xs ; x]; ys=[ys ; y];
 end

 if size(ys,2)==2 ys=ys(:,1); end;

 d=data(get_name(a),xs,ys);


function [u v] = opticalFlow_Classic_NL(frame1, frame2)

%tic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
uv = estimate_flow_interface(frame1, frame2, 'classic+nl-fast');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%toc

u = uv(:,:,1);
v = uv(:,:,2);


% General state space model for gps imu integration formulated in n-frame
% either in psi model or phi model. Psi model only appears in some
% papers, Phi model is well documented in books like Jekeli 2000, Titterton
% and Weston, 2000.

% states: IMU position in e frame, IMU velocity in n frame,
% attitude w.r.t n frame, accelerometer and gyro biases, accelerometer and gyro scale factors

% the error states are delta(r x,y,z in earth centered
% "abused" n frame), delta(vx, vy, vz in n frame),
% delta(roll, pitch, yaw) of the imu, accelerometer and gyro bias drift, acc
% scale and gyro scale factor error
% accelerometer and gyro bias are usually modeled as random walk, it can
% also be random constant, This does not make much difference
% acc scale and gyro scale factor are usually modeled as random walk, it can
% also be random constant, This does not make much difference

% The state dynamics are driven by a 18 (accel and gyro white noise,
% bias white noise and scale factor white noise) or 6 (only accel and
% gyro white noise) dimensional white Gaussian
% noise and the observations are corrupted by white Gaussian noise
% test cases: (1) random walk bias and scale facotr error, random constant
% bias and scale factor error,
% (2) covariance update step > sample interval
% (3) different imy types, 3DM GX3-35 AND h764g
% (4) psi and phi model
% There is a very subtle point in implementing a class in matlab. Always
% call a class the same name, do not call it a filter in a function and a
% model at another. It causes strange behaviors.
classdef EKF_filter_nframe < handle
    properties (Hidden)
        type = 'ekf';
        tag  = 'EKF_IMU_GPS_NFRM';  % ID tag
        covDim=9+12; % the dimension of covariance matrix
    end
    % The following properties can be set only by class methods
    properties (SetAccess = private)
        invalidateIMUerrors; % reset IMU errors when they goes beyond expectation
        imuType; % the type of IMU, e.g., MEMS 3DX GM 3-35, HG1700, etc.
        imuErrorModel=3;
        % the IMU error model corresponding to random walk bias and
        % random walk scale factor error,
        % 1 without turn on bias estimates,first order GM bias and random walk scale factor errors
        % 2 with random constant turn on bias estimates, first order GM bias and random walk scale factor errors
        % 3 assumes bias and scale factors are random walks
        % 4 assumes random constant bias and random constant scale factor errors

        % transform from vehicle body frame to IMU sensor frame
        Cb2imu;
        dt; % sampling interval of IMU, unit sec
        % the translation from antenna to IMU sensor frame, i.e., the antenna's
        % position in the s-frame.
        Tant2imu;
        Cen; % rotation from e frame to n frame
        height; % h in geodetic coordinates
        qs2n; % q s(sensor) 2 navigation frame
        Vn; % velocity of the IMU sensor in n frame
        imuErrors; %ba, bg, sa, sg

        imuOrientSIP=7; % imu orientation covariance start index
        imuBiasDriftSIP=10; %imu bias error covariance start index
        imuScaleFactorSIP=16;
        p_k_k; % the covariance of the entire state vector
        mode=1; % 1 for phi model, 2 for psi model
        mechanization=2; % 1 for wander azimuth, 2 for local geodetic
        rvqs2e; % added only for compatibility
        camPose; % added only for compatibility
    end
    methods
        function filter = EKF_filter_nframe(options)
            filter.invalidateIMUerrors=options.InvalidateIMUerrors;
            filter.imuType=options.imutype;
            filter.imuErrorModel=options.imuErrorModel;
            filter.dt=options.dt;
            filter.Cb2imu=options.Cb2imu;
            filter.Tant2imu=filter.Cb2imu*(options.Tant2body-options.Timu2body);
            filter.Vn=options.Vn;
            % initialize states and covariance for imu gps integration,
            % For imu, rs in n, vs in n, q s2n, ba, bg, sa, sg. (s denotes imu)
            % the position of GPS antenna
            inillh=options.inillh_ant;
            % Cb2n initial value given by external reference
            initqbn=options.qb2n;   % H764G INS data, this b refers to the vehicle body frame
            filter.qs2n=quatmult_v001(initqbn,rotro2qr(filter.Cb2imu),2);

            Ce2n0=llh2dcm_v000(inillh(1:2),[0;1]);
            qs2e=quatmult_v001(rotro2qr(Ce2n0), filter.qs2n,1);
            xyz_imu=ecef2geo_v000(inillh,1)-quatrot_v000(qs2e,filter.Tant2imu,0);
            inillh_imu=ecef2geo_v000(xyz_imu, 0);
            filter.height=inillh_imu(3); %elipsoidal height
            filter.Cen=llh2dcm_v000(inillh_imu(1:2),[0;1]);
            filter.imuErrors=options.imuErrors;
            filter.p_k_k=zeros(filter.covDim);
            filter.p_k_k(1:3,1:3)=eye(3)*1^2; %position errors in meter
            filter.p_k_k(4:6,4:6)=eye(3)*0.1^2; %vel error in m/s
            filter.p_k_k(filter.imuOrientSIP+(0:2),filter.imuOrientSIP+(0:2))=...
                diag([options.initAttVar,options.initAttVar,options.initAttVar*2].^2);

            IMU_ERRDEF=imu_err_defs_v000(options.imutype);
            filter.p_k_k(filter.imuBiasDriftSIP+(0:2),filter.imuBiasDriftSIP+(0:2))=4*eye(3)*IMU_ERRDEF.acc_bias_var;% enlarge initial std by 2
            filter.p_k_k(filter.imuBiasDriftSIP+(3:5),filter.imuBiasDriftSIP+(3:5))=4*eye(3)*IMU_ERRDEF.gyro_bias_var;

            filter.p_k_k(filter.imuScaleFactorSIP+(0:2),filter.imuScaleFactorSIP+(0:2))=4*eye(3)*IMU_ERRDEF.acc_scale_var;
            filter.p_k_k(filter.imuScaleFactorSIP+(3:5),filter.imuScaleFactorSIP+(3:5))=4*eye(3)*IMU_ERRDEF.gyro_scale_var;
            filter.mode= options.mode;
        end
        %===============================================================================================
        %-- State transition function
        % propogate state with accelerometer and gyro input at time k-1 to state at k,
        % i.e., X(k|k-1), from state at k-1. U1 contains IMU measurement
        % delta v, and delta angle of gyro or acc and angular rate
        % and 7th row is the previous epoch(k-1) and 8th row is the current epoch(k)
        % imuaccum records the accumulated delta v and delta angle for two speed
        % covariance update
        function imuaccum= ffun_state(filter, imuaccum, U1)
            if(sum(abs(U1(1:3,1)))<1)
                dt1=U1(8,end)-U1(7,1);
                gyroinc=sum(U1(4:6,:),2);
                accinc=sum(U1(1:3,:),2);

                %reset the imu errors if estimates diverges
                IMU_ERRDEF=imu_err_defs_v000(filter.imuType);

                if(filter.invalidateIMUerrors)
                    spuracc=find(abs(filter.imuErrors(1:3))>2*IMU_ERRDEF.initacc_bias_err,1);
                    spurgyro=find(abs(filter.imuErrors(4:6))>2*IMU_ERRDEF.initgyro_bias_err,1);
                    if(~isempty(spuracc)||~isempty(spurgyro))
                        disp(['IMU errors diverge at ' num2str(U1(8,end)) '!']);
                        filter.imuErrors=zeros(12,1);
                    end
                end
                angleinc=gyroinc-filter.imuErrors(4:6)*dt1-diag(gyroinc)*filter.imuErrors(6+(4:6))/1000;
                velinc=accinc-filter.imuErrors(1:3)*dt1-diag(accinc)*filter.imuErrors(6+(1:3))/1000;
                %imu data accumulator for the covariance update
                imuaccum=imuaccum+[velinc;angleinc];
            else
                dt1=U1(8,end)-U1(7,1);
                gyroinc=mean(U1(4:6,:),2);
                accinc=mean(U1(1:3,:),2);

                %reset the imu errors if estimates diverges
                IMU_ERRDEF=imu_err_defs_v000(filter.imuType);

                if(filter.invalidateIMUerrors)
                    spuracc=find(abs(filter.imuErrors(1:3))>2*IMU_ERRDEF.initacc_bias_err,1);
                    spurgyro=find(abs(filter.imuErrors(4:6))>2*IMU_ERRDEF.initgyro_bias_err,1);
                    if(~isempty(spuracc)||~isempty(spurgyro))
                        disp(['IMU errors diverge at ' num2str(U1(8,end)) '!']);
                        filter.imuErrors=zeros(12,1);
                    end
                end
                gyroinc=gyroinc-filter.imuErrors(4:6)-diag(gyroinc)*filter.imuErrors(6+(4:6))/1000;
                accinc=accinc-filter.imuErrors(1:3)-diag(accinc)*filter.imuErrors(6+(1:3))/1000;
                angleinc=gyroinc*dt1;
                velinc=accinc*dt1;
                %imu data accumulator for the covariance update
                imuaccum=imuaccum+[accinc;gyroinc]*dt1;
            end
            %run strapdown with angle and velocity increments
            [filter.qs2n, filter.Vn, filter.Cen, filter.height]=strapdown_Cen_quat_v000(...
                filter.qs2n, filter.Vn, filter.Cen, filter.height, velinc, angleinc, dt1);
        end
        function ffun_covariance(filter, imuaccum, covupt_time, curimutime)
            %propagate the covariance corresponds to states, rs in n, vs in n, \psi or \phi,
            % ba, bg, sa, sg
            covdt=curimutime-covupt_time;
            [STM, Qd]=sys_metric_phipsi_v000(filter.Cen, filter.height, ...
                filter.Vn, filter.qs2n,  imuaccum(1:3)/covdt,imuaccum(4:6)/covdt, ...
                covdt,filter.mode,filter.imuType, filter.imuErrorModel); %use psi implementation with 2
            %              if(filter.imuErrorModel==4)
            %                     [STM, Qd]=sys_metric_phipsi_v002(filter.Cen, filter.height, ...
            %                         filter.Vn, filter.qs2n,  imuaccum(1:3)/covdt,imuaccum(4:6)/covdt, ...
            %                         covdt,filter.mode,filter.imuType); %use psi implementation with 2
            %                     assert(norm(STM1-STM)+norm(Qd1-Qd)<1e-5);
            %              end
            filter.p_k_k=STM*filter.p_k_k*STM'+Qd;  % the covariance of the navigation states and imu error terms
        end
        %==============================================================================================
        %update both the covariance and state
        function correctstates(filter, predict,measure, H,R, ~)
            p_km1_k=filter.p_k_k;
            inno= predict-measure;
            %Kalman
            K=p_km1_k*H'/(H*p_km1_k*H'+R);
            deltaX=K*inno;
            % update covariance
            filter.p_k_k=(eye(filter.covDim)-K*H)*p_km1_k*(eye(filter.covDim)-K*H)'+K*R*K';
            % compute updated state
            [filter.qs2n, filter.Vn, filter.Cen, filter.height]=correctnav_Cen_v000(...
                filter.qs2n, filter.Vn, filter.Cen, filter.height,...
                deltaX(1:filter.imuOrientSIP+2), filter.mode, filter.mechanization);
            filter.imuErrors = filter.imuErrors + deltaX(filter.imuBiasDriftSIP:end);
        end
        % output: position of the IMU in a NED frame anchored at some point or in geodetic coordinates,
        % velocity of the IMU in the body frame, and euler angles of
        % rotation from body frame to the moving NED frame, and covariances
        % of 9 navigation ERROR states in the filter
        function SaveToFile(filter, inillh_ant, preimutime, ffilres)
            vr_c=rotqr2eu('xyz',quatmult_v001(filter.qs2n, rotro2qr(filter.Cb2imu), 0))*180/pi; % body frame w.r.t the moving N frame
            xyz_imu= ecef2geo_v000([asin(-filter.Cen(3,3));asin(-filter.Cen(2,1));filter.height],1);
         %   xyz_ant= xyz_imu + quatrot_v000(quatmult_v001(rotro2qr(filter.Cen),filter.qs2n,1),filter.Tant2imu,0);
            if(~isempty(inillh_ant))
                vr_a=posdiff_v001(xyz_imu, inillh_ant); % position of IMU in the initial N frame
                fwrite(ffilres,[preimutime;vr_a;filter.Vn;vr_c;sqrt(diag(filter.p_k_k(1:9,...
                    1:9)))],'double');
            else
                fwrite(ffilres,[preimutime;ecef2geo_v000(xyz_imu,0);filter.Vn;vr_c;sqrt(diag(filter.p_k_k(1:9,...
                    1:9)))],'double');
            end
        end
        function mag=GetVelocityMag(filter)
            mag=norm(filter.Vn,2);
        end
        function  SetCamAndRvqs2e(filter, options)
            filter.rvqs2e=zeros(10,1);
            Ce2n=filter.Cen;
            heights2n=filter.height;
            Re=6378137/(sqrt(1.0-0.00669437999014*Ce2n(3,3)^2));
            filter.rvqs2e(1:3,1)=-[(Re+heights2n)*Ce2n(3,1);(Re+heights2n)*Ce2n(3,2);(Re*(1-0.00669437999014)+heights2n)*Ce2n(3,3)];
            filter.rvqs2e(4:6,1)=Ce2n'*filter.Vn;
            filter.rvqs2e(7:10,1)=quatmult_v001(rotro2qr(Ce2n),filter.qs2n,1);
            filter.camPose=zeros(7,1);
            filter.camPose(5:7)=options.Cimu2cam*options.Cb2imu*(options.Timu2body-options.Tcam2body);
            filter.camPose(1:4)=rotro2qr(options.Cimu2cam);
        end
    end
end


function [f0v,vrv,dfv,nf,aav]=fixpF0VexMltpBG4(x,fs,f0floor,nvc,nvo,mu,imgi,shiftm,smp,minm,pc,nc)

%	Fixed point analysis to extract F0
%	[f0v,vrv,dfv,nf]=fixpF0VexMltpBG4(x,fs,f0floor,nvc,nvo,mu,imgi,shiftm,smp,minm,pc,nc)
%	x	: input signal
%	fs	: sampling frequency (Hz)
%	f0floor	: lowest frequency for F0 search
%	nvc	: total number of filter channels
%	nvo	: number of channels per octave
%	mu	: temporal stretching factor
%	imgi	: image display indicator (1: display image, default)
%	shiftm	: frame shift in ms
%	smp	: smoothing length relative to fc (ratio)
%	minm	: minimum smoothing length (ms)
%	pc	: exponent to represent nonlinear summation
%	nc	: number of harmonic component to use (1,2,3)

%	Designed and coded by Hideki Kawahara
%	28/March/1999
%	04/April/1999 revised to multi component version
%	07/April/1999 bi-reciprocal smoothing for multi component compensation
%	01/May/1999 first derivative of Amplitude is taken into account
%	17/Dec./2000 display bug fix
%	19/Sep./2002 bug fix (mu information was discarded.)
%   07/Dec./2002 waitbar was added
%	30/April/2005 modification for Matlab v7.0 compatibility
%	10/Aug./2005 modified by Takahashi on waitbar
%	10/Sept./2005 mofidied by Kawahara on waitbar
%   11/Sept./2005 fixed waitbar problem

%f0floor=40;
%nvo=12;
%nvc=52;
%mu=1.1;

x=cleaninglownoise(x,fs,f0floor);

fxx=f0floor*2.0.^((0:nvc-1)/nvo)';
fxh=max(fxx);

dn=max(1,floor(fs/(fxh*6.3)));

if nc>2
	pm3=multanalytFineCSPB(decimate(x,dn),fs/dn,f0floor,nvc,nvo,mu,3,imgi); % error crrect 2002.9.19 (mu was fixed 1.1)
	pif3=zwvlt2ifq(pm3,fs/dn);
	[~,mm]=size(pif3);
	pif3=pif3(:,1:3:mm);
	pm3=pm3(:,1:3:mm);
end;

if nc>1
	pm2=multanalytFineCSPB(decimate(x,dn),fs/dn,f0floor,nvc,nvo,mu,2,imgi);% error crrect 2002.9.19(mu was fixed 1.1)
	pif2=zwvlt2ifq(pm2,fs/dn);
	[~,mm]=size(pif2);
	pif2=pif2(:,1:3:mm);
	pm2=pm2(:,1:3:mm);
end;

pm1=multanalytFineCSPB(decimate(x,dn*3),fs/(dn*3),f0floor,nvc,nvo,mu,1,imgi);% error crrect 2002.9.19(mu was fixed 1.1)
%%%% safe guard added on 15/Jan./2003
mxpm1=max(max(abs(pm1)));
eeps=mxpm1/10000000;
pm1(pm1==0)=pm1(pm1==0)+eeps;
%%%% safe guard end
pif1=zwvlt2ifq(pm1,fs/(dn*3));
%keyboard;

[~,mm1]=size(pif1);
mm=mm1;
if nc>1
	[~,mm2]=size(pif2);
	mm=min(mm1,mm2);
end;

if nc>2
	[~,mm3]=size(pif3);
	mm=min([mm1 mm2 mm3]);
end;

if nc == 2
	for ii=1:mm
		pif2(:,ii)=(pif1(:,ii).*(abs(pm1(:,ii))).^pc ...
			+pif2(:,ii)/2.*(abs(pm2(:,ii))).^pc )...
			./((abs(pm1(:,ii))).^pc+(abs(pm2(:,ii))).^pc);
	end;
end;
if nc == 3
	for ii=1:mm
		pif2(:,ii)=(pif1(:,ii).*(abs(pm1(:,ii))).^pc ...
			+pif2(:,ii)/2.*(abs(pm2(:,ii))).^pc ...
			+pif3(:,ii)/3.*(abs(pm3(:,ii))).^pc )...
			./((abs(pm1(:,ii))).^pc+(abs(pm2(:,ii))).^pc+(abs(pm3(:,ii))).^pc);
	end;
end;
if nc == 1
	pif2=pif1;
end;

%pif2=zwvlt2ifq(pm,fs/dn)*2*pi;
pif2=pif2*2*pi;
dn=dn*3;

[slp,~]=zifq2gpm2(pif2,f0floor,nvo);
[nn,mm]=size(pif2);
dpif=(pif2(:,2:mm)-pif2(:,1:mm-1))*fs/dn;
dpif(:,mm)=dpif(:,mm-1);
[dslp,~]=zifq2gpm2(dpif,f0floor,nvo);

damp=(abs(pm1(:,2:mm))-abs(pm1(:,1:mm-1)))*fs/dn;
damp(:,mm)=damp(:,mm-1);
damp=damp./abs(pm1);

%[c1,c2]=znormwght(1000);
fxx=f0floor*2.0.^((0:nn-1)/nvo)'*2*pi;
mmp=0*dslp;
[c1,c2b]=znrmlcf2(1);
if imgi==1; hpg=waitbar(0,'P/N map calculation'); end; % 07/Dec./2002 by H.K.%10/Aug./2005
for ii=1:nn
%	[c1,c2]=znrmlcf2(fxx(ii)/2/pi); % This is OK, but the next Eq is much faster.
	c2=c2b*(fxx(ii)/2/pi)^2;
	cff=damp(ii,:)/fxx(ii)*2*pi*0;
	mmp(ii,:)=(dslp(ii,:)./(1+cff.^2)/sqrt(c2)).^2+(slp(ii,:)./sqrt(1+cff.^2)/sqrt(c1)).^2;
    if imgi==1; waitbar(ii/nn); end; %,hpg); % 07/Dec./2002 by H.K.%10/Aug./2005
end;
if imgi==1; close(hpg); end;%10/Aug./2005

if smp~=0
	smap=zsmoothmapB(mmp,fs/dn,f0floor,nvo,smp,minm,0.4);
else
	smap=mmp;
end;

fixpp=zeros(round(nn/3),mm);
fixvv=fixpp+100000000;
fixdf=fixpp+100000000;
fixav=fixpp+1000000000;
nf=zeros(1,mm);
if imgi==1; hpg=waitbar(0,'Fixed pints calculation'); end; % 07/Dec./2002 by H.K.%10/Aug./2005
for ii=1:mm
	[ff,vv,df,aa]=zfixpfreq3(fxx,pif2(:,ii),smap(:,ii),dpif(:,ii)/2/pi,pm1(:,ii));
	kk=length(ff);
	fixpp(1:kk,ii)=ff;
	fixvv(1:kk,ii)=vv;
	fixdf(1:kk,ii)=df;
	fixav(1:kk,ii)=aa;
	nf(ii)=kk;
    if imgi==1 && rem(ii,10)==0; waitbar(ii/mm); end;% 07/Dec./2002 by H.K.%10/Aug./2005
end;
if imgi==1; close(hpg); end; % 07/Dec./2002 by H.K.%10/Aug./2005
fixpp(fixpp==0)=fixpp(fixpp==0)+1000000;

%keyboard
%[vvm,ivv]=min(fixvv);
%
%for ii=1:mm
%	ff00(ii)=fixpp(ivv(ii),ii);
%	esgm(ii)=fixvv(ivv(ii),ii);
%end;
np=max(nf);
f0v=fixpp(1:np,round(1:shiftm/dn*fs/1000:mm))/2/pi;
vrv=fixvv(1:np,round(1:shiftm/dn*fs/1000:mm));
dfv=fixdf(1:np,round(1:shiftm/dn*fs/1000:mm));
aav=fixav(1:np,round(1:shiftm/dn*fs/1000:mm));
nf=nf(round(1:shiftm/dn*fs/1000:mm));

if imgi==1
	cnmap(fixpp,smap,fs,dn,nvo,f0floor,shiftm);
end;
%ff00=ff00(round(1:shiftm/dn*fs/1000:mm));
%esgm=sqrt(esgm(round(1:shiftm/dn*fs/1000:mm)));
%keyboard;

return;
%------------------------------------------------------------------
function okid=cnmap(fixpp,smap,fs,dn,nvo,f0floor,shiftm)

% 	This function had a bug in map axis.
%	17/Dec./2000 bug fix by Hideki Kawahara.

dt=dn/fs;
[nn,mm]=size(smap);
aa=figure;
set(aa,'PaperPosition',[0.3 0.25 8 10.9]);
set(aa,'Position',[30 130 520 680]);
subplot(211);
imagesc([0 (mm-1)*dt*1000],[1 nn],20*log10(smap(:,round(1:shiftm/dn*fs/1000:mm))));axis('xy')
hold on;
tx=((1:shiftm/dn*fs/1000:mm)-1)*dt*1000;
plot(tx,(nvo*log(fixpp(:,round(1:shiftm/dn*fs/1000:mm))/f0floor/2/pi)/log(2)+0.5)','ko');
plot(tx,(nvo*log(fixpp(:,round(1:shiftm/dn*fs/1000:mm))/f0floor/2/pi)/log(2)+0.5)','w.');
hold off
xlabel('time (ms)');
ylabel('channel #');
colormap(jet);

okid=1;
return;

%------------------------------------------------------------------

%%function pm=zmultanalytFineCSPm(x,fs,f0floor,nvc,nvo,mu,mlt);

%       Dual waveleta analysis using cardinal spline manipulation
%               pm=multanalytFineCSP(x,fs,f0floor,nvc,nvo);
%       Input parameters
%
%               x       : input signal (2kHz sampling rate is sufficient.)
%               fs      : sampling frequency (Hz)
%               f0floor : lower bound for pitch search (60Hz suggested)
%               nvc     : number of total voices for wavelet analysis
%               nvo     : number of voices in an octave
%				mu		: temporal stretch factor
%       Outpur parameters
%               pm      : wavelet transform using iso-metric Gabor function
%
%       If you have any questions,  mailto:kawahara@hip.atr.co.jp
%
%       Copyright (c) ATR Human Information Processing Research Labs. 1996
%       Invented and coded by Hideki Kawahara
%       30/Oct./1996

%t0=1/f0floor;
%lmx=round(6*t0*fs*mu);
%wl=2^ceil(log(lmx)/log(2));
%x=x(:)';
%nx=length(x);
%tx=[x,zeros(1,wl)];
%gent=((1:wl)-wl/2)/fs;

%nvc=18;

%wd=zeros(nvc,wl);
%wd2=zeros(nvc,wl);
%ym=zeros(nvc,nx);
%pm=zeros(nvc,nx);
%mpv=1;
%mu=1.0;
%for ii=1:nvc
%  t=gent*mpv;
%  t=t(abs(t)<3.5*mu*t0);
%  wbias=round((length(t)-1)/2);
%  wd1=exp(-pi*(t/t0/mu).^2);%.*exp(i*2*pi*t/t0);
%  wd2=max(0,1-abs(t/t0/mu));
%  wd2=wd2(wd2>0);
%  wwd=conv(wd2,wd1);
%  wwd=wwd(abs(wwd)>0.0001);
%  wbias=round((length(wwd)-1)/2);
%  wwd=wwd.*exp(i*2*pi*mlt*t(round((1:length(wwd))-wbias+length(t)/2))/t0);
%  pmtmp1=fftfilt(wwd,tx);
%  pm(ii,:)=pmtmp1(wbias+1:wbias+nx)*sqrt(mpv);
%  mpv=mpv*(2.0^(1/nvo));
%  keyboard;
%end;
%[nn,mm]=size(pm);
%pm=pm(:,1:mlt:mm);

%----------------------------------------------------------------
function pif=zwvlt2ifq(pm,fs)
%	Wavelet to instantaneous frequency map
%	fqv=wvlt2ifq(pm,fs)

%	Coded by Hideki Kawahara
%	02/March/1999

[~,mm]=size(pm);
pm=pm./(abs(pm));
pif=abs(pm(:,:)-[pm(:,1),pm(:,1:mm-1)]);
pif=fs/pi*asin(pif/2);
pif(:,1)=pif(:,2);

%----------------------------------------------------------------

function [slp,pbl]=zifq2gpm2(pif,f0floor,nvo)
%	Instantaneous frequency 2 geometric parameters
%	[slp,pbl]=ifq2gpm(pif,f0floor,nvo)
%	slp		: first order coefficient
%	pbl		: second order coefficient

%	Coded by Hideki Kawahara
%	02/March/1999

[nn,~]=size(pif);
fx=f0floor*2.0.^((0:nn-1)/nvo)*2*pi;

c=2.0^(1/nvo);
g=[1/c/c 1/c 1;1 1 1;c*c c 1];
h=inv(g);

%slp=pif(1:nn-2,:)*h(1,1)+pif(2:nn-1,:)*h(1,2)+pif(3:nn,:)*h(1,3);
slp=((pif(2:nn-1,:)-pif(1:nn-2,:))/(1-1/c) ...
    +(pif(3:nn,:)-pif(2:nn-1,:))/(c-1))/2;
slp=[slp(1,:);slp;slp(nn-2,:)];

pbl=pif(1:nn-2,:)*h(2,1)+pif(2:nn-1,:)*h(2,2)+pif(3:nn,:)*h(2,3);
pbl=[pbl(1,:);pbl;pbl(nn-2,:)];

for ii=1:nn
	slp(ii,:)=slp(ii,:)/fx(ii);
	pbl(ii,:)=pbl(ii,:)/fx(ii);
end;

%------------------------------------------

%function [c1,c2]=znormwght(n)

%zz=0:1/n:3;
%hh=[diff(zGcBs(zz,0)) 0]*n;
%c1=sum((zz.*hh).^2)/n;
%c2=sum((2*pi*zz.^2.*hh).^2)/n;

%-------------------------------------------

function p=zGcBs(x,k)

tt=x+0.0000001;
p=tt.^k.*exp(-pi*tt.^2).*(sin(pi*tt+0.0001)./(pi*tt+0.0001)).^2;

%--------------------------------------------
function smap=zsmoothmapB(map,fs,f0floor,nvo,mu,mlim,pex)

[nvc,mm]=size(map);
%mu=0.4;
t0=1/f0floor;
lmx=round(6*t0*fs*mu);
wl=2^ceil(log(lmx)/log(2));
gent=((1:wl)-wl/2)/fs;

smap=map;
mpv=1;
zt=0*gent;
iiv=1:mm;
for ii=1:nvc
	t=gent*mpv; %t0*mu/mpv*1000
	t=t(abs(t)<3.5*mu*t0);
	wbias=round((length(t)-1)/2);
	wd1=exp(-pi*(t/(t0*(1-pex))/mu).^2);
	wd2=exp(-pi*(t/(t0*(1+pex))/mu).^2);
	wd1=wd1/sum(wd1);
	wd2=wd2/sum(wd2);
	tm=fftfilt(wd1,[map(ii,:) zt]);
	tm=fftfilt(wd2,[1.0./tm(iiv+wbias) zt]);
	smap(ii,:)=1.0./tm(iiv+wbias);
	if t0*mu/mpv*1000 > mlim
		mpv=mpv*(2.0^(1/nvo));
	end;
end;

%--------------------------------------------
%function [ff,vv,df]=zfixpfreq2(fxx,pif2,mmp,dfv)
%
%nn=length(fxx);
%iix=(1:nn)';
%cd1=pif2-fxx;
%cd2=[diff(cd1);cd1(nn)-cd1(nn-1)];
%cdd1=[cd1(2:nn);cd1(nn)];
%fp=(cd1.*cdd1<0).*(cd2<0);
%ixx=iix(fp>0);
%ff=pif2(ixx)+(pif2(ixx+1)-pif2(ixx)).*cd1(ixx)./(cd1(ixx)-cdd1(ixx));
%vv=mmp(ixx);
%vv=mmp(ixx)+(mmp(ixx+1)-mmp(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));
%df=dfv(ixx)+(dfv(ixx+1)-dfv(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));

%--------------------------------------------
function [ff,vv,df,aa]=zfixpfreq3(fxx,pif2,mmp,dfv,pm)

aav=abs(pm);
nn=length(fxx);
iix=(1:nn)';
cd1=pif2-fxx;
cd2=[diff(cd1);cd1(nn)-cd1(nn-1)];
cdd1=[cd1(2:nn);cd1(nn)];
fp=(cd1.*cdd1<0).*(cd2<0);
ixx=iix(fp>0);
ff=pif2(ixx)+(pif2(ixx+1)-pif2(ixx)).*cd1(ixx)./(cd1(ixx)-cdd1(ixx));
%vv=mmp(ixx);
vv=mmp(ixx)+(mmp(ixx+1)-mmp(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));
df=dfv(ixx)+(dfv(ixx+1)-dfv(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));
aa=aav(ixx)+(aav(ixx+1)-aav(ixx)).*(ff-fxx(ixx))./(fxx(ixx+1)-fxx(ixx));

%--------------------------------------------
function [c1,c2]=znrmlcf2(f)

n=100;
x=0:1/n:3;
g=zGcBs(x,0);
dg=[diff(g) 0]*n;
dgs=dg/2/pi/f;
xx=2*pi*f*x;
c1=sum((xx.*dgs).^2)/n*2;
c2=sum((xx.^2.*dgs).^2)/n*2;

%--------------------------------------------
function x=cleaninglownoise(x,fs,f0floor)

flm=50;
flp=round(fs*flm/1000);
nn=length(x);
wlp=fir1(flp*2,f0floor/(fs/2));
wlp(flp+1)=wlp(flp+1)-1;
wlp=-wlp;

tx=[x(:)' zeros(1,2*length(wlp))];
ttx=fftfilt(wlp,tx);
x=ttx((1:nn)+flp);

return;


function t = subsasgn(t,s,b)
%SUBSASGN Subscripted assignement for ktensor.
%
%   See also KTENSOR.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.

% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt

switch s(1).type
    case '.'
        switch s(1).subs
            case 'lambda'
                if length(s) == 1
                    t = ktensor(b, t.u);
                else
                    newlambda = subsasgn(t.lambda, s(2:end), b);
                    t = ktensor(newlambda, t.u);
                end
            case {'u','U'}
                if length(s) == 1
                    t = ktensor(t.lambda, b);
                else
                    tmpu = subsasgn(t.u, s(2:end), b);
                    t = ktensor(t.lambda, tmpu);
                end
            otherwise
                error(['No such field: ', s(1).subs]);
        end
    case '()'
        error('Cannot change individual entries in a ktensor.')
    case '{}'
        new_s(1).type = '.';
        new_s(1).subs = 'u';
        new_s(2:length(s)+1) = s;
        t = subsasgn(t, new_s, b);
    otherwise
        error('Invalid subsasgn.');
end


function gridlines_test03 ( )

%*****************************************************************************80
%
%% GRIDLINES_TEST03 tests GRID_TRIANGULAR.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    30 July 2010
%
%  Author:
%
%    John Burkardt
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GRIDLINES_TEST03\n' );
  fprintf ( 1, '  GRID_TRIANGULAR draws a triangular grid.\n' );

  axis ( [ 0.0, 1.0, 0.0, 1.0 ] );

  xval = [ 0.1, 0.95, 0.25 ];
  yval = [ 0.1, 0.2, 0.90 ];
  ngrid = 10;
  grid_triangular ( xval, yval, ngrid );

  xval = [ 0.8, 0.6, 0.7 ];
  yval = [ 0.9, 0.9, 0.7 ];
  ngrid = 3;
  grid_triangular ( xval, yval, ngrid );

  xlabel ( 'X' )
  ylabel ( 'Y' )
  title ( 'Triangular grids' )
  axis equal

  fprintf ( 1, '\n' );
  fprintf ( 1, 'Press return to continue.\n' )
  hold off
  pause
  clf

  return
end


function y = objfun_grad(x)

y = [(2/3)*x(1);x(2)];


function mObject = setAnchorFromRawAnchor(mObject,rawAnchor);
%   Set anchor points using raw anchor information
%   mObject = setAnchorFromRawAnchor(mObject,rawAnchor);

%   Designed and coded by Hideki Kawahara
%   27/Feb./2005
%   Copyright(c) 2005, Hideki Kawahara

TIMINGmARGIN = 10; % threshould for merging location
[dm1,indsrt] = sort(rawAnchor(:,1));
sortedAnchor = rawAnchor(indsrt,1);
sortedFrequency = rawAnchor(indsrt,2);
indexNumber = 1:length(sortedAnchor);

%anchorCandidate = sortedAnchor(diff([-100;sortedAnchor])>TIMINGmARGIN);
anchorIndex = indexNumber(diff([-100;sortedAnchor])>TIMINGmARGIN);
anchorCandidate = sortedAnchor(anchorIndex);
mObject.anchorTimeLocation = anchorCandidate;
nFrequency = mObject.maximumFrequencyPoints;

nAnchor = length(anchorCandidate);
sortedAnchor(end+1) = sortedAnchor(end)+1;
anchorIndex(end+1) = anchorIndex(end)+1; % Terminator
frequencyAnchor = zeros(nAnchor,nFrequency);
for ii=1:nAnchor
    iFrequency = 0;
    anchorLocation = 0;
    for jj=1:min(nFrequency,anchorIndex(ii+1)-anchorIndex(ii)+1)
        if sortedAnchor((jj-1)+anchorIndex(ii)) < sortedAnchor(anchorIndex(ii+1))
            frequencyAnchor(ii,jj) = sortedFrequency((jj-1)+anchorIndex(ii));
            anchorLocation = anchorLocation+sortedAnchor((jj-1)+anchorIndex(ii));
            iFrequency = iFrequency+1;
        end;
    end;
    if iFrequency>1
        [dmy1,indsrt] = sort(frequencyAnchor(ii,1:iFrequency));
        frequencyAnchor(ii,1:iFrequency) = frequencyAnchor(ii,indsrt);
        mObject.anchorTimeLocation(ii) = anchorLocation/iFrequency;
    end;
end;
mObject.anchorFrequency = frequencyAnchor;


function [labels,classes] = ml_string2label(strings)
%ML_STRING2LABEL Converts a cell array of strings to a num array of labels.
%
%   input -----------------------------------------------------------------
%
%       o strings : cell(N x 1), cell array of string labels
%
%   output ----------------------------------------------------------------
%
%       o labels :  (N x 1), numerical array of class labels
%
%       o classes: cell(num_classes x 1), array of unique class names
%

classes = unique(strings);
labels  = zeros(size(strings,1),1);

for i=1:size(classes,1)

  idx    = ismember(strings,classes{i});
  labels(idx) = ones(sum(idx(:)),1) .* i;

end

end


function plotclustfir(infir,oXc)

colors = {'r' 'g' 'b' 'y' 'c' 'm' 'k'};
if max(oXc)>length(colors)
    error('not enough colors!');
end

for c=1:size(infir,1);
    for s=1:size(infir,2);
        fir(c,:,:,s)=infir{c,s};
    end
end

mfir=squeeze(mean(fir,4));
figure;
for c=1:max(oXc);
leg{c}=['clust',num2str(c)];
end

for n=1:size(fir,1);        % for each condition
    subplot(1,size(mfir,1),n);
    for c=1:max(oXc);
    hold on;
    plotfir=squeeze(mean(mfir(n,:,oXc==c),3));
    plotfir=squeeze(mfir(n,:,oXc==c));
    plot(plotfir,'color',colors{c},'LineWidth',3)
    end
    legend(leg)
end