function [vITRS,rotMat]=TIRS2ITRS(vTIRS,TT1,TT2,xpyp)
%%TIRS2ITRS Rotate vectors from the Terrestrial Intermediate Reference
%            System (TIRS) to the International Terrestrial Reference
%            System (ITRS). The ITRS is essentially the WGS-84 coordinate
%            system: it defines locations with respect to the crust of a
%            non-rotating Earth, where the z axis passes through a fixed
%            point on the surface. On the other hand, the TIRS is nearly
%            the same except the z axis is the axis of rotation of the
%            Earth, which slowly varies over time. Note that the velocity
%            conversion does not include the (small) centrifugal effect of
%            polar motion.
%
%INPUTS: x The NXnumVec collection of vectors in TIRS coordinates to
%          convert (units do not matter). N can be 3, or 6. If the vectors
%          are 3D, then they are position. 6D
%          vectors are assumed to be position and velocity. Since the TIRS
%          and ITRS co-rotate, there is no Coriolis effect to add. Also,
%          the accelerations due to the wobble of the rotation axis over
%          time are not considered. These accelerations are very small.
%          Thus, the function just rotates both halves of the vector.
% TT1, TT2 Two parts of a Julian date given in terrestrial time (TT).
%          The units of the date are days. The full date is the sum of
%          both terms. The date is broken into two parts to provide
%          more bits of precision. It does not matter how the date is
%          split.
%     xpyp xpyp=[xp;yp] are the polar motion coordinates in radians
%          including the effects of tides and librations. If this
%          parameter is omitted or if an empty matrix is passed, the
%          value from the function getEOP will be used.
%
%OUTPUTS: vITRS The NXnumVec vector of values of x rotated from the TIRS
%               into the ITRS.
%        rotMat The 3X3 rotation matrix used to rotate vectors from the
%               TIRS into the ITRS.
%
%The conversion functions from the International Astronomical Union's
%(IAU) Standard's of Fundamental Astronomy library are put together to get
%the necessary rotation matrix.
%
%The algorithm can be compiled for use in Matlab  using the
%CompileCLibraries function.
%
%The algorithm is run in Matlab using the command format
%[vITRS,rotMat]=TIRS2ITRS(vTIRS,TT1,TT2)
%or if more parameters are known, using the format
%[vITRS,rotMat]=TIRS2ITRS(vTIRS,TT2,TT2,xpyp);
%
%Different celestial coordinate systems are compared in [1].
%
%REFERENCES:
%[1] D. F. Crouse, "An Overview of Major Terrestrial, Celestial, and
%    Temporal Coordinate Systems for Target Tracking," Formal Report,
%    Naval Research Laboratory, no. NRL/FR/5344--16-10,279, 10 Aug. 2016,
%    173 pages.
%
%March 2015 David F. Crouse, Naval Research Laboratory, Washington D.C.
%(UNCLASSIFIED) DISTRIBUTION STATEMENT A. Approved for public release.

error('This function is only implemented as a mexed C or C++ function. Please run CompileCLibraries.m to compile the function for use.')

end

%LICENSE:
%
%The source code is in the public domain and not licensed or under
%copyright. The information and software may be used freely by the public.
%As required by 17 U.S.C. 403, third parties producing copyrighted works
%consisting predominantly of the material produced by U.S. government
%agencies must provide notice with such work(s) identifying the U.S.
%Government material incorporated and stating that such material is not
%subject to copyright protection.
%
%Derived works shall not identify themselves in a manner that implies an
%endorsement by or an affiliation with the Naval Research Laboratory.
%
%RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE
%SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY THE NAVAL
%RESEARCH LABORATORY FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS
%OF RECIPIENT IN THE USE OF THE SOFTWARE.


function drawplat3d(nodez,lc,lm)
import rvctools.*
hold on
nodenum = size(nodez,1);
for j=1:nodenum
    if size(nodez,2)==12
        xc = [nodez(j,1:2),nodez(j,12),0,0,nodez(j,3)];
        xr = [nodez(j,1:2),0,0,0,nodez(j,3)]; a = nodez(j,4:7); th = nodez(j,8:11);
    else
        xc = [nodez(j,1:2),nodez(j,4),0,0,0];
        xr = [nodez(j,1:2),0,0,0,0]; a = nodez(j,3)*ones(1,4); th = zeros(1,4);
    end
    cub = pkgMechanics.RigidCuboid(1,xc,lc);
    patch('Vertices',cub.verticesStates.position','Faces',cub.faces,'FaceColor','b','FaceAlpha',0.5);

    xm = xr2m(xr,a,th,lc,lm);
    % build mobile platform cuboid
    for i=1:4
        plat(i) = pkgMechanics.RigidCuboid(1,xm(i,:),lm);
        patch('Vertices',plat(i).verticesStates.position','Faces',plat(i).faces,'FaceColor','y','FaceAlpha',0.5);
    end
end
hold off
end


function v = axis(q,varargin)
% rotational axis of the quaternion
%
% Syntax
%   v = axis(q)
%
% Input
%  q - @quaternion
%
% Output
%  v - @vector3d

v = vector3d(q.b,q.c,q.d);
v(q.a<0) = -v(q.a<0);
v(isnull(norm(v))) = xvector;
v = v./norm(v);


function [x] = boundProject(x,LB,UB)
% function [x] = boundProject(x,LB,UB)
%   Computes projection of x onto constraints LB <= x <= UB

x(x < LB) = LB(x < LB);
if nargin > 2
x(x > UB) = UB(x > UB);
end


function c = sum(a,dim)
%SUM          Implements  sum(a,dim)  for slopes
%
%   u = sum(a,dim)
%
%parameter dim optional, functionality as Matlab function sum
%

% written  12/06/98     S.M. Rump
% modified 09/28/01     S.M. Rump  matrices and multi-dimensional arrays
% modified 04/04/04     S.M. Rump  set round to nearest for safety
% modified 04/06/05     S.M. Rump  rounding unchanged
% modified 09/28/08     S.M. Rump  check for rounding to nearest improved
%

  e = 1e-30;
  if 1+e==1-e                           % fast check for rounding to nearest
    rndold = 0;
  else
    rndold = getround;
    setround(0)
  end

  if nargin==1
    if a.size(1)==1
      dim = 2;
    else
      dim = 1;
    end
  end

  if dim==1
    c = ones(1,a.size(1))*a;
  else
    c = a*ones(a.size(2),1);
  end

  setround(rndold)


function N = count_network_parameters(net)
% -------------------------------------------------------------------------
%   Description:
%       Count the total number of network parameters
%
%   Input:
%       - net   : network
%
%   Output:
%       - N     : #parameters
%
%   Citation:
%       Fast and Accurate Image Super-Resolution with Deep Laplacian Pyramid Networks
%       Wei-Sheng Lai, Jia-Bin Huang, Narendra Ahuja, and Ming-Hsuan Yang
%       arXiv, 2017
%
%   Contact:
%       Wei-Sheng Lai
%       wlai24@ucmerced.edu
%       University of California, Merced
% -------------------------------------------------------------------------

    N = 0;
    for i = 1:length(net.params)

        N = N + numel(net.params(i).value);

    end

end


%%%%%%%%%%Programmed by: Chi-Hang Kwan%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%Completion Date: December 13, 2012%%%%%%%%%%%%%%%%%%%

function posc_new = AI(window,pos,vel,posc,tstep)
tb = get(window,'UserData');

posf = pos + vel*tstep; %the position of the puck at the next frame
maxspeed = 1; %maximum moving speed of the computer's mallet

if posf(2) < 0
    pos_desire = [posf(1) tb.fieldh/4];
else
    if (posc(2)-posf(2)) > tb.r_mallet && abs(posf(1)-posc(1)) < tb.r_mallet %sweet spot to strike
        pos_desire = posf;
        if (posc(2)-posf(2))<(tb.r_mallet + tb.r_puck + 0.06)
            maxspeed = 2; %accelerate to hit puck when it is within 6cm of impact
        end
    else
        pos_desire(2) = posf(2) + tb.r_mallet+tb.r_puck + 0.03;
        if (posf(2)-posc(2))>=(tb.r_mallet-tb.r_puck)
            pos_desire(1) = posf(1) + sign(posc(1)-posf(1))*(tb.r_mallet+tb.r_puck+0.01);
        else
            pos_desire(1) = posf(1);
        end
    end
end

%%%%%%%%%%To ensure the mallet stays within its own half%%%%%%%%%%%%%
if abs(pos_desire(1))>tb.fieldw/2-tb.r_mallet
    pos_desire(1)= sign(pos_desire(1))*(tb.fieldw/2-tb.r_mallet);
end
if pos_desire(2) > tb.fieldh/2-tb.r_mallet
    pos_desire(2)= tb.fieldh/2-tb.r_mallet;
elseif pos_desire(2) < tb.r_mallet
    pos_desire(2) = tb.r_mallet;
end

%%%%%%%%%%To limit the speed of travel of the mallet%%%%%%%%%%%%%
delta = pos_desire - posc;
deltam = sqrt(delta(1)^2 + delta(2)^2);
if deltam == 0
    posc_new = posc;
else
    posc_new = posc + min(deltam,tstep*maxspeed)/deltam*delta;
end


function filter = spm_cfg_eeg_filter
% configuration file for EEG Filtering
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Stefan Kiebel
% $Id: spm_cfg_eeg_filter.m 5377 2013-04-02 17:07:57Z vladimir $

rev = '$Rev: 5377 $';

D = cfg_files;
D.tag = 'D';
D.name = 'File Name';
D.filter = 'mat';
D.num = [1 1];
D.help = {'Select the EEG mat file.'};

type = cfg_menu;
type.tag = 'type';
type.name = 'Type';
type.labels = {'Butterworth', 'FIR'};
type.values = {'butterworth', 'fir'};
type.val = {'butterworth'};
type.help = {'Select the filter typee.'};

band = cfg_menu;
band.tag = 'band';
band.name = 'Band';
band.labels = {'Lowpass', 'Highpass', 'Bandpass', 'Stopband'};
band.values = {'low' 'high' 'bandpass' 'stop'};
band.val = {'low'};
band.help = {'Select the filter band.'};

freq = cfg_entry;
freq.tag = 'freq';
freq.name = 'Cutoff(s)';
freq.strtype = 'r';
freq.num = [1 inf];
freq.help = {'Enter the filter cutoff'};

dir = cfg_menu;
dir.tag = 'dir';
dir.name = 'Direction';
dir.labels = {'Zero phase', 'Forward', 'Backward'};
dir.values = {'twopass', 'onepass', 'onepass-reverse'};
dir.val = {'twopass'};
dir.help = {'Select the filter direction.'};

order = cfg_entry;
order.tag = 'order';
order.name = 'Order';
order.val = {5};
order.strtype = 'n';
order.num = [1 1];
order.help = {'Enter the filter order'};

prefix         = cfg_entry;
prefix.tag     = 'prefix';
prefix.name    = 'Filename Prefix';
prefix.help    = {'Specify the string to be prepended to the filenames of the filtered dataset. Default prefix is ''f''.'};
prefix.strtype = 's';
prefix.num     = [1 Inf];
prefix.val     = {'f'};

filter = cfg_exbranch;
filter.tag = 'filter';
filter.name = 'Filter';
filter.val = {D type band freq dir order, prefix};
filter.help = {'Filters EEG/MEG data.'};
filter.prog = @eeg_filter;
filter.vout = @vout_eeg_filter;
filter.modality = {'EEG'};

function out = eeg_filter(job)
% construct the S struct
S = job;
S.D = S.D{1};

out.D = spm_eeg_filter(S);
out.Dfname = {fullfile(out.D.path, out.D.fname)};

function dep = vout_eeg_filter(job)
% Output is always in field "D", no matter how job is structured
dep = cfg_dep;
dep.sname = 'Filtered Data';
% reference field "D" from output
dep.src_output = substruct('.','D');
% this can be entered into any evaluated input
dep.tgt_spec   = cfg_findspec({{'strtype','e'}});

dep(2) = cfg_dep;
dep(2).sname = 'Filtered Datafile';
% reference field "Dfname" from output
dep(2).src_output = substruct('.','Dfname');
% this can be entered into any file selector
dep(2).tgt_spec   = cfg_findspec({{'filter','mat'}});


%% Import from VPSC
%
%%
% <https://public.lanl.gov/lebenso/ VPSC> is a crystal plasticity code
% originally written by Ricardo Lebensohn and Carlos Tome from Los Alamos
% National Laboratory - USA.
%
% Original code can be requested to lebenso@lanl.gov
%
% https://public.lanl.gov/lebenso/
%
%% Import the orientations generated by VPSC
%
% Running a simulation in VPSC ussually results in an output file
% |TEX_PH1.OUT| which contains multiple sets of orientations for different
% strain levels. As these files does not contain any information on the
% crystal symmetry we need to specify it first

cs = crystalSymmetry('222', [4.762 10.225 5.994],'mineral', 'olivine');

%%
% In the next step the orientations are imported and converted into a list
% of <SO3Fun.SO3Fun.html ODFs> using the command <ODF.load.html |ODF.load|>.

% put in here the path to the VPSC output files
path2file = [mtexDataPath filesep 'VPSC'];

odf = ODF.load([path2file filesep 'TEX_PH1.OUT'],'halfwidth',10*degree,'CS',cs)

%%
% The individuel ODFs can be accessed by |odf{id}|

% lets plot the second ODF
plotSection(odf{2},'sigma','figSize','normal')

%%
% The information about the strain are stored as additional properties
% within each ODF variable

odf{1}.opt

%% Compare pole figures during deformation
%
% Next we examine the evaluation of the ODF during the deformation by
% plotting strain depended pole figures.

% define some crystal directions
h = Miller({1,0,0},{0,1,0},{0,0,1},cs,'uvw');

% generate some figure
fig = newMtexFigure('layout',[4,3],'figSize','huge');
subSet = 1:4;

% plot pole figures for different strain steps
for n = subSet
  nextAxis
  plotPDF(odf{n},h,'lower','contourf','doNotDraw');
  ylabel(fig.children(end-2),['\epsilon = ',xnum2str(odf{n}.opt.strain)]);
end
setColorRange('equal')
mtexColorbar

%% Visualize slip system activity
%
% Alongside with the orientation data VPSC also outputs a file
% |ACT_PH1.OUT| which contains the activity of the different slip systems
% during the deformation. Lets read this file as a table

ACT = readtable([path2file filesep 'ACT_PH1.OUT'],'FileType','text')

%%
% and plot the slip activity with respect to the strain for the different
% modes

% loop though the columns MODE1 ... MOD11
close all
for n = 3: size(ACT,2)

  % perform the plotting
  plot(ACT.STRAIN, table2array(ACT(:,n)),'linewidth',2,...
    'DisplayName',['Slip mode ',num2str(n-2)])
  hold on;
end
hold off

% some styling
xlabel('Strain');
ylabel('Slip activity');
legend('show','location','NorthEastOutside');

set(gca,'Ylim',[-0.005 1])
set(gcf,'MenuBar','none','units','normalized','position',[0.25 0.25 0.5 0.5]);

%for only one mode plot, e.g.,mode 3: cs = csapi(STRAIN,MODE{3});fnplt(cs,3,'color','b');hold off;


function [calculation_times]=PIVlab_commandline_parallel_speed(directory,cpu_core_number)

nr_of_cores =cpu_core_number; % integer, 1 means single core, greater than 1 means parallel
if nr_of_cores > 1
	try
		local_cluster=parcluster('local'); % single node
		corenum =  local_cluster.NumWorkers ; % fix : get the number of cores available
	catch
		warning('on');
		warning('parallel local cluster can not be created, assigning number of cores to 1');
		nr_of_cores = 1;
	end
end

if nr_of_cores > 1
	if pivparpool('size')~=nr_of_cores
		pivparpool('close');
		pivparpool('open',nr_of_cores);
	end
end

%% Create list of images inside user specified directory

% default directory: PIVlab/Examples
addpath(fileparts(mfilename('fullpath')));
%disp(fileparts(mfilename('fullpath')))

suffix='*.jpg'; %*.bmp or *.tif or *.jpg or *.tiff or *.jpeg
%disp(['Looking for ' suffix ' files in the selected directory.']);
direc = dir([directory,filesep,suffix]); filenames={};
[filenames{1:length(direc),1}] = deal(direc.name);
filenames = sortrows(filenames); %sort all image files
amount = length(filenames);

%% Standard PIV Settings
s = cell(15,2); % To make it more readable, let's create a "settings table"
%Parameter                          %Setting           %Options
s{1,1}= 'Int. area 1';              s{1,2}=128;         % window size of first pass
s{2,1}= 'Step size 1';              s{2,2}=64;         % step of first pass
s{3,1}= 'Subpix. finder';           s{3,2}=1;          % 1 = 3point Gauss, 2 = 2D Gauss
s{4,1}= 'Mask';                     s{4,2}=[];         % If needed, generate via: imagesc(image); [temp,Mask{1,1},Mask{1,2}]=roipoly;
s{5,1}= 'ROI';                      s{5,2}=[];         % Region of interest: [x,y,width,height] in pixels, may be left empty
s{6,1}= 'Nr. of passes';            s{6,2}=2;          % 1-4 nr. of passes
s{7,1}= 'Int. area 2';              s{7,2}=64;         % second pass window size
s{8,1}= 'Int. area 3';              s{8,2}=16;         % third pass window size
s{9,1}= 'Int. area 4';              s{9,2}=16;         % fourth pass window size
s{10,1}='Window deformation';       s{10,2}='*linear'; % '*spline' is more accurate, but slower
s{11,1}='Repeated Correlation';     s{11,2}=0;         % 0 or 1 : Repeat the correlation four times and multiply the correlation matrices.
s{12,1}='Disable Autocorrelation';  s{12,2}=0;         % 0 or 1 : Disable Autocorrelation in the first pass.
s{13,1}='Correlation style';        s{13,2}=0;         % 0 or 1 : Use circular correlation (0) or linear correlation (1).
s{14,1}='Repeat last pass';   s{14,2}=0; % 0 or 1 : Repeat the last pass of a multipass analyis
s{15,1}='Last pass quality slope';   s{15,2}=0.025; % Repetitions of last pass will stop when the average difference to the previous pass is less than this number.

%% Standard image preprocessing settings
p = cell(10,1);
%Parameter                       %Setting           %Options
p{1,1}= 'ROI';                   p{1,2}=s{5,2};     % same as in PIV settings
p{2,1}= 'CLAHE';                 p{2,2}=1;          % 1 = enable CLAHE (contrast enhancement), 0 = disable
p{3,1}= 'CLAHE size';            p{3,2}=50;         % CLAHE window size
p{4,1}= 'Highpass';              p{4,2}=0;          % 1 = enable highpass, 0 = disable
p{5,1}= 'Highpass size';         p{5,2}=15;         % highpass size
p{6,1}= 'Clipping';              p{6,2}=0;          % 1 = enable clipping, 0 = disable
p{7,1}= 'Wiener';                p{7,2}=0;          % 1 = enable Wiener2 adaptive denoise filter, 0 = disable
p{8,1}= 'Wiener size';           p{8,2}=3;          % Wiener2 window size
p{9,1}= 'Minimum intensity';     p{9,2}=0.0;        % Minimum intensity of input image (0 = no change)
p{10,1}='Maximum intensity';     p{10,2}=1.0;       % Maximum intensity on input image (1 = no change)

%% other settings
pairwise = 1; % 0 for [A+B], [B+C], [C+D]... sequencing style, and 1 for [A+B], [C+D], [E+F]... sequencing style

%% PIV analysis loop
if pairwise == 1
	if mod(amount,2) == 1 %Uneven number of images?
		disp('Image folder should contain an even number of images.')
		%remove last image from list
		amount=amount-1;
		filenames(size(filenames,1))=[];
	end

	%disp(['Found ' num2str(amount) ' images (' num2str(amount/2) ' image pairs).'])
	x=cell(amount/2,1);
	y=x;
	u=x;
	v=x;
else
	%disp(['Found ' num2str(amount) ' images'])
	x=cell(amount-1,1);
	y=x;
	u=x;
	v=x;
end

typevector=x; %typevector will be 1 for regular vectors, 0 for masked areas
correlation_map=x; % correlation coefficient

%% Pre-load the image names out side of the parallelizable loop
slicedfilename1=cell(0);
slicedfilename2=cell(0);
j = 1;
for i=1:1+pairwise:amount-1
	slicedfilename1{j}=filenames{i}; % begin
	slicedfilename2{j}=filenames{i+1}; % end
	j = j+1;
end

dummy=imread(fullfile(directory,filenames{1}));
disp(['    Current image size:    ' num2str(size(dummy,1)) ' px'])

tstart=tic;
%% Main PIV analysis loop:
% parallel
disp('Please wait....')
if nr_of_cores > 1

	parfor i=1:size(slicedfilename1,2)  % index must increment by 1

		[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...
			piv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,false);
	end
else % sequential loop

	for i=1:size(slicedfilename1,2)  % index must increment by 1

		[x{i}, y{i}, u{i}, v{i}, typevector{i},correlation_map{i}] = ...
			piv_analysis(directory, slicedfilename1{i}, slicedfilename2{i},p,s,nr_of_cores,false);

		%disp([int2str((i+1)/amount*100) ' %']);

	end
end

%% PIV postprocessing loop
% Standard image post processing settings

r = cell(6,1);
%Parameter     %Setting                                     %Options
r{1,1}= 'Calibration factor, 1 for uncalibrated data';      r{1,2}=1;                   % Calibration factor for u
r{2,1}= 'Calibration factor, 1 for uncalibrated data';      r{2,2}=1;                   % Calibration factor for v
r{3,1}= 'Valid velocities [u_min; u_max; v_min; v_max]';    r{3,2}=[-50; 50; -50; 50];  % Maximum allowed velocities, for uncalibrated data: maximum displacement in pixels
r{4,1}= 'Stdev check?';                                     r{4,2}=1;                   % 1 = enable global standard deviation test
r{5,1}= 'Stdev threshold';                                  r{5,2}=7;                   % Threshold for the stdev test
r{6,1}= 'Local median check?';                              r{6,2}=1;                   % 1 = enable local median test
r{7,1}= 'Local median threshold';                           r{7,2}=3;                   % Threshold for the local median test

u_filt=cell(size(u));
v_filt=cell(size(v));
typevector_filt=typevector;

if nr_of_cores >1 % parallel

	if pivparpool('size')~=nr_of_cores
		pivparpool('open',nr_of_cores);
	end

	parfor PIVresult=1:size(x,1)

		[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...
			post_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);

	end

else % sequential loop

	for PIVresult=1:size(x,1)

		[u_filt{PIVresult,1}, v_filt{PIVresult,1},typevector_filt{PIVresult,1}]= ...
			post_proc_wrapper(u{PIVresult,1},v{PIVresult,1},typevector{PIVresult,1},r,true);

	end

end
calculation_times=toc(tstart);
%% clean up parallel pool, and cluster
%{
if nr_of_cores >1 % parallel
	poolobj = gcp('nocreate'); % GET the current parallel pool
	if ~isempty(poolobj ); delete(poolobj );end
	clear local_cluster;
end
%}
%%
%save(fullfile(directory, [filenames{1} '_' filenames{end} '_' num2str(amount) '_frames_result_.mat']));

%%
%clearvars -except p s r x y u v typevector directory filenames u_filt v_filt typevector_filt correlation_map
disp('DONE.')

end
function [u_filt, v_filt,typevector_filt] = post_proc_wrapper(u,v,typevector,post_proc_setting,paint_nan)
% wrapper function for PIVlab_postproc

% INPUT
% u, v: u and v components of vector fields
% typevector: type vector
% post_proc_setting: post processing setting
% paint_nan: bool, whether to interpolate missing data

% OUTPUT
% u_filt, v_filt: post-processed u and v components of vector fields
% typevector_filt: post-processed type vector

[u_filt,v_filt] = PIVlab_postproc(u,v, ...
	post_proc_setting{1,2},...
	post_proc_setting{2,2},...
	post_proc_setting{3,2},...
	post_proc_setting{4,2},...
	post_proc_setting{5,2},...
	post_proc_setting{6,2},...
	post_proc_setting{7,2});

typevector_filt = typevector; % initiate
typevector_filt(isnan(u_filt))=2;
typevector_filt(isnan(v_filt))=2;
typevector_filt(typevector==0)=0; %restores typevector for mask

if paint_nan
	u_filt=inpaint_nans(u_filt,4);
	v_filt=inpaint_nans(v_filt,4);
end

end


% Author: Ricardo Baptista and Matthias Poloczek
% Date:   June 2018
%
% See LICENSE.md for copyright information
%

function models = sample_models(n_models, n_vars, values)
% SAMPLE_MODELS: Sample candidate model vectors with categorical values
%
% Inputs: n_models - number of vectors to return
%         n_vars - number of variables for each vector
%         values - {n_vars x 1} cell - numeric variables for each dimension

% check values and default to binary if not specified
if nargin < 3
	values = repmat({[0,1]},n_vars,1);
end

% check if n_vars and values have the same dimension
if length(values) ~= n_vars
    error('Number of variables does not match size of values cell')
end

% Generate matrix of zeros to store models
models = zeros(n_models, n_vars);

% Construct model vectors by sampling each dimension independently
% and with replacement
for j=1:n_vars
	models(:,j) = randsample(values{j}, n_models, true);
end

% -- END OF FILE --


%{
Authors:
Jonatas Lopes de Paiva
Claudio Fabiano Motta Toledo
Helio Pedrini

%}

function pop = createPop(sizePop, img, denoisedImages, beta, lambda  )

population(sizePop).fitness = 0;
population(sizePop).cromo = [];
population(sizePop).id = '';

mut1 = denoisedImages(1).img;
mut2 = denoisedImages(2).img;
mut3 = denoisedImages(3).img;

fit1 = calcFitness(mut1, img, beta, lambda);
fit2 = calcFitness(mut2, img, beta, lambda);
fit3 = calcFitness(mut3, img, beta, lambda);

population(1).fitness = fit1;
population(1).cromo = mut1;
population(1).id = char(java.util.UUID.randomUUID.toString);

population(2).fitness = fit2;
population(2).cromo = mut2;
population(2).id = char(java.util.UUID.randomUUID.toString);

population(3).fitness = fit3;
population(3).cromo = mut3;
population(3).id = char(java.util.UUID.randomUUID.toString);

for i = 4:sizePop
    tmp = denoisedImages(randi(3)).img;
    population(i).cromo = mutation(tmp);
    population(i).fitness = calcFitness(population(i).cromo, img, beta, lambda);
    population(i).id = char(java.util.UUID.randomUUID.toString);
end

pop = arrangePop(population);

end


function out = ctranspose2x2(in)

% compute ctranspose of multiple 2x2 matrices, input is 2x2xN

out = conj(in);
out(1,2,:,:) = conj(in(2,1,:,:));
out(2,1,:,:) = conj(in(1,2,:,:));


% PRTBRV - PRT Bayesian Random Variable Class
%   Abstract Methods:
%       nDimensions

classdef prtBrv < prtAction
    methods (Abstract)
        self = estimateParameters(self, priorSelf, x)
        y = predictivePdf(self, x)
        y = predictiveLogPdf(self, x)

        d = getNumDimensions(self)

        self = initialize(self, x)
    end

    methods
        % Optional methods that would be nice to have
        % You don't have to implement these but you are welcome to some
        % types of processing for example VB with
        % calculateNegativeFreeEnergy = true, might require some of these
        function kld = conjugateKld(self, prior) %#ok<INUSD,STOUT>
            missingMethodError(self,'conjugateKld')
        end
        function x = posteriorMeanDraw(self, n, varargin) %#ok<INUSD,STOUT>
            missingMethodError(self,'posteriorMeanDraw')
        end
        function s = posteriorMeanStruct(self) %#ok<STOUT>
            missingMethodError(self,'posteriorMeanStruct')
        end
        function plotCollection(selfVec,colors) %#ok<INUSD>
           missingMethodError(selfVec(1),'plotCollection')
        end
        function val = plotLimits(self) %#ok<STOUT>
           missingMethodError(self,'plotLimits')
        end
        %function plot(self)
        %    plotCollection(self);
        %end
    end

    % All prtBrv's get the property nDimensions
    % For a particular subclass getNumDimensions must be implemented
    properties (Dependent)
        nDimensions
    end
    methods
        function val = get.nDimensions(self)
            val = zeros(size(self));
            for iRv = 1:numel(self)
                val(iRv) = self(iRv).getNumDimensions();
            end
        end
    end

    % Because we are a prtAction we also must implement something like this

    %%% properties (SetAccess=private)
    %%%     name = 'Maximum a Posteriori'   % Maximum a Posteriori
    %%%     nameAbbreviation = 'MAP'        % MAP
    %%%     isNativeMary = true;            % True
    %%% end

    % For prtAction, we also must implement trainAction() and runAction()
    methods (Access = protected, Hidden = true)
        function self = trainAction(self, ds)
            self = estimateParameters(self, ds);
        end

        function ds = runAction(self, ds)
            ds = ds.setObservations(self.predictiveLogPdf(ds.getObservations));
        end
    end

    methods (Access = 'protected', Hidden = true)
        function missingMethodError(self,methodName) %#ok<MANU>
            error('The method %s is not defined for this prtBrv object',methodName);
        end

        function self = constructorInputParse(self,varargin)

            nIn = length(varargin);

            % Quick Exit for the zero input constructor
            if nIn == 0
                return
            elseif mod(nIn,2)
                error('prt:prtBrv:constructorInputParse','Inputs must be supplied by as string/value pairs');
            end

            self = prtUtilAssignStringValuePairs(self, varargin{:});

        end
    end
end


%GOBJ_POLYGON Create polygon geometry object.
%
%   [ GOBJ ] = GOBJ_POLYGON( P, TAG ) Creates a polygon
%   geometry object. Accepts the following input parameters.
%
%       Parameter   Value/{Default}           Description
%       -----------------------------------------------------------------------------------
%       p           array  {[0 0;1 0;0 1]}    Polygon vertex points
%       tag         string {P1}               Geometry object tag/name

% Copyright 2013-2022 Precise Simulation, Ltd.


%#eml
function [min,med,max] = get_median(inbuf)

numpixels = length(inbuf);

tbuf = inbuf;

for ii=eml.unroll(1:numpixels)
    if bitand(ii,uint32(1)) == 1
        tbuf = compare_stage1(tbuf);
    else
        tbuf = compare_stage2(tbuf);
    end
end

min = tbuf(1);
med = tbuf(ceil(numpixels/2));
max = tbuf(numpixels);

end

function outbuf = compare_stage1(inbuf)
numpixels = length(inbuf);
tbuf = compare_stage(inbuf(1:numpixels-1));
outbuf = [tbuf(:)' inbuf(numpixels)];
end

function outbuf = compare_stage2(inbuf)
numpixels = length(inbuf);
tbuf = compare_stage(inbuf(2:numpixels));
outbuf = [inbuf(1) tbuf(:)'];
end

function [outbuf] = compare_stage(inbuf)

step = 2;
numpixels = length(inbuf);

outbuf = inbuf;

for ii=eml.unroll(1:step:numpixels)
    t = compare_pixels([inbuf(ii), inbuf(ii+1)]);
    outbuf(ii) = t(1);
    outbuf(ii+1) = t(2);
end

end

function outbuf = compare_pixels(inbuf)
if (inbuf(1) > inbuf(2))
    outbuf = [inbuf(1), inbuf(2)];
else
    outbuf = [inbuf(2), inbuf(1)];
end
end


function [params] = sv_calcB(vResults)
% function [vResults] = sv_calcB(vResults)
% -------------------------------------
% Calculation of b-value uncertainty from given mValueGrid_ determined with
% sv_calcMc
%
%
% Input parameters:
% vResults
%
% Output parameters:
%
%
% J. Woessner; woessner@seismo.ifg.ethz.ch
% last update: 14.04.03

% Initialize

% Create Indices to catalog
[vResults.caNodeIndices] = ex_CreateIndexCatalog(vResults.mCatalog, vResults.mPolygon, vResults.bMap, vResults.nGriddingMode,...
    vResults.nNumberEvents, vResults.fRadius, vResults.fSizeRectHorizontal, vResults.fSizeRectDepth);

% Determine time period of catalog
vResults.fTminCat = min(vResults.mCatalog(:,3));
vResults.fTmaxCat = max(vResults.mCatalog(:,3));
% Adjust to decimal years
fTimePeriod =vResults.fTimePeriod/365;

% Init result matrix
mValueGrid_ = [];

% Loop over all grid nodes
for nNode_ = 1:length(vResults.mPolygon(:,1))
    nNode_
    % Create node catalog
    mNodeCatalog_ = vResults.mCatalog(vResults.caNodeIndices{nNode_}, :);
    % Select time period for mNodeCatalog_
    vSel = (vResults.fTstart <= mNodeCatalog_(:,3) & mNodeCatalog_(:,3) < vResults.fTstart+fTimePeriod);
    mNodeCatalog_ = mNodeCatalog_(vSel,:);
    % Check for constant number of events calculations
    if (vResults.nGriddingMode == 0)
        [mNodeCatalog_] = ex_MaxRadius(vResults.mCatalog, vResults.mPolygon, nNode_, vResults.caNodeIndices, vResults.fMaxRadius, vResults.nNumberEvents, vResults.bMap);
    end
    [nX,nY] = size(mNodeCatalog_);
    if (nX < vResults.nMinimumNumber)
        mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
    else
        try
            % b-value for median Mc(EMR)
            vSel1=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,6));
            mCat1=mNodeCatalog_(vSel1,:);
            [fMeanMag1, fBValue1, fStdDev1, fAValue1] =  calc_bmemag(mCat1, vResults.fBinning);
            % b-value for 16 percentile Mc
            vSel2=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,16));
            mCat2=mNodeCatalog_(vSel2,:);
            [fMeanMag2, fBValue2, fStdDev2, fAValue2] =  calc_bmemag(mCat2, vResults.fBinning);
            % b-value for 84 percentile Mc
            vSel3=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,17));
            mCat3=mNodeCatalog_(vSel3,:);
            [fMeanMag3, fBValue3, fStdDev3, fAValue3] =  calc_bmemag(mCat3, vResults.fBinning);
            % b-value check for Mc(EMR)
            vSel4=(mNodeCatalog_(:,6) >= vResults.mValueGrid(nNode_,5));
            mCat4=mNodeCatalog_(vSel4,:);
            [fMeanMag4, fBValue4, fStdDev4, fAValue4] =  calc_bmemag(mCat4, vResults.fBinning);
            mValueGrid_= [mValueGrid_; fBValue1 fStdDev1 fAValue1 fBValue2 fStdDev2 fAValue2...
                    fBValue3 fStdDev3 fAValue3 fMeanMag4 fBValue4 fStdDev4 fAValue4];
        catch
            mValueGrid_= [mValueGrid_; NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN];
        end
    end; % End of if on length(mNodeCatalog_(:,1)
end; % for nNode
save(['Bval_result_Time' num2str(vResults.fTstart) '_Nmin_' num2str(vResults.nMinimumNumber) '.mat'], 'mValueGrid_');


function [xpad, nup, n1, n2] = padsignal(x, padtype)

[nup, n1, n2] = p2up(length(x));

xl = padarray(x(:), n1, padtype, 'pre');
xr = padarray(x(:), n2, padtype, 'post');

xpad = [xl(1:n1); x(:); xr(end-n2+1:end)];


function x = testMaps()
%tests the functionality of the functions in testMaps especially drawLine,
%   drawConc, drawFlux
%
%   testMaps
%
%
%

oriFolder = pwd;

mFilePath = mfilename('fullpath');
cd(mFilePath(1:end-length(mfilename)));

mapCoordinateFilename='ecoli_core_map.txt';

map = readCbMap(mapCoordinateFilename);
load('ecoli_core_model.mat');
sol = optimizeCbModel(model);
global CB_MAP_OUTPUT
if ~strcmp(CB_MAP_OUTPUT,'svg')
    f = figure;
end
drawCbMap(map);

%tests drawConc with zero concentrations of metabolites
disp('Testing drawConc with zero concentrations');
conc = zeros(size(model.metNames,1), 1);
drawConc(map, model, conc);
disp(' ');
disp(' ');

disp('Testing drawConc with non-zero concentrations');
conc = rand(size(model.metNames,1),1);
drawConc(map, model, conc);
disp(' ');
disp(' ');

%tests drawFlux with zero fluxes
disp('Testing drawFlux with zero flux');
flux = zeros(size(model.rxns,1), 1);
drawFlux(map, model, flux);
disp(' ');
disp(' ');

%tests drawFlux with non-zero fluxes w/ reaction with zero flux set to
%width of 1
disp('Testing drawFlux with non-zero flux');
flux = sol.x;
drawFlux(map, model, flux, [],'zeroFluxWidth',1);
disp(' ');
disp(' ');

%tests drawFluxVariablity with enlarged arrowheads to denote flux
%directionality
load('testMapsData.mat','minFlux','maxFlux');
display('Testing drawFluxVariability')
drawFluxVariability(map,model,minFlux,maxFlux,[],'rxnDirMultiplier',2.5);
display(' ');
display(' ');

x=1;
if ~strcmp(CB_MAP_OUTPUT,'svg')
    close(f);
end
cd(oriFolder);

end


function data=syms2v(symbols,numberOfZeros)
%% syms2v : Symbols (nRows,N) to Vector of size (1,L)
% data=syms2v(symbols,numberOfZeros)
%% INPUTS: symbols, and numberOfZeros; as follows
% where L = number of the elements in the vector [data]
%% Outputs:
% data: is the original vector without the originally attached zeros
[r c]=size(symbols);
d=reshape(symbols,1,r*c);
data=d(1:end-numberOfZeros);


% select_region.m

% Copyright 2003-2010 The MathWorks, Inc.

f = squeeze(uint8(mean(f,3)));  %RGB color to grayscale conversion
avg = mean(f,3);                %composite leaves traces of moving objects
bg = median(double(f),3);       %ensemble median average minimizes motion

%difference image highlights circular path of motion
arcPath = imabsdiff(avg,bg);
figure, imshow(arcPath,[])
title('Click-drag-release to select region of interest')

% %user select region
% h=msgbox('Select region of interest.','ROI');
% set(h,'WindowStyle','Modal')
% waitfor(h)

done=false;
while ~done
  [subIm,roi]=imcrop;
  %wait for user to select region of interest (click-drag rubberband box)

  %determine corners of selected region
  x1=roi(1);  x2=roi(1)+roi(3);  xx=[x1 x1 x2 x2 x1];
  y1=roi(2);  y2=roi(2)+roi(4);  yy=[y1 y2 y2 y1 y1];
  %draw rectangle to indicate selected region
  hLine=line(xx,yy);
  title('Click inside to keep, outside to select again')
  pt=ginput(1);
  %wait for user to keep or discard selected region

  % check: is point inside region?
  if pt(1)>=roi(1) & pt(1)<=roi(1)+roi(3) & pt(2)>=roi(2) & pt(2)<=roi(2)+roi(4)
    done=true;  %exit loop
  else
    delete(hLine)   %remove previous selection
    title('Click-drag-release to select region of interest')
    %loop around to select another region
  end
end

% %display cropped region
% imshow(subIm,'notruesize')
% title('Selected region of interest')

% %convert RGB color frames to grayscale
% f = squeeze(mean(f,3));

%crop all frames; display cropped footage
f2 = zeros([size(subIm,1) size(subIm,2) nFrames]);  %allocate for cropped footage
shg, set(gcf,'doublebuffer','on')
for i=1:nFrames
  f2(:,:,i)=imcrop(f(:,:,i),roi);
  imshow(uint8(f2(:,:,i)))
  title(sprintf('Frame %d, t = %.2f sec',i,t(i)))
  drawnow, pause(0.1)
end
set(gcf,'doublebuffer','off')

f=f2; clear f2


%% FUNCTION init_opts
% initialization options for multi-task learning library
%
% If one of the ncessary opts are empty then it will be set to default
% values as specified in this file.
%
% Table of Options.  * * indicates default value.
% FIELD                DESCRIPTION
%% Optimization options
%
%  .max_iter               Maximum iteration step number
%                           *1000*
%  .tol                    Tolerance
%                           *10e-3*
%  .tFlag                  Termination condition
%                           0 => change of absolute function value:
%                             abs( funcVal(i)- funcVal(i-1) ) <= .tol
%                         * 1 => change of relative function value:
%                             abs( funcVal(i)- funcVal(i-1) )
%                              <= .tol * funcVal(i-1)
%                           2 => absolute function value:
%                             funcVal(end)<= .tol
%                           3 => Run the code for .maxIter iterations
%% Starting Point
%
% .W0               Starting point of W.
%                   Initialized according to .init.
%
% .C0               Starting point for the intercept C (for Logistic Loss)
%                   Initialized according to .init.
%
% .init             .init specifies how to initialize W, C.
%                         0 => .W0, C0 are set by a guess value infered from data
%                         1 => .W0 and .C0 are defined
%                       * 2 => .W0= zeros(.), .C0=0 *
%
%% Parallel Computing
%
% .pFlag            Enable Map-Reduce (needs Parallel Toolbox support).
%                        *false*
%
% .pSeg_num         set the number of total parallel segmentations. if the
%                   number is non-positive, then current matlab pool number
%                   will be used. [supported in the incoming version]
%                        * pool size *
%
%% LICENSE
%   This program is free software: you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation, either version 3 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License
%   along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%   Copyright (C) 2011 - 2012 Jiayu Zhou and Jieping Ye
%
%   You are suggested to first read the Manual.
%   For any problem, please contact with Jiayu Zhou via jiayu.zhou@asu.edu
%
%   Last modified on June 21, 2012.
%

function opts = init_opts (opts)

%% Default values
DEFAULT_MAX_ITERATION = 1000;
DEFAULT_TOLERANCE     = 1e-4;
MINIMUM_TOLERANCE     = eps * 100;
DEFAULT_TERMINATION_COND = 1;
DEFAULT_INIT = 2;
DEFAULT_PARALLEL_SWITCH = false;

%% Starting Point
if isfield(opts,'init')
    if (opts.init~=0) && (opts.init~=1) && (opts.init~=2)
        opts.init=DEFAULT_INIT; % if .init is not 0, 1, or 2, then use the default 0
    end

    if (~isfield(opts,'W0')) && (opts.init==1)
        opts.init=DEFAULT_INIT; % if .W0 is not defined and .init=1, set .init=0
    end
else
    opts.init = DEFAULT_INIT; % if .init is not specified, use "0"
end

%% Tolerance
if isfield(opts, 'tol')
    % detect if the tolerance is smaller than minimum
    % tolerance allowed.
    if (opts.tol <MINIMUM_TOLERANCE)
        opts.tol = MINIMUM_TOLERANCE;
    end
else
    opts.tol = DEFAULT_TOLERANCE;
end

%% Maximum iteration steps
if isfield(opts, 'maxIter')
    if (opts.maxIter<1)
        opts.maxIter = DEFAULT_MAX_ITERATION;
    end
else
    opts.maxIter = DEFAULT_MAX_ITERATION;
end

%% Termination condition
if isfield(opts,'tFlag')
    if opts.tFlag<0
        opts.tFlag=0;
    elseif opts.tFlag>3
        opts.tFlag=3;
    else
        opts.tFlag=floor(opts.tFlag);
    end
else
    opts.tFlag = DEFAULT_TERMINATION_COND;
end

%% Parallel Options
if isfield(opts, 'pFlag')
    if opts.pFlag == true && ~exist('matlabpool', 'file')
        opts.pFlag = false;
        warning('MALSAR:PARALLEL','Parallel Toolbox is not detected, MALSAR is forced to turn off pFlag.');
    elseif opts.pFlag ~= true && opts.pFlag ~= false
        % validate the pFlag.
        opts.pFlag = DEFAULT_PARALLEL_SWITCH;
    end
else
    % if not set the pFlag to default.
    opts.pFlag = DEFAULT_PARALLEL_SWITCH;
end

if opts.pFlag
    % if the pFlag is checked,
    % check segmentation number.
    if isfield(opts, 'pSeg_num')
        if opts.pSeg_num < 0
            opts.pSeg_num = matlabpool('size');
        else
            opts.pSeg_num = ceil(opts.pSeg_num);
        end
    else
        opts.pSeg_num = matlabpool('size');
    end
end


function [ panoout ] = combineViews( Imgs, width, height )
%COMBINEVIEWS Combine separate views to panorama
%   Imgs: same format as separatePano

panoout = zeros(height, width, size(Imgs(1).img,3));
panowei = zeros(height, width, size(Imgs(1).img,3));
imgNum = length(Imgs);
for i = 1:imgNum
    [sphereImg validMap] = ...
        im2Sphere( Imgs(i).img, Imgs(i).fov, width, height, Imgs(i).vx, Imgs(i).vy);
    sphereImg(~validMap) = 0;
    panoout = panoout + sphereImg;
    panowei = panowei + validMap;
end
panoout(panowei==0) = 0;
panowei(panowei==0) = 1;
panoout = panoout./double(panowei);

end


classdef TestPSNR
    %TestPSNR

    methods (Static)
        function test_1
            src1 = randi([0 255], [50 50], 'uint8');
            src2 = randi([0 255], [50 50], 'uint8');
            x = cv.PSNR(src1, src2);
        end

        function test_2
            src1 = randi([0 255], [50 50 3], 'uint8');
            src2 = randi([0 255], [50 50 3], 'uint8');
            x = cv.PSNR(src1, src2);
        end

        function test_error_argnum
            try
                cv.PSNR();
                throw('UnitTest:Fail');
            catch e
                assert(strcmp(e.identifier,'mexopencv:error'));
            end
        end
    end

end


clear all; close all;
I=imread('glass.png');
J=imcomplement(I);
figure;
subplot(121);
imshow(uint8(I));
subplot(122);
imshow(uint8(J));


function varargout = dsxy2figxy(varargin)
%DSXY2FIGXY Transform point or position from axis to figure coords
% Transforms [axx axy] or [xypos] from axes hAx (data) coords into coords
% wrt GCF for placing annotation objects that use figure coords into data
% space. The annotation objects this can be used for are
%    arrow, doublearrow, textarrow
%    ellipses (coordinates must be transformed to [x, y, width, height])
% Note that line, text, and rectangle anno objects already are placed
% on a plot using axes coordinates and must be located within an axes.
% Example to compute a position and apply to an annotation:
% Example:
%   [axx axy] = ginput(2);
%   [figx figy] = getaxannopos(gca, axx, axy);
%   har = annotation('textarrow',figx,figy);
%   set(har,'String',['(' num2str(axx(2)) ',' num2str(axy(2)) ')'])
%
% See also annotation, plot, ginput.

% Copyright 2006-2007, The MathWorks, Inc.  Used by permission (see
% http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/
% bquk5ia-4.html).

%% Obtain arguments (only limited argument checking is performed).
% Determine if axes handle is specified
if length(varargin{1})== 1 && ishandle(varargin{1}) && ...
  strcmp(get(varargin{1},'type'),'axes')
 hAx = varargin{1};
 varargin = varargin(2:end);
else
 hAx = gca;
end;
% Parse either a position vector or two 2-D point tuples
if length(varargin)==1 % Must be a 4-element POS vector
 pos = varargin{1};
else
 [x,y] = deal(varargin{:});  % Two tuples (start & end points)
end
%% Get limits
axun = get(hAx,'Units');
set(hAx,'Units','normalized');  % Need normaized units to do the xform
axpos = get(hAx,'Position');
axlim = axis(hAx);              % Get the axis limits [xlim ylim (zlim)]
axwidth = diff(axlim(1:2));
axheight = diff(axlim(3:4));
%% Transform data from figure space to data space
if exist('x','var')     % Transform a and return pair of points
 varargout{1} = (x-axlim(1))*axpos(3)/axwidth + axpos(1);
 varargout{2} = (y-axlim(3))*axpos(4)/axheight + axpos(2);
else                    % Transform and return a position rectangle
 pos(1) = (pos(1)-axlim(1))/axwidth*axpos(3) + axpos(1);
 pos(2) = (pos(2)-axlim(3))/axheight*axpos(4) + axpos(2);
 pos(3) = pos(3)*axpos(3)/axwidth;
 pos(4) = pos(4)*axpos(4)/axheight;
 varargout{1} = pos;
end
%% Restore axes units
set(hAx,'Units',axun)


function model = modelTieParam(model, paramsList)

% MODELTIEPARAM Tie parameters of a model together.
% FORMAT
% DESC groups of parameters of a model to be seen as one parameter
% during optimisation of the model.
% ARG model : the model for which parameters are being tied
% together.
% ARG paramsList : indices of parameteres to group together. The
% indices are provided in a cell array. Each cell in the array
% contains a vector of indices of parameters that should be
% considered as one parameter. Each group of parameters in each
% cell should obviously be mutually exclusive.
% Alternatively each element of the cell array can be a string which
% is interpreted as a regular expression of names of parameters
% (as returned by modelExtractParam) to be tied.
% RETURN model : the model with the parameters grouped together.
%
% SEEALSO : modelExtractParam, modeExpandParam, modelLogLikeGradients
%
% COPYRIGHT : Neil D. Lawrence, 2003, 2006, 2008
%
% MODIFICATIONS: Antti Honkela, 2009

% MLTOOLS

if ~isfield(model, 'paramGroups')
  if isfield(model, 'nParams')
    model.paramGroups = speye(model.nParams);
  elseif isfield(model, 'numParams')
    model.paramGroups = speye(model.numParams);
  else
    error('Model does not list number of parameters.');
  end
end
colToDelete = [];
try,
  [params, names] = modelExtractParam(model);
catch
  try,
    [params, names] = kernExtractParam(model);
  catch
    names = {};
  end
end

for i = 1:length(paramsList)
  if ischar(paramsList{i}),
    paramIndices=find(~cellfun('isempty', regexp(names, paramsList{i})));
    if isempty(paramIndices),
      warning(['No matches for parameter tie spec: ', paramsList{i}])
    end
  else
    paramIndices=sort(paramsList{i});
  end
  if any(paramIndices(1) == colToDelete)
    error('Parameter is already being tied')
  end

  for j = 2:length(paramIndices)
    model.paramGroups(paramIndices(j), paramIndices(1)) = 1;
    if any(paramIndices(j) == colToDelete)
      error('Parameter has already been tied')
    end
    colToDelete = [colToDelete paramIndices(j)];
  end
end

model.paramGroups(:, colToDelete) = [];
if isfield(model, 'nParams')
  % Update to the new number of parameters.
  model.nParams = size(model.paramGroups, 2);
elseif isfield(model, 'numParams')
  model.numParams = size(model.paramGroups, 2);
end


% DEMCMU35GPLVMVARGPLVM3 Run variational GPLVM with dynamics on CMU35 data.
%
% COPYRIGHT :  Andreas C. Damianou, Michalis K. Titsias, 2011
%
% SEEALSO : demCmu35vargplvmReconstructTaylor.m
% VARGPLVM

% Fix seeds
randn('seed', 1e5);
rand('seed', 1e5);

% Define constants (in a manner that allows other scripts to parametrize
% this one).
if ~exist('experimentNo') ,  experimentNo = 404;      end
if ~exist('itNo')         ,  itNo = [200 1000 1300];              end     % Default: 2000
if ~exist('indPoints')    ,  indPoints = 100;          end     % Default:
if ~exist('latentDim')    ,  latentDim = 9;          end
% Set to 1 to use dynamics or to 0 to use the standard var-GPLVM
if ~exist('dynUsed')      ,  dynUsed = 1;             end

if ~exist('fixedBetaIters'), fixedBetaIters = 50;      end     % DEFAULT:
% Set to 1 to tie the inducing points with the latent vars. X
if ~exist('fixInd')        ,     fixInd = 0;                             end
if ~exist('baseKern')   ,     baseKern = {'rbfard2', 'white'}; end
if ~exist('dynamicKern')   ,     dynamicKern = {'rbf', 'bias', 'white'}; end
if ~exist('reconstrIters') ,     reconstrIters = 2000;                   end
if ~exist('learnVariance'),     learnVariance =0;   end
%if ~exist('vardistCovarsMult'),  vardistCovarsMult=1.3;                  end
if ~exist('initX'),     initX ='ppca';   end
if ~exist('doReconstr'),     doReconstr=1;   end
if ~exist('optimiser', 'var'), optimiser = 'scg'; end
if ~exist('testReoptimise', 'var'), testReoptimise = 0; end
if ~exist('parallelVardist', 'var'), parallelVardist = false; end

% Get the sequence numbers.
[Y, lbls] = lvmLoadData('cmu35WalkJog');
seq = cumsum(sum(lbls)) - [1:31];

dataSetName = 'cmu35gplvm';

% load data
[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);

fprintf(1,'\n#----------------------------------------------------\n');
fprintf(1,'# Dataset: %s\n',dataSetName);
fprintf(1,'# ExperimentNo: %d\n', experimentNo);
fprintf(1,'# Inducing points: %d\n',indPoints);
fprintf(1,'# Latent dimensions: %d\n',latentDim);
fprintf(1,'# Iterations (with/without fixed Beta): %d / %s\n',fixedBetaIters, num2str(itNo));
%fprintf(1,'# VardistCovarsMult: %d\n',vardistCovarsMult);
fprintf(1,'# Reconstruction iterations: %d\n', reconstrIters);
fprintf(1,'# Dataset size used (train) : %d \n', size(Y,1));
fprintf(1,'# Tie Inducing points: %d\n',fixInd);
fprintf(1,'# InitX: %s\n',initX);
fprintf(1,'# Base kern: ');
disp(baseKern);
fprintf(1,'# Dynamics used: %d\n', dynUsed);
if dynUsed
    fprintf(1,'# Dynamics kern: ');
    disp(dynamicKern);
end

fprintf(1,'#----------------------------------------------------\n');

% %%% Uncomment this code to get a subset of the sequences
% seqFrom=2;
% seqEnd=4;
%
% if seqFrom ~= 1
%     Yfrom = seq(seqFrom-1)+1;
% else
%     Yfrom = 1;
% end
% Yend=seq(seqEnd);
% Y=Y(Yfrom:Yend,:);
% seq=seq(seqFrom:seqEnd);
% seq=seq - ones(1,length(seq)).*(Yfrom-1);

% Fix times:
prevSeq = 1;
timeStampsTraining = [];
dt=0.05;
for i=1:length(seq)
    t = ([0:(seq(i)-prevSeq)].*dt)';
    prevSeq = seq(i)+1;
    timeStampsTraining = [timeStampsTraining ;t];
end;
timeStampsTest = ([0:size(Ytest,1)-1].*dt)';

% Set up model
options = vargplvmOptions('dtcvar');
%options.kern = {'rbfard2', 'bias', 'white'};
options.kern = baseKern;
options.numActive = indPoints; % DEfault: 100

options.optimiser = optimiser;

d = size(Y, 2);
fprintf(1,'# Creating the model...\n');
if fixInd
    options.fixInducing=1;
    options.fixIndices=1:indPoints;
end
model = vargplvmCreate(latentDim, d, Y, options);
model = vargplvmParamInit(model, model.m, model.X);
model.beta=1/(0.01*var(model.m(:)));
model.vardist.covars = 0.5*ones(size(model.vardist.covars)) + 0.001*randn(size(model.vardist.covars));

model.reconstrIters = reconstrIters;

%-------- Add dynamics to the model -----
if dynUsed
    optionsDyn.type = 'vargpTime';
    optionsDyn.t=timeStampsTraining;
    optionsDyn.inverseWidth=30;
    %   optionsDyn.vardistCovars = vardistCovarsMult;
    optionsDyn.seq = seq;
    optionsDyn.learnVariance = learnVariance;
    optionsDyn.initX = initX;
    optionsDyn.regularizeMeans = 0;

    % Dynamic kernel:
    kern = kernCreate(t, dynamicKern); % Default: {'rbf','white','bias'}

    if strcmp(kern.comp{2}.type, 'white')
        kern.comp{2}.variance = 1e-2; % Usual values: 1e-1, 1e-3
    end

    if strcmp(kern.comp{2}.type, 'whitefixed')
        if ~exist('whiteVar')
            whiteVar = 1e-6;
        end
        kern.comp{2}.variance = whiteVar;
        fprintf(1,'# fixedwhite variance: %d\n',whiteVar);
    end

    if strcmp(kern.comp{1}.type, 'rbfperiodic')
        if exist('periodicPeriod')
            kern.comp{1}.period = periodicPeriod;
        end
        fprintf(1,'# periodic period: %d\n',kern.comp{1}.period);
    end

    % The following is related to the expected number of
    % zero-crossings.(larger inv.width numerator, rougher func)
    if ~strcmp(kern.comp{1}.type,'ou')
        kern.comp{1}.inverseWidth = optionsDyn.inverseWidth./(((max(t)-min(t))).^2);
        kern.comp{1}.variance = 1;
    end
    optionsDyn.kern = kern;

    if exist('vardistCovarsMult')
        optionsDyn.vardistCovars = vardistCovarsMult;
    end

    % Fill in with default values whatever is not already set
    optionsDyn = vargplvmOptionsDyn(optionsDyn);
    model = vargplvmAddDynamics(model, 'vargpTime', optionsDyn, optionsDyn.t, 0, 0,optionsDyn.seq);

    fprintf(1,'# Further calibration of the initial parameters...\n');
    model = vargplvmInitDynamics(model,optionsDyn);
end

if parallelVardist
    model.vardist.parallel = true;
end

modelInit = model;

% do not learn beta for few iterations for intitilization
if fixedBetaIters > 0
    model.learnBeta = 0; model.initVardist = 1; model.learnSigmaf = 0;
    display = 1;
    fprintf(1,'# Intitiliazing the model (fixed beta) %d iterations...\n',fixedBetaIters);
    model = vargplvmOptimise(model, display, fixedBetaIters);
    model.fixedBetaIters = fixedBetaIters;
    disp('# Saving model after optimising beta...')
    try
        vargplvmWriteResult(model, model.type, dataSetName, experimentNo);
    catch e
        warning('Error while saving model: ')
        fprintf('%s\n',e.message)
    end
end

% Optimise the model.
display = 1;
model.learnBeta = 1; model.initVardist = 0; model.learnSigmaf = 1;
model.iters=0;

for i=1:length(itNo)
    iters = itNo(i); % Default: 1000
    fprintf(1,'# Optimising the model for %d iterations (session %d)...\n',iters,i);
    model = vargplvmOptimise(model, display, iters);
    fprintf('1/b=%.4d var(model.m)=%.4d\n', 1/model.beta, var(model.m(:)));
    model.iters = model.iters + iters;
    model.date = date;
    % Save the results.
    fprintf(1,'# Saving model after doing %d iterations',iters)
    try
        vargplvmWriteResult(model, model.type, dataSetName, experimentNo);
    catch e
        warning('Error while saving model: ')
        fprintf('%s\n',e.message)
    end
end

%bar(model.kern.comp{1}.inputScales)
%prefix = 'scales';
%saveAllOpenFigures(['Results/CMU/NEW/' num2str(experimentNo) '/'], prefix,1)

if testReoptimise
    model.dynamics.reoptimise=1;
end

% Reconstruction can also be done separately calling demCmu35vargplvmReconstructTaylor
if doReconstr
    %---- RECONSTRUCTION ---%
    save 'TEMPExperimentNo.mat' 'experimentNo'
    clear
    load 'TEMPExperimentNo'
    delete TEMPExperimentNo.mat
    fprintf('# Taylor Reconstruction for expNo:%d\n', experimentNo);
    demCmu35vargplvmReconstructTaylor
    %prefix = [num2str(experimentNo) '/'];
    %saveAllOpenFigures('Results/CMU/NEW/', prefix,1)
end

%% ----------- VISUALISATION
%{
clear;ca
%load('/home/andreas/SoftwareNotDrpBox/oldMatFiles/vargplvm/2/demCmu35gplvmVargplvm33.mat');
load('/home/andreas/Dropbox/_PhD/Software/github/private/vargplvm/matlab/private/priv/matFiles/Nips11/demCmu35gplvmVargplvm33.mat');
baseDir = datasetsDirectory;
dirSep = filesep;
[Y1, lbls, Ytest, lblstest] = lvmLoadData('cmu35WalkJog', [], baseDir);
skel = acclaimReadSkel([baseDir 'mocap' dirSep 'cmu' dirSep '35' dirSep '35.asf']);
[tmpchan, skel] = acclaimLoadChannels([baseDir 'mocap' dirSep 'cmu' dirSep '35' dirSep '35_01.amc'], skel);

[Y, lbls] = lvmLoadData('cmu35WalkJog');
seq = cumsum(sum(lbls)) - [1:31];
dataSetName = 'cmu35gplvm';
% load data
[Y, lbls, Ytest, lblstest] = lvmLoadData(dataSetName);
channels = demCmu35VargplvmLoadChannels(Y, skel);

modelTmp = model;
modelTmp.dynamics = [];
lvmVisualise(modelTmp, [], 'skelVargplvmVisualise', 'skelVargplvmModify', channels, skel)
figure; vargplvmShowScales(model)
%}
%------------------------


if 1
  % This is the setup used in the paper
  a=40;
  M=60;
  L=a*M;
  W=4;
  nrep=50;
else
  a=50;
  M=200;
  L=a*M;
  W=4;
  nrep=50;

end;

system('rm crossover.log');
%for gl=M:M:20*M
for gl=M:M:16*M
  s=sprintf('./time_dgt_fb %i %i %i %i %i %i >> crossover.log\n',a,M,L,W,gl,nrep);

  disp(s);
  system(s);
end;

s=sprintf('./time_dgt_fac %i %i %i %i %i > crossover.ref\n',a,M,L,W,nrep);

disp(s);
system(s);

system('rm crossover_real.log');
%for gl=M:M:20*M
for gl=M:M:16*M
  s=sprintf('./time_dgtreal_fb %i %i %i %i %i %i >> crossover_real.log\n',a,M,L,W,gl,nrep);

  disp(s);
  system(s);
end;

s=sprintf('./time_dgtreal_fac %i %i %i %i %i > crossover_real.ref\n',a,M,L,W,nrep);

disp(s);
system(s);


function [selectedSlices, nrows, ncols] = montageDims(vw);
%
% [selectedSlices, nrows, ncols] = montageDims(vw);
%
% Return the dimensions of a montage view (for inplanes, flat
% levels). selectedSlices is a vector of the slices currently
% being displayed in the montage, nrows and ncols are the rows
% and columns in the image. Takes into account an optional
% 'columnMajor' setting, so montages can run across rows
% or columns (though the interface to set this isn't written
% yet).
%
% ras, 05/05
viewType = viewGet(vw,'viewType');
ui = viewGet(vw,'ui');
switch viewType
    case 'Inplane',
        firstSlice = viewGet(vw, 'curSlice');
        nSlices = get(ui.montageSize.sliderHandle,'Value');
        selectedSlices = firstSlice:firstSlice+nSlices-1;
    case 'Flat',
        selectedSlices = getFlatLevelSlices(vw);
        nSlices = length(selectedSlices);
    otherwise,
        error('drawROIsMontage: no support for this vw type.');
end

selectedSlices = selectedSlices(selectedSlices <= viewGet(vw, 'numSlices'));
nSlices = length(selectedSlices);

if isfield(vw.ui,'settings') && isfield(vw.ui.settings,'columnMajor') ...
    && vw.ui.settings.columnMajor==1
    % montage is column-major
	ncols = ceil(sqrt(nSlices));
	nrows = ceil(nSlices/ncols);
else
    % montage is row-major
	nrows = ceil(sqrt(length(selectedSlices)));
	ncols = ceil(nSlices/nrows);
end

return


function [ min_cost  ] = get_min_cost( compressResultsDir, qFile, lamda, epsilon_soft )
%GET_MIN_COST Summary of this function goes here
%   Detailed explanation goes here

    q_file_t = fopen(qFile);
    observe_value = fscanf(q_file_t, '%d');
    fclose(q_file_t);
    observe_value(find(observe_value > 100)) = 100;  % remove some unusual counts
    q_value = (1 - mapminmax(observe_value', 0, 1))';  % actually same as in CVPR_W 2013

    fileExt = '*.txt';
    files = dir(fullfile(compressResultsDir,fileExt));

    % get the union cost
    saved_ID = [];
    for i = 0:length(files)-1

        fileCnt = num2str(i);
        fileName = [compressResultsDir, fileCnt, '.txt'];

        file_t = fopen(fileName);
        point_ID = fscanf(file_t, '%d');
        fclose(file_t);

        saved_ID = union(saved_ID, point_ID);
    end

    % sum the q_value * if_compress
    min_cost = 0;
    for i = 1:1:length(saved_ID)
        min_cost = min_cost + q_value(saved_ID(i));
    end

%     % sum the soft part
%     for i = 1:length(files)
%         min_cost = min_cost + lamda*epsilon_soft(i,:);
%     end

end


function stats = rsa_regression(obj,design,study,varargin)
% Representational similarity-based analysis, including inferences about a stimulus/task model
% Constructs a rep. dissim. matrix (RDM) based on spatial covariance across images.
% Takes a stimulus/experimental design (design), which is a set of binary regressors specifying groups of images.
% Include a second grouping variable (study) of integers coding for blocks of images to resample within.
% The function regresses the RSA matrix on the design and returns bootstrapped
% statistics on each design regressor.
%   This method can be used to analyze generalizability across constructs and studies.
% e.g., see reference to Kragel et al. 2018 below. In this case, this method tests whether
% patterns of activity in an fmri data object are generalizable across
% different groupings specified in the matrix 'design'. 'study' is an integer
% valued vector grouping images according to study. This script does not
% currently implement repeated measures designs (only include one image per
% subject). See Kragel et al. (2018) Nature Neuroscience for details.
%
% Usage:
% ::
%
%    stats = rsa_regression(obj,design);
%
% ..
%     Author and copyright information:
%
%     Copyright (C) 2018 Phil Kragel
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.
% ..
%
% :Inputs:
%
%   **obj:**
%        An image object with one or more images loaded
%
%   **design:**
%        A binary matrix where each column corresponds to a grouping
%        variable and each row corresponds to an observation.
%
% :Optional inputs:
%
%	**'average_Euclidean'**
%		Use Euclidean distance of the response averaged across all voxels (univariate distance)
%	**'euclidean'**
%		Use Euclidean distance computed using all voxels
%	**'cosine'**
%		Compute distance using cosine similarity computed using all voxelst
%	**'correlation'**
%		Compute distance using correlation distance (1 - Pearson R) computed using all voxels (default)
% :Outputs:
%   **stats:**
%    Structure including:
%      gen_index  - sample estimate of generalization indices
%      bs_gen_index - bootstrap distribution for each generalization index
%      ste  - standard error of generalization index
%      Z  - Z score for each parameter
%      p  - p value for each parameter
%      sig - significance test at FDR q < .05
%
% :Examples:
% Example 1:
% ----------------------------------------------------------------------
% Download images from Kragel et al. 2018 Nature Neuroscience
% Kragel, P. A., Kano, M., Van Oudenhove, L., Ly, H. G., Dupont, P., Rubio, A., ? Wager, T. D. (2018). Generalizable representations of pain, cognitive control, and negative emotion in medial frontal cortex. Nature Neuroscience, 21(2), 283?289. doi:10.1038/s41593-017-0051-7
% 270 subject-level images systematically sampled from 18 studies across 3 domains
% [data_obj, names] = load_image_set('kragel18_alldata');
%
% Amygdala=select_atlas_subset(load_atlas('Canlab2018'),{'Amy'});
% masked_dat=apply_mask(data_obj,Amygdala);
%
% dsgn = condf2indic(ceil(data_obj.metadata_table.Studynumber/6));
% study = data_obj.metadata_table.Studynumber;
% stats = rsa_regression(masked_dat,dsgn,study);
%
% ..
%    Programmers' notes:
% List dates and changes here, and author of changes
%    01/08/2018, created function, Phil Kragel
% ..

%% convert design matrix into dissimilarity matrix
modelRDM=[];
for i=1:size(design,2) %for each specified grouping
   modelRDM(:,i)=pdist(design(:,i),'seuclidean'); %#ok<*AGROW> %compute squared euclidean distance
   modelRDM(:,i)=100000*modelRDM(:,i)/sum(modelRDM(:,i)); %normalize and scale
end

%supress distance warning - 0 value distances get removed...
warning('off','stats:pdist:ConstantPoints')

if any(strcmp([varargin{:}],'average_Euclidean'))
    brainRDM=pdist(nanmean(obj.dat)'); %distance is based on region average
elseif any(strcmp([varargin{:}],'euclidean'))
    brainRDM=pdist(obj.dat'); %euclidean

elseif any(strcmp([varargin{:}],'cosine'))
    brainRDM=pdist(obj.dat','cosine'); %euclidean

else %default to correlation
    brainRDM=pdist(obj.dat','correlation');
end
brainRDM(brainRDM<.00001)=NaN;
gen_index= glmfit([ones(length(modelRDM),1) double(modelRDM)],brainRDM','normal','constant','off');

num_it=1000;
bs_gen_index=zeros(num_it,size(gen_index,1));
parfor it=1:num_it
bs_gen_index(it,:) = random_resample_within_study(modelRDM,obj,study,varargin);
end

%compute stats from bootstrap distribution (normal approx)
b_ste = squeeze(nanstd(bs_gen_index));
b_mean = squeeze(nanmean(bs_gen_index));
b_ste(b_ste == 0) = Inf;
b_Z = b_mean ./ b_ste;
b_P = 2 * (1 - normcdf(abs(b_Z)));

% assign stats to output
stats.gen_index=gen_index;
stats.Z=b_Z;
stats.p=b_P;
stats.sig=b_P<FDR(b_P,.05);
stats.ste=b_ste;
stats.bs_gen_index=bs_gen_index;
stats.RDM=squareform(brainRDM);

end % main function

function beta = random_resample_within_study(modelRDM,obj,study,varargin)

bs_inds=zeros(size(obj.dat,2),1); %initialize

for i=1:max(study) %for each study

    study_inds=find(study==i); %find images that belong to this study
    bs_inds(study_inds)=study_inds(randi([1,length(study_inds)],1,length(study_inds))); %randomly resample with replacement

end
%supress distance warning - 0 value distances get removed...
warning('off','stats:pdist:ConstantPoints')

resampled_data=obj.dat(:,bs_inds)'; %random subsample and transpose for correlation

if any(strcmp([varargin{:}],'average_Euclidean'))
    brainRDM=pdist(nanmean(resampled_data')'); %distance is based on region average
elseif any(strcmp([varargin{:}],'euclidean'))
    brainRDM=pdist(resampled_data); %euclidean

elseif any(strcmp([varargin{:}],'cosine'))
    brainRDM=pdist(resampled_data,'cosine'); %euclidean

else %default to correlation
    brainRDM=pdist(resampled_data,'correlation');
end

brainRDM(brainRDM<.00001)=NaN; %exclude pairs that have exactly 0 distance

beta = glmfit([ones(length(modelRDM),1) double(modelRDM)],brainRDM','normal','constant','off'); %get parameter estimates using ols

end


function a = gen_pss_fo_rom_table(f_search_set)
close all;
clear all;
f_search_set = -60e3:5e3:55e3;
[~, td_pss] = pss_gen;

tmp_td_pss = td_pss./137;
fid = fopen('pss_rom_table.txt', 'w');
fprintf(fid, '__constant float2 td_pss[3][137] = { \\ \n');

for i=1:2
    fprintf(fid, '{');
    for j=1:136
        fprintf(fid, '(float2)(%e,%e), ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
    end
    j = j + 1;
    fprintf(fid, '(float2)(%e,%e)},\\ \n ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
end
i = 3;
fprintf(fid, '{');
for j=1:136
    fprintf(fid, '(float2)(%e,%e), ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));
end
j = j + 1;
fprintf(fid, '(float2)(%e,%e)}};\n ', real(tmp_td_pss(j,i)), imag(tmp_td_pss(j,i)));

fclose(fid);

pss_fo_set = pss_fo_set_gen(td_pss, f_search_set);
pss_fo_set = pss_fo_set.';

% figure;
% subplot(2,3,1); plot(real(pss_fo_set(13,:))); hold on;
% subplot(2,3,2); plot(real(pss_fo_set(end,:))); hold on;
% subplot(2,3,3); plot(real(pss_fo_set(1,:))); hold on;
% subplot(2,3,4); plot(real(pss_fo_set(30,:))); hold on;
% subplot(2,3,5); plot(real(pss_fo_set(50,:))); hold on;
% subplot(2,3,6); plot(real(pss_fo_set(70,:))); hold on;

max_val1 = max(max(abs(real(pss_fo_set))));
max_val2 = max(max(abs(imag(pss_fo_set))));
max_val = max(max_val1, max_val2);

enlarge_ratio = ((2^15)-1)/max_val;

enlarge_ratio = floor( log2(enlarge_ratio) );

enlarge_ratio = 2^enlarge_ratio;

pss_fo_set = round(real(pss_fo_set).*enlarge_ratio) + 1i.*round(imag(pss_fo_set).*enlarge_ratio);

% figure;
% subplot(2,3,1); plot(real(pss_fo_set(13,:))); hold on;
% subplot(2,3,2); plot(imag(pss_fo_set(end,:))); hold on;
% subplot(2,3,3); plot(real(pss_fo_set(1,:))); hold on;
% subplot(2,3,4); plot(imag(pss_fo_set(30,:))); hold on;
% subplot(2,3,5); plot(real(pss_fo_set(50,:))); hold on;
% subplot(2,3,6); plot(imag(pss_fo_set(70,:))); hold on;

enlarge_ratio_log2 = log2(enlarge_ratio);

[num_pss, len_pss] = size(pss_fo_set);

fid = fopen('pss_fo_rom_table.txt', 'w');

fprintf(fid, '#define ENLARGE_RATIO (2^%d)\n\n', enlarge_ratio_log2);

fprintf(fid, '__constant short2 coef[%d] = { \\ \n', num_pss*len_pss);

for i=1:(num_pss-1)
    for j=1:len_pss
        fprintf(fid, '(short2)(%d,%d), ', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));
    end
    fprintf(fid, '\\ \n');
end
i = num_pss;
for j=1:(len_pss-1)
    fprintf(fid, '(short2)(%d,%d), ', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));
end
j=len_pss;
fprintf(fid, '(short2)(%d,%d)};\n\n', real(pss_fo_set(i,j)), imag(pss_fo_set(i,j)));

fclose(fid);


%% Copyright (C) 2015 Carnë Draug
%% Copyright (C) 2016, 2018-2019, 2022 Colin B. Macdonald
%%
%% This file is part of OctSymPy.
%%
%% OctSymPy is free software; you can redistribute it and/or modify
%% it under the terms of the GNU General Public License as published
%% by the Free Software Foundation; either version 3 of the License,
%% or (at your option) any later version.
%%
%% This software is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty
%% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
%% the GNU General Public License for more details.
%%
%% You should have received a copy of the GNU General Public
%% License along with this software; see the file COPYING.
%% If not, see <http://www.gnu.org/licenses/>.

%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @deffn Constant eulergamma ()
%% Return Euler--Mascheroni constant.
%%
%% @example
%% @group
%% eulergamma
%%   @result{} (sym) γ
%%
%% vpa (eulergamma ())
%%   @result{} (sym) 0.57721566490153286060651209008240
%% @end group
%% @end example
%%
%% @seealso{catalan}
%% @end deffn

%% Author: Carnë Draug
%% Keywords: symbolic, constants

function g = eulergamma ()

  if (nargin ~= 0)
    print_usage ();
  end

  g = pycall_sympy__ ('return sympy.S.EulerGamma,');
end

%!error catalan (sym(1))
%!assert (double (eulergamma ()) > 0.577215664901)
%!assert (double (eulergamma ()) < 0.577215664902)


function [X,labels,class_names] = ml_load_data(filename,format,label_j)
%ML_LOAD_DATA Loads a data set in which the rows are samples and the
%columns are features/dimensions. The last column should contain the class
%label. If not specified
%
%
%
%   input -----------------------------------------------------------------
%
%       o filename : string,   path to file
%
%       o formate  : string,  [.txt,.csv,...]
%
%       o label_j  : (1 x 1), column index which containts the class labels
%
%   output ----------------------------------------------------------------
%
%       o X         : (N x D), dataset of N samples of dimension D
%
%       o labels    : (N x 1), N labels
%

data = [];
if ~exist('label_j','var'), label_j = []; end

if strcmp(format,'csv') == true

   data = readtable(filename);

elseif strcmp(format,'txt') == true

    data = load(filename);
else
   warning(['No such format: ' froamt ' implemented!']);
end

if isempty(label_j)
   X = data;
else

   X            = table2array(data(:,1:end-1));
   labels       = table2array(data(:,end));
   class_names  = unique(labels);

   % if data is string convert to numbers
   if iscellstr(X) == true
      x_unique   = unique(X);
      cellfind   = @(string)(@(cell_contents)(strcmp(string,cell_contents)));
      X_tmp      = zeros(size(X));
   %   bUnknown   = false;

   %   if sum(cellfun(cellfind('?'),x_unique)) == true, bUnknown=true;end

      v = 0;
      for i=1:length(x_unique)

           idx = cellfun(cellfind(x_unique{i}),X);

           if strcmp(x_unique{i},'?') == true
               X_tmp(idx) = -1;
           else
               X_tmp(idx) = v;
               v          = v + 1;
           end
      end

        X = X_tmp;
   end

   % if labels are strings convert them to numbers
   if iscellstr(class_names) == true
       labels_tmp = zeros(size(labels,1),1);
       cellfind   = @(string)(@(cell_contents)(strcmp(string,cell_contents)));

       for i=1:size(class_names,1)
           idx              = cellfun(cellfind(class_names{i}),labels);
           labels_tmp(idx)  = i;
       end

       labels = labels_tmp;

   end

end

end


function [uu, erriter, num, tt] = test_CMF3D
%
%   Function test_CMF3D
%
%   The matlab function to show how to use the functions CMF3D_Mex and CMF3D_GPU
%
%   Before using the functions CMF3D_mex, you should compile it as follows:
%       >> mex CMF3D_mex.c
%
%   Before using the functions CMF3D_GPU, you should compile the GPU program:
%       >> nvmex -f nvmexopts.bat CMF3D_GPU.cu -IC:\cuda\v4.0\include -LC:\cuda\v4.0\lib\x64 -lcufft -lcudart
%
%   After compilation, you can define all the parameters (penalty, C_s, C_t, para) as follows:
%
%        - penalty: point to the edge-weight penalty parameters to
%                   total-variation function.
%
%          For the case without incorporating image-edge weights,
%          penalty is given by the constant everywhere. For the case
%          with image-edge weights, penalty is given by the pixelwise
%          weight function:
%
%          for example, penalty(x) = b/(1 + a*| grad f(x)|) where b,a > 0 .
%
%        - C_s: point to the capacities of source flows ps
%
%        - C_t: point to the capacities of sink flows pt
%
%        - para: a sequence of parameters for the algorithm
%             para[0,1,2]: rows, cols, heights of the given image
%             para[3]: the maximum iteration number
%             para[4]: the error bound for convergence
%             para[5]: cc for the step-size of augmented Lagrangian method
%             para[6]: the step-size for the graident-projection step to the
%                    total-variation function. Its optimal range is [0.1, 0.17].
%
%
%       Example:
%
%             >> [u, erriter, i, timet] = CMF3D_GPU(single(penalty), single(Cs), single(Ct), single(para));
%
%             >> us = max(u, beta);  % where beta in (0,1)
%
%             >> figure, loglog(erriter,'DisplayName','erriterN');figure(gcf)
%
%             >> isosurface(u,0.5), axis([1 rows 1 cols 1 heights]), daspect([1 1 1]);
%
%
%   Please email Jing Yuan (cn.yuanjing@gmail.com) for any questions,
%   suggestions and bug reports
%
%   The Software is provided "as is", without warranty of any kind.
%
%               Version 1.0
%   https://sites.google.com/site/wwwjingyuan/
%
%   Copyright 2011 Jing Yuan (cn.yuanjing@gmail.com)
%

nfi_data = load_nii('IM_0190_frame_01.nii');
ur = double(nfi_data.img)/255;
%ur = ur(1:100,1:100,1:100);

[rows,cols,heights] = size(ur);

varParas = [rows; cols; heights; 200; 5e-4; 0.35; 0.11];
%                para 0,1,2 - rows, cols, heights of the given image
%                para 3 - the maximum number of iterations
%                para 4 - the error bound for convergence
%                para 5 - cc for the step-size of augmented Lagrangian method
%                para 6 - the step-size for the graident-projection of p

penalty = 0.2*ones(rows, cols, heights);

ulab(1) = 0.2;
ulab(2) = 0.7;

% build up the priori L_2 data terms
fCs = abs(ur - ulab(1));
fCt = abs(ur - ulab(2));

% ----------------------------------------------------------------------
%  Use the function CMF3D_mex to run the algorithm on CPU
% ----------------------------------------------------------------------

%[uu, erriter,num,tt] = CMF3D_mex(single(penalty), single(fCs), single(fCt), single(varParas));

% ----------------------------------------------------------------------
%  Use the function CMF3D_GPU to run the algorithm on GPU
% ----------------------------------------------------------------------

[uu, erriter,num,tt] = CMF3D_GPU(single(penalty), single(fCs), single(fCt), single(varParas));


function sparse_grid_mixed_size_tests ( )

%*****************************************************************************80
%
%% SPARSE_GRID_MIXED_SIZE_TESTS calls SPARSE_GRID_MIXED_SIZE_TEST with various arguments.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    03 March 2011
%
%  Author:
%
%    John Burkardt
%
%  Local Parameters:
%
%    Local, real TOL, a tolerance for point equality.
%    A value of sqrt ( eps ) is reasonable, and will allow the code to
%    consolidate points which are equal, or very nearly so.  A value of
%    -1.0, on the other hand, will force the code to use every point, regardless
%    of duplication.
%
  addpath ( '../sandia_rules' );

  tol = sqrt ( eps );

  fprintf ( 1, '\n' );
  timestamp ( );
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPARSE_GRID_MIXED_SIZE_TESTS\n' );
  fprintf ( 1, '  MATLAB version\n' );
  fprintf ( 1, '  Call SPARSE_GRID_MIXED_SIZE_TEST with various arguments.\n' );
  fprintf ( 1, '  All tests will use a point equality tolerance of %e\n', tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 1 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 3 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 4 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 7 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 8 ]';
  alpha = [ 0.0, 1.5 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 2, 9 ]';
  alpha = [ 0.0, 0.5 ]';
  beta = [ 0.0, 1.5 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 6, 4 ]';
  alpha = [ 2.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );

  dim_num = 3;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 1, 2, 5 ]';
  alpha = [ 0.0, 0.0, 0.0 ]';
  beta = [ 0.0, 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );
%
%  Dimension 2, Rule 13
%
  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 13, 13 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );
%
%  Dimension 2, Rule 16
%
  dim_num = 2;
  level_max_min = 0;
  level_max_max = 2;
  rule = [ 16, 16 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );
%
%  Dimension 2, Rule 17
%
  dim_num = 2;
  level_max_min = 0;
  level_max_max = 4;
  rule = [ 17, 17 ]';
  alpha = [ 0.0, 0.0 ]';
  beta = [ 0.0, 0.0 ]';
  sparse_grid_mixed_size_test ( dim_num, level_max_min, level_max_max, ...
    rule, alpha, beta, tol );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPARSE_GRID_MIXED_SIZE_TESTS\n' );
  fprintf ( 1, '  Normal end of execution.\n' );
  fprintf ( 1, '\n' );
  timestamp ( );

  rmpath ( '../sandia_rules' );

  return
end


function [n]=nnz(a)
% Returns TT-ranks of the given tensor in TT-format
%   [N]=NNZ(A) Returns number of non zero elements in the TT representation of A
%
% TT-Toolbox 2.2, 2009-2012
%
%This is TT Toolbox, written by Ivan Oseledets et al.
%Institute of Numerical Mathematics, Moscow, Russia
%webpage: http://spring.inm.ras.ru/osel
%
%For all questions, bugs and suggestions please mail
%ivan.oseledets@gmail.com
%---------------------------

n=nnz(a.core);
return
end