plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
Sbte/RAILS-master
|
RAILSsolver.m
|
.m
|
RAILS-master/matlab/RAILSsolver.m
| 20,341 |
utf_8
|
31b3890dc232722f74a3de00509c8c0c
|
function [V,T,res,iter,resvec,timevec,restart_data] = RAILSsolver(A, M, B, varargin)
% Solver for A*V*T*V'*M+M*V*T*V'*A'+B*B'=0
% [V,T,res,iter,resvec] = RAILSsolver(A, M, B, maxit, tol, opts);
%
% Input should be clear. M can be left empty for standard Lyapunov.
%
% opts.projection_method:
% Projected equations that are solver are of the form
% V'*A*V*T*V'*M'*V+V'*M*V*T*V'*A'*V+V'*B*B'*V=0
% where the options are
% 1: V = r (default, start with V_0)
% 1.1: V = A^{-1}r (start with A^{-1}V_0)
% 1.2: V = A^{-1}r (start with A^{-1}B)
% 1.3: V = A^{-1}r (start with V_0)
% 2.1: V = [r, A^{-1}r] (start with [V_0, A^{-1}V_0])
% 2.2: V = [r, A^{-1}r] (start with [B, A^{-1}B])
% 2.3: V = [r, A^{-1}r] (start with V_0)
%
% opts.invA or opts.Ainv:
% Function that performs A^{-1}x. This can be approximate. It is
% only referenced when projection_method > 1. The default uses \
% but of course it is better to factorize this beforehand.
% (default: @(x) A\x).
%
% opts.space:
% Initial space V_0. The default is a random vector, but it can be
% set to for instance B. It will be orthonormalized within this
% function. (default: random vector).
%
% opts.expand:
% Amount of vectors used to expand the space. (default: 3).
%
% opts.nullspace:
% Space we want to be projected out of V in each step. (default: []).
%
% opts.ortho:
% Orthogonalization method. Default is standard orthogonalization,
% but one can also choose to use M-orthogonalization by setting this
% to 'M'. (default: []).
%
% opts.restart_iterations:
% Amount of iterations after which the method is restarted. The
% method will not be restarted after a set amount of iterations if
% this is set to -1. This option should be used in combination with
% a restart tolerance, not with the restart size option mentioned
% below. (default: -1)
%
% opts.restart_tolerance:
% Tolerance used for retaining eigenvectors. If this is > 0 the
% amount of vectors in V is dependent on this tolerance. (default
% 1e-3 * tol).
%
% opts.restart_upon_start: Perform a restart after the first projected
% problem is solved to reduce the size of the space. This is
% especially useful when restarting from a solution to a similar
% previous problem. (default: false).
%
% opts.restart_upon_convergence: Perform a restart upon convergence to
% reduce the size of the space. This is the same as doing a rank
% reduction as a post-processing step except that it will also
% reiterate to make sure the convergence tolerance is still
% reached. (default: true).
%
% opts.restart_size:
% Maximum amount of vectors that V can contain. The amount of
% vectors will not be limited in case this is set to -1. Setting
% this may cause the method to not converge, since a minimum rank
% of the solution is required to reach a certain tolerance. Using
% a combination of restart_iterations and restart_tolerance is
% more robust. (default: -1).
%
% opts.reduced_size:
% Amount of vectors that is used after a restart. This can be set in
% combination with the restart size option. Note that by setting
% this it is possible to throw away too much information at every
% restart. The reduced size is not limited in case this is set to
% -1. (default: -1).
%
% opts.lanczos_vectors:
% Amount of eigenvectors that you want to compute using Lanczos.
% For this we use eigs at the moment. Usually it is a good idea to
% use more vectors than the amount of expand vectors since it can
% happen that eigenvectors of the residual are already in the
% space. (default: 2 * expand).
%
% opts.lanczos_tolerance
% Tolerance for computing the eigenvectors/values.
%
% opts.fast_orthogonalization
% Uses vector operations + ortho instead of doing modified GS.
% This is less stable but about 10x as fast. (default: true).
if nargin < 3
error('Not enough input arguments');
end
args = 3;
if nargin < args+1 || ~isnumeric(varargin{args-2}) || varargin{args-2} - ceil(varargin{args-2}) ~=0
if nargin >= args+1 && isempty(varargin{args-2})
args = args + 1;
end
maxit = 100;
else
maxit = varargin{args-2};
args = args + 1;
end
hasM = ~isempty(M);
invA = [];
V = [];
AV = [];
VAV = [];
if nargin < args+1 || ~isnumeric(varargin{args-2})
if nargin >= args+1 && isempty(varargin{args-2})
args = args + 1;
end
tol = 1e-4;
else
tol = varargin{args-2};
args = args + 1;
end
restart_size = -1;
restart_iterations = -1;
reduced_size = -1;
expand = min(3, size(B, 2));
mortho = false;
ortho = true;
nullspace = [];
projection_method = 1;
restart_tolerance = 1e-3 * tol;
restart_upon_convergence = true;
restart_upon_start = false;
eigs_tol = [];
nev = [];
fast_orthogonalization = true;
% Options
verbosity = 0;
if nargin > args
opts = varargin{args-2};
if ~isa(opts, 'struct')
error('RAILSsolver:OptionsNotStructure',...
'the last argument is not a structure');
end
if isfield(opts, 'verbosity')
if strcmp(opts.verbosity, 'Verbose')
verbosity = 1;
else
verbosity = opts.verbosity;
end
end
if isfield(opts, 'invA')
invA = opts.invA;
end
if isfield(opts, 'Ainv')
invA = opts.Ainv;
end
if isfield(opts, 'space')
V = opts.space;
if ~isempty(V) && size(V, 1) ~= size(B, 1)
error('RAILSsolver:InvalidOption',...
'opts.space should have the same row dimension as A');
end
end
if isfield(opts, 'V')
V = opts.V;
if ~isempty(V) && size(V, 1) ~= size(B, 1)
error('RAILSsolver:InvalidOption',...
'opts.V should have the same row dimension as A');
end
end
if isfield(opts, 'restart_data')
if ~isempty(opts.restart_data)
if ~isfield(opts.restart_data, 'V') || ...
~isfield(opts.restart_data, 'AV') || ~isfield(opts.restart_data, 'VAV')
error('RAILSsolver:InvalidOption',...
'opts.restart_data does not contain valid restart data');
end
V = opts.restart_data.V;
if ~isempty(V) && size(V, 1) ~= size(B, 1)
error('RAILSsolver:InvalidOption',...
'opts.restart_data.V should have the same row dimension as A');
end
AV = opts.restart_data.AV;
if ~isempty(AV) && size(V, 1) ~= size(AV, 1)
error('RAILSsolver:InvalidOption',...
'opts.restart_data.AV should have the same row dimension as A');
end
VAV = opts.restart_data.VAV;
if ~isempty(VAV) && size(V, 2) ~= size(VAV, 1)
error('RAILSsolver:InvalidOption',...
'opts.restart_data.VAV should have the same column dimension as V');
end
end
end
if isfield(opts, 'space_is_orthogonalized')
if isempty(V)
error('RAILSsolver:InvalidOption',...
'opts.space has not been defined');
end
ortho = ~opts.space_is_orthogonalized;
end
if isfield(opts, 'restart_size')
restart_size = opts.restart_size;
end
if isfield(opts, 'restart_upon_convergence')
restart_upon_convergence = opts.restart_upon_convergence;
end
if isfield(opts, 'restart_upon_start')
restart_upon_start = opts.restart_upon_start;
end
if isfield(opts, 'expand')
expand = opts.expand;
if expand > size(B, 2)
error('RAILSsolver:InvalidOption',...
'opts.expand is larger than the column dimension of B');
end
end
if isfield(opts, 'nullspace')
nullspace = Morth(opts.nullspace, []);
end
if isfield(opts, 'projection_method')
projection_method = opts.projection_method;
end
if isfield(opts, 'ortho') && opts.ortho == 'M'
mortho = true;
end
if isfield(opts, 'restart_iterations')
restart_iterations = opts.restart_iterations;
end
if isfield(opts, 'restart_tolerance')
restart_tolerance = opts.restart_tolerance;
end
if isfield(opts, 'lanczos_tolerance')
eigs_tol = opts.lanczos_tolerance;
end
if isfield(opts, 'lanczos_vectors')
nev = opts.lanczos_vectors;
end
if isfield(opts, 'fast_orthogonalization')
fast_orthogonalization = opts.fast_orthogonalization;
end
if isfield(opts, 'reduced_size')
reduced_size = opts.reduced_size;
if reduced_size > 0 && restart_size > 0 && reduced_size >= restart_size
error('RAILSsolver:InvalidOption',...
'opts.reduced_size should be smaller than opts.restart_size');
end
elseif restart_size > 0
reduced_size = restart_size / 2;
end
end
tstart = tic;
% Allow for matrices and functions as input
Afun = A;
if isa(A, 'double')
% Check matrix and right hand side vector inputs have appropriate sizes
[m,n] = size(A);
if (m ~= n)
error('RAILSsolver:SquareMatrix', 'A should be a square matrix');
end
Afun = @(x) A * x;
else
m = size(B,1);
n = m;
end
% Check for a singular mass matrix
if ~isempty(M) && 1 / condest(M) < 1e-12
warning('RAILSsolver:SingularMassMatrix', ...
['Your M matrix appears to be singular. ' ...
'It is advised to use the provided RAILSschur method.']);
end
% Check projection method usage
if ~isempty(invA) && projection_method == 1
warning('RAILSsolver:InverseNotUsed', ...
['An inverse application method is provided, but the current ', ...
'projection method does not make use of this']);
elseif isempty(invA)
invA = @(x) A \ x;
end
if isempty(V)
% We use a random vector
V = (rand(n,1) - .5) * 2;
end
W = V;
if ~isempty(invA) && abs(projection_method - floor(projection_method) - 0.1) < sqrt(eps)
W = invA(V);
end
if ~isempty(invA) && abs(projection_method - floor(projection_method) - 0.2) < sqrt(eps)
V = full(B);
W = invA(V);
end
if ~isempty(invA) && floor(projection_method) == 2 && ...
abs(projection_method - floor(projection_method) - 0.3) > sqrt(eps)
V = [V, W];
elseif ~isempty(invA) && floor(projection_method) == 1 && ...
abs(projection_method - floor(projection_method) - 0.3) > sqrt(eps)
V = W;
end
if mortho
V = Morth(V, M, nullspace, [], fast_orthogonalization);
elseif ortho
V = Morth(V, [], nullspace, [], fast_orthogonalization);
end
if isempty(nev)
nev = expand;
end
MV = [];
VMV = [];
BV = [];
VBV = [];
H = [];
T = [];
resvec = [];
timevec = [];
iter = 0;
iter_since_restart = 0;
converged = false;
reduced = false;
r0 = norm(full(B'*B), 2);
% Main loop
for i=1:maxit
iter = i;
iter_since_restart = iter_since_restart + 1;
if verbosity > 0
fprintf('Iter %d\n', i);
end
% VAV = V'*A*V;
new_indices = size(VAV,2)+1:size(V,2);
AVnew = Afun(V(:, new_indices));
if isempty(VAV)
VAV = V'*AVnew;
else
VAV = [[VAV; V(:,new_indices)'*AV], V'*AVnew];
end
AV = [AV, AVnew];
% VBV = V'*B*B'*V;
new_indices = size(VBV,2)+1:size(V,2);
BVnew = B' * V(:,new_indices);
if isempty(VBV)
VBV = BVnew'*BVnew;
else
t = BVnew'*BV;
VBV = [[VBV; t], [t'; BVnew'*BVnew]];
end
BV = [BV, BVnew];
% This is not needed if we use a normal
% Lyapunov solver instead of a general one
if hasM
old_indices = 1:size(MV,2);
new_indices = size(MV,2)+1:size(V,2);
MVnew = M*V(:, new_indices);
MV = [MV, MVnew];
end
if hasM && ~mortho
% VMV = V'*M*V;
if isempty(VMV)
VMV = V'*MVnew;
else
VMV = [[VMV; V(:, new_indices)'*MV(:,old_indices)], V'*MVnew];
end
T = lyap(VAV, VBV, [], VMV);
else
T = lyap(VAV, VBV);
end
% Compute eigenvalues and vectors of the residual, but make
% sure we do not compute too many
eopts.issym = true;
eopts.tol = eigs_tol;
if hasM
[V2,D2] = eigs(@(x) AV*(T*(MV'*x)) + MV*(T*(AV'*x)) + B*(B'*x), n, nev, 'lm');
else
[V2,D2] = eigs(@(x) AV*(T*(V'*x)) + V*(T*(AV'*x)) + B*(B'*x), n, nev, 'lm');
end
H = D2;
% Sort eigenvectors by size of the eigenvalue
[~,I2] = sort(abs(diag(D2)), 1, 'descend');
V2 = V2(:, I2);
D2 = D2(I2, I2);
% Orthogonalize so we do not use too eigenvectors that are
% already in the space
if mortho
V2 = Morth(V2, M, V, [], fast_orthogonalization);
else
V2 = Morth(V2, [], V, [], fast_orthogonalization);
end
res = norm(D2, inf);
if verbosity > 0
fprintf('Estimate Lanczos, absolute: %e, relative: %e, num eigenvectors: %d\n',...
res, res / r0, size(V2, 2));
end
res = res / r0;
if iter_since_restart > 1 || i == 1
resvec = [resvec; res];
timevec = [timevec; toc(tstart)];
end
if abs(res) < tol
if converged || ~restart_upon_convergence
if verbosity > 0
fprintf('Converged with space size %d\n', size(V, 2));
end
if nargout > 6
restart_data.V = V;
restart_data.AV = AV;
restart_data.VAV = VAV;
end
break;
end
converged = true;
end
if i >= maxit || size(V,2) >= m
if nargout > 6
restart_data.V = V;
restart_data.AV = AV;
restart_data.VAV = VAV;
end
if projection_method == 1
warning('RAILSsolver:ProjectionMethod', ...
['Convergence has not been achieved with ' ...
'opts.projection_method = 1. ' ...
'It is advised to set opts.projection_method ' ...
'to a different value. For instance ' ...
'opts.projection_method = 1.2.']);
end
break;
end
if (i == 1 && restart_upon_start) ...
|| (restart_iterations > 0 && iter_since_restart == restart_iterations) ...
|| (isempty(H) && reduced_size > 0 && size(T,1) > reduced_size) ...
|| (restart_size > 0 && size(T, 1) > restart_size) ...
|| (converged && ~reduced)
if reduced_size > 0 && reduced_size < size(V, 2)
if verbosity > 0
fprintf(['Decreasing search space size. Trying %d ' ...
'vectors.\n'], reduced_size);
end
[V3, D3] = eigs(T, reduced_size);
else
if verbosity > 0
fprintf(['Decreasing search space size. Trying %d ' ...
'vectors.\n'], size(V, 2));
end
[V3, D3] = eig(T);
end
d = abs(diag(D3));
I3 = find(d / max(d) > restart_tolerance);
% Restart using only the part of the largest eigenvectors
[~,s] = sort(d(I3),'descend');
V3 = V3(:, I3(s));
V = V * V3;
if verbosity > 0
fprintf('Restarted with %d vectors.\n', size(V, 2));
end
reduced = converged;
reortho = 0;
if reortho
VAV = [];
AV = [];
VMV = [];
MV = [];
VBV = [];
BV = [];
else
VAV = V3' * VAV * V3;
AV = AV * V3;
if ~isempty(MV)
MV = MV * V3;
end
if ~isempty(VMV)
VMV = V3' * VMV * V3;
end
VBV = V3' * VBV * V3;
% Make this symmetric for safety reasons
VBV = (VBV + VBV') / 2;
BV = BV * V3;
end
iter_since_restart = 0;
continue
end
% Max number of expansion vectors we want
num = min(min(expand, size(V2,2)), m - size(V,2));
W = V2(:, 1:num);
if ~isempty(invA) && projection_method < 2 && projection_method > 1
W = invA(W);
elseif ~isempty(invA) && projection_method < 3 && projection_method > 2
W = [W, invA(W)];
end
if mortho
V = Morth(W, M, nullspace, V, fast_orthogonalization);
else
V = Morth(W, [], nullspace, V, fast_orthogonalization);
end
end
if verbosity > 3 && verbosity < 5
semilogy(resvec);
end
end
function V = Morth(W, M, nullspace, V, fast_orthogonalization)
% MGS M-orthogonalisation
if nargin < 5
fast_orthogonalization = false;
end
if nargin < 4
V = [];
end
if nargin < 3
nullspace = [];
end
num_iter = 1;
tol = 1e-8;
if isempty(M)
if fast_orthogonalization
% Really fast orthogonalization, which is not so stable
if ~isempty(nullspace)
W = W - nullspace*(nullspace'*W);
end
if ~isempty(V)
W = W - V*(V'*W);
end
V = [V, orth(W)];
else
% Actual modified GS, which is supposed to be about as fast
% but is actually 10x as slow...
for i = 1:size(W,2)
v1 = W(:,i) / norm(W(:,i));
for k = 1:num_iter
v1 = nullspace_op(v1);
for j=1:size(V,2)
v1 = v1 - V(:,j)*(V(:,j)'*(v1));
end
end
nrm = norm(v1);
if nrm < tol
continue;
end
V(:,size(V,2)+1) = v1 / nrm;
end
end
else
% Modified GS with M-inner product
for i = 1:size(W,2)
v1 = W(:,i) / norm(W(:,i));
for k = 1:num_iter
v1 = nullspace_op(v1);
for j=1:size(V,2)
v1 = v1 - V(:,j)*(V(:,j)'*(M*v1));
end
end
nrm = sqrt(v1'*M*v1);
if nrm < tol
continue;
end
V(:,size(V,2)+1) = v1 / nrm;
end
end
function y = nullspace_op(x)
y = x;
if ~isempty(nullspace)
if isa(nullspace, 'function_handle')
y = nullspace(x);
else
if isempty(M)
for ii=1:size(nullspace, 2)
y = y - nullspace(:,ii) * (nullspace(:,ii)' * y);
end
else
for ii=1:size(nullspace, 2)
y = y - nullspace(:,ii) * (nullspace(:,ii)' * (M * y));
end
end
end
end
end
end
|
github
|
Sbte/RAILS-master
|
test_random.m
|
.m
|
RAILS-master/matlab/test/test_random.m
| 1,058 |
utf_8
|
91077ecde07f2915b1b3356db39952c0
|
function test_suite = test_random
try
test_functions = localfunctions();
test_suite = functiontests(test_functions);
catch
end
try
initTestSuite;
catch
end
end
function seed()
if ~exist('rng')
rand('state', 4634);
else
rng(4634)
end
end
function test_random_ev(t)
seed;
n = 64;
A = sprand(n,n,10/n);
M = speye(n);
[B,~] = eigs(A,1);
[V, S, res, iter] = RAILSsolver(A, M, B, 64);
t.assertLessThan(iter, 10);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_random_64(t)
seed;
n = 64;
A = sprand(n,n,10/n);
B = rand(n,1);
M = spdiags(rand(n,1), 0, n, n);
opts.restart_upon_convergence = false;
[V, S, res] = RAILSsolver(A, M, B, opts);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
|
github
|
Sbte/RAILS-master
|
test_Laplace.m
|
.m
|
RAILS-master/matlab/test/test_Laplace.m
| 2,469 |
utf_8
|
07e753f63eca25b1bf772d066ffe2f10
|
function test_suite = test_Laplace
try
test_functions = localfunctions();
test_suite = functiontests(test_functions);
catch
end
try
initTestSuite;
catch
end
end
function A = laplacian2(n)
m = sqrt(n);
I = speye(m);
e = ones(m,1);
T = spdiags([e -4*e e], -1:1, m, m);
S = spdiags([e e], [-1 1], m, m);
A = (kron(I,T) + kron(S,I));
end
function seed()
if ~exist('rng')
rand('state', 4634);
else
rng(4634)
end
end
function test_Laplace_64(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
[V, S, res, iter] = RAILSsolver(A,M,B);
t.assertLessThan(iter, n-10);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_Laplace_256(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
[V, S, res, iter] = RAILSsolver(A,M,B);
t.assertLessThan(iter, n-10);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_Laplace_maxit(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
t.assertWarning(@(x) RAILSsolver(A, M, B, 10), 'RAILSsolver:ProjectionMethod');
end
function test_Laplace_singular(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
M(n, n) = 0;
B = rand(n,1);
t.assertWarning(@(x) RAILSsolver(A, M, B, 10), 'RAILSsolver:SingularMassMatrix');
end
function test_Laplace_equivalence(t)
% Here we show that the Laplace problem is also a Lyapunov problem
seed;
n = 1024;
m = sqrt(n);
A_lapl = laplacian2(n);
e = ones(n, 1);
A = spdiags([e, -2*e, e], -1:1, m, m);
I = speye(m);
A_kron = kron(A, I) + kron(I, A);
t.assertEqual(A_lapl, A_kron);
B = rand(m, 1);
b = -reshape(B*B', n, 1);
x_lapl = A_lapl \ b;
opts.restart_upon_convergence = false;
[V, S, res, iter] = RAILSsolver(A, [], B, opts);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'+V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
x_lyap = reshape(V*S*V', n, 1);
t.assertLessThan(norm(x_lapl-x_lyap), 1E-4);
end
|
github
|
Sbte/RAILS-master
|
test_MOC.m
|
.m
|
RAILS-master/matlab/test/test_MOC.m
| 3,671 |
utf_8
|
0321d28c9adbeba96274c4647a162ff9
|
function test_suite = test_MOC
try
test_functions = localfunctions();
test_suite = functiontests(test_functions);
catch
end
try
initTestSuite;
catch
end
end
function test_MOC_Erik(t)
[A,M,B] = get_MOC_data();
n = size(A, 1);
t.assertEqual(n, 8*8*4*6);
res = 0;
[A2,M2,B2] = add_border(A, M, B);
% Solve the Schur complement system
[S, MS, BS, Sinv, Vtrans] = RAILSschur(A2, M2, B2);
[V, T] = RAILSsolver(S, MS, BS, 1000, 1e-3);
res = norm(S(V)*T*(V'*MS') + (MS*V)*(S(V)*T)' + BS*BS', 'fro');
t.assertLessThan(res, 1E-3);
V = Vtrans(V);
V = V(1:n,:);
res = norm(A*V*T*V'*M' + M*V*T*V'*A' + B*B', 'fro');
t.assertLessThan(res, 1E-3);
end
function test_MOC_inv(t)
[A,M,B] = get_MOC_data();
n = size(A, 1);
t.assertEqual(n, 8*8*4*6);
res = 0;
[A2,M2,B2] = add_border(A, M, B);
% Solve the Schur complement system
[S, MS, BS, Sinv, Vtrans] = RAILSschur(A2, M2, B2);
opts.projection_method = 2.2;
opts.Ainv = Sinv;
[V, T] = RAILSsolver(S, MS, BS, 1000, 1e-3, opts);
res = norm(S(V)*T*(V'*MS') + (MS*V)*(S(V)*T)' + BS*BS', 'fro');
t.assertLessThan(res, 1E-3);
V = Vtrans(V);
V = V(1:n,:);
res = norm(A*V*T*V'*M' + M*V*T*V'*A' + B*B', 'fro');
t.assertLessThan(res, 1E-3);
end
function test_MOC_factorize(t)
[A,M,B] = get_MOC_data();
n = size(A, 1);
t.assertEqual(n, 8*8*4*6);
res = 0;
[A2,M2,B2] = add_border(A, M, B);
% Solve the Schur complement system
[S, MS, BS, Sinv, Vtrans] = RAILSschur(A2, M2, B2, true);
opts.projection_method = 2.2;
opts.Ainv = Sinv;
[V, T] = RAILSsolver(S, MS, BS, 1000, 1e-3, opts);
res = norm(S(V)*T*(V'*MS') + (MS*V)*(S(V)*T)' + BS*BS', 'fro');
t.assertLessThan(res, 1E-3);
V = Vtrans(V);
V = V(1:n,:);
res = norm(A*V*T*V'*M' + M*V*T*V'*A' + B*B', 'fro');
t.assertLessThan(res, 1E-3);
end
function [A,M,B] = get_MOC_data()
dir = fileparts(mfilename('fullpath'));
Abeg = load([dir, '/../DataErik/Ap1.beg']);
Aco = load([dir, '/../DataErik/Ap1.co']);
Ainfo = load([dir, '/../DataErik/Ap1.info']);
Ajco = load([dir, '/../DataErik/Ap1.jco']);
Arl = load([dir, '/../DataErik/Ap1.rl']);
Mco = load([dir, '/../DataErik/Bp1.co']);
F = load([dir, '/../DataErik/Frcp1.co']);
n = Ainfo(1);
nnz = Ainfo(2);
ivals = zeros(nnz,1);
jvals = Ajco;
vals = Aco;
row = 1;
idx = 1;
while row <= n
for k = Abeg(row):Abeg(row+1)-1
ivals(idx) = row;
idx = idx + 1;
end
row = row + 1;
end
A = sparse(ivals, jvals, vals, n, n);
M = sparse(1:n, 1:n, Mco, n, n);
% Set everything but temperature and salinity to zero
idx = 1:6:n;
idx = [idx, idx+1, idx+2, idx+3];
M(idx,idx) = 0;
% Set everything but salinity to zero
idx = 1:6:n;
idx = [idx, idx+1, idx+2, idx+3, idx+4];
F(idx) = 0;
% Spatially correlated noise
B = 0.1 * F;
end
function [A2, M2, B2] = add_border(A, M, B)
% Add the nullspace to the matrix as border
n = size(A, 1);
A2 = sparse(n+2, n+2);
A2(1:n, 1:n) = A;
for j = 0:n-1
if (mod(j, 6) == 3)
if mod((mod(floor(j / 6), 4) + mod(floor(floor(j / 6) / 4), 16)), 2) == 0
A2(n+1, j+1) = 1;
A2(j+1, n+1) = 1;
else
A2(n+2, j+1) = 1;
A2(j+1, n+2) = 1;
end
end
end
M2 = sparse(n+2, n+2);
M2(1:n, 1:n) = M;
B2 = sparse(n+2, size(B,2));
B2(1:n, 1:size(B,2)) = B;
end
|
github
|
Sbte/RAILS-master
|
test_opts.m
|
.m
|
RAILS-master/matlab/test/test_opts.m
| 5,219 |
utf_8
|
978879b3a34be12cc2cbaadd5018327f
|
function test_suite = test_opts
try
test_functions = localfunctions();
test_suite = functiontests(test_functions);
catch
end
try
initTestSuite;
catch
end
end
function A = laplacian2(n)
m = sqrt(n);
I = speye(m);
e = ones(m,1);
T = spdiags([e -4*e e], -1:1, m, m);
S = spdiags([e e], [-1 1], m, m);
A = (kron(I,T) + kron(S,I));
end
function seed()
if ~exist('rng')
rand('state', 4634);
else
rng(4634)
end
end
function test_tol(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
tol = 5e-5;
[V, S, res, iter] = RAILSsolver(A,M,B,tol);
t.assertLessThan(iter, n-10);
t.assertLessThan(res, tol);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), tol);
t.assertGreaterThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), tol / 10);
end
function test_restart(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
clear opts;
opts.restart_size = 50;
opts.reduced_size = 10;
[V, S, res, iter] = RAILSsolver(A,M,B,opts);
t.assertEqual(size(V,2), 10);
t.assertLessThan(iter, 100);
t.assertEqual(size(V, 2), size(S, 2));
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_restart2(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
maxit = 110;
clear opts;
opts.reduced_size = 15;
opts.restart_iterations = 40;
[V, S, res, iter] = RAILSsolver(A,M,B,maxit,opts);
t.assertLessThan(iter, maxit);
t.assertEqual(size(V, 2), size(S, 2));
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_restart3(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
maxit = 150;
clear opts;
opts.restart_size = 50;
opts.reduced_size = 10;
opts.restart_iterations = 20;
opts.restart_tolerance = 1e-2;
[V, S, res, iter] = RAILSsolver(A,M,B,maxit,opts);
t.assertLessThan(iter, maxit);
t.assertEqual(size(V, 2), size(S, 2));
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_wrong_restart(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
clear opts;
opts.restart_size = 10;
opts.reduced_size = 50;
t.assertError(@() RAILSsolver(A,M,B,opts), 'RAILSsolver:InvalidOption');
end
function test_wrong_expand(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
clear opts;
opts.expand = 3;
t.assertError(@() RAILSsolver(A,M,B,opts), 'RAILSsolver:InvalidOption');
end
function test_wrong_space(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
clear opts;
opts.space = rand(n-1,1);
t.assertError(@() RAILSsolver(A,M,B,opts), 'RAILSsolver:InvalidOption');
end
function test_no_inverse(t)
seed;
n = 64;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
clear opts;
opts.Ainv = @(x) [];
t.assertWarning(@() RAILSsolver(A,M,B,opts), 'RAILSsolver:InverseNotUsed');
end
function test_space(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
maxit = 150;
clear opts;
opts.restart_size = 50;
opts.reduced_size = 10;
[V, S, res, iter] = RAILSsolver(A,M,B,maxit,opts);
opts.space = V(:,1:9);
[V, S, res, iter2] = RAILSsolver(A,M,B,maxit,opts);
t.assertLessThan(iter2, iter);
t.assertEqual(size(V, 2), size(S, 2));
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_morth(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
opts.ortho = 'M';
[V, S, res, iter] = RAILSsolver(A,M,B,opts);
t.assertLessThan(iter, n-10);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
function test_nullspace(t)
seed;
n = 256;
A = laplacian2(n);
M = spdiags(rand(n,1), 0, n, n);
B = rand(n,1);
Q = rand(n,1);
Q = Q / norm(Q);
P = speye(n) - Q * Q';
A = P*A*P;
B = P*B;
M = P*M*P;
opts.nullspace = Q;
warning('off', 'RAILSsolver:SingularMassMatrix');
[V, S, res, iter] = RAILSsolver(A,M,B,opts);
warning('on', 'RAILSsolver:SingularMassMatrix');
t.assertLessThan(norm(Q'*V), 1E-10);
t.assertLessThan(res * norm(B'*B), 1E-2);
t.assertLessThan(res, 1E-4);
t.assertLessThan(norm(A*V*S*V'*M'+M*V*S*V'*A'+B*B') / norm(B'*B), 1E-4);
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
even_sample.m
|
.m
|
E231A_QuadcopterMPC-master/gen/even_sample.m
| 2,009 |
utf_8
|
1d30ba0d23065fd6540ed2803c83ed56
|
%***********************************************************************
%
% CONVERTS A RANDOMLY SAMPLED SIGNAL SET INTO AN EVENLY SAMPLED
% SIGNAL SET (by interpolation)
%
% By : Haldun KOMSUOGLU
% Start : 07/23/1999
% Last : 07/23/1999
% Statue : Neural Model Research Material
%
% Inputs:
% t : A column vector that contains the time values for the
% corresponding computed state trajectory points
% x : A matrix in which each row is a state value on the
% solution trajectory that corresponds to the time value in
% vector t with the same row value. Format of each row:
% row = [x1 x2 ... xN]
% Fs: The sampling frequency (1/sec) for the evenly sampled
% set to be generated.
%
% Outputs:
% Et : Even sampling instants. This is a column vector in the
% same format with "t".
% Ex : A matrix of the same form with "x" that contains the
% state values corresponding to the time instants in Et
%
%***********************************************************************
function [Et, Ex] = even_sample(t, x, Fs, type)
if nargin < 4, type = 'linear'; end
dt = diff(t);
dt = dt + (dt==0)*1e-5;
t = [0;cumsum(dt)];
% Obtain the process related parameters
N = size(x, 2); % number of signals to be interpolated
M = size(t, 1); % Number of samples provided
t0 = t(1,1); % Initial time
tf = t(M,1); % Final time
EM = (tf-t0)*Fs; % Number of samples in the evenly sampled case with
% the specified sampling frequency
Et = linspace(t0, tf, round(EM))';
% Using linear interpolation (used to be cubic spline interpolation)
% and re-sample each signal to obtain the evenly sampled forms
for s = 1:N,
Ex(:,s) = interp1(t(:,1), x(:,s), Et(:,1),type);
end;
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
generate_ref_trajectory.m
|
.m
|
E231A_QuadcopterMPC-master/gen/generate_ref_trajectory.m
| 1,320 |
utf_8
|
9b963154ee1991952c8362024c02885b
|
function[xref,uref] = generate_ref_trajectory(t, sys)
%%
% function to generate reference trajectory
%%
% time = 0:params.Ts:(params.Tf+params.N*params.Ts);
traj = @(t) sin_traj(t);
% traj = @(t) circ_traj(t);
% xref = [];
% uref = [];
% for it = time
[ref] = sys.flat2state(traj(t));
xref = [ref.y; ref.z; ref.phi; ref.dy; ref.dz; ref.dphi];
uref = [ref.F1; ref.F2];
% xref = [xref, xref_];
% uref = [uref, uref_];
% end
end
function [flats] = sin_traj(t)
y0 = 0;
z0 = 0;
vy0 = 1;
ay0 = 0.05;
zr = 1;
f = 0.25;
w = 2*pi*f;
flats.x = [ay0.*t.^2+t.*vy0+y0;z0+zr.*sin(t.*w)];
flats.dx = [2.*ay0.*t+vy0;w.*zr.*cos(t.*w)];
flats.d2x = [2.*ay0;(-1).*w.^2.*zr.*sin(t.*w)];
flats.d3x = [0;(-1).*w.^3.*zr.*cos(t.*w)];
flats.d4x = [0;w.^4.*zr.*sin(t.*w)];
end
function [flats] = circ_traj(t)
y0 = 0;
z0 = 0;
ry = 0.5;
rz = 0.5;
f = 0.5;
w = 2*pi*f;
flats.x = [y0+ry.*sin(t.*w),z0+rz.*cos(t.*w)];
flats.dx = [ry.*w.*cos(t.*w),(-1).*rz.*w.*sin(t.*w)];
flats.d2x = [(-1).*ry.*w.^2.*sin(t.*w),(-1).*rz.*w.^2.*cos(t.*w)];
flats.d3x = [(-1).*ry.*w.^3.*cos(t.*w),rz.*w.^3.*sin(t.*w)];
flats.d4x = [ry.*w.^4.*sin(t.*w),rz.*w.^4.*cos(t.*w)];
% flats.x = flip(flats.x);
% flats.dx = flip(flats.dx);
% flats.d2x = flip(flats.d2x);
% flats.d3x = flip(flats.d3x);
% flats.d4x = flip(flats.d4x);
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
struct_overlay.m
|
.m
|
E231A_QuadcopterMPC-master/gen/struct_overlay.m
| 2,259 |
utf_8
|
658e5adeaf0be01c43bb8ef6922d5f7f
|
%> @brief struct_overlay Overlay default fields with input fields
%> @author Eric Cousineau <[email protected]>
%> @note From optOverlay() on Mathworks, modified
function [opts] = struct_overlay(opts_default, opts_in, options)
% Simple cases
if iscell(opts_default)
opts_default = struct(opts_default{:});
end
if isempty(opts_in)
opts = opts_default;
return;
end
if iscell(opts_in)
opts_in = struct(opts_in{:});
end
is_valid = @(o) isstruct(o) && length(o) == 1;
assert(is_valid(opts_default), 'opts_default must be scalar struct or structable cell array');
assert(is_valid(opts_in), 'opts_in must be scalar struct or structable cell array');
persistent func_opts_default;
if isempty(func_opts_default)
func_opts_default = struct('Recursive', true, 'AllowNew', false);
end
if nargin < 3
options = func_opts_default;
else
if iscell(options)
options = struct(options{:});
end
options = struct_overlay(func_opts_default, options);
end
%TODO Tackle struct arrays?
new_fields = fieldnames(opts_in);
options_index = find(strcmp(new_fields, 'overlay_options'));
indices = 1:length(new_fields);
if ~isempty(options_index)
options = struct_overlay(options, opts_in.overlay_options);
indices(options_index) = [];
end
if ~options.AllowNew
% Check to see if there are bad fields
fields = fieldnames(opts_default);
unoriginal = setdiff(new_fields(indices), fields);
if ~isempty(unoriginal)
error(['Fields are not in original: ', implode(unoriginal, ', ')]);
end
end
opts = opts_default;
for i = 1:length(indices)
index = indices(i);
field = new_fields{index};
new_value = opts_in.(field);
% Apply recursion
if options.Recursive && isfield(opts, field)
cur_value = opts.(field);
% Both values must be proper option structs
if is_valid(cur_value) && is_valid(new_value)
new_value = struct_overlay(cur_value, new_value, options);
end
end
opts.(field) = new_value;
end
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
animateQuadrotorload.m
|
.m
|
E231A_QuadcopterMPC-master/@Quadrotorload/animateQuadrotorload.m
| 4,679 |
utf_8
|
71d2d272f431653bc24b013a34dc03b5
|
function animateQuadrotorload(obj,opts_in)
% function to animate the quadrotor
% default options
opts_default.RATE = 25 * 2;
opts_default.t = [];
opts_default.x = [];
opts_default.xd = [0;0];
opts_default.td = [];
opts_default.interp_type = 'spline';
opts_default.vid.MAKE_MOVIE = 0;
opts_default.vid.filename = 'results/vid1';
opts_default.vid.Quality = 100;
opts_default.vid.FrameRate = 24;
% initialize the animation figure and axes
figure_x_limits = [-2 2];
figure_y_limits = [-2 2];
figure_z_limits = [0 1] ;
fig1 = figure;
set(0,'Units','pixels')
scnsize = get(0,'ScreenSize');
screen_width = scnsize(3);
screen_height = scnsize(4);
% find the minimum scaling factor
figure_x_size = figure_x_limits(2) - figure_x_limits(1);
figure_y_size = figure_y_limits(2) - figure_y_limits(1);
xfactor = screen_width/figure_x_size;
yfactor = screen_height/figure_y_size;
if (xfactor < yfactor)
screen_factor = 0.5*xfactor;
else
screen_factor = 0.5*yfactor;
end
% calculate screen offsets
screen_x_offset = (screen_width - screen_factor*figure_x_size)/2;
screen_y_offset = (screen_height - screen_factor*figure_y_size)/2;
% draw figure and axes
set(fig1,'Position', [screen_x_offset screen_y_offset...
1.5*screen_factor*figure_x_size 1.5*screen_factor*figure_y_size]);
set(fig1,'MenuBar', 'none');
axes1 = axes;
set(axes1,'XLim',figure_x_limits,'YLim',figure_y_limits);
% set(axes1,'Position',[0 0 1 1]);
% set(axes1,'Color','w');
% set(axes1,'TickDir','out');
axis equal ;
% get inputs
opts = struct_overlay(opts_default,opts_in);
% extract data
RATE = opts.RATE;
t = opts.t;
x = opts.x;
td = opts.td;
xd = opts.xd;
if isrow(t)
t = t';
end
if size(x,2)>size(x,1)
x = x';
end
box on;
[t, x] = even_sample(t, x, RATE,opts.interp_type);
t = t+t(1);
xd_flag = true;
if length(xd) == 2
xd = repmat(xd',length(x),1);
else
[~, xd] = even_sample(td,xd,RATE,opts.interp_type);
end
if(opts.vid.MAKE_MOVIE)
M = moviein(length(t)) ;
vidObj = VideoWriter(strcat(opts.vid.filename,'.avi'),'Motion JPEG AVI');
vidObj.FrameRate = opts.vid.FrameRate;
vidObj.Quality = opts.vid.Quality;
open(vidObj);frameRate = vidObj.FrameRate;
% nFrame = floor(frameRate*t(end));
frameDelay = 1/frameRate;
time = 0;
end
%%
L_cable = obj.l;
hist = 1 ;
%% animate
for i=1:length(t)
drawQuadrotorload(axes1, x(i,:)',L_cable);
plot(x(max(1,i-hist):i, 1), x(max(1,i-hist):i, 2), 'k') ;
if xd_flag
l = plot(xd(max(1,i-hist):i, 1), xd(max(1,i-hist):i, 2), 'og','linewidth',1);
l.Color(4) = 0.4;
end
% plot3(x(max(1,i-hist):i, 1)-L*x(max(1,i-hist):i,7), x(max(1,i-hist):i, 2)-L*x(max(1,i-hist):i,8), x(max(1,i-hist):i, 3)-L*x(max(1,i-hist):i,9), 'r') ;
s = sprintf('Running\n t = %1.2fs \n 1/%d realtime speed',t(i), RATE/25);
text(x(i,1)-1.5,x(i,2)+1.5,s,'FontAngle','italic','FontWeight','bold');
drawnow;
figure_x_limits_ = figure_x_limits+x(i,1);
figure_y_limits_ = figure_y_limits+x(i,2);
set(axes1,'XLim',figure_x_limits_,'YLim',figure_y_limits_);
if opts.vid.MAKE_MOVIE
M(:,i) = getframe;
% Write data to video file
writeVideo(vidObj,getframe(gcf));
% time step system to next frame:
time = time + frameDelay;
end
end
end
function drawQuadrotorload(parent,x,l)
tem = get(parent,'Children');
delete(tem);
yL = x(1);
zL = x(2);
phiL = x(3);
phiQ = x(4);
yQ = yL-l*sin(phiL);
zQ = zL+l*cos(phiL);
s.L = 0.175;
s.R = 0.05;
base = [[s.L; 0], [-s.L; 0], [s.L; s.R], [-s.L; s.R]];
R = [cos(phiQ), -sin(phiQ);
sin(phiQ), cos(phiQ)];
points = [yQ;zQ] + R'*base;
cable = [ [yQ; zQ], [yL; zL]];
s.qhandle1 = line([points(1,1), points(1,2)], [points(2,1), points(2,2)]); hold on ;
s.qhandle2 = line([points(1,1), points(1,3)], [points(2,1), points(2,3)]);
s.qhandle3 = line([points(1,2), points(1,4)], [points(2,2), points(2,4)]);
s.cable = line(cable(1,:),cable(2,:));
set(s.qhandle1,'Color','r', 'LineWidth',2);
set(s.qhandle2,'Color','b', 'LineWidth',2);
set(s.qhandle3,'Color','b', 'LineWidth',2);
set(s.cable,'Color','b');
s.hload = scatter(yL,zL, 'rs', 'LineWidth',1) ;
grid on;
xlabel('Y');
ylabel('Z');
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
bSpline2.m
|
.m
|
E231A_QuadcopterMPC-master/mpc_ayush/bSpline2.m
| 2,059 |
utf_8
|
b45ad2816bc9e52ce44275b49f0c1de6
|
function x = bSpline2(tGrid,xGrid,fGrid,t)
% x = bSpline2(tGrid,xGrid,fGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data.
% The quadratic interpolant is constructed such that the slope matches on
% both sides of each interval, and the function value matches on the lower
% side of the interval.
%
% INPUTS:
% tGrid = [1, n] = time grid (knot points)
% xGrid = [m, n] = function at each grid point in tGrid
% fGrid = [m, n] = derivative at each grid point in tGrid
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
[m,n] = size(xGrid);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
[~, bin] = histc(t,[-inf,tGrid,inf]);
bin = bin - 1;
% Loop over each quadratic segment
for i=1:(n-1)
idx = i==bin;
if sum(idx) > 0
h = (tGrid(i+1)-tGrid(i));
xLow = xGrid(:,i);
fLow = fGrid(:,i);
fUpp = fGrid(:,i+1);
delta = t(idx) - tGrid(i);
x(:,idx) = bSpline2Core(h,delta,xLow,fLow,fUpp);
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==0 | bin==(n+1);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = bSpline2Core(h,delta,xLow,fLow,fUpp)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% alpha = fraction of the way through the interval
% xLow = function value at lower bound
% fLow = derivative at lower bound
% fUpp = derivative at upper bound
%
% OUTPUTS:
% x = [m, p] = function at query times
%
%Fix dimensions for matrix operations...
col = ones(size(delta));
row = ones(size(xLow));
delta = row*delta;
xLow = xLow*col;
fLow = fLow*col;
fUpp = fUpp*col;
fDel = (0.5/h)*(fUpp-fLow);
x = delta.*(delta.*fDel + fLow) + xLow;
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
pwPoly2.m
|
.m
|
E231A_QuadcopterMPC-master/traj_opt_ayush/pwPoly2.m
| 2,091 |
utf_8
|
711acbf5b78fa5ee04eaca84e6de2f0c
|
function x = pwPoly2(tGrid,xGrid,t)
% x = pwPoly2(tGrid,xGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data,
% given the function value at the edges and midpoint of the interval of
% interest.
%
% INPUTS:
% tGrid = [1, 2*n-1] = time grid, knot idx = 1:2:end
% xGrid = [m, 2*n-1] = function at each grid point in tGrid
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
nGrid = length(tGrid);
if mod(nGrid-1,2)~=0 || nGrid < 3
error('The number of grid-points must be odd and at least 3');
end
% Figure out sizes
n = floor((length(tGrid)-1)/2);
m = size(xGrid,1);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
edges = [-inf, tGrid(1:2:end), inf];
[~, bin] = histc(t,edges);
% Loop over each quadratic segment
for i=1:n
idx = bin==(i+1);
if sum(idx) > 0
gridIdx = 2*(i-1) + [1,2,3];
x(:,idx) = quadInterp(tGrid(gridIdx),xGrid(:,gridIdx),t(idx));
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==1 | bin==(n+2);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = quadInterp(tGrid,xGrid,t)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% tGrid = [1, 3] = time grid
% xGrid = [m, 3] = function grid
% t = [1, p] = query times, spanned by tGrid
%
% OUTPUTS:
% x = [m, p] = function at query times
%
% Rescale the query points to be on the domain [-1,1]
t = 2*(t-tGrid(1))/(tGrid(3)-tGrid(1)) - 1;
% Compute the coefficients:
a = 0.5*(xGrid(:,3) + xGrid(:,1)) - xGrid(:,2);
b = 0.5*(xGrid(:,3)-xGrid(:,1));
c = xGrid(:,2);
% Evaluate the polynomial for each dimension of the function:
p = length(t);
m = size(xGrid,1);
x = zeros(m,p);
tt = t.^2;
for i=1:m
x(i,:) = a(i)*tt + b(i)*t + c(i);
end
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
pwPoly3.m
|
.m
|
E231A_QuadcopterMPC-master/traj_opt_ayush/pwPoly3.m
| 2,445 |
utf_8
|
f6e1d4ad154e13881760efe5bc8ffe9b
|
function x = pwPoly3(tGrid,xGrid,fGrid,t)
% x = pwPoly3(tGrid,xGrid,fGrid,t)
%
% This function does piece-wise quadratic interpolation of a set of data,
% given the function value at the edges and midpoint of the interval of
% interest.
%
% INPUTS:
% tGrid = [1, 2*n-1] = time grid, knot idx = 1:2:end
% xGrid = [m, 2*n-1] = function at each grid point in time
% fGrid = [m, 2*n-1] = derivative at each grid point in time
% t = [1, k] = vector of query times (must be contained within tGrid)
%
% OUTPUTS:
% x = [m, k] = function value at each query time
%
% NOTES:
% If t is out of bounds, then all corresponding values for x are replaced
% with NaN
%
nGrid = length(tGrid);
if mod(nGrid-1,2)~=0 || nGrid < 3
error('The number of grid-points must be odd and at least 3');
end
% Figure out sizes
n = floor((length(tGrid)-1)/2);
m = size(xGrid,1);
k = length(t);
x = zeros(m, k);
% Figure out which segment each value of t should be on
edges = [-inf, tGrid(1:2:end), inf];
[~, bin] = histc(t,edges);
% Loop over each quadratic segment
for i=1:n
idx = bin==(i+1);
if sum(idx) > 0
kLow = 2*(i-1) + 1;
kMid = kLow + 1;
kUpp = kLow + 2;
h = tGrid(kUpp)-tGrid(kLow);
xLow = xGrid(:,kLow);
fLow = fGrid(:,kLow);
fMid = fGrid(:,kMid);
fUpp = fGrid(:,kUpp);
alpha = t(idx) - tGrid(kLow);
x(:,idx) = cubicInterp(h,xLow, fLow, fMid, fUpp,alpha);
end
end
% Replace any out-of-bounds queries with NaN
outOfBounds = bin==1 | bin==(n+2);
x(:,outOfBounds) = nan;
% Check for any points that are exactly on the upper grid point:
if sum(t==tGrid(end))>0
x(:,t==tGrid(end)) = xGrid(:,end);
end
end
function x = cubicInterp(h,xLow, fLow, fMid, fUpp,del)
%
% This function computes the interpolant over a single interval
%
% INPUTS:
% h = time step (tUpp-tLow)
% xLow = function value at tLow
% fLow = derivative at tLow
% fMid = derivative at tMid
% fUpp = derivative at tUpp
% del = query points on domain [0, h]
%
% OUTPUTS:
% x = [m, p] = function at query times
%
%%% Fix matrix dimensions for vectorized calculations
nx = length(xLow);
nt = length(del);
xLow = xLow*ones(1,nt);
fLow = fLow*ones(1,nt);
fMid = fMid*ones(1,nt);
fUpp = fUpp*ones(1,nt);
del = ones(nx,1)*del;
a = (2.*(fLow - 2.*fMid + fUpp))./(3.*h.^2);
b = -(3.*fLow - 4.*fMid + fUpp)./(2.*h);
c = fLow;
d = xLow;
x = d + del.*(c + del.*(b + del.*a));
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
traj_gen_QR_pointmass.m
|
.m
|
E231A_QuadcopterMPC-master/traj_gen/traj_gen_QR_pointmass.m
| 2,983 |
utf_8
|
98d5b8d09bae71769f0a9205fae541d3
|
function traj = traj_gen_QR_pointmass(obj)
% FUNCTION INPUTS:
x0 = [-10.5;-10.5;0;0;0;0];
xF = [0;0;0;0;0;0];
xU = inf(6,1);
xL = -xU;
uU = 15*ones(2,1); % at least 10 to be able to compensate gravity
uL = zeros(2,1);
N = 80;
% Generate obstacle
% LATER: FUNCTION INPUT
O = {Polyhedron('V',[-1 1; -20 1; -1 -2; -20 -2]),Polyhedron('V',[2 -1; 2 -10; 6 -1; 6 -10])};
%% Generate optimization problem
M = length(O); % number of obstacles
numConstrObs = zeros(1,M); % number of constraints to define each obstacle
for m=1:M
numConstrObs(m) = size(O{m}.H,1);
end
nx = length(xF); % number of states
nu = length(uU); % number of inputs
% Define optimization variables
x = sdpvar(nx, N+1); % states
u = sdpvar(nu, N); % control inputs
% Topt = sdpvar(1,N); % optimal timestep variable over horizon
Topt = sdpvar(1,1);
lambda = sdpvar(sum(numConstrObs),N); % dual variables corresponding to
% the constraints defining the obs.
% A = sdpvar(nx,nx);
% B = sdpvar(nx,nu);
% [A,B]==obj.discrLinearizeQuadrotor(Topt,...
% zeros(obj.nDof,1),obj.mQ*obj.g*ones(obj.nAct,1)./2)
% Specify cost function and constraints
q1 = 50; % cost per time unit
q2 = 100;
R = eye(nu); % cost for control inputs
dmin = 0.3; % minimum safety distance
cost = 0;
constr = [x(:,1)==x0, x(:,N+1)==xF];
for k = 1:N
cost = cost + u(:,k)'*R*u(:,k) ...
+ q1*Topt + q2*Topt^2;
% + q1*Topt(k) + q2*Topt(k)^2;
% Currently for the dynamics, an Euler discretization is used
constr = [constr, xL<=x(:,k)<=xU, uL<=u(:,k)<=uU, ...
% x(:,k+1)==x(:,k)+Topt(k)*systemDyn(obj,x(:,k),u(:,k)), ...
% 0.01<=Topt(k)<=0.375...
x(:,k+1)==x(:,k)+Topt*systemDyn(obj,x(:,k),u(:,k)), ...
0.01<=Topt<=0.375 ...
];
% Include obstacle avoidance constraints
for m=1:M
lda = lambda(sum(numConstrObs(1:m-1))+1:sum(numConstrObs(1:m)),k);
constr = [constr, ...
(O{m}.H(:,1:2)*x(1:2,k)-O{m}.H(:,2+1))'*lda>=dmin, ...
sum((O{m}.H(:,1:2)'*lda).^2)<=1, ...
lda>=zeros(size(lda))];
end
end
% Specify solver and solve the optimization problem
options = sdpsettings('verbose', 1, 'solver', 'IPOPT');
opt = optimize(constr, cost, options);
% Assign output variables
% traj.t = cumsum(value(Topt));
traj.t = 0:value(Topt):N*value(Topt);
traj.u = value(u);
traj.x = value(x);
if opt.problem ~= 0
% infeasible
traj.t = [];
traj.x = [];
traj.u = [];
end
% Plot the resulting trajectory
figure
plot(traj.x(1,:),traj.x(2,:),'x-')
xlabel('y')
ylabel('z')
title('Generated path with obstacle avoidance')
hold on
for m=1:M
plot(O{m},'alpha',0.5)
end
% Display the amount of time the planned motion would take
disp(['Reaching the target takes ' num2str(traj.t(end)) 's.'])
end
function ddx = systemDyn(obj,x,u)
[fvec,gvec] = obj.quadVectorFields(x);
ddx = fvec + gvec*u;
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
traj_gen_QR_polyhedron.m
|
.m
|
E231A_QuadcopterMPC-master/traj_gen/traj_gen_QR_polyhedron.m
| 3,925 |
utf_8
|
6bc3e92343784f6bb380b88cb9079e27
|
function traj = traj_gen_QR_polyhedron(obj)
% FUNCTION INPUTS:
x0 = [-10.5;-10.5;0;0;0;0];
xF = [0;0;0;0;0;0];
xU = inf(6,1);
xL = -xU;
uU = 15*ones(2,1); % at least 10 to be able to compensate gravity
uL = zeros(2,1);
N = 80;
QR_width = 2*0.02;
QR_height = 0.015;
% Generate obstacle
% LATER: FUNCTION INPUT
O ={Polyhedron('V',[-2 1; -20 1; -2 -2; -20 -2])};%,...
% Polyhedron('V',[0 -3; 0 -10; 6 -3; 6 -10])};
%% Generate quadrotor shape (at "zero" position)
QR = Polyhedron('V',[-QR_width/2 0; QR_width/2 0; -QR_width/2 QR_height;...
QR_width/2 QR_height]);
%% Generate optimization problem
M = length(O); % number of obstacles
numConstrObs = zeros(1,M); % number of constraints to define each obstacle
for m=1:M
numConstrObs(m) = size(O{m}.H,1);
end
numConstrQR = size(QR.H,1);
nx = length(xF); % number of states
nu = length(uU); % number of inputs
% Define optimization variables
x = sdpvar(nx, N+1); % states
u = sdpvar(nu, N); % control inputs
% Topt = sdpvar(1,N); % optimal timestep variable over horizon
Topt = sdpvar(1,1);
% dual variables corresponding to the constraints defining the obs.
lambda = sdpvar(sum(numConstrObs),N);
% dual variables ...
mu = sdpvar(M*numConstrQR,N);
% Define 2D rotation matrix
Rot = @(angle) [cos(angle) -sin(angle); sin(angle) cos(angle)];
% A = sdpvar(nx,nx);
% B = sdpvar(nx,nu);
% [A,B]==obj.discrLinearizeQuadrotor(Topt,...
% zeros(obj.nDof,1),obj.mQ*obj.g*ones(obj.nAct,1)./2)
% Specify cost function and constraints
q1 = 50; % cost per time unit
q2 = 100;
R = eye(nu); % cost for control inputs
dmin = 0.3; % minimum safety distance
cost = 0;
constr = [x(:,1)==x0, x(:,N+1)==xF];
for k = 1:N
cost = cost + u(:,k)'*R*u(:,k) ...
+ q1*Topt + q2*Topt^2;
% + q1*Topt(k) + q2*Topt(k)^2;
% Currently for the dynamics, an Euler discretization is used
constr = [constr, xL<=x(:,k)<=xU, uL<=u(:,k)<=uU, ...
% x(:,k+1)==x(:,k)+Topt(k)*systemDyn(obj,x(:,k),u(:,k)), ...
% 0.01<=Topt(k)<=0.375...
x(:,k+1)==x(:,k)+Topt*systemDyn(obj,x(:,k),u(:,k)), ...
0.01<=Topt<=0.375...
];
% Include obstacle avoidance constraints
for m=1:M
lda_m = lambda(sum(numConstrObs(1:m-1))+1:sum(numConstrObs(1:m)),k);
mu_m = mu((m-1)*numConstrQR+1:m*numConstrQR,k);
constr = [constr, ...
-QR.H(:,2+1)'*mu_m + ...
(O{m}.H(:,1:2)*x(1:2,k)-O{m}.H(:,2+1))'*lda_m>=dmin, ...
QR.H(:,1:2)'*mu_m + Rot(x(3,k))'*O{m}.H(:,1:2)'*lda_m == 0, ...
sum((O{m}.H(:,1:2)'*lda_m).^2)<=1, ...
lda_m>=zeros(size(lda_m)), ...
mu_m>=zeros(size(mu_m))];
end
end
% Specify solver and solve the optimization problem
options = sdpsettings('verbose', 1, 'solver', 'IPOPT');
opt = optimize(constr, cost, options);
% Assign output variables
% traj.t = cumsum(value(Topt));
traj.t = 0:value(Topt):N*value(Topt);
traj.u = value(u);
traj.x = value(x);
if opt.problem ~= 0
% infeasible
traj.t = [];
traj.x = [];
traj.u = [];
end
% Plot the resulting trajectory
figure
plot(traj.x(1,:),traj.x(2,:),'x-')
xlabel('y')
ylabel('z')
title('Generated path with obstacle avoidance')
hold on
for m=1:M
plot(O{m},'alpha',0.5)
end
for k=1:N+1
plot(Polyhedron('H',[QR.H(:,1:2)*Rot(traj.x(3,k))',...
QR.H(:,2+1)+QR.H(:,1:2)*Rot(traj.x(3,k))'*traj.x(1:2,k)]),...
'color','b','alpha',0)
end
axis equal
figure
plot(traj.t,traj.x)
title('States vs. time')
legend('y_Q','z_Q','\phi_Q','yd_Q','zd_Q','\phi d_Q')
figure
plot(traj.t(1:end-1),traj.u)
title('Inputs vs. time')
legend('u_1','u_2')
% Display the amount of time the planned motion would take
disp(['Reaching the target takes ' num2str(traj.t(end)) 's.'])
end
function ddx = systemDyn(obj,x,u)
[fvec,gvec] = obj.quadVectorFields(x);
ddx = fvec + gvec*u;
end
|
github
|
nlbucki/E231A_QuadcopterMPC-master
|
animateQuadrotor.m
|
.m
|
E231A_QuadcopterMPC-master/@Quadrotor/animateQuadrotor.m
| 4,375 |
utf_8
|
419f861ed023b2edf8e60017902ac05d
|
function animateQuadrotor(obj,opts_in)
% function to animate the quadrotor
% default options
opts_default.RATE = 25 * 2;
opts_default.t = [];
opts_default.x = [];
opts_default.xd = [0;0];
opts_default.td = [];
opts_default.interp_type = 'spline';
opts_default.vid.MAKE_MOVIE = 0;
opts_default.vid.filename = 'results/vid1';
opts_default.vid.Quality = 100;
opts_default.vid.FrameRate = 24;
% initialize the animation figure and axes
figure_x_limits = [-2 2];
figure_y_limits = [-2 2];
figure_z_limits = [0 1] ;
fig1 = figure;
set(0,'Units','pixels')
scnsize = get(0,'ScreenSize');
screen_width = scnsize(3);
screen_height = scnsize(4);
% find the minimum scaling factor
figure_x_size = figure_x_limits(2) - figure_x_limits(1);
figure_y_size = figure_y_limits(2) - figure_y_limits(1);
xfactor = screen_width/figure_x_size;
yfactor = screen_height/figure_y_size;
if (xfactor < yfactor)
screen_factor = 0.5*xfactor;
else
screen_factor = 0.5*yfactor;
end
% calculate screen offsets
screen_x_offset = (screen_width - screen_factor*figure_x_size)/2;
screen_y_offset = (screen_height - screen_factor*figure_y_size)/2;
% draw figure and axes
set(fig1,'Position', [screen_x_offset screen_y_offset...
1.5*screen_factor*figure_x_size 1.5*screen_factor*figure_y_size]);
set(fig1,'MenuBar', 'none');
axes1 = axes;
set(axes1,'XLim',figure_x_limits,'YLim',figure_y_limits);
% set(axes1,'Position',[0 0 1 1]);
% set(axes1,'Color','w');
% set(axes1,'TickDir','out');
axis equal ;
% get inputs
opts = struct_overlay(opts_default,opts_in);
% extract data
RATE = opts.RATE;
t = opts.t;
x = opts.x;
td = opts.td;
xd = opts.xd;
if isrow(t)
t = t';
end
if size(x,2)>size(x,1)
x = x';
end
box on;
[t, x] = even_sample(t, x, RATE,opts.interp_type);
t = t+t(1);
xd_flag = true;
if length(xd) == 2
xd = repmat(xd',length(x),1);
else
[~, xd] = even_sample(td,xd,RATE,opts.interp_type);
end
if(opts.vid.MAKE_MOVIE)
M = moviein(length(t)) ;
vidObj = VideoWriter(strcat(opts.vid.filename,'.avi'),'Motion JPEG AVI');
vidObj.FrameRate = opts.vid.FrameRate;
vidObj.Quality = opts.vid.Quality;
open(vidObj);frameRate = vidObj.FrameRate;
% nFrame = floor(frameRate*t(end));
frameDelay = 1/frameRate;
time = 0;
end
hist = 5000 ;
for i=1:length(t)
drawQuadrotor(axes1, x(i,:)');
plot(x(max(1,i-hist):i, 1), x(max(1,i-hist):i, 2), 'k') ;
if xd_flag
l = plot(xd(max(1,i-hist):i, 1), xd(max(1,i-hist):i, 2), 'g','linewidth',1);
l.Color(4) = 0.4;
end
% plot3(x(max(1,i-hist):i, 1)-L*x(max(1,i-hist):i,7), x(max(1,i-hist):i, 2)-L*x(max(1,i-hist):i,8), x(max(1,i-hist):i, 3)-L*x(max(1,i-hist):i,9), 'r') ;
s = sprintf('Running\n t = %1.2fs \n 1/%d realtime speed',t(i), RATE/25);
text(x(i,1)-1.5,x(i,2)+1.5,s,'FontAngle','italic','FontWeight','bold');
drawnow;
figure_x_limits_ = figure_x_limits+x(i,1);
figure_y_limits_ = figure_y_limits+x(i,2);
set(axes1,'XLim',figure_x_limits_,'YLim',figure_y_limits_);
if opts.vid.MAKE_MOVIE
M(:,i) = getframe;
% Write data to video file
writeVideo(vidObj,getframe(gcf));
% time step system to next frame:
time = time + frameDelay;
end
end
end
function drawQuadrotor(parent,x)
tem = get(parent,'Children');
delete(tem);
y = x(1);
z = x(2);
phi = x(3);
s.L = 0.175;
s.R = 0.05;
base = [[s.L; 0], [-s.L; 0], [s.L; s.R], [-s.L; s.R]];
R = [cos(phi), -sin(phi);
sin(phi), cos(phi)];
points = [y;z] + R*base;
s.qhandle1 = line([points(1,1), points(1,2)], [points(2,1), points(2,2)]); hold on ;
s.qhandle2 = line([points(1,1), points(1,3)], [points(2,1), points(2,3)]);
s.qhandle3 = line([points(1,2), points(1,4)], [points(2,2), points(2,4)]);
set(s.qhandle1,'Color','r', 'LineWidth',2);
set(s.qhandle2,'Color','b', 'LineWidth',2);
set(s.qhandle3,'Color','b', 'LineWidth',2);
grid on;
xlabel('Y');
ylabel('Z');
end
|
github
|
alexisgoar/MA_RADAR-master
|
animate.m
|
.m
|
MA_RADAR-master/MDoppler1.1.3/Functions/target/animate.m
| 617 |
utf_8
|
f74360fa02b1140e4652aa675a785d48
|
% function to plot the target per time
function animate(obj,tstep,tstart,tend,rx,tx)
if nargin == 4
obj.move(tstart);
time = tstart;
while time < tend
plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
end
% Animate target with antennas
elseif nargin == 6
obj.move(tstart);
time = tstart;
while time < tend
hold on;
plot(rx);
plot(tx);
h1 = plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
if time < tend
delete(h1);
end
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_setup.m
|
.m
|
MA_RADAR-master/MDoppler1.1.3/Functions/signal/plot_setup.m
| 376 |
utf_8
|
02bb14f2bcd9385a6f19ee7a9865f454
|
% Plots the whole setup given a signal class
% the obj variable must of type signal (class)
function plot_setup(obj,ax)
if nargin == 1
plot(obj.tx);
plot(obj.rx);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i));
end
else
plot(obj.tx,ax);
plot(obj.rx,ax);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i),ax);
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
animate.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/target/animate.m
| 617 |
utf_8
|
f74360fa02b1140e4652aa675a785d48
|
% function to plot the target per time
function animate(obj,tstep,tstart,tend,rx,tx)
if nargin == 4
obj.move(tstart);
time = tstart;
while time < tend
plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
end
% Animate target with antennas
elseif nargin == 6
obj.move(tstart);
time = tstart;
while time < tend
hold on;
plot(rx);
plot(tx);
h1 = plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
if time < tend
delete(h1);
end
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_ranges2.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_ranges2.m
| 637 |
utf_8
|
cdbb94a28b4b47ca4a4b659282732880
|
%plots the estimated range for all possible paths
% for a single target
function plot_estimated_ranges2(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
plot_estimated_range2(obj,i,j,NPulses);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
obj.tx.resetTime();
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_rangerate4.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_rangerate4.m
| 1,530 |
utf_8
|
c613c13cd1546484cb4c76f4a1386129
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_rangerate4(obj)
NPulses = 100;
NObj = size(obj.target,2);
NSamples = 54*2;
sampleRate = NSamples/obj.tx.tchirp;
sampleFreq = 1/sampleRate;
Nout = 2;
signal_freq = zeros(NPulses,NSamples);
signal_rr = zeros(NPulses,1);
figure;
hold on;
time2 = 0;
for chirp = 1:NPulses
signal = zeros(NSamples,1);
timeStamp = zeros(NSamples,1);
for k = 1:NSamples
for j=1:NObj
signal(k)=signal(k)+rxSignal3(obj,obj.tx.time,time2,1,1,j)...
+rxSignal3(obj,obj.tx.time,time2,2,1,j);
end
timeStamp(k) = obj.tx.time;
time2 = time2+ obj.tx.samplingRate;
obj.tx.nextStep_sampling();
end
obj.tx.resetTime();
out = fft(signal);
signal_freq(chirp,:) = out;
signal_rr(chirp) = signal(Nout);
plot(real(signal));
end
freq_rr = -(NPulses-1)/(2*NPulses*obj.tx.tchirp):1/(obj.tx.tchirp*NPulses):(NPulses-1)/(2*NPulses*obj.tx.tchirp);
freq_rr = freq_rr;
%freq_rr = 0:1/(obj.tx.tchirp*NPulses):(NPulses-1)/(NPulses*obj.tx.tchirp);
v = freq_rr*obj.tx.lambda/4;
signal_freq_all = fftshift(fft(signal_freq,[],1),1);
freq =0:1/(obj.tx.samplingRate*NSamples):(NSamples-1)/(NSamples*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
s = signal_freq;
[R_plot,v_plot] =meshgrid(R,v);
figure;
set(0,'DefaultFigureWindowStyle','docked');
h = surf(R_plot,v_plot,abs(signal_freq_all));
view(0, 90);
set(h,'edgecolor','none');
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_setup.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_setup.m
| 229 |
utf_8
|
63b8be9863ae28ac20b890400848e6b9
|
% Plots the whole setup given a signal class
% the obj variable must of type signal (class)
function plot_setup(obj)
plot(obj.tx);
plot(obj.rx);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i));
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_rxSignal.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_rxSignal.m
| 452 |
utf_8
|
dc6475688db4a256bfd803e0f1e3fa84
|
%Plots the frequency of the received signal after considering all delays
%for one transmitter, one receiver and one target
function s = plot_rxSignal(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
freq(i,j) = rxSignal(obj,obj.tx.time,txi,rxi,j);
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep();
i = i+1;
end
for j = 1:size(obj.target,2)
h = plot(timeStamp,freq(:,j));
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_rxSignals.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_rxSignals.m
| 819 |
utf_8
|
d05ac00f37d2221db46426069088e7ef
|
%Plots the frequency of the received signal after considering all delays
%for one transmitter, one receiver and one target
function s = plot_rxSignals(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
hold on;
plot_rxSignal(obj,i,j,NPulses);
obj.tx.resetTime();
set(gca,'ylim',[obj.tx.frequency-obj.tx.k*obj.tx.tchirp,...
obj.tx.frequency+obj.tx.k*obj.tx.tchirp]);
set(gca,'xlim',[obj.tx.t0,obj.tx.tchirp*NPulses]);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
end
end
s = 1;
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_range.m
| 567 |
utf_8
|
0a86ee0e977e8a645237ec1a33094865
|
% plots the estimated range based on the received signal after
% applying an FFT for transimeter txi and receiver rxi
% for a single target
function h = plot_estimated_range(obj,txi,rxi,targeti)
numberofChirps = 1;
samplesperChirp = obj.tx.tchirp/obj.tx.samplingRate;
time = 0:obj.tx.tchirp/samplesperChirp:obj.tx.tchirp*numberofChirps;
for i = 1:size(time,2)
s = receivedSignal(obj,time,txi,rxi,targeti);
end
N=size(time,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
sfd = fft(s);
h = plot(R,abs(sfd));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range3.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_range3.m
| 528 |
utf_8
|
902b6ff1ee462a7b5c2eaa786ad93ad2
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_range3(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal3(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
s_time = sum(s,2);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_ranges.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_ranges.m
| 606 |
utf_8
|
417473a6bd71ed69b06b59f4c81aed8b
|
%plots the estimated range for all possible paths
% for a single target
function plot_estimated_ranges(obj,targeti)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
plot_estimated_range(obj,i,j,targeti);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_rangerate3.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_rangerate3.m
| 1,990 |
utf_8
|
7623b9ef50bdfc4f65a62a76448d71e7
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_rangerate3(obj)
i = 1;
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
range_rate = [0:0.2:5];
txi = 1;
rxi = 1;
NPulses = 100;
% Get the time domain signal for all targets
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal3(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
obj.tx.resetTime();
s_time = sum(s,2);
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
% FFT to get spectrum
%s_freq = fft(s_time);
% K = [0:1:N-1];
% for ii = 1:N
% s_out = 0;
% for iii = 1:N
% s = exp(-1i*2*pi*K(ii)*(iii-1)/N);
% s_out = s_out + s_time(iii)*s;
% end
% s_freq(ii) = s_out;
%
%
% end
s_time = s_time(1:54:end);
timeStamp = timeStamp(1:54:end);
% FFT for range_rate
N=size(timeStamp,2);
sR = obj.tx.samplingRate*54;
freq =0:1/(sR*N):(N-1)/(N*sR);
K = [0:1:N-1];
for ii = 1:N
s_out = 0;
for iii = 1:N
s = exp(-1i*2*pi*K(ii)*(iii-1)/N);
s_out = s_out + s_time(iii)*s;
end
s_freq2(ii) = s_out;
end
for range_ratei = 1:size(range_rate,2)
arg = 4*pi*obj.tx.frequency;
N2 = max(size(s_time));
s_out = 0; size(s_time,2);
for int = 1:N2
s = exp(-1i*arg*(int-1)/N2);
s_out = s_out + s_time(int)*s;
end
s_freq_rrate(range_ratei) = s_out;
end
%size(s_freq_rrate);
%profile = mtimes(s_freq,s_freq_rrate);
[Rrate_plot,R_plot] = meshgrid(range_rate,R);
figure;
set(0,'DefaultFigureWindowStyle','docked');
%hold on;
%h = surf(R_plot,Rrate_plot,abs(profile));
%set(h,'edgecolor','none');
%figure;
%plot(range_rate,abs(s_freq_rrate)) ;
%figure;
plot(freq,abs(s_freq2));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range4.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_range4.m
| 856 |
utf_8
|
a5ccee64f14a4313e9fb9f2473713737
|
%Used optimized received signal
function s = plot_estimated_range4(obj)
[signal,timeStamp] = obj.rxSignal4();
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for txi = 1:txn
for rxi = 1:rxn
h = subplot(rxn,txn,txi+(rxi-1)*txn);
s_time = reshape(signal(txi,rxi,:),[],1);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
Txnum = ['Tx ',num2str(txi)];
Rxnum = [' Rx ',num2str(rxi)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
obj.tx.resetTime();
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range2.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/signal/plot_estimated_range2.m
| 528 |
utf_8
|
ad8d65f05db9e320d854467e40bc28a4
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_range2(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal2(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
s_time = sum(s,2);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_txSignals.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/txarray/plot_txSignals.m
| 539 |
utf_8
|
ab7ea48f68445ea24241a87408e1cdf1
|
% Function used by class txarray to plot a sent signal
% Plots all transmitters
%obj must me a txarray class
function h = plot_txSignals(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
txn = obj.numberofElements;
for i = 1:txn
h = subplot(txn,1,i);
plot_txSignal(obj,i,NPulses);
Txnum = ['Tx ',num2str(i)];
title([Txnum]);
set(gca,'ylim',[obj.frequency-obj.k*obj.tchirp,...
obj.frequency+obj.k*obj.tchirp]);
set(gca,'xlim',[obj.t0,obj.tchirp*NPulses]);
obj.resetTime();
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_txSignal.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.1/Functions/txarray/plot_txSignal.m
| 324 |
utf_8
|
3a69862f61a7f0651a3fac09348bf0ba
|
% Function used by class txarray to plot a sent signal
% For one receiver only
%obj must me a txarray class
function h = plot_txSignal(obj,txi,NPulses)
i = 1;
while obj.chirpi < NPulses
freq(i) = txSignal(obj,txi,obj.time);
timeStamp(i) = obj.time;
obj.nextStep();
i = i+1;
end
h = plot(timeStamp,freq);
end
|
github
|
alexisgoar/MA_RADAR-master
|
animate.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.3/Functions/target/animate.m
| 617 |
utf_8
|
f74360fa02b1140e4652aa675a785d48
|
% function to plot the target per time
function animate(obj,tstep,tstart,tend,rx,tx)
if nargin == 4
obj.move(tstart);
time = tstart;
while time < tend
plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
end
% Animate target with antennas
elseif nargin == 6
obj.move(tstart);
time = tstart;
while time < tend
hold on;
plot(rx);
plot(tx);
h1 = plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
if time < tend
delete(h1);
end
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_setup.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.3/Functions/signal/plot_setup.m
| 376 |
utf_8
|
02bb14f2bcd9385a6f19ee7a9865f454
|
% Plots the whole setup given a signal class
% the obj variable must of type signal (class)
function plot_setup(obj,ax)
if nargin == 1
plot(obj.tx);
plot(obj.rx);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i));
end
else
plot(obj.tx,ax);
plot(obj.rx,ax);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i),ax);
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
animate.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.2/Functions/target/animate.m
| 617 |
utf_8
|
f74360fa02b1140e4652aa675a785d48
|
% function to plot the target per time
function animate(obj,tstep,tstart,tend,rx,tx)
if nargin == 4
obj.move(tstart);
time = tstart;
while time < tend
plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
end
% Animate target with antennas
elseif nargin == 6
obj.move(tstart);
time = tstart;
while time < tend
hold on;
plot(rx);
plot(tx);
h1 = plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
if time < tend
delete(h1);
end
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_setup.m
|
.m
|
MA_RADAR-master/MA_RADAR/MDoppler1.1.2/Functions/signal/plot_setup.m
| 376 |
utf_8
|
02bb14f2bcd9385a6f19ee7a9865f454
|
% Plots the whole setup given a signal class
% the obj variable must of type signal (class)
function plot_setup(obj,ax)
if nargin == 1
plot(obj.tx);
plot(obj.rx);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i));
end
else
plot(obj.tx,ax);
plot(obj.rx,ax);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i),ax);
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
animate.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/target/animate.m
| 617 |
utf_8
|
f74360fa02b1140e4652aa675a785d48
|
% function to plot the target per time
function animate(obj,tstep,tstart,tend,rx,tx)
if nargin == 4
obj.move(tstart);
time = tstart;
while time < tend
plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
end
% Animate target with antennas
elseif nargin == 6
obj.move(tstart);
time = tstart;
while time < tend
hold on;
plot(rx);
plot(tx);
h1 = plot(obj);
pause(0.05);
time = time + tstep;
obj.move(tstep);
if time < tend
delete(h1);
end
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_ranges2.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_ranges2.m
| 637 |
utf_8
|
cdbb94a28b4b47ca4a4b659282732880
|
%plots the estimated range for all possible paths
% for a single target
function plot_estimated_ranges2(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
plot_estimated_range2(obj,i,j,NPulses);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
obj.tx.resetTime();
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_rangerate4.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_rangerate4.m
| 1,599 |
utf_8
|
9057be9c1bb2fa5abf70d1ce5ccb0226
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_rangerate4(obj)
NPulses = 100;
NObj = size(obj.target,2);
NSamples = 54;
sampleRate = NSamples/obj.tx.tchirp;
sampleFreq = 1/sampleRate;
Nout = 2;
signal_freq = zeros(NPulses,NSamples);
signal_rr = zeros(NPulses,1);
for chirp = 1:NPulses
signal = zeros(NSamples,1);
timeStamp = zeros(NSamples,1);
for k = 1:NSamples
for j=1:NObj
signal(k)=signal(k)+rxSignal3(obj,obj.tx.time,1,1,j);
end
timeStamp(k) = obj.tx.time;
obj.tx.nextStep_sampling();
end
out = fft(signal);
signal_freq(chirp,:) = out;
signal_rr(chirp) = signal(Nout);
end
freq_rr = -(NPulses-1)/(2*NPulses*obj.tx.tchirp):1/(obj.tx.tchirp*NPulses):(NPulses-1)/(2*NPulses*obj.tx.tchirp);
freq_rr = freq_rr;
%freq_rr = 0:1/(obj.tx.tchirp*NPulses):(NPulses-1)/(NPulses*obj.tx.tchirp);
v = freq_rr*obj.tx.lambda/4;
v = v(1:2:end);
size(v);
freq_rr = freq_rr(1:2:end);
figure;
hold on;
for chirp = 1:NSamples
signal_to_transform = signal_freq(1:2:end,chirp);
% signal_freq_all(:,chirp) = fftshift(signal_transformed);
signal_freq_all(:,chirp) = fftshift(fft((signal_to_transform)));
end
signal_freq_rr = fft(signal_rr(1:2:end));
freq =0:1/(obj.tx.samplingRate*NSamples):(NSamples-1)/(NSamples*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
R
[R_plot,v_plot] =meshgrid(R,v);
figure;
set(0,'DefaultFigureWindowStyle','docked');
h = surf(R_plot,v_plot,abs(signal_freq_all));
view(0, 90);
set(h,'edgecolor','none');
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_setup.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_setup.m
| 288 |
utf_8
|
3fa316db0ca5a0f2da80b975d223b62f
|
% Plots the whole setup given a signal class
% the obj variable must of type signal (class)
function plot_setup(obj)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
plot(obj.tx);
plot(obj.rx);
size(obj.target,2);
for i = 1:size(obj.target,2)
plot(obj.target(i));
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_rxSignal.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_rxSignal.m
| 452 |
utf_8
|
dc6475688db4a256bfd803e0f1e3fa84
|
%Plots the frequency of the received signal after considering all delays
%for one transmitter, one receiver and one target
function s = plot_rxSignal(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
freq(i,j) = rxSignal(obj,obj.tx.time,txi,rxi,j);
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep();
i = i+1;
end
for j = 1:size(obj.target,2)
h = plot(timeStamp,freq(:,j));
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_rxSignals.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_rxSignals.m
| 819 |
utf_8
|
d05ac00f37d2221db46426069088e7ef
|
%Plots the frequency of the received signal after considering all delays
%for one transmitter, one receiver and one target
function s = plot_rxSignals(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
hold on;
plot_rxSignal(obj,i,j,NPulses);
obj.tx.resetTime();
set(gca,'ylim',[obj.tx.frequency-obj.tx.k*obj.tx.tchirp,...
obj.tx.frequency+obj.tx.k*obj.tx.tchirp]);
set(gca,'xlim',[obj.tx.t0,obj.tx.tchirp*NPulses]);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
end
end
s = 1;
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_range.m
| 567 |
utf_8
|
0a86ee0e977e8a645237ec1a33094865
|
% plots the estimated range based on the received signal after
% applying an FFT for transimeter txi and receiver rxi
% for a single target
function h = plot_estimated_range(obj,txi,rxi,targeti)
numberofChirps = 1;
samplesperChirp = obj.tx.tchirp/obj.tx.samplingRate;
time = 0:obj.tx.tchirp/samplesperChirp:obj.tx.tchirp*numberofChirps;
for i = 1:size(time,2)
s = receivedSignal(obj,time,txi,rxi,targeti);
end
N=size(time,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
sfd = fft(s);
h = plot(R,abs(sfd));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range3.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_range3.m
| 528 |
utf_8
|
902b6ff1ee462a7b5c2eaa786ad93ad2
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_range3(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal3(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
s_time = sum(s,2);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_ranges.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_ranges.m
| 606 |
utf_8
|
417473a6bd71ed69b06b59f4c81aed8b
|
%plots the estimated range for all possible paths
% for a single target
function plot_estimated_ranges(obj,targeti)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for i = 1:txn
for j = 1:rxn
h = subplot(rxn,txn,i+(j-1)*txn);
plot_estimated_range(obj,i,j,targeti);
Txnum = ['Tx ',num2str(i)];
Rxnum = [' Rx ',num2str(j)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_rangerate3.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_rangerate3.m
| 1,990 |
utf_8
|
7623b9ef50bdfc4f65a62a76448d71e7
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_rangerate3(obj)
i = 1;
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
range_rate = [0:0.2:5];
txi = 1;
rxi = 1;
NPulses = 100;
% Get the time domain signal for all targets
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal3(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
obj.tx.resetTime();
s_time = sum(s,2);
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
% FFT to get spectrum
%s_freq = fft(s_time);
% K = [0:1:N-1];
% for ii = 1:N
% s_out = 0;
% for iii = 1:N
% s = exp(-1i*2*pi*K(ii)*(iii-1)/N);
% s_out = s_out + s_time(iii)*s;
% end
% s_freq(ii) = s_out;
%
%
% end
s_time = s_time(1:54:end);
timeStamp = timeStamp(1:54:end);
% FFT for range_rate
N=size(timeStamp,2);
sR = obj.tx.samplingRate*54;
freq =0:1/(sR*N):(N-1)/(N*sR);
K = [0:1:N-1];
for ii = 1:N
s_out = 0;
for iii = 1:N
s = exp(-1i*2*pi*K(ii)*(iii-1)/N);
s_out = s_out + s_time(iii)*s;
end
s_freq2(ii) = s_out;
end
for range_ratei = 1:size(range_rate,2)
arg = 4*pi*obj.tx.frequency;
N2 = max(size(s_time));
s_out = 0; size(s_time,2);
for int = 1:N2
s = exp(-1i*arg*(int-1)/N2);
s_out = s_out + s_time(int)*s;
end
s_freq_rrate(range_ratei) = s_out;
end
%size(s_freq_rrate);
%profile = mtimes(s_freq,s_freq_rrate);
[Rrate_plot,R_plot] = meshgrid(range_rate,R);
figure;
set(0,'DefaultFigureWindowStyle','docked');
%hold on;
%h = surf(R_plot,Rrate_plot,abs(profile));
%set(h,'edgecolor','none');
%figure;
%plot(range_rate,abs(s_freq_rrate)) ;
%figure;
plot(freq,abs(s_freq2));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range4.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_range4.m
| 856 |
utf_8
|
a5ccee64f14a4313e9fb9f2473713737
|
%Used optimized received signal
function s = plot_estimated_range4(obj)
[signal,timeStamp] = obj.rxSignal4();
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
% subplot(obj.tx.numberofElements*obj.rx.numberofElements,1,1);
txn = obj.tx.numberofElements;
rxn = obj.rx.numberofElements;
for txi = 1:txn
for rxi = 1:rxn
h = subplot(rxn,txn,txi+(rxi-1)*txn);
s_time = reshape(signal(txi,rxi,:),[],1);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
Txnum = ['Tx ',num2str(txi)];
Rxnum = [' Rx ',num2str(rxi)];
title([Txnum,Rxnum]);
set(gca,'ytick',[]);
set(gca,'yticklabel',[]);
obj.tx.resetTime();
end
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_estimated_range2.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/signal/plot_estimated_range2.m
| 528 |
utf_8
|
ad8d65f05db9e320d854467e40bc28a4
|
%Plots the received signal in time domain for a single path
function s = plot_estimated_range2(obj,txi,rxi,NPulses)
i = 1;
while obj.tx.chirpi < NPulses
for j = 1:size(obj.target,2)
s(i,j) =(rxSignal2(obj,obj.tx.time,txi,rxi,j));
end
timeStamp(i) = obj.tx.time;
obj.tx.nextStep_sampling();
i = i+1;
end
N=size(timeStamp,2);
freq =0:1/(obj.tx.samplingRate*N):(N-1)/(N*obj.tx.samplingRate);
R = obj.tx.c*freq/(obj.tx.k*2);
s_time = sum(s,2);
s_freq = fft(s_time);
h = plot(R,abs(s_freq));
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_txSignals.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/txarray/plot_txSignals.m
| 539 |
utf_8
|
ab7ea48f68445ea24241a87408e1cdf1
|
% Function used by class txarray to plot a sent signal
% Plots all transmitters
%obj must me a txarray class
function h = plot_txSignals(obj,NPulses)
figure;
set(0,'DefaultFigureWindowStyle','docked');
hold on;
txn = obj.numberofElements;
for i = 1:txn
h = subplot(txn,1,i);
plot_txSignal(obj,i,NPulses);
Txnum = ['Tx ',num2str(i)];
title([Txnum]);
set(gca,'ylim',[obj.frequency-obj.k*obj.tchirp,...
obj.frequency+obj.k*obj.tchirp]);
set(gca,'xlim',[obj.t0,obj.tchirp*NPulses]);
obj.resetTime();
end
end
|
github
|
alexisgoar/MA_RADAR-master
|
plot_txSignal.m
|
.m
|
MA_RADAR-master/MDoppler/Functions/txarray/plot_txSignal.m
| 324 |
utf_8
|
3a69862f61a7f0651a3fac09348bf0ba
|
% Function used by class txarray to plot a sent signal
% For one receiver only
%obj must me a txarray class
function h = plot_txSignal(obj,txi,NPulses)
i = 1;
while obj.chirpi < NPulses
freq(i) = txSignal(obj,txi,obj.time);
timeStamp(i) = obj.time;
obj.nextStep();
i = i+1;
end
h = plot(timeStamp,freq);
end
|
github
|
daniellerch/aletheia-master
|
GFR.m
|
.m
|
aletheia-master/aletheia-octave/octave/GFR.m
| 6,318 |
utf_8
|
5907e54c33bb3ff14818fcfa87056123
|
function F=GFR(IMAGE,NR,QF,channel)
% -------------------------------------------------------------------------
% Copyright (c) 2015 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | July 2015
% [email protected]
%
% http://dde.binghamton.edu/download/feature_extractors
% -------------------------------------------------------------------------
% This function extracts Gabor features for steganalysis of JPEG images
% proposed in [1]. Parameters are exactly set as they are described in the
% paper. Total dimensionality of the features with 32 rotations: 17000.
% Note: Phil Sallee's Matlab JPEG toolbox(function jpeg_read)is needed for
% running this function.
% -------------------------------------------------------------------------
% Input: IMAGE .. path to the JPEG image
% QF ..... JPEG quality factor (can be either 75 or 95)
% NR .... number of rotations for Gabor kernel
% Output: F ...... extracted Gabor features
% -------------------------------------------------------------------------
% [1] X. Song, F. Liu, C. Yang, X. Luo and Y. Zhang "Steganalysis of
% Adaptive JPEG Steganography Using 2D Gabor Filters", Proceedings of
% the 3rd ACM Workshop on Information Hiding and Multimedia Security,
% Pages 15-23, Portland, OR, June 2015.
% -------------------------------------------------------------------------
I_STRUCT = jpeg_read(IMAGE);
% number of histogram bins
T = 4;
% quantization steps
if QF==75
q = [2 4 6 8];
elseif QF==85
q = [1.5 2 4 6];
elseif QF==95
q = [0.5 1 1.5 2];
end
Rotations = (0:NR-1)*pi/NR;
sr=numel(Rotations);
% Standard deviations
Sigma = [0.5 0.75 1 1.25];
ss=numel(Sigma);
PhaseShift = [0 pi/2];
sp=numel(PhaseShift);
AspectRatio = 0.5;
% Decompress to spatial domain
% fun = @(x)x.data .*I_STRUCT.quant_tables{1};
if channel>1
fun = @(x)x .*I_STRUCT.quant_tables{2};
else
fun = @(x)x .*I_STRUCT.quant_tables{1};
end
I_spatial = blockproc(I_STRUCT.coef_arrays{channel},[8 8],fun);
% fun=@(x)idct2(x.data);
fun=@(x)idct2(x);
I_spatial = blockproc(I_spatial,[8 8],fun);
% Compute DCTR locations to be merged
mergedCoordinates = cell(25, 1);
for i=1:5
for j=1:5
coordinates = [i,j; i,10-j; 10-i,j; 10-i,10-j];
coordinates = coordinates(all(coordinates<9, 2), :);
mergedCoordinates{(i-1)*5 + j} = unique(coordinates, 'rows');
end
end
% Load Gabor Kernels
Kernel = cell(ss,sr,sp);
for S = Sigma
for R = Rotations
for P=PhaseShift
Kernel{S==Sigma,R==Rotations,P==PhaseShift} = gaborkernel(S, R, P, AspectRatio);
end
end
end
% Compute features
modeFeaDim = numel(mergedCoordinates)*(T+1);
DimF=sp*ss*sr;
DimS=sp*ss*(sr/2+1);
FF = zeros(1, DimF*modeFeaDim, 'single');
F = zeros(1, DimS*modeFeaDim, 'single');
for mode_P=1:sp
for mode_S = 1:ss
for mode_R = 1:sr
modeIndex = (mode_P-1)*(sr*ss) + (mode_S-1)*sr+ mode_R;
R = conv2(I_spatial, Kernel{mode_S,mode_R,mode_P}, 'valid');
R = abs(round(R / q(mode_S)));
R(R > T) = T;
% feature extraction and merging
for merged_index=1:numel(mergedCoordinates)
f_merged = zeros(1, T+1, 'single');
for coord_index = 1:size(mergedCoordinates{merged_index}, 1);
r_shift = mergedCoordinates{merged_index}(coord_index, 1);
c_shift = mergedCoordinates{merged_index}(coord_index, 2);
R_sub = R(r_shift:8:end, c_shift:8:end);
f_merged = f_merged + hist(R_sub(:), 0:T);
end
F_index_from = (modeIndex-1)*modeFeaDim+(merged_index-1)*(T+1)+1;
F_index_to = (modeIndex-1)*modeFeaDim+(merged_index-1)*(T+1)+T+1;
FF(F_index_from:F_index_to) = f_merged / sum(f_merged);
end
end
% merging of symmetrical directions
MIndex=1:sr/2-1;
MS=size(MIndex,2)+2;
SI = (modeIndex-sr)*modeFeaDim;
Fout=FF(SI+1: SI + MS* modeFeaDim );
F_M=FF(SI+1: SI + sr* modeFeaDim );
for i=MIndex
Fout(i*modeFeaDim+1:i*modeFeaDim+modeFeaDim)= ( F_M(i*modeFeaDim+1:i*modeFeaDim+modeFeaDim)+ F_M( (sr-i)*modeFeaDim+1: (sr-i)*modeFeaDim+modeFeaDim ) )/2; %%% Needs Modification
end
ind = (mode_P-1)*ss + mode_S;
F((ind-1)*MS*modeFeaDim+1 :(ind-1)*MS*modeFeaDim + MS*modeFeaDim )=Fout;
end
end
function kernel = gaborkernel(sigma, theta, phi, gamma)
lambda = sigma / 0.56;
gamma2 = gamma^2;
s = 1 / (2*sigma^2);
f = 2*pi/lambda;
% sampling points for Gabor function
[x,y]=meshgrid([-7/2:-1/2,1/2:7/2],[-7/2:-1/2,1/2:7/2]);
y = -y;
xp = x * cos(theta) + y * sin(theta);
yp = -x * sin(theta) + y * cos(theta);
kernel = exp(-s*(xp.*xp + gamma2*(yp.*yp))) .* cos(f*xp + phi);
% normalization
kernel = kernel- sum(kernel(:))/sum(abs(kernel(:)))*abs(kernel);
|
github
|
daniellerch/aletheia-master
|
HUGO.m
|
.m
|
aletheia-master/aletheia-octave/octave/HUGO.m
| 7,480 |
utf_8
|
f1d2eb26eef610cf221886e0ceff7633
|
function [stego, distortion] = HUGO(cover, payload)
params.gamma = 1;
params.sigma = 1;
cover = double(imread(cover));
wetCost = 10^8;
responseP1 = [0; 0; -1; +1; 0; 0];
% create mirror padded cover image
padSize = 3;
coverPadded = padarray(cover, [padSize padSize], 'symmetric');
% create residuals
C_Rez_H = coverPadded(:, 1:end-1) - coverPadded(:, 2:end);
C_Rez_V = coverPadded(1:end-1, :) - coverPadded(2:end, :);
C_Rez_Diag = coverPadded(1:end-1, 1:end-1) - coverPadded(2:end, 2:end);
C_Rez_MDiag = coverPadded(1:end-1, 2:end) - coverPadded(2:end, 1:end-1);
stego = cover; % initialize stego image
stegoPadded = coverPadded;
% create residuals
S_Rez_H = stegoPadded(:, 1:end-1) - stegoPadded(:, 2:end);
S_Rez_V = stegoPadded(1:end-1, :) - stegoPadded(2:end, :);
S_Rez_Diag = stegoPadded(1:end-1, 1:end-1) - stegoPadded(2:end, 2:end);
S_Rez_MDiag = stegoPadded(1:end-1, 2:end) - stegoPadded(2:end, 1:end-1);
rhoM1 = zeros(size(cover)); % declare cost of -1 change
rhoP1 = zeros(size(cover)); % declare cost of +1 change
%% Iterate over elements in the sublattice
for row=1:size(cover, 1)
for col=1:size(cover, 2)
D_P1 = 0;
D_M1 = 0;
% Horizontal
cover_sub = C_Rez_H(row+3, col:col+5)';
stego_sub = S_Rez_H(row+3, col:col+5)';
stego_sub_P1 = stego_sub + responseP1;
stego_sub_M1 = stego_sub - responseP1;
D_M1 = D_M1 + GetLocalDistortion(cover_sub, stego_sub_M1, params);
D_P1 = D_P1 + GetLocalDistortion(cover_sub, stego_sub_P1, params);
% Vertical
cover_sub = C_Rez_V(row:row+5, col+3);
stego_sub = S_Rez_V(row:row+5, col+3);
stego_sub_P1 = stego_sub + responseP1;
stego_sub_M1 = stego_sub - responseP1;
D_M1 = D_M1 + GetLocalDistortion(cover_sub, stego_sub_M1, params);
D_P1 = D_P1 + GetLocalDistortion(cover_sub, stego_sub_P1, params);
% Diagonal
cover_sub = [C_Rez_Diag(row, col); C_Rez_Diag(row+1, col+1); C_Rez_Diag(row+2, col+2); C_Rez_Diag(row+3, col+3); C_Rez_Diag(row+4, col+4); C_Rez_Diag(row+5, col+5)];
stego_sub = [S_Rez_Diag(row, col); S_Rez_Diag(row+1, col+1); S_Rez_Diag(row+2, col+2); S_Rez_Diag(row+3, col+3); S_Rez_Diag(row+4, col+4); S_Rez_Diag(row+5, col+5)];
stego_sub_P1 = stego_sub + responseP1;
stego_sub_M1 = stego_sub - responseP1;
D_M1 = D_M1 + GetLocalDistortion(cover_sub, stego_sub_M1, params);
D_P1 = D_P1 + GetLocalDistortion(cover_sub, stego_sub_P1, params);
% Minor Diagonal
cover_sub = [C_Rez_MDiag(row, col+5); C_Rez_MDiag(row+1, col+4); C_Rez_MDiag(row+2, col+3); C_Rez_MDiag(row+3, col+2); C_Rez_MDiag(row+4, col+1); C_Rez_MDiag(row+5, col)];
stego_sub = [S_Rez_MDiag(row, col+5); S_Rez_MDiag(row+1, col+4); S_Rez_MDiag(row+2, col+3); S_Rez_MDiag(row+3, col+2); S_Rez_MDiag(row+4, col+1); S_Rez_MDiag(row+5, col)];
stego_sub_P1 = stego_sub + responseP1;
stego_sub_M1 = stego_sub - responseP1;
D_M1 = D_M1 + GetLocalDistortion(cover_sub, stego_sub_M1, params);
D_P1 = D_P1 + GetLocalDistortion(cover_sub, stego_sub_P1, params);
rhoM1(row, col) = D_M1;
rhoP1(row, col) = D_P1;
end
end
% truncation of the costs
rhoM1(rhoM1>wetCost) = wetCost;
rhoP1(rhoP1>wetCost) = wetCost;
rhoP1(cover == 255) = wetCost;
rhoM1(cover == 0) = wetCost;
%% Embedding
% embedding simulator - params.qarity \in {2,3}
stego = EmbeddingSimulator(cover, rhoP1, rhoM1, round(numel(cover)*payload), false);
% compute distortion
distM1 = rhoM1(stego-cover==-1);
distP1 = rhoP1(stego-cover==1);
distortion = sum(distM1) + sum(distP1);
end
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
function [y] = EmbeddingSimulator(x, rhoP1, rhoM1, m, fixEmbeddingChanges)
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
if fixEmbeddingChanges == 1
%RandStream.setGlobalStream(RandStream('mt19937ar','seed',139187));
rand('state', 139187);
else
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',sum(100*clock)));
rand('state', sum(100*clock));
end
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 100)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 100 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<100)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
function D = GetLocalDistortion(C_resVect, S_resVect, params)
D = 0;
% C_resVect and S_resVect must have size of 6x1
D = D + GetLocalPotential(C_resVect(1:3), S_resVect(1:3), params);
D = D + GetLocalPotential(C_resVect(2:4), S_resVect(2:4), params);
D = D + GetLocalPotential(C_resVect(3:5), S_resVect(3:5), params);
D = D + GetLocalPotential(C_resVect(4:6), S_resVect(4:6), params);
end
function Vc = GetLocalPotential(c_res, s_res, params)
c_w = (params.sigma + sqrt(sum(c_res.^2))).^(-params.gamma);
s_w = (params.sigma + sqrt(sum(s_res.^2))).^(-params.gamma);
Vc = (c_w + s_w);
end
|
github
|
daniellerch/aletheia-master
|
HILL_MAXSRM.m
|
.m
|
aletheia-master/aletheia-octave/octave/HILL_MAXSRM.m
| 2,109 |
utf_8
|
ea3a3722b129eca8a5940ed6b496b13c
|
function f = HILL_MAXSRM(IMAGE)
if ischar(IMAGE)
X = imread(IMAGE);
else
X = IMAGE;
end
P = f_cal_cost(X);
M = 1./P;
f = MAXSRM(X, M);
end
function cost = f_cal_cost(cover)
% Copyright (c) 2014 Shenzhen University,
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from Shenzhen University.
% -------------------------------------------------------------------------
% Author: Ming Wang
% -------------------------------------------------------------------------
% Contact: [email protected]
% [email protected]
% -------------------------------------------------------------------------
% Input: cover ... cover image%
% Output: cost ....... costs value of all pixels
% -------------------------------------------------------------------------
% [1] A New Cost Function for Spatial Image Steganography,
% B.Li, M.Wang,J.Huang and X.Li, to be presented at IEEE International Conference on Image Processing, 2014.
% -------------------------------------------------------------------------
%Get filter
HF1=[-1,2,-1;2,-4,2;-1,2,-1];
H2 = fspecial('average',[3 3]);
%% Get cost
cover=double(cover);
sizeCover=size(cover);
padsize=max(size(HF1));
coverPadded = padarray(cover, [padsize padsize], 'symmetric');% add padding
R1 = conv2(coverPadded,HF1, 'same');%mirror-padded convolution
W1 = conv2(abs(R1),H2,'same');
if mod(size(HF1, 1), 2) == 0, W1= circshift(W1, [1, 0]); end;
if mod(size(HF1, 2), 2) == 0, W1 = circshift(W1, [0, 1]); end;
W1 = W1(((size(W1, 1)-sizeCover(1))/2)+1:end-((size(W1, 1)-sizeCover(1))/2), ((size(W1, 2)-sizeCover(2))/2)+1:end-((size(W1, 2)-sizeCover(2))/2));
rho=1./(W1+10^(-10));
HW = fspecial('average',[15 15]);
cost = imfilter(rho, HW ,'symmetric','same');
end
|
github
|
daniellerch/aletheia-master
|
SRM.m
|
.m
|
aletheia-master/aletheia-octave/octave/SRM.m
| 55,472 |
utf_8
|
2dd9ded5028c0dd58acc1dbafdacbcf0
|
function f = SRM(IMAGE, channel)
% -------------------------------------------------------------------------
% Copyright (c) 2011 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | October 2011
% http://dde.binghamton.edu/download/feature_extractors
% -------------------------------------------------------------------------
% Extracts all 106 submodels presented in [1] as part of a rich model for
% steganalysis of digital images. All features are calculated in the
% spatial domain and are stored in a structured variable 'f'. For more
% deatils about the individual submodels, please see the publication [1].
% Total dimensionality of all 106 submodels is 34671.
% -------------------------------------------------------------------------
% Input: IMAGE ... path to the image (can be JPEG)
% Output: f ....... extracted SRM features in a structured format
% -------------------------------------------------------------------------
% [1] Rich Models for Steganalysis of Digital Images, J. Fridrich and J.
% Kodovsky, IEEE Transactions on Information Forensics and Security, 2011.
% Under review.
% -------------------------------------------------------------------------
X = double(imread(IMAGE));
if(size(size(I))==2)
X=I(:,:,channel)
end
f = post_processing(all1st(X,1),'f1',1); % 1st order, q=1
f = post_processing(all1st(X,2),'f1',2,f); % 1st order, q=2
for q=[1 1.5 2], f = post_processing(all2nd(X,q*2),'f2',q,f); end % 2nd order
for q=[1 1.5 2], f = post_processing(all3rd(X,q*3),'f3',q,f); end % 3rd order
for q=[1 1.5 2], f = post_processing(all3x3(X,q*4),'f3x3',q,f); end % 3x3
for q=[1 1.5 2], f = post_processing(all5x5(X,q*12),'f5x5',q,f); end % 5x5
% print submodels / offsets
% i = 0;
% e = 0;
% for [v, k] = f
% e = e + size(v)(2);
% printf('%s : %d, %d-%d\n', k, size(v)(2), i, e-1)
% i = e;
% endfor
function RESULT = post_processing(DATA,f,q,RESULT)
Ss = fieldnames(DATA);
for Sid = 1:length(Ss)
VARNAME = [f '_' Ss{Sid} '_q' strrep(num2str(q),'.','')];
eval(['RESULT.' VARNAME ' = reshape(single(DATA.' Ss{Sid} '),1,[]);' ])
end
% symmetrize
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='s', continue; end
[T,N,Q] = parse_feaname(name);
if strcmp(T,''), continue; end
% symmetrization
if strcmp(N(1:3),'min') || strcmp(N(1:3),'max')
% minmax symmetrization
OUT = ['s' T(2:end) '_minmax' N(4:end) '_' Q];
if isfield(RESULT,OUT), continue; end
eval(['Fmin = RESULT.' strrep(name,'max','min') ';']);
eval(['Fmax = RESULT.' strrep(name,'min','max') ';']);
F = symfea([Fmin Fmax]',2,4,'mnmx')'; %#ok<*NASGU>
eval(['RESULT.' OUT ' = single(F);' ]);
elseif strcmp(N(1:4),'spam')
% spam symmetrization
OUT = ['s' T(2:end) '_' N '_' Q];
if isfield(RESULT,OUT), continue; end
eval(['Fold = RESULT.' name ';']);
F = symm1(Fold',2,4)';
eval(['RESULT.' OUT ' = single(F);' ]);
end
end
% delete RESULT.f*
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='f'
RESULT = rmfield(RESULT,name);
end
end
% merge spam features
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
[T,N,Q] = parse_feaname(name);
if ~strcmp(N(1:4),'spam'), continue; end
if strcmp(T,''), continue; end
if strcmp(N(end),'v')||(strcmp(N,'spam11')&&strcmp(T,'s5x5'))
elseif strcmp(N(end),'h')
% h+v union
OUT = [T '_' N 'v_' Q ];
if isfield(RESULT,OUT), continue; end
name2 = strrep(name,'h_','v_');
eval(['Fh = RESULT.' name ';']);
eval(['Fv = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [Fh Fv];']);
RESULT = rmfield(RESULT,name);
RESULT = rmfield(RESULT,name2);
elseif strcmp(N,'spam11')
% KBKV creation
OUT = ['s35_' N '_' Q];
if isfield(RESULT,OUT), continue; end
name1 = strrep(name,'5x5','3x3');
name2 = strrep(name,'3x3','5x5');
if ~isfield(RESULT,name1), continue; end
if ~isfield(RESULT,name2), continue; end
eval(['F_KB = RESULT.' name1 ';']);
eval(['F_KV = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [F_KB F_KV];']);
RESULT = rmfield(RESULT,name1);
RESULT = rmfield(RESULT,name2);
end
end
function [T,N,Q] = parse_feaname(name)
[T,N,Q] = deal('');
P = strfind(name,'_'); if length(P)~=2, return; end
T = name(1:P(1)-1);
N = name(P(1)+1:P(2)-1);
Q = name(P(2)+1:end);
function g = all1st(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 1st-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam14h
% 1b) spam14v (orthogonal-spam)
% 1c) minmax22v
% 1d) minmax24
% 1e) minmax34v
% 1f) minmax41
% 1g) minmax34
% 1h) minmax48h
% 1i) minmax54
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All odd residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals --
% -- they should "stick out" (trcet) in the same direction as
% the 1st order ones. For example, for the 3rd order:
%
% RU = -X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1); ... etc.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
% This function calls Cooc.m and Quant.m
[M N] = size(X); [I,J,T,order] = deal(2:M-1,2:N-1,2,4);
% Variable names are self-explanatory (R = right, U = up, L = left, D = down)
[R,L,U,D] = deal(X(I,J+1)-X(I,J),X(I,J-1)-X(I,J),X(I-1,J)-X(I,J),X(I+1,J)-X(I,J));
[Rq,Lq,Uq,Dq] = deal(Quant(R,q,T),Quant(L,q,T),Quant(U,q,T),Quant(D,q,T));
[RU,LU,RD,LD] = deal(X(I-1,J+1)-X(I,J),X(I-1,J-1)-X(I,J),X(I+1,J+1)-X(I,J),X(I+1,J-1)-X(I,J));
[RUq,RDq,LUq,LDq] = deal(Quant(RU,q,T),Quant(RD,q,T),Quant(LU,q,T),Quant(LD,q,T));
% minmax22h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical.
[RLq_min,UDq_min,RLq_max,UDq_max] = deal(min(Rq,Lq),min(Uq,Dq),max(Rq,Lq),max(Uq,Dq));
g.min22h = reshape(Cooc(RLq_min,order,'hor',T) + Cooc(UDq_min,order,'ver',T),[],1);
g.max22h = reshape(Cooc(RLq_max,order,'hor',T) + Cooc(UDq_max,order,'ver',T),[],1);
% minmax34h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[Uq_min,Rq_min,Dq_min,Lq_min] = deal(min(min(Lq,Uq),Rq),min(min(Uq,Rq),Dq),min(min(Rq,Dq),Lq),min(min(Dq,Lq),Uq));
[Uq_max,Rq_max,Dq_max,Lq_max] = deal(max(max(Lq,Uq),Rq),max(max(Uq,Rq),Dq),max(max(Rq,Dq),Lq),max(max(Dq,Lq),Uq));
g.min34h = reshape(Cooc([Uq_min;Dq_min],order,'hor',T) + Cooc([Lq_min Rq_min],order,'ver',T),[],1);
g.max34h = reshape(Cooc([Uq_max;Dq_max],order,'hor',T) + Cooc([Rq_max Lq_max],order,'ver',T),[],1);
% spam14h/v -- to be symmetrized as spam, directional, hv-nonsymmetrical
g.spam14h = reshape(Cooc(Rq,order,'hor',T) + Cooc(Uq,order,'ver',T),[],1);
g.spam14v = reshape(Cooc(Rq,order,'ver',T) + Cooc(Uq,order,'hor',T),[],1);
% minmax22v -- to be symmetrized as mnmx, directional, hv-nonsymmetrical. Good with higher-order residuals! Note: 22h is bad (too much neighborhood overlap).
g.min22v = reshape(Cooc(RLq_min,order,'ver',T) + Cooc(UDq_min,order,'hor',T),[],1);
g.max22v = reshape(Cooc(RLq_max,order,'ver',T) + Cooc(UDq_max,order,'hor',T),[],1);
% minmax24 -- to be symmetrized as mnmx, directional, hv-symmetrical. Darn good, too.
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(Rq,Uq),min(Rq,Dq),min(Lq,Uq),min(Lq,Dq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(Rq,Uq),max(Rq,Dq),max(Lq,Uq),max(Lq,Dq));
g.min24 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max24 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax34v -- v works well, h does not, to be symmetrized as mnmx, directional, hv-nonsymmetrical
g.min34v = reshape(Cooc([Uq_min Dq_min],order,'ver',T) + Cooc([Rq_min;Lq_min],order,'hor',T),[],1);
g.max34v = reshape(Cooc([Uq_max Dq_max],order,'ver',T) + Cooc([Rq_max;Lq_max],order,'hor',T),[],1);
% minmax41 -- to be symmetrized as mnmx, non-directional, hv-symmetrical
[R_min,R_max] = deal(min(RLq_min,UDq_min),max(RLq_max,UDq_max));
g.min41 = reshape(Cooc(R_min,order,'hor',T) + Cooc(R_min,order,'ver',T),[],1);
g.max41 = reshape(Cooc(R_max,order,'hor',T) + Cooc(R_max,order,'ver',T),[],1);
% minmax34 -- good, to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(RUq_min,RUq),min(RDq_min,RDq),min(LUq_min,LUq),min(LDq_min,LDq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(RUq_max,RUq),max(RDq_max,RDq),max(LUq_max,LUq),max(LDq_max,LDq));
g.min34 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max34 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax48h -- h better than v, to be symmetrized as mnmx, directional, hv-nonsymmetrical. 48v is almost as good as 48h; for 3rd-order but weaker for 1st-order. Here, I am outputting both but Figure 1 in our paper lists only 48h.
[RUq_min2,RDq_min2,LDq_min2,LUq_min2] = deal(min(RUq_min,LUq),min(RDq_min,RUq),min(LDq_min,RDq),min(LUq_min,LDq));
[RUq_min3,RDq_min3,LDq_min3,LUq_min3] = deal(min(RUq_min,RDq),min(RDq_min,LDq),min(LDq_min,LUq),min(LUq_min,RUq));
g.min48h = reshape(Cooc([RUq_min2;LDq_min2;RDq_min3;LUq_min3],order,'hor',T) + Cooc([RDq_min2 LUq_min2 RUq_min3 LDq_min3],order,'ver',T),[],1);
g.min48v = reshape(Cooc([RDq_min2;LUq_min2;RUq_min3;LDq_min3],order,'hor',T) + Cooc([RUq_min2 LDq_min2 RDq_min3 LUq_min3],order,'ver',T),[],1);
[RUq_max2,RDq_max2,LDq_max2,LUq_max2] = deal(max(RUq_max,LUq),max(RDq_max,RUq),max(LDq_max,RDq),max(LUq_max,LDq));
[RUq_max3,RDq_max3,LDq_max3,LUq_max3] = deal(max(RUq_max,RDq),max(RDq_max,LDq),max(LDq_max,LUq),max(LUq_max,RUq));
g.max48h = reshape(Cooc([RUq_max2;LDq_max2;RDq_max3;LUq_max3],order,'hor',T) + Cooc([RDq_max2 LUq_max2 RUq_max3 LDq_max3],order,'ver',T),[],1);
g.max48v = reshape(Cooc([RDq_max2;LUq_max2;RUq_max3;LDq_max3],order,'hor',T) + Cooc([RUq_max2 LDq_max2 RDq_max3 LUq_max3],order,'ver',T),[],1);
% minmax54 -- to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min4,RDq_min4,LDq_min4,LUq_min4] = deal(min(RUq_min2,RDq),min(RDq_min2,LDq),min(LDq_min2,LUq),min(LUq_min2,RUq));
[RUq_min5,RDq_min5,LDq_min5,LUq_min5] = deal(min(RUq_min3,LUq),min(RDq_min3,RUq),min(LDq_min3,RDq),min(LUq_min3,LDq));
g.min54 = reshape(Cooc([RUq_min4;LDq_min4;RDq_min5;LUq_min5],order,'hor',T) + Cooc([RDq_min4 LUq_min4 RUq_min5 LDq_min5],order,'ver',T),[],1);
[RUq_max4,RDq_max4,LDq_max4,LUq_max4] = deal(max(RUq_max2,RDq),max(RDq_max2,LDq),max(LDq_max2,LUq),max(LUq_max2,RUq));
[RUq_max5,RDq_max5,LDq_max5,LUq_max5] = deal(max(RUq_max3,LUq),max(RDq_max3,RUq),max(LDq_max3,RDq),max(LUq_max3,LDq));
g.max54 = reshape(Cooc([RUq_max4;LDq_max4;RDq_max5;LUq_max5],order,'hor',T) + Cooc([RDq_max4 LUq_max4 RUq_max5 LDq_max5],order,'ver',T),[],1);
function g = all2nd(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 2nd-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam12h
% 1b) spam12v (orthogonal-spam)
% 1c) minmax21
% 1d) minmax41
% 1e) minmax24h (24v is also outputted but not listed in Figure 1)
% 1f) minmax32
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All even residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
%
% This function calls Residual.m, Cooc.m, and Quant.m
[T,order] = deal(2,4);
% 2nd-order residuals are implemented using Residual.m
[Dh,Dv,Dd,Dm] = deal(Residual(X,2,'hor'),Residual(X,2,'ver'),Residual(X,2,'diag'),Residual(X,2,'mdiag'));
[Yh,Yv,Yd,Ym] = deal(Quant(Dh,q,T),Quant(Dv,q,T),Quant(Dd,q,T),Quant(Dm,q,T));
% spam12h/v
g.spam12h = reshape(Cooc(Yh,order,'hor',T) + Cooc(Yv,order,'ver',T),[],1);
g.spam12v = reshape(Cooc(Yh,order,'ver',T) + Cooc(Yv,order,'hor',T),[],1);
% minmax21
[Dmin,Dmax] = deal(min(Yh,Yv),max(Yh,Yv));
g.min21 = reshape(Cooc(Dmin,order,'hor',T) + Cooc(Dmin,order,'ver',T),[],1);
g.max21 = reshape(Cooc(Dmax,order,'hor',T) + Cooc(Dmax,order,'ver',T),[],1);
% minmax41
[Dmin2,Dmax2] = deal(min(Dmin,min(Yd,Ym)),max(Dmax,max(Yd,Ym)));
g.min41 = reshape(Cooc(Dmin2,order,'hor',T) + Cooc(Dmin2,order,'ver',T),[],1);
g.max41 = reshape(Cooc(Dmax2,order,'hor',T) + Cooc(Dmax2,order,'ver',T),[],1);
% minmax32 -- good, directional, hv-symmetrical, to be symmetrized as mnmx
[RUq_min,RDq_min] = deal(min(Dmin,Ym),min(Dmin,Yd));
[RUq_max,RDq_max] = deal(max(Dmax,Ym),max(Dmax,Yd));
g.min32 = reshape(Cooc([RUq_min;RDq_min],order,'hor',T) + Cooc([RUq_min RDq_min],order,'ver',T),[],1);
g.max32 = reshape(Cooc([RUq_max;RDq_max],order,'hor',T) + Cooc([RUq_max RDq_max],order,'ver',T),[],1);
% minmax24h,v -- both "not bad," h slightly better, directional, hv-nonsymmetrical, to be symmetrized as mnmx
[RUq_min2,RDq_min2,RUq_min3,LUq_min3] = deal(min(Ym,Yh),min(Yd,Yh),min(Ym,Yv),min(Yd,Yv));
g.min24h = reshape(Cooc([RUq_min2;RDq_min2],order,'hor',T)+Cooc([RUq_min3 LUq_min3],order,'ver',T),[],1);
g.min24v = reshape(Cooc([RUq_min2 RDq_min2],order,'ver',T)+Cooc([RUq_min3;LUq_min3],order,'hor',T),[],1);
[RUq_max2,RDq_max2,RUq_max3,LUq_max3] = deal(max(Ym,Yh),max(Yd,Yh),max(Ym,Yv),max(Yd,Yv));
g.max24h = reshape(Cooc([RUq_max2;RDq_max2],order,'hor',T)+Cooc([RUq_max3 LUq_max3],order,'ver',T),[],1);
g.max24v = reshape(Cooc([RUq_max2 RDq_max2],order,'ver',T)+Cooc([RUq_max3;LUq_max3],order,'hor',T),[],1);
function g = all3rd(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 3rd-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam14h
% 1b) spam14v (orthogonal-spam)
% 1c) minmax22v
% 1d) minmax24
% 1e) minmax34v
% 1f) minmax41
% 1g) minmax34
% 1h) minmax48h
% 1i) minmax54
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All odd residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals --
% -- they should "stick out" (trcet) in the same direction as
% the 1st order ones. For example, for the 3rd order:
%
% RU = -X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1); ... etc.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
[M N] = size(X); [I,J,T,order] = deal(3:M-2,3:N-2,2,4);
[R,L,U,D] = deal(-X(I,J+2)+3*X(I,J+1)-3*X(I,J)+X(I,J-1),-X(I,J-2)+3*X(I,J-1)-3*X(I,J)+X(I,J+1),-X(I-2,J)+3*X(I-1,J)-3*X(I,J)+X(I+1,J),-X(I+2,J)+3*X(I+1,J)-3*X(I,J)+X(I-1,J));
[Rq,Lq,Uq,Dq] = deal(Quant(R,q,T),Quant(L,q,T),Quant(U,q,T),Quant(D,q,T));
[RU,LU,RD,LD] = deal(-X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1),-X(I-2,J-2)+3*X(I-1,J-1)-3*X(I,J)+X(I+1,J+1),-X(I+2,J+2)+3*X(I+1,J+1)-3*X(I,J)+X(I-1,J-1),-X(I+2,J-2)+3*X(I+1,J-1)-3*X(I,J)+X(I-1,J+1));
[RUq,RDq,LUq,LDq] = deal(Quant(RU,q,T),Quant(RD,q,T),Quant(LU,q,T),Quant(LD,q,T));
% minmax22h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[RLq_min,UDq_min] = deal(min(Rq,Lq),min(Uq,Dq));
[RLq_max,UDq_max] = deal(max(Rq,Lq),max(Uq,Dq));
g.min22h = reshape(Cooc(RLq_min,order,'hor',T) + Cooc(UDq_min,order,'ver',T),[],1);
g.max22h = reshape(Cooc(RLq_max,order,'hor',T) + Cooc(UDq_max,order,'ver',T),[],1);
% minmax34h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[Uq_min,Rq_min,Dq_min,Lq_min] = deal(min(RLq_min,Uq),min(UDq_min,Rq),min(RLq_min,Dq),min(UDq_min,Lq));
[Uq_max,Rq_max,Dq_max,Lq_max] = deal(max(RLq_max,Uq),max(UDq_max,Rq),max(RLq_max,Dq),max(UDq_max,Lq));
g.min34h = reshape(Cooc([Uq_min;Dq_min],order,'hor',T)+Cooc([Rq_min Lq_min],order,'ver',T),[],1);
g.max34h = reshape(Cooc([Uq_max;Dq_max],order,'hor',T)+Cooc([Rq_max Lq_max],order,'ver',T),[],1);
% spam14h,v -- to be symmetrized as spam, directional, hv-nonsymmetrical
g.spam14h = reshape(Cooc(Rq,order,'hor',T) + Cooc(Uq,order,'ver',T),[],1);
g.spam14v = reshape(Cooc(Rq,order,'ver',T) + Cooc(Uq,order,'hor',T),[],1);
% minmax22v -- to be symmetrized as mnmx, directional, hv-nonsymmetrical. Good with higher-order residuals! Note: 22h is bad (too much neighborhood overlap).
g.min22v = reshape(Cooc(RLq_min,order,'ver',T) + Cooc(UDq_min,order,'hor',T),[],1);
g.max22v = reshape(Cooc(RLq_max,order,'ver',T) + Cooc(UDq_max,order,'hor',T),[],1);
% minmax24 -- to be symmetrized as mnmx, directional, hv-symmetrical Note: Darn good, too.
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(Rq,Uq),min(Rq,Dq),min(Lq,Uq),min(Lq,Dq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(Rq,Uq),max(Rq,Dq),max(Lq,Uq),max(Lq,Dq));
g.min24 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max24 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax34v -- v works well, h does not, to be symmetrized as mnmx, directional, hv-nonsymmetrical
g.min34v = reshape(Cooc([Uq_min Dq_min],order,'ver',T) + Cooc([Rq_min;Lq_min],order,'hor',T),[],1);
g.max34v = reshape(Cooc([Uq_max Dq_max],order,'ver',T) + Cooc([Rq_max;Lq_max],order,'hor',T),[],1);
% minmax41 -- unknown performance as of 6/14/11, to be symmetrized as mnmx, non-directional, hv-symmetrical
[R_min,R_max] = deal(min(RUq_min,LDq_min),max(RUq_max,LDq_max));
g.min41 = reshape(Cooc(R_min,order,'hor',T) + Cooc(R_min,order,'ver',T),[],1);
g.max41 = reshape(Cooc(R_max,order,'hor',T) + Cooc(R_max,order,'ver',T),[],1);
% minmax34 -- good, to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min2,RDq_min2,LUq_min2,LDq_min2] = deal(min(RUq_min,RUq),min(RDq_min,RDq),min(LUq_min,LUq),min(LDq_min,LDq));
[RUq_max2,RDq_max2,LUq_max2,LDq_max2] = deal(max(RUq_max,RUq),max(RDq_max,RDq),max(LUq_max,LUq),max(LDq_max,LDq));
g.min34 = reshape(Cooc([RUq_min2;RDq_min2;LUq_min2;LDq_min2],order,'hor',T) + Cooc([RUq_min2 RDq_min2 LUq_min2 LDq_min2],order,'ver',T),[],1);
g.max34 = reshape(Cooc([RUq_max2;RDq_max2;LUq_max2;LDq_max2],order,'hor',T) + Cooc([RUq_max2 RDq_max2 LUq_max2 LDq_max2],order,'ver',T),[],1);
% minmax48h -- h better than v, to be symmetrized as mnmx, directional, hv-nonsymmetrical. 48v is almost as good as 48h for 3rd-order but weaker for 1st-order. Here, I am outputting both but Figure 1 in our paper lists only 48h.
[RUq_min3,RDq_min3,LDq_min3,LUq_min3] = deal(min(RUq_min2,LUq),min(RDq_min2,RUq),min(LDq_min2,RDq),min(LUq_min2,LDq));
[RUq_min4,RDq_min4,LDq_min4,LUq_min4] = deal(min(RUq_min2,RDq),min(RDq_min2,LDq),min(LDq_min2,LUq),min(LUq_min2,RUq));
g.min48h = reshape(Cooc([RUq_min3;LDq_min3;RDq_min4;LUq_min4],order,'hor',T)+Cooc([RDq_min3 LUq_min3 RUq_min4 LDq_min4],order,'ver',T),[],1);
g.min48v = reshape(Cooc([RUq_min3 LDq_min3 RDq_min4 LUq_min4],order,'ver',T)+Cooc([RDq_min3;LUq_min3;RUq_min4;LDq_min4],order,'hor',T),[],1);
[RUq_max3,RDq_max3,LDq_max3,LUq_max3] = deal(max(RUq_max2,LUq),max(RDq_max2,RUq),max(LDq_max2,RDq),max(LUq_max2,LDq));
[RUq_max4,RDq_max4,LDq_max4,LUq_max4] = deal(max(RUq_max2,RDq),max(RDq_max2,LDq),max(LDq_max2,LUq),max(LUq_max2,RUq));
g.max48h = reshape(Cooc([RUq_max3;LDq_max3;RDq_max4;LUq_max4],order,'hor',T)+Cooc([RDq_max3 LUq_max3 RUq_max4 LDq_max4],order,'ver',T),[],1);
g.max48v = reshape(Cooc([RUq_max3 LDq_max3 RDq_max4 LUq_max4],order,'ver',T)+Cooc([RDq_max3;LUq_max3;RUq_max4;LDq_max4],order,'hor',T),[],1);
% minmax54 -- to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min5,RDq_min5,LDq_min5,LUq_min5] = deal(min(RUq_min3,RDq),min(RDq_min3,LDq),min(LDq_min3,LUq),min(LUq_min3,RUq));
[RUq_max5,RDq_max5,LDq_max5,LUq_max5] = deal(max(RUq_max3,RDq),max(RDq_max3,LDq),max(LDq_max3,LUq),max(LUq_max3,RUq));
g.min54 = reshape(Cooc([RUq_min5;LDq_min5;RDq_min5;LUq_min5],order,'hor',T) + Cooc([RDq_min5 LUq_min5 RUq_min5 LDq_min5],order,'ver',T),[],1);
g.max54 = reshape(Cooc([RUq_max5;LDq_max5;RDq_max5;LUq_max5],order,'hor',T) + Cooc([RDq_max5 LUq_max5 RUq_max5 LDq_max5],order,'ver',T),[],1);
function g = all3x3(X,q)
% This function outputs co-occurrences of ALL residuals based on the
% KB kernel and its "halves" (EDGE residuals) as listed in Figure 1
% in our journal HUGO paper (version from June 14), including the naming
% convention.
[T,order] = deal(2,4);
% spam11 (old name KB residual), good, non-directional, hv-symmetrical, to be symmetrized as spam
D = Residual(X,2,'KB'); Y = Quant(D,q,T);
g.spam11 = reshape(Cooc(Y,order,'hor',T) + Cooc(Y,order,'ver',T),[],1);
% EDGE residuals
D = Residual(X,2,'edge-h');Du = D(:,1:size(D,2)/2);Db = D(:,size(D,2)/2+1:end);
D = Residual(X,2,'edge-v');Dl = D(:,1:size(D,2)/2);Dr = D(:,size(D,2)/2+1:end);
[Yu,Yb,Yl,Yr] = deal(Quant(Du,q,T),Quant(Db,q,T),Quant(Dl,q,T),Quant(Dr,q,T));
% spam14h,v not bad, directional, hv-nonsym, to be symmetrized as spam
g.spam14v = reshape(Cooc([Yu Yb],order,'ver',T) + Cooc([Yl;Yr],order,'hor',T),[],1);
g.spam14h = reshape(Cooc([Yu;Yb],order,'hor',T) + Cooc([Yl Yr],order,'ver',T),[],1);
% minmax24 -- EXCELLENT, directional, hv-sym, to be symmetrized as mnmx
[Dmin1,Dmin2,Dmin3,Dmin4] = deal(min(Yu,Yl),min(Yb,Yr),min(Yu,Yr),min(Yb,Yl));
g.min24 = reshape(Cooc([Dmin1 Dmin2 Dmin3 Dmin4],order,'ver',T) + Cooc([Dmin1;Dmin2;Dmin3;Dmin4],order,'hor',T),[],1);
[Dmax1,Dmax2,Dmax3,Dmax4] = deal(max(Yu,Yl),max(Yb,Yr),max(Yu,Yr),max(Yb,Yl));
g.max24 = reshape(Cooc([Dmax1 Dmax2 Dmax3 Dmax4],order,'ver',T) + Cooc([Dmax1;Dmax2;Dmax3;Dmax4],order,'hor',T),[],1);
% minmax22 - hv-nonsymmetrical
% min22h -- good, to be symmetrized as mnmx, directional, hv-nonsymmetrical
% min22v -- EXCELLENT - to be symmetrized as mnmx, directional,
[UEq_min,REq_min] = deal(min(Yu,Yb),min(Yr,Yl));
g.min22h = reshape(Cooc(UEq_min,order,'hor',T) + Cooc(REq_min,order,'ver',T),[],1);
g.min22v = reshape(Cooc(UEq_min,order,'ver',T) + Cooc(REq_min,order,'hor',T),[],1);
[UEq_max,REq_max] = deal(max(Yu,Yb),max(Yr,Yl));
g.max22h = reshape(Cooc(UEq_max,order,'hor',T) + Cooc(REq_max,order,'ver',T),[],1);
g.max22v = reshape(Cooc(UEq_max,order,'ver',T) + Cooc(REq_max,order,'hor',T),[],1);
% minmax41 -- good, non-directional, hv-sym, to be symmetrized as mnmx
[Dmin5,Dmax5] = deal(min(Dmin1,Dmin2),max(Dmax1,Dmax2));
g.min41 = reshape(Cooc(Dmin5,order,'ver',T) + Cooc(Dmin5,order,'hor',T),[],1);
g.max41 = reshape(Cooc(Dmax5,order,'ver',T) + Cooc(Dmax5,order,'hor',T),[],1);
function g = all5x5(X,q)
% This function outputs co-occurrences of ALL residuals based on the
% KV kernel and its "halves" (EDGE residuals) as listed in Figure 1
% in our journal HUGO paper (version from June 14), including the naming
% convention.
[M N] = size(X); [I,J,T,order] = deal(3:M-2,3:N-2,2,4);
% spam11 (old name KV residual), good, non-directional, hv-symmetrical, to be symmetrized as spam
D = Residual(X,3,'KV'); Y = Quant(D,q,T);
g.spam11 = reshape(Cooc(Y,order,'hor',T) + Cooc(Y,order,'ver',T),[],1);
% EDGE residuals
Du = 8*X(I,J-1)+8*X(I-1,J)+8*X(I,J+1)-6*X(I-1,J-1)-6*X(I-1,J+1)-2*X(I,J-2)-2*X(I,J+2)-2*X(I-2,J)+2*X(I-1,J-2)+2*X(I-2,J-1)+2*X(I-2,J+1)+2*X(I-1,J+2)-X(I-2,J-2)-X(I-2,J+2)-12*X(I,J);
Dr = 8*X(I-1,J)+8*X(I,J+1)+8*X(I+1,J)-6*X(I-1,J+1)-6*X(I+1,J+1)-2*X(I-2,J)-2*X(I+2,J)-2*X(I,J+2)+2*X(I-2,J+1)+2*X(I-1,J+2)+2*X(I+1,J+2)+2*X(I+2,J+1)-X(I-2,J+2)-X(I+2,J+2)-12*X(I,J);
Db = 8*X(I,J+1)+8*X(I+1,J)+8*X(I,J-1)-6*X(I+1,J+1)-6*X(I+1,J-1)-2*X(I,J-2)-2*X(I,J+2)-2*X(I+2,J)+2*X(I+1,J+2)+2*X(I+2,J+1)+2*X(I+2,J-1)+2*X(I+1,J-2)-X(I+2,J+2)-X(I+2,J-2)-12*X(I,J);
Dl = 8*X(I+1,J)+8*X(I,J-1)+8*X(I-1,J)-6*X(I+1,J-1)-6*X(I-1,J-1)-2*X(I-2,J)-2*X(I+2,J)-2*X(I,J-2)+2*X(I+2,J-1)+2*X(I+1,J-2)+2*X(I-1,J-2)+2*X(I-2,J-1)-X(I+2,J-2)-X(I-2,J-2)-12*X(I,J);
[Yu,Yb,Yl,Yr] = deal(Quant(Du,q,T),Quant(Db,q,T),Quant(Dl,q,T),Quant(Dr,q,T));
% spam14v not bad, directional, hv-nonsym, to be symmetrized as spam
g.spam14v = reshape(Cooc([Yu Yb],order,'ver',T) + Cooc([Yl;Yr],order,'hor',T),[],1);
g.spam14h = reshape(Cooc([Yu;Yb],order,'hor',T) + Cooc([Yl Yr],order,'ver',T),[],1);
% minmax24 -- EXCELLENT, directional, hv-sym, to be symmetrized as mnmx
[Dmin1,Dmin2,Dmin3,Dmin4] = deal(min(Yu,Yl),min(Yb,Yr),min(Yu,Yr),min(Yb,Yl));
g.min24 = reshape(Cooc([Dmin1 Dmin2 Dmin3 Dmin4],order,'ver',T) + Cooc([Dmin1;Dmin2;Dmin3;Dmin4],order,'hor',T),[],1);
[Dmax1,Dmax2,Dmax3,Dmax4] = deal(max(Yu,Yl),max(Yb,Yr),max(Yu,Yr),max(Yb,Yl));
g.max24 = reshape(Cooc([Dmax1 Dmax2 Dmax3 Dmax4],order,'ver',T) + Cooc([Dmax1;Dmax2;Dmax3;Dmax4],order,'hor',T),[],1);
% minmax22 - hv-nonsymmetrical
% min22h -- good, to be symmetrized as mnmx, directional, hv-nonsymmetrical
% min22v -- EXCELLENT - to be symmetrized as mnmx, directional,
[UEq_min,REq_min] = deal(min(Yu,Yb),min(Yr,Yl));
g.min22h = reshape(Cooc(UEq_min,order,'hor',T) + Cooc(REq_min,order,'ver',T),[],1);
g.min22v = reshape(Cooc(UEq_min,order,'ver',T) + Cooc(REq_min,order,'hor',T),[],1);
[UEq_max,REq_max] = deal(max(Yu,Yb),max(Yr,Yl));
g.max22h = reshape(Cooc(UEq_max,order,'hor',T) + Cooc(REq_max,order,'ver',T),[],1);
g.max22v = reshape(Cooc(UEq_max,order,'ver',T) + Cooc(REq_max,order,'hor',T),[],1);
% minmax41 -- good, non-directional, hv-sym, to be symmetrized as mnmx
[Dmin5,Dmax5] = deal(min(Dmin1,Dmin2),max(Dmax1,Dmax2));
g.min41 = reshape(Cooc(Dmin5,order,'ver',T) + Cooc(Dmin5,order,'hor',T),[],1);
g.max41 = reshape(Cooc(Dmax5,order,'ver',T) + Cooc(Dmax5,order,'hor',T),[],1);
function f = Cooc(D,order,type,T)
% Co-occurrence operator to be appied to a 2D array of residuals D \in [-T,T]
% T ... threshold
% order ... cooc order \in {1,2,3,4,5}
% type ... cooc type \in {hor,ver,diag,mdiag,square,square-ori,hvdm}
% f ... an array of size (2T+1)^order
B = 2*T+1;
if max(abs(D(:))) > T, fprintf('*** ERROR in Cooc.m: Residual out of range ***\n'), end
switch order
case 1
f = hist(D(:),-T:T);
case 2
f = zeros(B,B);
if strcmp(type,'hor'), L = D(:,1:end-1); R = D(:,2:end);end
if strcmp(type,'ver'), L = D(1:end-1,:); R = D(2:end,:);end
if strcmp(type,'diag'), L = D(1:end-1,1:end-1); R = D(2:end,2:end);end
if strcmp(type,'mdiag'), L = D(1:end-1,2:end); R = D(2:end,1:end-1);end
for i = -T : T
R2 = R(L(:)==i);
for j = -T : T
f(i+T+1,j+T+1) = sum(R2(:)==j);
end
end
case 3
f = zeros(B,B,B);
if strcmp(type,'hor'), L = D(:,1:end-2); C = D(:,2:end-1); R = D(:,3:end);end
if strcmp(type,'ver'), L = D(1:end-2,:); C = D(2:end-1,:); R = D(3:end,:);end
if strcmp(type,'diag'), L = D(1:end-2,1:end-2); C = D(2:end-1,2:end-1); R = D(3:end,3:end);end
if strcmp(type,'mdiag'), L = D(1:end-2,3:end); C = D(2:end-1,2:end-1); R = D(3:end,1:end-2);end
for i = -T : T
C2 = C(L(:)==i);
R2 = R(L(:)==i);
for j = -T : T
R3 = R2(C2(:)==j);
for k = -T : T
f(i+T+1,j+T+1,k+T+1) = sum(R3(:)==k);
end
end
end
case 4
f = zeros(B,B,B,B);
if strcmp(type,'hor'), L = D(:,1:end-3); C = D(:,2:end-2); E = D(:,3:end-1); R = D(:,4:end);end
if strcmp(type,'ver'), L = D(1:end-3,:); C = D(2:end-2,:); E = D(3:end-1,:); R = D(4:end,:);end
if strcmp(type,'diag'), L = D(1:end-3,1:end-3); C = D(2:end-2,2:end-2); E = D(3:end-1,3:end-1); R = D(4:end,4:end);end
if strcmp(type,'mdiag'), L = D(4:end,1:end-3); C = D(3:end-1,2:end-2); E = D(2:end-2,3:end-1); R = D(1:end-3,4:end);end
if strcmp(type,'square'), L = D(2:end,1:end-1); C = D(2:end,2:end); E = D(1:end-1,2:end); R = D(1:end-1,1:end-1);end
if strcmp(type,'square-ori'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M);
L = Dh(2:end,1:end-1); C = Dv(2:end,2:end); E = Dh(1:end-1,2:end); R = Dv(1:end-1,1:end-1);end
if strcmp(type,'hvdm'), [M, N] = size(D); L = D(:,1:M); C = D(:,M+1:2*M); E = D(:,2*M+1:3*M); R = D(:,3*M+1:4*M);end
if strcmp(type,'s-in'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh(2:end,1:end-1); C = Dh1(2:end,2:end); E = Dh1(1:end-1,2:end); R = Dh(1:end-1,1:end-1);end
if strcmp(type,'s-out'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh1(2:end,1:end-1); C = Dh(2:end,2:end); E = Dh(1:end-1,2:end); R = Dh1(1:end-1,1:end-1);end
if strcmp(type,'ori-in'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh(2:end,1:end-1); C = Dv1(2:end,2:end); E = Dh1(1:end-1,2:end); R = Dv(1:end-1,1:end-1);end
if strcmp(type,'ori-out'),[M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh1(2:end,1:end-1); C = Dv(2:end,2:end); E = Dh(1:end-1,2:end); R = Dv1(1:end-1,1:end-1);end
for i = -T : T
ind = (L(:)==i); C2 = C(ind); E2 = E(ind); R2 = R(ind);
for j = -T : T
ind = (C2(:)==j); E3 = E2(ind); R3 = R2(ind);
for k = -T : T
R4 = R3(E3(:)==k);
for l = -T : T
f(i+T+1,j+T+1,k+T+1,l+T+1) = sum(R4(:)==l);
end
end
end
end
case 5
f = zeros(B,B,B,B,B);
if strcmp(type,'hor'),L = D(:,1:end-4); C = D(:,2:end-3); E = D(:,3:end-2); F = D(:,4:end-1); R = D(:,5:end);end
if strcmp(type,'ver'),L = D(1:end-4,:); C = D(2:end-3,:); E = D(3:end-2,:); F = D(4:end-1,:); R = D(5:end,:);end
for i = -T : T
ind = (L(:)==i); C2 = C(ind); E2 = E(ind); F2 = F(ind); R2 = R(ind);
for j = -T : T
ind = (C2(:)==j); E3 = E2(ind); F3 = F2(ind); R3 = R2(ind);
for k = -T : T
ind = (E3(:)==k); F4 = F3(ind); R4 = R3(ind);
for l = -T : T
R5 = R4(F4(:)==l);
for m = -T : T
f(i+T+1,j+T+1,k+T+1,l+T+1,m+T+1) = sum(R5(:)==m);
end
end
end
end
end
end
% normalization
f = double(f);
fsum = sum(f(:));
if fsum>0, f = f/fsum; end
function Y = Quant(X,q,T)
% Quantization routine
% X ... variable to be quantized/truncated
% T ... threshold
% q ... quantization step (with type = 'scalar') or a vector of increasing
% non-negative integers outlining the quantization process.
% Y ... quantized/truncated variable
% Example 0: when q is a positive scalar, Y = trunc(round(X/q),T)
% Example 1: q = [0 1 2 3] quantizes 0 to 0, 1 to 1, 2 to 2, [3,Inf) to 3,
% (-Inf,-3] to -3, -2 to -2, -1 to -1. It is equivalent to Quant(.,3,1).
% Example 2: q = [0 2 4 5] quantizes 0 to 0, {1,2} to 1, {3,4} to 2,
% [5,Inf) to 3, and similarly with the negatives.
% Example 3: q = [1 2] quantizes {-1,0,1} to 0, [2,Inf) to 1, (-Inf,-2] to -1.
% Example 4: q = [1 3 7 15 16] quantizes {-1,0,1} to 0, {2,3} to 1, {4,5,6,7}
% to 2, {8,9,10,11,12,13,14,15} to 3, [16,Inf) to 4, and similarly the
% negatives.
if numel(q) == 1
if q > 0, Y = trunc(round(X/q),T);
else fprintf('*** ERROR: Attempt to quantize with non-positive step. ***\n'),end
else
q = round(q); % Making sure the vector q is made of integers
if min(q(2:end)-q(1:end-1)) <= 0
fprintf('*** ERROR: quantization vector not strictly increasing. ***\n')
end
if min(q) < 0, fprintf('*** ERROR: Attempt to quantize with negative step. ***\n'),end
T = q(end); % The last value determines the truncation threshold
v = zeros(1,2*T+1); % value-substitution vector
Y = trunc(X,T)+T+1; % Truncated X and shifted to positive values
if q(1) == 0
v(T+1) = 0; z = 1; ind = T+2;
for i = 2 : numel(q)
v(ind:ind+q(i)-q(i-1)-1) = z;
ind = ind+q(i)-q(i-1);
z = z+1;
end
v(1:T) = -v(end:-1:T+2);
else
v(T+1-q(1):T+1+q(1)) = 0; z = 1; ind = T+2+q(1);
for i = 2 : numel(q)
v(ind:ind+q(i)-q(i-1)-1) = z;
ind = ind+q(i)-q(i-1);
z = z+1;
end
v(1:T-q(1)) = -v(end:-1:T+2+q(1));
end
Y = v(Y); % The actual quantization :)
end
function Z = trunc(X,T)
% Truncation to [-T,T]
Z = X;
Z(Z > T) = T;
Z(Z < -T) = -T;
function fsym = symfea(f,T,order,type)
% Marginalization by sign and directional symmetry for a feature vector
% stored as one of our 2*(2T+1)^order-dimensional feature vectors. This
% routine should be used for features possiessing sign and directional
% symmetry, such as spam-like features or 3x3 features. It should NOT be
% used for features from MINMAX residuals. Use the alternative
% symfea_minmax for this purpose.
% The feature f is assumed to be a 2dim x database_size matrix of features
% stored as columns (e.g., hor+ver, diag+minor_diag), with dim =
% 2(2T+1)^order.
[dim,N] = size(f);
B = 2*T+1;
c = B^order;
ERR = 1;
if strcmp(type,'spam')
if dim == 2*c
switch order % Reduced dimensionality for a B^order dimensional feature vector
case 1, red = T + 1;
case 2, red = (T + 1)^2;
case 3, red = 1 + 3*T + 4*T^2 + 2*T^3;
case 4, red = B^2 + 4*T^2*(T + 1)^2;
case 5, red = 1/4*(B^2 + 1)*(B^3 + 1);
end
fsym = zeros(2*red,N);
for i = 1 : N
switch order
case 1, cube = f(1:c,i);
case 2, cube = reshape(f(1:c,i),[B B]);
case 3, cube = reshape(f(1:c,i),[B B B]);
case 4, cube = reshape(f(1:c,i),[B B B B]);
case 5, cube = reshape(f(1:c,i),[B B B B B]);
end
% [size(symm_dir(cube,T,order)) red]
fsym(1:red,i) = symm(cube,T,order);
switch order
case 1, cube = f(c+1:2*c,i);
case 2, cube = reshape(f(c+1:2*c,i),[B B]);
case 3, cube = reshape(f(c+1:2*c,i),[B B B]);
case 4, cube = reshape(f(c+1:2*c,i),[B B B B]);
case 5, cube = reshape(f(c+1:2*c,i),[B B B B B]);
end
fsym(red+1:2*red,i) = symm(cube,T,order);
end
else
fsym = [];
fprintf('*** ERROR: feature dimension is not 2x(2T+1)^order. ***\n')
end
ERR = 0;
end
if strcmp(type,'mnmx')
if dim == 2*c
switch order
case 3, red = B^3 - T*B^2; % Dim of the marginalized set is (2T+1)^3-T*(2T+1)^2
case 4, red = B^4 - 2*T*(T+1)*B^2; % Dim of the marginalized set is (2T+1)^4-2T*(T+1)*(2T+1)^2
end
fsym = zeros(red, N);
for i = 1 : N
switch order
case 1, cube_min = f(1:c,i); cube_max = f(c+1:2*c,i);
case 2, cube_min = reshape(f(1:c,i),[B B]); cube_max = reshape(f(c+1:2*c,i),[B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1);
case 3, cube_min = reshape(f(1:c,i),[B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1);
case 4, cube_min = reshape(f(1:c,i),[B B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1,end:-1:1);
case 5, cube_min = reshape(f(1:c,i),[B B B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1,end:-1:1,end:-1:1);
end
% f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1);
fsym(:,i) = symm_dir(f_signsym,T,order);
end
end
ERR = 0;
end
if ERR == 1, fprintf('*** ERROR: Feature dimension and T, order incompatible. ***\n'), end
function As = symm_dir(A,T,order)
% Symmetry marginalization routine. The purpose is to reduce the feature
% dimensionality and make the features more populated.
% A is an array of features of size (2*T+1)^order, otherwise error is outputted.
%
% Directional marginalization pertains to the fact that the
% differences d1, d2, d3, ... in a natural (both cover and stego) image
% are as likely to occur as ..., d3, d2, d1.
% Basically, we merge all pairs of bins (i,j,k, ...) and (..., k,j,i)
% as long as they are two different bins. Thus, instead of dim =
% (2T+1)^order, we decrease the dim by 1/2*{# of non-symmetric bins}.
% For order = 3, the reduced dim is (2T+1)^order - T(2T+1)^(order-1),
% for order = 4, it is (2T+1)^4 - 2T(T+1)(2T+1)^2.
B = 2*T+1;
done = zeros(size(A));
switch order
case 3, red = B^3 - T*B^2; % Dim of the marginalized set is (2T+1)^3-T*(2T+1)^2
case 4, red = B^4 - 2*T*(T+1)*B^2; % Dim of the marginalized set is (2T+1)^4-2T*(T+1)*(2T+1)^2
case 5, red = B^5 - 2*T*(T+1)*B^3;
end
As = zeros(red, 1);
m = 1;
switch order
case 3
for i = -T : T
for j = -T : T
for k = -T : T
if k ~= i % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1) + A(k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1) = 1;
done(k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1);
done(i+T+1,j+T+1,k+T+1) = 1;
m = m + 1;
end
end
end
end
case 4
for i = -T : T
for j = -T : T
for k = -T : T
for n = -T : T
if (i ~= n) || (j ~= k) % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1,n+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1) + A(n+T+1,k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
done(n+T+1,k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1);
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
m = m + 1;
end
end
end
end
end
case 5
for i = -T : T
for j = -T : T
for k = -T : T
for l = -T : T
for n = -T : T
if (i ~= n) || (j ~= l) % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) + A(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1);
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
m = m + 1;
end
end
end
end
end
end
otherwise
fprintf('*** ERROR: Order not equal to 3 or 4 or 5! ***\n')
end
function fsym = symm1(f,T,order)
% Marginalization by sign and directional symmetry for a feature vector
% stored as a (2T+1)^order-dimensional array. The input feature f is
% assumed to be a dim x database_size matrix of features stored as columns.
[dim,N] = size(f);
B = 2*T+1;
c = B^order;
ERR = 1;
if dim == c
ERR = 0;
switch order % Reduced dimensionality for a c-dimensional feature vector
case 1, red = T + 1;
case 2, red = (T + 1)^2;
case 3, red = 1 + 3*T + 4*T^2 + 2*T^3;
case 4, red = B^2 + 4*T^2*(T + 1)^2;
case 5, red = 1/4*(B^2 + 1)*(B^3 + 1);
end
fsym = zeros(red,N);
for i = 1 : N
switch order
case 1, cube = f(:,i);
case 2, cube = reshape(f(:,i),[B B]);
case 3, cube = reshape(f(:,i),[B B B]);
case 4, cube = reshape(f(:,i),[B B B B]);
case 5, cube = reshape(f(:,i),[B B B B B]);
end
% [size(symm_dir(cube,T,order)) red]
fsym(:,i) = symm(cube,T,order);
end
end
if ERR == 1, fprintf('*** ERROR in symm1: Feature dimension and T, order incompatible. ***\n'), end
function As = symm(A,T,order)
% Symmetry marginalization routine. The purpose is to reduce the feature
% dimensionality and make the features more populated. It can be applied to
% 1D -- 5D co-occurrence matrices (order \in {1,2,3,4,5}) with sign and
% directional symmetries (explained below).
% A must be an array of (2*T+1)^order, otherwise error is outputted.
%
% Marginalization by symmetry pertains to the fact that, fundamentally,
% the differences between consecutive pixels in a natural image (both cover
% and stego) d1, d2, d3, ..., have the same probability of occurrence as the
% triple -d1, -d2, -d3, ...
%
% Directional marginalization pertains to the fact that the
% differences d1, d2, d3, ... in a natural (cover and stego) image are as
% likely to occur as ..., d3, d2, d1.
ERR = 1; % Flag denoting when size of A is incompatible with the input parameters T and order
m = 2;
B = 2*T + 1;
switch order
case 1 % First-order coocs are only symmetrized
if numel(A) == 2*T+1
As(1) = A(T+1); % The only non-marginalized bin is the origin 0
As(2:T+1) = A(1:T) + A(T+2:end);
As = As(:);
ERR = 0;
end
case 2
if numel(A) == (2*T+1)^2
As = zeros((T+1)^2, 1);
As(1) = A(T+1,T+1); % The only non-marginalized bin is the origin (0,0)
for i = -T : T
for j = -T : T
if (done(i+T+1,j+T+1) == 0) && (abs(i)+abs(j) ~= 0)
As(m) = A(i+T+1,j+T+1) + A(T+1-i,T+1-j);
done(i+T+1,j+T+1) = 1;
done(T+1-i,T+1-j) = 1;
if (i ~= j) && (done(j+T+1,i+T+1) == 0)
As(m) = As(m) + A(j+T+1,i+T+1) + A(T+1-j,T+1-i);
done(j+T+1,i+T+1) = 1;
done(T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
ERR = 0;
end
case 3
if numel(A) == B^3
done = zeros(size(A));
As = zeros(1+3*T+4*T^2+2*T^3, 1);
As(1) = A(T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
if (done(i+T+1,j+T+1,k+T+1) == 0) && (abs(i)+abs(j)+abs(k) ~= 0)
As(m) = A(i+T+1,j+T+1,k+T+1) + A(T+1-i,T+1-j,T+1-k);
done(i+T+1,j+T+1,k+T+1) = 1;
done(T+1-i,T+1-j,T+1-k) = 1;
if (i ~= k) && (done(k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(k+T+1,j+T+1,i+T+1) + A(T+1-k,T+1-j,T+1-i);
done(k+T+1,j+T+1,i+T+1) = 1;
done(T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
ERR = 0;
end
case 4
if numel(A) == (2*T+1)^4
done = zeros(size(A));
As = zeros(B^2 + 4*T^2*(T+1)^2, 1);
As(1) = A(T+1,T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
for n = -T : T
if (done(i+T+1,j+T+1,k+T+1,n+T+1) == 0) && (abs(i)+abs(j)+abs(k)+abs(n)~=0)
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1) + A(T+1-i,T+1-j,T+1-k,T+1-n);
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
done(T+1-i,T+1-j,T+1-k,T+1-n) = 1;
if ((i ~= n) || (j ~= k)) && (done(n+T+1,k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(n+T+1,k+T+1,j+T+1,i+T+1) + A(T+1-n,T+1-k,T+1-j,T+1-i);
done(n+T+1,k+T+1,j+T+1,i+T+1) = 1;
done(T+1-n,T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
end
ERR = 0;
end
case 5
if numel(A) == (2*T+1)^5
done = zeros(size(A));
As = zeros(1/4*(B^2 + 1)*(B^3 + 1), 1);
As(1) = A(T+1,T+1,T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
for l = -T : T
for n = -T : T
if (done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) == 0) && (abs(i)+abs(j)+abs(k)+abs(l)+abs(n)~=0)
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) + A(T+1-i,T+1-j,T+1-k,T+1-l,T+1-n);
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
done(T+1-i,T+1-j,T+1-k,T+1-l,T+1-n) = 1;
if ((i ~= n) || (j ~= l)) && (done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) + A(T+1-n,T+1-l,T+1-k,T+1-j,T+1-i);
done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) = 1;
done(T+1-n,T+1-l,T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
end
end
ERR = 0;
end
otherwise
As = [];
fprintf(' Order of cooc is not in {1,2,3,4,5}.\n')
end
if ERR == 1
As = [];
fprintf('*** ERROR in symm: The number of elements in the array is not (2T+1)^order. ***\n')
end
As = As(:);
function D = Residual(X,order,type)
% Computes the noise residual of a given type and order from MxN image X.
% residual order \in {1,2,3,4,5,6}
% type \in {hor,ver,diag,mdiag,KB,edge-h,edge-v,edge-d,edge-m}
% The resulting residual is an (M-b)x(N-b) array of the specified order,
% where b = ceil(order/2). This cropping is little more than it needs to
% be to make sure all the residuals are easily "synchronized".
% !!!!!!!!!!!!! Use order = 2 with KB and all edge residuals !!!!!!!!!!!!!
[M N] = size(X);
I = 1+ceil(order/2) : M-ceil(order/2);
J = 1+ceil(order/2) : N-ceil(order/2);
switch type
case 'hor'
switch order
case 1, D = - X(I,J) + X(I,J+1);
case 2, D = X(I,J-1) - 2*X(I,J) + X(I,J+1);
case 3, D = X(I,J-1) - 3*X(I,J) + 3*X(I,J+1) - X(I,J+2);
case 4, D = -X(I,J-2) + 4*X(I,J-1) - 6*X(I,J) + 4*X(I,J+1) - X(I,J+2);
case 5, D = -X(I,J-2) + 5*X(I,J-1) - 10*X(I,J) + 10*X(I,J+1) - 5*X(I,J+2) + X(I,J+3);
case 6, D = X(I,J-3) - 6*X(I,J-2) + 15*X(I,J-1) - 20*X(I,J) + 15*X(I,J+1) - 6*X(I,J+2) + X(I,J+3);
end
case 'ver'
switch order
case 1, D = - X(I,J) + X(I+1,J);
case 2, D = X(I-1,J) - 2*X(I,J) + X(I+1,J);
case 3, D = X(I-1,J) - 3*X(I,J) + 3*X(I+1,J) - X(I+2,J);
case 4, D = -X(I-2,J) + 4*X(I-1,J) - 6*X(I,J) + 4*X(I+1,J) - X(I+2,J);
case 5, D = -X(I-2,J) + 5*X(I-1,J) - 10*X(I,J) + 10*X(I+1,J) - 5*X(I+2,J) + X(I+3,J);
case 6, D = X(I-3,J) - 6*X(I-2,J) + 15*X(I-1,J) - 20*X(I,J) + 15*X(I+1,J) - 6*X(I+2,J) + X(I+3,J);
end
case 'diag'
switch order
case 1, D = - X(I,J) + X(I+1,J+1);
case 2, D = X(I-1,J-1) - 2*X(I,J) + X(I+1,J+1);
case 3, D = X(I-1,J-1) - 3*X(I,J) + 3*X(I+1,J+1) - X(I+2,J+2);
case 4, D = -X(I-2,J-2) + 4*X(I-1,J-1) - 6*X(I,J) + 4*X(I+1,J+1) - X(I+2,J+2);
case 5, D = -X(I-2,J-2) + 5*X(I-1,J-1) - 10*X(I,J) + 10*X(I+1,J+1) - 5*X(I+2,J+2) + X(I+3,J+3);
case 6, D = X(I-3,J-3) - 6*X(I-2,J-2) + 15*X(I-1,J-1) - 20*X(I,J) + 15*X(I+1,J+1) - 6*X(I+2,J+2) + X(I+3,J+3);
end
case 'mdiag'
switch order
case 1, D = - X(I,J) + X(I-1,J+1);
case 2, D = X(I-1,J+1) - 2*X(I,J) + X(I+1,J-1);
case 3, D = X(I-1,J+1) - 3*X(I,J) + 3*X(I+1,J-1) - X(I+2,J-2);
case 4, D = -X(I-2,J+2) + 4*X(I-1,J+1) - 6*X(I,J) + 4*X(I+1,J-1) - X(I+2,J-2);
case 5, D = -X(I-2,J+2) + 5*X(I-1,J+1) - 10*X(I,J) + 10*X(I+1,J-1) - 5*X(I+2,J-2) + X(I+3,J-3);
case 6, D = X(I-3,J+3) - 6*X(I-2,J+2) + 15*X(I-1,J+1) - 20*X(I,J) + 15*X(I+1,J-1) - 6*X(I+2,J-2) + X(I+3,J-3);
end
case 'KB'
D = -X(I-1,J-1) + 2*X(I-1,J) - X(I-1,J+1) + 2*X(I,J-1) - 4*X(I,J) + 2*X(I,J+1) - X(I+1,J-1) + 2*X(I+1,J) - X(I+1,J+1);
case 'edge-h'
Du = 2*X(I-1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I-1,J-1) - X(I-1,J+1) - 4*X(I,J); % -1 2 -1
Db = 2*X(I+1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I+1,J-1) - X(I+1,J+1) - 4*X(I,J); % 2 C 2 + flipped vertically
D = [Du,Db];
case 'edge-v'
Dl = 2*X(I,J-1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J-1) - X(I+1,J-1) - 4*X(I,J); % -1 2
Dr = 2*X(I,J+1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J+1) - X(I+1,J+1) - 4*X(I,J); % 2 C + flipped horizontally
D = [Dl,Dr]; % -1 2
case 'edge-m'
Dlu = 2*X(I,J-1) + 2*X(I-1,J) - X(I-1,J-1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % -1 2 -1
Drb = 2*X(I,J+1) + 2*X(I+1,J) - X(I+1,J+1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % 2 C + flipped mdiag
D = [Dlu,Drb]; % -1
case 'edge-d'
Dru = 2*X(I-1,J) + 2*X(I,J+1) - X(I-1,J+1) - X(I-1,J-1) - X(I+1,J+1) - X(I,J); % -1 2 -1
Dlb = 2*X(I,J-1) + 2*X(I+1,J) - X(I+1,J-1) - X(I+1,J+1) - X(I-1,J-1) - X(I,J); % C 2 + flipped diag
D = [Dru,Dlb]; % -1
case 'KV'
D = 8*X(I-1,J) + 8*X(I+1,J) + 8*X(I,J-1) + 8*X(I,J+1);
D = D - 6*X(I-1,J+1) - 6*X(I-1,J-1) - 6*X(I+1,J-1) - 6*X(I+1,J+1);
D = D - 2*X(I-2,J) - 2*X(I+2,J) - 2*X(I,J+2) - 2*X(I,J-2);
D = D + 2*X(I-1,J-2) + 2*X(I-2,J-1) + 2*X(I-2,J+1) + 2*X(I-1,J+2) + 2*X(I+1,J+2) + 2*X(I+2,J+1) + 2*X(I+2,J-1) + 2*X(I+1,J-2);
D = D - X(I-2,J-2) - X(I-2,J+2) - X(I+2,J-2) - X(I+2,J+2) - 12*X(I,J);
end
|
github
|
daniellerch/aletheia-master
|
S_UNIWARD.m
|
.m
|
aletheia-master/aletheia-octave/octave/S_UNIWARD.m
| 6,938 |
utf_8
|
12eab6d1eb941654f400a98253b0a617
|
function stego = S_UNIWARD(coverPath, payload)
% -------------------------------------------------------------------------
% Copyright (c) 2013 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | October 2012
% http://dde.binghamton.edu/download/steganography
% -------------------------------------------------------------------------
% This function simulates embedding using S-UNIWARD steganographic
% algorithm. For more deatils about the individual submodels, please see
% the publication [1].
% -------------------------------------------------------------------------
% Input: coverPath ... path to the image
% payload ..... payload in bits per pixel
% Output: stego ....... resulting image with embedded payload
% -------------------------------------------------------------------------
% PAPER
% -------------------------------------------------------------------------
sgm = 1;
%% Get 2D wavelet filters - Daubechies 8
% 1D high pass decomposition filter
hpdf = [-0.0544158422, 0.3128715909, -0.6756307363, 0.5853546837, 0.0158291053, -0.2840155430, -0.0004724846, 0.1287474266, 0.0173693010, -0.0440882539, ...
-0.0139810279, 0.0087460940, 0.0048703530, -0.0003917404, -0.0006754494, -0.0001174768];
% 1D low pass decomposition filter
lpdf = (-1).^(0:numel(hpdf)-1).*fliplr(hpdf);
% construction of 2D wavelet filters
F{1} = lpdf'*hpdf;
F{2} = hpdf'*lpdf;
F{3} = hpdf'*hpdf;
%% Get embedding costs
% inicialization
cover = double(imread(coverPath));
wetCost = 10^8;
[k,l] = size(cover);
% add padding
padSize = max([size(F{1})'; size(F{2})'; size(F{3})']);
coverPadded = padarray(cover, [padSize padSize], 'symmetric');
xi = cell(3, 1);
for fIndex = 1:3
% compute residual
R = conv2(coverPadded, F{fIndex}, 'same');
% compute suitability
xi{fIndex} = conv2(1./(abs(R)+sgm), rot90(abs(F{fIndex}), 2), 'same');
% correct the suitability shift if filter size is even
if mod(size(F{fIndex}, 1), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [1, 0]); end;
if mod(size(F{fIndex}, 2), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [0, 1]); end;
% remove padding
xi{fIndex} = xi{fIndex}(((size(xi{fIndex}, 1)-k)/2)+1:end-((size(xi{fIndex}, 1)-k)/2), ((size(xi{fIndex}, 2)-l)/2)+1:end-((size(xi{fIndex}, 2)-l)/2));
end
% compute embedding costs \rho
rho = xi{1} + xi{2} + xi{3};
% adjust embedding costs
rho(rho > wetCost) = wetCost; % threshold on the costs
rho(isnan(rho)) = wetCost; % if all xi{} are zero threshold the cost
rhoP1 = rho;
rhoM1 = rho;
rhoP1(cover==255) = wetCost; % do not embed +1 if the pixel has max value
rhoM1(cover==0) = wetCost; % do not embed -1 if the pixel has min value
%% Embedding simulator
stego = EmbeddingSimulator(cover, rhoP1, rhoM1, payload*numel(cover), false);
%% --------------------------------------------------------------------------------------------------------------------------
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
function [y] = EmbeddingSimulator(x, rhoP1, rhoM1, m, fixEmbeddingChanges)
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
if fixEmbeddingChanges == 1
%RandStream.setGlobalStream(RandStream('mt19937ar','seed',139187));
rand('state', 139187);
else
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',sum(100*clock)));
rand('state', sum(100*clock));
end
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
end
|
github
|
daniellerch/aletheia-master
|
TRIPLES.m
|
.m
|
aletheia-master/aletheia-octave/octave/TRIPLES.m
| 2,811 |
utf_8
|
246cc344502066369572be6f8fb846a5
|
function beta_hat = TRIPLES(path, channel)
%
% Triples message length estimator utilizing only the symmetry e_2m+1,2n+1
% = o_2m+1,2n+1 with m,n \in {-5,...,5}.
% This implementation follows the method description in:
% Andrew D. Ker: "A general framework for the structural steganalysis of
% LSB replacement." In: Proc. 7th Information Hiding Workshop, LNCS vol.
% 3727, pp. 296-311, Barcelona, Spain. Springer-Verlag, 2005.
%
% 2011 Copyright by Jessica Fridrich, [email protected],
% http:\\ws.binghamton.edu\fridrich
%
X = double(imread(path));
if(size(size(X))!=2)
X=X(:,:,channel);
end
[M N] = size(X);
X = double(X);
I = 1 : M;
J = 1 : N-2;
e = zeros(25,25); o = e;
c0 = zeros(11,11); c1 = c0; c2 = c0; c3 = c0;
L = X(I,J); C = X(I,J+1); R = X(I,J+2); % Only row triples are considered
T1 = C(:) - L(:); % s2 - s1
T2 = R(:) - C(:); % s3 - s2
for m1 = -11 : 13 % We need subscripts 2n-1...2n+3 and the same for 2m-1...2m+3, which means m1,m2 \in {-11...13}
for m2 = -11 : 13
i1 = find(T1 == m1);
i2 = i1(T2(i1) == m2);
e(m1+12,m2+12) = sum(1 - mod(L(i2),2)); % (s1..s3), s2=s1+m1, s3=s2+m2, s1 even
o(m1+12,m2+12) = sum(mod(L(i2),2)); % (s1..s3), s2=s1+m1, s3=s2+m2, s1 odd
end
end
m = -5 : 5;
n = -5 : 5;
d0 = e(2*m+1+12,2*n+1+12)-o(2*m+1+12,2*n+1+12);
d1 = e(2*m+1+12,2*n+2+12)+e(2*m+12,2*n+2+12)+o(2*m+12,2*n+1+12)-o(2*m+1+12,2*n+12)-o(2*m+2+12,2*n+12)-e(2*m+2+12,2*n+1+12);
d2 = e(2*m+12,2*n+3+12)+o(2*m-1+12,2*n+2+12)+o(2*m+12,2*n+2+12)-o(2*m+2+12,2*n-1+12)-e(2*m+2+12,2*n+12)-e(2*m+3+12,2*n+12);
d3 = o(2*m-1+12,2*n+3+12)-e(2*m+3+12,2*n-1+12);
c0 = d0 + d1 + d2 + d3;
c1 = 3*d0 + d1 - d2 - 3*d3;
c2 = 3*d0 - d1 - d2 + 3*d3;
c3 = d0 - d1 + d2 - d3;
% Solving the quintic
epsilon = 0.000000001;
Left = 0.6; Right = 7;
FL = quintic(Left,c0,c1,c2,c3);
FR = quintic(Right,c0,c1,c2,c3);
accuracy = 1;
if FL * FR > 0
beta_hat = -1;
else % Binary search
while accuracy > epsilon
y = (Left + Right) / 2;
Fy = quintic(y,c0,c1,c2,c3);
if Fy * FL <= 0
Right = y;
FR = Fy;
else
Left = y;
FL = Fy;
end
accuracy = abs(Right - Left);
end
end
q_hat = (Left + Right) / 2;
beta_hat = 1/2*(1 - 1/q_hat);
% t = 0.5:0.01:7;
% y = quintic(t,c0,c1,c2,c3);
% plot(t,y,'k')
function y = quintic(q,c0,c1,c2,c3)
% q can be a vector
[Cm,Cn] = size(c0);
y = 0;
for m = 1 : Cm
for n = 1 : Cn
y = y + 2*c0(m,n)*c1(m,n) + q*(4*c0(m,n)*c2(m,n) + 2*c1(m,n)^2);
y = y + q.^2*(6*c0(m,n)*c3(m,n) + 6*c1(m,n)*c2(m,n));
y = y + q.^3*(4*c2(m,n)^2 + 8*c1(m,n)*c3(m,n)) + q.^4*10*c2(m,n)*c3(m,n) + q.^5*6*c3(m,n)^2;
end
end
|
github
|
daniellerch/aletheia-master
|
J_UNIWARD.m
|
.m
|
aletheia-master/aletheia-octave/octave/J_UNIWARD.m
| 7,419 |
utf_8
|
862bdb2dc9f6bd8a14f585696267cc87
|
function J_UNIWARD(cover, payload, stego)
% -------------------------------------------------------------------------
% Copyright (c) 2013 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | February
% 2013
% http://dde.binghamton.edu/download/stego_algorithms/
% -------------------------------------------------------------------------
% This function simulates embedding using J-UNIWARD steganographic
% algorithm.
% -------------------------------------------------------------------------
% Input: cover ... ... path to the image
% payload ..... payload in bits per non zero DCT coefficient
% Output: stego ....... resulting JPEG structure with embedded payload
% -------------------------------------------------------------------------
C_SPATIAL = double(imread(cover));
C_STRUCT = jpeg_read(cover);
C_COEFFS = C_STRUCT.coef_arrays{1};
C_QUANT = C_STRUCT.quant_tables{1};
wetConst = 10^13;
sgm = 2^(-6);
%% Get 2D wavelet filters - Daubechies 8
% 1D high pass decomposition filter
hpdf = [-0.0544158422, 0.3128715909, -0.6756307363, 0.5853546837, 0.0158291053, -0.2840155430, -0.0004724846, 0.1287474266, 0.0173693010, -0.0440882539, ...
-0.0139810279, 0.0087460940, 0.0048703530, -0.0003917404, -0.0006754494, -0.0001174768];
% 1D low pass decomposition filter
lpdf = (-1).^(0:numel(hpdf)-1).*fliplr(hpdf);
F{1} = lpdf'*hpdf;
F{2} = hpdf'*lpdf;
F{3} = hpdf'*hpdf;
%% Pre-compute impact in spatial domain when a jpeg coefficient is changed by 1
spatialImpact = cell(8, 8);
for bcoord_i=1:8
for bcoord_j=1:8
testCoeffs = zeros(8, 8);
testCoeffs(bcoord_i, bcoord_j) = 1;
spatialImpact{bcoord_i, bcoord_j} = idct2(testCoeffs)*C_QUANT(bcoord_i, bcoord_j);
end
end
%% Pre compute impact on wavelet coefficients when a jpeg coefficient is changed by 1
waveletImpact = cell(numel(F), 8, 8);
for Findex = 1:numel(F)
for bcoord_i=1:8
for bcoord_j=1:8
waveletImpact{Findex, bcoord_i, bcoord_j} = imfilter(spatialImpact{bcoord_i, bcoord_j}, F{Findex}, 'full');
end
end
end
%% Create reference cover wavelet coefficients (LH, HL, HH)
% Embedding should minimize their relative change. Computation uses mirror-padding
padSize = max([size(F{1})'; size(F{2})']);
C_SPATIAL_PADDED = padarray(C_SPATIAL, [padSize padSize], 'symmetric'); % pad image
RC = cell(size(F));
for i=1:numel(F)
RC{i} = imfilter(C_SPATIAL_PADDED, F{i});
end
[k, l] = size(C_COEFFS);
nzAC = nnz(C_COEFFS)-nnz(C_COEFFS(1:8:end,1:8:end));
rho = zeros(k, l);
tempXi = cell(3, 1);
%% Computation of costs
for row = 1:k
for col = 1:l
modRow = mod(row-1, 8)+1;
modCol = mod(col-1, 8)+1;
subRows = row-modRow-6+padSize:row-modRow+16+padSize;
subCols = col-modCol-6+padSize:col-modCol+16+padSize;
for fIndex = 1:3
% compute residual
RC_sub = RC{fIndex}(subRows, subCols);
% get differences between cover and stego
wavCoverStegoDiff = waveletImpact{fIndex, modRow, modCol};
% compute suitability
tempXi{fIndex} = abs(wavCoverStegoDiff) ./ (abs(RC_sub)+sgm);
end
rhoTemp = tempXi{1} + tempXi{2} + tempXi{3};
rho(row, col) = sum(rhoTemp(:));
end
end
rhoM1 = rho;
rhoP1 = rho;
rhoP1(rhoP1 > wetConst) = wetConst;
rhoP1(isnan(rhoP1)) = wetConst;
rhoP1(C_COEFFS > 1023) = wetConst;
rhoM1(rhoM1 > wetConst) = wetConst;
rhoM1(isnan(rhoM1)) = wetConst;
rhoM1(C_COEFFS < -1023) = wetConst;
%% Embedding simulation
S_COEFFS = EmbeddingSimulator(C_COEFFS, rhoP1, rhoM1, round(payload * nzAC));
S_STRUCT = C_STRUCT;
S_STRUCT.coef_arrays{1} = S_COEFFS;
try
jpeg_write(S_STRUCT, stego);
catch
error('ERROR (problem with saving the stego image)')
end
function [y, pChangeP1, pChangeM1] = EmbeddingSimulator(x, rhoP1, rhoM1, m)
x = double(x);
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
pP1 = pP1(:);
pM1 = pM1(:);
Ht = -(pP1.*log2(pP1))-(pM1.*log2(pM1))-((1-pP1-pM1).*log2(1-pP1-pM1));
Ht(isnan(Ht)) = 0;
Ht = sum(Ht);
end
end
end
|
github
|
daniellerch/aletheia-master
|
HILL_COLOR.m
|
.m
|
aletheia-master/aletheia-octave/octave/HILL_COLOR.m
| 5,448 |
utf_8
|
4b65debe28bd32907c6d33ecfc553d73
|
function stego = HILL_COLOR(cover_path, payload)
H=0;
cover_3ch = double(imread(cover_path));
stego = zeros(size(cover_3ch));
for index_color=1:3
x = cover_3ch(:,:,index_color);
cost=f_cal_cost(x);
stego(:,:,index_color) = f_sim_embedding(x, cost, payload, H);
end
end
function cost = f_cal_cost(cover)
% Copyright (c) 2014 Shenzhen University,
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from Shenzhen University.
% -------------------------------------------------------------------------
% Author: Ming Wang
% -------------------------------------------------------------------------
% Contact: [email protected]
% [email protected]
% -------------------------------------------------------------------------
% Input: cover ... cover image%
% Output: cost ....... costs value of all pixels
% -------------------------------------------------------------------------
% [1] A New Cost Function for Spatial Image Steganography,
% B.Li, M.Wang,J.Huang and X.Li, to be presented at IEEE International Conference on Image Processing, 2014.
% -------------------------------------------------------------------------
%Get filter
HF1=[-1,2,-1;2,-4,2;-1,2,-1];
H2 = fspecial('average',[3 3]);
%% Get cost
cover=double(cover);
sizeCover=size(cover);
padsize=max(size(HF1));
coverPadded = padarray(cover, [padsize padsize], 'symmetric');% add padding
R1 = conv2(coverPadded,HF1, 'same');%mirror-padded convolution
W1 = conv2(abs(R1),H2,'same');
if mod(size(HF1, 1), 2) == 0, W1= circshift(W1, [1, 0]); end;
if mod(size(HF1, 2), 2) == 0, W1 = circshift(W1, [0, 1]); end;
W1 = W1(((size(W1, 1)-sizeCover(1))/2)+1:end-((size(W1, 1)-sizeCover(1))/2), ((size(W1, 2)-sizeCover(2))/2)+1:end-((size(W1, 2)-sizeCover(2))/2));
rho=1./(W1+10^(-10));
HW = fspecial('average',[15 15]);
cost = imfilter(rho, HW ,'symmetric','same');
end
function stegoB = f_sim_embedding(cover, costmat, payload)
cover = double(cover);
seed = 123;
wetCost = 10^10;
% compute embedding costs \rho
rhoA = costmat;
rhoA(rhoA > wetCost) = wetCost; % threshold on the costs
rhoA(isnan(rhoA)) = wetCost; % if all xi{} are zero threshold the cost
rhoP1 = rhoA;
rhoM1 = rhoA;
rhoP1(cover==255) = wetCost; % do not embed +1 if the pixel has max value
rhoM1(cover==0) = wetCost; % do not embed -1 if the pixel has min value
stegoB = f_EmbeddingSimulator_seed(cover, rhoP1, rhoM1, payload*numel(cover));
end
function y = f_EmbeddingSimulator_seed(x, rhoP1, rhoM1, m)
%% --------------------------------------------------------------------------------------------------
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
rand('state', sum(100*clock));
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
iterations = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<300)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
% disp(iterations);
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
|
github
|
daniellerch/aletheia-master
|
HILL.m
|
.m
|
aletheia-master/aletheia-octave/octave/HILL.m
| 5,287 |
utf_8
|
5a1e478de28a0b51c3428f209e0f6047
|
function stego = HILL(cover_path, payload)
H=0;
x = imread(cover_path);
cost=f_cal_cost(x);
stego=f_sim_embedding(x, cost, payload, H);
end
function cost = f_cal_cost(cover)
% Copyright (c) 2014 Shenzhen University,
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from Shenzhen University.
% -------------------------------------------------------------------------
% Author: Ming Wang
% -------------------------------------------------------------------------
% Contact: [email protected]
% [email protected]
% -------------------------------------------------------------------------
% Input: cover ... cover image%
% Output: cost ....... costs value of all pixels
% -------------------------------------------------------------------------
% [1] A New Cost Function for Spatial Image Steganography,
% B.Li, M.Wang,J.Huang and X.Li, to be presented at IEEE International Conference on Image Processing, 2014.
% -------------------------------------------------------------------------
%Get filter
HF1=[-1,2,-1;2,-4,2;-1,2,-1];
H2 = fspecial('average',[3 3]);
%% Get cost
cover=double(cover);
sizeCover=size(cover);
padsize=max(size(HF1));
coverPadded = padarray(cover, [padsize padsize], 'symmetric');% add padding
R1 = conv2(coverPadded,HF1, 'same');%mirror-padded convolution
W1 = conv2(abs(R1),H2,'same');
if mod(size(HF1, 1), 2) == 0, W1= circshift(W1, [1, 0]); end;
if mod(size(HF1, 2), 2) == 0, W1 = circshift(W1, [0, 1]); end;
W1 = W1(((size(W1, 1)-sizeCover(1))/2)+1:end-((size(W1, 1)-sizeCover(1))/2), ((size(W1, 2)-sizeCover(2))/2)+1:end-((size(W1, 2)-sizeCover(2))/2));
rho=1./(W1+10^(-10));
HW = fspecial('average',[15 15]);
cost = imfilter(rho, HW ,'symmetric','same');
end
function stegoB = f_sim_embedding(cover, costmat, payload)
cover = double(cover);
seed = 123;
wetCost = 10^10;
% compute embedding costs \rho
rhoA = costmat;
rhoA(rhoA > wetCost) = wetCost; % threshold on the costs
rhoA(isnan(rhoA)) = wetCost; % if all xi{} are zero threshold the cost
rhoP1 = rhoA;
rhoM1 = rhoA;
rhoP1(cover==255) = wetCost; % do not embed +1 if the pixel has max value
rhoM1(cover==0) = wetCost; % do not embed -1 if the pixel has min value
stegoB = f_EmbeddingSimulator_seed(cover, rhoP1, rhoM1, payload*numel(cover));
end
function y = f_EmbeddingSimulator_seed(x, rhoP1, rhoM1, m)
%% --------------------------------------------------------------------------------------------------
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
rand('state', sum(100*clock));
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
iterations = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<300)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
% disp(iterations);
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
|
github
|
daniellerch/aletheia-master
|
EBS_COLOR.m
|
.m
|
aletheia-master/aletheia-octave/octave/EBS_COLOR.m
| 4,870 |
UNKNOWN
|
003a2f4f562a2f671e2e9327e39b2805
|
function EBS_COLOR(cover, payload, stego)
% Script modified by R�mi Cogranne, based upon the ones provided by Vojtech Holub (in 2014)
% use:
% toto = jpeg_read('./test.jpg');
% payload = 0.4;
% S_STRUCT = EBS(toto, payload)
%
try
C_STRUCT = jpeg_read(cover);
catch
error('ERROR (problem with the cover image)');
end
wetConst = 10^13;
STEGO=C_STRUCT;
for index_color=1:3
if (index_color==1)
C_QUANT = C_STRUCT.quant_tables{index_color};
else
C_QUANT = C_STRUCT.quant_tables{2};
end
DCT_rounded = C_STRUCT.coef_arrays{index_color};
%% Block Entropy Cost
rho_ent = zeros(size(DCT_rounded));
for row=1:size(DCT_rounded, 1)/8
for col=1:size(DCT_rounded, 2)/8
all_coeffs = DCT_rounded(row*8-7:row*8, col*8-7:col*8);
all_coeffs(1, 1) = 0; %remove DC
nzAC_coeffs = all_coeffs(all_coeffs ~= 0);
nzAC_unique_coeffs = unique(nzAC_coeffs);
if numel(nzAC_unique_coeffs) > 1
b = hist(nzAC_coeffs, nzAC_unique_coeffs);
b = b(b~=0);
p = b ./ sum(b);
H_block = -sum(p.*log(p));
else
H_block = 0;
end
rho_ent(row*8-7:row*8, col*8-7:col*8) = 1/(H_block^2);
end
end
qi = repmat(C_QUANT, size(DCT_rounded) ./ 8);
rho_f = (qi).^2;
%% Final cost
rho = rho_ent .* rho_f;
rho = rho + 10^(-4);
rho(rho > wetConst) = wetConst;
rho(isnan(rho)) = wetConst;
rho(DCT_rounded > 1022) = wetConst;
rho(DCT_rounded < -1022) = wetConst;
maxCostMat = false(size(rho));
maxCostMat(1:8:end, 1:8:end) = true;
maxCostMat(5:8:end, 1:8:end) = true;
maxCostMat(1:8:end, 5:8:end) = true;
maxCostMat(5:8:end, 5:8:end) = true;
rho(maxCostMat) = wetConst;
changeable = (rho< wetConst);
rho=rho(changeable);
%% Compute message lenght for each run
nzAC = nnz(DCT_rounded)-nnz(DCT_rounded(1:8:end,1:8:end)); % number of nonzero AC DCT coefficients
%% Embedding
% permutes path
DCT_rounded_changeable=DCT_rounded(changeable);
perm = randperm(numel(DCT_rounded_changeable));
[LSBs] = EmbeddingSimulator(DCT_rounded_changeable(perm), rho(perm)', round(payload*nzAC));
LSBs(perm) = LSBs; % inverse permutation
% Create stego coefficients
temp = mod(DCT_rounded_changeable, 2);
ToBeChanged = zeros(size(DCT_rounded_changeable));
ToBeChanged(temp == LSBs) = DCT_rounded_changeable(temp == LSBs);
ToBeChanged(temp ~= LSBs) = DCT_rounded_changeable(temp ~= LSBs) + ((rand(1)>0.5)-0.5)*2;
S_COEFFS = DCT_rounded;
S_COEFFS(changeable) = ToBeChanged;
STEGO.coef_arrays{index_color} = S_COEFFS;
try
jpeg_write(STEGO, stego);
catch
error('ERROR (problem with saving the stego image)')
end
end
end
function [LSBs] = EmbeddingSimulator(x, rho, m)
rho = rho';
x = double(x);
n = numel(x);
lambda = calc_lambda(rho, m, n);
pChange = 1 - (double(1)./(1+exp(-lambda.*rho)));
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',sum(100*clock)));
rand('state', sum(100*clock));
randChange = rand(size(x));
flippedPixels = (randChange < pChange);
LSBs = mod(x + flippedPixels, 2);
function lambda = calc_lambda(rho, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
p = double(1)./(1 + exp(-l3 .* rho));
m3 = binary_entropyf(p);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
p = double(1)./(1+exp(-lambda.*rho));
m2 = binary_entropyf(p);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Hb = binary_entropyf(p)
p = p(:);
Hb = (-p.*log2(p))-((1-p).*log2(1-p));
Hb(isnan(Hb)) = 0;
Hb = sum(Hb);
end
end
|
github
|
daniellerch/aletheia-master
|
NSF5.m
|
.m
|
aletheia-master/aletheia-octave/octave/NSF5.m
| 3,266 |
utf_8
|
4ce30e16d5eae39d4b9b653b21f3d113
|
function [nzAC,embedding_efficiency,changes] = NSF5(COVER, ALPHA, STEGO)
SEED=sum(100*clock); % random key
% -------------------------------------------------------------------------
% Contact: [email protected] | June 2011
% -------------------------------------------------------------------------
% This program simulates the embedding impact of the steganographic
% algorithm nsF5 [1] as if the best possible coding was used. Please, visit
% the webpage http://dde.binghamton.edu/download/nsf5simulator for more
% information.
% -------------------------------------------------------------------------
% Input:
% COVER - cover image (grayscale JPEG image)
% STEGO - resulting stego image that will be created
% ALPHA - relative payload in terms of bits per nonzero AC DCT coefficient
% SEED - PRNG seed for the random walk over the coefficients
% Output:
% nzAC - number of nonzero AC DCT coefficients in the cover image
% embedding_efficiency - bound on embedding efficiency used for simulation
% changes - number of changes made
% -------------------------------------------------------------------------
% References:
% [1] J. Fridrich, T. Pevny, and J. Kodovsky, Statistically undetectable
% JPEG steganography: Dead ends, challenges, and opportunities. In J.
% Dittmann and J. Fridrich, editors, Proceedings of the 9th ACM
% Multimedia & Security Workshop, pages 3-14, Dallas, TX, September
% 20-21, 2007.
% -------------------------------------------------------------------------
% Note: The program requires Phil Sallee's MATLAB JPEG toolbox available at
% http://www.philsallee.com/
% -------------------------------------------------------------------------
%%% load the cover image
try
jobj = jpeg_read(COVER); % JPEG image structure
DCT = jobj.coef_arrays{1}; % DCT plane
catch
error('ERROR (problem with the cover image)');
end
if ALPHA>0
%%% embedding simulation
embedding_efficiency = ALPHA/invH(ALPHA); % bound on embedding efficiency
nzAC = nnz(DCT)-nnz(DCT(1:8:end,1:8:end)); % number of nonzero AC DCT coefficients
changes = ceil(ALPHA*nzAC/embedding_efficiency); % number of changes nsF5 would make on bound
changeable = (DCT~=0); % mask of all nonzero DCT coefficients in the image
changeable(1:8:end,1:8:end) = false; % do not embed into DC modes
changeable = find(changeable); % indexes of the changeable coefficients
rand('state',SEED); % initialize PRNG using given SEED
changeable = changeable(randperm(nzAC)); % create a pseudorandom walk over nonzero AC coefficients
to_be_changed = changeable(1:changes); % coefficients to be changed
DCT(to_be_changed) = DCT(to_be_changed)-sign(DCT(to_be_changed)); % decrease the absolute value of the coefficients to be changed
end
%%% save the resulting stego image
try
jobj.coef_arrays{1} = DCT;
jobj.optimize_coding = 1;
jpeg_write(jobj,STEGO);
catch
error('ERROR (problem with saving the stego image)')
end
function res = invH(y)
% inverse of the binary entropy function
to_minimize = @(x) (H(x)-y)^2;
res = fminbnd(to_minimize,eps,0.5-eps);
function res = H(x)
% binary entropy function
res = -x*log2(x)-(1-x)*log2(1-x);
|
github
|
daniellerch/aletheia-master
|
S_UNIWARD_COLOR.m
|
.m
|
aletheia-master/aletheia-octave/octave/S_UNIWARD_COLOR.m
| 7,177 |
utf_8
|
2990fdc10c4bfdb0df3a1d85f8a67b10
|
function stego = S_UNIWARD_COLOR(coverPath, payload)
% -------------------------------------------------------------------------
% Copyright (c) 2013 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | October 2012
% http://dde.binghamton.edu/download/steganography
% -------------------------------------------------------------------------
% This function simulates embedding using S-UNIWARD steganographic
% algorithm. For more deatils about the individual submodels, please see
% the publication [1].
% -------------------------------------------------------------------------
% Input: coverPath ... path to the image
% payload ..... payload in bits per pixel
% Output: stego ....... resulting image with embedded payload
% -------------------------------------------------------------------------
% PAPER
% -------------------------------------------------------------------------
sgm = 1;
%% Get 2D wavelet filters - Daubechies 8
% 1D high pass decomposition filter
hpdf = [-0.0544158422, 0.3128715909, -0.6756307363, 0.5853546837, 0.0158291053, -0.2840155430, -0.0004724846, 0.1287474266, 0.0173693010, -0.0440882539, ...
-0.0139810279, 0.0087460940, 0.0048703530, -0.0003917404, -0.0006754494, -0.0001174768];
% 1D low pass decomposition filter
lpdf = (-1).^(0:numel(hpdf)-1).*fliplr(hpdf);
% construction of 2D wavelet filters
F{1} = lpdf'*hpdf;
F{2} = hpdf'*lpdf;
F{3} = hpdf'*hpdf;
wetCost = 10^8;
%% Get embedding costs
% inicialization
cover_3ch = double(imread(coverPath));
stego = zeros(size(cover_3ch));
for index_color=1:3
cover = cover_3ch(:,:,index_color);
[k,l] = size(cover);
% add padding
padSize = max([size(F{1})'; size(F{2})'; size(F{3})']);
coverPadded = padarray(cover, [padSize padSize], 'symmetric');
xi = cell(3, 1);
for fIndex = 1:3
% compute residual
R = conv2(coverPadded, F{fIndex}, 'same');
% compute suitability
xi{fIndex} = conv2(1./(abs(R)+sgm), rot90(abs(F{fIndex}), 2), 'same');
% correct the suitability shift if filter size is even
if mod(size(F{fIndex}, 1), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [1, 0]); end;
if mod(size(F{fIndex}, 2), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [0, 1]); end;
% remove padding
xi{fIndex} = xi{fIndex}(((size(xi{fIndex}, 1)-k)/2)+1:end-((size(xi{fIndex}, 1)-k)/2), ((size(xi{fIndex}, 2)-l)/2)+1:end-((size(xi{fIndex}, 2)-l)/2));
end
% compute embedding costs \rho
rho = xi{1} + xi{2} + xi{3};
% adjust embedding costs
rho(rho > wetCost) = wetCost; % threshold on the costs
rho(isnan(rho)) = wetCost; % if all xi{} are zero threshold the cost
rhoP1 = rho;
rhoM1 = rho;
rhoP1(cover==255) = wetCost; % do not embed +1 if the pixel has max value
rhoM1(cover==0) = wetCost; % do not embed -1 if the pixel has min value
%% Embedding simulator
stego(:,:,index_color) = EmbeddingSimulator(cover, rhoP1, rhoM1, payload*numel(cover), false);
end
%% --------------------------------------------------------------------------------------------------------------------------
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
function [y] = EmbeddingSimulator(x, rhoP1, rhoM1, m, fixEmbeddingChanges)
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
if fixEmbeddingChanges == 1
%RandStream.setGlobalStream(RandStream('mt19937ar','seed',139187));
rand('state', 139187);
else
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',sum(100*clock)));
rand('state', sum(100*clock));
end
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
end
|
github
|
daniellerch/aletheia-master
|
NSF5_COLOR.m
|
.m
|
aletheia-master/aletheia-octave/octave/NSF5_COLOR.m
| 3,331 |
utf_8
|
47c5da642adfa3b7099c404ade7a6a67
|
function [STEGO,embedding_efficiency,changes] = NSF5_COLOR(cover, payload, stego)
% -------------------------------------------------------------------------
% Contact: [email protected] | June 2011
% -------------------------------------------------------------------------
% This program simulates the embedding impact of the steganographic
% algorithm nsF5 [1] as if the best possible coding was used. Please, visit
% the webpage http://dde.binghamton.edu/download/nsf5simulator for more
% information.
% -------------------------------------------------------------------------
% Input:
% COVER - cover image (grayscale JPEG image)
% STEGO - resulting stego image that will be created
% ALPHA - relative payload in terms of bits per nonzero AC DCT coefficient
% SEED - PRNG seed for the random walk over the coefficients
% Output:
% nzAC - number of nonzero AC DCT coefficients in the cover image
% embedding_efficiency - bound on embedding efficiency used for simulation
% changes - number of changes made
% -------------------------------------------------------------------------
% References:
% [1] J. Fridrich, T. Pevny, and J. Kodovsky, Statistically undetectable
% JPEG steganography: Dead ends, challenges, and opportunities. In J.
% Dittmann and J. Fridrich, editors, Proceedings of the 9th ACM
% Multimedia & Security Workshop, pages 3-14, Dallas, TX, September
% 20-21, 2007.
% -------------------------------------------------------------------------
% Note: The program requires Phil Sallee's MATLAB JPEG toolbox available at
% http://www.philsallee.com/
% -------------------------------------------------------------------------
%%% load the cover image
COVER=jpeg_read(cover);
STEGO=COVER;
for index_color=1:3
DCT=COVER.coef_arrays{index_color};
ALPHA=1;
if ALPHA>0
%%% embedding simulation
embedding_efficiency = payload/invH(payload); % bound on embedding efficiency
nAC = nnz(DCT); % number of nonzero AC DCT coefficients
nzAC = nnz(DCT)-nnz(DCT(1:8:end,1:8:end)); % number of nonzero AC DCT coefficients
changes = ceil(payload*nzAC/embedding_efficiency); % number of changes nsF5 would make on bound
ALPHA=changes/nzAC;
embedding_efficiency = ALPHA/invH(ALPHA); % bound on embedding efficiency
changeable = (DCT~=0); % mask of all nonzero DCT coefficients in the image
changeable(1:8:end,1:8:end) = false; % do not embed into DC modes
changeable = find(changeable); % indexes of the changeable coefficients
% rand('state',SEED); % initialize PRNG using given SEED
changeable = changeable(randperm(nzAC)); % create a pseudorandom walk over nonzero AC coefficients
to_be_changed = changeable(1:changes); % coefficients to be changed
DCT(to_be_changed) = DCT(to_be_changed)-sign(DCT(to_be_changed)); % decrease the absolute value of the coefficients to be changed
end
STEGO.coef_arrays{index_color}=DCT;
end
try
jpeg_write(STEGO, stego);
catch
error('ERROR (problem with saving the stego image)')
end
function res = invH(y)
% inverse of the binary entropy function
to_minimize = @(x) (H(x)-y)^2;
res = fminbnd(to_minimize,eps,0.5-eps);
function res = H(x)
% binary entropy function
res = -x*log2(x)-(1-x)*log2(1-x);
|
github
|
daniellerch/aletheia-master
|
AUMP.m
|
.m
|
aletheia-master/aletheia-octave/octave/AUMP.m
| 2,725 |
utf_8
|
45e5662031d19b8dff0f7251355cf3bf
|
function beta = AUMP(path, channel)
%
% AUMP LSB detector as described by L. Fillatre, "Adaptive Steganalysis of
% Least Significant Bit Replacement in Grayscale Natural Images", IEEE
% TSP, October 2011.
%
% X = image to be analyzed
% m = pixel block size
% d = q - 1 = polynomial degree for fitting (predictor)
% beta = \hat{\Lambda}^\star(X) detection statistic
%
m = 16
d = 5
X = double(imread(path));
if(size(size(X))!=2)
X=X(:,:,channel);
end
%X = double(X);
[Xpred,~,w] = Pred_aump(X,m,d); % Polynomial prediction, w = weights
r = X - Xpred; % Residual
Xbar = X + 1 - 2 * mod(X,2); % Flip all LSBs
beta = sum(sum(w.*(X-Xbar).*r)); % Detection statistic
function [Xpred,S,w] = Pred_aump(X,m,d)
%
% Pixel predictor by fitting local polynomial of degree d = q - 1 to
% m pixels, m must divide the number of pixels in the row.
% OUTPUT: predicted image Xpred, local variances S, weights w.
%
% Implemention follows the description in: L. Fillantre, "Adaptive
% Steganalysis of Least Significant Bit Replacement in Grayscale Images",
% IEEE Trans. on Signal Processing, 2011.
%
sig_th = 1; % Threshold for sigma for numerical stability
q = d + 1; % q = number of parameters per block
Kn = numel(X)/m; % Number of blocks of m pixels
Y = zeros(m,Kn); % Y will hold block pixel values as columns
S = zeros(size(X)); % Pixel variance
Xpred = zeros(size(X)); % Predicted image
H = zeros(m,q); % H = Vandermonde matrix for the LSQ fit
x1 = (1:m)/m;
for i = 1 : q, H(:,i) = (x1').^(i-1); end
for i = 1 : m % Form Kn blocks of m pixels (row-wise) as
aux = X(:,i:m:end); % columns of Y
Y(i,:) = aux(:);
end
p = H\Y; % Polynomial fit
Ypred = H*p; % Predicted Y
for i = 1 : m % Predicted X
Xpred(:,i:m:end) = reshape(Ypred(i,:),size(X(:,i:m:end))); % Xpred = l_k in the paper
end
sig2 = sum((Y - Ypred).^2) / (m-q); % sigma_k_hat in the paper (variance in kth block)
sig2 = max(sig_th^2 * ones(size(sig2)),sig2); % Assuring numerical stability
% le01 = find(sig2 < sig_th^2);
% sig2(le01) = (0.1 + sqrt(sig2(le01))).^2; % An alternative way of "scaling" to guarantee num. stability
Sy = ones(m,1) * sig2; % Variance of all pixels (order as in Y)
for i = 1 : m % Reshaping the variance Sy to size of X
S(:,i:m:end) = reshape(Sy(i,:),size(X(:,i:m:end)));
end
s_n2 = Kn / sum(1./sig2); % Global variance sigma_n_bar_hat^2 in the paper
w = sqrt( s_n2 / (Kn * (m-q)) ) ./ S; % Weights
|
github
|
daniellerch/aletheia-master
|
SRMQ1.m
|
.m
|
aletheia-master/aletheia-octave/octave/SRMQ1.m
| 55,091 |
utf_8
|
33d050deb6f97a8dae9b351e56119024
|
function f = SRMQ1(IMAGE, channel)
% -------------------------------------------------------------------------
% Copyright (c) 2011 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | November 2011
% http://dde.binghamton.edu/download/feature_extractors
% -------------------------------------------------------------------------
% Extracts 39 submodels presented in [1] -- only q=1c. All features are
% calculated in the spatial domain and are stored in a structured variable
% 'f'. For more deatils about the individual submodels, please see the
% publication [1]. Total dimensionality of all 39 submodels is 12,753.
% -------------------------------------------------------------------------
% Input: IMAGE ... path to the image (can be JPEG)
% Output: f ...... extracted SRMQ1 features in a structured format
% -------------------------------------------------------------------------
% [1] Rich Models for Steganalysis of Digital Images, J. Fridrich and J.
% Kodovsky, IEEE Transactions on Information Forensics and Security, 2011.
% Under review.
% -------------------------------------------------------------------------
X = double(imread(IMAGE));
if(size(size(I))==2)
X=I(:,:,channel)
end
f = post_processing(all1st(X,1),'f1',1); % 1st order
f = post_processing(all2nd(X,2),'f2',1,f); % 2nd order
f = post_processing(all3rd(X,3),'f3',1,f); % 3rd order
f = post_processing(all3x3(X,4),'f3x3',1,f); % 3x3
f = post_processing(all5x5(X,12),'f5x5',1,f); % 5x5
function RESULT = post_processing(DATA,f,q,RESULT)
Ss = fieldnames(DATA);
for Sid = 1:length(Ss)
VARNAME = [f '_' Ss{Sid} '_q' strrep(num2str(q),'.','')];
eval(['RESULT.' VARNAME ' = reshape(single(DATA.' Ss{Sid} '),1,[]);' ])
end
% symmetrize
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='s', continue; end
[T,N,Q] = parse_feaname(name);
if strcmp(T,''), continue; end
% symmetrization
if strcmp(N(1:3),'min') || strcmp(N(1:3),'max')
% minmax symmetrization
OUT = ['s' T(2:end) '_minmax' N(4:end) '_' Q];
if isfield(RESULT,OUT), continue; end
eval(['Fmin = RESULT.' strrep(name,'max','min') ';']);
eval(['Fmax = RESULT.' strrep(name,'min','max') ';']);
F = symfea([Fmin Fmax]',2,4,'mnmx')'; %#ok<*NASGU>
eval(['RESULT.' OUT ' = single(F);' ]);
elseif strcmp(N(1:4),'spam')
% spam symmetrization
OUT = ['s' T(2:end) '_' N '_' Q];
if isfield(RESULT,OUT), continue; end
eval(['Fold = RESULT.' name ';']);
F = symm1(Fold',2,4)';
eval(['RESULT.' OUT ' = single(F);' ]);
end
end
% delete RESULT.f*
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='f'
RESULT = rmfield(RESULT,name);
end
end
% merge spam features
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
[T,N,Q] = parse_feaname(name);
if ~strcmp(N(1:4),'spam'), continue; end
if strcmp(T,''), continue; end
if strcmp(N(end),'v')||(strcmp(N,'spam11')&&strcmp(T,'s5x5'))
elseif strcmp(N(end),'h')
% h+v union
OUT = [T '_' N 'v_' Q ];
if isfield(RESULT,OUT), continue; end
name2 = strrep(name,'h_','v_');
eval(['Fh = RESULT.' name ';']);
eval(['Fv = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [Fh Fv];']);
RESULT = rmfield(RESULT,name);
RESULT = rmfield(RESULT,name2);
elseif strcmp(N,'spam11')
% KBKV creation
OUT = ['s35_' N '_' Q];
if isfield(RESULT,OUT), continue; end
name1 = strrep(name,'5x5','3x3');
name2 = strrep(name,'3x3','5x5');
if ~isfield(RESULT,name1), continue; end
if ~isfield(RESULT,name2), continue; end
eval(['F_KB = RESULT.' name1 ';']);
eval(['F_KV = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [F_KB F_KV];']);
RESULT = rmfield(RESULT,name1);
RESULT = rmfield(RESULT,name2);
end
end
function [T,N,Q] = parse_feaname(name)
[T,N,Q] = deal('');
P = strfind(name,'_'); if length(P)~=2, return; end
T = name(1:P(1)-1);
N = name(P(1)+1:P(2)-1);
Q = name(P(2)+1:end);
function g = all1st(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 1st-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam14h
% 1b) spam14v (orthogonal-spam)
% 1c) minmax22v
% 1d) minmax24
% 1e) minmax34v
% 1f) minmax41
% 1g) minmax34
% 1h) minmax48h
% 1i) minmax54
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All odd residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals --
% -- they should "stick out" (trcet) in the same direction as
% the 1st order ones. For example, for the 3rd order:
%
% RU = -X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1); ... etc.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
% This function calls Cooc.m and Quant.m
[M N] = size(X); [I,J,T,order] = deal(2:M-1,2:N-1,2,4);
% Variable names are self-explanatory (R = right, U = up, L = left, D = down)
[R,L,U,D] = deal(X(I,J+1)-X(I,J),X(I,J-1)-X(I,J),X(I-1,J)-X(I,J),X(I+1,J)-X(I,J));
[Rq,Lq,Uq,Dq] = deal(Quant(R,q,T),Quant(L,q,T),Quant(U,q,T),Quant(D,q,T));
[RU,LU,RD,LD] = deal(X(I-1,J+1)-X(I,J),X(I-1,J-1)-X(I,J),X(I+1,J+1)-X(I,J),X(I+1,J-1)-X(I,J));
[RUq,RDq,LUq,LDq] = deal(Quant(RU,q,T),Quant(RD,q,T),Quant(LU,q,T),Quant(LD,q,T));
% minmax22h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical.
[RLq_min,UDq_min,RLq_max,UDq_max] = deal(min(Rq,Lq),min(Uq,Dq),max(Rq,Lq),max(Uq,Dq));
g.min22h = reshape(Cooc(RLq_min,order,'hor',T) + Cooc(UDq_min,order,'ver',T),[],1);
g.max22h = reshape(Cooc(RLq_max,order,'hor',T) + Cooc(UDq_max,order,'ver',T),[],1);
% minmax34h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[Uq_min,Rq_min,Dq_min,Lq_min] = deal(min(min(Lq,Uq),Rq),min(min(Uq,Rq),Dq),min(min(Rq,Dq),Lq),min(min(Dq,Lq),Uq));
[Uq_max,Rq_max,Dq_max,Lq_max] = deal(max(max(Lq,Uq),Rq),max(max(Uq,Rq),Dq),max(max(Rq,Dq),Lq),max(max(Dq,Lq),Uq));
g.min34h = reshape(Cooc([Uq_min;Dq_min],order,'hor',T) + Cooc([Lq_min Rq_min],order,'ver',T),[],1);
g.max34h = reshape(Cooc([Uq_max;Dq_max],order,'hor',T) + Cooc([Rq_max Lq_max],order,'ver',T),[],1);
% spam14h/v -- to be symmetrized as spam, directional, hv-nonsymmetrical
g.spam14h = reshape(Cooc(Rq,order,'hor',T) + Cooc(Uq,order,'ver',T),[],1);
g.spam14v = reshape(Cooc(Rq,order,'ver',T) + Cooc(Uq,order,'hor',T),[],1);
% minmax22v -- to be symmetrized as mnmx, directional, hv-nonsymmetrical. Good with higher-order residuals! Note: 22h is bad (too much neighborhood overlap).
g.min22v = reshape(Cooc(RLq_min,order,'ver',T) + Cooc(UDq_min,order,'hor',T),[],1);
g.max22v = reshape(Cooc(RLq_max,order,'ver',T) + Cooc(UDq_max,order,'hor',T),[],1);
% minmax24 -- to be symmetrized as mnmx, directional, hv-symmetrical. Darn good, too.
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(Rq,Uq),min(Rq,Dq),min(Lq,Uq),min(Lq,Dq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(Rq,Uq),max(Rq,Dq),max(Lq,Uq),max(Lq,Dq));
g.min24 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max24 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax34v -- v works well, h does not, to be symmetrized as mnmx, directional, hv-nonsymmetrical
g.min34v = reshape(Cooc([Uq_min Dq_min],order,'ver',T) + Cooc([Rq_min;Lq_min],order,'hor',T),[],1);
g.max34v = reshape(Cooc([Uq_max Dq_max],order,'ver',T) + Cooc([Rq_max;Lq_max],order,'hor',T),[],1);
% minmax41 -- to be symmetrized as mnmx, non-directional, hv-symmetrical
[R_min,R_max] = deal(min(RLq_min,UDq_min),max(RLq_max,UDq_max));
g.min41 = reshape(Cooc(R_min,order,'hor',T) + Cooc(R_min,order,'ver',T),[],1);
g.max41 = reshape(Cooc(R_max,order,'hor',T) + Cooc(R_max,order,'ver',T),[],1);
% minmax34 -- good, to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(RUq_min,RUq),min(RDq_min,RDq),min(LUq_min,LUq),min(LDq_min,LDq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(RUq_max,RUq),max(RDq_max,RDq),max(LUq_max,LUq),max(LDq_max,LDq));
g.min34 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max34 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax48h -- h better than v, to be symmetrized as mnmx, directional, hv-nonsymmetrical. 48v is almost as good as 48h; for 3rd-order but weaker for 1st-order. Here, I am outputting both but Figure 1 in our paper lists only 48h.
[RUq_min2,RDq_min2,LDq_min2,LUq_min2] = deal(min(RUq_min,LUq),min(RDq_min,RUq),min(LDq_min,RDq),min(LUq_min,LDq));
[RUq_min3,RDq_min3,LDq_min3,LUq_min3] = deal(min(RUq_min,RDq),min(RDq_min,LDq),min(LDq_min,LUq),min(LUq_min,RUq));
g.min48h = reshape(Cooc([RUq_min2;LDq_min2;RDq_min3;LUq_min3],order,'hor',T) + Cooc([RDq_min2 LUq_min2 RUq_min3 LDq_min3],order,'ver',T),[],1);
g.min48v = reshape(Cooc([RDq_min2;LUq_min2;RUq_min3;LDq_min3],order,'hor',T) + Cooc([RUq_min2 LDq_min2 RDq_min3 LUq_min3],order,'ver',T),[],1);
[RUq_max2,RDq_max2,LDq_max2,LUq_max2] = deal(max(RUq_max,LUq),max(RDq_max,RUq),max(LDq_max,RDq),max(LUq_max,LDq));
[RUq_max3,RDq_max3,LDq_max3,LUq_max3] = deal(max(RUq_max,RDq),max(RDq_max,LDq),max(LDq_max,LUq),max(LUq_max,RUq));
g.max48h = reshape(Cooc([RUq_max2;LDq_max2;RDq_max3;LUq_max3],order,'hor',T) + Cooc([RDq_max2 LUq_max2 RUq_max3 LDq_max3],order,'ver',T),[],1);
g.max48v = reshape(Cooc([RDq_max2;LUq_max2;RUq_max3;LDq_max3],order,'hor',T) + Cooc([RUq_max2 LDq_max2 RDq_max3 LUq_max3],order,'ver',T),[],1);
% minmax54 -- to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min4,RDq_min4,LDq_min4,LUq_min4] = deal(min(RUq_min2,RDq),min(RDq_min2,LDq),min(LDq_min2,LUq),min(LUq_min2,RUq));
[RUq_min5,RDq_min5,LDq_min5,LUq_min5] = deal(min(RUq_min3,LUq),min(RDq_min3,RUq),min(LDq_min3,RDq),min(LUq_min3,LDq));
g.min54 = reshape(Cooc([RUq_min4;LDq_min4;RDq_min5;LUq_min5],order,'hor',T) + Cooc([RDq_min4 LUq_min4 RUq_min5 LDq_min5],order,'ver',T),[],1);
[RUq_max4,RDq_max4,LDq_max4,LUq_max4] = deal(max(RUq_max2,RDq),max(RDq_max2,LDq),max(LDq_max2,LUq),max(LUq_max2,RUq));
[RUq_max5,RDq_max5,LDq_max5,LUq_max5] = deal(max(RUq_max3,LUq),max(RDq_max3,RUq),max(LDq_max3,RDq),max(LUq_max3,LDq));
g.max54 = reshape(Cooc([RUq_max4;LDq_max4;RDq_max5;LUq_max5],order,'hor',T) + Cooc([RDq_max4 LUq_max4 RUq_max5 LDq_max5],order,'ver',T),[],1);
function g = all2nd(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 2nd-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam12h
% 1b) spam12v (orthogonal-spam)
% 1c) minmax21
% 1d) minmax41
% 1e) minmax24h (24v is also outputted but not listed in Figure 1)
% 1f) minmax32
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All even residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
%
% This function calls Residual.m, Cooc.m, and Quant.m
[T,order] = deal(2,4);
% 2nd-order residuals are implemented using Residual.m
[Dh,Dv,Dd,Dm] = deal(Residual(X,2,'hor'),Residual(X,2,'ver'),Residual(X,2,'diag'),Residual(X,2,'mdiag'));
[Yh,Yv,Yd,Ym] = deal(Quant(Dh,q,T),Quant(Dv,q,T),Quant(Dd,q,T),Quant(Dm,q,T));
% spam12h/v
g.spam12h = reshape(Cooc(Yh,order,'hor',T) + Cooc(Yv,order,'ver',T),[],1);
g.spam12v = reshape(Cooc(Yh,order,'ver',T) + Cooc(Yv,order,'hor',T),[],1);
% minmax21
[Dmin,Dmax] = deal(min(Yh,Yv),max(Yh,Yv));
g.min21 = reshape(Cooc(Dmin,order,'hor',T) + Cooc(Dmin,order,'ver',T),[],1);
g.max21 = reshape(Cooc(Dmax,order,'hor',T) + Cooc(Dmax,order,'ver',T),[],1);
% minmax41
[Dmin2,Dmax2] = deal(min(Dmin,min(Yd,Ym)),max(Dmax,max(Yd,Ym)));
g.min41 = reshape(Cooc(Dmin2,order,'hor',T) + Cooc(Dmin2,order,'ver',T),[],1);
g.max41 = reshape(Cooc(Dmax2,order,'hor',T) + Cooc(Dmax2,order,'ver',T),[],1);
% minmax32 -- good, directional, hv-symmetrical, to be symmetrized as mnmx
[RUq_min,RDq_min] = deal(min(Dmin,Ym),min(Dmin,Yd));
[RUq_max,RDq_max] = deal(max(Dmax,Ym),max(Dmax,Yd));
g.min32 = reshape(Cooc([RUq_min;RDq_min],order,'hor',T) + Cooc([RUq_min RDq_min],order,'ver',T),[],1);
g.max32 = reshape(Cooc([RUq_max;RDq_max],order,'hor',T) + Cooc([RUq_max RDq_max],order,'ver',T),[],1);
% minmax24h,v -- both "not bad," h slightly better, directional, hv-nonsymmetrical, to be symmetrized as mnmx
[RUq_min2,RDq_min2,RUq_min3,LUq_min3] = deal(min(Ym,Yh),min(Yd,Yh),min(Ym,Yv),min(Yd,Yv));
g.min24h = reshape(Cooc([RUq_min2;RDq_min2],order,'hor',T)+Cooc([RUq_min3 LUq_min3],order,'ver',T),[],1);
g.min24v = reshape(Cooc([RUq_min2 RDq_min2],order,'ver',T)+Cooc([RUq_min3;LUq_min3],order,'hor',T),[],1);
[RUq_max2,RDq_max2,RUq_max3,LUq_max3] = deal(max(Ym,Yh),max(Yd,Yh),max(Ym,Yv),max(Yd,Yv));
g.max24h = reshape(Cooc([RUq_max2;RDq_max2],order,'hor',T)+Cooc([RUq_max3 LUq_max3],order,'ver',T),[],1);
g.max24v = reshape(Cooc([RUq_max2 RDq_max2],order,'ver',T)+Cooc([RUq_max3;LUq_max3],order,'hor',T),[],1);
function g = all3rd(X,q)
%
% X must be a matrix of doubles or singles (the image) and q is the
% quantization step (any positive number).
%
% Recommended values of q are c, 1.5c, 2c, where c is the central
% coefficient in the differential (at X(I,J)).
%
% This function outputs co-occurrences of ALL 3rd-order residuals
% listed in Figure 1 in our journal HUGO paper (version from June 14),
% including the naming convention.
%
% List of outputted features:
%
% 1a) spam14h
% 1b) spam14v (orthogonal-spam)
% 1c) minmax22v
% 1d) minmax24
% 1e) minmax34v
% 1f) minmax41
% 1g) minmax34
% 1h) minmax48h
% 1i) minmax54
%
% Naming convention:
%
% name = {type}{f}{sigma}{scan}
% type \in {spam, minmax}
% f \in {1,2,3,4,5} number of filters that are "minmaxed"
% sigma \in {1,2,3,4,8} symmetry index
% scan \in {h,v,\emptyset} scan of the cooc matrix (empty = sum of both
% h and v scans).
%
% All odd residuals are implemented the same way simply by
% narrowing the range for I and J and replacing the residuals --
% -- they should "stick out" (trcet) in the same direction as
% the 1st order ones. For example, for the 3rd order:
%
% RU = -X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1); ... etc.
%
% Note1: The term X(I,J) should always have the "-" sign.
% Note2: This script does not include s, so, cout, cin versions (weak).
[M N] = size(X); [I,J,T,order] = deal(3:M-2,3:N-2,2,4);
[R,L,U,D] = deal(-X(I,J+2)+3*X(I,J+1)-3*X(I,J)+X(I,J-1),-X(I,J-2)+3*X(I,J-1)-3*X(I,J)+X(I,J+1),-X(I-2,J)+3*X(I-1,J)-3*X(I,J)+X(I+1,J),-X(I+2,J)+3*X(I+1,J)-3*X(I,J)+X(I-1,J));
[Rq,Lq,Uq,Dq] = deal(Quant(R,q,T),Quant(L,q,T),Quant(U,q,T),Quant(D,q,T));
[RU,LU,RD,LD] = deal(-X(I-2,J+2)+3*X(I-1,J+1)-3*X(I,J)+X(I+1,J-1),-X(I-2,J-2)+3*X(I-1,J-1)-3*X(I,J)+X(I+1,J+1),-X(I+2,J+2)+3*X(I+1,J+1)-3*X(I,J)+X(I-1,J-1),-X(I+2,J-2)+3*X(I+1,J-1)-3*X(I,J)+X(I-1,J+1));
[RUq,RDq,LUq,LDq] = deal(Quant(RU,q,T),Quant(RD,q,T),Quant(LU,q,T),Quant(LD,q,T));
% minmax22h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[RLq_min,UDq_min] = deal(min(Rq,Lq),min(Uq,Dq));
[RLq_max,UDq_max] = deal(max(Rq,Lq),max(Uq,Dq));
g.min22h = reshape(Cooc(RLq_min,order,'hor',T) + Cooc(UDq_min,order,'ver',T),[],1);
g.max22h = reshape(Cooc(RLq_max,order,'hor',T) + Cooc(UDq_max,order,'ver',T),[],1);
% minmax34h -- to be symmetrized as mnmx, directional, hv-nonsymmetrical
[Uq_min,Rq_min,Dq_min,Lq_min] = deal(min(RLq_min,Uq),min(UDq_min,Rq),min(RLq_min,Dq),min(UDq_min,Lq));
[Uq_max,Rq_max,Dq_max,Lq_max] = deal(max(RLq_max,Uq),max(UDq_max,Rq),max(RLq_max,Dq),max(UDq_max,Lq));
g.min34h = reshape(Cooc([Uq_min;Dq_min],order,'hor',T)+Cooc([Rq_min Lq_min],order,'ver',T),[],1);
g.max34h = reshape(Cooc([Uq_max;Dq_max],order,'hor',T)+Cooc([Rq_max Lq_max],order,'ver',T),[],1);
% spam14h,v -- to be symmetrized as spam, directional, hv-nonsymmetrical
g.spam14h = reshape(Cooc(Rq,order,'hor',T) + Cooc(Uq,order,'ver',T),[],1);
g.spam14v = reshape(Cooc(Rq,order,'ver',T) + Cooc(Uq,order,'hor',T),[],1);
% minmax22v -- to be symmetrized as mnmx, directional, hv-nonsymmetrical. Good with higher-order residuals! Note: 22h is bad (too much neighborhood overlap).
g.min22v = reshape(Cooc(RLq_min,order,'ver',T) + Cooc(UDq_min,order,'hor',T),[],1);
g.max22v = reshape(Cooc(RLq_max,order,'ver',T) + Cooc(UDq_max,order,'hor',T),[],1);
% minmax24 -- to be symmetrized as mnmx, directional, hv-symmetrical Note: Darn good, too.
[RUq_min,RDq_min,LUq_min,LDq_min] = deal(min(Rq,Uq),min(Rq,Dq),min(Lq,Uq),min(Lq,Dq));
[RUq_max,RDq_max,LUq_max,LDq_max] = deal(max(Rq,Uq),max(Rq,Dq),max(Lq,Uq),max(Lq,Dq));
g.min24 = reshape(Cooc([RUq_min;RDq_min;LUq_min;LDq_min],order,'hor',T) + Cooc([RUq_min RDq_min LUq_min LDq_min],order,'ver',T),[],1);
g.max24 = reshape(Cooc([RUq_max;RDq_max;LUq_max;LDq_max],order,'hor',T) + Cooc([RUq_max RDq_max LUq_max LDq_max],order,'ver',T),[],1);
% minmax34v -- v works well, h does not, to be symmetrized as mnmx, directional, hv-nonsymmetrical
g.min34v = reshape(Cooc([Uq_min Dq_min],order,'ver',T) + Cooc([Rq_min;Lq_min],order,'hor',T),[],1);
g.max34v = reshape(Cooc([Uq_max Dq_max],order,'ver',T) + Cooc([Rq_max;Lq_max],order,'hor',T),[],1);
% minmax41 -- unknown performance as of 6/14/11, to be symmetrized as mnmx, non-directional, hv-symmetrical
[R_min,R_max] = deal(min(RUq_min,LDq_min),max(RUq_max,LDq_max));
g.min41 = reshape(Cooc(R_min,order,'hor',T) + Cooc(R_min,order,'ver',T),[],1);
g.max41 = reshape(Cooc(R_max,order,'hor',T) + Cooc(R_max,order,'ver',T),[],1);
% minmax34 -- good, to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min2,RDq_min2,LUq_min2,LDq_min2] = deal(min(RUq_min,RUq),min(RDq_min,RDq),min(LUq_min,LUq),min(LDq_min,LDq));
[RUq_max2,RDq_max2,LUq_max2,LDq_max2] = deal(max(RUq_max,RUq),max(RDq_max,RDq),max(LUq_max,LUq),max(LDq_max,LDq));
g.min34 = reshape(Cooc([RUq_min2;RDq_min2;LUq_min2;LDq_min2],order,'hor',T) + Cooc([RUq_min2 RDq_min2 LUq_min2 LDq_min2],order,'ver',T),[],1);
g.max34 = reshape(Cooc([RUq_max2;RDq_max2;LUq_max2;LDq_max2],order,'hor',T) + Cooc([RUq_max2 RDq_max2 LUq_max2 LDq_max2],order,'ver',T),[],1);
% minmax48h -- h better than v, to be symmetrized as mnmx, directional, hv-nonsymmetrical. 48v is almost as good as 48h for 3rd-order but weaker for 1st-order. Here, I am outputting both but Figure 1 in our paper lists only 48h.
[RUq_min3,RDq_min3,LDq_min3,LUq_min3] = deal(min(RUq_min2,LUq),min(RDq_min2,RUq),min(LDq_min2,RDq),min(LUq_min2,LDq));
[RUq_min4,RDq_min4,LDq_min4,LUq_min4] = deal(min(RUq_min2,RDq),min(RDq_min2,LDq),min(LDq_min2,LUq),min(LUq_min2,RUq));
g.min48h = reshape(Cooc([RUq_min3;LDq_min3;RDq_min4;LUq_min4],order,'hor',T)+Cooc([RDq_min3 LUq_min3 RUq_min4 LDq_min4],order,'ver',T),[],1);
g.min48v = reshape(Cooc([RUq_min3 LDq_min3 RDq_min4 LUq_min4],order,'ver',T)+Cooc([RDq_min3;LUq_min3;RUq_min4;LDq_min4],order,'hor',T),[],1);
[RUq_max3,RDq_max3,LDq_max3,LUq_max3] = deal(max(RUq_max2,LUq),max(RDq_max2,RUq),max(LDq_max2,RDq),max(LUq_max2,LDq));
[RUq_max4,RDq_max4,LDq_max4,LUq_max4] = deal(max(RUq_max2,RDq),max(RDq_max2,LDq),max(LDq_max2,LUq),max(LUq_max2,RUq));
g.max48h = reshape(Cooc([RUq_max3;LDq_max3;RDq_max4;LUq_max4],order,'hor',T)+Cooc([RDq_max3 LUq_max3 RUq_max4 LDq_max4],order,'ver',T),[],1);
g.max48v = reshape(Cooc([RUq_max3 LDq_max3 RDq_max4 LUq_max4],order,'ver',T)+Cooc([RDq_max3;LUq_max3;RUq_max4;LDq_max4],order,'hor',T),[],1);
% minmax54 -- to be symmetrized as mnmx, directional, hv-symmetrical
[RUq_min5,RDq_min5,LDq_min5,LUq_min5] = deal(min(RUq_min3,RDq),min(RDq_min3,LDq),min(LDq_min3,LUq),min(LUq_min3,RUq));
[RUq_max5,RDq_max5,LDq_max5,LUq_max5] = deal(max(RUq_max3,RDq),max(RDq_max3,LDq),max(LDq_max3,LUq),max(LUq_max3,RUq));
g.min54 = reshape(Cooc([RUq_min5;LDq_min5;RDq_min5;LUq_min5],order,'hor',T) + Cooc([RDq_min5 LUq_min5 RUq_min5 LDq_min5],order,'ver',T),[],1);
g.max54 = reshape(Cooc([RUq_max5;LDq_max5;RDq_max5;LUq_max5],order,'hor',T) + Cooc([RDq_max5 LUq_max5 RUq_max5 LDq_max5],order,'ver',T),[],1);
function g = all3x3(X,q)
% This function outputs co-occurrences of ALL residuals based on the
% KB kernel and its "halves" (EDGE residuals) as listed in Figure 1
% in our journal HUGO paper (version from June 14), including the naming
% convention.
[T,order] = deal(2,4);
% spam11 (old name KB residual), good, non-directional, hv-symmetrical, to be symmetrized as spam
D = Residual(X,2,'KB'); Y = Quant(D,q,T);
g.spam11 = reshape(Cooc(Y,order,'hor',T) + Cooc(Y,order,'ver',T),[],1);
% EDGE residuals
D = Residual(X,2,'edge-h');Du = D(:,1:size(D,2)/2);Db = D(:,size(D,2)/2+1:end);
D = Residual(X,2,'edge-v');Dl = D(:,1:size(D,2)/2);Dr = D(:,size(D,2)/2+1:end);
[Yu,Yb,Yl,Yr] = deal(Quant(Du,q,T),Quant(Db,q,T),Quant(Dl,q,T),Quant(Dr,q,T));
% spam14h,v not bad, directional, hv-nonsym, to be symmetrized as spam
g.spam14v = reshape(Cooc([Yu Yb],order,'ver',T) + Cooc([Yl;Yr],order,'hor',T),[],1);
g.spam14h = reshape(Cooc([Yu;Yb],order,'hor',T) + Cooc([Yl Yr],order,'ver',T),[],1);
% minmax24 -- EXCELLENT, directional, hv-sym, to be symmetrized as mnmx
[Dmin1,Dmin2,Dmin3,Dmin4] = deal(min(Yu,Yl),min(Yb,Yr),min(Yu,Yr),min(Yb,Yl));
g.min24 = reshape(Cooc([Dmin1 Dmin2 Dmin3 Dmin4],order,'ver',T) + Cooc([Dmin1;Dmin2;Dmin3;Dmin4],order,'hor',T),[],1);
[Dmax1,Dmax2,Dmax3,Dmax4] = deal(max(Yu,Yl),max(Yb,Yr),max(Yu,Yr),max(Yb,Yl));
g.max24 = reshape(Cooc([Dmax1 Dmax2 Dmax3 Dmax4],order,'ver',T) + Cooc([Dmax1;Dmax2;Dmax3;Dmax4],order,'hor',T),[],1);
% minmax22 - hv-nonsymmetrical
% min22h -- good, to be symmetrized as mnmx, directional, hv-nonsymmetrical
% min22v -- EXCELLENT - to be symmetrized as mnmx, directional,
[UEq_min,REq_min] = deal(min(Yu,Yb),min(Yr,Yl));
g.min22h = reshape(Cooc(UEq_min,order,'hor',T) + Cooc(REq_min,order,'ver',T),[],1);
g.min22v = reshape(Cooc(UEq_min,order,'ver',T) + Cooc(REq_min,order,'hor',T),[],1);
[UEq_max,REq_max] = deal(max(Yu,Yb),max(Yr,Yl));
g.max22h = reshape(Cooc(UEq_max,order,'hor',T) + Cooc(REq_max,order,'ver',T),[],1);
g.max22v = reshape(Cooc(UEq_max,order,'ver',T) + Cooc(REq_max,order,'hor',T),[],1);
% minmax41 -- good, non-directional, hv-sym, to be symmetrized as mnmx
[Dmin5,Dmax5] = deal(min(Dmin1,Dmin2),max(Dmax1,Dmax2));
g.min41 = reshape(Cooc(Dmin5,order,'ver',T) + Cooc(Dmin5,order,'hor',T),[],1);
g.max41 = reshape(Cooc(Dmax5,order,'ver',T) + Cooc(Dmax5,order,'hor',T),[],1);
function g = all5x5(X,q)
% This function outputs co-occurrences of ALL residuals based on the
% KV kernel and its "halves" (EDGE residuals) as listed in Figure 1
% in our journal HUGO paper (version from June 14), including the naming
% convention.
[M N] = size(X); [I,J,T,order] = deal(3:M-2,3:N-2,2,4);
% spam11 (old name KV residual), good, non-directional, hv-symmetrical, to be symmetrized as spam
D = Residual(X,3,'KV'); Y = Quant(D,q,T);
g.spam11 = reshape(Cooc(Y,order,'hor',T) + Cooc(Y,order,'ver',T),[],1);
% EDGE residuals
Du = 8*X(I,J-1)+8*X(I-1,J)+8*X(I,J+1)-6*X(I-1,J-1)-6*X(I-1,J+1)-2*X(I,J-2)-2*X(I,J+2)-2*X(I-2,J)+2*X(I-1,J-2)+2*X(I-2,J-1)+2*X(I-2,J+1)+2*X(I-1,J+2)-X(I-2,J-2)-X(I-2,J+2)-12*X(I,J);
Dr = 8*X(I-1,J)+8*X(I,J+1)+8*X(I+1,J)-6*X(I-1,J+1)-6*X(I+1,J+1)-2*X(I-2,J)-2*X(I+2,J)-2*X(I,J+2)+2*X(I-2,J+1)+2*X(I-1,J+2)+2*X(I+1,J+2)+2*X(I+2,J+1)-X(I-2,J+2)-X(I+2,J+2)-12*X(I,J);
Db = 8*X(I,J+1)+8*X(I+1,J)+8*X(I,J-1)-6*X(I+1,J+1)-6*X(I+1,J-1)-2*X(I,J-2)-2*X(I,J+2)-2*X(I+2,J)+2*X(I+1,J+2)+2*X(I+2,J+1)+2*X(I+2,J-1)+2*X(I+1,J-2)-X(I+2,J+2)-X(I+2,J-2)-12*X(I,J);
Dl = 8*X(I+1,J)+8*X(I,J-1)+8*X(I-1,J)-6*X(I+1,J-1)-6*X(I-1,J-1)-2*X(I-2,J)-2*X(I+2,J)-2*X(I,J-2)+2*X(I+2,J-1)+2*X(I+1,J-2)+2*X(I-1,J-2)+2*X(I-2,J-1)-X(I+2,J-2)-X(I-2,J-2)-12*X(I,J);
[Yu,Yb,Yl,Yr] = deal(Quant(Du,q,T),Quant(Db,q,T),Quant(Dl,q,T),Quant(Dr,q,T));
% spam14v not bad, directional, hv-nonsym, to be symmetrized as spam
g.spam14v = reshape(Cooc([Yu Yb],order,'ver',T) + Cooc([Yl;Yr],order,'hor',T),[],1);
g.spam14h = reshape(Cooc([Yu;Yb],order,'hor',T) + Cooc([Yl Yr],order,'ver',T),[],1);
% minmax24 -- EXCELLENT, directional, hv-sym, to be symmetrized as mnmx
[Dmin1,Dmin2,Dmin3,Dmin4] = deal(min(Yu,Yl),min(Yb,Yr),min(Yu,Yr),min(Yb,Yl));
g.min24 = reshape(Cooc([Dmin1 Dmin2 Dmin3 Dmin4],order,'ver',T) + Cooc([Dmin1;Dmin2;Dmin3;Dmin4],order,'hor',T),[],1);
[Dmax1,Dmax2,Dmax3,Dmax4] = deal(max(Yu,Yl),max(Yb,Yr),max(Yu,Yr),max(Yb,Yl));
g.max24 = reshape(Cooc([Dmax1 Dmax2 Dmax3 Dmax4],order,'ver',T) + Cooc([Dmax1;Dmax2;Dmax3;Dmax4],order,'hor',T),[],1);
% minmax22 - hv-nonsymmetrical
% min22h -- good, to be symmetrized as mnmx, directional, hv-nonsymmetrical
% min22v -- EXCELLENT - to be symmetrized as mnmx, directional,
[UEq_min,REq_min] = deal(min(Yu,Yb),min(Yr,Yl));
g.min22h = reshape(Cooc(UEq_min,order,'hor',T) + Cooc(REq_min,order,'ver',T),[],1);
g.min22v = reshape(Cooc(UEq_min,order,'ver',T) + Cooc(REq_min,order,'hor',T),[],1);
[UEq_max,REq_max] = deal(max(Yu,Yb),max(Yr,Yl));
g.max22h = reshape(Cooc(UEq_max,order,'hor',T) + Cooc(REq_max,order,'ver',T),[],1);
g.max22v = reshape(Cooc(UEq_max,order,'ver',T) + Cooc(REq_max,order,'hor',T),[],1);
% minmax41 -- good, non-directional, hv-sym, to be symmetrized as mnmx
[Dmin5,Dmax5] = deal(min(Dmin1,Dmin2),max(Dmax1,Dmax2));
g.min41 = reshape(Cooc(Dmin5,order,'ver',T) + Cooc(Dmin5,order,'hor',T),[],1);
g.max41 = reshape(Cooc(Dmax5,order,'ver',T) + Cooc(Dmax5,order,'hor',T),[],1);
function f = Cooc(D,order,type,T)
% Co-occurrence operator to be appied to a 2D array of residuals D \in [-T,T]
% T ... threshold
% order ... cooc order \in {1,2,3,4,5}
% type ... cooc type \in {hor,ver,diag,mdiag,square,square-ori,hvdm}
% f ... an array of size (2T+1)^order
B = 2*T+1;
if max(abs(D(:))) > T, fprintf('*** ERROR in Cooc.m: Residual out of range ***\n'), end
switch order
case 1
f = hist(D(:),-T:T);
case 2
f = zeros(B,B);
if strcmp(type,'hor'), L = D(:,1:end-1); R = D(:,2:end);end
if strcmp(type,'ver'), L = D(1:end-1,:); R = D(2:end,:);end
if strcmp(type,'diag'), L = D(1:end-1,1:end-1); R = D(2:end,2:end);end
if strcmp(type,'mdiag'), L = D(1:end-1,2:end); R = D(2:end,1:end-1);end
for i = -T : T
R2 = R(L(:)==i);
for j = -T : T
f(i+T+1,j+T+1) = sum(R2(:)==j);
end
end
case 3
f = zeros(B,B,B);
if strcmp(type,'hor'), L = D(:,1:end-2); C = D(:,2:end-1); R = D(:,3:end);end
if strcmp(type,'ver'), L = D(1:end-2,:); C = D(2:end-1,:); R = D(3:end,:);end
if strcmp(type,'diag'), L = D(1:end-2,1:end-2); C = D(2:end-1,2:end-1); R = D(3:end,3:end);end
if strcmp(type,'mdiag'), L = D(1:end-2,3:end); C = D(2:end-1,2:end-1); R = D(3:end,1:end-2);end
for i = -T : T
C2 = C(L(:)==i);
R2 = R(L(:)==i);
for j = -T : T
R3 = R2(C2(:)==j);
for k = -T : T
f(i+T+1,j+T+1,k+T+1) = sum(R3(:)==k);
end
end
end
case 4
f = zeros(B,B,B,B);
if strcmp(type,'hor'), L = D(:,1:end-3); C = D(:,2:end-2); E = D(:,3:end-1); R = D(:,4:end);end
if strcmp(type,'ver'), L = D(1:end-3,:); C = D(2:end-2,:); E = D(3:end-1,:); R = D(4:end,:);end
if strcmp(type,'diag'), L = D(1:end-3,1:end-3); C = D(2:end-2,2:end-2); E = D(3:end-1,3:end-1); R = D(4:end,4:end);end
if strcmp(type,'mdiag'), L = D(4:end,1:end-3); C = D(3:end-1,2:end-2); E = D(2:end-2,3:end-1); R = D(1:end-3,4:end);end
if strcmp(type,'square'), L = D(2:end,1:end-1); C = D(2:end,2:end); E = D(1:end-1,2:end); R = D(1:end-1,1:end-1);end
if strcmp(type,'square-ori'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M);
L = Dh(2:end,1:end-1); C = Dv(2:end,2:end); E = Dh(1:end-1,2:end); R = Dv(1:end-1,1:end-1);end
if strcmp(type,'hvdm'), [M, N] = size(D); L = D(:,1:M); C = D(:,M+1:2*M); E = D(:,2*M+1:3*M); R = D(:,3*M+1:4*M);end
if strcmp(type,'s-in'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh(2:end,1:end-1); C = Dh1(2:end,2:end); E = Dh1(1:end-1,2:end); R = Dh(1:end-1,1:end-1);end
if strcmp(type,'s-out'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh1(2:end,1:end-1); C = Dh(2:end,2:end); E = Dh(1:end-1,2:end); R = Dh1(1:end-1,1:end-1);end
if strcmp(type,'ori-in'), [M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh(2:end,1:end-1); C = Dv1(2:end,2:end); E = Dh1(1:end-1,2:end); R = Dv(1:end-1,1:end-1);end
if strcmp(type,'ori-out'),[M, N] = size(D); Dh = D(:,1:M); Dv = D(:,M+1:2*M); Dh1 = D(:,2*M+1:3*M); Dv1 = D(:,3*M+1:4*M);
L = Dh1(2:end,1:end-1); C = Dv(2:end,2:end); E = Dh(1:end-1,2:end); R = Dv1(1:end-1,1:end-1);end
for i = -T : T
ind = (L(:)==i); C2 = C(ind); E2 = E(ind); R2 = R(ind);
for j = -T : T
ind = (C2(:)==j); E3 = E2(ind); R3 = R2(ind);
for k = -T : T
R4 = R3(E3(:)==k);
for l = -T : T
f(i+T+1,j+T+1,k+T+1,l+T+1) = sum(R4(:)==l);
end
end
end
end
case 5
f = zeros(B,B,B,B,B);
if strcmp(type,'hor'),L = D(:,1:end-4); C = D(:,2:end-3); E = D(:,3:end-2); F = D(:,4:end-1); R = D(:,5:end);end
if strcmp(type,'ver'),L = D(1:end-4,:); C = D(2:end-3,:); E = D(3:end-2,:); F = D(4:end-1,:); R = D(5:end,:);end
for i = -T : T
ind = (L(:)==i); C2 = C(ind); E2 = E(ind); F2 = F(ind); R2 = R(ind);
for j = -T : T
ind = (C2(:)==j); E3 = E2(ind); F3 = F2(ind); R3 = R2(ind);
for k = -T : T
ind = (E3(:)==k); F4 = F3(ind); R4 = R3(ind);
for l = -T : T
R5 = R4(F4(:)==l);
for m = -T : T
f(i+T+1,j+T+1,k+T+1,l+T+1,m+T+1) = sum(R5(:)==m);
end
end
end
end
end
end
% normalization
f = double(f);
fsum = sum(f(:));
if fsum>0, f = f/fsum; end
function Y = Quant(X,q,T)
% Quantization routine
% X ... variable to be quantized/truncated
% T ... threshold
% q ... quantization step (with type = 'scalar') or a vector of increasing
% non-negative integers outlining the quantization process.
% Y ... quantized/truncated variable
% Example 0: when q is a positive scalar, Y = trunc(round(X/q),T)
% Example 1: q = [0 1 2 3] quantizes 0 to 0, 1 to 1, 2 to 2, [3,Inf) to 3,
% (-Inf,-3] to -3, -2 to -2, -1 to -1. It is equivalent to Quant(.,3,1).
% Example 2: q = [0 2 4 5] quantizes 0 to 0, {1,2} to 1, {3,4} to 2,
% [5,Inf) to 3, and similarly with the negatives.
% Example 3: q = [1 2] quantizes {-1,0,1} to 0, [2,Inf) to 1, (-Inf,-2] to -1.
% Example 4: q = [1 3 7 15 16] quantizes {-1,0,1} to 0, {2,3} to 1, {4,5,6,7}
% to 2, {8,9,10,11,12,13,14,15} to 3, [16,Inf) to 4, and similarly the
% negatives.
if numel(q) == 1
if q > 0, Y = trunc(round(X/q),T);
else fprintf('*** ERROR: Attempt to quantize with non-positive step. ***\n'),end
else
q = round(q); % Making sure the vector q is made of integers
if min(q(2:end)-q(1:end-1)) <= 0
fprintf('*** ERROR: quantization vector not strictly increasing. ***\n')
end
if min(q) < 0, fprintf('*** ERROR: Attempt to quantize with negative step. ***\n'),end
T = q(end); % The last value determines the truncation threshold
v = zeros(1,2*T+1); % value-substitution vector
Y = trunc(X,T)+T+1; % Truncated X and shifted to positive values
if q(1) == 0
v(T+1) = 0; z = 1; ind = T+2;
for i = 2 : numel(q)
v(ind:ind+q(i)-q(i-1)-1) = z;
ind = ind+q(i)-q(i-1);
z = z+1;
end
v(1:T) = -v(end:-1:T+2);
else
v(T+1-q(1):T+1+q(1)) = 0; z = 1; ind = T+2+q(1);
for i = 2 : numel(q)
v(ind:ind+q(i)-q(i-1)-1) = z;
ind = ind+q(i)-q(i-1);
z = z+1;
end
v(1:T-q(1)) = -v(end:-1:T+2+q(1));
end
Y = v(Y); % The actual quantization :)
end
function Z = trunc(X,T)
% Truncation to [-T,T]
Z = X;
Z(Z > T) = T;
Z(Z < -T) = -T;
function fsym = symfea(f,T,order,type)
% Marginalization by sign and directional symmetry for a feature vector
% stored as one of our 2*(2T+1)^order-dimensional feature vectors. This
% routine should be used for features possiessing sign and directional
% symmetry, such as spam-like features or 3x3 features. It should NOT be
% used for features from MINMAX residuals. Use the alternative
% symfea_minmax for this purpose.
% The feature f is assumed to be a 2dim x database_size matrix of features
% stored as columns (e.g., hor+ver, diag+minor_diag), with dim =
% 2(2T+1)^order.
[dim,N] = size(f);
B = 2*T+1;
c = B^order;
ERR = 1;
if strcmp(type,'spam')
if dim == 2*c
switch order % Reduced dimensionality for a B^order dimensional feature vector
case 1, red = T + 1;
case 2, red = (T + 1)^2;
case 3, red = 1 + 3*T + 4*T^2 + 2*T^3;
case 4, red = B^2 + 4*T^2*(T + 1)^2;
case 5, red = 1/4*(B^2 + 1)*(B^3 + 1);
end
fsym = zeros(2*red,N);
for i = 1 : N
switch order
case 1, cube = f(1:c,i);
case 2, cube = reshape(f(1:c,i),[B B]);
case 3, cube = reshape(f(1:c,i),[B B B]);
case 4, cube = reshape(f(1:c,i),[B B B B]);
case 5, cube = reshape(f(1:c,i),[B B B B B]);
end
% [size(symm_dir(cube,T,order)) red]
fsym(1:red,i) = symm(cube,T,order);
switch order
case 1, cube = f(c+1:2*c,i);
case 2, cube = reshape(f(c+1:2*c,i),[B B]);
case 3, cube = reshape(f(c+1:2*c,i),[B B B]);
case 4, cube = reshape(f(c+1:2*c,i),[B B B B]);
case 5, cube = reshape(f(c+1:2*c,i),[B B B B B]);
end
fsym(red+1:2*red,i) = symm(cube,T,order);
end
else
fsym = [];
fprintf('*** ERROR: feature dimension is not 2x(2T+1)^order. ***\n')
end
ERR = 0;
end
if strcmp(type,'mnmx')
if dim == 2*c
switch order
case 3, red = B^3 - T*B^2; % Dim of the marginalized set is (2T+1)^3-T*(2T+1)^2
case 4, red = B^4 - 2*T*(T+1)*B^2; % Dim of the marginalized set is (2T+1)^4-2T*(T+1)*(2T+1)^2
end
fsym = zeros(red, N);
for i = 1 : N
switch order
case 1, cube_min = f(1:c,i); cube_max = f(c+1:2*c,i);
case 2, cube_min = reshape(f(1:c,i),[B B]); cube_max = reshape(f(c+1:2*c,i),[B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1);
case 3, cube_min = reshape(f(1:c,i),[B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1);
case 4, cube_min = reshape(f(1:c,i),[B B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1,end:-1:1);
case 5, cube_min = reshape(f(1:c,i),[B B B B B]); cube_max = reshape(f(c+1:2*c,i),[B B B B B]); f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1,end:-1:1,end:-1:1);
end
% f_signsym = cube_min + cube_max(end:-1:1,end:-1:1,end:-1:1);
fsym(:,i) = symm_dir(f_signsym,T,order);
end
end
ERR = 0;
end
if ERR == 1, fprintf('*** ERROR: Feature dimension and T, order incompatible. ***\n'), end
function As = symm_dir(A,T,order)
% Symmetry marginalization routine. The purpose is to reduce the feature
% dimensionality and make the features more populated.
% A is an array of features of size (2*T+1)^order, otherwise error is outputted.
%
% Directional marginalization pertains to the fact that the
% differences d1, d2, d3, ... in a natural (both cover and stego) image
% are as likely to occur as ..., d3, d2, d1.
% Basically, we merge all pairs of bins (i,j,k, ...) and (..., k,j,i)
% as long as they are two different bins. Thus, instead of dim =
% (2T+1)^order, we decrease the dim by 1/2*{# of non-symmetric bins}.
% For order = 3, the reduced dim is (2T+1)^order - T(2T+1)^(order-1),
% for order = 4, it is (2T+1)^4 - 2T(T+1)(2T+1)^2.
B = 2*T+1;
done = zeros(size(A));
switch order
case 3, red = B^3 - T*B^2; % Dim of the marginalized set is (2T+1)^3-T*(2T+1)^2
case 4, red = B^4 - 2*T*(T+1)*B^2; % Dim of the marginalized set is (2T+1)^4-2T*(T+1)*(2T+1)^2
case 5, red = B^5 - 2*T*(T+1)*B^3;
end
As = zeros(red, 1);
m = 1;
switch order
case 3
for i = -T : T
for j = -T : T
for k = -T : T
if k ~= i % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1) + A(k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1) = 1;
done(k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1);
done(i+T+1,j+T+1,k+T+1) = 1;
m = m + 1;
end
end
end
end
case 4
for i = -T : T
for j = -T : T
for k = -T : T
for n = -T : T
if (i ~= n) || (j ~= k) % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1,n+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1) + A(n+T+1,k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
done(n+T+1,k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1);
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
m = m + 1;
end
end
end
end
end
case 5
for i = -T : T
for j = -T : T
for k = -T : T
for l = -T : T
for n = -T : T
if (i ~= n) || (j ~= l) % Asymmetric bin
if done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) == 0
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) + A(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1); % Two mirror-bins are merged
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) = 1;
m = m + 1;
end
else % Symmetric bin is just copied
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1);
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
m = m + 1;
end
end
end
end
end
end
otherwise
fprintf('*** ERROR: Order not equal to 3 or 4 or 5! ***\n')
end
function fsym = symm1(f,T,order)
% Marginalization by sign and directional symmetry for a feature vector
% stored as a (2T+1)^order-dimensional array. The input feature f is
% assumed to be a dim x database_size matrix of features stored as columns.
[dim,N] = size(f);
B = 2*T+1;
c = B^order;
ERR = 1;
if dim == c
ERR = 0;
switch order % Reduced dimensionality for a c-dimensional feature vector
case 1, red = T + 1;
case 2, red = (T + 1)^2;
case 3, red = 1 + 3*T + 4*T^2 + 2*T^3;
case 4, red = B^2 + 4*T^2*(T + 1)^2;
case 5, red = 1/4*(B^2 + 1)*(B^3 + 1);
end
fsym = zeros(red,N);
for i = 1 : N
switch order
case 1, cube = f(:,i);
case 2, cube = reshape(f(:,i),[B B]);
case 3, cube = reshape(f(:,i),[B B B]);
case 4, cube = reshape(f(:,i),[B B B B]);
case 5, cube = reshape(f(:,i),[B B B B B]);
end
% [size(symm_dir(cube,T,order)) red]
fsym(:,i) = symm(cube,T,order);
end
end
if ERR == 1, fprintf('*** ERROR in symm1: Feature dimension and T, order incompatible. ***\n'), end
function As = symm(A,T,order)
% Symmetry marginalization routine. The purpose is to reduce the feature
% dimensionality and make the features more populated. It can be applied to
% 1D -- 5D co-occurrence matrices (order \in {1,2,3,4,5}) with sign and
% directional symmetries (explained below).
% A must be an array of (2*T+1)^order, otherwise error is outputted.
%
% Marginalization by symmetry pertains to the fact that, fundamentally,
% the differences between consecutive pixels in a natural image (both cover
% and stego) d1, d2, d3, ..., have the same probability of occurrence as the
% triple -d1, -d2, -d3, ...
%
% Directional marginalization pertains to the fact that the
% differences d1, d2, d3, ... in a natural (cover and stego) image are as
% likely to occur as ..., d3, d2, d1.
ERR = 1; % Flag denoting when size of A is incompatible with the input parameters T and order
m = 2;
B = 2*T + 1;
switch order
case 1 % First-order coocs are only symmetrized
if numel(A) == 2*T+1
As(1) = A(T+1); % The only non-marginalized bin is the origin 0
As(2:T+1) = A(1:T) + A(T+2:end);
As = As(:);
ERR = 0;
end
case 2
if numel(A) == (2*T+1)^2
As = zeros((T+1)^2, 1);
As(1) = A(T+1,T+1); % The only non-marginalized bin is the origin (0,0)
for i = -T : T
for j = -T : T
if (done(i+T+1,j+T+1) == 0) && (abs(i)+abs(j) ~= 0)
As(m) = A(i+T+1,j+T+1) + A(T+1-i,T+1-j);
done(i+T+1,j+T+1) = 1;
done(T+1-i,T+1-j) = 1;
if (i ~= j) && (done(j+T+1,i+T+1) == 0)
As(m) = As(m) + A(j+T+1,i+T+1) + A(T+1-j,T+1-i);
done(j+T+1,i+T+1) = 1;
done(T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
ERR = 0;
end
case 3
if numel(A) == B^3
done = zeros(size(A));
As = zeros(1+3*T+4*T^2+2*T^3, 1);
As(1) = A(T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
if (done(i+T+1,j+T+1,k+T+1) == 0) && (abs(i)+abs(j)+abs(k) ~= 0)
As(m) = A(i+T+1,j+T+1,k+T+1) + A(T+1-i,T+1-j,T+1-k);
done(i+T+1,j+T+1,k+T+1) = 1;
done(T+1-i,T+1-j,T+1-k) = 1;
if (i ~= k) && (done(k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(k+T+1,j+T+1,i+T+1) + A(T+1-k,T+1-j,T+1-i);
done(k+T+1,j+T+1,i+T+1) = 1;
done(T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
ERR = 0;
end
case 4
if numel(A) == (2*T+1)^4
done = zeros(size(A));
As = zeros(B^2 + 4*T^2*(T+1)^2, 1);
As(1) = A(T+1,T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
for n = -T : T
if (done(i+T+1,j+T+1,k+T+1,n+T+1) == 0) && (abs(i)+abs(j)+abs(k)+abs(n)~=0)
As(m) = A(i+T+1,j+T+1,k+T+1,n+T+1) + A(T+1-i,T+1-j,T+1-k,T+1-n);
done(i+T+1,j+T+1,k+T+1,n+T+1) = 1;
done(T+1-i,T+1-j,T+1-k,T+1-n) = 1;
if ((i ~= n) || (j ~= k)) && (done(n+T+1,k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(n+T+1,k+T+1,j+T+1,i+T+1) + A(T+1-n,T+1-k,T+1-j,T+1-i);
done(n+T+1,k+T+1,j+T+1,i+T+1) = 1;
done(T+1-n,T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
end
ERR = 0;
end
case 5
if numel(A) == (2*T+1)^5
done = zeros(size(A));
As = zeros(1/4*(B^2 + 1)*(B^3 + 1), 1);
As(1) = A(T+1,T+1,T+1,T+1,T+1); % The only non-marginalized bin is the origin (0,0,0,0,0)
for i = -T : T
for j = -T : T
for k = -T : T
for l = -T : T
for n = -T : T
if (done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) == 0) && (abs(i)+abs(j)+abs(k)+abs(l)+abs(n)~=0)
As(m) = A(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) + A(T+1-i,T+1-j,T+1-k,T+1-l,T+1-n);
done(i+T+1,j+T+1,k+T+1,l+T+1,n+T+1) = 1;
done(T+1-i,T+1-j,T+1-k,T+1-l,T+1-n) = 1;
if ((i ~= n) || (j ~= l)) && (done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) == 0)
As(m) = As(m) + A(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) + A(T+1-n,T+1-l,T+1-k,T+1-j,T+1-i);
done(n+T+1,l+T+1,k+T+1,j+T+1,i+T+1) = 1;
done(T+1-n,T+1-l,T+1-k,T+1-j,T+1-i) = 1;
end
m = m + 1;
end
end
end
end
end
end
ERR = 0;
end
otherwise
As = [];
fprintf(' Order of cooc is not in {1,2,3,4,5}.\n')
end
if ERR == 1
As = [];
fprintf('*** ERROR in symm: The number of elements in the array is not (2T+1)^order. ***\n')
end
As = As(:);
function D = Residual(X,order,type)
% Computes the noise residual of a given type and order from MxN image X.
% residual order \in {1,2,3,4,5,6}
% type \in {hor,ver,diag,mdiag,KB,edge-h,edge-v,edge-d,edge-m}
% The resulting residual is an (M-b)x(N-b) array of the specified order,
% where b = ceil(order/2). This cropping is little more than it needs to
% be to make sure all the residuals are easily "synchronized".
% !!!!!!!!!!!!! Use order = 2 with KB and all edge residuals !!!!!!!!!!!!!
[M N] = size(X);
I = 1+ceil(order/2) : M-ceil(order/2);
J = 1+ceil(order/2) : N-ceil(order/2);
switch type
case 'hor'
switch order
case 1, D = - X(I,J) + X(I,J+1);
case 2, D = X(I,J-1) - 2*X(I,J) + X(I,J+1);
case 3, D = X(I,J-1) - 3*X(I,J) + 3*X(I,J+1) - X(I,J+2);
case 4, D = -X(I,J-2) + 4*X(I,J-1) - 6*X(I,J) + 4*X(I,J+1) - X(I,J+2);
case 5, D = -X(I,J-2) + 5*X(I,J-1) - 10*X(I,J) + 10*X(I,J+1) - 5*X(I,J+2) + X(I,J+3);
case 6, D = X(I,J-3) - 6*X(I,J-2) + 15*X(I,J-1) - 20*X(I,J) + 15*X(I,J+1) - 6*X(I,J+2) + X(I,J+3);
end
case 'ver'
switch order
case 1, D = - X(I,J) + X(I+1,J);
case 2, D = X(I-1,J) - 2*X(I,J) + X(I+1,J);
case 3, D = X(I-1,J) - 3*X(I,J) + 3*X(I+1,J) - X(I+2,J);
case 4, D = -X(I-2,J) + 4*X(I-1,J) - 6*X(I,J) + 4*X(I+1,J) - X(I+2,J);
case 5, D = -X(I-2,J) + 5*X(I-1,J) - 10*X(I,J) + 10*X(I+1,J) - 5*X(I+2,J) + X(I+3,J);
case 6, D = X(I-3,J) - 6*X(I-2,J) + 15*X(I-1,J) - 20*X(I,J) + 15*X(I+1,J) - 6*X(I+2,J) + X(I+3,J);
end
case 'diag'
switch order
case 1, D = - X(I,J) + X(I+1,J+1);
case 2, D = X(I-1,J-1) - 2*X(I,J) + X(I+1,J+1);
case 3, D = X(I-1,J-1) - 3*X(I,J) + 3*X(I+1,J+1) - X(I+2,J+2);
case 4, D = -X(I-2,J-2) + 4*X(I-1,J-1) - 6*X(I,J) + 4*X(I+1,J+1) - X(I+2,J+2);
case 5, D = -X(I-2,J-2) + 5*X(I-1,J-1) - 10*X(I,J) + 10*X(I+1,J+1) - 5*X(I+2,J+2) + X(I+3,J+3);
case 6, D = X(I-3,J-3) - 6*X(I-2,J-2) + 15*X(I-1,J-1) - 20*X(I,J) + 15*X(I+1,J+1) - 6*X(I+2,J+2) + X(I+3,J+3);
end
case 'mdiag'
switch order
case 1, D = - X(I,J) + X(I-1,J+1);
case 2, D = X(I-1,J+1) - 2*X(I,J) + X(I+1,J-1);
case 3, D = X(I-1,J+1) - 3*X(I,J) + 3*X(I+1,J-1) - X(I+2,J-2);
case 4, D = -X(I-2,J+2) + 4*X(I-1,J+1) - 6*X(I,J) + 4*X(I+1,J-1) - X(I+2,J-2);
case 5, D = -X(I-2,J+2) + 5*X(I-1,J+1) - 10*X(I,J) + 10*X(I+1,J-1) - 5*X(I+2,J-2) + X(I+3,J-3);
case 6, D = X(I-3,J+3) - 6*X(I-2,J+2) + 15*X(I-1,J+1) - 20*X(I,J) + 15*X(I+1,J-1) - 6*X(I+2,J-2) + X(I+3,J-3);
end
case 'KB'
D = -X(I-1,J-1) + 2*X(I-1,J) - X(I-1,J+1) + 2*X(I,J-1) - 4*X(I,J) + 2*X(I,J+1) - X(I+1,J-1) + 2*X(I+1,J) - X(I+1,J+1);
case 'edge-h'
Du = 2*X(I-1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I-1,J-1) - X(I-1,J+1) - 4*X(I,J); % -1 2 -1
Db = 2*X(I+1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I+1,J-1) - X(I+1,J+1) - 4*X(I,J); % 2 C 2 + flipped vertically
D = [Du,Db];
case 'edge-v'
Dl = 2*X(I,J-1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J-1) - X(I+1,J-1) - 4*X(I,J); % -1 2
Dr = 2*X(I,J+1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J+1) - X(I+1,J+1) - 4*X(I,J); % 2 C + flipped horizontally
D = [Dl,Dr]; % -1 2
case 'edge-m'
Dlu = 2*X(I,J-1) + 2*X(I-1,J) - X(I-1,J-1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % -1 2 -1
Drb = 2*X(I,J+1) + 2*X(I+1,J) - X(I+1,J+1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % 2 C + flipped mdiag
D = [Dlu,Drb]; % -1
case 'edge-d'
Dru = 2*X(I-1,J) + 2*X(I,J+1) - X(I-1,J+1) - X(I-1,J-1) - X(I+1,J+1) - X(I,J); % -1 2 -1
Dlb = 2*X(I,J-1) + 2*X(I+1,J) - X(I+1,J-1) - X(I+1,J+1) - X(I-1,J-1) - X(I,J); % C 2 + flipped diag
D = [Dru,Dlb]; % -1
case 'KV'
D = 8*X(I-1,J) + 8*X(I+1,J) + 8*X(I,J-1) + 8*X(I,J+1);
D = D - 6*X(I-1,J+1) - 6*X(I-1,J-1) - 6*X(I+1,J-1) - 6*X(I+1,J+1);
D = D - 2*X(I-2,J) - 2*X(I+2,J) - 2*X(I,J+2) - 2*X(I,J-2);
D = D + 2*X(I-1,J-2) + 2*X(I-2,J-1) + 2*X(I-2,J+1) + 2*X(I-1,J+2) + 2*X(I+1,J+2) + 2*X(I+2,J+1) + 2*X(I+2,J-1) + 2*X(I+1,J-2);
D = D - X(I-2,J-2) - X(I-2,J+2) - X(I+2,J-2) - X(I+2,J+2) - 12*X(I,J);
end
|
github
|
daniellerch/aletheia-master
|
sigma_spam_PSRM.m
|
.m
|
aletheia-master/aletheia-octave/octave/sigma_spam_PSRM.m
| 14,676 |
utf_8
|
dc32f2d3b8c164295acc43e9a70410ce
|
function f = sigma_spam_PSRM(IMAGE, q, Prob)
% -------------------------------------------------------------------------
% Copyright (c) 2011 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | November 2011
% http://dde.binghamton.edu/download/feature_extractors
% -------------------------------------------------------------------------
% Extracts 39 submodels presented in [1] -- only q=1c. All features are
% calculated in the spatial domain and are stored in a structured variable
% 'f'. For more deatils about the individual submodels, please see the
% publication [1]. Total dimensionality of all 39 submodels is 12,753.
% -------------------------------------------------------------------------
% Input: IMAGE ... path to the image (can be JPEG)
% Output: f ...... extracted PSRM features in a structured format
% -------------------------------------------------------------------------
settings.qBins = 3;
settings.projCount = 55;
settings.seedIndex = 1;
settings.fixedSize = 8;
settings.binSize = q;
X = double(IMAGE);
f = post_processing(all1st(X,1),'f1'); % 1st order
f = post_processing(all2nd(X,1),'f2',f); % 2nd order
f = post_processing(all3rd(X,1),'f3',f); % 3rd order
f = post_processing(all3x3(X,1),'f3x3', f); % 3x3
f = post_processing(all5x5(X,1),'f5x5', f); % 5x5
function RESULT = post_processing(DATA,f,RESULT)
Ss = fieldnames(DATA);
for Sid = 1:length(Ss)
VARNAME = [f '_' Ss{Sid}];
eval(['RESULT.' VARNAME ' = reshape(single(DATA.' Ss{Sid} '),1,[]);' ])
end
% symmetrize
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='s', continue; end
[T,N] = parse_feaname(name);
if strcmp(T,''), continue; end
% symmetrization
if strcmp(N(1:3),'min') || strcmp(N(1:3),'max')
% minmax symmetrization
OUT = ['s' T(2:end) '_minmax' N(4:end)];
if isfield(RESULT,OUT), continue; end
Fmin = []; Fmax = [];
eval(['Fmin = RESULT.' strrep(name,'max','min') ';']);
eval(['Fmax = RESULT.' strrep(name,'min','max') ';']);
F = mergeMinMax(Fmin, Fmax);
eval(['RESULT.' OUT ' = single(F);' ]);
elseif strcmp(N(1:4),'spam')
% spam symmetrization
OUT = ['s' T(2:end) '_' N];
if isfield(RESULT,OUT), continue; end
eval(['RESULT.' OUT ' = single(RESULT.' name ');' ]);
end
end
% delete RESULT.f*
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
if name(1)=='f'
RESULT = rmfield(RESULT,name);
end
end
% merge spam features
L = fieldnames(RESULT);
for i=1:length(L)
name = L{i}; % feature name
[T,N] = parse_feaname(name);
if ~strcmp(N(1:4),'spam'), continue; end
if strcmp(T,''), continue; end
if strcmp(N(end),'v')||(strcmp(N,'spam11')&&strcmp(T,'s5x5'))
elseif strcmp(N(end),'h')
% h+v union
OUT = [T '_' N 'v'];
if isfield(RESULT,OUT), continue; end
name2 = strrep(name,'h','v');
Fh = []; Fv = [];
eval(['Fh = RESULT.' name ';']);
eval(['Fv = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [Fh Fv];']);
RESULT = rmfield(RESULT,name);
RESULT = rmfield(RESULT,name2);
elseif strcmp(N,'spam11')
% KBKV creation
OUT = ['s35_' N];
if isfield(RESULT,OUT), continue; end
name1 = strrep(name,'5x5','3x3');
name2 = strrep(name,'3x3','5x5');
if ~isfield(RESULT,name1), continue; end
if ~isfield(RESULT,name2), continue; end
F_KB = []; F_KV = [];
eval(['F_KB = RESULT.' name1 ';']);
eval(['F_KV = RESULT.' name2 ';']);
eval(['RESULT.' OUT ' = [F_KB F_KV];']);
RESULT = rmfield(RESULT,name1);
RESULT = rmfield(RESULT,name2);
end
end
end
function [T,N] = parse_feaname(name)
[T,N] = deal('');
S = strfind(name,'_'); if length(S)~=1, return; end
T = name(1:S-1);
N = name(S+1:end);
end
function g = all1st(X,q)
R = [0 0 0; 0 -1 1; 0 0 0];
U = [0 1 0; 0 -1 0; 0 0 0];
g.spam14h = reshape(ProjHistSpam(X,R,Prob,'hor',q) + ProjHistSpam(X,U,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
g.spam14v = reshape(ProjHistSpam(X,R,Prob,'ver',q) + ProjHistSpam(X,U,Prob,'hor',q),[],1);settings.seedIndex=settings.seedIndex+1;
end
function g = all2nd(X,q)
Dh = [0 0 0; 1 -2 1; 0 0 0]/2;
Dv = [0 1 0; 0 -2 0; 0 1 0]/2;
g.spam12h = reshape(ProjHistSpam(X,Dh,Prob,'hor',q) + ProjHistSpam(X,Dv,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
g.spam12v = reshape(ProjHistSpam(X,Dh,Prob,'ver',q) + ProjHistSpam(X,Dv,Prob,'hor',q),[],1);settings.seedIndex=settings.seedIndex+1;
end
function g = all3rd(X,q)
R = [0 0 0 0 0; 0 0 0 0 0; 0 1 -3 3 -1; 0 0 0 0 0; 0 0 0 0 0]/3;
U = [0 0 -1 0 0; 0 0 3 0 0; 0 0 -3 0 0; 0 0 1 0 0; 0 0 0 0 0]/3;
g.spam14h = reshape(ProjHistSpam(X,R,Prob,'hor',q) + ProjHistSpam(X,U,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
g.spam14v = reshape(ProjHistSpam(X,R,Prob,'ver',q) + ProjHistSpam(X,U,Prob,'hor',q),[],1);settings.seedIndex=settings.seedIndex+1;
end
function g = all3x3(X,q)
F = [-1 2 -1; 2 -4 2; -1 2 -1]/4;
g.spam11 = reshape(ProjHistSpam(X,F,Prob,'hor',q) + ProjHistSpam(X,F,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
[Du, Db, Dl, Dr] = deal(F);
Du(3,:) = 0;
Db(1,:) = 0;
Dl(:,3) = 0;
Dr(:,1) = 0;
g.spam14v = reshape(ProjHistSpam(X,Du,Prob,'ver',q) + ProjHistSpam(X,Db,Prob,'ver',q) + ProjHistSpam(X,Dl,Prob,'hor',q) + ProjHistSpam(X,Dr,Prob,'hor',q),[],1);settings.seedIndex=settings.seedIndex+1;
g.spam14h = reshape(ProjHistSpam(X,Du,Prob,'hor',q) + ProjHistSpam(X,Db,Prob,'hor',q) + ProjHistSpam(X,Dl,Prob,'ver',q) + ProjHistSpam(X,Dr,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
end
function g = all5x5(X,q)
F = [-1 2 -2 2 -1; 2 -6 8 -6 2; -2 8 -12 8 -2; 2 -6 8 -6 2; -1 2 -2 2 -1]/12;
g.spam11 = reshape(ProjHistSpam(X,F,Prob,'hor',q) + ProjHistSpam(X,F,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
[Du, Db, Dl, Dr] = deal(F);
Du(4:5,:) = 0;
Db(1:2,:) = 0;
Dl(:,4:5) = 0;
Dr(:,1:2) = 0;
g.spam14v = reshape(ProjHistSpam(X,Du,Prob,'ver',q) + ProjHistSpam(X,Db,Prob,'ver',q) + ProjHistSpam(X,Dl,Prob,'hor',q) + ProjHistSpam(X,Dr,Prob,'hor',q),[],1);settings.seedIndex=settings.seedIndex+1;
g.spam14h = reshape(ProjHistSpam(X,Du,Prob,'hor',q) + ProjHistSpam(X,Db,Prob,'hor',q) + ProjHistSpam(X,Dl,Prob,'ver',q) + ProjHistSpam(X,Dr,Prob,'ver',q),[],1);settings.seedIndex=settings.seedIndex+1;
end
function h = ProjHistSpam(X,F,Prob, type, centerVal)
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',settings.seedIndex));
rand('state', settings.seedIndex);
h = zeros(settings.qBins * settings.projCount, 1);
for projIndex = 1:settings.projCount
Psize = randi(settings.fixedSize, 2, 1);
P = randn(Psize(1), Psize(2));
n = sqrt(sum(P(:).^2));
P = P ./ n;
if strcmp(type, 'ver'), P = P'; end;
binEdges = 0:settings.qBins;
binEdges = binEdges * settings.binSize * centerVal;
proj = conv2( X, conv2( F, P ), 'valid' );
sigma = sqrt( conv2( Prob, conv2( F, P ).^2, 'valid' ) );
h_neigh = prob_hist(abs(proj(:)), sigma, binEdges);
if size(P, 2) > 1
proj = conv2( X, conv2( F, fliplr(P) ), 'valid' );
sigma = sqrt( conv2( Prob, conv2( F, fliplr(P) ).^2, 'valid' ) );
h_neigh = h_neigh + prob_hist(abs(proj(:)), sigma, binEdges);
end
if size(P, 1) > 1
proj = conv2( X, conv2( F, flipud(P) ), 'valid' );
sigma = sqrt( conv2( Prob, conv2( F, flipud(P) ).^2, 'valid' ) );
h_neigh = h_neigh + prob_hist(abs(proj(:)), sigma, binEdges);
end
if all(size(P)>1)
proj = conv2( X, conv2( F, rot90(P, 2) ), 'valid' );
sigma = sqrt( conv2( Prob, conv2( F, rot90(P, 2) ).^2, 'valid' ) );
h_neigh = h_neigh + prob_hist(abs(proj(:)), sigma, binEdges);
end
h((projIndex-1)*settings.qBins + 1:projIndex*settings.qBins, 1) = h_neigh;
end
end
function h = prob_hist( proj, sigma, binEdges )
h = zeros( length(binEdges)-1, 1 );
for i = 1:length(h)
I = (proj >= binEdges(i)) & (proj < binEdges(i+1));
h(i) = sum( sigma(I) );
end
end
function result = mergeMinMax(Fmin, Fmax)
Fmin = reshape(Fmin, 2*settings.qBins, []);
Fmin = flipud(Fmin);
result = Fmax + Fmin(:)';
end
function D = Residual(X,order,type)
% Computes the noise residual of a given type and order from MxN image X.
% residual order \in {1,2,3,4,5,6}
% type \in {hor,ver,diag,mdiag,KB,edge-h,edge-v,edge-d,edge-m}
% The resulting residual is an (M-b)x(N-b) array of the specified order,
% where b = ceil(order/2). This cropping is little more than it needs to
% be to make sure all the residuals are easily "synchronized".
% !!!!!!!!!!!!! Use order = 2 with KB and all edge residuals !!!!!!!!!!!!!
[M N] = size(X);
I = 1+ceil(order/2) : M-ceil(order/2);
J = 1+ceil(order/2) : N-ceil(order/2);
switch type
case 'hor'
switch order
case 1, D = - X(I,J) + X(I,J+1);
case 2, D = X(I,J-1) - 2*X(I,J) + X(I,J+1);
case 3, D = X(I,J-1) - 3*X(I,J) + 3*X(I,J+1) - X(I,J+2);
case 4, D = -X(I,J-2) + 4*X(I,J-1) - 6*X(I,J) + 4*X(I,J+1) - X(I,J+2);
case 5, D = -X(I,J-2) + 5*X(I,J-1) - 10*X(I,J) + 10*X(I,J+1) - 5*X(I,J+2) + X(I,J+3);
case 6, D = X(I,J-3) - 6*X(I,J-2) + 15*X(I,J-1) - 20*X(I,J) + 15*X(I,J+1) - 6*X(I,J+2) + X(I,J+3);
end
case 'ver'
switch order
case 1, D = - X(I,J) + X(I+1,J);
case 2, D = X(I-1,J) - 2*X(I,J) + X(I+1,J);
case 3, D = X(I-1,J) - 3*X(I,J) + 3*X(I+1,J) - X(I+2,J);
case 4, D = -X(I-2,J) + 4*X(I-1,J) - 6*X(I,J) + 4*X(I+1,J) - X(I+2,J);
case 5, D = -X(I-2,J) + 5*X(I-1,J) - 10*X(I,J) + 10*X(I+1,J) - 5*X(I+2,J) + X(I+3,J);
case 6, D = X(I-3,J) - 6*X(I-2,J) + 15*X(I-1,J) - 20*X(I,J) + 15*X(I+1,J) - 6*X(I+2,J) + X(I+3,J);
end
case 'diag'
switch order
case 1, D = - X(I,J) + X(I+1,J+1);
case 2, D = X(I-1,J-1) - 2*X(I,J) + X(I+1,J+1);
case 3, D = X(I-1,J-1) - 3*X(I,J) + 3*X(I+1,J+1) - X(I+2,J+2);
case 4, D = -X(I-2,J-2) + 4*X(I-1,J-1) - 6*X(I,J) + 4*X(I+1,J+1) - X(I+2,J+2);
case 5, D = -X(I-2,J-2) + 5*X(I-1,J-1) - 10*X(I,J) + 10*X(I+1,J+1) - 5*X(I+2,J+2) + X(I+3,J+3);
case 6, D = X(I-3,J-3) - 6*X(I-2,J-2) + 15*X(I-1,J-1) - 20*X(I,J) + 15*X(I+1,J+1) - 6*X(I+2,J+2) + X(I+3,J+3);
end
case 'mdiag'
switch order
case 1, D = - X(I,J) + X(I-1,J+1);
case 2, D = X(I-1,J+1) - 2*X(I,J) + X(I+1,J-1);
case 3, D = X(I-1,J+1) - 3*X(I,J) + 3*X(I+1,J-1) - X(I+2,J-2);
case 4, D = -X(I-2,J+2) + 4*X(I-1,J+1) - 6*X(I,J) + 4*X(I+1,J-1) - X(I+2,J-2);
case 5, D = -X(I-2,J+2) + 5*X(I-1,J+1) - 10*X(I,J) + 10*X(I+1,J-1) - 5*X(I+2,J-2) + X(I+3,J-3);
case 6, D = X(I-3,J+3) - 6*X(I-2,J+2) + 15*X(I-1,J+1) - 20*X(I,J) + 15*X(I+1,J-1) - 6*X(I+2,J-2) + X(I+3,J-3);
end
case 'KB'
D = -X(I-1,J-1) + 2*X(I-1,J) - X(I-1,J+1) + 2*X(I,J-1) - 4*X(I,J) + 2*X(I,J+1) - X(I+1,J-1) + 2*X(I+1,J) - X(I+1,J+1);
case 'edge-h'
Du = 2*X(I-1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I-1,J-1) - X(I-1,J+1) - 4*X(I,J); % -1 2 -1
Db = 2*X(I+1,J) + 2*X(I,J-1) + 2*X(I,J+1) - X(I+1,J-1) - X(I+1,J+1) - 4*X(I,J); % 2 C 2 + flipped vertically
D = [Du,Db];
case 'edge-v'
Dl = 2*X(I,J-1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J-1) - X(I+1,J-1) - 4*X(I,J); % -1 2
Dr = 2*X(I,J+1) + 2*X(I-1,J) + 2*X(I+1,J) - X(I-1,J+1) - X(I+1,J+1) - 4*X(I,J); % 2 C + flipped horizontally
D = [Dl,Dr]; % -1 2
case 'edge-m'
Dlu = 2*X(I,J-1) + 2*X(I-1,J) - X(I-1,J-1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % -1 2 -1
Drb = 2*X(I,J+1) + 2*X(I+1,J) - X(I+1,J+1) - X(I+1,J-1) - X(I-1,J+1) - X(I,J); % 2 C + flipped mdiag
D = [Dlu,Drb]; % -1
case 'edge-d'
Dru = 2*X(I-1,J) + 2*X(I,J+1) - X(I-1,J+1) - X(I-1,J-1) - X(I+1,J+1) - X(I,J); % -1 2 -1
Dlb = 2*X(I,J-1) + 2*X(I+1,J) - X(I+1,J-1) - X(I+1,J+1) - X(I-1,J-1) - X(I,J); % C 2 + flipped diag
D = [Dru,Dlb]; % -1
case 'KV'
D = 8*X(I-1,J) + 8*X(I+1,J) + 8*X(I,J-1) + 8*X(I,J+1);
D = D - 6*X(I-1,J+1) - 6*X(I-1,J-1) - 6*X(I+1,J-1) - 6*X(I+1,J+1);
D = D - 2*X(I-2,J) - 2*X(I+2,J) - 2*X(I,J+2) - 2*X(I,J-2);
D = D + 2*X(I-1,J-2) + 2*X(I-2,J-1) + 2*X(I-2,J+1) + 2*X(I-1,J+2) + 2*X(I+1,J+2) + 2*X(I+2,J+1) + 2*X(I+2,J-1) + 2*X(I+1,J-2);
D = D - X(I-2,J-2) - X(I-2,J+2) - X(I+2,J-2) - X(I+2,J+2) - 12*X(I,J);
end
end
end
|
github
|
daniellerch/aletheia-master
|
WOW.m
|
.m
|
aletheia-master/aletheia-octave/octave/WOW.m
| 7,349 |
utf_8
|
62f1fbf31d4e9bc8bdb35c9b788a0a4c
|
function [stego, distortion] = WOW(cover_path, payload)
% -------------------------------------------------------------------------
% Copyright (c) 2012 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | October 2012
% http://dde.binghamton.edu/download/steganography
% -------------------------------------------------------------------------
% This function simulates embedding using WOW steganographic
% algorithm. For more deatils about the individual submodels, please see
% the publication [1].
% -------------------------------------------------------------------------
% Input: coverPath ... path to the image
% payload ..... payload in bits per pixel
% Output: stego ....... resulting image with embedded payload
% -------------------------------------------------------------------------
% [1] Designing Steganographic Distortion Using Directional Filters,
% V. Holub and J. Fridrich, to be presented at WIFS'12 IEEE International
% Workshop on Information Forensics and Security
% -------------------------------------------------------------------------
%% Get 2D wavelet filters - Daubechies 8
% 1D high pass decomposition filter
hpdf = [-0.0544158422, 0.3128715909, -0.6756307363, 0.5853546837, 0.0158291053, -0.2840155430, -0.0004724846, 0.1287474266, 0.0173693010, -0.0440882539, ...
-0.0139810279, 0.0087460940, 0.0048703530, -0.0003917404, -0.0006754494, -0.0001174768];
% 1D low pass decomposition filter
lpdf = (-1).^(0:numel(hpdf)-1).*fliplr(hpdf);
% construction of 2D wavelet filters
F{1} = lpdf'*hpdf;
F{2} = hpdf'*lpdf;
F{3} = hpdf'*hpdf;
%% Get embedding costs
% inicialization
cover = double(imread(cover_path));
p = -1;
wetCost = 10^10;
sizeCover = size(cover);
% add padding
padSize = max([size(F{1})'; size(F{2})'; size(F{3})']);
coverPadded = padarray(cover, [padSize padSize], 'symmetric');
% compute directional residual and suitability \xi for each filter
xi = cell(3, 1);
for fIndex = 1:3
% compute residual
R = conv2(coverPadded, F{fIndex}, 'same');
% compute suitability
xi{fIndex} = conv2(abs(R), rot90(abs(F{fIndex}), 2), 'same');
% correct the suitability shift if filter size is even
if mod(size(F{fIndex}, 1), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [1, 0]); end;
if mod(size(F{fIndex}, 2), 2) == 0, xi{fIndex} = circshift(xi{fIndex}, [0, 1]); end;
% remove padding
xi{fIndex} = xi{fIndex}(((size(xi{fIndex}, 1)-sizeCover(1))/2)+1:end-((size(xi{fIndex}, 1)-sizeCover(1))/2), ((size(xi{fIndex}, 2)-sizeCover(2))/2)+1:end-((size(xi{fIndex}, 2)-sizeCover(2))/2));
end
% compute embedding costs \rho
rho = ( (xi{1}.^p) + (xi{2}.^p) + (xi{3}.^p) ) .^ (-1/p);
% adjust embedding costs
rho(rho > wetCost) = wetCost; % threshold on the costs
rho(isnan(rho)) = wetCost; % if all xi{} are zero threshold the cost
rhoP1 = rho;
rhoM1 = rho;
rhoP1(cover==255) = wetCost; % do not embed +1 if the pixel has max value
rhoM1(cover==0) = wetCost; % do not embed -1 if the pixel has min value
%% Embedding simulator
stego = EmbeddingSimulator(cover, rhoP1, rhoM1, payload*numel(cover), false);
distortion_local = rho(cover~=stego);
distortion = sum(distortion_local);
%% --------------------------------------------------------------------------------------------------------------------------
% Embedding simulator simulates the embedding made by the best possible ternary coding method (it embeds on the entropy bound).
% This can be achieved in practice using "Multi-layered syndrome-trellis codes" (ML STC) that are asymptotically aproaching the bound.
function [y] = EmbeddingSimulator(x, rhoP1, rhoM1, m, fixEmbeddingChanges)
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
if fixEmbeddingChanges == 1
%RandStream.setGlobalStream(RandStream('mt19937ar','seed',139187));
rand('state', 139187);
else
%RandStream.setGlobalStream(RandStream('mt19937ar','Seed',sum(100*clock)));
rand('state', sum(100*clock));
end
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
p0 = 1-pP1-pM1;
P = [p0(:); pP1(:); pM1(:)];
H = -((P).*log2(P));
H((P<eps) | (P > 1-eps)) = 0;
Ht = sum(H);
end
end
end
|
github
|
daniellerch/aletheia-master
|
J_UNIWARD_COLOR.m
|
.m
|
aletheia-master/aletheia-octave/octave/J_UNIWARD_COLOR.m
| 8,229 |
utf_8
|
b30f919c16492cfe2115cfd7ded0ecea
|
function STEGO = J_UNIWARD_COLOR(cover, payload, stego)
% -------------------------------------------------------------------------
% Copyright (c) 2013 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | February
% 2013
% http://dde.binghamton.edu/download/stego_algorithms/
% -------------------------------------------------------------------------
% This function simulates embedding using J-UNIWARD steganographic
% algorithm.
% -------------------------------------------------------------------------
% Input: coverPath ... path to the image
% payload ..... payload in bits per non zero DCT coefficient
% Output: stego ....... resulting JPEG structure with embedded payload
% -------------------------------------------------------------------------
C_STRUCT = jpeg_read(cover);
% C_COEFFS = C_STRUCT.coef_arrays{1};
% C_QUANT = C_STRUCT.quant_tables{1};
wetConst = 10^13;
sgm = 2^(-6);
%% Get 2D wavelet filters - Daubechies 8
% 1D high pass decomposition filter
hpdf = [-0.0544158422, 0.3128715909, -0.6756307363, 0.5853546837, 0.0158291053, -0.2840155430, -0.0004724846, 0.1287474266, 0.0173693010, -0.0440882539, ...
-0.0139810279, 0.0087460940, 0.0048703530, -0.0003917404, -0.0006754494, -0.0001174768];
% 1D low pass decomposition filter
lpdf = (-1).^(0:numel(hpdf)-1).*fliplr(hpdf);
F{1} = lpdf'*hpdf;
F{2} = hpdf'*lpdf;
F{3} = hpdf'*hpdf;
STEGO=C_STRUCT;
for index_color=1:3
if (index_color==1)
C_QUANT = C_STRUCT.quant_tables{index_color};
else
C_QUANT = C_STRUCT.quant_tables{2};
end
C_COEFFS = C_STRUCT.coef_arrays{index_color};
fun= @(x) x.*C_QUANT;
% Dequantization
xi_back= blockproc(C_COEFFS,[8 8],fun);
fun=@idct2;
C_SPATIAL = blockproc(xi_back,[8 8],fun)+128;
%% Pre-compute impact in spatial domain when a jpeg coefficient is changed by 1
spatialImpact = cell(8, 8);
for bcoord_i=1:8
for bcoord_j=1:8
testCoeffs = zeros(8, 8);
testCoeffs(bcoord_i, bcoord_j) = 1;
spatialImpact{bcoord_i, bcoord_j} = idct2(testCoeffs)*C_QUANT(bcoord_i, bcoord_j);
end
end
%% Pre compute impact on wavelet coefficients when a jpeg coefficient is changed by 1
waveletImpact = cell(numel(F), 8, 8);
for Findex = 1:numel(F)
for bcoord_i=1:8
for bcoord_j=1:8
waveletImpact{Findex, bcoord_i, bcoord_j} = imfilter(spatialImpact{bcoord_i, bcoord_j}, F{Findex}, 'full');
end
end
end
%% Create reference cover wavelet coefficients (LH, HL, HH)
% Embedding should minimize their relative change. Computation uses mirror-padding
padSize = max([size(F{1})'; size(F{2})']);
C_SPATIAL_PADDED = padarray(C_SPATIAL, [padSize padSize], 'symmetric'); % pad image
RC = cell(size(F));
for i=1:numel(F)
RC{i} = imfilter(C_SPATIAL_PADDED, F{i});
end
[k, l] = size(C_COEFFS);
nzAC = nnz(C_COEFFS)-nnz(C_COEFFS(1:8:end,1:8:end));
rho = zeros(k, l);
tempXi = cell(3, 1);
%% Computation of costs
for row = 1:k
for col = 1:l
modRow = mod(row-1, 8)+1;
modCol = mod(col-1, 8)+1;
subRows = row-modRow-6+padSize:row-modRow+16+padSize;
subCols = col-modCol-6+padSize:col-modCol+16+padSize;
for fIndex = 1:3
% compute residual
RC_sub = RC{fIndex}(subRows, subCols);
% get differences between cover and stego
wavCoverStegoDiff = waveletImpact{fIndex, modRow, modCol};
% compute suitability
tempXi{fIndex} = abs(wavCoverStegoDiff) ./ (abs(RC_sub)+sgm);
end
rhoTemp = tempXi{1} + tempXi{2} + tempXi{3};
rho(row, col) = sum(rhoTemp(:));
end
end
rhoM1 = rho;
rhoP1 = rho;
rhoP1(rhoP1 > wetConst) = wetConst;
rhoP1(isnan(rhoP1)) = wetConst;
rhoP1(C_COEFFS > 1023) = wetConst;
rhoM1(rhoM1 > wetConst) = wetConst;
rhoM1(isnan(rhoM1)) = wetConst;
rhoM1(C_COEFFS < -1023) = wetConst;
%% Embedding simulation
STEGO.coef_arrays{index_color} = EmbeddingSimulator(C_COEFFS, rhoP1, rhoM1, round(payload*nzAC));
try
jpeg_write(STEGO, stego);
catch
error('ERROR (problem with saving the stego image)')
end
end
function [y, pChangeP1, pChangeM1] = EmbeddingSimulator(x, rhoP1, rhoM1, m)
x = double(x);
n = numel(x);
lambda = calc_lambda(rhoP1, rhoM1, m, n);
pChangeP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pChangeM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
randChange = rand(size(x));
y = x;
y(randChange < pChangeP1) = y(randChange < pChangeP1) + 1;
y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) = y(randChange >= pChangeP1 & randChange < pChangeP1+pChangeM1) - 1;
function lambda = calc_lambda(rhoP1, rhoM1, message_length, n)
l3 = 1e+3;
m3 = double(message_length + 1);
iterations = 0;
while m3 > message_length
l3 = l3 * 2;
pP1 = (exp(-l3 .* rhoP1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
pM1 = (exp(-l3 .* rhoM1))./(1 + exp(-l3 .* rhoP1) + exp(-l3 .* rhoM1));
m3 = ternary_entropyf(pP1, pM1);
iterations = iterations + 1;
if (iterations > 10)
lambda = l3;
return;
end
end
l1 = 0;
m1 = double(n);
lambda = 0;
alpha = double(message_length)/n;
% limit search to 30 iterations
% and require that relative payload embedded is roughly within 1/1000 of the required relative payload
while (double(m1-m3)/n > alpha/1000.0 ) && (iterations<30)
lambda = l1+(l3-l1)/2;
pP1 = (exp(-lambda .* rhoP1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
pM1 = (exp(-lambda .* rhoM1))./(1 + exp(-lambda .* rhoP1) + exp(-lambda .* rhoM1));
m2 = ternary_entropyf(pP1, pM1);
if m2 < message_length
l3 = lambda;
m3 = m2;
else
l1 = lambda;
m1 = m2;
end
iterations = iterations + 1;
end
end
function Ht = ternary_entropyf(pP1, pM1)
pP1 = pP1(:);
pM1 = pM1(:);
H1= -(pP1.*log2(pP1));
H1(isnan(H1)) = 0;
H2= -(pM1.*log2(pM1));
H2(isnan(H2)) = 0;
H3= -((1-pP1-pM1).*log2(1-pP1-pM1));
H3(isnan(H3)) = 0;
% Ht = -(pP1.*log2(pP1))-(pM1.*log2(pM1))-((1-pP1-pM1).*log2(1-pP1-pM1));
Ht = H1 + H2 + H3;
Ht = sum(Ht);
end
end
end
|
github
|
daniellerch/aletheia-master
|
ensemble_training.m
|
.m
|
aletheia-master/aletheia-octave/octave/ensemble_training.m
| 25,595 |
utf_8
|
b967dd7b363b4163b56725f5003306f1
|
function [trained_ensemble,results] = ensemble_training(Xc,Xs,settings)
% -------------------------------------------------------------------------
% Ensemble Classification | June 2013 | version 2.0
% -------------------------------------------------------------------------
% The purpose of version 2.0 is to simplify everything as much as possible.
% Here is a list of the main modifications compared to the first version of
% the ensemble classifier:
% - Instead of a single routine, we separated training form testing. This
% allows for more flexibility in the usage.
% - Training outputs the data structure 'trained_ensemble' which allows
% for easy storing of the trained classifier.
% - Ensemble now doesn't accept paths to features any more. Instead, it
% requires the features directly (Xc - cover features, Xs - stego
% features). Xc and Xs must have the same dimension and must contain
% synchronized cover/stego pairs - see the attached tutorial for more
% details on this.
% - There is no output into a log file. So there is no hard-drive access
% at all now.
% - Since the training and testing routines were separated, our ensemble
% implementation no longer takes care of training/testing divisions.
% This is the responsibility of the user now. Again, see the attached
% tutorial for examples.
% - Bagging is now always on
% - We fixed the fclose bug (Error: too many files open)
% - Covariance caching option was removed
% - Added settings.verbose = 2 option (screen output of only the last row)
% - Ensemble now works even if full dimension is equal to 1 or 2. If equal
% to 1, multiple decisions are still combined as different base learners
% are trained on different bootstrap samples (bagging).
% -------------------------------------------------------------------------
% Copyright (c) 2013 DDE Lab, Binghamton University, NY.
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from DDE Lab. DDE Lab does not warrant the
% operation of the program will be uninterrupted or error-free. The
% end-user understands that the program was developed for research purposes
% and is advised not to rely exclusively on the program for any reason. In
% no event shall Binghamton University or DDE Lab be liable to any party
% for direct, indirect, special, incidental, or consequential damages,
% including lost profits, arising out of the use of this software. DDE Lab
% disclaims any warranties, and has no obligations to provide maintenance,
% support, updates, enhancements or modifications.
% -------------------------------------------------------------------------
% Contact: [email protected] | [email protected] | June 2013
% http://dde.binghamton.edu/download/ensemble
% -------------------------------------------------------------------------
% References:
% [1] - J. Kodovsky, J. Fridrich, and V. Holub. Ensemble classifiers for
% steganalysis of digital media. IEEE Transactions on Information Forensics
% and Security. Currently under review.
% -------------------------------------------------------------------------
% INPUT:
% Xc - cover features in a row-by-row manner
% Xs - corresponding stego features (needs to be synchronized!)
% settings
% .seed_subspaces (default = random) - PRNG seed for random subspace
% generation
% .seed_bootstrap (default = random) - PRNG seed for bootstrap samples
% generation
% .d_sub (default = 'automatic') - random subspace dimensionality; either
% an integer (e.g. 200) or the string 'automatic' is accepted; in
% the latter case, an automatic search for the optimal subspace
% dimensionality is performed, see [1] for more details
% .L (default = 'automatic') - number of random subspaces / base
% learners; either an integer (e.g. 50) or the string 'automatic'
% is accepted; in the latter case, an automatic stopping criterion
% is used, see [1] for more details
% .verbose (default = 0) - turn on/off screen output
% = 0 ... no screen output
% = 1 ... full screen output
% = 2 ... screen output of only the last row (results)
%
% Parameters for the search for d_sub (when .d_sub = 'automatic'):
%
% .k_step (default = 200) - initial step for d_sub when searching from
% left (stage 1 of Algorithm 2 in [1])
% .Eoob_tolerance (default = 0.02) - the relative tolerance for the
% minimality of OOB within the search, i.e. specifies the stopping
% criterion for the stage 2 in Algorithm 2
%
% Both default parameters work well for most of the steganalysis scenarios.
%
% Parameters for automatic stopping criterion for L (when .L ='automatic');
% see [1] for more details:
%
% .L_kernel (default = ones(1,5)/5) - over how many values of OOB
% estimates is the moving average taken over
% .L_min_length (default = 25) - the minimum number of random subspaces
% that will be generated
% .L_memory (default = 50) - how many last OOB estimates need to stay in
% the epsilon tube
% .L_epsilon (default = 0.005) - specification of the epsilon tube
%
% According to our experiments, these values are sufficient for most of the
% steganalysis tasks (different algorithms and features). Nevertheless, any
% of these parameters can be modified before calling the ensemble if
% desired.
% -------------------------------------------------------------------------
% OUTPUT:
% trained_ensemble - cell array of individual FLD base learners, each
% containing the following three fields:
% - subspace - random subspace indices
% - w - vector of weights (normal vector to the decision boundary)
% - b - bias
% results - data structure with additional results of the training
% procedure (training time, progress of the OOB error estimate,
% summary of the search for d_sub, etc. See the attached tutorial
% where we use some of these pieces of information for demonstrative
% purposes
% -------------------------------------------------------------------------
if ~exist('settings','var'), settings.all_default = 1; end
% check settings, set default values, initial screen print
[Xc,Xs,settings] = check_initial_setup(Xc,Xs,settings);
% initialization of the search for d_sub
[SEARCH,settings,search_counter,MIN_OOB,OOB.error] = initialize_search(settings);
% search loop (if search for d_sub is to be executed)
while SEARCH.in_progress
search_counter = search_counter+1;
% initialization
[SEARCH.start_time_current_d_sub,i,next_random_subspace,TXT,base_learner] = deal(tic,0,1,'',cell(settings.max_number_base_learners,1));
% loop over individual base learners
while next_random_subspace
i = i+1;
%%% RANDOM SUBSPACE GENERATION
%base_learner{i}.subspace = generate_random_subspace(settings.randstream.subspaces,settings.max_dim,settings.d_sub);
base_learner{i}.subspace = generate_random_subspace(settings.max_dim,settings.d_sub);
%%% BOOTSTRAP INITIALIZATION
OOB = bootstrap_initialization(Xc,Xs,OOB,settings);
%%% TRAINING PHASE
base_learner{i} = FLD_training(Xc,Xs,base_learner{i},OOB,settings);
%%% OOB ERROR ESTIMATION
OOB = update_oob_error_estimates(Xc,Xs,base_learner{i},OOB,i);
[next_random_subspace,MSG] = getFlag_nextRandomSubspace(i,OOB,settings);
% SCREEN OUTPUT
CT = double(toc(SEARCH.start_time_current_d_sub));
%%TXT = updateTXT(TXT,sprintf(' - d_sub %s : OOB %.4f : L %i : T %.1f sec%s',k_to_string(settings.d_sub),OOB.error,i,CT,MSG),settings);
end % while next_random_subspace
results.search.d_sub(search_counter) = settings.d_sub;
%%updateLog_swipe(settings,'\n');
if OOB.error<MIN_OOB
% found the best value of k so far
MIN_OOB = OOB.error;
results.optimal_L = i;
results.optimal_d_sub = settings.d_sub;
results.optimal_OOB = OOB.error;
results.OOB_progress = OOB.y;
trained_ensemble = base_learner(1:i);
end
[settings,SEARCH] = update_search(settings,SEARCH,OOB.error);
results = add_search_info(results,settings,search_counter,SEARCH,i,CT);
clear base_learner OOB
OOB.error = 1;
end % while search_in_progress
% training time evaluation
results.training_time = toc(uint64(settings.start_time));
%%updateLog_swipe(settings,'# -------------------------\n');
%%updateLog_swipe(settings,sprintf('optimal d_sub %i : OOB %.4f : L %i : T %.1f sec\n',results.optimal_d_sub,results.optimal_OOB,results.optimal_L,results.training_time),1);
% -------------------------------------------------------------------------
% SUPPORTING FUNCTIONS
% -------------------------------------------------------------------------
function [Xc,Xs,settings] = check_initial_setup(Xc,Xs,settings)
% check settings, set default values
if size(Xc,2)~=size(Xs,2)
error('Ensemble error: cover/stego features must have the same dimension.');
end
if size(Xc,1)~=size(Xs,1)
error('Ensemble error: cover/stego feature matrices must have the same number of rows (corresponding images!).');
end
% convert to single precision (speedup)
Xc = single(Xc);
Xs = single(Xs);
settings.start_time = tic;
% settings.randstream.main = RandStream('mt19937ar','Seed',sum(100*clock));
%--settings.randstream.main = RandStream('mt19937ar','Seed',1);
% if PRNG seeds for random subspaces and bootstrap samples not specified, generate them randomly
if ~isfield(settings,'seed_subspaces')
%--settings.seed_subspaces = ceil(rand(settings.randstream.main)*1e9);
settings.seed_subspaces = ceil(rand()*1e9);
end
if ~isfield(settings,'seed_bootstrap')
%--settings.seed_bootstrap = ceil(rand(settings.randstream.main)*1e9);
settings.seed_bootstrap = ceil(rand()*1e9);
end
%--settings.randstream.subspaces = RandStream('mt19937ar','Seed',settings.seed_subspaces);
%--settings.randstream.bootstrap = RandStream('mt19937ar','Seed',settings.seed_bootstrap);
if ~isfield(settings,'L'), settings.L = 'automatic'; end
if ~isfield(settings,'d_sub'), settings.d_sub = 'automatic'; end
if ~isfield(settings,'verbose'), settings.verbose = 0; end
if ~isfield(settings,'max_number_base_learners'), settings.max_number_base_learners = 500; end
% Set default values for the automatic stopping criterion for L
if ischar(settings.L)
if ~isfield(settings,'L_kernel'), settings.L_kernel = ones(1,5)/5; end
if ~isfield(settings,'L_min_length'), settings.L_min_length = 25; end
if ~isfield(settings,'L_memory'), settings.L_memory = 50; end
if ~isfield(settings,'L_epsilon'), settings.L_epsilon = 0.005; end
settings.bootstrap = 1;
end
if ~isfield(settings,'ignore_nearly_singular_matrix_warning')
settings.ignore_nearly_singular_matrix_warning = 1;
end
% Set default values for the search for the subspace dimension d_sub
if ischar(settings.d_sub)
if ~isfield(settings,'Eoob_tolerance'), settings.Eoob_tolerance = 0.02; end
if ~isfield(settings,'d_sub_step'), settings.d_sub_step = 200; end
settings.bootstrap = 1;
settings.search_for_d_sub = 1;
else
settings.search_for_d_sub = 0;
end
settings.max_dim = size(Xc,2);
% if full dimensionality is 1, just do a single FLD
if settings.max_dim == 1
settings.d_sub = 1;
settings.search_for_d_sub = 0;
end
initial_screen_output(Xc,Xs,settings);
function initial_screen_output(Xc,Xs,settings)
% initial screen output
if settings.verbose~=1,return; end
fprintf('# -------------------------\n');
fprintf('# Ensemble classification\n');
fprintf('# - Training samples: %i (%i/%i)\n',size(Xc,1)+size(Xs,1),size(Xc,1),size(Xs,1));
fprintf('# - Feature-space dimensionality: %i\n',size(Xc,2));
if ~ischar(settings.L)
fprintf('# - L : %i\n',settings.L);
else
fprintf('# - L : %s (min %i, max %i, length %i, eps %.5f)\n',settings.L,settings.L_min_length,settings.max_number_base_learners,settings.L_memory,settings.L_epsilon);
end
if ischar(settings.d_sub)
fprintf('# - d_sub : automatic (Eoob tolerance %.4f, step %i)\n',settings.Eoob_tolerance,settings.d_sub_step);
else
fprintf('# - d_sub : %i\n',settings.d_sub);
end
fprintf('# - Seed 1 (subspaces) : %i\n',settings.seed_subspaces);
fprintf('# - Seed 2 (bootstrap) : %i\n',settings.seed_bootstrap);
fprintf('# -------------------------\n');
function [next_random_subspace,TXT] = getFlag_nextRandomSubspace(i,OOB,settings)
% decide whether to generate another random subspace or not, based on the
% settings
TXT='';
if ischar(settings.L)
if strcmp(settings.L,'automatic')
% automatic criterion for termination
next_random_subspace = 1;
if ~isfield(OOB,'x'), next_random_subspace = 0; return; end
if length(OOB.x)<settings.L_min_length, return; end
A = convn(OOB.y(max(length(OOB.y)-settings.L_memory+1,1):end),settings.L_kernel,'valid');
V = abs(max(A)-min(A));
if V<settings.L_epsilon
next_random_subspace = 0;
return;
end
if i == settings.max_number_base_learners,
% maximal number of base learners reached
next_random_subspace = 0;
TXT = ' (maximum reached)';
end
return;
end
else
% fixed number of random subspaces
if i<settings.L
next_random_subspace = 1;
else
next_random_subspace = 0;
end
end
function [settings,SEARCH] = update_search(settings,SEARCH,currErr)
% update search progress
if ~settings.search_for_d_sub, SEARCH.in_progress = 0; return; end
SEARCH.E(settings.d_sub==SEARCH.x) = currErr;
% any other unfinished values of k?
unfinished = find(SEARCH.E==-1);
if ~isempty(unfinished), settings.d_sub = SEARCH.x(unfinished(1)); return; end
% check where is minimum
[MINIMAL_ERROR,minE_id] = min(SEARCH.E);
if SEARCH.step == 1 || MINIMAL_ERROR == 0
% smallest possible step or error => terminate search
SEARCH.in_progress = 0;
SEARCH.optimal_d_sub = SEARCH.x(SEARCH.E==MINIMAL_ERROR);
SEARCH.optimal_d_sub = SEARCH.optimal_d_sub(1);
return;
end
if minE_id == 1
% smallest k is the best => reduce step
SEARCH.step = floor(SEARCH.step/2);
SEARCH = add_gridpoints(SEARCH,SEARCH.x(1)+SEARCH.step*[-1 1]);
elseif minE_id == length(SEARCH.x)
% largest k is the best
if SEARCH.x(end) + SEARCH.step <= settings.max_dim && (min(abs(SEARCH.x(end) + SEARCH.step-SEARCH.x))>SEARCH.step/2)
% continue to the right
SEARCH = add_gridpoints(SEARCH,SEARCH.x(end) + SEARCH.step);
else
% hitting the full dimensionality
if (MINIMAL_ERROR/SEARCH.E(end-1) >= 1 - settings.Eoob_tolerance) ... % desired tolerance fulfilled
|| SEARCH.E(end-1)-MINIMAL_ERROR < 5e-3 ... % maximal precision in terms of error set to 0.5%
|| SEARCH.step<SEARCH.x(minE_id)*0.05 ... % step is smaller than 5% of the optimal value of k
% stopping criterion met
SEARCH.in_progress = false;
SEARCH.optimal_d_sub = SEARCH.x(SEARCH.E==MINIMAL_ERROR);
SEARCH.optimal_d_sub = SEARCH.optimal_d_sub(1);
return;
else
% reduce step
SEARCH.step = floor(SEARCH.step/2);
if SEARCH.x(end) + SEARCH.step <= settings.max_dim
SEARCH = add_gridpoints(SEARCH,SEARCH.x(end)+SEARCH.step*[-1 1]);
else
SEARCH = add_gridpoints(SEARCH,SEARCH.x(end)-SEARCH.step);
end;
end
end
elseif (minE_id == length(SEARCH.x)-1) ... % if lowest is the last but one
&& (settings.d_sub + SEARCH.step <= settings.max_dim) ... % one more step to the right is still valid (less than d)
&& (min(abs(settings.d_sub + SEARCH.step-SEARCH.x))>SEARCH.step/2) ... % one more step to the right is not too close to any other point
&& ~(SEARCH.E(end)>SEARCH.E(end-1) && SEARCH.E(end)>SEARCH.E(end-2)) % the last point is not worse than the two previous ones
% robustness ensurance, try one more step to the right
SEARCH = add_gridpoints(SEARCH,settings.d_sub + SEARCH.step);
else
% best k is not at the edge of the grid (and robustness is resolved)
err_around = mean(SEARCH.E(minE_id+[-1 1]));
if (MINIMAL_ERROR/err_around >= 1 - settings.Eoob_tolerance) ... % desired tolerance fulfilled
|| err_around-MINIMAL_ERROR < 5e-3 ... % maximal precision in terms of error set to 0.5%
|| SEARCH.step<SEARCH.x(minE_id)*0.05 ... % step is smaller than 5% of the optimal value of k
% stopping criterion met
SEARCH.in_progress = false;
SEARCH.optimal_d_sub = SEARCH.x(SEARCH.E==MINIMAL_ERROR);
SEARCH.optimal_d_sub = SEARCH.optimal_d_sub(1);
return;
else
% reduce step
SEARCH.step = floor(SEARCH.step/2);
SEARCH = add_gridpoints(SEARCH,SEARCH.x(minE_id)+SEARCH.step*[-1 1]);
end
end
unfinished = find(SEARCH.E==-1);
settings.d_sub = SEARCH.x(unfinished(1));
return;
function [SEARCH,settings,search_counter,MIN_OOB,OOB_error] = initialize_search(settings)
% search for d_sub initialization
SEARCH.in_progress = 1;
if settings.search_for_d_sub
% automatic search for d_sub
if settings.d_sub_step >= settings.max_dim/4, settings.d_sub_step = floor(settings.max_dim/4); end
if settings.max_dim < 10, settings.d_sub_step = 1; end
SEARCH.x = settings.d_sub_step*[1 2 3];
if settings.max_dim==2, SEARCH.x = [1 2]; end
SEARCH.E = -ones(size(SEARCH.x));
SEARCH.terminate = 0;
SEARCH.step = settings.d_sub_step;
settings.d_sub = SEARCH.x(1);
end
search_counter = 0;
MIN_OOB = 1;
OOB_error = 1;
function TXT = updateTXT(old,TXT,settings)
if isfield(settings,'kmin')
if length(TXT)>3
if ~strcmp(TXT(1:3),' - ')
TXT = [' - ' TXT];
end
end
end
if settings.verbose==1
if exist('/home','dir')
% do not delete on cluster, it displays incorrectly when writing through STDOUT into file
fprintf(['\n' TXT]);
else
fprintf([repmat('\b',1,length(old)) TXT]);
end
end
function s = k_to_string(k)
if length(k)==1
s = num2str(k);
return;
end
s=['[' num2str(k(1))];
for i=2:length(k)
s = [s ',' num2str(k(i))]; %#ok<AGROW>
end
s = [s ']'];
function updateLog_swipe(settings,TXT,final)
if ~exist('final','var'), final=0; end
if settings.verbose==1 || (settings.verbose==2 && final==1), fprintf(TXT); end
function OOB = bootstrap_initialization(Xc,Xs,OOB,settings)
% initialization of the structure for OOB error estimates
%--OOB.SUB = floor(size(Xc,1)*rand(settings.randstream.bootstrap,size(Xc,1),1))+1;
OOB.SUB = floor(size(Xc,1)*rand(size(Xc,1),1))+1;
OOB.ID = setdiff(1:size(Xc,1),OOB.SUB);
if ~isfield(OOB,'Xc')
OOB.Xc.fusion_majority_vote = zeros(size(Xc,1),1); % majority voting fusion
OOB.Xc.num = zeros(size(Xc,1),1); % number of fused votes
OOB.Xs.fusion_majority_vote = zeros(size(Xs,1),1); % majority voting fusion
OOB.Xs.num = zeros(size(Xs,1),1); % number of fused votes
end
if ~isfield(OOB,'randstream_for_ties')
% Doesn't really matter that we fix the seed here. This will be used
% only for resolving voting ties. We are fixing this in order to make
% all results nicely reproducible.
%--OOB.randstream_for_ties = RandStream('mt19937ar','Seed',1);
end
function [base_learner] = findThreshold(Xm,Xp,base_learner)
% find threshold through minimizing (MD+FA)/2, where MD stands for the
% missed detection rate and FA for the false alarms rate
P1 = Xm*base_learner.w;
P2 = Xp*base_learner.w;
L = [-ones(size(Xm,1),1);ones(size(Xp,1),1)];
[P,IX] = sort([P1;P2]);
L = L(IX);
Lm = (L==-1);
sgn = 1;
MD = 0;
FA = sum(Lm);
MD2=FA;
FA2=MD;
Emin = (FA+MD);
Eact = zeros(size(L-1));
Eact2 = Eact;
for idTr=1:length(P)-1
if L(idTr)==-1
FA=FA-1;
MD2=MD2+1;
else
FA2=FA2-1;
MD=MD+1;
end
Eact(idTr) = FA+MD;
Eact2(idTr) = FA2+MD2;
if Eact(idTr)<Emin
Emin = Eact(idTr);
iopt = idTr;
sgn=1;
end
if Eact2(idTr)<Emin
Emin = Eact2(idTr);
iopt = idTr;
sgn=-1;
end
end
base_learner.b = sgn*0.5*(P(iopt)+P(iopt+1));
if sgn==-1, base_learner.w = -base_learner.w; end
function OOB = update_oob_error_estimates(Xc,Xs,base_learner,OOB,i)
% update OOB error estimates
OOB.Xc.proj = Xc(OOB.ID,base_learner.subspace)*base_learner.w-base_learner.b;
OOB.Xs.proj = Xs(OOB.ID,base_learner.subspace)*base_learner.w-base_learner.b;
OOB.Xc.num(OOB.ID) = OOB.Xc.num(OOB.ID) + 1;
OOB.Xc.fusion_majority_vote(OOB.ID) = OOB.Xc.fusion_majority_vote(OOB.ID)+sign(OOB.Xc.proj);
OOB.Xs.num(OOB.ID) = OOB.Xs.num(OOB.ID) + 1;
OOB.Xs.fusion_majority_vote(OOB.ID) = OOB.Xs.fusion_majority_vote(OOB.ID)+sign(OOB.Xs.proj);
% update errors
%--TMP_c = OOB.Xc.fusion_majority_vote; TMP_c(TMP_c==0) = rand(OOB.randstream_for_ties,sum(TMP_c==0),1)-0.5;
TMP_c = OOB.Xc.fusion_majority_vote; TMP_c(TMP_c==0) = rand(sum(TMP_c==0),1)-0.5;
%--TMP_s = OOB.Xs.fusion_majority_vote; TMP_s(TMP_s==0) = rand(OOB.randstream_for_ties,sum(TMP_s==0),1)-0.5;
TMP_s = OOB.Xs.fusion_majority_vote; TMP_s(TMP_s==0) = rand(sum(TMP_s==0),1)-0.5;
OOB.error = (sum(TMP_c>0)+sum(TMP_s<0))/(length(TMP_c)+length(TMP_s));
if ~ischar(OOB) && ~isempty(OOB)
H = hist([OOB.Xc.num;OOB.Xs.num],0:max([OOB.Xc.num;OOB.Xs.num]));
avg_L = sum(H.*(0:length(H)-1))/sum(H); % average L in OOB
OOB.x(i) = avg_L;
OOB.y(i) = OOB.error;
end
function base_learner = FLD_training(Xc,Xs,base_learner,OOB,settings)
% FLD TRAINING
Xm = Xc(OOB.SUB,base_learner.subspace);
Xp = Xs(OOB.SUB,base_learner.subspace);
% remove constants
remove = false(1,size(Xm,2));
adepts = unique([find(Xm(1,:)==Xm(2,:)) find(Xp(1,:)==Xp(2,:))]);
for ad_id = adepts
U1=unique(Xm(:,ad_id));
if numel(U1)==1
U2=unique(Xp(:,ad_id));
if numel(U2)==1, if U1==U2, remove(ad_id) = true; end; end
end
end
muC = sum(Xm,1); muC = double(muC)/size(Xm,1);
muS = sum(Xp,1); muS = double(muS)/size(Xp,1);
mu = (muS-muC)';
% calculate sigC
xc = bsxfun(@minus,Xm,muC);
sigC = xc'*xc;
sigC = double(sigC)/size(Xm,1);
% calculate sigS
xc = bsxfun(@minus,Xp,muS);
sigS = xc'*xc;
sigS = double(sigS)/size(Xp,1);
sigCS = sigC + sigS;
% regularization
sigCS = sigCS + 1e-10*eye(size(sigC,1));
% check for NaN values (may occur when the feature value is constant over images)
nan_values = sum(isnan(sigCS))>0;
nan_values = nan_values | remove;
sigCS = sigCS(~nan_values,~nan_values);
mu = mu(~nan_values);
lastwarn('');
warning('off','MATLAB:nearlySingularMatrix');
warning('off','MATLAB:singularMatrix');
base_learner.w = sigCS\mu;
% regularization (if necessary)
[txt,warnid] = lastwarn(); %#ok<ASGLU>
while strcmp(warnid,'MATLAB:singularMatrix') || (strcmp(warnid,'MATLAB:nearlySingularMatrix') && ~settings.ignore_nearly_singular_matrix_warning)
lastwarn('');
if ~exist('counter','var'), counter=1; else counter = counter*5; end
sigCS = sigCS + counter*eps*eye(size(sigCS,1));
base_learner.w = sigCS\mu;
[txt,warnid] = lastwarn(); %#ok<ASGLU>
end
warning('on','MATLAB:nearlySingularMatrix');
warning('on','MATLAB:singularMatrix');
if length(sigCS)~=length(sigC)
% resolve previously found NaN values, set the corresponding elements of w equal to zero
w_new = zeros(length(sigC),1);
w_new(~nan_values) = base_learner.w;
base_learner.w = w_new;
end
% find threshold to minimize FA+MD
[base_learner] = findThreshold(Xm,Xp,base_learner);
function results = add_search_info(results,settings,search_counter,SEARCH,i,CT)
% update information about d_sub search
if settings.search_for_d_sub
results.search.OOB(search_counter) = SEARCH.E(SEARCH.x==results.search.d_sub(search_counter));
results.search.L(search_counter) = i;
results.search.time(search_counter) = CT;
end
function SEARCH = add_gridpoints(SEARCH,points)
% add new points for the search for d_sub
for point=points
if SEARCH.x(1)>point
SEARCH.x = [point SEARCH.x];
SEARCH.E = [-1 SEARCH.E];
continue;
end
if SEARCH.x(end)<point
SEARCH.x = [SEARCH.x point];
SEARCH.E = [SEARCH.E -1];
continue;
end
pos = 2;
while SEARCH.x(pos+1)<point,pos = pos+1; end
SEARCH.x = [SEARCH.x(1:pos-1) point SEARCH.x(pos:end)];
SEARCH.E = [SEARCH.E(1:pos-1) -1 SEARCH.E(pos:end)];
end
%--function subspace = generate_random_subspace(randstr,max_dim,d_sub)
function subspace = generate_random_subspace(max_dim,d_sub)
%subspace = randperm(randstr,max_dim);
subspace = randperm(max_dim);
subspace = subspace(1:d_sub);
|
github
|
daniellerch/aletheia-master
|
HILL_sigma_spam_PSRM.m
|
.m
|
aletheia-master/aletheia-octave/octave/HILL_sigma_spam_PSRM.m
| 2,143 |
utf_8
|
98d9ae16440c8a4e9a55029502756479
|
function f = HILL_sigma_spam_PSRM(IMAGE)
if ischar(IMAGE)
X = double(imread(IMAGE));
else
X = double(IMAGE);
end
q = 1;
P = f_cal_cost(X);
f = sigma_spam_PSRM(X, q, P);
end
function cost = f_cal_cost(cover)
% Copyright (c) 2014 Shenzhen University,
% All Rights Reserved.
% -------------------------------------------------------------------------
% Permission to use, copy, modify, and distribute this software for
% educational, research and non-profit purposes, without fee, and without a
% written agreement is hereby granted, provided that this copyright notice
% appears in all copies. The program is supplied "as is," without any
% accompanying services from Shenzhen University.
% -------------------------------------------------------------------------
% Author: Ming Wang
% -------------------------------------------------------------------------
% Contact: [email protected]
% [email protected]
% -------------------------------------------------------------------------
% Input: cover ... cover image%
% Output: cost ....... costs value of all pixels
% -------------------------------------------------------------------------
% [1] A New Cost Function for Spatial Image Steganography,
% B.Li, M.Wang,J.Huang and X.Li, to be presented at IEEE International Conference on Image Processing, 2014.
% -------------------------------------------------------------------------
%Get filter
HF1=[-1,2,-1;2,-4,2;-1,2,-1];
H2 = fspecial('average',[3 3]);
%% Get cost
cover=double(cover);
sizeCover=size(cover);
padsize=max(size(HF1));
coverPadded = padarray(cover, [padsize padsize], 'symmetric');% add padding
R1 = conv2(coverPadded,HF1, 'same');%mirror-padded convolution
W1 = conv2(abs(R1),H2,'same');
if mod(size(HF1, 1), 2) == 0, W1= circshift(W1, [1, 0]); end;
if mod(size(HF1, 2), 2) == 0, W1 = circshift(W1, [0, 1]); end;
W1 = W1(((size(W1, 1)-sizeCover(1))/2)+1:end-((size(W1, 1)-sizeCover(1))/2), ((size(W1, 2)-sizeCover(2))/2)+1:end-((size(W1, 2)-sizeCover(2))/2));
rho=1./(W1+10^(-10));
HW = fspecial('average',[15 15]);
cost = imfilter(rho, HW ,'symmetric','same');
end
|
github
|
dylewsky/MultiRes_Discovery-master
|
Simple_Toy_Model.m
|
.m
|
MultiRes_Discovery-master/Example_Simple_Toy_Model/Simple_Toy_Model.m
| 21,750 |
utf_8
|
3191468cb3fb9ecdf1f5d0f154223343
|
%%% DMD SCALE SEPARATION FOR A SIMPLE MULTISCALE TOY MODEL
%%%
%%% Before running, make sure to download and set up the optdmd package
%%% available here: https://github.com/duqbo/optdmd
%%%
%%% This code reproduces the results of Sec. III of "Dynamic mode decomposition
%%% for multiscale nonlinear physics," by Dylewsky, Tao, and Kutz
%%% (DOI: 10.1103/PhysRevE.99.063311)
clear variables; close all; clc
%% Simulate System
% parameters
a0=0; b0=0; r0=sqrt(2^2+0.8^2); theta0=atan2(0.8,2);
x1_0 = 0;
x2_0 = 0.5;
y1_0 = 0;
y2_0 = 0.5;
x0 = [x1_0; x2_0; y1_0; y2_0];
epsilon=0.01;
delta = 4;
T=48;
% RK4 integration of the mixed system
h=epsilon/100;
TimeSpan = 0:h:T; TimeSteps=length(TimeSpan)-1;
% x = zeros(4,TimeSteps+1);
% x(:,1) = [x1_0; x2_0; y1_0; y2_0];
[t, x] = ode45(@(t,x) rhs(x,delta,epsilon),TimeSpan,x0);
tStep = mean(diff(t))*4;
nSteps = ceil(T/tStep);
tN = 0:tStep:T;
tN = tN(1:nSteps); %match to nSteps
xOld = x;
x = interp1(t,xOld,tN); %enforce evenly spaced time steps
TimeSpan = tN;
% Plot Results
plot(TimeSpan, x);
title('Raw data');
xlabel('Time');
% Apply Linear Mixing
rng(111); %seed
n = size(x,2);
% generate a random unitary matrix M
X = rand(n)/sqrt(2);
[Q,R] = qr(X);
R = diag(diag(R)./abs(diag(R)));
M = real(Q*R);
x = x * M;
save('Simple_Toy_Model_Raw_Data.mat','x','TimeSpan','M');
%% Run Sliding-Window DMD
x = x.';
r = size(x,1); %rank to fit w/ optdmd
imode = 1; %parameter for optdmd code
% imode = 1, fit full data, slower
% imode = 2, fit data projected onto first r POD modes
% or columns of varargin{2} (should be at least r
% columns in varargin{2})
nComponents = 2; %number of distinct time scales present
global_SVD = 1; %use global SVD modes for each DMD rather than individual SVD on each window
if global_SVD == 1
[u,~,v] = svd(x,'econ');
u = u(:,1:r); %just first r modes
v = v(:,1:r);
end
% Method for making initial guess of DMD eigenvalues:
% Recommended settings for first run:
initialize_artificially = 0; %this is required for use_last_freq OR use_median_freqs
use_last_freq = 0;
use_median_freqs = 0; %mutually exclusive w/ use_last_freq
% Recommended settings for subsequent runs (using clustering information
% obtained from the first run):
% initialize_artificially = 1; %this is required for use_last_freq OR use_median_freqs
% use_last_freq = 0;
% use_median_freqs = 1; %mutually exclusive w/ use_last_freq
if use_median_freqs == 1
load('km_centroids.mat'); % Load pre-defined eigenvalue guesses
freq_meds = repelem(sqrt(km_centroids),r/nComponents);
end
wSteps = 5500; % Window size (in time steps)
nSplit = 21; %number of windows if they were non-overlapping
nSteps = wSteps * nSplit;
nVars = size(x,1);
thresh_pct = 1;
stepSize = 20;
nSlide = floor((nSteps-wSteps)/stepSize); % Number of sliding-window iterations
save('mwDMD_params.mat','r','nComponents','initialize_artificially','use_last_freq','use_median_freqs','wSteps','nSplit','nSteps','nVars','thresh_pct','stepSize','nSlide');
%% execute optDMD
corner_sharpness = 16; %higher = sharper corners
lv_kern = tanh(corner_sharpness*(1:wSteps)/wSteps) - tanh(corner_sharpness*((1:wSteps)-wSteps)/wSteps) - 1;
mr_res = cell(nSlide,1);
for k = 1:nSlide
sampleStart = stepSize*(k-1) + 1;
sampleSteps = sampleStart : sampleStart + wSteps - 1;
xSample = x(:,sampleSteps);
tSample = TimeSpan(sampleSteps);
mr_res{k}.x = xSample;
mr_res{k}.t = tSample;
c = mean(xSample,2); %subtract off mean before rounding corners
xSample = xSample - repmat(c,1,size(xSample,2));
xSample = xSample.*repmat(lv_kern,nVars,1); %round off corners
t_start = tSample(1);
tSample = tSample - t_start;
if global_SVD == 0
[u,~,~] = svd(xSample,'econ');
u = u(:,1:r);
end
if (exist('e_init','var')) && (initialize_artificially == 1)
[w, e, b] = optdmd(xSample,tSample,r,imode,[],e_init,u);
else
[w, e, b] = optdmd(xSample,tSample,r,imode,[],[],u);
end
if use_last_freq == 1
e_init = e;
end
if use_median_freqs == 1
[eSq, eInd] = sort(e.*conj(e)); %match order to that of freq_meds
freq_angs = angle(e(eInd));
e_init = exp(sqrt(-1)*freq_angs) .* freq_meds;
end
mr_res{k}.w = w;
mr_res{k}.Omega = e;
mr_res{k}.b = b;
mr_res{k}.c = c;
mr_res{k}.t_start = t_start;
end
%% Cluster Frequencies
close all;
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
all_om = [];
all_om_grouped = [];
for k = 1:nSlide
try
Omega = mr_res{k}.Omega;
catch ME
disp(['Error on k = ' num2str(k)]);
continue
end
all_om = [all_om; Omega];
[~,imSortInd] = sort(imag(Omega));
all_om_grouped = [all_om_grouped; Omega(imSortInd).'];
end
all_om_sq = conj(all_om) .* all_om;
all_om_sq = sort(all_om_sq);
all_om_sq_thresh = all_om_sq(floor(thresh_pct*length(all_om_sq)));
all_om_sq = all_om_sq(1:floor(thresh_pct*length(all_om_sq)));
[~, km_centroids] = kmeans(all_om_sq,nComponents,'Distance','cityblock','Replicates',5);
[km_centroids,sortInd] = sort(km_centroids);
for k = 1:nSlide
try
omega = mr_res{k}.Omega;
catch ME
continue
end
om_sq = omega.*conj(omega);
om_sq_dists = (repmat(km_centroids.',r,1) - repmat(om_sq,1,nComponents)).^2;
[~,om_class] = min(om_sq_dists,[],2);
mr_res{k}.om_class = om_class;
end
if use_median_freqs == 0
save('mwDMD_mr_res.mat', 'mr_res');
else
save('mwDMD_mr_res_i2.mat', 'mr_res');
end
%% Plot MultiRes Results
close all;
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
export_result = 0;
logScale = 0;
% figure('units','pixels','Position',[0 0 1366 2*768])
% plotDims = [3 4]; %rows, columns of plot grid on screen at a given time
% plotDims = [1 4]; %rows, columns of plot grid on screen at a given time
colorList = {'b','r','g','k','y'};
x_PoT = x(:,1:nSteps);
t_PoT = TimeSpan(1:nSteps);
%res_list: [pn, level #, nSplit, sampleSteps/nSplit]
dupShift = 0; %multiplier to shift duplicate values so they can be visually distinguished
nBins = 64;
figure('units','pixels','Position',[100 100 1200 400])
% j = res_list(q,2);
% pn = res_list(q,1);
% nSplit = 2^(j-1);
% om_spec = zeros(nVars,nSteps);
all_om = [];
for k = 1:nSlide
Omega = mr_res{k}.Omega;
all_om = [all_om; Omega];
end
all_om_sq = sort(all_om .* conj(all_om));
thresh_om_sq = all_om_sq(floor(thresh_pct*length(all_om_sq)));
all_om_sq = all_om_sq(1:floor(thresh_pct*length(all_om_sq)));
subplot(2,2,[1 3]);
om_hist = histogram(all_om_sq,nBins);
mesh_pad = 10;
bin_mesh = om_hist.BinEdges(1)-mesh_pad:0.5:om_hist.BinEdges(end)+mesh_pad;
xlabel('|\omega|^2');
ylabel('Count');
title('|\omega|^2 Spectrum & k-Means Centroids');
hold on
yl = ylim;
for c = 1:nComponents
plot([km_centroids(c), km_centroids(c)], yl,'Color',colorList{c},'LineWidth',2)
end
xr = zeros(size(x(:,1:nSteps))); %reconstructed time series
xn = zeros(nSteps,1); %count # of windows contributing to each step
omega_series = nan(nVars,nSlide);
time_series = nan(nSlide,1);
for k = 1:nSlide
w = mr_res{k}.w;
b = mr_res{k}.b;
Omega = mr_res{k}.Omega;
om_class = mr_res{k}.om_class;
t = mr_res{k}.t;
c = mr_res{k}.c;
t_start = mr_res{k}.t_start;
tShift = t-t(1); %compute each segment of xr starting at "t = 0"
xr_window = w*diag(b)*exp(Omega*(t-t_start)) + c;
xr(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_window;
xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) + 1;
% Plot |omega|^2 spectrum
om_sq = conj(Omega).*Omega;
om_class = om_class(om_sq <= thresh_om_sq);
om_sq = om_sq(om_sq <= thresh_om_sq); %threshold to remove outliers
for oi = 1:length(om_sq)
for oj = oi:length(om_sq)
if (abs(om_sq(oi)-om_sq(oj))/((om_sq(oi)+om_sq(oj))/2)) <= dupShift && (oi ~= oj)
om_sq(oi) = om_sq(oi)*(1-dupShift);
om_sq(oj) = om_sq(oj)*(1+dupShift);
end
end
end
subplot(2,2,2);
for g = 1:nComponents
om_window_spec_cat = om_sq(om_class == g,:);
if isempty(om_window_spec_cat) == 1
continue
end
if length(om_window_spec_cat) == 2
omega_series(2*g-1:2*g,k) = om_window_spec_cat;
time_series(k) = mean(t);
end
if logScale == 1
for f = 1:length(om_window_spec_cat)
semilogy(mean(t),om_window_spec_cat(f),'.','Color',colorList{g},'LineWidth',1,'MarkerSize',10);
end
else
for f = 1:length(om_window_spec_cat)
plot(mean(t),om_window_spec_cat,'.','Color',colorList{g},'LineWidth',1,'MarkerSize',10);
end
end
hold on
end
title('|\omega|^2 Spectra (Moving Window)');
end
subplot(2,2,4);
plot(t_PoT,real(x_PoT),'k-','LineWidth',1.5) %plot ground truth
xlabel('t')
ylabel('Measurement Data')
xMax = max(max(abs(x_PoT)));
ylim(1.5*[-xMax, xMax]);
hold on
xr = xr./repmat(xn.',4,1); %weight xr so all steps are on equal footing
plot(t_PoT,real(xr),'b-','LineWidth',1.5) %plot averaged reconstruction
title('Input (Black); DMD Recon. (Blue)');
if export_result == 1
if lv == 1
export_fig 'manyres_opt' '-pdf';
% print(gcf, '-dpdf', 'manyres_opt.pdf');
else
export_fig 'manyres_opt' '-pdf' '-append';
% print(gcf, '-dpdf', 'manyres_opt.pdf', '-append');
end
close(gcf);
end
%% Link Consecutive Modes
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
allModes = zeros(nSlide,r,r);
allFreqs = zeros(nSlide,r);
catList = flipud(perms(1:r));
modeCats = zeros(nSlide,r);
modeCats(1,:) = 1:r; %label using order of 1st modes
allModes(1,:,:) = mr_res{1}.w;
allFreqs(1,:) = mr_res{1}.Omega;
[~,catsAsc] = sort(mr_res{1}.Omega.*conj(mr_res{1}.Omega)); %category labels in ascending frequency order
distThresh = 0; %if more than one mode is within this distance then match using derivative
permDistsHist = zeros(size(catList,1),nSlide-1);
for k = 2:nSlide
w_old = squeeze(allModes(k-1,:,:));
w = mr_res{k}.w;
permDists = zeros(size(catList,1),1);
for np = 1:size(catList,1)
permDists(np) = norm(w(:,catList(np,:))-w_old);
end
permDistsHist(:,k-1) = sort(permDists);
if nnz(permDists <= distThresh) >= 1
if k == 2 %can't compute derivative 1 step back, so skip it
[~,minCat] = min(permDists);
continue;
end
w_older = squeeze(allModes(k-2,:,:));
[~,minInds] = sort(permDists); %minInds(1) and minInds(2) point to 2 lowest distances
wPrime = w - w_old;
wPrime_old = w_old - w_older;
for j = 1:size(wPrime,2)
wPrime(:,j) = wPrime(:,j)/norm(wPrime(:,j));
wPrime_old(:,j) = wPrime_old(:,j)/norm(wPrime_old(:,j));
end
derivDists = zeros(2,1);
for np = 1:length(derivDists)
derivDists(np) = norm(wPrime(:,catList(minInds(np),:))-wPrime_old);
end
[~,minDerInd] = min(derivDists);
derivDistsSort = sort(derivDists);
permDistsSort= sort(permDists);
disp(['Derivative-Matching on k = ' num2str(k)])
if (derivDistsSort(2)-derivDistsSort(1)) > (permDistsSort(2) - permDistsSort(1))
minCat = minInds(minDerInd);
[~,minCatNaive] = min(permDists);
if minCat ~= minCatNaive
disp('Naive result was wrong!')
end
else
[~,minCat] = min(permDists);
disp('Naive result trumps derivative match')
end
else
[~,minCat] = min(permDists);
end
modeCats(k,:) = catList(minCat,:);
allModes(k,:,:) = w(:,catList(minCat,:));
allFreqs(k,:) = mr_res{k}.Omega(catList(minCat,:));
end
meanFreqsSq = sum(allFreqs.*conj(allFreqs),1)/nSlide;
if use_median_freqs == 0
save('mwDMD_allModes.mat','allModes','allFreqs');
else
save('mwDMD_allModes_i2.mat','allModes','allFreqs');
end
%% Second derivative of mode coordinates
sd_norms = zeros(r,size(allModes,1)-2);
for j = 1:r
tsPP = allModes(1:end-2,:,j) + allModes(3:end,:,j) - 2*allModes(2:end-1,:,j);
sd_norms(j,:) = vecnorm(tsPP.');
end
sd_norms = vecnorm(sd_norms).';
sd_thresh = 0.1; %threshold above which to try different permutations to reduce 2nd deriv
%can be set to 0 to just check every step
ppOverrideRatio = 0.7; %apply new permutation if 2nd deriv is reduced by at least this factor
for k = 2:nSlide-1
thisData = allModes(k-1:k+1,:,:);
tdPP = squeeze(thisData(1,:,:) + thisData(3,:,:) - 2*thisData(2,:,:));
if norm(tdPP) < sd_thresh
continue;
end
permDists = zeros(size(catList,1),1);
permData = zeros(size(thisData));
for np = 1:size(catList,1)
%hold k-1 configuration constant, permute k and k+1 registers
permData(1,:,:) = thisData(1,:,:);
permData(2:3,:,:) = thisData(2:3,:,catList(np,:));
permPP = squeeze(permData(1,:,:) + permData(3,:,:) - 2*permData(2,:,:));
permDists(np) = norm(permPP);
if permDists(np) <= ppOverrideRatio * norm(tdPP)
newCat = catList(np,:);
allModes(k:end,:,:) = allModes(k:end,:,newCat);
modeCats(k,:) = modeCats(k,newCat);
disp(['2nd Deriv. Perm. Override: k = ' num2str(k)]);
end
end
end
if use_median_freqs == 0
save('mwDMD_allModes.mat','allModes','allFreqs');
else
save('mwDMD_allModes_i2.mat','allModes','allFreqs');
end
%% Visualize Modes
figure('units','pixels','Position',[0 0 1366 768])
colorlist = {'k','r','b','g'};
w = squeeze(allModes(1,:,:));
wPlots = cell(r,r);
wTrails = cell(r,r);
trailLength = 1000; %in window steps
% Plot time series
subplot(2,4,5:8)
plot(TimeSpan(1:nSteps),x(:,1:nSteps),'LineWidth',1.5)
xlim([TimeSpan(1) TimeSpan(nSteps)])
hold on
lBound = plot([mr_res{1}.t(1) mr_res{1}.t(1)],ylim,'r-','LineWidth',2);
hold on
rBound = plot([mr_res{1}.t(end) mr_res{1}.t(end)],ylim,'r-','LineWidth',2);
hold on
% Plot 1st frame
for dim = 1:r
subplot(2,4,dim)
wi = w(dim,:);
for j = 1:r
wPlots{dim,j} = plot(real(wi(j)),imag(wi(j)),'o','Color',colorlist{j},'MarkerSize',7);
hold on
wTrails{dim,j} = plot(real(wi(j)),imag(wi(j)),'-','Color',colorlist{j},'LineWidth',0.1);
hold on
wTrails{dim,j}.Color(4) = 0.3; % 50% opacity
end
title(['Proj. Modes into Dimension ' num2str(dim)])
axis equal
xlim([-1 1])
ylim([-1 1])
xlabel('Real');
ylabel('Imag');
plot(xlim,[0 0],'k:')
hold on
plot([0 0],ylim,'k:')
hold off
end
legend([wPlots{r,catsAsc(1)},wPlots{r,catsAsc(2)},wPlots{r,catsAsc(3)},wPlots{r,catsAsc(4)}],{'LF Mode 1','LF Mode 2','HF Mode 1','HF Mode 2'},'Position',[0.93 0.65 0.05 0.2])
%Plot subsequent frames
for k = 2:nSlide
w = squeeze(allModes(k,:,:));
for dim = 1:r
% subplot(4,4,dim)
wi = w(dim,:);
for j = 1:r
wPlots{dim,j}.XData = real(wi(j));
wPlots{dim,j}.YData = imag(wi(j));
if k > trailLength
wTrails{dim,j}.XData = [wTrails{dim,j}.XData(2:end) real(wi(j))];
wTrails{dim,j}.YData = [wTrails{dim,j}.YData(2:end) imag(wi(j))];
else
wTrails{dim,j}.XData = [wTrails{dim,j}.XData real(wi(j))];
wTrails{dim,j}.YData = [wTrails{dim,j}.YData imag(wi(j))];
end
end
end
lBound.XData = [mr_res{k}.t(1) mr_res{k}.t(1)];
rBound.XData = [mr_res{k}.t(end) mr_res{k}.t(end)];
pause(0.05)
end
%% Times series of mode coordinates
figure('units','pixels','Position',[100 100 1366 768])
for j = 1:r
subplot(r,2,2*j-1)
plot(real(allModes(:,:,j)))
title(['Re[w_' num2str(j) ']'])
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
subplot(r,2,2*j)
plot(imag(allModes(:,:,j)))
title(['Im[w_' num2str(j) ']'])
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
end
%% Times series of modes in polar coordinates
figure('units','pixels','Position',[100 100 1366 768])
for j = 1:r
cMode = squeeze(allModes(:,j,:));
rMode = abs(cMode);
thMode = unwrap(angle(cMode));
subplot(r,2,2*j-1)
plot(rMode)
title(['Magnitudes of Modes in Dim. ' num2str(j)])
legend({'HF','HF','LF','LF'})
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
subplot(r,2,2*j)
plot(thMode)
title(['Angles of Modes in Dim. ' num2str(j)])
legend({'HF','HF','LF','LF'})
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
end
%% Show how modes are reflections of one another
figure('units','pixels','Position',[100 100 1366 768])
subplot(2,2,1)
plot(real(allModes(:,:,1) - conj(allModes(:,:,2))))
title('Re[w_1 - w_2^*]')
subplot(2,2,2)
plot(imag(allModes(:,:,1) - conj(allModes(:,:,2))))
title('Im[w_1 - w_2^*]')
subplot(2,2,3)
plot(real(allModes(:,:,3) - conj(allModes(:,:,4))))
title('Re[w_3 - w_4^*]')
subplot(2,2,4)
plot(imag(allModes(:,:,3) - conj(allModes(:,:,4))))
title('Im[w_3 - w_4^*]')
%% Output mode time series data
t_step = (TimeSpan(2)-TimeSpan(1))*stepSize; %time per window sliding step
start_steps = 100; %chop off from beginning to get rid of initial transients
% good_winds = [start_steps:626, 644:nSlide]; %manually excise outliers from DMD error
% cutoff_inds = 626-start_steps; %after omitting outliers, this is the index location of the cutoff between continuous regions
% allFreqsCut = allFreqs(good_winds,:);
% allModesCut = allModes(good_winds,:,:);
modeStack = zeros(size(allModes,1),r*r);
for j = 1:r
for k = 1:r
modeStack(:,(j-1)*r+k) = allModes(:,k,j);
end
end
% figure
% subplot(2,1,1)
% plot(real(modeStack(:,1:8)))
% subplot(2,1,2)
% plot(real(modeStack(:,9:16)))
if use_median_freqs == 0
save('modeSeries.mat','modeStack','t_step');
else
save('modeSeries_i2.mat','modeStack','t_step');
end
%% Split HF/LF Reconstruction
xr_H = zeros(size(x(:,1:nSteps)));
xr_L = zeros(size(x(:,1:nSteps)));
all_b = zeros(nVars,nSlide);
xn = zeros(nSteps,1); %track total contribution from all windows to each time step
recon_filter_sd = wSteps/8;
recon_filter = exp(-((1 : wSteps) - (wSteps+1)/2).^2/recon_filter_sd^2);
for k = 1:nSlide
w = mr_res{k}.w;
b = mr_res{k}.b;
all_b(:,k) = b;
Omega = mr_res{k}.Omega;
om_class = mr_res{k}.om_class;
t = mr_res{k}.t;
c = mr_res{k}.c;
t_start = mr_res{k}.t_start;
tShift = t-t(1); %compute each segment of xr starting at "t = 0"
% t_nudge = 5;
% constant shift gets put in LF recon
xr_L_window = w(:, om_class == 1)*diag(b(om_class == 1))*exp(Omega(om_class == 1)*(t-t_start)) + c;
xr_H_window = w(:, om_class == 2)*diag(b(om_class == 2))*exp(Omega(om_class == 2)*(t-t_start));
xr_L_window = xr_L_window.*repmat(recon_filter,nVars,1);
xr_H_window = xr_H_window.*repmat(recon_filter,nVars,1);
xr_L(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr_L(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_L_window;
xr_H(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr_H(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_H_window;
xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) + recon_filter.';
end
xr_L = xr_L./repmat(xn.',nVars,1);
xr_H = xr_H./repmat(xn.',nVars,1);
figure
subplot(3,1,1)
plot(TimeSpan(1:nSteps),x(:,1:nSteps))
title('Input Data')
subplot(3,1,2)
plot(TimeSpan(1:nSteps),xr_L)
title('LF Recon')
subplot(3,1,3)
plot(TimeSpan(1:nSteps),xr_H)
title('HF Recon')
figure
plot(all_b.')
nanCols = ~isnan([xr_H; xr_L]);
nanCols = sum(nanCols,1) ~= 0;
tspan = TimeSpan(1:nSteps);
xr_H = real(xr_H(:,nanCols));
xr_L = real(xr_L(:,nanCols));
tspan = tspan(nanCols);
save('mwDMD_sep_recon.mat','xr_L','xr_H','tspan');
%% Construct A Matrices
if global_SVD ~= 1
disp('Warning: Averaging A matrices in different bases')
end
A_avg = zeros(r);
A_proj_avg = zeros(r);
A_thresh = 100;
for k = 1:nSlide
x_window = mr_res{k}.x;
w = mr_res{k}.w;
Omega = mr_res{k}.Omega;
A = w*diag(Omega)*pinv(w);
A_proj = (u'*w)*diag(Omega)*(pinv(w)*u);
A(abs(A) <= A_thresh) = 0; %threshold small values
A_proj(abs(A_proj) <= A_thresh) = 0;
A_avg = A_avg + A;
A_proj_avg = A_proj_avg + A_proj;
end
A_avg = real(A_avg)/nSlide; %strips small imaginary residuals
A_proj_avg = real(A_proj_avg)/nSlide;
figure
plot(TimeSpan(1:nSteps),v(1:nSteps,:))
legend({'Mode 1','Mode 2','Mode 3','Mode 4'})
%% Time series of mode projections
allB = zeros(nSlide,r);
colFreqs = zeros(r,1);
for k = 1:nSlide
thisCat = modeCats(k,:);
b = mr_res{k}.b;
% b = b(thisCat);
allB(k,:) = b.';
colFreqs = colFreqs + abs(mr_res{k}.Omega);
end
colFreqs = colFreqs/nSlide;
wMids = (TimeSpan(2)-TimeSpan(1))*(wSteps/2 + stepSize*(1:nSlide));
figure
subplot(2,1,1)
plot(wMids,allB(:,[1 3]))
legend({'LF','HF'});
title('OptDMD Weight Coefficients Over Time');
xlim([wMids(1) wMids(end)]);
subplot(2,1,2)
plot(TimeSpan(1:nSteps),x(:,1:nSteps))
xlim([wMids(1) wMids(end)]);
%% Function definitions
function dx = rhs(x,delta,epsilon)
x1 = x(1); x2 = x(2); y1 = x(3); y2 = x(4);
dx=[x2; -y1^2 * x1^3; y2; -epsilon^(-1)*y1 - delta*y1^3];
end
|
github
|
dylewsky/MultiRes_Discovery-master
|
Overlapping_Scale_Oscillators.m
|
.m
|
MultiRes_Discovery-master/Example_Overlapping_Scale_Oscillators/Overlapping_Scale_Oscillators.m
| 21,904 |
utf_8
|
cf468a2658d1fe4f0690c6c00986f538
|
%%% DMD SCALE SEPARATION FOR A SYSTEM WITH SEPARATE BUT
%%% INTERMITTANTLY-OVERLAPPING TIME SCALES
%%%
%%% Before running, make sure to download and set up the optdmd package
%%% available here: https://github.com/duqbo/optdmd
%%%
%%% This code reproduces the results of Sec. IV of "Dynamic mode decomposition
%%% for multiscale nonlinear physics," by Dylewsky, Tao, and Kutz
%%% (DOI: 10.1103/PhysRevE.99.063311)
clear; close all; clc
%% Simulate Dynamics
% parameters
T=64;
downsample_factor = 2; %integer >= 1
x0 = [-1.110,-0.125];
tau1 = 2;
a = 0.7;
b = 0.8;
Iext = 0.65;
y0 = [0 1];
eta = 0; %dampling
epsilon = 1;
tau2 = 0.2;
% RK4 integration of the mixed system
dt = 0.0001;
TimeSpan = 0:dt:T; TimeSteps=length(TimeSpan)-1;
% x = zeros(4,TimeSteps+1);
% x(:,1) = [x1_0; x2_0; y1_0; y2_0];
[t1, x] = ode45(@(t1,x) rhs1(x,tau1,a,b,Iext),TimeSpan,x0);
[t2, y] = ode45(@(t2,y) rhs2(y,eta,epsilon,tau2),TimeSpan,y0);
tStep = mean(diff(t1))*4;
nSteps = ceil(T/tStep);
tN = 0:tStep:T;
tN = tN(1:nSteps); %match to nSteps
xOld = x;
yOld = y;
x = interp1(t1,xOld,tN); %enforce evenly spaced time steps
y = interp1(t2,yOld,tN); %enforce evenly spaced time steps
TimeSpan = tN;
% Plot Results
figure
subplot(2,1,1)
plot(TimeSpan, x);
title('x data');
xlabel('Time');
subplot(2,1,2)
plot(TimeSpan, y);
title('y data')
xlabel('Time');
figure
plot(TimeSpan(1:end-1),diff(x(:,1)),'DisplayName','x')
hold on
plot(TimeSpan(1:end-1),diff(y(:,1)),'DisplayName','y')
title('Derivatives')
legend
% Downsample
x = x(1:downsample_factor:end,:);
y = y(1:downsample_factor:end,:);
TimeSpan = TimeSpan(1:downsample_factor:end);
uv = [x(:,1) y(:,1)];
% Apply Linear Mixing
rng(123); %seed
uv_ratio = 1; %ratio of u and v in linear combination
n = size(uv,2);
m = size(uv,1);
nVars_out = 4; %dimension of space to map into
A = randn(n,nVars_out);
Q = orth(A.').'; %orthonormalize
x = uv * A;
plot(TimeSpan,x)
save('Overlapping_Scale_Oscillators_Raw_Data.mat','x','TimeSpan','A');
%% Sliding-Window DMD
x = x.';
r = size(x,1); %rank to fit w/ optdmd
imode = 1; %parameter for optdmd code
% imode = 1, fit full data, slower
% imode = 2, fit data projected onto first r POD modes
% or columns of varargin{2} (should be at least r
% columns in varargin{2})
nComponents = 2; %number of distinct time scales present
global_SVD = 1; %use global SVD modes for each DMD rather than individual SVD on each window
if global_SVD == 1
[u,~,v] = svd(x,'econ');
u = u(:,1:r); %just first r modes
v = v(:,1:r);
end
% Method for making initial guess of DMD eigenvalues:
% Recommended settings for first run:
initialize_artificially = 0; %this is required for use_last_freq OR use_median_freqs
use_last_freq = 0;
use_median_freqs = 0; %mutually exclusive w/ use_last_freq
% Recommended settings for subsequent runs (using clustering information
% obtained from the first run):
% initialize_artificially = 1; %this is required for use_last_freq OR use_median_freqs
% use_last_freq = 0;
% use_median_freqs = 1; %mutually exclusive w/ use_last_freq
optDMD_opts = varpro_opts('ifprint',0); %disable verbose output for optDMD
if (initialize_artificially == 1) && (use_median_freqs == 1)
load('km_centroids.mat'); % Load pre-defined eigenvalue guesses
freq_meds = repelem(sqrt(km_centroids),r/nComponents);
end
wSteps = 7000; % Window size (in time steps)
nSplit = floor(length(TimeSpan)/wSteps); %number of windows if they were non-overlapping
nSteps = wSteps * nSplit;
nVars = size(x,1);
thresh_pct = 1;
stepSize = 2;
nSlide = floor((nSteps-wSteps)/stepSize); % Number of sliding-window iterations
save('mwDMD_params.mat','r','nComponents','initialize_artificially','use_last_freq','use_median_freqs','wSteps','nSplit','nSteps','nVars','thresh_pct','stepSize','nSlide');
%% execute optDMD
corner_sharpness = 16; %higher = sharper corners
lv_kern = tanh(corner_sharpness*(1:wSteps)/wSteps) - tanh(corner_sharpness*((1:wSteps)-wSteps)/wSteps) - 1;
mr_res = cell(nSlide,1);
for k = 1:nSlide
disp(['k = ' num2str(k) ' / ' num2str(nSlide)])
sampleStart = stepSize*(k-1) + 1;
sampleSteps = sampleStart : sampleStart + wSteps - 1;
xSample = x(:,sampleSteps);
tSample = TimeSpan(sampleSteps);
mr_res{k}.x = xSample;
mr_res{k}.t = tSample;
c = mean(xSample,2); %subtract off mean before rounding corners
xSample = xSample - repmat(c,1,size(xSample,2));
xSample = xSample.*repmat(lv_kern,nVars,1); %round off corners
t_start = tSample(1);
tSample = tSample - t_start;
if global_SVD == 0
[u,~,~] = svd(xSample,'econ');
u = u(:,1:r);
end
if (exist('e_init','var')) && (initialize_artificially == 1)
[w, e, b] = optdmd(xSample,tSample,r,imode,optDMD_opts,e_init,u);
else
[w, e, b] = optdmd(xSample,tSample,r,imode,optDMD_opts,[],u);
end
if use_last_freq == 1
e_init = e;
end
if use_median_freqs == 1
[eSq, eInd] = sort(e.*conj(e)); %match order to that of freq_meds
freq_angs = angle(e(eInd));
e_init = exp(sqrt(-1)*freq_angs) .* freq_meds;
end
mr_res{k}.w = w;
mr_res{k}.Omega = e;
mr_res{k}.b = b;
mr_res{k}.c = c;
mr_res{k}.t_start = t_start;
end
%% Cluster Frequencies
close all;
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
all_om = [];
all_om_grouped = [];
for k = 1:nSlide
try
Omega = mr_res{k}.Omega;
catch ME
disp(['Error on k = ' num2str(k)]);
continue
end
all_om = [all_om; Omega];
[~,imSortInd] = sort(imag(Omega));
all_om_grouped = [all_om_grouped; Omega(imSortInd).'];
end
all_om_sq = conj(all_om) .* all_om;
all_om_sq = sort(all_om_sq);
all_om_sq_thresh = all_om_sq(floor(thresh_pct*length(all_om_sq)));
all_om_sq = all_om_sq(1:floor(thresh_pct*length(all_om_sq)));
[~, km_centroids] = kmeans(all_om_sq,nComponents,'Distance','cityblock','Replicates',5);
[km_centroids,sortInd] = sort(km_centroids);
for k = 1:nSlide
try
omega = mr_res{k}.Omega;
catch ME
continue
end
om_sq = omega.*conj(omega);
om_sq_dists = (repmat(km_centroids.',r,1) - repmat(om_sq,1,nComponents)).^2;
[~,om_class] = min(om_sq_dists,[],2);
mr_res{k}.om_class = om_class;
end
if use_median_freqs == 0
save('mwDMD_mr_res.mat', 'mr_res','-v7.3');
save('km_centroids.mat','km_centroids');
else
save('mwDMD_mr_res_i2.mat', 'mr_res','-v7.3');
save('km_centroids_i2.mat','km_centroids');
end
%% Plot MultiRes Results
close all;
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
export_result = 0;
logScale = 0;
colorList = {'b','r','g','k','y'};
x_PoT = x(:,1:nSteps);
t_PoT = TimeSpan(1:nSteps);
%res_list: [pn, level #, nSplit, sampleSteps/nSplit]
dupShift = 0; %multiplier to shift duplicate values so they can be visually distinguished
nBins = 64;
figure('units','pixels','Position',[100 100 1200 400])
all_om = [];
for k = 1:nSlide
Omega = mr_res{k}.Omega;
all_om = [all_om; Omega];
end
all_om_sq = sort(all_om .* conj(all_om));
thresh_om_sq = all_om_sq(floor(thresh_pct*length(all_om_sq)));
all_om_sq = all_om_sq(1:floor(thresh_pct*length(all_om_sq)));
subplot(2,2,[1 3]);
om_hist = histogram(all_om_sq,nBins);
mesh_pad = 10;
bin_mesh = om_hist.BinEdges(1)-mesh_pad:0.5:om_hist.BinEdges(end)+mesh_pad;
xlabel('|\omega|^2');
ylabel('Count');
title('|\omega|^2 Spectrum & k-Means Centroids');
hold on
yl = ylim;
for c = 1:nComponents
plot([km_centroids(c), km_centroids(c)], yl,'Color',colorList{c},'LineWidth',2)
end
xr = zeros(size(x(:,1:nSteps))); %reconstructed time series
xn = zeros(nSteps,1); %count # of windows contributing to each step
omega_series = nan(nVars,nSlide);
time_series = nan(nSlide,1);
for k = 1:nSlide
w = mr_res{k}.w;
b = mr_res{k}.b;
Omega = mr_res{k}.Omega;
om_class = mr_res{k}.om_class;
t = mr_res{k}.t;
c = mr_res{k}.c;
t_start = mr_res{k}.t_start;
tShift = t-t(1); %compute each segment of xr starting at "t = 0"
xr_window = w*diag(b)*exp(Omega*(t-t_start)) + c;
xn_window = all(~isnan(xr_window)); %NaNs don't contribute
xr_window(:,any(isnan(xr_window))) = 0;
xr(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_window;
xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xn_window.';
% Plot |omega|^2 spectrum
om_sq = conj(Omega).*Omega;
om_class = om_class(om_sq <= thresh_om_sq);
om_sq = om_sq(om_sq <= thresh_om_sq); %threshold to remove outliers
for oi = 1:length(om_sq)
for oj = oi:length(om_sq)
if (abs(om_sq(oi)-om_sq(oj))/((om_sq(oi)+om_sq(oj))/2)) <= dupShift && (oi ~= oj)
om_sq(oi) = om_sq(oi)*(1-dupShift);
om_sq(oj) = om_sq(oj)*(1+dupShift);
end
end
end
subplot(2,2,2);
for g = 1:nComponents
om_window_spec_cat = om_sq(om_class == g,:);
if isempty(om_window_spec_cat) == 1
continue
end
if length(om_window_spec_cat) == 2
omega_series(2*g-1:2*g,k) = om_window_spec_cat;
time_series(k) = mean(t);
end
if logScale == 1
for f = 1:length(om_window_spec_cat)
semilogy(mean(t),om_window_spec_cat(f),'.','Color',colorList{g},'LineWidth',1,'MarkerSize',10);
end
else
for f = 1:length(om_window_spec_cat)
plot(mean(t),om_window_spec_cat,'.','Color',colorList{g},'LineWidth',1,'MarkerSize',10);
end
end
hold on
end
end
title('|\omega|^2 Spectra (Moving Window)');
subplot(2,2,4);
plot(t_PoT,real(x_PoT),'k-','LineWidth',1.5) %plot ground truth
xlabel('t')
ylabel('Measurement Data')
xMax = max(max(abs(x_PoT)));
ylim(1.5*[-xMax, xMax]);
hold on
xr = xr./repmat(xn.',4,1); %weight xr so all steps are on equal footing
plot(t_PoT,real(xr),'b-','LineWidth',1.5) %plot averaged reconstruction
title('Input (Black); DMD Recon. (Blue)');
if export_result == 1
if lv == 1
export_fig 'manyres_opt' '-pdf';
% print(gcf, '-dpdf', 'manyres_opt.pdf');
else
export_fig 'manyres_opt' '-pdf' '-append';
% print(gcf, '-dpdf', 'manyres_opt.pdf', '-append');
end
close(gcf);
end
%% Link Consecutive Modes
if exist('mr_res','var') == 0
try
load('mwDMD_mr_res_i2.mat');
catch ME
load('mwDMD_mr_res.mat');
end
end
allModes = zeros(nSlide,r,r);
allFreqs = zeros(nSlide,r);
catList = flipud(perms(1:r));
modeCats = zeros(nSlide,r);
modeCats(1,:) = 1:r; %label using order of 1st modes
allModes(1,:,:) = mr_res{1}.w;
allFreqs(1,:) = mr_res{1}.Omega;
[~,catsAsc] = sort(mr_res{1}.Omega.*conj(mr_res{1}.Omega)); %category labels in ascending frequency order
distThresh = 0;
% distThresh = 0.11; %if more than one mode is within this distance then match using derivative
% minDists = zeros(nSlide-1,1);
permDistsHist = zeros(size(catList,1),nSlide-1);
for k = 2:nSlide
w_old = squeeze(allModes(k-1,:,:));
w = mr_res{k}.w;
permDists = zeros(size(catList,1),1);
for np = 1:size(catList,1)
permDists(np) = norm(w(:,catList(np,:))-w_old);
end
permDistsHist(:,k-1) = sort(permDists);
% minDists(k-1) = min(permDists);
if nnz(permDists <= distThresh) >= 1
if k == 2 %can't compute derivative 1 step back, so skip it
[~,minCat] = min(permDists);
continue;
end
w_older = squeeze(allModes(k-2,:,:));
[~,minInds] = sort(permDists); %minInds(1) and minInds(2) point to 2 lowest distances
wPrime = w - w_old;
wPrime_old = w_old - w_older;
for j = 1:size(wPrime,2)
wPrime(:,j) = wPrime(:,j)/norm(wPrime(:,j));
wPrime_old(:,j) = wPrime_old(:,j)/norm(wPrime_old(:,j));
end
derivDists = zeros(2,1);
for np = 1:length(derivDists)
derivDists(np) = norm(wPrime(:,catList(minInds(np),:))-wPrime_old);
end
[~,minDerInd] = min(derivDists);
derivDistsSort = sort(derivDists);
permDistsSort= sort(permDists);
disp(['Derivative-Matching on k = ' num2str(k)])
if (derivDistsSort(2)-derivDistsSort(1)) > (permDistsSort(2) - permDistsSort(1))
minCat = minInds(minDerInd);
[~,minCatNaive] = min(permDists);
if minCat ~= minCatNaive
disp('Naive result was wrong!')
end
else
[~,minCat] = min(permDists);
disp('Naive result trumps derivative match')
end
else
[~,minCat] = min(permDists);
end
modeCats(k,:) = catList(minCat,:);
allModes(k,:,:) = w(:,catList(minCat,:));
allFreqs(k,:) = mr_res{k}.Omega(catList(minCat,:));
end
meanFreqsSq = sum(allFreqs.*conj(allFreqs),1)/nSlide;
if use_median_freqs == 0
save('mwDMD_allModes.mat','allModes','allFreqs');
else
save('mwDMD_allModes_i2.mat','allModes','allFreqs');
end
%% Second derivative of mode coordinates
sd_norms = zeros(r,size(allModes,1)-2);
for j = 1:r
tsPP = allModes(1:end-2,:,j) + allModes(3:end,:,j) - 2*allModes(2:end-1,:,j);
sd_norms(j,:) = vecnorm(tsPP.');
end
sd_norms = vecnorm(sd_norms).';
sd_thresh = 0.1; %threshold above which to try different permutations to reduce 2nd deriv
%can be set to 0 to just check every step
ppOverrideRatio = 0.7; %apply new permutation if 2nd deriv is reduced by at least this factor
for k = 2:nSlide-1
thisData = allModes(k-1:k+1,:,:);
tdPP = squeeze(thisData(1,:,:) + thisData(3,:,:) - 2*thisData(2,:,:));
if norm(tdPP) < sd_thresh
continue;
end
permDists = zeros(size(catList,1),1);
permData = zeros(size(thisData));
for np = 1:size(catList,1)
%hold k-1 configuration constant, permute k and k+1 registers
permData(1,:,:) = thisData(1,:,:);
permData(2:3,:,:) = thisData(2:3,:,catList(np,:));
permPP = squeeze(permData(1,:,:) + permData(3,:,:) - 2*permData(2,:,:));
permDists(np) = norm(permPP);
if permDists(np) <= ppOverrideRatio * norm(tdPP)
newCat = catList(np,:);
allModes(k:end,:,:) = allModes(k:end,:,newCat);
modeCats(k,:) = modeCats(k,newCat);
disp(['2nd Deriv. Perm. Override: k = ' num2str(k)]);
end
end
end
if use_median_freqs == 0
save('mwDMD_allModes.mat','allModes','allFreqs');
else
save('mwDMD_allModes_i2.mat','allModes','allFreqs');
end
%% Visualize Modes
figure('units','pixels','Position',[0 0 1366 768])
colorlist = {'k','r','b','g'};
w = squeeze(allModes(1,:,:));
wPlots = cell(r,r);
wTrails = cell(r,r);
trailLength = 1000; %in window steps
% Plot time series
subplot(2,4,5:8)
plot(TimeSpan(1:nSteps),x(:,1:nSteps),'LineWidth',1.5)
xlim([TimeSpan(1) TimeSpan(nSteps)])
hold on
lBound = plot([mr_res{1}.t(1) mr_res{1}.t(1)],ylim,'r-','LineWidth',2);
hold on
rBound = plot([mr_res{1}.t(end) mr_res{1}.t(end)],ylim,'r-','LineWidth',2);
hold on
% Plot 1st frame
for dim = 1:r
subplot(2,4,dim)
wi = w(dim,:);
for j = 1:r
wPlots{dim,j} = plot(real(wi(j)),imag(wi(j)),'o','Color',colorlist{j},'MarkerSize',7);
hold on
wTrails{dim,j} = plot(real(wi(j)),imag(wi(j)),'-','Color',colorlist{j},'LineWidth',0.1);
hold on
wTrails{dim,j}.Color(4) = 0.3; % 50% opacity
end
title(['Proj. Modes into Dimension ' num2str(dim)])
axis equal
xlim([-1 1])
ylim([-1 1])
xlabel('Real');
ylabel('Imag');
plot(xlim,[0 0],'k:')
hold on
plot([0 0],ylim,'k:')
hold off
end
legend([wPlots{r,catsAsc(1)},wPlots{r,catsAsc(2)},wPlots{r,catsAsc(3)},wPlots{r,catsAsc(4)}],{'LF Mode 1','LF Mode 2','HF Mode 1','HF Mode 2'},'Position',[0.93 0.65 0.05 0.2])
%Plot subsequent frames
for k = 2:nSlide
w = squeeze(allModes(k,:,:));
for dim = 1:r
% subplot(4,4,dim)
wi = w(dim,:);
for j = 1:r
wPlots{dim,j}.XData = real(wi(j));
wPlots{dim,j}.YData = imag(wi(j));
if k > trailLength
wTrails{dim,j}.XData = [wTrails{dim,j}.XData(2:end) real(wi(j))];
wTrails{dim,j}.YData = [wTrails{dim,j}.YData(2:end) imag(wi(j))];
else
wTrails{dim,j}.XData = [wTrails{dim,j}.XData real(wi(j))];
wTrails{dim,j}.YData = [wTrails{dim,j}.YData imag(wi(j))];
end
end
end
lBound.XData = [mr_res{k}.t(1) mr_res{k}.t(1)];
rBound.XData = [mr_res{k}.t(end) mr_res{k}.t(end)];
% pause(0.05)
end
%% Times series of mode coordinates
figure('units','pixels','Position',[100 100 1366 768])
for j = 1:r
subplot(r,2,2*j-1)
plot(real(allModes(:,:,j)))
title(['Re[w_' num2str(j) ']'])
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
subplot(r,2,2*j)
plot(imag(allModes(:,:,j)))
title(['Im[w_' num2str(j) ']'])
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
end
%% Times series of modes in polar coordinates
figure('units','pixels','Position',[100 100 1366 768])
for j = 1:r
cMode = squeeze(allModes(:,j,:));
rMode = abs(cMode);
thMode = unwrap(angle(cMode));
subplot(r,2,2*j-1)
plot(rMode)
title(['Magnitudes of Modes in Dim. ' num2str(j)])
legend({'HF','HF','LF','LF'})
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
subplot(r,2,2*j)
plot(thMode)
title(['Angles of Modes in Dim. ' num2str(j)])
legend({'HF','HF','LF','LF'})
% legend('a','b','r','\theta')
if j == r
xlabel('Window #')
end
end
%% Output mode time series data
t_step = (TimeSpan(2)-TimeSpan(1))*stepSize; %time per window sliding step
start_steps = 100; %chop off from beginning to get rid of initial transients
modeStack = zeros(size(allModes,1),r*r);
for j = 1:r
for k = 1:r
modeStack(:,(j-1)*r+k) = allModes(:,k,j);
end
end
if use_median_freqs == 0
save('modeSeries.mat','modeStack','t_step');
else
save('modeSeries_i2.mat','modeStack','t_step');
end
%% Split HF/LF Reconstruction
xr_H = zeros(size(x(:,1:nSteps)));
xr_L = zeros(size(x(:,1:nSteps)));
all_b = zeros(nVars,nSlide);
xn = zeros(nSteps,1); %track total contribution from all windows to each time step
recon_filter_sd = wSteps/8;
recon_filter = exp(-((1 : wSteps) - (wSteps+1)/2).^2/recon_filter_sd^2);
for k = 1:nSlide
w = mr_res{k}.w;
b = mr_res{k}.b;
all_b(:,k) = b;
Omega = mr_res{k}.Omega;
om_class = mr_res{k}.om_class;
t = mr_res{k}.t;
c = mr_res{k}.c;
t_start = mr_res{k}.t_start;
tShift = t-t(1); %compute each segment of xr starting at "t = 0"
% constant shift gets put in LF recon
xr_L_window = w(:, om_class == 1)*diag(b(om_class == 1))*exp(Omega(om_class == 1)*(t-t_start)) + c;
xr_H_window = w(:, om_class == 2)*diag(b(om_class == 2))*exp(Omega(om_class == 2)*(t-t_start));
xr_L_window = xr_L_window.*repmat(recon_filter,nVars,1);
xr_H_window = xr_H_window.*repmat(recon_filter,nVars,1);
xr_L(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr_L(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_L_window;
xr_H(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xr_H(:,(k-1)*stepSize+1:(k-1)*stepSize+wSteps) + xr_H_window;
xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) = xn((k-1)*stepSize+1:(k-1)*stepSize+wSteps) + recon_filter.';
end
xr_L = xr_L./repmat(xn.',nVars,1);
xr_H = xr_H./repmat(xn.',nVars,1);
figure
subplot(3,1,1)
plot(TimeSpan(1:nSteps),x(:,1:nSteps))
title('Input Data')
subplot(3,1,2)
plot(TimeSpan(1:nSteps),xr_L)
title('LF Recon')
subplot(3,1,3)
plot(TimeSpan(1:nSteps),xr_H)
title('HF Recon')
figure
plot(all_b.')
nanCols = ~isnan([xr_H; xr_L]);
nanCols = sum(nanCols,1) ~= 0;
tspan = TimeSpan(1:nSteps);
xr_H = real(xr_H(:,nanCols));
xr_L = real(xr_L(:,nanCols));
tspan = tspan(nanCols);
save('mwDMD_sep_recon.mat','xr_L','xr_H','tspan');
%% Construct A Matrices
if global_SVD ~= 1
disp('Warning: Averaging A matrices in different bases')
end
A_avg = zeros(r);
A_proj_avg = zeros(r);
A_thresh = 100;
for k = 1:nSlide
x_window = mr_res{k}.x;
w = mr_res{k}.w;
Omega = mr_res{k}.Omega;
A = w*diag(Omega)*pinv(w);
A_proj = (u'*w)*diag(Omega)*(pinv(w)*u);
A(abs(A) <= A_thresh) = 0; %threshold small values
A_proj(abs(A_proj) <= A_thresh) = 0;
A_avg = A_avg + A;
A_proj_avg = A_proj_avg + A_proj;
end
A_avg = real(A_avg)/nSlide; %strips small imaginary residuals
A_proj_avg = real(A_proj_avg)/nSlide;
figure
plot(TimeSpan(1:nSteps),v(1:nSteps,:))
legend({'Mode 1','Mode 2','Mode 3','Mode 4'})
%% Time series of mode projections
allB = zeros(nSlide,r);
colFreqs = zeros(r,1);
for k = 1:nSlide
thisCat = modeCats(k,:);
b = mr_res{k}.b;
allB(k,:) = b.';
colFreqs = colFreqs + abs(mr_res{k}.Omega);
end
colFreqs = colFreqs/nSlide;
wMids = (TimeSpan(2)-TimeSpan(1))*(wSteps/2 + stepSize*(1:nSlide));
figure
subplot(2,1,1)
plot(wMids,allB(:,[1 3]))
legend({'LF','HF'});
title('OptDMD Weight Coefficients Over Time');
xlim([wMids(1) wMids(end)]);
subplot(2,1,2)
plot(TimeSpan(1:nSteps),x(:,1:nSteps))
xlim([wMids(1) wMids(end)]);
%% Function Definitions
function dx = rhs1(x,tau,a,b,Iext)
% FitzHugh-Nagumo Model
v = x(1); w = x(2);
vdot = v - (v^3)/3 - w + Iext;
wdot = (1/tau) * (v + a - b*w);
dx = [vdot; wdot];
end
function dy = rhs2(y,eta,epsilon,tau)
% Unforced Duffing Oscillator
p = y(1); q = y(2);
pdot = q;
qdot = (1/tau) * (-2*eta*q - p - epsilon*p^3);
dy = [pdot; qdot];
end
|
github
|
AgriHarmony/soil-hydraulic-simulation-backup-master
|
SMmodel_GA_WEB.m
|
.m
|
soil-hydraulic-simulation-backup-master/SMmodel_code/SMmodel_GA_WEB.m
| 4,293 |
utf_8
|
550e15e7de23359f535b01408d760f94
|
% SMmodel_GA_WEB(name,PAR,FIG)
%
% SMmodel_GA_WEB: Soil Moisture Model based on Green-Ampt for infiltration
% Authors: Luca Brocca, Florisa Melone, Tommaso Moramarco
function [NS,NS_lnQ,NS_radQ,RQ,RMSE] = SMmodel_GA_WEB(name,PAR,FIG);
% Loading input data
PTSM=load([name,'.txt']);
[M,N]=size(PTSM);
D=PTSM(:,1); PIO=PTSM(:,2); TEMPER=PTSM(:,3); WWobs=PTSM(:,4);
dt=round(nanmean(diff(D))*24*10000)/10000;
MESE=month(D);
% Model parameter
W_0_RZ= PAR(1);
W_max= PAR(2); % mm
Psi_av_L= PAR(3);
Ks_sup= PAR(4); % mm/h
Ks_RZ= PAR(5); % mm/h
m_RZ= PAR(6);
Kc= PAR(7);
% Parameters adjustment
Ks_sup=Ks_sup.*dt;
Ks_RZ=Ks_RZ.*dt;
% Potential Evapotranspiration parameter
L=[0.2100;0.2200;0.2300;0.2800;0.3000;0.3100;
0.3000;0.2900;0.2700;0.2500;0.2200;0.2000];
Ka=1.26;
EPOT=(TEMPER>0).*(Kc*(Ka*L(MESE).*(0.46*TEMPER+8)-2))/(24/dt);
clear PTSM TEMPER
% Thresholds for numerical computations
soglia=0.01; % Water Content
soglia1=0.01; % Infiltration
% Parameter initialization
F_p=0;
F=0.00001;
W_init=-9999;
WW=zeros(M,1);
W_RZ_p=W_0_RZ*W_max;
PIOprec=0; inf=0;
ii=1; i=1;
% Main ROUTINE
for t=1:M
W_RZ=W_RZ_p;
jj=0;
err=1000;
while err>soglia;
% infiltration computation (Green-Ampt)
jj=jj+1;
if (PIOprec<=0.001)
if (PIO(t)>0)
W_init=W_RZ;
Psi=Psi_av_L*(W_max-W_init);
else
W_init=-9999;
ii=1;
F_p=0;
F=0.00001;
end
end
if W_init~=-9999
if jj>1
ii=ii-1;
end
inf=(ii==1)*1000+(ii~=1)*Ks_sup*(1-Psi/F);
if inf>PIO(t)
inf=PIO(t);
F=F+PIO(t);
else
F_p=F;
errore=1000;
while errore>soglia1 % iteration for the infiltration
F1=F_p-Psi*log((F-Psi)/(F_p-Psi))+Ks_sup;
errore=abs((F-F1)/F);
F=F+0.01;
end
inf=F-F_p;
end
F_p=F;
ii=ii+1;
end
e=EPOT(t)*W_RZ/W_max;
perc=Ks_RZ*(W_RZ/W_max).^(m_RZ);
W_RZ_corr=W_RZ_p+(inf-e-perc);
if W_RZ_corr>=W_max
W_RZ_corr=W_max;
end
err=abs((W_RZ_corr-W_RZ)/W_max);
W_RZ=W_RZ_corr;
if jj==100, break, end
end
W_RZ_p=W_RZ_corr;
if t>3,PIOprec=sum(PIO(t-3:t));end
WW(t)=W_RZ_corr./W_max;
end;
% Calculation of model performance
RMSE=nanmean((WW-WWobs).^2).^0.5;
NS=1-nansum((WW-WWobs).^2)./nansum((WWobs-nanmean(WWobs)).^2);
NS_radQ=1-nansum((sqrt(WW+0.00001)-sqrt(WWobs+0.00001)).^2)./...
nansum((sqrt(WWobs+0.00001)-nanmean(sqrt(WWobs+0.00001))).^2);
NS_lnQ=1-nansum((log(WW+0.0001)-log(WWobs+0.0001)).^2)...
./nansum((log(WWobs+0.0001)-nanmean(log(WWobs+0.0001))).^2);
NS_lnQ=real(NS_lnQ);
NS_radQ=real(NS_radQ);
X=[WW,WWobs]; X(any(isnan(X)'),:) = [];
RRQ=corrcoef(X).^2; RQ=RRQ(2);
% Figure
if FIG==1
set(gcf,'paperpositionmode','manual','paperposition',[1 1 20 16])
set(gcf,'position',[560 174 1018 774])
h(1) = axes('Position',[0.1 0.5 0.8 0.40]);
set(gca,'Fontsize',12)
s=(['NS= ',num2str(NS,'%4.3f'),...
' NS(log)= ',num2str(NS_lnQ,'%4.3f'),...
' NS(radq)= ',num2str(NS_radQ,'%4.3f'),...
' RQ= ',num2str(RQ,'%4.3f'),...
' RMSE= ',num2str(RMSE,'%4.3f')]);
title(['\bf',s]);
hold on
plot(D,WWobs,'g','Linewidth',3)
plot(D,WW,'r','Linewidth',2);
legend('\theta_o_b_s','\theta_s_i_m',0);
datetick('x',20)
set(gca,'Xticklabel','')
ylabel('relative soil moisture [-]')
grid on, box on
axis([D(1) D(end) min(WWobs)-0.05 max(WWobs)+0.05])
h(2) = axes('Position',[0.1 0.1 0.8 0.40]);
set(gca,'Fontsize',12)
hold on
plot(D,PIO,'color',[.5 .5 .5],'Linewidth',3)
grid on, box on
ylabel('rain (mm/h)')
datetick('x',20)
grid on, box on
axis([D(1) D(end) 0 1.05.*max(PIO)])
print(gcf,['GAmodel_',name],'-dpng','-r150')
% save res
end
|
github
|
AgriHarmony/soil-hydraulic-simulation-backup-master
|
cal_SMmodel_GA_WEB.m
|
.m
|
soil-hydraulic-simulation-backup-master/SMmodel_code/cal_SMmodel_GA_WEB.m
| 1,122 |
utf_8
|
d36850ec5f279c4fc1e3bd395fb88b83
|
function X_OPT=cal_SMmodel_GA_WEB(name,X_ini)
if nargin==1,X_ini=ones(7,1)*.5;,end
% X_ini=rand(5,1);
% [RES,FVAL,EXITFLAG,OUTPUT]=fminsearch(@calibOK,X_ini,...
% optimset('Display','iter','MaxIter',1000,...
% 'MaxFunEvals',1000,'TolFun',0.5*1E-3,'Largescale','off'),name)
[RES,FVAL,EXITFLAG,OUTPUT]=fmincon(@calibOK,X_ini,[],[],[],[],...
zeros(7,1),ones(7,1),[],optimset('Display','iter','MaxIter',50,...
'MaxFunEvals',500,'TolFun',1E-5,'TolCon',6,'Largescale','off'),name)
X=convert_adim(RES);
[NS,NS_lnQ,NS_radQ,RQ]=SMmodel_GA_WEB(name,X,1)
!del X_optGA_WEB.txt
fid=fopen('X_optGA_WEB.txt','w');
fprintf(fid,'%9.4f\n',X);
fclose(fid);
%---------------------------------------------------------------------------------
function [err]=calibOK(X_0,name)
X=convert_adim(X_0);
[NS,NS_lnQ,NS_radQ,RQ]=SMmodel_GA_WEB(name,X,0);
err=1-NS;
save X_PAR
%---------------------------------------------------------------------------------
function X=convert_adim(X_0);
LOW=[ 0.0, 40, -1.50, 0.01, 0.01, 1, 0.5]';
UP =[ 1.0, 200, -0.10, 25.0, 25.0, 45, 2.5]';
X=LOW+(UP-LOW).*X_0;
|
github
|
AgriHarmony/soil-hydraulic-simulation-backup-master
|
richards.m
|
.m
|
soil-hydraulic-simulation-backup-master/richards_matlab/richards.m
| 2,511 |
utf_8
|
db5175e69e7cd545a8891f6f8d52f1d5
|
function richards
% Solution of the Richards equation
% using MATLAB pdepe
%
% $Ekkehard Holzbecher $Date: 2006/07/13 $
%
% Soil data for Guelph Loam (Hornberger and Wiberg, 2005)
% m-file based partially on a first version by Janek Greskowiak
% url source: https://www.mathworks.com/matlabcentral/fileexchange/15646-environmental-modeling/content/richards.m
%--------------------------------------------------------------------------
L = 200; % length [L]
s1 = 0.5; % infiltration velocity [L/T]
s2 = 0; % bottom suction head [L]
T = 4; % maximum time [T]
qr = 0.218; % residual water content
f = 0.52; % porosity
a = 0.0115; % van Genuchten parameter [1/L]
n = 2.03; % van Genuchten parameter
ks = 31.6; % saturated conductivity [L/T]
x = linspace(0,L,100);
t = linspace(0,T,25);
options=odeset('RelTol',1e-4,'AbsTol',1e-4,'NormControl','off','InitialStep',1e-7)
u = pdepe(0,@unsatpde,@unsatic,@unsatbc,x,t,options,s1,s2,qr,f,a,n,ks);
figure;
title('Richards Equation Numerical Solution, computed with 100 mesh points');
subplot (1,3,1);
plot (x,u(1:length(t),:));
xlabel('Depth [L]');
ylabel('Pressure Head [L]');
subplot (1,3,2);
plot (x,u(1:length(t),:)-(x'*ones(1,length(t)))');
xlabel('Depth [L]');
ylabel('Hydraulic Head [L]');
for j=1:length(t)
for i=1:length(x)
[q(j,i),k(j,i),c(j,i)]=sedprop(u(j,i),qr,f,a,n,ks);
end
end
subplot (1,3,3);
plot (x,q(1:length(t),:)*100)
xlabel('Depth [L]');
ylabel('Water Content [%]');
% -------------------------------------------------------------------------
function [c,f,s] = unsatpde(x,t,u,DuDx,s1,s2,qr,f,a,n,ks)
[q,k,c] = sedprop(u,qr,f,a,n,ks);
f = k.*DuDx-k;
s = 0;
% -------------------------------------------------------------------------
function u0 = unsatic(x,s1,s2,qr,f,a,n,ks)
u0 = -200+x;
if x < 10 u0 = -0.5; end
% -------------------------------------------------------------------------
function [pl,ql,pr,qr] = unsatbc(xl,ul,xr,ur,t,s1,s2,qr,f,a,n,ks)
pl = s1;
ql = 1;
pr = ur(1)-s2;
qr = 0;
%------------------- soil hydraulic properties ----------------------------
function [q,k,c] = sedprop(u,qr,f,a,n,ks)
m = 1-1/n;
if u >= 0
c=1e-20;
k=ks;
q=f;
else
q=qr+(f-qr)*(1+(-a*u)^n)^-m;
c=((f-qr)*n*m*a*(-a*u)^(n-1))/((1+(-a*u)^n)^(m+1))+1.e-20;
k=ks*((q-qr)/(f-qr))^0.5*(1-(1-((q-qr)/(f-qr))^(1/m))^m)^2;
end
|
github
|
ChangPaul/B0Mapping-master
|
region_seg.m
|
.m
|
B0Mapping-master/Dependencies/region_seg.m
| 6,473 |
utf_8
|
3184fa5dbf26411a14d7b731345fcadb
|
% Region Based Active Contour Segmentation
%
% seg = region_seg(I,init_mask,max_its,alpha,display)
%
% Inputs: I 2D image
% init_mask Initialization (1 = foreground, 0 = bg)
% max_its Number of iterations to run segmentation for
% alpha (optional) Weight of smoothing term
% higer = smoother. default = 0.2
% display (optional) displays intermediate outputs
% default = true
%
% Outputs: seg Final segmentation mask (1=fg, 0=bg)
%
% Description: This code implements the paper: "Active Contours Without
% Edges" By Chan Vese. This is a nice way to segment images whose
% foregrounds and backgrounds are statistically different and homogeneous.
%
% Example:
% img = imread('tire.tif');
% m = zeros(size(img));
% m(33:33+117,44:44+128) = 1;
% seg = region_seg(img,m,500);
%
% Coded by: Shawn Lankton (www.shawnlankton.com)
%------------------------------------------------------------------------
function seg = region_seg(I,init_mask,max_its,alpha,display)
%-- default value for parameter alpha is .1
if(~exist('alpha','var'))
alpha = .2;
end
%-- default behavior is to display intermediate outputs
if(~exist('display','var'))
display = true;
end
%-- ensures image is 2D double matrix
I = im2graydouble(I);
%-- Create a signed distance map (SDF) from mask
phi = mask2phi(init_mask);
%--main loop
for its = 1:max_its % Note: no automatic convergence test
idx = find(phi <= 1.2 & phi >= -1.2); %get the curve's narrow band
%-- find interior and exterior mean
upts = find(phi<=0); % interior points
vpts = find(phi>0); % exterior points
u = sum(I(upts))/(length(upts)+eps); % interior mean
v = sum(I(vpts))/(length(vpts)+eps); % exterior mean
F = (I(idx)-u).^2-(I(idx)-v).^2; % force from image information
curvature = get_curvature(phi,idx); % force from curvature penalty
dphidt = F./max(abs(F)) + alpha*curvature; % gradient descent to minimize energy
if sum( isnan( dphidt ) ) > 0
seg = phi <= 0;
return;
end
%-- maintain the CFL condition
dt = .45/(max(dphidt)+eps);
if size( phi(idx) ) ~= size( dphidt ) | size( dt ) ~= size( dphidt )
seg = phi <= 0;
return;
end
%-- evolve the curve
phi(idx) = phi(idx) + dt.*dphidt;
%-- Keep SDF smooth
phi = sussman(phi, .5);
%-- intermediate output
if((display>0)&&(mod(its,20) == 0))
showCurveAndPhi(I,phi,its);
end
end
%-- final output
if(display)
showCurveAndPhi(I,phi,its);
end
%-- make mask from SDF
seg = phi<=0; %-- Get mask from levelset
%---------------------------------------------------------------------
%---------------------------------------------------------------------
%-- AUXILIARY FUNCTIONS ----------------------------------------------
%---------------------------------------------------------------------
%---------------------------------------------------------------------
%-- Displays the image with curve superimposed
function showCurveAndPhi(I, phi, i)
imshow(I,'initialmagnification',200,'displayrange',[0 255]); hold on;
contour(phi, [0 0], 'g','LineWidth',4);
contour(phi, [0 0], 'k','LineWidth',2);
hold off; title([num2str(i) ' Iterations']); drawnow;
%-- converts a mask to a SDF
function phi = mask2phi(init_a)
% phi=bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5;
phi=bwdistsc(init_a)-bwdistsc(1-init_a)+init_a-.5;
%-- compute curvature along SDF
function curvature = get_curvature(phi,idx)
[dimy, dimx] = size(phi);
[y x] = ind2sub([dimy,dimx],idx); % get subscripts
%-- get subscripts of neighbors
ym1 = y-1; xm1 = x-1; yp1 = y+1; xp1 = x+1;
%-- bounds checking
ym1(ym1<1) = 1; xm1(xm1<1) = 1;
yp1(yp1>dimy)=dimy; xp1(xp1>dimx) = dimx;
%-- get indexes for 8 neighbors
idup = sub2ind(size(phi),yp1,x);
iddn = sub2ind(size(phi),ym1,x);
idlt = sub2ind(size(phi),y,xm1);
idrt = sub2ind(size(phi),y,xp1);
idul = sub2ind(size(phi),yp1,xm1);
idur = sub2ind(size(phi),yp1,xp1);
iddl = sub2ind(size(phi),ym1,xm1);
iddr = sub2ind(size(phi),ym1,xp1);
%-- get central derivatives of SDF at x,y
phi_x = -phi(idlt)+phi(idrt);
phi_y = -phi(iddn)+phi(idup);
phi_xx = phi(idlt)-2*phi(idx)+phi(idrt);
phi_yy = phi(iddn)-2*phi(idx)+phi(idup);
phi_xy = -0.25*phi(iddl)-0.25*phi(idur)...
+0.25*phi(iddr)+0.25*phi(idul);
phi_x2 = phi_x.^2;
phi_y2 = phi_y.^2;
%-- compute curvature (Kappa)
curvature = ((phi_x2.*phi_yy + phi_y2.*phi_xx - 2*phi_x.*phi_y.*phi_xy)./...
(phi_x2 + phi_y2 +eps).^(3/2)).*(phi_x2 + phi_y2).^(1/2);
%-- Converts image to one channel (grayscale) double
function img = im2graydouble(img)
[dimy, dimx, c] = size(img);
if(isfloat(img)) % image is a double
if(c==3)
img = rgb2gray(uint8(img));
end
else % image is a int
if(c==3)
img = rgb2gray(img);
end
img = double(img);
end
%-- level set re-initialization by the sussman method
function D = sussman(D, dt)
% forward/backward differences
a = D - shiftR(D); % backward
b = shiftL(D) - D; % forward
c = D - shiftD(D); % backward
d = shiftU(D) - D; % forward
a_p = a; a_n = a; % a+ and a-
b_p = b; b_n = b;
c_p = c; c_n = c;
d_p = d; d_n = d;
a_p(a < 0) = 0;
a_n(a > 0) = 0;
b_p(b < 0) = 0;
b_n(b > 0) = 0;
c_p(c < 0) = 0;
c_n(c > 0) = 0;
d_p(d < 0) = 0;
d_n(d > 0) = 0;
dD = zeros(size(D));
D_neg_ind = find(D < 0);
D_pos_ind = find(D > 0);
dD(D_pos_ind) = sqrt(max(a_p(D_pos_ind).^2, b_n(D_pos_ind).^2) ...
+ max(c_p(D_pos_ind).^2, d_n(D_pos_ind).^2)) - 1;
dD(D_neg_ind) = sqrt(max(a_n(D_neg_ind).^2, b_p(D_neg_ind).^2) ...
+ max(c_n(D_neg_ind).^2, d_p(D_neg_ind).^2)) - 1;
D = D - dt .* sussman_sign(D) .* dD;
%-- whole matrix derivatives
function shift = shiftD(M)
shift = shiftR(M')';
function shift = shiftL(M)
shift = [ M(:,2:size(M,2)) M(:,size(M,2)) ];
function shift = shiftR(M)
shift = [ M(:,1) M(:,1:size(M,2)-1) ];
function shift = shiftU(M)
shift = shiftL(M')';
function S = sussman_sign(D)
S = D ./ sqrt(D.^2 + 1);
|
github
|
TurtleZhong/MSCKF-1-master
|
loadCalibrationCamToCam.m
|
.m
|
MSCKF-1-master/kitti_extraction/utils/devkit/loadCalibrationCamToCam.m
| 1,894 |
utf_8
|
88db832a2338f205ea36b1a9f6231aed
|
function calib = loadCalibrationCamToCam(filename)
% open file
fid = fopen(filename,'r');
if fid<0
calib = [];
return;
end
% read corner distance
calib.cornerdist = readVariable(fid,'corner_dist',1,1);
% read all cameras (maximum: 100)
for cam=1:100
% read variables
S_ = readVariable(fid,['S_' num2str(cam-1,'%02d')],1,2);
K_ = readVariable(fid,['K_' num2str(cam-1,'%02d')],3,3);
D_ = readVariable(fid,['D_' num2str(cam-1,'%02d')],1,5);
R_ = readVariable(fid,['R_' num2str(cam-1,'%02d')],3,3);
T_ = readVariable(fid,['T_' num2str(cam-1,'%02d')],3,1);
S_rect_ = readVariable(fid,['S_rect_' num2str(cam-1,'%02d')],1,2);
R_rect_ = readVariable(fid,['R_rect_' num2str(cam-1,'%02d')],3,3);
P_rect_ = readVariable(fid,['P_rect_' num2str(cam-1,'%02d')],3,4);
% calibration for this cam completely found?
if isempty(S_) || isempty(K_) || isempty(D_) || isempty(R_) || isempty(T_)
break;
end
% write calibration
calib.S{cam} = S_;
calib.K{cam} = K_;
calib.D{cam} = D_;
calib.R{cam} = R_;
calib.T{cam} = T_;
% if rectification available
if ~isempty(S_rect_) && ~isempty(R_rect_) && ~isempty(P_rect_)
calib.S_rect{cam} = S_rect_;
calib.R_rect{cam} = R_rect_;
calib.P_rect{cam} = P_rect_;
end
end
% close file
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A = readVariable(fid,name,M,N)
% rewind
fseek(fid,0,'bof');
% search for variable identifier
success = 1;
while success>0
[str,success] = fscanf(fid,'%s',1);
if strcmp(str,[name ':'])
break;
end
end
% return if variable identifier not found
if ~success
A = [];
return;
end
% fill matrix
A = zeros(M,N);
for m=1:M
for n=1:N
[val,success] = fscanf(fid,'%f',1);
if success
A(m,n) = val;
else
A = [];
return;
end
end
end
|
github
|
TurtleZhong/MSCKF-1-master
|
loadCalibrationRigid.m
|
.m
|
MSCKF-1-master/kitti_extraction/utils/devkit/loadCalibrationRigid.m
| 855 |
utf_8
|
9148661cd7335b41dace4f57bd25b3a4
|
function Tr = loadCalibrationRigid(filename)
% open file
fid = fopen(filename,'r');
if fid<0
error(['ERROR: Could not load: ' filename]);
end
% read calibration
R = readVariable(fid,'R',3,3);
T = readVariable(fid,'T',3,1);
Tr = [R T;0 0 0 1];
% close file
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A = readVariable(fid,name,M,N)
% rewind
fseek(fid,0,'bof');
% search for variable identifier
success = 1;
while success>0
[str,success] = fscanf(fid,'%s',1);
if strcmp(str,[name ':'])
break;
end
end
% return if variable identifier not found
if ~success
A = [];
return;
end
% fill matrix
A = zeros(M,N);
for m=1:M
for n=1:N
[val,success] = fscanf(fid,'%f',1);
if success
A(m,n) = val;
else
A = [];
return;
end
end
end
|
github
|
ganlubbq/Signal-Processing-master
|
findpeaks.m
|
.m
|
Signal-Processing-master/findpeaks.m
| 32,468 |
utf_8
|
2b7f5afefbaaafe14b836c32851f6f3d
|
function [Ypk,Xpk,Wpk,Ppk] = findpeaks(Yin,varargin)
%FINDPEAKS Find local peaks in data
% PKS = FINDPEAKS(Y) finds local peaks in the data vector Y. A local peak
% is defined as a data sample which is either larger than the two
% neighboring samples or is equal to Inf.
%
% [PKS,LOCS]= FINDPEAKS(Y) also returns the indices LOCS at which the
% peaks occur.
%
% [PKS,LOCS] = FINDPEAKS(Y,X) specifies X as the location vector of data
% vector Y. X must be a strictly increasing vector of the same length as
% Y. LOCS returns the corresponding value of X for each peak detected.
% If X is omitted, then X will correspond to the indices of Y.
%
% [PKS,LOCS] = FINDPEAKS(Y,Fs) specifies the sample rate, Fs, as a
% positive scalar, where the first sample instant of Y corresponds to a
% time of zero.
%
% [...] = FINDPEAKS(...,'MinPeakHeight',MPH) finds only those peaks that
% are greater than the minimum peak height, MPH. MPH is a real-valued
% scalar. The default value of MPH is -Inf.
%
% [...] = FINDPEAKS(...,'MinPeakProminence',MPP) finds peaks guaranteed
% to have a vertical drop of more than MPP from the peak on both sides
% without encountering either the end of the signal or a larger
% intervening peak. The default value of MPP is zero.
%
% [...] = FINDPEAKS(...,'Threshold',TH) finds peaks that are at least
% greater than both adjacent samples by the threshold, TH. TH is a
% real-valued scalar greater than or equal to zero. The default value of
% TH is zero.
%
% FINDPEAKS(...,'WidthReference',WR) estimates the width of the peak as
% the distance between the points where the signal intercepts a
% horizontal reference line. The points are found by linear
% interpolation. The height of the line is selected using the criterion
% specified in WR:
%
% 'halfprom' - the reference line is positioned beneath the peak at a
% vertical distance equal to half the peak prominence.
%
% 'halfheight' - the reference line is positioned at one-half the peak
% height. The line is truncated if any of its intercept points lie
% beyond the borders of the peaks selected by the 'MinPeakHeight',
% 'MinPeakProminence' and 'Threshold' parameters. The border between
% peaks is defined by the horizontal position of the lowest valley
% between them. Peaks with heights less than zero are discarded.
%
% The default value of WR is 'halfprom'.
%
% [...] = FINDPEAKS(...,'MinPeakWidth',MINW) finds peaks whose width is
% at least MINW. The default value of MINW is zero.
%
% [...] = FINDPEAKS(...,'MaxPeakWidth',MAXW) finds peaks whose width is
% at most MAXW. The default value of MAXW is Inf.
%
% [...] = FINDPEAKS(...,'MinPeakDistance',MPD) finds peaks separated by
% more than the minimum peak distance, MPD. This parameter may be
% specified to ignore smaller peaks that may occur in close proximity to
% a large local peak. For example, if a large local peak occurs at LOC,
% then all smaller peaks in the range [N-MPD, N+MPD] are ignored. If not
% specified, MPD is assigned a value of zero.
%
% [...] = FINDPEAKS(...,'SortStr',DIR) specifies the direction of sorting
% of peaks. DIR can take values of 'ascend', 'descend' or 'none'. If not
% specified, DIR takes the value of 'none' and the peaks are returned in
% the order of their occurrence.
%
% [...] = FINDPEAKS(...,'NPeaks',NP) specifies the maximum number of peaks
% to be found. NP is an integer greater than zero. If not specified, all
% peaks are returned. Use this parameter in conjunction with setting the
% sort direction to 'descend' to return the NP largest peaks. (see
% 'SortStr')
%
% [PKS,LOCS,W] = FINDPEAKS(...) returns the width, W, of each peak by
% linear interpolation of the left- and right- intercept points to the
% reference defined by 'WidthReference'.
%
% [PKS,LOCS,W,P] = FINDPEAKS(...) returns the prominence, P, of each
% peak.
%
% FINDPEAKS(...) without output arguments plots the signal and the peak
% values it finds
%
% FINDPEAKS(...,'Annotate',PLOTSTYLE) will annotate a plot of the
% signal with PLOTSTYLE. If PLOTSTYLE is 'peaks' the peaks will be
% plotted. If PLOTSTYLE is 'extents' the signal, peak values, widths,
% prominences of each peak will be annotated. 'Annotate' will be ignored
% if called with output arguments. The default value of PLOTSTYLE is
% 'peaks'.
%
% % Example 1:
% % Plot the Zurich numbers of sunspot activity from years 1700-1987
% % and identify all local maxima at least six years apart
% load sunspot.dat
% findpeaks(sunspot(:,2),sunspot(:,1),'MinPeakDistance',6)
% xlabel('Year');
% ylabel('Zurich number');
%
% % Example 2:
% % Plot peak values of an audio signal that drop at least 1V on either
% % side without encountering values larger than the peak.
% load mtlb
% findpeaks(mtlb,Fs,'MinPeakProminence',1)
%
% % Example 3:
% % Plot all peaks of a chirp signal whose widths are between .5 and 1
% % milliseconds.
% Fs = 44.1e3; N = 1000;
% x = sin(2*pi*(1:N)/N + (10*(1:N)/N).^2);
% findpeaks(x,Fs,'MinPeakWidth',.5e-3,'MaxPeakWidth',1e-3, ...
% 'Annotate','extents')
%
% See also MAX, FINDCHANGEPTS.
% Copyright 2007-2015 The MathWorks, Inc.
%#ok<*EMCLS>
%#ok<*EMCA>
%#codegen
cond = nargin >= 1;
if ~cond
coder.internal.assert(cond,'MATLAB:narginchk:notEnoughInputs');
end
cond = nargin <= 22;
if ~cond
coder.internal.assert(cond,'MATLAB:narginchk:tooManyInputs');
end
% extract the parameters from the input argument list
[y,yIsRow,x,xIsRow,minH,minP,minW,maxW,minD,minT,maxN,sortDir,annotate,refW] ...
= parse_inputs(Yin,varargin{:});
% find indices of all finite and infinite peaks and the inflection points
[iFinite,iInfite,iInflect] = getAllPeaks(y);
% keep only the indices of finite peaks that meet the required
% minimum height and threshold
iPk = removePeaksBelowMinPeakHeight(y,iFinite,minH,refW);
iPk = removePeaksBelowThreshold(y,iPk,minT);
% indicate if we need to compute the extent of a peak
needWidth = minW>0 || maxW<inf || minP>0 || nargout>2 || strcmp(annotate,'extents');
if needWidth
% obtain the indices of each peak (iPk), the prominence base (bPk), and
% the x- and y- coordinates of the peak base (bxPk, byPk) and the width
% (wxPk)
[iPk,bPk,bxPk,byPk,wxPk] = findExtents(y,x,iPk,iFinite,iInfite,iInflect,minP,minW,maxW,refW);
else
% combine finite and infinite peaks into one list
[iPk,bPk,bxPk,byPk,wxPk] = combinePeaks(iPk,iInfite);
end
% find the indices of the largest peaks within the specified distance
idx = findPeaksSeparatedByMoreThanMinPeakDistance(y,x,iPk,minD);
% re-order and bound the number of peaks based upon the index vector
idx = orderPeaks(y,iPk,idx,sortDir);
idx = keepAtMostNpPeaks(idx,maxN);
% use the index vector to fetch the correct peaks.
iPk = iPk(idx);
if needWidth
[bPk, bxPk, byPk, wxPk] = fetchPeakExtents(idx,bPk,bxPk,byPk,wxPk);
end
if nargout > 0
% assign output variables
if needWidth
[Ypk,Xpk,Wpk,Ppk] = assignFullOutputs(y,x,iPk,wxPk,bPk,yIsRow,xIsRow);
else
[Ypk,Xpk] = assignOutputs(y,x,iPk,yIsRow,xIsRow);
end
else
% no output arguments specified. plot and optionally annotate
hAxes = plotSignalWithPeaks(x,y,iPk);
if strcmp(annotate,'extents')
plotExtents(hAxes,x,y,iPk,bPk,bxPk,byPk,wxPk,refW);
end
scalePlot(hAxes);
end
%--------------------------------------------------------------------------
function [y,yIsRow,x,xIsRow,Ph,Pp,Wmin,Wmax,Pd,Th,NpOut,Str,Ann,Ref] = parse_inputs(Yin,varargin)
% Validate input signal
validateattributes(Yin,{'numeric'},{'nonempty','real','vector'},...
'findpeaks','Y');
yIsRow = isrow(Yin);
y = Yin(:);
% copy over orientation of y to x.
xIsRow = yIsRow;
% indicate if the user specified an Fs or X
hasX = ~isempty(varargin) && (isnumeric(varargin{1}) || ...
coder.target('MATLAB') && isdatetime(varargin{1}) && numel(varargin{1})>1);
if hasX
startArg = 2;
if isscalar(varargin{1})
% Fs
Fs = varargin{1};
validateattributes(Fs,{'double'},{'real','finite','positive'},'findpeaks','Fs');
x = (0:numel(y)-1).'/Fs;
else
% X
Xin = varargin{1};
if isnumeric(Xin)
validateattributes(Xin,{'double'},{'real','finite','vector','increasing'},'findpeaks','X');
else % isdatetime(Xin)
validateattributes(seconds(Xin-Xin(1)),{'double'},{'real','finite','vector','increasing'},'findpeaks','X');
end
if numel(Xin) ~= numel(Yin)
if coder.target('MATLAB')
throwAsCaller(MException(message('signal:findpeaks:mismatchYX')));
else
coder.internal.errorIf(true,'signal:findpeaks:mismatchYX');
end
end
xIsRow = isrow(Xin);
x = Xin(:);
end
else
startArg = 1;
% unspecified, use index vector
x = (1:numel(y)).';
end
if coder.target('MATLAB')
try %#ok<EMTC>
% Check the input data type. Single precision is not supported.
chkinputdatatype(y);
if isnumeric(x)
chkinputdatatype(x);
end
catch ME
throwAsCaller(ME);
end
else
chkinputdatatype(y);
chkinputdatatype(x);
end
M = numel(y);
cond = (M < 3);
if cond
coder.internal.errorIf(cond,'signal:findpeaks:emptyDataSet');
end
%#function dspopts.findpeaks
defaultMinPeakHeight = -inf;
defaultMinPeakProminence = 0;
defaultMinPeakWidth = 0;
defaultMaxPeakWidth = Inf;
defaultMinPeakDistance = 0;
defaultThreshold = 0;
defaultNPeaks = [];
defaultSortStr = 'none';
defaultAnnotate = 'peaks';
defaultWidthReference = 'halfprom';
if coder.target('MATLAB')
p = inputParser;
addParameter(p,'MinPeakHeight',defaultMinPeakHeight);
addParameter(p,'MinPeakProminence',defaultMinPeakProminence);
addParameter(p,'MinPeakWidth',defaultMinPeakWidth);
addParameter(p,'MaxPeakWidth',defaultMaxPeakWidth);
addParameter(p,'MinPeakDistance',defaultMinPeakDistance);
addParameter(p,'Threshold',defaultThreshold);
addParameter(p,'NPeaks',defaultNPeaks);
addParameter(p,'SortStr',defaultSortStr);
addParameter(p,'Annotate',defaultAnnotate);
addParameter(p,'WidthReference',defaultWidthReference);
parse(p,varargin{startArg:end});
Ph = p.Results.MinPeakHeight;
Pp = p.Results.MinPeakProminence;
Wmin = p.Results.MinPeakWidth;
Wmax = p.Results.MaxPeakWidth;
Pd = p.Results.MinPeakDistance;
Th = p.Results.Threshold;
Np = p.Results.NPeaks;
Str = p.Results.SortStr;
Ann = p.Results.Annotate;
Ref = p.Results.WidthReference;
else
parms = struct('MinPeakHeight',uint32(0), ...
'MinPeakProminence',uint32(0), ...
'MinPeakWidth',uint32(0), ...
'MaxPeakWidth',uint32(0), ...
'MinPeakDistance',uint32(0), ...
'Threshold',uint32(0), ...
'NPeaks',uint32(0), ...
'SortStr',uint32(0), ...
'Annotate',uint32(0), ...
'WidthReference',uint32(0));
pstruct = eml_parse_parameter_inputs(parms,[],varargin{startArg:end});
Ph = eml_get_parameter_value(pstruct.MinPeakHeight,defaultMinPeakHeight,varargin{startArg:end});
Pp = eml_get_parameter_value(pstruct.MinPeakProminence,defaultMinPeakProminence,varargin{startArg:end});
Wmin = eml_get_parameter_value(pstruct.MinPeakWidth,defaultMinPeakWidth,varargin{startArg:end});
Wmax = eml_get_parameter_value(pstruct.MaxPeakWidth,defaultMaxPeakWidth,varargin{startArg:end});
Pd = eml_get_parameter_value(pstruct.MinPeakDistance,defaultMinPeakDistance,varargin{startArg:end});
Th = eml_get_parameter_value(pstruct.Threshold,defaultThreshold,varargin{startArg:end});
Np = eml_get_parameter_value(pstruct.NPeaks,defaultNPeaks,varargin{startArg:end});
Str = eml_get_parameter_value(pstruct.SortStr,defaultSortStr,varargin{startArg:end});
Ann = eml_get_parameter_value(pstruct.Annotate,defaultAnnotate,varargin{startArg:end});
Ref = eml_get_parameter_value(pstruct.WidthReference,defaultWidthReference,varargin{startArg:end});
end
% limit the number of peaks to the number of input samples
if isempty(Np)
NpOut = M;
else
NpOut = Np;
end
% ignore peaks below zero when using halfheight width reference
if strcmp(Ref,'halfheight')
Ph = max(Ph,0);
end
validateattributes(Ph,{'numeric'},{'real','scalar','nonempty'},'findpeaks','MinPeakHeight');
if isnumeric(x)
validateattributes(Pd,{'numeric'},{'real','scalar','nonempty','nonnegative','<',x(M)-x(1)},'findpeaks','MinPeakDistance');
else
if coder.target('MATLAB') && isduration(Pd)
validateattributes(seconds(Pd),{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakDistance');
else
validateattributes(Pd,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakDistance');
end
end
validateattributes(Pp,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakProminence');
if coder.target('MATLAB') && isduration(Wmin)
validateattributes(seconds(Wmin),{'numeric'},{'real','scalar','finite','nonempty','nonnegative'},'findpeaks','MinPeakWidth');
else
validateattributes(Wmin,{'numeric'},{'real','scalar','finite','nonempty','nonnegative'},'findpeaks','MinPeakWidth');
end
if coder.target('MATLAB') && isduration(Wmax)
validateattributes(seconds(Wmax),{'numeric'},{'real','scalar','nonnan','nonempty','nonnegative'},'findpeaks','MaxPeakWidth');
else
validateattributes(Wmax,{'numeric'},{'real','scalar','nonnan','nonempty','nonnegative'},'findpeaks','MaxPeakWidth');
end
if coder.target('MATLAB') && isduration(Pd)
validateattributes(seconds(Pd),{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakDistance');
else
validateattributes(Pd,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','MinPeakDistance');
end
validateattributes(Th,{'numeric'},{'real','scalar','nonempty','nonnegative'},'findpeaks','Threshold');
validateattributes(NpOut,{'numeric'},{'real','scalar','nonempty','integer','positive'},'findpeaks','NPeaks');
Str = validatestring(Str,{'ascend','none','descend'},'findpeaks','SortStr');
Ann = validatestring(Ann,{'peaks','extents'},'findpeaks','SortStr');
Ref = validatestring(Ref,{'halfprom','halfheight'},'findpeaks','WidthReference');
%--------------------------------------------------------------------------
function [iPk,iInf,iInflect] = getAllPeaks(y)
% fetch indices all infinite peaks
iInf = find(isinf(y) & y>0);
% temporarily remove all +Inf values
yTemp = y;
yTemp(iInf) = NaN;
% determine the peaks and inflection points of the signal
[iPk,iInflect] = findLocalMaxima(yTemp);
%--------------------------------------------------------------------------
function [iPk, iInflect] = findLocalMaxima(yTemp)
% bookend Y by NaN and make index vector
yTemp = [NaN; yTemp; NaN];
iTemp = (1:numel(yTemp)).';
% keep only the first of any adjacent pairs of equal values (including NaN).
yFinite = ~isnan(yTemp);
iNeq = [1; 1 + find((yTemp(1:end-1) ~= yTemp(2:end)) & ...
(yFinite(1:end-1) | yFinite(2:end)))];
iTemp = iTemp(iNeq);
% take the sign of the first sample derivative
s = sign(diff(yTemp(iTemp)));
% find local maxima
iMax = 1 + find(diff(s)<0);
% find all transitions from rising to falling or to NaN
iAny = 1 + find(s(1:end-1)~=s(2:end));
% index into the original index vector without the NaN bookend.
iInflect = iTemp(iAny)-1;
iPk = iTemp(iMax)-1;
%--------------------------------------------------------------------------
function iPk = removePeaksBelowMinPeakHeight(Y,iPk,Ph,widthRef)
if ~isempty(iPk)
iPk = iPk(Y(iPk) > Ph);
if isempty(iPk) && ~strcmp(widthRef,'halfheight')
if coder.target('MATLAB')
warning(message('signal:findpeaks:largeMinPeakHeight', 'MinPeakHeight', 'MinPeakHeight'));
end
end
end
%--------------------------------------------------------------------------
function iPk = removePeaksBelowThreshold(Y,iPk,Th)
base = max(Y(iPk-1),Y(iPk+1));
iPk = iPk(Y(iPk)-base >= Th);
%--------------------------------------------------------------------------
function [iPk,bPk,bxPk,byPk,wxPk] = findExtents(y,x,iPk,iFin,iInf,iInflect,minP,minW,maxW,refW)
% temporarily filter out +Inf from the input
yFinite = y;
yFinite(iInf) = NaN;
% get the base and left and right indices of each prominence base
[bPk,iLB,iRB] = getPeakBase(yFinite,iPk,iFin,iInflect);
% keep only those indices with at least the specified prominence
[iPk,bPk,iLB,iRB] = removePeaksBelowMinPeakProminence(yFinite,iPk,bPk,iLB,iRB,minP);
% get the x-coordinates of the half-height width borders of each peak
[wxPk,iLBh,iRBh] = getPeakWidth(yFinite,x,iPk,bPk,iLB,iRB,refW);
% merge finite and infinite peaks together into one list
[iPk,bPk,bxPk,byPk,wxPk] = combineFullPeaks(y,x,iPk,bPk,iLBh,iRBh,wxPk,iInf);
% keep only those in the range minW < w < maxW
[iPk,bPk,bxPk,byPk,wxPk] = removePeaksOutsideWidth(iPk,bPk,bxPk,byPk,wxPk,minW,maxW);
%--------------------------------------------------------------------------
function [peakBase,iLeftSaddle,iRightSaddle] = getPeakBase(yTemp,iPk,iFin,iInflect)
% determine the indices that border each finite peak
[iLeftBase, iLeftSaddle] = getLeftBase(yTemp,iPk,iFin,iInflect);
[iRightBase, iRightSaddle] = getLeftBase(yTemp,flipud(iPk),flipud(iFin),flipud(iInflect));
iRightBase = flipud(iRightBase);
iRightSaddle = flipud(iRightSaddle);
peakBase = max(yTemp(iLeftBase),yTemp(iRightBase));
%--------------------------------------------------------------------------
function [iBase, iSaddle] = getLeftBase(yTemp,iPeak,iFinite,iInflect)
% pre-initialize output base and saddle indices
iBase = zeros(size(iPeak));
iSaddle = zeros(size(iPeak));
% table stores the most recently encountered peaks in order of height
peak = zeros(size(iFinite));
valley = zeros(size(iFinite));
iValley = zeros(size(iFinite));
n = 0;
i = 1;
j = 1;
k = 1;
% pre-initialize v for code generation
v = NaN;
iv = 1;
while k<=numel(iPeak)
% walk through the inflections until you reach a peak
while iInflect(i) ~= iFinite(j)
v = yTemp(iInflect(i));
iv = iInflect(i);
if isnan(v)
% border seen, start over.
n = 0;
else
% ignore previously stored peaks with a valley larger than this one
while n>0 && valley(n)>v;
n = n - 1;
end
end
i = i + 1;
end
% get the peak
p = yTemp(iInflect(i));
% keep the smallest valley of all smaller peaks
while n>0 && peak(n) < p
if valley(n) < v
v = valley(n);
iv = iValley(n);
end
n = n - 1;
end
% record "saddle" valleys in between equal-height peaks
isv = iv;
% keep seeking smaller valleys until you reach a larger peak
while n>0 && peak(n) <= p
if valley(n) < v
v = valley(n);
iv = iValley(n);
end
n = n - 1;
end
% record the new peak and save the index of the valley into the base
% and saddle
n = n + 1;
peak(n) = p;
valley(n) = v;
iValley(n) = iv;
if iInflect(i) == iPeak(k)
iBase(k) = iv;
iSaddle(k) = isv;
k = k + 1;
end
i = i + 1;
j = j + 1;
end
%--------------------------------------------------------------------------
function [iPk,pbPk,iLB,iRB] = removePeaksBelowMinPeakProminence(y,iPk,pbPk,iLB,iRB,minP)
% compute the prominence of each peak
Ppk = y(iPk)-pbPk;
% keep those that are above the specified prominence
idx = find(Ppk >= minP);
iPk = iPk(idx);
pbPk = pbPk(idx);
iLB = iLB(idx);
iRB = iRB(idx);
%--------------------------------------------------------------------------
function [wxPk,iLBh,iRBh] = getPeakWidth(y,x,iPk,pbPk,iLB,iRB,wRef)
if isempty(iPk)
% no peaks. define empty containers
base = zeros(size(iPk));
iLBh = zeros(size(iPk));
iRBh = zeros(size(iPk));
elseif strcmp(wRef,'halfheight')
% set the baseline to zero
base = zeros(size(iPk));
% border the width by no more than the lowest valley between this peak
% and the next peak
iLBh = [iLB(1); max(iLB(2:end),iRB(1:end-1))];
iRBh = [min(iRB(1:end-1),iLB(2:end)); iRB(end)];
iGuard = iLBh > iPk;
iLBh(iGuard) = iLB(iGuard);
iGuard = iRBh < iPk;
iRBh(iGuard) = iRB(iGuard);
else
% use the prominence base
base = pbPk;
% border the width by the saddle of the peak
iLBh = iLB;
iRBh = iRB;
end
% get the width boundaries of each peak
wxPk = getHalfMaxBounds(y, x, iPk, base, iLBh, iRBh);
%--------------------------------------------------------------------------
function bounds = getHalfMaxBounds(y, x, iPk, base, iLB, iRB)
if isnumeric(x)
bounds = zeros(numel(iPk),2);
else
bounds = [x(1:numel(iPk)) x(1:numel(iPk))];
end
% interpolate both the left and right bounds clamping at borders
for i=1:numel(iPk)
% compute the desired reference level at half-height or half-prominence
refHeight = (y(iPk(i))+base(i))/2;
% compute the index of the left-intercept at half max
iLeft = findLeftIntercept(y, iPk(i), iLB(i), refHeight);
if iLeft < iLB(i)
xLeft = x(iLB(i));
else
xLeft = linterp(x(iLeft),x(iLeft+1),y(iLeft),y(iLeft+1),y(iPk(i)),base(i));
end
% compute the index of the right-intercept
iRight = findRightIntercept(y, iPk(i), iRB(i), refHeight);
if iRight > iRB(i)
xRight = x(iRB(i));
else
xRight = linterp(x(iRight), x(iRight-1), y(iRight), y(iRight-1), y(iPk(i)),base(i));
end
% store result
bounds(i,:) = [xLeft xRight];
end
%--------------------------------------------------------------------------
function idx = findLeftIntercept(y, idx, borderIdx, refHeight)
% decrement index until you pass under the reference height or pass the
% index of the left border, whichever comes first
while idx>=borderIdx && y(idx) > refHeight
idx = idx - 1;
end
%--------------------------------------------------------------------------
function idx = findRightIntercept(y, idx, borderIdx, refHeight)
% increment index until you pass under the reference height or pass the
% index of the right border, whichever comes first
while idx<=borderIdx && y(idx) > refHeight
idx = idx + 1;
end
%--------------------------------------------------------------------------
function xc = linterp(xa,xb,ya,yb,yc,bc)
% interpolate between points (xa,ya) and (xb,yb) to find (xc, 0.5*(yc-yc)).
xc = xa + (xb-xa) .* (0.5*(yc+bc)-ya) ./ (yb-ya);
% invoke L'Hospital's rule when -Inf is encountered.
if isnumeric(xc) && isnan(xc) || coder.target('MATLAB') && isdatetime(xc) && isnat(xc)
% yc and yb are guaranteed to be finite.
if isinf(bc)
% both ya and bc are -Inf.
if isnumeric(xa)
xc = 0.5*(xa+xb);
else
xc = xa+0.5*(xb-xa);
end
else
% only ya is -Inf.
xc = xb;
end
end
%--------------------------------------------------------------------------
function [iPk,bPk,bxPk,byPk,wxPk] = removePeaksOutsideWidth(iPk,bPk,bxPk,byPk,wxPk,minW,maxW)
if isempty(iPk) || minW==0 && maxW == inf;
return
end
% compute the width of each peak and extract the matching indices
w = diff(wxPk,1,2);
idx = find(minW <= w & w <= maxW);
% fetch the surviving peaks
iPk = iPk(idx);
bPk = bPk(idx);
bxPk = bxPk(idx,:);
byPk = byPk(idx,:);
wxPk = wxPk(idx,:);
%--------------------------------------------------------------------------
function [iPkOut,bPk,bxPk,byPk,wxPk] = combinePeaks(iPk,iInf)
iPkOut = union(iPk,iInf);
bPk = zeros(0,1);
bxPk = zeros(0,2);
byPk = zeros(0,2);
wxPk = zeros(0,2);
%--------------------------------------------------------------------------
function [iPkOut,bPkOut,bxPkOut,byPkOut,wxPkOut] = combineFullPeaks(y,x,iPk,bPk,iLBw,iRBw,wPk,iInf)
iPkOut = union(iPk, iInf);
% create map of new indices to old indices
[~, iFinite] = intersect(iPkOut,iPk);
[~, iInfinite] = intersect(iPkOut,iInf);
% prevent row concatenation when iPk and iInf both have less than one
% element
iPkOut = iPkOut(:);
% compute prominence base
bPkOut = zeros(size(iPkOut));
bPkOut(iFinite) = bPk;
bPkOut(iInfinite) = 0;
% compute indices of left and right infinite borders
iInfL = max(1,iInf-1);
iInfR = min(iInf+1,numel(x));
% copy out x- values of the left and right prominence base
% set each base border of an infinite peaks halfway between itself and
% the next adjacent sample
if isnumeric(x)
bxPkOut = zeros(size(iPkOut,1),2);
bxPkOut(iFinite,1) = x(iLBw);
bxPkOut(iFinite,2) = x(iRBw);
bxPkOut(iInfinite,1) = 0.5*(x(iInf)+x(iInfL));
bxPkOut(iInfinite,2) = 0.5*(x(iInf)+x(iInfR));
else
bxPkOut = [x(1:size(iPkOut,1)) x(1:size(iPkOut,1))];
bxPkOut(iFinite,1) = x(iLBw);
bxPkOut(iFinite,2) = x(iRBw);
bxPkOut(iInfinite,1) = x(iInf) + 0.5*(x(iInfL)-x(iInf));
bxPkOut(iInfinite,2) = x(iInf) + 0.5*(x(iInfR)-x(iInf));
end
% copy out y- values of the left and right prominence base
byPkOut = zeros(size(iPkOut,1),2);
byPkOut(iFinite,1) = y(iLBw);
byPkOut(iFinite,2) = y(iRBw);
byPkOut(iInfinite,1) = y(iInfL);
byPkOut(iInfinite,2) = y(iInfR);
% copy out x- values of the width borders
% set each width borders of an infinite peaks halfway between itself and
% the next adjacent sample
if isnumeric(x)
wxPkOut = zeros(size(iPkOut,1),2);
wxPkOut(iFinite,:) = wPk;
wxPkOut(iInfinite,1) = 0.5*(x(iInf)+x(iInfL));
wxPkOut(iInfinite,2) = 0.5*(x(iInf)+x(iInfR));
else
wxPkOut = [x(1:size(iPkOut,1)) x(1:size(iPkOut,1))];
wxPkOut(iFinite,:) = wPk;
wxPkOut(iInfinite,1) = x(iInf)+0.5*(x(iInfL)-x(iInf));
wxPkOut(iInfinite,2) = x(iInf)+0.5*(x(iInfR)-x(iInf));
end
%--------------------------------------------------------------------------
function idx = findPeaksSeparatedByMoreThanMinPeakDistance(y,x,iPk,Pd)
% Start with the larger peaks to make sure we don't accidentally keep a
% small peak and remove a large peak in its neighborhood.
if isempty(iPk) || Pd==0
idx = (1:numel(iPk)).';
return
end
% copy peak values and locations to a temporary place
pks = y(iPk);
locs = x(iPk);
% Order peaks from large to small
[~, sortIdx] = sort(pks,'descend');
locs_temp = locs(sortIdx);
idelete = ones(size(locs_temp))<0;
for i = 1:length(locs_temp)
if ~idelete(i)
% If the peak is not in the neighborhood of a larger peak, find
% secondary peaks to eliminate.
idelete = idelete | (locs_temp>=locs_temp(i)-Pd)&(locs_temp<=locs_temp(i)+Pd);
idelete(i) = 0; % Keep current peak
end
end
% report back indices in consecutive order
idx = sort(sortIdx(~idelete));
%--------------------------------------------------------------------------
function idx = orderPeaks(Y,iPk,idx,Str)
if isempty(idx) || strcmp(Str,'none')
return
end
if strcmp(Str,'ascend')
[~,s] = sort(Y(iPk(idx)),'ascend');
else
[~,s] = sort(Y(iPk(idx)),'descend');
end
idx = idx(s);
%--------------------------------------------------------------------------
function idx = keepAtMostNpPeaks(idx,Np)
if length(idx)>Np
idx = idx(1:Np);
end
%--------------------------------------------------------------------------
function [bPk,bxPk,byPk,wxPk] = fetchPeakExtents(idx,bPk,bxPk,byPk,wxPk)
bPk = bPk(idx);
bxPk = bxPk(idx,:);
byPk = byPk(idx,:);
wxPk = wxPk(idx,:);
%--------------------------------------------------------------------------
function [YpkOut,XpkOut] = assignOutputs(y,x,iPk,yIsRow,xIsRow)
% fetch the coordinates of the peak
Ypk = y(iPk);
Xpk = x(iPk);
% preserve orientation of Y
if yIsRow
YpkOut = Ypk.';
else
YpkOut = Ypk;
end
% preserve orientation of X
if xIsRow
XpkOut = Xpk.';
else
XpkOut = Xpk;
end
%--------------------------------------------------------------------------
function [YpkOut,XpkOut,WpkOut,PpkOut] = assignFullOutputs(y,x,iPk,wxPk,bPk,yIsRow,xIsRow)
% fetch the coordinates of the peak
Ypk = y(iPk);
Xpk = x(iPk);
% compute the width and prominence
Wpk = diff(wxPk,1,2);
Ppk = Ypk-bPk;
% preserve orientation of Y (and P)
if yIsRow
YpkOut = Ypk.';
PpkOut = Ppk.';
else
YpkOut = Ypk;
PpkOut = Ppk;
end
% preserve orientation of X (and W)
if xIsRow
XpkOut = Xpk.';
WpkOut = Wpk.';
else
XpkOut = Xpk;
WpkOut = Wpk;
end
%--------------------------------------------------------------------------
function hAxes = plotSignalWithPeaks(x,y,iPk)
% plot signal
hLine = plot(x,y,'Tag','Signal');
hAxes = ancestor(hLine,'Axes');
% turn on grid
grid on;
if numel(x)>1
hAxes.XLim = hLine.XData([1 end]);
end
% use the color of the line
color = get(hLine,'Color');
hLine = line(hLine.XData(iPk),y(iPk),'Parent',hAxes, ...
'Marker','o','LineStyle','none','Color',color,'tag','Peak');
% if using MATLAB use offset inverted triangular marker
if coder.target('MATLAB')
plotpkmarkers(hLine,y(iPk));
end
%--------------------------------------------------------------------------
function plotExtents(hAxes,x,y,iPk,bPk,bxPk,byPk,wxPk,refW)
% compute level of half-maximum (height or prominence)
if strcmp(refW,'halfheight')
hm = 0.5*y(iPk);
else
hm = 0.5*(y(iPk)+bPk);
end
% get the default color order
colors = get(0,'DefaultAxesColorOrder');
% plot boundaries between adjacent peaks when using half-height
if strcmp(refW,'halfheight')
% plot height
plotLines(hAxes,'Height',x(iPk),y(iPk),x(iPk),zeros(numel(iPk),1),colors(2,:));
% plot width
plotLines(hAxes,'HalfHeightWidth',wxPk(:,1),hm,wxPk(:,2),hm,colors(3,:));
% plot peak borders
idx = find(byPk(:,1)>0);
plotLines(hAxes,'Border',bxPk(idx,1),zeros(numel(idx),1),bxPk(idx,1),byPk(idx,1),colors(4,:));
idx = find(byPk(:,2)>0);
plotLines(hAxes,'Border',bxPk(idx,2),zeros(numel(idx),1),bxPk(idx,2),byPk(idx,2),colors(4,:));
else
% plot prominence
plotLines(hAxes,'Prominence',x(iPk), y(iPk), x(iPk), bPk, colors(2,:));
% plot width
plotLines(hAxes,'HalfProminenceWidth',wxPk(:,1), hm, wxPk(:,2), hm, colors(3,:));
% plot peak borders
idx = find(bPk(:)<byPk(:,1));
plotLines(hAxes,'Border',bxPk(idx,1),bPk(idx),bxPk(idx,1),byPk(idx,1),colors(4,:));
idx = find(bPk(:)<byPk(:,2));
plotLines(hAxes,'Border',bxPk(idx,2),bPk(idx),bxPk(idx,2),byPk(idx,2),colors(4,:));
end
if coder.target('MATLAB')
hLine = get(hAxes,'Children');
tags = get(hLine,'tag');
legendStrs = {};
searchTags = {'Signal','Peak','Prominence','Height','HalfProminenceWidth','HalfHeightWidth','Border'};
for i=1:numel(searchTags)
if any(strcmp(searchTags{i},tags))
legendStrs = [legendStrs, ...
{getString(message(['signal:findpeaks:Legend' searchTags{i}]))}]; %#ok<AGROW>
end
end
if numel(hLine)==1
legend(getString(message('signal:findpeaks:LegendSignalNoPeaks')), ...
'Location','best');
else
legend(legendStrs,'Location','best');
end
end
%--------------------------------------------------------------------------
function plotLines(hAxes,tag,x1,y1,x2,y2,c)
% concatenate multiple lines into a single line and fencepost with NaN
n = numel(x1);
if isnumeric(x1)
line(reshape([x1(:).'; x2(:).'; NaN(1,n)], 3*n, 1), ...
reshape([y1(:).'; y2(:).'; NaN(1,n)], 3*n, 1), ...
'Color',c,'Parent',hAxes,'tag',tag);
elseif coder.target('MATLAB') && isdatetime(x1)
line(reshape(datenum([x1(:).'; x2(:).'; NaT(1,n)]), 3*n, 1), ...
reshape([y1(:).'; y2(:).'; NaN(1,n)], 3*n, 1), ...
'Color',c,'Parent',hAxes,'tag',tag);
end
%--------------------------------------------------------------------------
function scalePlot(hAxes)
% In the event that the plot has integer valued y limits, 'axis auto' may
% clip the YLimits directly to the data with no margin. We search every
% line for its max and minimum value and create a temporary annotation that
% is 10% larger than the min and max values. We then feed this to "axis
% auto", save the y limits, set axis to "tight" then restore the y limits.
% This obviates the need to check each line for its max and minimum x
% values as well.
minVal = Inf;
maxVal = -Inf;
if coder.target('MATLAB')
hLines = findall(hAxes,'Type','line');
for i=1:numel(hLines)
data = get(hLines(i),'YData');
data = data(isfinite(data));
if ~isempty(data)
minVal = min(minVal, min(data(:)));
maxVal = max(maxVal, max(data(:)));
end
end
xlimits = xlim;
axis auto
% grow upper and lower y extent by 5% (a total of 10%)
p = .05;
y1 = (1+p)*maxVal - p*minVal;
y2 = (1+p)*minVal - p*maxVal;
% artificially expand the data range by the specified amount
hTempLine = line(xlimits([1 1]),[y1 y2],'Parent',hAxes);
% save the limits
ylimits = ylim;
delete(hTempLine);
else
axis auto
ylimits = ylim;
end
% preserve expanded y limits but tighten x axis.
axis tight
ylim(ylimits);
xlim(xlimits);
% [EOF]
|
github
|
ganlubbq/Signal-Processing-master
|
findFrequencySets.m
|
.m
|
Signal-Processing-master/findFrequencySets.m
| 6,594 |
utf_8
|
e7153b1ff720af9dbc471ef144397eb7
|
% ======================================================================
%> @brief findFrequencySets(obj, type, fLow, fHigh, noHarmonics)
%> Changed by CS, no obj
%> Function finds all frequencies that matches a harmonic set
%>
%> @param obj ThicknessAlgorithm class object
%> @param type Type of psd to search: RESONANCE or MAIN
%> @param fLow Lower Frequency
%> @param fLow Higher Frequency
%> @param fLow Required number of harmonics in each set
%>
%> @retval setsFound Reference to sets found
% ======================================================================
function [setsFound] = findFrequencySets(type, fLow, fHigh, noHarmonics)
%% Function finds all frequencies that matches a harmonic set.
% Start searching for sets from fHigh and towards fLow
% psd: PSD
% locs: Array containing index to peaks in PSD
% fHigh: Upper frequency in emitted pulse.
% Deviation is calculated based on (Fs/N) * deviationFactor
import ppPkg.HarmonicSet
if(obj.RESONANCE == type)
psd = obj.psdResonance;
locs = obj.peakLocationResonance;
deviationInFrequency = (obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH) * obj.config.DEVIATION_FACTOR;
% @TODO: Consider changing how we calculate the deviation frquency.
% It should be based on the relevant frequency resolution
% Frequency resolution is given by
% R = 1/T,
% where T is the recording time of the signal. T = Fs/L,
% where L is number of samples
%
% FTT resolution is given by:
% Rf = Fs/Nfft.
% So having a high Nfft does not improve the frequency
% resolution if T is short
% Ideal we should have: Fs/L = Fs/Nfft => L = Nfft, but this is not the
% case
MIN_REQUIRED_HARMONICS = noHarmonics;
numberOfSets = 0;
% Calculate minimum fundemental frequency that can exists
freqFundamentalMinimum = obj.config.V_PIPE/(2*obj.config.D_NOM);
% Allowed percentage deviaion from target harmonic frequency
% Iterate through array of maxima and find all frequencies that
% matches a set.
% Flip array so start searching from higher frequency
locs = sort(locs);
locs = flip(locs);
for n = 1:length(locs)
for m = (n+1):length(locs)
for j =(m):length(locs)
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
if( j == m )
fN.freq = (locs(n)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fN.peakValue = (psd(locs(n)));
fN.index = locs(n);
fM.freq = (locs(m)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fM.peakValue = (psd(locs(m)));
fM.index = locs(m);
%tempSet = HarmonicSet(freqN, peakN, locs(n), freqM, peakM, locs(m), deviationInFrequency);
%fprintf('create set index n: %d m: %d j: %d\n',n, m, j);
% Only create a new set if the difference
% between freqN and freqM is larger than
% freqFundamentalMinimum
if(abs(fM.freq - fN.freq) > freqFundamentalMinimum)
% Create harmonicSet object
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
%tempSet = HarmonicSet(freqN, peakN, locs(n), freqM, peakM, locs(m), deviationInFrequency);
tempSet = HarmonicSet(fN, fM, deviationInFrequency, fLow, fHigh);
else
tempSet = [];
break;
end
else
fJ.freq = (locs(j)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fJ.peakValue = (psd(locs(j)));
fJ.index = locs(j);
% Try to add next frequency to set
if(tempSet.tryAddFreqFromHigh(fJ))
end
end
end
% Search the other direction
% Try to add frequencies
if(n > 1 && ( numel(tempSet) > 0 ))
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
for K = flip(locs(1:n-1))'
fK.freq = (K-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fK.peakValue = (psd(K));
fK.index = K;
tempSet.tryAddFreqFromLow(fK);
end
end
if( j == length(locs))
%fprintf('try save sets %d countf %d\n',numberOfSets, tempSet.frequencyCount);
if(isempty(tempSet))
elseif(numberOfSets == 0 && (tempSet.numFrequencies >= MIN_REQUIRED_HARMONICS))
numberOfSets = 1;
set = tempSet;
% Only keep sets that have more than MIN_REQUIRED_HARMONICS
% harmonic frequencies
elseif(tempSet.numFrequencies >= MIN_REQUIRED_HARMONICS)
numberOfSets = numberOfSets + 1;
set(numberOfSets) = tempSet;
tempSet = [];
end
end
end
end
if(numberOfSets == 0)
if(obj.config.DEBUG_INFO)
disp('No Sets found, try do adjust dB level')
end
set = [];
else
% Remove all subsets
%set = obj.removeAllSubsets2(set);
% Flip frequency array in Harmonic set so that set always
% start with the lower frequency
for index = 1:length(set)
set(index).flip();
end
end
% Store set to class
if(obj.RESONANCE == type)
obj.setResonance = set;
elseif(obj.MAIN == type)
obj.setMain = set;
end
setsFound = numel(set);
end
|
github
|
ganlubbq/Signal-Processing-master
|
processingBinFile.m
|
.m
|
Signal-Processing-master/Test_Dev/processingBinFile.m
| 2,307 |
utf_8
|
10c8bb9206d91df52481556c83e8c8a9
|
%> @file processingBinFile.m
%> @brief transform one .bin file to 96 x 520 x 2000 .mat file
% ======================================================================
%> @brief Input:
% - PathName, Filename
% - round_per_read = 520
%
%> @brief Output:
% - Signal in .mat format
%
%> @brief Author: Chen Sun; Yingjian Liu
%
%> @brief Date: Sept 13, 2017
% ======================================================================
function [SignalMatrix] = processingBinFile(PathName,FileName)
SignalMatrix = zeros(96,520,2000);
dirF = dir(fullfile(PathName,FileName));
sizeAll = dirF.bytes; % total bytes of 96 x 520 x 2000 data
round_per_read = floor(sizeAll/32096/12); % = 520
fid=fopen(fullfile(PathName,FileName));
status = fseek(fid,0,'bof');
raw_data = fread(fid,32096*12*round_per_read,'uint8');
fclose(fid);
% % Check if is the last read
SignalMatrix = zeros(96,520,2000);
% if size(raw_data,1)<32096
% break
% end
sb=0;
rp_i=0;
ii=zeros(1,128);
for i = 1:fix(size(raw_data,1)/32096) %128
gain(i) = uint8(raw_data(sb+24:sb+24)');
raw_fireTime = uint8(raw_data(sb+25:sb+32)');
fireTimeA(i)= typecast(raw_fireTime,'uint64');
roll_b =typecast(uint8(raw_data(sb+17:sb+18)'),'int16');
pitch_b =typecast(uint8(raw_data(sb+19:sb+20)'),'int16');
if((roll_b~=8224)||(pitch_b~=8224))
rp_i=rp_i+1;
rp_locs(rp_i)=i;
roll_r(i)=roll_b;
pitch_r(i)=pitch_b;
end
for k=0:7
raw_signal = uint8(raw_data(sb+k*4008+41:sb+k*4008+4040)');
signal0 = (typecast(raw_signal, 'uint16'));
signal0 = (double(signal0)-32768)/32768;
% signal0(1)=32768;
raw_firstRef = uint8(raw_data(sb+k*4008+33:sb+k*4008+34)');
firstRef = typecast(raw_firstRef,'uint16');
ch= uint8(raw_data(sb+k*4008+39));
j=ch+1;
ii(j)=ii(j)+1;
SignalMatrix(j,ii(j),:)=signal0;
end
% Increment starting bit. Needed
sb = sb + 32096;
end
|
github
|
ganlubbq/Signal-Processing-master
|
MultiChnLoad.m
|
.m
|
Signal-Processing-master/Test_Dev/reference/MultiChnLoad.m
| 44,220 |
utf_8
|
fb1445fac828ff1d542f7dd03a5a2520
|
function varargout = MultiChnLoad(varargin)
% MULTICHNLOAD MATLAB code for MultiChnLoad.fig
% See also: GUIDE, GUIDATA, GUIHANDLES
% Last Modified by GUIDE v2.5 11-Sep-2017 15:30:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @MultiChnLoad_OpeningFcn, ...
'gui_OutputFcn', @MultiChnLoad_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before MultiChnLoad is made visible.
function MultiChnLoad_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to MultiChnLoad (see VARARGIN)
% Choose default command line output for MultiChnLoad
handles.output = hObject;
handles.figure2 = [];
handles.pathname = [];
handles.filename = [];
handles.metricdata.h1 = [];
handles.metricdata.h2 = [];
handles.thickness = [];
handles.markedthickness = [];
handles.LMax = [];
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes MultiChnLoad wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = MultiChnLoad_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
varargout{1} = handles.output;
% --- Executes on button press in LoadFile.
function LoadFile_Callback(hObject, eventdata, handles)
axes(handles.axes1);
cla;
Testing96D1;
Filename = strcat(PathName,filename);
handles = guidata(findobj('Name','MultiChnLoad'));
%set(handles.FilePath,'String',Filename);
msgbox('Process done!');
guidata(hObject, handles);
% --------------------------------------------------------------------
function FileMenu_Callback(hObject, eventdata, handles)
% --------------------------------------------------------------------
function OpenMenuItem_Callback(hObject, eventdata, handles)
file = uigetfile('*.fig');
if ~isequal(file, 0)
open(file);
end
% --------------------------------------------------------------------
function PrintMenuItem_Callback(hObject, eventdata, handles)
printdlg(handles.figure1)
% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
['Close ' get(handles.figure1,'Name') '...'],...
'Yes','No','Yes');
if strcmp(selection,'No')
return;
end
delete(handles.figure1)
% --- Executes during object creation, after setting all properties.
function FilePath_CreateFcn(hObject, eventdata, handles)
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in Plotting.
function Plotting_Callback(hObject, eventdata, handles)
if isempty(get(handles.FilePath,'String'))
if isempty(handles.pathname)
[filename,PathName]= uigetfile('*.mat');
else
[filename,PathName] = uigetfile([handles.pathname,'*.mat'],'Select the file');
end
dirF = dir(fullfile(PathName,filename));
FileName = strcat(PathName,filename);
set(handles.FilePath,'String',FileName);
load(FileName);
handles.pathname = PathName;
handles.filename = filename;
handles.signal = S;
else
BinName = get(handles.FilePath,'String');
FileName = strcat(BinName(1:end-4),'.mat');
if isempty(handles.filename)
load(FileName);
% handles.filename = FileName;
handles.signal = S;
else
S = handles.signal;
end
end
channelValue = get(handles.listChannels,'Value');
if isempty(get(handles.ActualMapping,'String'))
%for Olympus
trLayout = [1 33 17 29 13 93 49 81 65 77 61 21 25 9 41 5 37 69 73 57 89 53 85 45 2 34 18 30 14 94 50 82 66 78 62 22 26 10 42 6 38 70 74 58 90 54 86 46 3 35 19 31 15 95 51 83 67 79 63 23 27 11 43 7 39 71 75 59 91 55 87 47 4 36 20 32 16 96 52 84 68 80 64 24 28 12 44 8 40 72 76 60 92 56 88 48];
% %for Olympus
% trLayout = 1:96;
% % for Fraunhofer.
% trLayout = [1 17 13 33 5 93 49 65 61 81 77 21 25 41 37 9 29 69 73 89 85 57 53 45 2 18 14 34 6 94 50 66 62 82 78 22 26 42 38 10 30 70 74 90 86 58 54 46 3 19 15 35 7 95 51 67 63 83 79 23 27 43 39 11 31 71 75 91 87 59 55 47 4 20 16 36 8 96 52 68 64 84 80 24 28 44 40 12 32 72 76 92 88 60 56 48];
% for Frauhofer old.
% trLayout = [54 63 72 81 90 3 12 21 60 69 78 87 96 9 18 27 66 75 84 93 6 15 24 33 48 57 36 42 45 51 30 39 53 62 71 80 89 2 11 20 58 68 77 86 95 8 17 26 65 74 83 92 5 14 23 32 47 56 35 41 44 50 29 38 46 55 64 73 82 91 4 13 52 61 70 79 88 1 10 19 58 67 76 85 94 7 16 25 40 49 28 34 37 43 22 31]
% for Frauhofer old.
% trLayout = [78 44 6 71 37 21 86 52 14 79 45 7 72 38 22 87 53 15 80 46 8 63 39 23 88 54 16 59 47 95 64 40 24 60 55 91 61 48 96 57 31 92 62 56 93 65 27 89 58 32 94 73 28 1 66 29 90 81 25 9 74 30 2 67 33 17 82 26 10 75 41 3 68 34 18 83 49 11 76 42 4 69 35 19 84 50 12 77 43 5 70 36 20 85 51 13 14];
set(handles.ActualMapping,'String',num2str(trLayout));
else
trLayout = str2num(get(handles.ActualMapping,'String'));
end
StartChn = (channelValue-1)*12;
SNames = fieldnames(S);
PlottingChoice = get(handles.PlottingChoice,'Value');
% TimeYLimMin = 500;
% TimeYLimMax = 1200;
% SpectrumYLimMin = 200;
% SpectrumYLimMax = 1100;
TimeYLimMin = str2num(handles.TimeMin.String);
TimeYLimMax = str2num(handles.TimeMax.String);
SpectrumYLimMin = str2num(handles.SpectrumMin.String);
SpectrumYLimMax = str2num(handles.SpectrumMax.String);
scale = str2num(handles.TimeColorScale.String);
SpectrumScale = str2num(handles.SpectrumColorScale.String);
fftStart = str2num(handles.SignalStart.String);
fftEnd = str2num(handles.SignalEnd.String);
switch PlottingChoice
case 1
signal = S.(SNames{trLayout(StartChn+1)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes1);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+2)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes2);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+3)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes3);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+4)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes4);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+5)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes5);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+6)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes6);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+7)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes7);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+8)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes8);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+9)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes9);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+10)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes10);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+11)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes11);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
signal = S.(SNames{trLayout(StartChn+12)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
axes(handles.axes12);
gca,imagesc(signal');
set(gca,'YLim',[TimeYLimMin TimeYLimMax]);
case 2
nFFT = 4096;
Fs = 15E6;
%newSpectrogram = zeros(size(signal,1),nFFT);
axes(handles.axes1);
signal = S.(SNames{trLayout(StartChn+1)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes2);
signal = S.(SNames{trLayout(StartChn+2)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes3);
signal = S.(SNames{trLayout(StartChn+3)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes4);
signal = S.(SNames{trLayout(StartChn+4)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes5);
signal = S.(SNames{trLayout(StartChn+5)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes6);
signal = S.(SNames{trLayout(StartChn+6)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes7);
signal = S.(SNames{trLayout(StartChn+7)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes8);
signal = S.(SNames{trLayout(StartChn+8)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes9);
signal = S.(SNames{trLayout(StartChn+9)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes10);
signal = S.(SNames{trLayout(StartChn+10)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes11);
signal = S.(SNames{trLayout(StartChn+11)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
axes(handles.axes12);
signal = S.(SNames{trLayout(StartChn+12)});
% if max(max(signal(:,1400:2000))) > 0.8
% signal((signal > 0.7)) = signal((signal > 0.7)) - 1;
% end
for i = 1:size(signal,1)
newSpectrogram(i,:) = abs(fft(signal(i,fftStart:fftEnd)/max(max(signal)),nFFT));
end
plotting = newSpectrogram(:,1:nFFT/2);
gca,imagesc(plotting');
set(gca,'YLim',[SpectrumYLimMin SpectrumYLimMax]);
end
axesHandles = findobj(gcf,'Type','Axes');
StepofData = handles.StepofData.Value;
set(axesHandles(1:12),'XLim',[0 StepofData]);
if SpectrumScale == 0 && handles.PlottingChoice.Value == 2;
set(axesHandles(1:12),'CLimMode','auto');
handles.SpectrumScale = get(axesHandles(1:12),'CLim');
elseif SpectrumScale ~= 0 && handles.PlottingChoice.Value == 2;
set(axesHandles(1:12),'CLim',[0 SpectrumScale]);
%set(axesHandles(1:12),'CLim',[0 SpectrumScale*handles.SpectrumScale]);
elseif scale == 0 && handles.PlottingChoice.Value == 1;
set(axesHandles(1:12),'CLimMode','auto');
handles.SpectrumScale = get(axesHandles(1:12),'CLim');
else
set(axesHandles(1:12),'CLim',[-scale scale]);
end
%update the channel numbers.
handles.ch1.String = num2str(StartChn+1);
handles.ch2.String = num2str(StartChn+2);
handles.ch3.String = num2str(StartChn+3);
handles.ch4.String = num2str(StartChn+4);
handles.ch5.String = num2str(StartChn+5);
handles.ch6.String = num2str(StartChn+6);
handles.ch7.String = num2str(StartChn+7);
handles.ch8.String = num2str(StartChn+8);
handles.ch9.String = num2str(StartChn+9);
handles.ch10.String = num2str(StartChn+10);
handles.ch11.String = num2str(StartChn+11);
handles.ch12.String = num2str(StartChn+12);
guidata(hObject, handles);
% --- Executes on button press in PlottingChoice.
function PlottingChoice_Callback(hObject, eventdata, handles)
% Hint: get(hObject,'Value') returns toggle state of PlottingChoice
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
% --- Executes on selection change in listChannels.
function listChannels_Callback(hObject, eventdata, handles)
% Hints: contents = cellstr(get(hObject,'String')) returns listChannels contents as cell array
% contents{get(hObject,'Value')} returns selected item from listChannels
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
% --- Executes on slider movement.
function StepofData_Callback(hObject, eventdata, handles)
handles.text7.String = num2str(get(hObject,'Value'));
Plotting_Callback(hObject, eventdata, handles);
% --- Executes on button press in LinkX.
function LinkX_Callback(hObject, eventdata, handles)
axesHandles = [handles.axes1 handles.axes2 handles.axes3 handles.axes4...
handles.axes5 handles.axes6 handles.axes7 handles.axes8...
handles.axes9 handles.axes10 handles.axes11 handles.axes12];
if get(hObject,'Value') == 1
linkaxes(axesHandles,'x');
h = zoom;
h.Motion = 'horizontal';
h = pan;
h.Motion = 'horizontal';
end
% --- Executes on button press in LinkY.
function LinkY_Callback(hObject, eventdata, handles)
axesHandles = [handles.axes1 handles.axes2 handles.axes3 handles.axes4...
handles.axes5 handles.axes6 handles.axes7 handles.axes8...
handles.axes9 handles.axes10 handles.axes11 handles.axes12];
if get(hObject,'Value') == 1
linkaxes(axesHandles,'y');
linkaxes([handles.axes13 handles.axes14],'off');
h = zoom;
h.Motion = 'vertical';
h = pan;
h.Motion = 'vertical';
end
% --- Executes on button press in LinkOff.
function LinkOff_Callback(hObject, eventdata, handles)
axesHandles = [handles.axes1 handles.axes2 handles.axes3 handles.axes4...
handles.axes5 handles.axes6 handles.axes7 handles.axes8...
handles.axes9 handles.axes10 handles.axes11 handles.axes12];
if get(hObject,'Value') == 1
linkaxes(axesHandles,'off');
h = zoom;
h.Motion = 'both';
h = pan;
h.Motion = 'both';
end
% --- Executes on button press in LinkXY.
function LinkXY_Callback(hObject, eventdata, handles)
axesHandles = [handles.axes1 handles.axes2 handles.axes3 handles.axes4...
handles.axes5 handles.axes6 handles.axes7 handles.axes8...
handles.axes9 handles.axes10 handles.axes11 handles.axes12];
if get(hObject,'Value') == 1
h = zoom;
h.Motion = 'both';
h = pan;
h.Motion = 'both';
linkaxes(axesHandles,'xy');
end
function TimeColorScale_Callback(hObject, eventdata, handles)
% hObject handle to TimeColorScale (see GCBO)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function SpectrumColorScale_Callback(hObject, eventdata, handles)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function TimeMin_Callback(hObject, eventdata, handles)
% hObject handle to TimeMin (see GCBO)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function TimeMax_Callback(hObject, eventdata, handles)
% hObject handle to TimeMax (see GCBO)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function SpectrumMin_Callback(hObject, eventdata, handles)
% hObject handle to SpectrumMin (see GCBO)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function SpectrumMax_Callback(hObject, eventdata, handles)
% hObject handle to SpectrumMax (see GCBO)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
% --- Executes on button press in getTime.
function getTime_Callback(hObject, eventdata, handles)
% hObject handle to getTime (see GCBO)
[x,~] = ginput(1);
axesObjs = gca;
dataObjs = axesObjs.Children;
data = dataObjs.CData;
XLim = axesObjs.YLim;
point = round(x);
pointData = data(:,point);
switch handles.PlottingChoice.Value
case 1
figure,plot(pointData);set(gca,'XLim',XLim);title('plot Time');
Position = get(gcf,'Position');Position(3) = 800; Position(4) = 300;
set(gcf,'Position',Position);
case 2
figure,plot(pointData);set(gca,'XLim',XLim);title('plot Spectrum');
Position = get(gcf,'Position');Position(3) = 800; Position(4) = 300;
set(gcf,'Position',Position);
%figure,plot(mag2db(pointData));set(gca,'XLim',XLim);title('plot Spectrum');
%figure,plot(runMean(mag2db(pointData),5)-runMean(mag2db(pointData),200));axis tight; title('plot Spectrum');
ylabel('Magnitude (dB)');
end
function SignalStart_Callback(hObject, eventdata, handles)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
function SignalEnd_Callback(hObject, eventdata, handles)
axesHandles = findobj(gcf,'Type','Axes');
for i = 1:length(axesHandles)
XLim(i,:) = get(axesHandles(i),'XLim');
end
Plotting_Callback(hObject, eventdata, handles);
for i = 1:length(axesHandles)
set(axesHandles(i),'XLim',XLim(i,:));
end
% --- Executes on button press in Normalization.
function Normalization_Callback(hObject, eventdata, handles)
% hObject handle to Normalization (see GCBO)
if isempty(handles.filename)
Testing96D1;
else
BinName = get(handles.FilePath,'String');
FileName = strcat(BinName(1:end-4),'.mat');
load(FileName);
handles.filename = FileName;
end
%% normalize to the main energy envelope.
if isempty(get(handles.ActualMapping,'String'))
trLayout = [1 33 17 29 13 2 49 81 65 77 61 21 25 9 41 5 37 69 73 57 89 53 85 45 93 34 18 30 14 94 50 82 66 78 62 22 26 10 42 6 38 70 74 58 90 54 86 46 3 35 19 31 15 95 51 83 67 79 63 23 27 11 43 7 39 71 75 59 91 55 87 47 4 36 20 32 16 96 52 84 68 80 64 24 28 12 44 8 40 72 76 60 92 56 88 48];
trLayout = 1:96
set(handles.ActualMapping,'String',num2str(trLayout));
else
trLayout = str2num(get(handles.ActualMapping,'String'));
end
SNames = fieldnames(S);
for i = 1:numel(trLayout)
signal = S.(SNames{trLayout(i)});
lengthOfPoints = size(signal,1);
for j = 1:lengthOfPoints
tempSignal = signal(j,:);
maximum = max(tempSignal);
NormSignal(j,:) = tempSignal/maximum; % normalized the signal to have maximum at 1.
end
normalizedS.(SNames{trLayout(i)}) = NormSignal;
end
filename = handles.FilePath.String;
S = normalizedS;
save(strcat(filename(1:end-4),'_Normalized.mat'),'S');
msgbox('Normalization done!');
% --- Executes on button press in PlotSpecEnergy.
function PlotSpecEnergy_Callback(hObject, eventdata, handles)
S = handles.signal;
trLayout = str2num(get(handles.ActualMapping,'String'));
SNames = fieldnames(S);
fftStart = str2double(handles.SignalStart.String);
fftEnd = str2double(handles.SignalEnd.String);
nFFT = 4096;
Fs = 15E6;
freqTolerance = 5; %frequency tolerance in filtering the desired frequency interal, in data points.
materialV = str2num(handles.materialV.String); % sound velocity of the material.
Direction = handles.Direction.Value;
startThickness = str2double(handles.SlicingStart.String);
endThickness = str2double(handles.SlicingEnd.String);
BaseFreqStartThickness = materialV/startThickness; %calculate using thickness equals to half wavelength.
BaseFreqEndThickness = materialV/endThickness;
BaseFreqStartPoints = round((nFFT/2)*BaseFreqStartThickness/Fs); % FFT is double sided.
BaseFreqEndPoints = round((nFFT/2)*BaseFreqEndThickness/Fs); % FFT is double sided.
% nFreqStart = floor((nFFT/2)/BaseFreqStartPoints); % number of harmonics in spectrum of the start thickness.
% nFreqEnd = floor((nFFT/2)/BaseFreqEndPoints); % number of harmonics in spectrum of the end thickness.
WeightFreqStart = BaseFreqStartPoints:BaseFreqStartPoints:nFFT/2;
WeightFreqEnd = BaseFreqEndPoints:BaseFreqEndPoints:nFFT/2;
WeightFreqInterval = [WeightFreqEnd(1:length(WeightFreqStart));WeightFreqStart];
% calculate the energy slicing only for the central frequency band,
% roughly at 200-1400 points (10%-70% of 2048 points).
nStartSlicing = floor(0.1*length(WeightFreqEnd));
nEndSlicing = floor(0.7*length(WeightFreqEnd));
newSpectrogram = zeros(4096,520);
NormalizedSpectrum = zeros(4096,520);
energySlicing = zeros(1,nEndSlicing-nStartSlicing+1);
EnergySlicing = zeros(96,520);
for chn = 1:96
signal = S.(SNames{trLayout(chn)});
for i = 1:size(signal,1)
newSpectrogram(:,i) = abs(fft(signal(i,fftStart:fftEnd),nFFT));
% NormalizedSpectrum(:,i) = preprocessSpectrum(newSpectrogram(:,i));
if ~isequal(handles.CoatThickness.String,'CoatThk')&&~isequal(handles.CoatThickness.String,'0');
NormalizedSpectrum(:,i) = newSpectrogram(:,i);
else
baseline = envelope(newSpectrogram(:,i),120,'rms');
NormalizedSpectrum(:,i) = baseline-newSpectrogram(:,i); % use the teeth rather than peaks.
end
%% slicing spectrum.
for nSlicing = nStartSlicing:nEndSlicing
energySlicing(nSlicing-nStartSlicing+1) = sum(NormalizedSpectrum(WeightFreqInterval(1,nSlicing)-freqTolerance:WeightFreqInterval(2,nSlicing)+freqTolerance,i));
end
EnergySlicing(chn,i) = sum(energySlicing)/sum(NormalizedSpectrum(:,i));
end
EnergySlicing(chn,:) = size(signal,1)*EnergySlicing(chn,:)/sum(EnergySlicing(chn,:)); %normalization.
%figure(111),plot(WeightFreqStart,zeros(length(WeightFreqStart),1)+i,'r*'),hold on;plot(WeightFreqEnd,zeros(length(WeightFreqEnd),1)+i,'bo');axis tight;
end
ToolSpeed = str2double(handles.FlowRate.String)/3.28; % convert from ft/s to m/s.
Aligned = lineupRings(ToolSpeed,EnergySlicing,Direction);
% figure(111);
% imagesc(EnergySlicing,[0.2 1.5]);
% figure(112);
% imagesc(Aligned,[0.2 1.5]);
axes(handles.axes13);
imagesc(Aligned);
handles.SpecEnergyMap = EnergySlicing;
guidata(hObject, handles);
% --- Executes on button press in PlotTimeEnergy.
function PlotTimeEnergy_Callback(hObject, eventdata, handles)
% hObject handle to PlotTimeEnergy (see GCBO)
S = handles.signal;
trLayout = str2num(get(handles.ActualMapping,'String'));
SNames = fieldnames(S);
Direction = handles.Direction.Value;
Fs = 15E6;
materialV = str2double(handles.materialV.String); % sound velocity of the material.
coatingV = str2double(handles.coatingV.String); % sound velocity of the material.
newSignal = zeros(2000,520);
LMax = zeros(96,520);
PulseLength = 20; % length of the first pulse reflection.
startThickness = str2double(handles.SlicingStart.String);
endThickness = str2double(handles.SlicingEnd.String);
RefInterval = round(((startThickness+endThickness)*Fs/materialV)*1); % calculate use the nominal thickness plus 20% tolerance.
energySlicing1 = zeros(1,520);
energySlicing2 = zeros(1,520);
EnergySlicing1 = zeros(96,520);
EnergySlicing2 = zeros(96,520);
if isequal(handles.CoatThickness.String,'CoatThk')
CoatingPoints = 0;
elseif isequal(handles.CoatThickness.String,'0')
CoatingPoints = 0;
else
CoatThickness = str2double(handles.CoatThickness.String);
CoatingPoints = round(CoatThickness*2*Fs/coatingV);
end
for chn = 1:96
Signal = S.(SNames{trLayout(chn)});
for i = 1:520
newSignal(:,i) = abs(Signal(i,:));%.*Signal(i,:);
%NormalizedSignal(:,i) = newSignal(:,i)-runMean(newSignal(:,i),80);
%% slicing spectrum.
Max = max(newSignal(:,i));
LMax(chn,i) = find(newSignal(:,i)>0.6*Max,1); % find the first incline that has 60% of max value.
if LMax(chn,i)<1800
energySlicing1(i) = sum(newSignal(LMax(chn,i)+CoatingPoints+PulseLength:LMax(chn,i)+CoatingPoints+RefInterval-5,i))/sum(newSignal(:,i)); % Energy calculation for in between 1st and 2nd reflections.
if LMax(chn,i) < 1300
energySlicing2(i) = sum(newSignal(LMax(chn,i)+81:LMax(chn,i)+150,i))/sum(newSignal(:,i)); % Energy calculation the next 600 points as resonance.
elseif LMax(chn,i) > 1300 && LMax(chn,i) < 1800
energySlicing2(i) = sum(newSignal(LMax(chn,i)+201:end,i))/sum(newSignal(:,i)); % Energy calculation the next 600 points as resonance.
end
else
msgbox('one signal starts after data points 1800, check data');
return
end
end
EnergySlicing1(chn,:) = 1000*energySlicing1/sum(energySlicing1);
EnergySlicing2(chn,:) = 1000*energySlicing2/sum(energySlicing2);
end
handles.LMax = LMax;
ToolSpeed = str2double(handles.FlowRate.String)/3.28; % convert from ft/s to m/s.
switch handles.TimeSlicingChoice.Value
case 1
Aligned = lineupRings(ToolSpeed,EnergySlicing1,Direction);
axes(handles.axes14);
imagesc(Aligned,[0 4]);
case 2
Aligned = lineupRings(ToolSpeed,EnergySlicing2,Direction);
axes(handles.axes14);
imagesc(Aligned,[0 3.5]);
end
handles.TimeEnergyMap1 = EnergySlicing1;
handles.TimeEnergyMap2 = EnergySlicing2;
guidata(hObject, handles);
% --- Executes on selection change in TimeSlicingChoice.
function TimeSlicingChoice_Callback(hObject, eventdata, handles)
function SlicingStart_Callback(hObject, eventdata, handles)
% hObject handle to SlicingStart (see GCBO)
function SlicingEnd_Callback(hObject, eventdata, handles)
% hObject handle to SlicingEnd (see GCBO)
% --- Executes on button press in SaveEnergyPlot.
function SaveEnergyPlot_Callback(hObject, eventdata, handles)
PathName = handles.pathname;
FileName = handles.filename;
TimeEnergyMap1 = handles.TimeEnergyMap1;
TimeEnergyMap2 = handles.TimeEnergyMap2;
SpecEnergyMap = handles.SpecEnergyMap;
[tok,rem]=strtok(FileName,'.');
mkdir(strcat(PathName,'MapResults'));
save(strcat(PathName,'MapResults\',tok,'_EnergyMap.mat'),'TimeEnergyMap1','TimeEnergyMap2','SpecEnergyMap');
% --- Executes on button press in LoadEneryPlot.
function LoadEneryPlot_Callback(hObject, eventdata, handles)
% --- Executes on button press in StitchMultiple.
function StitchMultiple_Callback(hObject, eventdata, handles)
%%
if isempty(handles.pathname)
[filename,PathName]= uigetfile('*.mat','MultiSelect', 'on');
else
[filename,PathName] = uigetfile([handles.pathname,'*.mat'],'Select the file','MultiSelect', 'on');
end
%[filename,PathName]= uigetfile('*.mat','MultiSelect', 'on');
Direction = handles.Direction.Value;
datapointsPerFile = 520;
toolSpeed = str2double(handles.FlowRate.String)/3.28; % convert from ft/s to m/s.; % tool speed in m/s.
for i = 1:length(filename)
Energymap = load(fullfile(PathName,cell2mat(filename(i))));
TimeEnergyMap1 = Energymap.TimeEnergyMap1;
newTimeEnergyMap1(:,datapointsPerFile*(i-1)+1:datapointsPerFile*i) = TimeEnergyMap1;
TimeEnergyMap2 = Energymap.TimeEnergyMap2;
newTimeEnergyMap2(:,datapointsPerFile*(i-1)+1:datapointsPerFile*i) = TimeEnergyMap2;
SpecEnergyMap = Energymap.SpecEnergyMap;
newSpecEnergyMap(:,datapointsPerFile*(i-1)+1:datapointsPerFile*i) = SpecEnergyMap;
end
AlignedTimeEnergyMap1 = lineupRings(toolSpeed,newTimeEnergyMap1,Direction);
AlignedTimeEnergyMap2 = lineupRings(toolSpeed,newTimeEnergyMap2,Direction);
AlignedSpecEnergyMap = lineupRings(toolSpeed,newSpecEnergyMap,Direction);
%%
pipeDia = 36; % in inches.
physicalWidth= toolSpeed*5*40*length(filename); % in inches, every file is 5 second, 1m = 40 inches.
physicalCircumference = pipeDia*pi; % in inches.
height = 800;
width = round(height*(physicalWidth/physicalCircumference));
figure(4);
set(4,'Name','Harmonics Energy Map','Position',[350 60 width height]);
imagesc(AlignedSpecEnergyMap,[0.2 1.5]);
figure(5);
set(5,'Name','Time Energy Map 1','Position',[350 60 width height]);
imagesc(AlignedTimeEnergyMap1,[0 10]);
figure(6);
set(6,'Name','Time Energy Map 2','Position',[350 60 width height]);
imagesc(AlignedTimeEnergyMap2,[0 3.5]);
save(strcat(PathName,'stitchedEnergyMap.mat'),'newSpecEnergyMap','newTimeEnergyMap1','newTimeEnergyMap2');
savefig(4,strcat(PathName,'stitchedSpecEnergyMap-Aligned.fig'));
savefig(5,strcat(PathName,'stitchedTimeEnergyMap1-Aligned.fig'));
savefig(6,strcat(PathName,'stitchedTimeEnergyMap2-Aligned.fig'));
function FlowRate_Callback(hObject, eventdata, handles)
% --- Executes during object creation, after setting all properties.
function FlowRate_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function Aligned = lineupRings(ToolSpeed,MatrixNeedAlign,Direction)
%% Offset and line up the array
if nargin<2
error('at least two argin is required');
return
elseif nargin<3
Direction = 1;
end
%
transducerPingRate = 104.1667;
% Position offset for each ring (in mm)
posArray = [0, 55.88, 111.76, 27.94, 83.82, 139.7]';
% if scan direction is opposite.
if Direction == 2
posArray = max(posArray)-posArray;
end
% Position offset for each transducer
posOffset = [posArray; posArray; posArray; posArray; ...
posArray; posArray; posArray; posArray; ...
posArray; posArray; posArray; posArray; ...
posArray; posArray; posArray; posArray];
% Convert from mm to meter
posOffset = posOffset/1000;
numberOfSamplesOffsetPrChannel = round((posOffset/ToolSpeed)*transducerPingRate);
RefElementsToAdd = max(numberOfSamplesOffsetPrChannel);
allElementsToAdd = RefElementsToAdd-numberOfSamplesOffsetPrChannel;
tempM = zeros(96,size(MatrixNeedAlign,2)+RefElementsToAdd);
Aligned = tempM;
for index = 1:96
elementsToRemove = numberOfSamplesOffsetPrChannel(index);
elementsToAdd = allElementsToAdd(index);
tempM = MatrixNeedAlign(index,:);
%if(elementsToRemove > 0)
% Remove elements in front
%tempM(1:elementsToRemove) = [];
% Append same amount of zeros to the end
tempM = [zeros(1,elementsToAdd)+median(median(MatrixNeedAlign)) tempM zeros(1,elementsToRemove)+median(median(MatrixNeedAlign))];
%end
Aligned (index,:) = tempM;
end
% --- Executes on button press in updateThickness.
function updateThickness_Callback(hObject, eventdata, handles)
% hObject handle to updateThickness (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
S = handles.signal;
PlottingChoice = get(handles.PlottingChoice,'Value');
LMax = handles.LMax; % if there is saved calculation of first reflection peak.
trLayout = str2num(get(handles.ActualMapping,'String'));
SNames = fieldnames(S);
Fs = 15E6;
materialV = str2double(handles.materialV.String); % sound velocity of the material.
newSignal = zeros(2000,520);
startThickness = str2double(handles.SlicingStart.String);
timeFlight = round(startThickness*2*Fs/materialV);
if isequal(get(handles.CoatThickness,'String'),'CoatThk');
coating = 0;
coatingThickness = 0;
elseif isequal(get(handles.CoatThickness,'String'),'0');
coating = 0;
coatingThickness = 0;
else
coating = 1;
coatingThickness = str2double(get(handles.CoatThickness,'String'));
end
coatingV = str2double(handles.coatingV.String);
%coatingThickness = 0.0024; % 3mm coating for mortar in DI.
coatingFlight = round(coatingThickness*2*Fs/coatingV);
signalEnd = 1400; % where signal ends, for 12"DI there might be a 2nd set of reflections in the 2000 points range.
% button = questdlg('Choose 10 points from the first reference line',...
% 'Point Selection','Yes','No','Yes');
% if button ~= 'Yes'
% return
% msgbox('user cancelled');
% else
% [x1,y1] = ginput(10);
% axes1 = gca;
% end
% button = questdlg('Choose 10 points from the second reference line',...
% 'Point Selection','Yes','No','Yes');
% if button ~= 'Yes'
% return
% msgbox('user cancelled');
% else
% [x2,y2] = ginput(10);
% axes2 = gca;
%
% end
%
% if axes1 ~=axes2;
% msgbox('both lines should be from the same channel');
% return
% else
% Axes = axes1;
% end
%
if isempty(LMax)
LMax = zeros(96,520);
for chn = 1:96
Signal = S.(SNames{trLayout(chn)});
for i = 1:520
newSignal(:,i) = abs(Signal(i,:));%.*Signal(i,:);
%NormalizedSignal(:,i) = newSignal(:,i)-runMean(newSignal(:,i),80);
%% slicing spectrum.
Max = max(newSignal(:,i));
LMax(chn,i) = find(newSignal(:,i)>0.6*Max,1); % find the first incline that has 30% of max value.
end
end
handles.LMax = LMax;
end
axesObjs = gca;
dataObjs = axesObjs.Children;
data = dataObjs.CData;
XLim = axesObjs.YLim;
Direction = handles.Direction.Value; % if scan with opposite direction.
switch PlottingChoice
case 1 % in time domain.
[thickPoints,coatPoints] = Thickness(coating,S,trLayout,timeFlight,coatingFlight,signalEnd); % selecting 0 for coating as no coating, 1 as with coating.
%%
ToolSpeed = str2double(handles.FlowRate.String)/3.28; % convert from ft/s to m/s.; % tool speed in m/s.
AlignedThickPoints = lineupRings(ToolSpeed,thickPoints,Direction);
%%
thickness = thickPoints*materialV/(2*Fs);
figure(3),imagesc(thickness,[0.008 0.012]);
AlignedThickness = lineupRings(ToolSpeed,thickness,Direction);
figure(4),imagesc(AlignedThickness,[0.008 0.012]);
%%
gca;hold on;
plot(x1,y1,'ro');plot(x2,y2,'go');
p1 = spline(x1,y1);p2 = spline(x2,y2);
Xmin1 = round(min(x1));Xmin2 = round(min(x2));
Xmax1 = round(max(x1));Xmax2 = round(max(x2));
X1 = linspace(Xmin1,Xmax1,Xmax1-Xmin1+1);
f1 = ppval(p1,X1);
X2 = linspace(Xmin2,Xmax2,Xmax2-Xmin2+1);
f2 = ppval(p2,X2);
gca;hold on;plot(X1,f1,'r');plot(X1,f1,'g');
%%
case 2 % in frequency domain.
end
guidata(hObject, handles);
% --- Executes on button press in saveThickness.
function saveThickness_Callback(hObject, eventdata, handles)
% hObject handle to saveThickness (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in PCA.
function PCA_Callback(hObject, eventdata, handles)
%% -------------------- preparation of plotting -----------------------
if isempty(handles.figure2) || ~ishandle(handles.figure2)
handles.figure2 = figure;
%handles.metricdata.figure2 = handles.figure2;
set(handles.figure2,'Position',[10 50 1400 800],'Name','Data Plotting','Units','Points',...
'NumberTitle','off',... % clip of figure number.
'WindowButtonDownFcn',@figure2_WindowButtonDownFcn,...
'WindowButtonUpFcn',@figure2_WindowButtonUpFcn,...
'WindowScrollWheelFcn',@figure2_WindowScrollWheelFcn);
handles.lbutton = uicontrol('Parent',handles.figure2,...
'Units','normalized',...
'Position',[0.02 0.94 0.05 0.05],...
'Style','pushbutton',...
'String','load Map',...
'Callback','loadMap');
handles.lbutton = uicontrol('Parent',handles.figure2,...
'Units','normalized',...
'Position',[0.07 0.94 0.05 0.05],...
'Style','pushbutton',...
'String','load Marker',...
'Callback','loadMarker');
handles.lbutton = uicontrol('Parent',handles.figure2,...
'Units','normalized',...
'Position',[0.02 0.02 0.05 0.05],...
'Style','pushbutton',...
'String','save Marker',...
'Callback','saveMarker');
end
%% draw uilines on figure 2.
% set up axes 1.
if isempty(handles.metricdata.h1) || ~ishandle(handles.metricdata.h1)||isempty(handles.metricdata.h2) || ~ishandle(handles.metricdata.h2)
h1 = axes('Parent',handles.figure2,...
'Units','normalized','Position',[0.045 0.12 0.92 0.8],...
'Color',[1 1 1],'FontName','Arial','FontSize',8, ...
'Tag','OriAxis',...
'XColor',[0 0 0],'YColor',[0 0 0],'ZColor',[0 0 0],...
'XLim',[0 1],'YLim',[0 1]);
title(h1,'Amplitude','FontName','Arial');
ylabel(h1,'Normalized amp','FontName','Arial');
set(h1, 'XLim',[min(XData) max(XData)],'YLim',[0.5 1.5]);
handles.metricdata.h1 = h1;
% set up axes 2.
h2 = axes('Parent',handles.figure2,...
'Units','normalized','Position',[0.0466 0.0584 0.919 0.429],...
'Color',[1 1 1],'FontName','Arial','FontSize',8, ...
'Tag','SmoAxis',...
'XColor',[0 0 0],'YColor',[0 0 0],'ZColor',[0 0 0],...
'XLim',[0 1],'YLim',[0.5 1.5]);
namedisplay = strcat('Path: ',handles.metricdata.path,' Name:',handles.metricdata.name(1,:));
title(h2,namedisplay,'FontName','Arial');
xlabel(h2,'Phase','FontName','Arial');
ylabel(h2,'Normalized phase','FontName','Arial');
set(h2, 'XLim',[min(XData) max(XData)],'YLim',[0.5 1.5]);
handles.metricdata.h2 = h2;
else
% load data directly from storage.
h1 = handles.metricdata.h1;
h2 = handles.metricdata.h2;
end
%%
% --- Executes on button press in Debug.
function Debug_Callback(hObject, eventdata, handles)
% hObject handle to Debug (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
keyboard
|
github
|
ganlubbq/Signal-Processing-master
|
hydrophoneDataProcessLinear.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/hydrophoneDataProcessLinear.m
| 5,486 |
utf_8
|
9c3667e31b0474394c570aece3a8b5a3
|
function [ psdArray, fVector, distanceArray, meanArray ] = processHydrophoneDataLinear( FFT_LENGTH, fileName )
import ppPkg.*
im = ImportHandler;
% Import data file
header = im.readHeader(fileName);
tmArr = im.importDataFile();
% Init variables
psdArray = zeros(length(tmArr), FFT_LENGTH/2 + 1);
distanceArrayTemp = zeros(1, length(tmArr));
% Create tx pulse
txPulse = generatePulse(header.pulsePattern, header.sampleRate, header.pulseLength, header.fLow, header.fHigh );
enablePeak2PeakCalc = 1;
for index = 1:length(tmArr)
tm = tmArr(index);
recordedSignal = tm.signal;
%plot(recordedSignal)
%y = smooth(recordedSignal, 4);
%hold on
%plot(y)
%grid on
if(enablePeak2PeakCalc )
% Find start of emitted pulse in recording
[distance, startIndexPulse] = findStartIndexPulse(txPulse, recordedSignal);
% Extract signal segment to do FFT etc
signalSegment = recordedSignal(startIndexPulse:startIndexPulse+header.pulseLength);
% Calculate periodogram
[psdPulse, fVector] = periodogram(signalSegment, rectwin(length(signalSegment)), FFT_LENGTH, header.sampleRate,'psd');
psdArray(index, : ) = psdPulse;
distanceArrayTemp(index) = distance;
% Calculate minimum peak distance
peakDistance = round(2/3 * header.sampleRate / header.fLow);
% Calculate 6 max and min peaks for signal
[maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance);
% Sum max and min to calculate "peak2peak" value
peak2peakArray = maxPeaks - minPeaks;
% Calculate mean
meanArray(index) = mean(peak2peakArray);
end
end
distanceArray = distanceArrayTemp;
end
function y = smooth(x, N)
b = (1/N)*ones(1, N);
a = 1;
y = filtfilt(b, a, x);
end
function [txPulse, tPulse] = generatePulse(pattern, sampleRate, pulseLength, fLow, fHigh)
import ppPkg.*
switch lower(pattern)
case 'simple'
[txPulse, tPulse] = generateSin(sampleRate, pulseLength, fLow);
case 'chirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
case 'rectchirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
txPulse = sign(txPulse);
case 'sinc'
[txPulse, tPulse] = generateSinc(sampleRate, pulseLength, fLow, fHigh);
case 'rectpulse'
[txPulse, tPulse] = generateRectPulseTrain(sampleRate, pulseLength, fLow, fHigh);
txPulse = flip(txPulse)
otherwise
error('Signal pattern not supported')
end
end
function [distance, startIndexPulse] = findStartIndexPulse(txPulse, signal)
% Function use correlation between emitted pulse and recorded signal to find
% startIndex for pulse in recorded signal
import ppPkg.*
ctrl = Controller;
callipAlg = CalliperAlgorithm(ctrl.config);
% Calculate Calliper
% Set transmitted pulse
callipAlg.setTxPulse(txPulse);
% Start searching at index 0
delay = 0;
%% Calculate startIndex for pulse in recording
[distance, startIndexPulse] = callipAlg.calculateDistance( delay, signal, 0);
% Need to double distance since this is calculated as it should have
% been reflected
distance = distance * 2;
end
function plotFrequency(step, psdArray, distanceArray, FFT_LENGTH)
f = 0:0.5e6:4e6;
N = round( f*FFT_LENGTH/15e6);
N(1) = 1;
for index = 1:length(N)
figure
plot(distanceArray, psdArray(:,N(index)))
grid on
msg = sprintf('Frequency vs distance plot, for f=%d', f(index));
title(msg);
xlabel('distance')
ylabel('Frequency gain')
end
end
function [maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance)
interpFactor = 10;
peakDistanceModified = peakDistance * interpFactor;
signalSegment_interp = interp(signalSegment,interpFactor);
[pksMax, locsMax] = findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
[pksMin, locsMin] = findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
% Only keep peaks 3 to 8
if((length(pksMax) >= 15) && (length(pksMin) >= 15))
maxPeaks = pksMax(10:15);
minPeaks = -pksMin(10:15);
locsMax = locsMax(10:15);
locsMin = locsMin(10:15);
elseif(length(pksMax) > 2)
error('Error Should find more than 17 peaks')
lengthMax = length(pksMax);
lengthMin = length(pksMin);
if(lengthMax > lengthMin)
maxLength = lengthMin;
else
maxLength = lengthMax;
end
maxPeaks = pksMax(1:maxLength);
minPeaks = -pksMin(1:maxLength);
locsMax = locsMax(1:maxLength);
locsMin = locsMin(1:maxLength);
else
error('Error in finding peaks')
end
end
|
github
|
ganlubbq/Signal-Processing-master
|
hanning.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/hanning.m
| 2,240 |
utf_8
|
e50c3a9e967b4ad6289daa0583051b6b
|
function w = hanning(varargin)
%HANNING Hanning window.
% HANNING(N) returns the N-point symmetric Hanning window in a column
% vector. Note that the first and last zero-weighted window samples
% are not included.
%
% HANNING(N,'symmetric') returns the same result as HANNING(N).
%
% HANNING(N,'periodic') returns the N-point periodic Hanning window,
% and includes the first zero-weighted window sample.
%
% NOTE: Use the HANN function to get a Hanning window which has the
% first and last zero-weighted samples.
%
% See also BARTLETT, BLACKMAN, BOXCAR, CHEBWIN, HAMMING, HANN, KAISER
% and TRIANG.
% Copyright 1988-2004 The MathWorks, Inc.
% Check number of inputs
narginchk(1,2);
% Check for trivial order
[n,w,trivialwin] = check_order(varargin{1});
if trivialwin, return, end
% Select the sampling option
if nargin == 1,
sflag = 'symmetric';
else
sflag = lower(varargin{2});
end
% Allow partial strings for sampling options
allsflags = {'symmetric','periodic'};
sflagindex = find(strncmp(sflag, allsflags, length(sflag)));
if length(sflagindex)~=1 % catch 0 or 2 matches
error(message('signal:hanning:InvalidEnum'));
end
sflag = allsflags{sflagindex};
% Evaluate the window
switch sflag,
case 'periodic'
% Includes the first zero sample
w = [0; sym_hanning(n-1)];
case 'symmetric'
% Does not include the first and last zero sample
w = sym_hanning(n);
end
%---------------------------------------------------------------------
function w = sym_hanning(n)
%SYM_HANNING Symmetric Hanning window.
% SYM_HANNING Returns an exactly symmetric N point window by evaluating
% the first half and then flipping the same samples over the other half.
if ~rem(n,2)
% Even length window
half = n/2;
w = calc_hanning(half,n);
w = [w; w(end:-1:1)];
else
% Odd length window
half = (n+1)/2;
w = calc_hanning(half,n);
w = [w; w(end-1:-1:1)];
end
%---------------------------------------------------------------------
function w = calc_hanning(m,n)
%CALC_HANNING Calculates Hanning window samples.
% CALC_HANNING Calculates and returns the first M points of an N point
% Hanning window.
w = .5*(1 - cos(2*pi*(1:m)'/(n+1)));
% [EOF] hanning.m
|
github
|
ganlubbq/Signal-Processing-master
|
pulseTest.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/pulseTest.m
| 8,219 |
utf_8
|
df4650e4966086aaa576800aac218103
|
function res = pulseTest(ctrl, folder, folderToSaveFig)
% Read folder
% Get all subfolder names
% Do a regex
% Keep the ones that matches the regex
listing = dir(folder);
%folderNames;
[pathstr,name,ext] = fileparts(folder);
folderIndex = 1;
for index = 1:size(listing,1)
temp = regexp(listing(index).name,'CIP_.*','match');
if(~isempty(temp))
dataFolders(folderIndex) = cellstr(listing(index).name);
folderIndex = folderIndex + 1;
end
end
folderFirstPart = strcat(listing(1).folder,'\');
% Initialize struct
res(numel(dataFolders)) = struct('medianNoise',0,...
'meanNoise',0,...
'medianDbAboveNoise',0,...
'meanDbAboveNoise',0,...
'thickness',0,...
'averageF0',0,...
'snr',0,...
'psdF',0,...
'psdMain', 0,...
'psdResonance', 0,...
'dataHeader','',...
'title','');
% Get path to all header files in dataFolders
for indexN = 1:numel(dataFolders)
folderPath = char(dataFolders(indexN));
folderPath = strcat(folderFirstPart, folderPath);
folderPath = strcat(folderPath,'\');
% Get content of folderPath
listingFolder = dir(char(folderPath));
% Iterate through the files in the folder
for indexM = 1:size(listingFolder,1)
% Get the file that contains 'header' and extract information
% from the file name
temp = regexp(listingFolder(indexM).name,'.*header','match');
if(~isempty(temp))
% Get Transducer info
% token1 = regexp(listingFolder(indexM).name,'.*(CHIRP_\d\d_\d\d\d).*','tokens');
% res(indexN).transducer = char(token1{1});
% Get Title txt
token2 = regexp(listingFolder(indexM).name,'(.*)_[0-9]+_[0-9]+_header','tokens');
%strrep(res.transducer, '_', ' ');
%res(indexN).title = char(token2{1});
res(indexN).title = strrep(char(token2{1}), '_', ' ');
%strrep(char(token2{1}), '_', ' ')
% Get path to data file header
fileName = listingFolder(indexM).name;
res(indexN).dataHeader = strcat(folderPath, fileName);
end
end
end
% Iterate through struct array to process data from each transducer
for index = 1:numel(res)
% Process data
index
res(index) = processData(ctrl, res(index), folderToSaveFig);
% Plot PSD main with psd compare
%plotPsdMain(ctrl, res(index), psdCompare, folderToSaveFig);
%plotPsdResonance(ctrl, res(index), folderToSaveFig);
%res(index);
%pause()
close all
end
end
function res = processData(ctrl, res, folderToSaveFig)
import ppPkg.*
im = ImportHandler;
im.readHeader(res.dataHeader);
s = SignalGenerator(lower(im.header.pulsePattern), ...
im.header.sampleRate, ...
im.header.pulseLength/im.header.sampleRate, ...
im.header.fLow, ...
im.header.fHigh);
txPulse = s.signal;
%plot(s.time, s.signal)
%grid on
ctrl.config.SAMPLE_RATE = im.header.sampleRate;
im.dataFileIndex = 1;
tmArr = im.importDataFile();
index = 1;
tm = tmArr(index);
ctrl.callipAlg.setTxPulse(txPulse);
delay = 1000; % Start searching at index
%
% Calculate time in number of samples before recording is started
[distance, firstReflectionStartIndex, secondReflectionStartIndex, pitDept] = ctrl.callipAlg.calculateDistance( delay, tm.signal, tm.startTimeRec);
%ctrl.callipAlg
%
% Second reflection is in this data
%callipAlg.secondReflectionIndex = 2000;
if(distance < 0)
error('Outside pipe')
return
end
%% Noise signal
noiseSignal = tm.signal(1000:firstReflectionStartIndex-20);
%
% Enable / Disable use of transducer sensitivity
enableTS = false;
enableTS_noise = false;
transducerId = 1;
% Noise PSD calculation: Using pWelch or periodogram
[psdNoise, fNoise] = ctrl.noiseAlg.calculatePsd(tm.transducerId, noiseSignal, enableTS_noise, 'periodogram', 'hanning', 400);
% Calculate mean and var for range [fLow, fHigh]
[meanValue, varValue] = ctrl.noiseAlg.calculateMeanVarInRange(tm.transducerId, im.header.fLow , im.header.fHigh);
% Plot Noise PSD
% fig = ctrl.noiseAlg.plotPsd(tm.transducerId);
% titleTxt = sprintf('Noise psd tr %d mean: %0.1f dB var: %0.1f dB ',tm.transducerId, round(meanValue,1), round(varValue,1));
% title(titleTxt);
% ylim([-160 -100]);
%% Calculate psdMain and psdResonance
ctrl.thicknessAlg.fLow = tm.fLow;
ctrl.thicknessAlg.fHigh = tm.fHigh;
if(false == ctrl.thicknessAlg.calculateStartStopForAbsorptionAndResonance(tm.signal, ctrl.callipAlg))
error('Error in calculating start and stop index for resonance')
end
% Calculate PSD for resonance and absoption part of the signal
ctrl.thicknessAlg.calculatePsd(tm.signal);
% Plot PSD for resonance and absoption part of the signal
%ctrl.thicknessAlg.plotPsd(tm.signal);
res.psdResonance = ctrl.thicknessAlg.psdResonance;
res.psdMain = ctrl.thicknessAlg.psdMain;
res.psdF = ctrl.thicknessAlg.fVector;
res.snr = ctrl.thicknessAlg.calculateSNR(tm.signal, noiseSignal);
ctrl.thicknessAlg.meanNoiseFloor = meanValue;%noiseAlg.meanPsd(1);
% Override frequency range by setting fLow or fHigh.
fLow = tm.fLow; %tm.fLow;
fHigh = tm.fHigh + ctrl.config.DELTA_FREQUENCY_RANGE; %tm.fHigh;
%ctrl.config.Q_DB_ABOVE_NOISE = 10;
%ctrl.config.Q_DB_MAX = 10;
%ctrl.config.PROMINENCE = 8;
%tic
% Find peaks
ctrl.thicknessAlg.findPeaksInPsd(ctrl.thicknessAlg.RESONANCE, fLow, fHigh, PeakMethod.MIN_PEAK_PROMINENCE_AND_MIN_DB_ABOVE_NOISE);
%toc
%
% Plot peaks
%ctrl.thicknessAlg.plotPsdPeaks(ctrl.thicknessAlg.RESONANCE);
ctrl.config.DEVIATION_FACTOR = (ctrl.config.FFT_LENGTH/ctrl.config.SAMPLE_RATE) * (ctrl.config.SAMPLE_RATE/ctrl.config.PERIODOGRAM_SEGMENT_LENGTH) * 1.5;
requiredNumberOfHarmonicsInSet = 2;
% Find sets
ctrl.thicknessAlg.findFrequencySets(ctrl.thicknessAlg.RESONANCE, fLow, fHigh, requiredNumberOfHarmonicsInSet);
%set = ctrl.thicknessAlg.setResonance
%% Find resonance sets
ctrl.thicknessAlg.processSets(ctrl.thicknessAlg.RESONANCE, ctrl.noiseAlg.psd(transducerId)) ;
%set = ctrl.thicknessAlg.setResonance
[setC] = ctrl.thicknessAlg.findBestSetE(ctrl.thicknessAlg.setResonance);
res.averageF0 = ctrl.thicknessAlg.setResonance(setC).averageFreqDiff;
res.thickness = ctrl.thicknessAlg.setResonance(setC).thickness;
% Plot the set candidate
close all
ctrl.thicknessAlg.plotAllSets('resonance', setC)
titleTxtPart = strrep(im.header.projectId, '_', ' ');
%filenameFig = strcat('Psd_Resonance_', res.title);
titleTxt = sprintf('Resonance PSD, \"%s\" segL %d', titleTxtPart, ctrl.config.PERIODOGRAM_SEGMENT_LENGTH);
%titleTxt = sprintf('Resonance PSD, %s F %2.2d %2.2e Hz, t: %1.2e s', im.header.pulsePattern, im.header.fLow, im.header.fHigh, im.header.pulseLength/im.header.sampleRate);
title(titleTxt)
filenameFig = strcat(im.header.projectId,'_psd_resonance');
saveFigPath = strcat(folderToSaveFig,filenameFig);
fig = gcf;
savefig(fig, saveFigPath)
end
|
github
|
ganlubbq/Signal-Processing-master
|
RegularizeData3D.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/RegularizeData3D.m
| 40,572 |
utf_8
|
4c8d0f722d7d1c70c2d58fb1cf81d48b
|
function [zgrid,xgrid,ygrid] = RegularizeData3D(x,y,z,xnodes,ynodes,varargin)
% RegularizeData3D: Produces a smooth 3D surface from scattered input data.
%
% RegularizeData3D is a modified version of GridFit from the Matlab File Exchange.
% RegularizeData3D does essentially the same thing, but is an attempt to overcome several
% shortcomings inherent in the design of the legacy code in GridFit.
%
% * GridFit lacks cubic interpolation capabilities.
% Interpolation is necessary to map the scattered input data to locations on the output
% surface. The output surface is most likely nonlinear, so linear interpolation used in
% GridFit is a lousy approximation. Cubic interpolation accounts for surface curvature,
% which is especially beneficial when the output grid is coarse in x and y.
%
% * GridFit's "smoothness" parameter was poorly defined and its methodology may have led to bad output data.
% In RegularizeData3D the smoothness parameter is actually the ratio of smoothness (flatness) to
% fidelity (goodness of fit) and is not affected by the resolution of the output grid.
% Smoothness = 100 gives 100 times as much weight to smoothness (and produces a nearly flat output
% surface)
% Smoothness = 1 gives equal weight to smoothness and fidelity (and results in noticeable smoothing)
% Smoothness = 0.01 gives 100 times as much weight to fitting the surface to the scattered input data (and
% results in very little smoothing)
% Smoothness = 0.001 is good for data with low noise. The input points nearly coincide with the output
% surface.
%
% * GridFit didn't do a good job explaining what math it was doing; it just gave usage examples.
%
% For a detailed explanation of "the math behind the magic" on a 3D dataset, see:
% http://mathformeremortals.wordpress.com/2013/07/22/introduction-to-regularizing-3d-data-part-1-of-2/
%
% and to apply the same principles to a 2D dataset see:
% http://mathformeremortals.wordpress.com/2013/01/29/introduction-to-regularizing-with-2d-data-part-1-of-3/
%
% Both of these links include Excel spreadsheets that break down the calculations step by step
% so that you can see how RegularizeData3D works. There are also very limited (and very slow!) Excel
% spreadsheet functions that do the same thing in 2D or 3D.
%
%
% Aside from the above changes, most of the GridFit code is left intact.
% The original GridFit page is:
% http://www.mathworks.com/matlabcentral/fileexchange/8998-surface-fitting-using-gridfit
% usage #1: zgrid = RegularizeData3D(x, y, z, xnodes, ynodes);
% usage #2: [zgrid, xgrid, ygrid] = RegularizeData3D(x, y, z, xnodes, ynodes);
% usage #3: zgrid = RegularizeData3D(x, y, z, xnodes, ynodes, prop, val, prop, val,...);
%
% Arguments: (input)
% x,y,z - vectors of equal lengths, containing arbitrary scattered data
% The only constraint on x and y is they cannot ALL fall on a
% single line in the x-y plane. Replicate points will be treated
% in a least squares sense.
%
% ANY points containing a NaN are ignored in the estimation
%
% xnodes - vector defining the nodes in the grid in the independent
% variable (x). xnodes need not be equally spaced. xnodes
% must completely span the data. If they do not, then the
% 'extend' property is applied, adjusting the first and last
% nodes to be extended as necessary. See below for a complete
% description of the 'extend' property.
%
% If xnodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% ynodes - vector defining the nodes in the grid in the independent
% variable (y). ynodes need not be equally spaced.
%
% If ynodes is a scalar integer, then it specifies the number
% of equally spaced nodes between the min and max of the data.
%
% Also see the extend property.
%
% Additional arguments follow in the form of property/value pairs.
% Valid properties are:
% 'smoothness', 'interp', 'solver', 'maxiter'
% 'extend', 'tilesize', 'overlap'
%
% Any UNAMBIGUOUS shortening (even down to a single letter) is
% valid for property names. All properties have default values,
% chosen (I hope) to give a reasonable result out of the box.
%
% 'smoothness' - scalar or vector of length 2 - the ratio of
% smoothness to fidelity of the output surface. This must be a
% positive real number.
%
% A smoothness of 1 gives equal weight to fidelity (goodness of fit)
% and smoothness of the output surface. This results in noticeable
% smoothing. If your input data x,y,z have little or no noise, use
% 0.01 to give smoothness 1% as much weight as goodness of fit.
% 0.1 applies a little bit of smoothing to the output surface.
%
% If this parameter is a vector of length 2, then it defines
% the relative smoothing to be associated with the x and y
% variables. This allows the user to apply a different amount
% of smoothing in the x dimension compared to the y dimension.
%
% DEFAULT: 0.01
%
%
% 'interp' - character, denotes the interpolation scheme used
% to interpolate the data.
%
% DEFAULT: 'triangle'
%
% 'bicubic' - use bicubic interpolation within the grid
% This is the most accurate because it accounts
% for the fact that the output surface is not flat.
% In some cases it may be slower than the other methods.
%
% 'bilinear' - use bilinear interpolation within the grid
%
% 'triangle' - split each cell in the grid into a triangle,
% then apply linear interpolation inside each triangle
%
% 'nearest' - nearest neighbor interpolation. This will
% rarely be a good choice, but I included it
% as an option for completeness.
%
%
% 'solver' - character flag - denotes the solver used for the
% resulting linear system. Different solvers will have
% different solution times depending upon the specific
% problem to be solved. Up to a certain size grid, the
% direct \ solver will often be speedy, until memory
% swaps causes problems.
%
% What solver should you use? Problems with a significant
% amount of extrapolation should avoid lsqr. \ may be
% best numerically for small smoothnesss parameters and
% high extents of extrapolation.
%
% Large numbers of points will slow down the direct
% \, but when applied to the normal equations, \ can be
% quite fast. Since the equations generated by these
% methods will tend to be well conditioned, the normal
% equations are not a bad choice of method to use. Beware
% when a small smoothing parameter is used, since this will
% make the equations less well conditioned.
%
% DEFAULT: 'normal'
%
% '\' - uses matlab's backslash operator to solve the sparse
% system. 'backslash' is an alternate name.
%
% 'symmlq' - uses matlab's iterative symmlq solver
%
% 'lsqr' - uses matlab's iterative lsqr solver
%
% 'normal' - uses \ to solve the normal equations.
%
%
% 'maxiter' - only applies to iterative solvers - defines the
% maximum number of iterations for an iterative solver
%
% DEFAULT: min(10000,length(xnodes)*length(ynodes))
%
%
% 'extend' - character flag - controls whether the first and last
% nodes in each dimension are allowed to be adjusted to
% bound the data, and whether the user will be warned if
% this was deemed necessary to happen.
%
% DEFAULT: 'warning'
%
% 'warning' - Adjust the first and/or last node in
% x or y if the nodes do not FULLY contain
% the data. Issue a warning message to this
% effect, telling the amount of adjustment
% applied.
%
% 'never' - Issue an error message when the nodes do
% not absolutely contain the data.
%
% 'always' - automatically adjust the first and last
% nodes in each dimension if necessary.
% No warning is given when this option is set.
%
%
% 'tilesize' - grids which are simply too large to solve for
% in one single estimation step can be built as a set
% of tiles. For example, a 1000x1000 grid will require
% the estimation of 1e6 unknowns. This is likely to
% require more memory (and time) than you have available.
% But if your data is dense enough, then you can model
% it locally using smaller tiles of the grid.
%
% My recommendation for a reasonable tilesize is
% roughly 100 to 200. Tiles of this size take only
% a few seconds to solve normally, so the entire grid
% can be modeled in a finite amount of time. The minimum
% tilesize can never be less than 3, although even this
% size tile is so small as to be ridiculous.
%
% If your data is so sparse than some tiles contain
% insufficient data to model, then those tiles will
% be left as NaNs.
%
% DEFAULT: inf
%
%
% 'overlap' - Tiles in a grid have some overlap, so they
% can minimize any problems along the edge of a tile.
% In this overlapped region, the grid is built using a
% bi-linear combination of the overlapping tiles.
%
% The overlap is specified as a fraction of the tile
% size, so an overlap of 0.20 means there will be a 20%
% overlap of successive tiles. I do allow a zero overlap,
% but it must be no more than 1/2.
%
% 0 <= overlap <= 0.5
%
% Overlap is ignored if the tilesize is greater than the
% number of nodes in both directions.
%
% DEFAULT: 0.20
%
%
% Arguments: (output)
% zgrid - (nx,ny) array containing the fitted surface
%
% xgrid, ygrid - as returned by meshgrid(xnodes,ynodes)
%
%
% Speed considerations:
% Remember that gridfit must solve a LARGE system of linear
% equations. There will be as many unknowns as the total
% number of nodes in the final lattice. While these equations
% may be sparse, solving a system of 10000 equations may take
% a second or so. Very large problems may benefit from the
% iterative solvers or from tiling.
%
%
% Example usage:
%
% x = rand(100,1);
% y = rand(100,1);
% z = exp(x+2*y);
% xnodes = 0:.1:1;
% ynodes = 0:.1:1;
%
% g = RegularizeData3D(x,y,z,xnodes,ynodes);
%
% Note: this is equivalent to the following call:
%
% g = RegularizeData3D(x,y,z,xnodes,ynodes, ...
% 'smooth',1, ...
% 'interp','triangle', ...
% 'solver','normal', ...
% 'gradient', ...
% 'extend','warning', ...
% 'tilesize',inf);
%
%
% Rereleased with improvements as RegularizeData3D
% 2014
% - Added bicubic interpolation
% - Fixed a bug that caused smoothness to depend on grid fidelity
% - Removed the "regularizer" setting and documented the calculation process
% Original Version:
% Author: John D'Errico
% e-mail address: [email protected]
% Release: 2.0
% Release date: 5/23/06
% set defaults
% The default smoothness is 0.01. i.e. assume the input data x,y,z
% have little or no noise. This is different from the legacy code,
% which used a default of 1.
params.smoothness = 0.01;
params.interp = 'triangle';
params.solver = 'backslash';
params.maxiter = [];
params.extend = 'warning';
params.tilesize = inf;
params.overlap = 0.20;
params.mask = [];
% was the params struct supplied?
if ~isempty(varargin)
if isstruct(varargin{1})
% params is only supplied if its a call from tiled_gridfit
params = varargin{1};
if length(varargin)>1
% check for any overrides
params = parse_pv_pairs(params,varargin{2:end});
end
else
% check for any overrides of the defaults
params = parse_pv_pairs(params,varargin);
end
end
% check the parameters for acceptability
params = check_params(params);
% ensure all of x,y,z,xnodes,ynodes are column vectors,
% also drop any NaN data
x=x(:);
y=y(:);
z=z(:);
k = isnan(x) | isnan(y) | isnan(z);
if any(k)
x(k)=[];
y(k)=[];
z(k)=[];
end
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
% did they supply a scalar for the nodes?
if length(xnodes)==1
xnodes = linspace(xmin,xmax,xnodes)';
xnodes(end) = xmax; % make sure it hits the max
end
if length(ynodes)==1
ynodes = linspace(ymin,ymax,ynodes)';
ynodes(end) = ymax; % make sure it hits the max
end
xnodes=xnodes(:);
ynodes=ynodes(:);
dx = diff(xnodes);
dy = diff(ynodes);
nx = length(xnodes);
ny = length(ynodes);
ngrid = nx*ny;
% check to see if any tiling is necessary
if (params.tilesize < max(nx,ny))
% split it into smaller tiles. compute zgrid and ygrid
% at the very end if requested
zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params);
else
% its a single tile.
% mask must be either an empty array, or a boolean
% aray of the same size as the final grid.
nmask = size(params.mask);
if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny))
if ((nmask(2)==ny) || (nmask(1)==nx))
error 'Mask array is probably transposed from proper orientation.'
else
error 'Mask array must be the same size as the final grid.'
end
end
if ~isempty(params.mask)
params.maskflag = 1;
else
params.maskflag = 0;
end
% default for maxiter?
if isempty(params.maxiter)
params.maxiter = min(10000,nx*ny);
end
% check lengths of the data
n = length(x);
if (length(y)~=n) || (length(z)~=n)
error 'Data vectors are incompatible in size.'
end
if n<3
error 'Insufficient data for surface estimation.'
end
% verify the nodes are distinct
if any(diff(xnodes)<=0) || any(diff(ynodes)<=0)
error 'xnodes and ynodes must be monotone increasing'
end
% Are there enough output points to form a surface?
% Bicubic interpolation requires a 4x4 output grid. Other types require a 3x3 output grid.
if strcmp(params.interp, 'bicubic')
MinAxisLength = 4;
else
MinAxisLength = 3;
end
if length(xnodes) < MinAxisLength
error(['The output grid''s x axis must have at least ', num2str(MinAxisLength), ' nodes.']);
end
if length(ynodes) < MinAxisLength
error(['The output grid''s y axis must have at least ', num2str(MinAxisLength), ' nodes.']);
end
clear MinAxisLength;
% do we need to tweak the first or last node in x or y?
if xmin<xnodes(1)
switch params.extend
case 'always'
xnodes(1) = xmin;
case 'warning'
warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)])
xnodes(1) = xmin;
case 'never'
error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)])
end
end
if xmax>xnodes(end)
switch params.extend
case 'always'
xnodes(end) = xmax;
case 'warning'
warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)])
xnodes(end) = xmax;
case 'never'
error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))])
end
end
if ymin<ynodes(1)
switch params.extend
case 'always'
ynodes(1) = ymin;
case 'warning'
warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)])
ynodes(1) = ymin;
case 'never'
error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)])
end
end
if ymax>ynodes(end)
switch params.extend
case 'always'
ynodes(end) = ymax;
case 'warning'
warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)])
ynodes(end) = ymax;
case 'never'
error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))])
end
end
% determine which cell in the array each point lies in
[~, indx] = histc(x,xnodes);
[~, indy] = histc(y,ynodes);
% any point falling at the last node is taken to be
% inside the last cell in x or y.
k=(indx==nx);
indx(k)=indx(k)-1;
k=(indy==ny);
indy(k)=indy(k)-1;
ind = indy + ny*(indx-1);
% Do we have a mask to apply?
if params.maskflag
% if we do, then we need to ensure that every
% cell with at least one data point also has at
% least all of its corners unmasked.
params.mask(ind) = 1;
params.mask(ind+1) = 1;
params.mask(ind+ny) = 1;
params.mask(ind+ny+1) = 1;
end
% interpolation equations for each point
tx = min(1,max(0,(x - xnodes(indx))./dx(indx)));
ty = min(1,max(0,(y - ynodes(indy))./dy(indy)));
% Future enhancement: add cubic interpolant
switch params.interp
case 'triangle'
% linear interpolation inside each triangle
k = (tx > ty);
L = ones(n,1);
L(k) = ny;
t1 = min(tx,ty);
t2 = max(tx,ty);
A = sparse(repmat((1:n)', 1, 3), [ind, ind + ny + 1, ind + L], [1 - t2, t1, t2 - t1], n, ngrid);
case 'nearest'
% nearest neighbor interpolation in a cell
k = round(1-ty) + round(1-tx)*ny;
A = sparse((1:n)',ind+k,ones(n,1),n,ngrid);
case 'bilinear'
% bilinear interpolation in a cell
A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ...
[(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ...
n,ngrid);
case 'bicubic'
% Legacy code calculated the starting index ind for bilinear interpolation, but for bicubic interpolation we need to be further away by one
% row and one column (but not off the grid). Bicubic interpolation involves a 4x4 grid of coefficients, and we want x,y to be right
% in the middle of that 4x4 grid if possible. Use min and max to ensure we won't exceed matrix dimensions.
% The sparse matrix format has each column of the sparse matrix A assigned to a unique output grid point. We need to determine which column
% numbers are assigned to those 16 grid points.
% What are the first indexes (in x and y) for the points?
XIndexes = min(max(1, indx - 1), nx - 3);
YIndexes = min(max(1, indy - 1), ny - 3);
% These are the first indexes of that 4x4 grid of nodes where we are doing the interpolation.
AllColumns = (YIndexes + (XIndexes - 1) * ny)';
% Add in the next three points. This gives us output nodes in the first row (i.e. along the x direction).
AllColumns = [AllColumns; AllColumns + ny; AllColumns + 2 * ny; AllColumns + 3 * ny];
% Add in the next three rows. This gives us 16 total output points for each input point.
AllColumns = [AllColumns; AllColumns + 1; AllColumns + 2; AllColumns + 3];
% Coefficients are calculated based on:
% http://en.wikipedia.org/wiki/Lagrange_interpolation
% Calculate coefficients for this point based on its coordinates as if we were doing cubic interpolation in x.
% Calculate the first coefficients for x and y.
XCoefficients = (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 2)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 2)) .* (xnodes(XIndexes(:)) - xnodes(XIndexes(:) + 3)));
YCoefficients = (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 2)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 2)) .* (ynodes(YIndexes(:)) - ynodes(YIndexes(:) + 3)));
% Calculate the second coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 2)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:) + 2)) .* (xnodes(XIndexes(:) + 1) - xnodes(XIndexes(:) + 3)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 2)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:) + 2)) .* (ynodes(YIndexes(:) + 1) - ynodes(YIndexes(:) + 3)))];
% Calculate the third coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 3)) ./ ((xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:) + 2) - xnodes(XIndexes(:) + 3)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 3)) ./ ((ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:) + 2) - ynodes(YIndexes(:) + 3)))];
% Calculate the fourth coefficients.
XCoefficients = [XCoefficients, (x(:) - xnodes(XIndexes(:))) .* (x(:) - xnodes(XIndexes(:) + 1)) .* (x(:) - xnodes(XIndexes(:) + 2)) ./ ((xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:))) .* (xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:) + 1)) .* (xnodes(XIndexes(:) + 3) - xnodes(XIndexes(:) + 2)))];
YCoefficients = [YCoefficients, (y(:) - ynodes(YIndexes(:))) .* (y(:) - ynodes(YIndexes(:) + 1)) .* (y(:) - ynodes(YIndexes(:) + 2)) ./ ((ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:))) .* (ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:) + 1)) .* (ynodes(YIndexes(:) + 3) - ynodes(YIndexes(:) + 2)))];
% Allocate space for all of the data we're about to insert.
AllCoefficients = zeros(16, n);
% There may be a clever way to vectorize this, but then the code would be unreadable and difficult to debug or upgrade.
% The matrix solution process will take far longer than this, so it's not worth the effort to vectorize this.
for i = 1 : n
% Multiply the coefficients to accommodate bicubic interpolation. The resulting matrix is a 4x4 of the interpolation coefficients.
TheseCoefficients = repmat(XCoefficients(i, :)', 1, 4) .* repmat(YCoefficients(i, :), 4, 1);
% Add these coefficients to the list.
AllCoefficients(1 : 16, i) = TheseCoefficients(:);
end
% Each input point has 16 interpolation coefficients (because of the 4x4 grid).
AllRows = repmat(1 : n, 16, 1);
% Now that we have all of the indexes and coefficients, we can create the sparse matrix of equality conditions.
A = sparse(AllRows(:), AllColumns(:), AllCoefficients(:), n, ngrid);
end
rhs = z;
% Do we have relative smoothing parameters?
if numel(params.smoothness) == 1
% Nothing special; this is just a scalar quantity that needs to be the same for x and y directions.
xyRelativeStiffness = [1; 1] * params.smoothness;
else
% What the user asked for
xyRelativeStiffness = params.smoothness(:);
end
% Build a regularizer using the second derivative. This used to be called "gradient" even though it uses a second
% derivative, not a first derivative. This is an important distinction because "gradient" implies a horizontal
% surface, which is not correct. The second derivative favors flatness, especially if you use a large smoothness
% constant. Flat and horizontal are two different things, and in this script we are taking an irregular surface and
% flattening it according to the smoothness constant.
% The second-derivative calculation is documented here:
% http://mathformeremortals.wordpress.com/2013/01/12/a-numerical-second-derivative-from-three-points/
% Minimizes the sum of the squares of the second derivatives (wrt x and y) across the grid
[i,j] = meshgrid(1:nx,2:(ny-1));
ind = j(:) + ny*(i(:)-1);
dy1 = dy(j(:)-1);
dy2 = dy(j(:));
Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ...
2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid);
[i,j] = meshgrid(2:(nx-1),1:ny);
ind = j(:) + ny*(i(:)-1);
dx1 = dx(i(:) - 1);
dx2 = dx(i(:));
Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ...
xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ...
2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)];
nreg = size(Areg, 1);
FidelityEquationCount = size(A, 1);
% Number of the second derivative equations in the matrix
RegularizerEquationCount = nx * (ny - 2) + ny * (nx - 2);
% We are minimizing the sum of squared errors, so adjust the magnitude of the squared errors to make second-derivative
% squared errors match the fidelity squared errors. Then multiply by smoothparam.
NewSmoothnessScale = sqrt(FidelityEquationCount / RegularizerEquationCount);
% Second derivatives scale with z exactly because d^2(K*z) / dx^2 = K * d^2(z) / dx^2.
% That means we've taken care of the z axis.
% The square root of the point/derivative ratio takes care of the grid density.
% We also need to take care of the size of the dataset in x and y.
% The scaling up to this point applies to local variation. Local means within a domain of [0, 1] or [10, 11], etc.
% The smoothing behavior needs to work for datasets that are significantly larger or smaller than that.
% For example, if x and y span [0 10,000], smoothing local to [0, 1] is insufficient to influence the behavior of
% the whole surface. For the same reason there would be a problem applying smoothing for [0, 1] to a small surface
% spanning [0, 0.01]. Multiplying the smoothing constant by SurfaceDomainScale compensates for this, producing the
% expected behavior that a smoothing constant of 1 produces noticeable smoothing (when looking at the entire surface
% profile) and that 1% does not produce noticeable smoothing.
SurfaceDomainScale = (max(max(xnodes)) - min(min(xnodes))) * (max(max(ynodes)) - min(min(ynodes)));
NewSmoothnessScale = NewSmoothnessScale * SurfaceDomainScale;
A = [A; Areg * NewSmoothnessScale];
rhs = [rhs;zeros(nreg,1)];
% do we have a mask to apply?
if params.maskflag
unmasked = find(params.mask);
end
% solve the full system, with regularizer attached
switch params.solver
case {'\' 'backslash'}
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
zgrid(unmasked) = A(:,unmasked)\rhs;
else
% no mask
zgrid = reshape(A\rhs,ny,nx);
end
case 'normal'
% The normal equations, solved with \. Can be faster
% for huge numbers of data points, but reasonably
% sized grids. The regularizer makes A well conditioned
% so the normal equations are not a terribly bad thing
% here.
if params.maskflag
% there is a mask to use
Aunmasked = A(:,unmasked);
zgrid=nan(ny,nx);
zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs);
else
zgrid = reshape((A'*A)\(A'*rhs),ny,nx);
end
case 'symmlq'
% iterative solver - symmlq - requires a symmetric matrix,
% so use it to solve the normal equations. No preconditioner.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ...
A(:,unmasked)'*rhs,tol,params.maxiter);
else
[zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% SYMMLQ iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ...
' iterations but did not converge.'])
case 3
% SYMMLQ stagnated, successive iterates were the same
warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.')
otherwise
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' symmlq was too small or too large to continue computing.'])
end
case 'lsqr'
% iterative solver - lsqr. No preconditioner here.
tol = abs(max(z)-min(z))*1.e-13;
if params.maskflag
% there is a mask to use
zgrid=nan(ny,nx);
[zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter);
else
[zgrid,flag] = lsqr(A,rhs,tol,params.maxiter);
zgrid = reshape(zgrid,ny,nx);
end
% display a warning if convergence problems
switch flag
case 0
% no problems with convergence
case 1
% lsqr iterated MAXIT times but did not converge.
warning('GRIDFIT:solver',['Lsqr performed ', ...
num2str(params.maxiter),' iterations but did not converge.'])
case 3
% lsqr stagnated, successive iterates were the same
warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.')
case 4
warning('GRIDFIT:solver',['One of the scalar quantities calculated in',...
' LSQR was too small or too large to continue computing.'])
end
end % switch params.solver
end % if params.tilesize...
% only generate xgrid and ygrid if requested.
if nargout>1
[xgrid,ygrid]=meshgrid(xnodes,ynodes);
end
% ============================================
% End of main function - gridfit
% ============================================
% ============================================
% subfunction - parse_pv_pairs
% ============================================
function params=parse_pv_pairs(params,pv_pairs)
% parse_pv_pairs: parses sets of property value pairs, allows defaults
% usage: params=parse_pv_pairs(default_params,pv_pairs)
%
% arguments: (input)
% default_params - structure, with one field for every potential
% property/value pair. Each field will contain the default
% value for that property. If no default is supplied for a
% given property, then that field must be empty.
%
% pv_array - cell array of property/value pairs.
% Case is ignored when comparing properties to the list
% of field names. Also, any unambiguous shortening of a
% field/property name is allowed.
%
% arguments: (output)
% params - parameter struct that reflects any updated property/value
% pairs in the pv_array.
%
% Example usage:
% First, set default values for the parameters. Assume we
% have four parameters that we wish to use optionally in
% the function examplefun.
%
% - 'viscosity', which will have a default value of 1
% - 'volume', which will default to 1
% - 'pie' - which will have default value 3.141592653589793
% - 'description' - a text field, left empty by default
%
% The first argument to examplefun is one which will always be
% supplied.
%
% function examplefun(dummyarg1,varargin)
% params.Viscosity = 1;
% params.Volume = 1;
% params.Pie = 3.141592653589793
%
% params.Description = '';
% params=parse_pv_pairs(params,varargin);
% params
%
% Use examplefun, overriding the defaults for 'pie', 'viscosity'
% and 'description'. The 'volume' parameter is left at its default.
%
% examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world')
%
% params =
% Viscosity: 10
% Volume: 1
% Pie: 3
% Description: 'Hello world'
%
% Note that capitalization was ignored, and the property 'viscosity'
% was truncated as supplied. Also note that the order the pairs were
% supplied was arbitrary.
npv = length(pv_pairs);
n = npv/2;
if n~=floor(n)
error 'Property/value pairs must come in PAIRS.'
end
if n<=0
% just return the defaults
return
end
if ~isstruct(params)
error 'No structure for defaults was supplied'
end
% there was at least one pv pair. process any supplied
propnames = fieldnames(params);
lpropnames = lower(propnames);
for i=1:n
p_i = lower(pv_pairs{2*i-1});
v_i = pv_pairs{2*i};
ind = strmatch(p_i,lpropnames,'exact');
if isempty(ind)
ind = find(strncmp(p_i,lpropnames,length(p_i)));
if isempty(ind)
error(['No matching property found for: ',pv_pairs{2*i-1}])
elseif length(ind)>1
error(['Ambiguous property name: ',pv_pairs{2*i-1}])
end
end
p_i = propnames{ind};
% override the corresponding default in params
params = setfield(params,p_i,v_i); %#ok
end
% ============================================
% subfunction - check_params
% ============================================
function params = check_params(params)
% check the parameters for acceptability
% smoothness == 1 by default
if isempty(params.smoothness)
params.smoothness = 1;
else
if (numel(params.smoothness)>2) || any(params.smoothness<=0)
error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.'
end
end
% interp must be one of:
% 'bicubic', 'bilinear', 'nearest', or 'triangle'
% but accept any shortening thereof.
valid = {'bicubic', 'bilinear', 'nearest', 'triangle'};
if isempty(params.interp)
params.interp = 'bilinear';
end
ind = find(strncmpi(params.interp,valid,length(params.interp)));
if (length(ind)==1)
params.interp = valid{ind};
else
error(['Invalid interpolation method: ',params.interp])
end
% solver must be one of:
% 'backslash', '\', 'symmlq', 'lsqr', or 'normal'
% but accept any shortening thereof.
valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'};
if isempty(params.solver)
params.solver = '\';
end
ind = find(strncmpi(params.solver,valid,length(params.solver)));
if (length(ind)==1)
params.solver = valid{ind};
else
error(['Invalid solver option: ',params.solver])
end
% extend must be one of:
% 'never', 'warning', 'always'
% but accept any shortening thereof.
valid = {'never', 'warning', 'always'};
if isempty(params.extend)
params.extend = 'warning';
end
ind = find(strncmpi(params.extend,valid,length(params.extend)));
if (length(ind)==1)
params.extend = valid{ind};
else
error(['Invalid extend option: ',params.extend])
end
% tilesize == inf by default
if isempty(params.tilesize)
params.tilesize = inf;
elseif (length(params.tilesize)>1) || (params.tilesize<3)
error 'Tilesize must be scalar and > 0.'
end
% overlap == 0.20 by default
if isempty(params.overlap)
params.overlap = 0.20;
elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5)
error 'Overlap must be scalar and 0 < overlap < 1.'
end
% ============================================
% subfunction - tiled_gridfit
% ============================================
function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params)
% tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries
% usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params)
%
% Tiled_gridfit is used when the total grid is far too large
% to model using a single call to gridfit. While gridfit may take
% only a second or so to build a 100x100 grid, a 2000x2000 grid
% will probably not run at all due to memory problems.
%
% Tiles in the grid with insufficient data (<4 points) will be
% filled with NaNs. Avoid use of too small tiles, especially
% if your data has holes in it that may encompass an entire tile.
%
% A mask may also be applied, in which case tiled_gridfit will
% subdivide the mask into tiles. Note that any boolean mask
% provided is assumed to be the size of the complete grid.
%
% Tiled_gridfit may not be fast on huge grids, but it should run
% as long as you use a reasonable tilesize. 8-)
% Note that we have already verified all parameters in check_params
% Matrix elements in a square tile
tilesize = params.tilesize;
% Size of overlap in terms of matrix elements. Overlaps
% of purely zero cause problems, so force at least two
% elements to overlap.
overlap = max(2,floor(tilesize*params.overlap));
% reset the tilesize for each particular tile to be inf, so
% we will never see a recursive call to tiled_gridfit
Tparams = params;
Tparams.tilesize = inf;
nx = length(xnodes);
ny = length(ynodes);
zgrid = zeros(ny,nx);
% linear ramp for the bilinear interpolation
rampfun = inline('(t-t(1))/(t(end)-t(1))','t');
% loop over each tile in the grid
h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.');
warncount = 0;
xtind = 1:min(nx,tilesize);
while ~isempty(xtind) && (xtind(1)<=nx)
xinterp = ones(1,length(xtind));
if (xtind(1) ~= 1)
xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap)));
end
if (xtind(end) ~= nx)
xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end)));
end
ytind = 1:min(ny,tilesize);
while ~isempty(ytind) && (ytind(1)<=ny)
% update the waitbar
waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx)
yinterp = ones(length(ytind),1);
if (ytind(1) ~= 1)
yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap)));
end
if (ytind(end) ~= ny)
yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end)));
end
% was a mask supplied?
if ~isempty(params.mask)
submask = params.mask(ytind,xtind);
Tparams.mask = submask;
end
% extract data that lies in this grid tile
k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ...
(y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end)));
k = find(k);
if length(k)<4
if warncount == 0
warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.')
end
warncount = warncount + 1;
% fill this part of the grid with NaNs
zgrid(ytind,xtind) = NaN;
else
% build this tile
zgtile = RegularizeData3D(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams);
% bilinear interpolation (using an outer product)
interp_coef = yinterp*xinterp;
% accumulate the tile into the complete grid
zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef;
end
% step to the next tile in y
if ytind(end)<ny
ytind = ytind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (ytind(end)+max(3,overlap))>=ny
% extend this tile to the edge
ytind = ytind(1):ny;
end
else
ytind = ny+1;
end
end % while loop over y
% step to the next tile in x
if xtind(end)<nx
xtind = xtind + tilesize - overlap;
% are we within overlap elements of the edge of the grid?
if (xtind(end)+max(3,overlap))>=nx
% extend this tile to the edge
xtind = xtind(1):nx;
end
else
xtind = nx+1;
end
end % while loop over x
% close down the waitbar
close(h)
if warncount>0
warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs'])
end
|
github
|
ganlubbq/Signal-Processing-master
|
hydrophoneDataProcessSineSweep.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/hydrophoneDataProcessSineSweep.m
| 6,377 |
utf_8
|
0b06324432fbdf55310db51ea1046637
|
function [meanArray ] = hydrophoneDataProcessSineSweep( fileName, startFrequency, stepFrequency )
import ppPkg.*
im = ImportHandler;
% Import data file
header = im.readHeader(fileName);
tmArr = im.importDataFile();
fileName
%% Use moving average filter to smooth the data points
N = 4;
b = (1/N)*ones(1, N);
a = 1;
% Frequency increases with 100kHz for each step
for index = 1:1:length(tmArr)
tm = tmArr(index);
%
% if(index < 170 )
% recordedSignal = filtfilt(b, a, tm.signal);
% else
% recordedSignal = tm.signal;
% end
recordedSignal = tm.signal;
%plot(recordedSignal)
sinusFrequency = startFrequency + stepFrequency*(index-1);
pulseLength = 20 * header.sampleRate / sinusFrequency;
% Create tx pulse
txPulse = generatePulse(header.pulsePattern, header.sampleRate, pulseLength, sinusFrequency, sinusFrequency );
[startIndexPulse] = findStartIndexPulse(txPulse, recordedSignal, 1000);
if(round(startIndexPulse) < 7500 && round(startIndexPulse) > 6500 )
% Extract signal segment to investigate
signalSegment = recordedSignal(round(startIndexPulse):round(startIndexPulse+pulseLength));
% Calculate minimum peak distance
peakDistance = round(2/3 * header.sampleRate / sinusFrequency);
[maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance);
% Sum max and min to calculate "peak2peak" value
peak2peakArray = maxPeaks - minPeaks;
% Calculate mean
meanArray(index) = mean(peak2peakArray);
else
meanArray(index) = 0;
end
%plot(tm.signal, )
%grid on
end
end
function [maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance)
interpFactor = 10;
peakDistanceModified = peakDistance * interpFactor;
signalSegment_interp = interp(signalSegment,interpFactor);
%findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
%findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
[pksMax, locsMax] = findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
[pksMin, locsMin] = findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
% sigZeropad(1:10:10 * length(signalSegment) - 1) = signalSegment;
% stem(sigZeropad)
% hold on
% plot(signalSegment_interp)
% hold off
% Only keep peaks 3 to 8
if((numel(pksMax) >= 12) && (numel(pksMin) >= 12))
maxPeaks = pksMax(5:12);
minPeaks = -pksMin(5:12);
locsMax = locsMax(5:12);
locsMin = locsMin(5:12);
elseif(length(pksMax) > 2)
disp('Error Should find more than 12 peaks')
lengthMax = length(pksMax);
lengthMin = length(pksMin);
if(lengthMax > lengthMin)
maxLength = lengthMin;
else
maxLength = lengthMax;
end
maxPeaks = pksMax(1:maxLength);
minPeaks = -pksMin(1:maxLength);
locsMax = locsMax(1:maxLength);
locsMin = locsMin(1:maxLength);
else
error('Error in finding peaks')
end
end
function [txPulse, tPulse] = generatePulse(pattern, sampleRate, pulseLength, fLow, fHigh)
import ppPkg.*
switch lower(pattern)
case 'simple'
[txPulse, tPulse] = generateSin(sampleRate, pulseLength, fLow);
case 'chirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
case 'rectchirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
txPulse = sign(txPulse);
case 'sinc'
[txPulse, tPulse] = generateSinc(sampleRate, pulseLength, fLow, fHigh);
case 'rectpulse'
[txPulse, tPulse] = generateRectPulseTrain(sampleRate, pulseLength, fLow, fHigh);
txPulse = flip(txPulse)
otherwise
error('Signal pattern not supported')
end
end
function startIndexPulse = findStartIndexPulse(txPulse, signal, delay)
% Function use correlation between emitted pulse and recorded signal to find
% startIndex for pulse in recorded signal
startIndex = 1 + delay;
[r, lags] = xcorr(signal(startIndex:end), txPulse);
% Find the index where the absolute value of the cross correlation is at its
% maximum
r_abs = abs(r);
[maxValue, maxIndex] = max(r);
lagInterp = findLagUsingInterpolation(r_abs, lags, maxIndex);
startIndexPulse = delay + round(lagInterp);
end
function lag = findLagUsingInterpolation(r, x, maxIndex)
%%
% This function uses interpolation to find a better estimate for the
% location of the maximum value of r.
% r: sample values (cross correlation)
% x: sample points (lags)
% max_index: index where r has its maximum value.
% Number of point before and after max peak
deltaPoint = 3;
% Number of quary points for each sample
interpolation_factor = 8;
startIndex = maxIndex-deltaPoint;
stopIndex = maxIndex+deltaPoint;
x_startIndex = x(startIndex);
x_stopIndex = x(stopIndex);
%% Retrieve small segment including max peak
% Segment sample points
segmentRange = startIndex:1:stopIndex;
% Segment sample values
r_segment = r(segmentRange);
%% Create quary vector
% Quary segment sample points
interpolationRange = x_startIndex:1/interpolation_factor:x_stopIndex;
x_segmentRange = x_startIndex:1:x_stopIndex;
r_interp = interp1(x_segmentRange, r_segment,interpolationRange,'spline');
% Find index for max peak for the interpolated curve
[~,I_intep] = max(r_interp);
% Find lag at this index
lag = interpolationRange(I_intep);
end
|
github
|
ganlubbq/Signal-Processing-master
|
transducerTest.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/transducerTest.m
| 6,750 |
utf_8
|
c7830cdb2a8c1eec2bec64fd33dc07ab
|
%> @file transducerTest.m
%> @brief Contain functions for processing transducer test measurements
% ======================================================================
%> @brief Contain functions for processing transducer test measurements
%
%>
% ======================================================================
% ======================================================================
%> @brief Function transducerTest
%>
%> @param ctrl Controller object
%> @param folder Folder containing transducer test measurements
%> @param psdCompare Baseline transducer to compare with
%> @param folderToSave Path to folder to where plots should be saved
%> @retval res Struct containing:
%> medianNoise
%> meanNoise
%> medianDbAboveNoise
%> meanDbAboveNoise
%> psdMain
%> psdResonance
%> dataHeader
%> transducer
%> title
% ======================================================================
function res = transducerTest(ctrl, folder, psdCompare, folderToSaveFig)
% Read folder
% Get all subfolder names
% Do a regex
% Keep the ones that matches the regex
listing = dir(folder);
%folderNames;
[pathstr,name,ext] = fileparts(folder);
folderIndex = 1;
for index = 1:size(listing,1)
temp = regexp(listing(index).name,'B12_BN218.*','match');
if(~isempty(temp))
dataFolders(folderIndex) = cellstr(listing(index).name);
folderIndex = folderIndex + 1;
end
end
folderFirstPart = strcat(listing(1).folder,'\');
% Initialize struct
res(numel(dataFolders)) = struct('medianNoise',0,...
'meanNoise',0,...
'medianDbAboveNoise',0,...
'meanDbAboveNoise',0,...
'psdMain', 0,...
'psdResonance', 0,...
'dataHeader','',...
'transducer','',...
'title','');
% Get path to all header files in dataFolders
for indexN = 1:numel(dataFolders)
folderPath = char(dataFolders(indexN));
folderPath = strcat(folderFirstPart, folderPath);
folderPath = strcat(folderPath,'\');
% Get content of folderPath
listingFolder = dir(char(folderPath));
% Iterate through the files in the folder
for indexM = 1:size(listingFolder,1)
% Get the file that contains 'header' and extract information
% from the file name
temp = regexp(listingFolder(indexM).name,'.*header','match');
if(~isempty(temp))
% Get Transducer info
token1 = regexp(listingFolder(indexM).name,'.*(BN218_\d\d_\d\d\d).*','tokens');
res(indexN).transducer = char(token1{1});
% Get Title txt
token2 = regexp(listingFolder(indexM).name,'(.*)_[0-9]+_[0-9]+_header','tokens');
res(indexN).title = char(token2{1});
% Get path to data file header
fileName = listingFolder(indexM).name;
res(indexN).dataHeader = strcat(folderPath, fileName);
end
end
end
% Iterate through struct array to process data from each transducer
for index = 1:numel(res)
% Process data
res(index) = processData(ctrl, res(index));
% Plot PSD main with psd compare
plotPsdMain(ctrl, res(index), psdCompare, folderToSaveFig);
plotPsdResonance(ctrl, res(index), folderToSaveFig);
res(index)
%pause()
close all
end
end
% ======================================================================
%> @brief Function process transducer data
%> Function will calculate median and mean noise, and median and
%> mean dB above noise for the peaks. And calculate the mean Psd
%> main and psd resonance
%>
%> @param ctrl Controller object
%> @param res Struct
%> @retval res Struct
% ======================================================================
function res = processData(ctrl, res)
ctrl.start(res.dataHeader);
res.medianNoise = median([ctrl.pr(:).noiseMean])
res.meanNoise = mean([ctrl.pr(:).noiseMean])
dbAboveNoiseTemp = zeros(1, length(ctrl.pr));
for indexM = 1:length(ctrl.pr)
dbAboveNoiseTemp(indexM) = mean(ctrl.pr(indexM).peakDB) - res.medianNoise;
end
res.medianDbAboveNoise = median(dbAboveNoiseTemp);
res.meanDbAboveNoise = mean(dbAboveNoiseTemp);
res.psdMain = mean([ctrl.pr(:).psdMain], 2);
res.psdResonance = mean([ctrl.pr(:).psdResonance], 2);
end
% ======================================================================
%> @brief Function plots Psd Main and save figure to file
%>
%> @param ctrl Controller object
%> @param res Struct
%> @param psdCompare
%> @param folderToSaveFig
% ======================================================================
function plotPsdMain(ctrl, res, psdCompare, folderToSaveFig)
fig = figure;
plot(ctrl.pr(1).fMain,[res.psdMain])
hold on
plot(ctrl.pr(1).fMain, psdCompare)
title('Psd Main')
grid on
transducerTxt = strrep(res.transducer, '_', ' ');
titleTxt = strrep(res.title, '_', ' ');
filenameFig = strcat('Psd_Main_', res.title)
legend(transducerTxt,'BN lab 3 LG40 SG05 latest')
title(titleTxt)
ylim([-120 -60]);
saveFigPath = strcat(folderToSaveFig,'\');
saveFigPath = strcat(saveFigPath,filenameFig);
savefig(fig, saveFigPath)
end
% ======================================================================
%> @brief Function plots Psd Resonance
%>
%> @param ctrl Controller object
%> @param res Struct
%> @param folderToSaveFig
% ======================================================================
function plotPsdResonance(ctrl, res, folderToSaveFig)
fig = figure;
plot(ctrl.pr(1).fMain,[res.psdResonance])
grid on
titleTxt = strrep(res.title, '_', ' ');
filenameFig = strcat('Psd_Resonance_', res.title);
title(titleTxt)
ylim([-150 -80]);
saveFigPath = strcat(folderToSaveFig,'\');
saveFigPath = strcat(saveFigPath,filenameFig);
savefig(fig, saveFigPath)
end
|
github
|
ganlubbq/Signal-Processing-master
|
hydrophoneDataProcess.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/hydrophoneDataProcess.m
| 7,812 |
utf_8
|
015cad9b5dbeee8da2b79fd5733aed31
|
function [ meanArray, startIndexArray ] = hydrophoneDataProcess( fileName, varargin)
% Function calculates the mean peak2peak value of the sinus recorded
% by the hydrophone, for each shot the transducer is moved in an angle.
% Function now assumes that transducer is moved with 1 degree for each shot
%
import ppPkg.*
im = ImportHandler
% Create function input parser object
p = inputParser;
nVarargs = length(varargin);
defaultStep = 0;
defaultStartIndex = 0;
addRequired(p, 'fileName', @ischar);
addRequired(p,'angleResolution', @isnumeric);
addRequired(p,'startAngle', @isnumeric);
addRequired(p,'stopAngle', @isnumeric);
addParameter(p,'stepProcessing', defaultStep, @isnumeric);
addParameter(p,'startIndex', defaultStartIndex, @isnumeric);
% Parse function input
parse(p, fileName, varargin{:})
if(p.Results.stepProcessing)
f = figure;
end
header = im.readHeader(fileName);
tmArr = im.importDataFile();
% Create tx pulse
txPulse = generatePulse(header.pulsePattern, header.sampleRate, header.pulseLength, header.fLow, header.fHigh );
% Init array
meanArray = zeros(1, length(tmArr));
startIndexArray = zeros(1, length(tmArr) );
if(p.Results.angleResolution == 0)
startIndex = 1;
stopIndex = length(tmArr)
elseif(p.Results.startIndex ~= 0)
if(p.Results.startIndex>1)
startIndex = p.Results.startIndex-1;
else
startIndex = p.Results.startIndex;
end
stopIndex = length(tmArr);
else
startIndex = p.Results.startAngle/p.Results.angleResolution;
stopIndex = p.Results.stopAngle/p.Results.angleResolution;
if(startIndex > length(tmArr) || stopIndex > length(tmArr))
error('Error in calculating start and stop index')
return
end
end
% if(p.Results.startIndex ~= 0)
% if(p.Results.startIndex>1)
% startIndex = p.Results.startIndex-1;
% else
% startIndex = p.Results.startIndex;
% end
% end
for index = (startIndex+1):stopIndex
%for index = 1:length(tmArr)
tm = tmArr(index);
recordedSignal = tm.signal;
% Find start index pulse
startIndexPulse = findStartIndexPulse(txPulse, recordedSignal);
startIndexArray(index) = startIndexPulse;
%plot(recordedSignal)
if(startIndexPulse <= 450 || startIndexPulse > 6000 )
disp('StartIndexPulse outside valid range');
continue;
end
% Extract signal segment with pulse
signalSegment = recordedSignal(startIndexPulse:(startIndexPulse + header.pulseLength));
% Calculate minimum peak distance
peakDistance = round(2/3 * header.sampleRate / header.fLow);
% Calculate 6 max and min peaks for signal
[maxPeaks, locsMax, minPeaks, locsMin, segmentWithPeaks] = findMaxAndMinPeaks((signalSegment), peakDistance);
% Sum max and min to calculate "peak2peak" value
peak2peakArray = maxPeaks - minPeaks;
% Calculate mean
meanArray(index) = mean(peak2peakArray);
if(p.Results.stepProcessing)
subplot(2,1,1)
plot(recordedSignal)
hold on
plot(startIndexPulse,recordedSignal(startIndexPulse), '*')
title('Red start: start of signal segment')
grid on
hold off
x = 1:length(segmentWithPeaks);
padding = 10;
% Create x array for signal segment
x_ = ((1:length(signalSegment))*padding)-padding;
subplot(2,1,2)
plot(x, segmentWithPeaks, ...
locsMax, maxPeaks, 'o', ...
locsMin, minPeaks,'*',...
x_, signalSegment);
grid on
titleTxt = sprintf('Index %d, press button to continue', index);
title(titleTxt);
w = 0;
while(w == 0)
w = waitforbuttonpress;
% if w == 0
% disp('Button click')
% else
% disp('Key press')
% end
end
end
end
end
function [txPulse, tPulse] = generatePulse(pattern, sampleRate, pulseLength, fLow, fHigh)
import ppPkg.*
switch lower(pattern)
case 'simple'
[txPulse, tPulse] = generateSin(sampleRate, pulseLength, fLow);
case 'chirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
case 'rectchirp'
[txPulse, tPulse] = generateChirp(sampleRate, pulseLength, fLow, fHigh);
txPulse = sign(txPulse);
case 'sinc'
[txPulse, tPulse] = generateSinc(sampleRate, pulseLength, fLow, fHigh);
case 'rectpulse'
[txPulse, tPulse] = generateRectPulseTrain(sampleRate, pulseLength, fLow, fHigh);
txPulse = flip(txPulse)
otherwise
error('Signal pattern not supported')
end
end
function startIndexPulse = findStartIndexPulse(txPulse, signal)
% Function use correlation between emitted pulse and recorded signal to find
% startIndex for pulse in recorded signal
import ppPkg.*
ctrl = Controller;
callipAlg = CalliperAlgorithm(ctrl.config);
% Calculate Calliper
% Set transmitted pulse
callipAlg.setTxPulse(txPulse);
% Start searching at index 0
delay = 0;
%% Calculate startIndex for pulse in recording
[distance, startIndexPulse] = callipAlg.calculateDistance( delay, signal, 0);
end
function [maxPeaks, locsMax, minPeaks, locsMin, segment] = findMaxAndMinPeaks(signalSegment, peakDistance)
if(1)
interpFactor = 10;
peakDistanceModified = peakDistance * interpFactor;
signalSegment_interp = interp(signalSegment,interpFactor);
[pksMax, locsMax] = findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
[pksMin, locsMin] = findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
else
[pksMax, locsMax] = findpeaks(signalSegment,'MinPeakDistance', peakDistance);
[pksMin, locsMin] = findpeaks(-signalSegment,'MinPeakDistance', peakDistance);
end
segment = signalSegment_interp;
% Only keep peaks 3 to 8
if((length(pksMax) > 12) && (length(pksMin) > 12))
maxPeaks = pksMax(6:13);
minPeaks = -pksMin(6:13);
locsMax = locsMax(6:13);
locsMin = locsMin(6:13);
% elseif(length(pksMax) > 2)
% lengthMax = length(pksMax);
% lengthMin = length(pksMin);
% if(lengthMax > lengthMin)
% maxLength = lengthMin;
% else
% maxLength = lengthMax;
% end
%
% maxPeaks = pksMax(1:maxLength);
% minPeaks = -pksMin(1:maxLength);
% locsMax = locsMax(1:maxLength);
% locsMin = locsMin(1:maxLength);
else
disp('Error in finding peaks')
maxPeaks = 0;
minPeaks = 0;
end
end
|
github
|
ganlubbq/Signal-Processing-master
|
findFrequencySets.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@ThicknessAlgorithm/findFrequencySets.m
| 6,873 |
utf_8
|
c64c627814ebd16c8d51ff8abb5da649
|
% ======================================================================
%> @brief findFrequencySets(obj, type, fLow, fHigh, noHarmonics)
%>
%> Function finds all frequencies that matches a harmonic set
%>
%> @param obj ThicknessAlgorithm class object
%> @param type Type of psd to search: RESONANCE or MAIN
%> @param fLow Lower Frequency
%> @param fLow Higher Frequency
%> @param fLow Required number of harmonics in each set
%>
%> @retval setsFound Reference to sets found
% ======================================================================
function [setsFound] = findFrequencySets(obj, type, fLow, fHigh, noHarmonics)
%% Function finds all frequencies that matches a harmonic set.
% Start searching for sets from fHigh and towards fLow
% psd: PSD
% locs: Array containing index to peaks in PSD
% fHigh: Upper frequency in emitted pulse.
% Deviation is calculated based on (Fs/N) * deviationFactor
import ppPkg.HarmonicSet
if(obj.RESONANCE == type)
psd = obj.psdResonance;
locs = obj.peakLocationResonance;
deviationInFrequency = (obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH) * obj.config.DEVIATION_FACTOR;
% @TODO: Consider changing how we calculate the deviation frquency.
% It should be based on the relevant frequency resolution
% Frequency resolution is given by
% R = 1/T,
% where T is the recording time of the signal. T = Fs/L,
% where L is number of samples
%
% FTT resolution is given by:
% Rf = Fs/Nfft.
% So having a high Nfft does not improve the frequency
% resolution if T is short
% Ideal we should have: Fs/L = Fs/Nfft => L = Nfft, but this is not the
% case
elseif(obj.MAIN == type)
psd = obj.psdMain;
locs = obj.peakLocationMain;
deviationInFrequency = (obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH) * obj.config.DEVIATION_FACTOR;
else
error('Illegal spectrum type: %s\n', type);
end
MIN_REQUIRED_HARMONICS = noHarmonics;
numberOfSets = 0;
% Calculate minimum fundemental frequency that can exists
freqFundamentalMinimum = obj.config.V_PIPE/(2*obj.config.D_NOM);
% Allowed percentage deviaion from target harmonic frequency
% Iterate through array of maxima and find all frequencies that
% matches a set.
% Flip array so start searching from higher frequency
locs = sort(locs);
locs = flip(locs);
for n = 1:length(locs)
for m = (n+1):length(locs)
for j =(m):length(locs)
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
if( j == m )
fN.freq = (locs(n)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fN.peakValue = (psd(locs(n)));
fN.index = locs(n);
fM.freq = (locs(m)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fM.peakValue = (psd(locs(m)));
fM.index = locs(m);
%tempSet = HarmonicSet(freqN, peakN, locs(n), freqM, peakM, locs(m), deviationInFrequency);
%fprintf('create set index n: %d m: %d j: %d\n',n, m, j);
% Only create a new set if the difference
% between freqN and freqM is larger than
% freqFundamentalMinimum
if(abs(fM.freq - fN.freq) > freqFundamentalMinimum)
% Create harmonicSet object
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
%tempSet = HarmonicSet(freqN, peakN, locs(n), freqM, peakM, locs(m), deviationInFrequency);
tempSet = HarmonicSet(fN, fM, deviationInFrequency, fLow, fHigh);
else
tempSet = [];
break;
end
else
fJ.freq = (locs(j)-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fJ.peakValue = (psd(locs(j)));
fJ.index = locs(j);
% Try to add next frequency to set
if(tempSet.tryAddFreqFromHigh(fJ))
end
end
end
% Search the other direction
% Try to add frequencies
if(n > 1 && ( numel(tempSet) > 0 ))
%fprintf('index n: %d m: %d j: %d\n',n, m, j);
for K = flip(locs(1:n-1))'
fK.freq = (K-1)*obj.config.SAMPLE_RATE/obj.config.FFT_LENGTH;
fK.peakValue = (psd(K));
fK.index = K;
tempSet.tryAddFreqFromLow(fK);
end
end
if( j == length(locs))
%fprintf('try save sets %d countf %d\n',numberOfSets, tempSet.frequencyCount);
if(isempty(tempSet))
elseif(numberOfSets == 0 && (tempSet.numFrequencies >= MIN_REQUIRED_HARMONICS))
numberOfSets = 1;
set = tempSet;
% Only keep sets that have more than MIN_REQUIRED_HARMONICS
% harmonic frequencies
elseif(tempSet.numFrequencies >= MIN_REQUIRED_HARMONICS)
numberOfSets = numberOfSets + 1;
set(numberOfSets) = tempSet;
tempSet = [];
end
end
end
end
if(numberOfSets == 0)
if(obj.config.DEBUG_INFO)
disp('No Sets found, try do adjust dB level')
end
set = [];
else
% Remove all subsets
%set = obj.removeAllSubsets2(set);
% Flip frequency array in Harmonic set so that set always
% start with the lower frequency
for index = 1:length(set)
set(index).flip();
end
end
% Store set to class
if(obj.RESONANCE == type)
obj.setResonance = set;
elseif(obj.MAIN == type)
obj.setMain = set;
end
setsFound = numel(set);
end
|
github
|
ganlubbq/Signal-Processing-master
|
importDataVersion4.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@ImportHandler/importDataVersion4.m
| 5,342 |
utf_8
|
f2b9870adc59c60749f6514c7db1a4f5
|
function [tm, numberOfRec, header] = importDataVersion4(obj, h, fileId)
% Read file version. Based on version call correct handler
% Expects that Labview data is little endian.
% Header format
% header.version uint8
% header.seqNo uint32
% header.dataType uint8
% header.pattern; uint8
% header.pulseLengthInTime; single
% header.fLow; uint32
% header.fHigh; uint32
% header.gain; uint16
% header.sampleRate; uint32
% header.attenuation; uint8
% header.verticalRange; uint8
% header.noRec; uint16
% header.vPipe; uint16
errorMsg = 'Error reading header, Hit EOF';
% TODO: function should return a struct with information about
% the emitted pulse.
if( not(4 == h.version))
error('File version not supported');
end
% SEQ NO
[h.seqNo, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% DATA TYPE: shotData or noise
[h.dataType, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
% Pattern
[h.pattern, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
[h.pulseLengthInTime, count] = fread(fileId, 1,'single');
if count < 1
error(errorMsg);
end
% F LOW
[h.fLow, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% F HIGH
[h.fHigh, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% Gain
[h.gain, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
[h.sampleRate, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[h.attenuation, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
[h.verticalRange, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
[h.numRec, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
numberOfRec = h.numRec;
[h.vPipe, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
% Check number of transducer records
if h.numRec < 1
fclose(fileId);
error('File contain no records')
end
import ppPkg.TransducerMeasurement
% Set header info
header.setNo = h.seqNo;
header.pulsePattern = h.pattern;
header.pulseLength = h.sampleRate * h.pulseLengthInTime;
header.dataType = h.dataType;
header.fileVersion = h.version;
% TODO: need to define data types for each field
% startTimeRec single
% numberOfSamples uint16
% xPos double
% yPos double
% zPos double
% transducerId uint8
% samples single ( 4 bytes )
% TODO: Error handling:
% How do we avoid corrupted data while reading?
for n = 1:h.numRec;
numberOfSamples = 0;
% Create a new tm object.
tm(n) = TransducerMeasurement;
% Set common header data
tm(n).sampleRate = h.sampleRate;
tm(n).fLow = h.fLow;
tm(n).fHigh = h.fHigh;
% Set specific header data
[tm(n).date, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).fireTime, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).startTimeRec, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[numberOfSamples, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
%
[tm(n).xPos, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).yPos, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).zPos, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).uPos, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[tm(n).transducerId, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
% Read data
[tm(n).signal, count] = fread(fileId, numberOfSamples,'single');
if count < numberOfSamples
error(errorMsg);
end
end
end
|
github
|
ganlubbq/Signal-Processing-master
|
importDataVersion1.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@ImportHandler/importDataVersion1.m
| 4,718 |
utf_8
|
f31eb699831a09c3f8dd1447f150ea99
|
function [tm, numberOfRec, header] = importDataVersion1(obj, h, fileId)
% Read file version. Based on version call correct handler
% Expects that Labview data is little endian.
% Header format
% header.version uint8
% header.seqNo uint32
% header.dataType uint8
% header.pattern; uint16
% header.fLow; uint32
% header.fHigh; uint32
% header.gain; uint16
% header.sampleRate; uint32
% header.attenuation; uint16
% header.verticalRange; uint16
% header.noRec; uint16
% header.vPipe; uint16
% header.transducerType; uint16
errorMsg = 'Error reading header, Hit EOF';
if( not(obj.supportedFileVersion == h.version))
error('File version not supported');
end
% SEQ NO
[h.seqNo, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% DATA TYPE: shotData or noise
[h.dataType, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
% Pattern
[h.pattern, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
% F LOW
[h.fLow, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% F HIGH
[h.fHigh, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
% Gain
[h.gain, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
[h.sampleRate, count] = fread(fileId, 1,'uint32');
if count < 1
error(errorMsg);
end
[h.attenuation, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
[h.verticalRange, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
[h.numRec, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
numberOfRec = h.numRec;
[h.vPipe, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
% Check number of transducer records
if h.numRec < 1
fclose(fileId);
error('File contain no records')
end
import ppPkg.TransducerMeasurement
% Set header info
header.setNo = h.seqNo;
header.pulsePattern = h.pattern; % Default for version 1
header.pulseLength = 0; % Default for version 1
header.dataType = h.dataType;
header.fileVersion = h.version;
% TODO: need to define data types for each field
% transducerId uint16
% startTime uint16
% numSamples uint16
% xPos int16 ( single? )
% yPos int16
% zPos int16
% samples single ( 4 bytes )
% TODO: Error handling:
% How do we avoid corrupted data while reading?
for n = 1:h.numRec;
numberOfSamples = 0;
% Create a new tm object.
tm(n) = TransducerMeasurement;
% Set common header data
tm(n).sampleRate = h.sampleRate;
tm(n).fLow = h.fLow;
tm(n).fHigh = h.fHigh;
% Set specific header data
[tm(n).startTimeRec, count] = fread(fileId, 1,'single');
if count < 1
error(errorMsg);
end
[numberOfSamples, count] = fread(fileId, 1,'uint16');
if count < 1
error(errorMsg);
end
%
[tm(n).xPos, count] = fread(fileId, 1,'double');
if count < 1
error(errorMsg);
end
[tm(n).yPos, count] = fread(fileId, 1,'double');
if count < 1
error(errorMsg);
end
[tm(n).zPos, count] = fread(fileId, 1,'double');
if count < 1
error(errorMsg);
end
[tm(n).transducerId, count] = fread(fileId, 1,'uint8');
if count < 1
error(errorMsg);
end
% Read data
[tm(n).signal, count] = fread(fileId, numberOfSamples,'single');
if count < numberOfSamples
error(errorMsg);
end
end
end
|
github
|
ganlubbq/Signal-Processing-master
|
guaranteedEllipseFit.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/guaranteedEllipseFit.m
| 7,011 |
utf_8
|
b971e2ffc43ddbc2156a2ecc3cea081d
|
% Function: guaranteedEllipseFit
%
% This function implements the ellipse fitting algorithm described in
% Z.Szpak, W. Chojnacki and A. van den Hengel
% "Guaranteed Ellipse Fitting with the Sampson Distance"
% Proc. 12th European Conference on Computer Vision. ECCV
% Firenze,Italy, oct, 2012
%
% Parameters:
%
% t - an initial seed for parameters [a b c d e f] associated with
% the equation a x^2 + b x y + c y^2 + d x + e y + f = 0
% data_points - a 2xN matrix where N is the number of data points
%
% Returns:
%
% a length-6 vector [a b c d e f] representing the parameters of the equation
%
% a x^2 + b x y + c y^2 + d x + e y + f = 0
%
% with the additional result that b^2 - 4 a c < 0.
%
% See Also:
%
% compute_guaranteedellipse_estimates
% levenbergMarquardtStep
% lineSearchStep
%
% Zygmunt L. Szpak (c) 2012
% Last modified 25/7/2012
function [theta] = guaranteedEllipseFit(obj, t, data_points )
% various variable initialisations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% primary loop variable
keep_going = true;
% determines whether we use LineSearchStep or LevenbergMarquadtStep
struct.use_pseudoinverse = false;
% in some case a LevenbergMarquardtStep does not decrease the cost
% function and so the parameters (theta) are not updated
struct.theta_updated = false;
% damping parameter in LevenbergMarquadtStep
struct.lambda = 0.01;
% loop counter (matlab arrays start at index 1, not index 0)
struct.k = 1;
% used to modify the tradeoff between gradient descent and hessian based
% descent in LevenbergMarquadtStep
struct.damping_multiplier = 1.2;
% used in LineSearchStep
struct.gamma = 0.00005;
% number of data points
struct.numberOfPoints = length(data_points);
% barrier term that forces parameters to stay in elliptic region
Fprim = [0 0 2; 0 -1 0; 2 0 0];
struct.F = [Fprim zeros(3,3); zeros(3,3) zeros(3,3)];
struct.I = eye(6,6);
% homotopy parameters that weighs contribution of barrier term
struct.alpha = 1e-3;
% data points that we are going to fit an ellipse to
struct.data_points = data_points;
% various parameters that determine stopping criteria
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% maximum loop iterations
maxIter = 200;
% step-size tolerance
struct.tolDelta = 1e-7;
% cost tolerance
struct.tolCost = 1e-7;
% parameter tolerance
struct.tolTheta = 1e-7;
% various initial memory allocations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% allocate space for cost of each iteration
struct.cost = zeros(1,maxIter);
% allocate space for the parameters of each iteration
struct.t = zeros(6,maxIter);
% allocate space for the parameter direction of each iteration
struct.delta = zeros(6,maxIter);
% make parameter vector a unit norm vector for numerical stability
t = t / norm(t);
% store the parameters associated with the first iteration
struct.t(:,struct.k) = t;
% start with some random search direction (here we choose all 1's)
% we can initialise with anything we want, so long as the norm of the
% vector is not smaller than tolDeta. The initial search direction
% is not used in any way in the algorithm.
struct.delta(:,struct.k) = ones(6,1);
% main estimation loop
while (keep_going && struct.k < maxIter)
% allocate space for residuals (+1 to store barrier term)
struct.r = zeros(struct.numberOfPoints+1,1);
% allocate space for the jacobian matrix based on AML component
struct.jacobian_matrix = zeros(struct.numberOfPoints,6);
% allocate space for the jacobian matrix based on Barrier component
struct.jacobian_matrix_barrier = zeros(1,6);
% grab the current parameter estimates
t = struct.t(:,struct.k);
% residuals computed on data points
for i = 1:struct.numberOfPoints
m = data_points(:,i);
% transformed data point
ux_j = [m(1)^2 m(1)*m(2) m(2)^2 m(1) m(2) 1]';
% derivative of transformed data point
dux_j =[2*m(1) m(2) 0 1 0 0; 0 m(1) 2*m(2) 0 1 0]';
% outer product
A = ux_j * ux_j';
% use identity covs ...
B = dux_j * dux_j';
tBt = t' * B * t;
tAt = t' * A * t;
% AML cost for i'th data point
struct.r(i) = sqrt(tAt/tBt);
% derivative AML component
M = (A / tBt);
Xbits = B * ((tAt) / (tBt^2));
X = M - Xbits;
% gradient for AML cost function
grad = (X*t) / sqrt((tAt/tBt));
% build up jacobian matrix
struct.jacobian_matrix(i,:) = grad;
end
% Barrier term
tIt = t' * struct.I * t;
tFt = t' * struct.F * t;
% add the penalty term
struct.r(end) = struct.alpha*(tIt/tFt);
% Derivative barrier component
N = (struct.I / tFt);
Ybits = struct.F * ((tIt) / (tFt)^2);
Y = N-Ybits;
grad_penalty = 2*struct.alpha*Y*t;
struct.jacobian_matrix_barrier(1,:) = grad_penalty;
% Jacobian matrix after combining AML and barrier terms
struct.jacobian_matrix_full = [struct.jacobian_matrix ; struct.jacobian_matrix_barrier];
% approximate Hessian matrix
struct.H = struct.jacobian_matrix_full'* struct.jacobian_matrix_full;
% sum of squares cost for the current iteration
%struct.cost(k) = 0.5*(struct.r'*struct.r);
struct.cost(struct.k) = (struct.r'*struct.r);
% If we haven't overshot the barrier term then we use LevenbergMarquadt
% step
if (~struct.use_pseudoinverse)
struct = levenbergMarquardtStep(obj, struct);
else
struct = lineSearchStep(obj, struct);
end
% Check if the latest update overshot the barrier term
if (struct.t(:,struct.k+1)' * struct.F * struct.t(:,struct.k+1) <= 0)
% from now onwards we will only use lineSearchStep to ensure
% that we do not overshoot the barrier
struct.use_pseudoinverse = true;
struct.lambda = 0;
struct.t(:,struct.k+1) = struct.t(:,struct.k);
if (struct.k > 1)
struct.t(:,struct.k) = struct.t(:,struct.k-1);
end
1;
% Check for various stopping criteria to end the main loop
elseif (min(norm(struct.t(:,struct.k+1)-struct.t(:,struct.k)),norm(struct.t(:,struct.k+1)+struct.t(:,struct.k))) < struct.tolTheta && struct.theta_updated)
keep_going = false;
elseif (abs(struct.cost(struct.k) - struct.cost(struct.k+1)) < struct.tolCost && struct.theta_updated)
keep_going = false;
elseif (norm(struct.delta(:,struct.k+1)) < struct.tolDelta && struct.theta_updated)
keep_going = false;
end
struct.k = struct.k + 1;
end
1;
theta = struct.t(:,struct.k);
theta = theta / norm(theta);
end
|
github
|
ganlubbq/Signal-Processing-master
|
levenbergMarquardtStep.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/levenbergMarquardtStep.m
| 6,160 |
utf_8
|
1120ba6cf4b82e344e57b31cc3dac075
|
% Function: levenbergMarquardtStep
%
% This function is used in the main loop of guaranteedEllipseFit in the process
% of minimizing an approximate maximum likelihood cost function of an
% ellipse fit to data. It computes an update for the parameters
% representing the ellipse, using the method of Levenberg-Marquardt for
% non-linear optimisation.
% See: http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm
%
% Parameters:
%
% struct - a data structure containing various parameters
% needed for the optimisation process.
%
% Returns:
%
% the same data structure 'struct', except that relevant fields have been updated
%
% See Also:
%
% guaranteedEllipseFit
%
% Zygmunt L. Szpak (c) 2012
% Last modified 25/7/2012
function struct = levenbergMarquardtStep(obj, struct )
% extract variables from data structure
jacobian_matrix = struct.jacobian_matrix;
jacobian_matrix_barrier = struct.jacobian_matrix_barrier;
r = struct.r;
I = struct.I;
lambda = struct.lambda;
delta = struct.delta(struct.k);
damping_multiplier = struct.damping_multiplier;
F = struct.F;
I = struct.I;
t = struct.t(:,struct.k);
current_cost = struct.cost(struct.k);
alpha = struct.alpha;
data_points = struct.data_points;
numberOfPoints = struct.numberOfPoints;
% compute two potential updates for theta based on different weightings of
% the identity matrix.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% jacobian (vector), r(t)'d/dtheta[r(t)]
jacob = [jacobian_matrix ; jacobian_matrix_barrier]'*r;
%tIt = t' * I * t;
tFt = t' * F * t;
% We solve for the new update direction in a numerically careful manner
% If we didn't worry about numerical stability then we would compute
% the first new search direction like this:
% update_a = - (H+lambda*I)\jacob;
% But close to the barrier between ellipses and hyperbolas we may
% experience numerical conditioning problems due to the nature of the
% barrier term itself. Hence we perform the calculation in a
% numerically more stable way with
Z_a = [((jacobian_matrix'*jacobian_matrix) + lambda*I) tFt^4*(jacobian_matrix_barrier'*jacobian_matrix_barrier) ; I -(tFt)^4*I];
zz_a = -[jacob ; zeros(6,1)];
update_a = Z_a\zz_a;
% drop the nuisance parameter components
update_a = update_a(1:6);
% In a similar fashion, the second potential search direction could be
% computed like this:
% update_b = - (H+(lambda/v)*I)\jacob
% but instead we computed it with
Z_b = [((jacobian_matrix'*jacobian_matrix) + (lambda/damping_multiplier)*I) tFt^4*(jacobian_matrix_barrier'*jacobian_matrix_barrier) ; I -(tFt)^4*I];
zz_b = -[jacob ; zeros(6,1)];
update_b = Z_b\zz_b;
% drop the nuisance parameter components
update_b = update_b(1:6);
% the potential new parameters are then
t_potential_a = t + update_a;
t_potential_b = t + update_b;
% compute new residuals and costs based on these updates
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% residuals computed on data points
cost_a = 0;
cost_b = 0;
for i = 1:numberOfPoints
m = data_points(:,i);
% transformed data point
ux_j = [m(1)^2 m(1)*m(2) m(2)^2 m(1) m(2) 1]';
% derivative of transformed data point
dux_j =[2*m(1) m(2) 0 1 0 0; 0 m(1) 2*m(2) 0 1 0]';
% outer product
A = ux_j * ux_j';
% use identity covs ...
B = dux_j * dux_j';
t_aBt_a = t_potential_a' * B * t_potential_a;
t_aAt_a = t_potential_a' * A * t_potential_a;
t_bBt_b = t_potential_b' * B * t_potential_b;
t_bAt_b = t_potential_b' * A * t_potential_b;
% AML cost for i'th data point
cost_a = cost_a + t_aAt_a/t_aBt_a ;
cost_b = cost_b + t_bAt_b/t_bBt_b ;
end
% Barrier term
t_aIt_a = t_potential_a' * I * t_potential_a;
t_aFt_a = t_potential_a' * F * t_potential_a;
t_bIt_b = t_potential_b' * I * t_potential_b;
t_bFt_b = t_potential_b' * F * t_potential_b;
% add the barrier term
cost_a = cost_a + (alpha*(t_aIt_a/t_aFt_a))^2;
cost_b = cost_b + (alpha*(t_bIt_b/t_bFt_b))^2;
% determine appropriate damping and if possible select an update
if (cost_a >= current_cost && cost_b >= current_cost)
% neither update reduced the cost
struct.theta_updated = false;
% no change in the cost
struct.cost(struct.k+1) = current_cost;
% no change in parameters
struct.t(:,struct.k+1) = t;
% no changes in step direction
struct.delta(:,struct.k+1) = delta;
% next iteration add more Identity matrix
struct.lambda = lambda * damping_multiplier;
elseif (cost_b < current_cost)
% update 'b' reduced the cost function
struct.theta_updated = true;
% store the new cost
struct.cost(struct.k+1) = cost_b;
% choose update 'b'
struct.t(:,struct.k+1) = t_potential_b / norm(t_potential_b);
% store the step direction
struct.delta(:,struct.k+1) = update_b';
% next iteration add less Identity matrix
struct.lambda = lambda / damping_multiplier;
else
% update 'a' reduced the cost function
struct.theta_updated = true;
% store the new cost
struct.cost(struct.k+1) = cost_a;
% choose update 'a'
struct.t(:,struct.k+1) = t_potential_a / norm(t_potential_a);
% store the step direction
struct.delta(:,struct.k+1) = update_a';
% keep the same damping for the next iteration
struct.lambda = lambda;
end
% return a data structure containing all the updates
struct;
end
|
github
|
ganlubbq/Signal-Processing-master
|
compute_directellipse_estimates.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/compute_directellipse_estimates.m
| 2,286 |
utf_8
|
f7046187cec5532b1043fdba910dfbbe
|
% Function: compute_directellipse_estimates
%
% This function is a wrapper for the numerically stable direct ellipse fit
% due to
%
% R. Halif and J. Flusser
% "Numerically stable direct least squares fitting of ellipses"
% Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG '98
% Czech Republic,125--132, feb, 1998
%
% which is a modificaiton of
%
% A. W. Fitzgibbon, M. Pilu, R. B. Fisher
% "Direct Least Squares Fitting of Ellipses"
% IEEE Trans. PAMI, Vol. 21, pages 476-480 (1999)
%
% It first shifts all the data points to a new
% coordinate system so that the origin of the coordinate system is at the
% center of the data points, and then scales all data points so that they
% lie more or less within a unit box. It is within this transformed
% coordinate system that the ellipse is estimated. The resulting ellipse
% parameters are then transformed back to the original data space.
%
% Parameters:
%
% dataPts - a 2xN matrix where N is the number of data points
%
% Returns:
%
% a length-6 vector [a b c d e f] representing the parameters of the equation
%
% a x^2 + b x y + c y^2 + d x + e y + f = 0
%
% with the additional result that b^2 - 4 a c < 0.
%
% See Also:
%
% compute_guaranteedellipse_estimates
%
% Zygmunt L. Szpak (c) 2012
% Last modified 25/7/2012
function [theta] = compute_directellipse_estimates(obj, data_points)
% grab data points
x = data_points;
n = length(x);
% Need homogenous coordinates for normalize_transform function
x = [ x; ones( 1, n ) ];
% hartley normalise the data
[x, T] = normalise2dpts(obj, x);
% Direct Ellipse Fit
%-----------------------------------------------------
normalised_data = x;
theta = direct_ellipse_fit(obj, normalised_data);
theta = theta / norm(theta);
%-----------------------------------------------------
a = theta(1); b = theta(2) ; c = theta(3) ; d = theta(4) ; e = theta(5); f = theta(6);
C = [a b/2 d/2 ; b/2 c e/2; d/2 e/2 f];
% denormalise C
C = T'*C*T;
aa = C(1,1);
bb = C(1,2)*2;
dd = C(1,3)*2;
cc = C(2,2);
ee = C(2,3)*2;
ff = C(3,3);
theta = [aa bb cc dd ee ff]';
theta = theta / norm(theta);
end
|
github
|
ganlubbq/Signal-Processing-master
|
lineSearchStep.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/lineSearchStep.m
| 4,119 |
utf_8
|
2a62d73c853d11f08b5e04bb4cc25115
|
% Function: lineSearchStep
%
% This function is used in the main loop of guaranteedEllipseFit in the process
% of minimizing an approximate maximum likelihood cost function of an
% ellipse fit to data. It computes an update for the parameters
% representing the ellipse, using the pseudo-inverse of a Gauss-Newton
% approximation of the Hessian matrix. It then performs an inexact
% line search to determine how far to move along the update direction
% so that the resulting fit is still an ellipse.
%
% Parameters:
%
% struct - a data structure containing various parameters
% needed for the optimisation process.
%
% Returns:
%
% the same data structure 'struct', except that relevant fields have been updated
%
% See Also:
%
% guaranteedEllipseFit
%
% Zygmunt L. Szpak (c) 2012
% Last modified 25/7/2012
function struct = lineSearchStep( obj, struct )
% extract variables from data structure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
t = struct.t(:,struct.k);
jacobian_matrix = struct.jacobian_matrix;
jacobian_matrix_barrier = struct.jacobian_matrix_barrier;
r = struct.r;
I = struct.I;
lambda = struct.lambda;
delta = struct.delta(struct.k);
tolDelta = struct.tolDelta;
damping_multiplier = struct.damping_multiplier;
F = struct.F;
I = struct.I;
current_cost = struct.cost(struct.k);
data_points = struct.data_points;
alpha = struct.alpha;
gamma = struct.gamma;
numberOfPoints = struct.numberOfPoints;
% jacobian (vector), r(t)'d/dtheta[r(t)]
jacob = [jacobian_matrix ; jacobian_matrix_barrier]'*r;
tFt = t' * F * t;
% We solve for the new update direction in a numerically careful manner
% If we didn't worry about numerical stability then we would compute
% the first new search direction like this:
% update = - pinv(H)*jacob;
% But close to the barrier between ellipses and hyperbolas we may
% experience numerical conditioning problems due to the nature of the
% barrier term itself. Hence we perform the calculation in a
% numerically more stable way with
Z = [((jacobian_matrix'*jacobian_matrix) + lambda*I) tFt^4*(jacobian_matrix_barrier'*jacobian_matrix_barrier) ; I -(tFt)^4*I];
zz = -[jacob ; zeros(6,1)];
update = pinv(Z,1e-20)*zz;
% drop the nuisance parameter components
update = update(1:6);
% there is no repeat...until construct so we use a while-do
frac = 0.5;
while true
% compute potential update
t_potential = t + frac*update;
delta = frac*update;
% halve the step-size
frac = frac / 2 ;
% compute new residuals on data points
cost = 0;
for i = 1:numberOfPoints
m = data_points(:,i);
% transformed data point
ux_j = [m(1)^2 m(1)*m(2) m(2)^2 m(1) m(2) 1]';
% derivative of transformed data point
dux_j =[2*m(1) m(2) 0 1 0 0; 0 m(1) 2*m(2) 0 1 0]';
% outer product
A = ux_j * ux_j';
% use identity covs ...
B = dux_j * dux_j';
tBt = t_potential' * B * t_potential;
tAt = t_potential' * A * t_potential;
% AML cost for i'th data point
cost = cost + tAt/tBt ;
end
% Barrier term
tIt = t_potential' * I * t_potential;
tFt = t_potential' * F * t_potential;
% add the barrier term
cost = cost + (alpha*(tIt/tFt))^2;
% check to see if cost function was sufficiently decreased, and whether
% the estimate is still an ellipse. Additonally, if the step size
% becomes too small we stop.
if (t_potential'* F * t_potential > 0 && (cost < (1-frac*gamma)*current_cost) || norm(delta) < tolDelta)
break;
end
end
struct.theta_update = true;
struct.t(:,struct.k+1) = t_potential / norm(t_potential);
struct.delta(:,struct.k+1) = delta;
struct.cost(struct.k+1) = cost;
% return a data structure with all the updates
struct;
end
|
github
|
ganlubbq/Signal-Processing-master
|
direct_ellipse_fit.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/direct_ellipse_fit.m
| 1,238 |
utf_8
|
b911503812da4726e5ba06646fbee602
|
% This code is an implementation of the following paper
%
% R. Halif and J. Flusser
% Numerically stable direct least squares fitting of ellipses
% Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG '98
% Czech Republic,125--132, feb, 1998
function a = direct_ellipse_fit(obj, data)
x = data(1,:)';
y = data(2,:)';
D1 = [x .^ 2, x .* y, y .^ 2]; % quadratic part of the design matrix
D2 = [x, y, ones(size(x))]; % linear part of the design matrix
S1 = D1' * D1; % quadratic part of the scatter matrix
S2 = D1' * D2; % combined part of the scatter matrix
S3 = D2' * D2; % linear part of the scatter matrix
T = - inv(S3) * S2'; % for getting a2 from a1
M = S1 + S2 * T; % reduce scatter matrix
M = [M(3, :) ./2; - M(2, :); M(1, :) ./2]; % premultiply by inv(C1)
[evec, evalue] = eig(M); % solve eigensystem
cond = 4 * evec(1, :) .* evec(3, :) - evec(2, :) .^ 2; % evaluate a'Ca
al = evec(:, find(cond > 0)); % eigenvector for min. pos. eigenvalue
a = [al; T * al]; % ellipse coefficients
a = a/norm(a);
end
|
github
|
ganlubbq/Signal-Processing-master
|
compute_guaranteedellipse_estimates.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/compute_guaranteedellipse_estimates.m
| 2,809 |
utf_8
|
b8db968f07ea32b64e821728f52ac58d
|
% Function: compute_guaranteedellipse_estimates
%
% This function is a wrapper for an approximate maximum likelihood guaranteed
% ellipse fit due to
%
% Z.Szpak, W. Chojnacki and A. van den Hengel
% "Guaranteed Ellipse Fitting with the Sampson Distance"
% Proc. 12th European Conference on Computer Vision. ECCV
% Firenze,Italy, oct, 2012
%
% It first shifts all the data points to a new coordinate system so that
% the origin of the coordinate system is at the center of the data points,
% and then scales all data points so that they lie more or less within
% a unit box. It is within this transformed coordinate system that the
% ellipse is estimated. Since the approximate maximum likelihood method
% is an iterative scheme, it requires an initial seed for the parameters.
% The seed is taken to be the direct ellipse fit due to
%
% R. Halif and J. Flusser
% "Numerically stable direct least squares fitting of ellipses"
% Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG '98
% Czech Republic,125--132, feb, 1998
%
% Their work is a numerically stable version of
%
% A. W. Fitzgibbon, M. Pilu, R. B. Fisher
% "Direct Least Squares Fitting of Ellipses"
% IEEE Trans. PAMI, Vol. 21, pages 476-480 (1999)
%
% The final ellipse parameters estimates are transformed
% back to the original data space.
%
% Parameters:
%
% dataPts - a 2xN matrix where N is the number of data points
%
% Returns:
%
% a length-6 vector [a b c d e f] representing the parameters of the equation
%
% a x^2 + b x y + c y^2 + d x + e y + f = 0
%
% with the additional result that b^2 - 4 a c < 0.
%
% See Also:
%
% compute_directellipse_estimates
% guaranteedEllipseFit
%
% Zygmunt L. Szpak (c) 2012
% Last modified 25/7/2012
function [theta] = compute_guaranteedellipse_estimates(obj, data_points)
x = data_points;
n = length(x);
% Need homogenous coordinates for normalize_transform function
x = [ x; ones( 1, n ) ];
% hartley normalise the data
[x, T] = normalise2dpts(obj, x);
% Flusser Fit
%-----------------------------------------------------
normalised_data = x;
theta = direct_ellipse_fit(obj, normalised_data);
theta = theta / norm(theta);
%-----------------------------------------------------
theta = guaranteedEllipseFit(obj, theta, x );
theta = theta/norm(theta);
a = theta(1); b = theta(2) ; c = theta(3) ; d = theta(4) ; e = theta(5); f = theta(6);
C = [a b/2 d/2 ; b/2 c e/2; d/2 e/2 f];
% denormalise C
C = T'*C*T;
aa = C(1,1);
bb = C(1,2)*2;
dd = C(1,3)*2;
cc = C(2,2);
ee = C(2,3)*2;
ff = C(3,3);
theta = [aa bb cc dd ee ff]';
theta = theta / norm(theta);
end
|
github
|
ganlubbq/Signal-Processing-master
|
normalise2dpts.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/+ppPkg/@EllipseFit/normalise2dpts.m
| 2,435 |
utf_8
|
69ae603cd7c0fa17b28fd805ea19cfb4
|
% NORMALISE2DPTS - normalises 2D homogeneous points
%
% Function translates and normalises a set of 2D homogeneous points
% so that their centroid is at the origin and their mean distance from
% the origin is sqrt(2). This process typically improves the
% conditioning of any equations used to solve homographies, fundamental
% matrices etc.
%
% Usage: [newpts, T] = normalise2dpts(pts)
%
% Argument:
% pts - 3xN array of 2D homogeneous coordinates
%
% Returns:
% newpts - 3xN array of transformed 2D homogeneous coordinates. The
% scaling parameter is normalised to 1 unless the point is at
% infinity.
% T - The 3x3 transformation matrix, newpts = T*pts
%
% If there are some points at infinity the normalisation transform
% is calculated using just the finite points. Being a scaling and
% translating transform this will not affect the points at infinity.
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% May 2003 - Original version
% February 2004 - Modified to deal with points at infinity.
% December 2008 - meandist calculation modified to work with Octave 3.0.1
% (thanks to Ron Parr)
function [newpts, T] = normalise2dpts(obj, pts)
if size(pts,1) ~= 3
error('pts must be 3xN');
end
% Find the indices of the points that are not at infinity
finiteind = find(abs(pts(3,:)) > eps);
if length(finiteind) ~= size(pts,2)
warning('Some points are at infinity');
end
% For the finite points ensure homogeneous coords have scale of 1
pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind);
pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind);
pts(3,finiteind) = 1;
c = mean(pts(1:2,finiteind)')'; % Centroid of finite points
newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.
newp(2,finiteind) = pts(2,finiteind)-c(2);
dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2);
meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1
scale = sqrt(2)/meandist;
T = [scale 0 -scale*c(1)
0 scale -scale*c(2)
0 0 1 ];
newpts = T*pts;
|
github
|
ganlubbq/Signal-Processing-master
|
processHydrophoneDataLinearFromCsv.m
|
.m
|
Signal-Processing-master/release_version_0.9_Fraunhofer/matlab/labTestScripts/processHydrophoneDataLinearFromCsv.m
| 3,820 |
utf_8
|
3a2bc5cc40fec8ebd09584dfa8a894f7
|
function [ meanArray ] = processHydrophoneDataLinearFromCsv( folderName )
%% Import data from text file.
% Script for importing data from the following text file:
%
% D:\scan\hydrophone_scans\CSV\4MHz\4M_20.csv
%
% To extend the code to different selected data or a different text file,
% generate a function instead of a script.
% Auto-generated by MATLAB on 2016/08/05 08:41:02
%% Initialize variables.
%filename = 'D:\scan\hydrophone_scans\CSV\4MHz\4M_20.csv';
[scan, numScan] = importDataFromCsv(folderName);
%% Use moving average filter to smooth the data points
N = 8;
b = (1/N)*ones(1, N);
a = 1
for index = 1:numScan
scanFilt(index,:) = filtfilt(b, a, scan(index,:));
end
%%
% figure
% plot(scanFilt(5,:))
% hold on
% plot(scan(5,:))
% grid on
for index = 1:numScan
signalSegment = scanFilt(index,8000:end);
peakDistance = 200;
% Calculate 6 max and min peaks for signal
[maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance);
% Sum max and min to calculate "peak2peak" value
peak2peakArray = maxPeaks - minPeaks;
% Calculate mean
meanArray(index) = mean(peak2peakArray);
end
end
function [maxPeaks, locsMax, minPeaks, locsMin] = findMaxAndMinPeaks(signalSegment, peakDistance)
peakDistanceModified = peakDistance;
signalSegment_interp = signalSegment;
[pksMax, locsMax] = findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
%findpeaks(signalSegment_interp,'MinPeakDistance', peakDistanceModified);
[pksMin, locsMin] = findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
%findpeaks(-signalSegment_interp,'MinPeakDistance', peakDistanceModified);
% Only keep peaks 3 to 8
if((length(pksMax) >= 17 && (length(pksMin) >= 17)))
maxPeaks = pksMax(5:12);
minPeaks = -pksMin(5:12);
locsMax = locsMax(5:12);
locsMin = locsMin(5:12);
elseif(length(pksMax) > 2)
error('Error Should find more than 17 peaks')
lengthMax = length(pksMax);
lengthMin = length(pksMin);
if(lengthMax > lengthMin)
maxLength = lengthMin;
else
maxLength = lengthMax;
end
maxPeaks = pksMax(1:maxLength);
minPeaks = -pksMin(1:maxLength);
locsMax = locsMax(1:maxLength);
locsMin = locsMin(1:maxLength);
else
error('Error in finding peaks')
end
end
function [scan, numScan] = importDataFromCsv(folderName)
delimiter = '';
startRow = 2;
%%
listing = dir(folderName);
% Read data filename into dataFiles cell array
fileIndex = 1;
for index = 1:size(listing,1)
if(0 == listing(index).isdir)
dataFiles(fileIndex) = cellstr(listing(index).name);
fileIndex = fileIndex + 1;
end
end
dataFiles = sort(dataFiles');
%%
%% Format string for each line of text:
% column1: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%[^\n\r]';
scan = zeros(length(dataFiles), 12500);
for index = 1:length(dataFiles)
filename = char(strcat('D:\scan\hydrophone_scans\CSV\4MHz\',dataFiles(index)));
fileID = fopen(filename,'r');
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines' ,startRow-1, 'ReturnOnError', false);
fclose(fileID);
scan(index,:) = dataArray{:, 1};
end
numScan = length(dataFiles);
end
|
github
|
sjgershm/exploration-master
|
barerrorbar.m
|
.m
|
exploration-master/util/barerrorbar.m
| 6,797 |
utf_8
|
75d58de8b06685309614932e0d5f14f9
|
function varargout = barerrorbar(varargin)
% BARERRORBAR Create a bar plot with error bars. BARERRORBAR() uses the
% MATLAB functions BAR() and ERRORBAR() and changes the 'XData' property
% of the errorbar plot so that the error bars are plotted at the center
% of each bar. This does not support "stack" bar plots.
%
% Syntax: varargout = barerrorbar(varargin)
%
% Inputs:
% Method 1: Cell array method
% varargin{1} - A cell array containing all of the inputs to be fed
% to bar().
% varargin{2} - A cell array containing all of the inputs to be fed
% to errorbar().
% Method 2: Simple Method
% varargin{1} - The data to be plotted by bar().
% varargin{2} - The E input to errorbar().
%
% Outputs:
% varargout{1} - The handle to the bar plot.
% varargout{2} - The handle to the errorbar plot.
%
% Examples:
% x = 0.2*randn(3,4,100) + 1;
% xMeans = mean(x,3);
% xMeansConf = repmat(2*0.2/10,3,4);
% xMeansL = repmat(3*0.2/10,3,4);
% xMeansU = repmat(4*0.2/10,3,4);
%
% figure
% barerrorbar(xMeans,xMeansConf);
%
% figure
% barerrorbar({3:5,xMeans,'m'}, {repmat((3:5)',1,4),xMeans, xMeansL,xMeansU,'bx'});
%
% figure
% barerrorbar({3:5,xMeans,'k'}, {repmat((3:5)',1,4),xMeans, xMeansL,xMeansU,'bx'});
% hold on
% barerrorbar({7:9,xMeans}, {repmat((7:9)',1,4),xMeans, 2*xMeansL,4*xMeansU,'d','color',[0.7 0.7 0.7]});
%
% Other m-files required: none
% Subfunctions: interpretinputs
% MAT-files required: none
%
% See also: bar.m errorbar.m
% Author: Kenneth D. Morton Jr. and J. Simeon Stohl
% Revised by: Kenneth D. Morton Jr.
% Duke University, Department of Electrical and Computer Engineering
% Email Address: [email protected]
% Created: 07-July-2005
% Last revision: 06-January-2006
% Check if hold is on
startedWithHoldOn = ishold;
[data, barInputs, errorbarInputs] = interpinputs(varargin);
% Create the bar plot and keep the handles for later use.
barHandles = bar(barInputs{:});
barHandlesStruct = get(barHandles);
if ~startedWithHoldOn
hold on
else
% Hold is already on so we need to check the XTick and save them.
oldXTicks = get(gca,'XTick');
oldXTickLabels = get(gca,'XTickLabel');
end
% Find out the bar width which is dependent on the number of bar sets and
% the number of bars in each set.
barWidth = barHandlesStruct(1).BarWidth;
errorbarHandles = errorbar(errorbarInputs{:});
% The crazy stuff to find the bar centers. Some of it is how bar.m does it.
[nGroups, nBarsPerGroup] = size(data);
for iBpg = 1:nBarsPerGroup
groupMembership(:,iBpg) = barHandlesStruct(iBpg).XData;
end
groupWidth = min(0.8, nBarsPerGroup/(nBarsPerGroup+1.5));
groupLocs = groupMembership(:,1);
distanceToNearestGroup = zeros(1,nGroups);
if nGroups > 1
for iGroup = 1:nGroups
distanceToNearestGroup(iGroup) = ...
min(abs(groupLocs(iGroup)-...
groupLocs(groupLocs~=groupLocs(iGroup))));
end
end
groupWidth = groupWidth*min(distanceToNearestGroup);
barGap = (nGroups - 1) * groupWidth / (nGroups-1) / nBarsPerGroup;
almostCenters = (0:nBarsPerGroup-1)'.*barGap - 0.5*barGap*nBarsPerGroup;
relativeCenters = almostCenters + mean([(1-barWidth)/2.*barGap; (1+barWidth)/2.*barGap]);
centers = repmat(relativeCenters',nGroups,1) + groupMembership;
% Change the XData of the errorbars to be at our bar centers.
for iBpg = 1:nBarsPerGroup
set(errorbarHandles(iBpg),'XData',centers(:,iBpg));
end
% Turn hold off if it wasn't on to begin with
if ~startedWithHoldOn
hold off
else
% Set the XTick and XTickLabels to inlcude the old and new information.
newXTicks = groupMembership(:,1);
newXTickLabels = num2str(newXTicks);
set(gca,'XTick',sort(unique([oldXTicks newXTicks'])));
if ischar(oldXTickLabels)
% If this is a string then they are probably default so update with
% the new additions.
set(gca,'XTickLabel',[oldXTickLabels; newXTickLabels]);
end
end
% Prepare both sets of handles as outputs, if requested.
if nargout > 0
varargout{1} = barHandles;
end
if nargout > 1
varargout{2} = errorbarHandles;
end
colormap(linspecer);
% End of barerrorbar()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data, barInputs, errorbarInputs] = interpinputs(inCell)
% Interperate the inputs so that they can be used in barerrorbar(). Make
% two different possibilities based on the type of inputs.
% Method 1: Cell array method.
% varargin{1} - A cell array containing all of the inputs to be fed
% to bar().
% varargin{2} - A cell array containing all of the inputs to be fed
% to errorbar().
% Method 2: Simple Method
% varargin{1} - The data to be plotted by bar().
% varargin{2} - The data to be plotted by errorbar().
if iscell(inCell{1})
% We have entered Method 1
barInputs = inCell{1};
if length(barInputs) > 2
data = barInputs{2};
elseif length(barInputs) < 2
data = barInputs{1};
elseif length(barInputs) == 2
if ischar(barInputs{2})
data = barInputs{1};
else
data = barInputs{2};
end
end
else
barInputs = {inCell{1}};
data = inCell{1};
nRows = size(barInputs{1},1);
if nRows == 1
barInputs{1} = barInputs{1}';
end
end
%Plot black dot errorbars for the default.
if iscell(inCell{2})
errorbarInputs = inCell{2};
else
errorbarInputs = {inCell{1}, inCell{2}, 'k.','LineWidth',2};
end
if length(inCell) > 2
error(['Too many input arguments.' ...
' Try using the cell array input method.']);
end
% Search for the 'stack' option in the bar inputs
for iBI = 1:length(barInputs)
if ischar(barInputs{iBI})
if strcmpi(barInputs{iBI},'stack')
error('barerrorbar() does not support "stack" bar plots.')
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.