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
|
sunhongfu/scripts-master
|
jpg_write.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/jpg_write.m
| 898 |
utf_8
|
2ec215dcac320f380bff814c62d09c54
|
function jpg_write(x, file, varargin)
%function jpg_write(x, file, varargin)
arg.clim = [];
arg.qual = 99;
arg = vararg_pair(arg, varargin);
if isempty(arg.clim)
arg.clim = minmax(x);
end
x = floor(255*(x-arg.clim(1))/(arg.clim(2)-arg.clim(1)));
x = max(x,0);
x = min(x,255);
x = uint8(x);
x = x.';
file = file_check(file, '.jpg');
if ~isempty(file)
imwrite(x, file, 'quality', arg.qual)
end
function file = file_check(base, suff)
keepask = 1;
while (keepask)
keepask = 0;
file = [base suff];
if exist(file, 'file')
prompt = sprintf('overwrite figure "%s"? y/a/[n]: ', file);
else
prompt = sprintf('print new figure "%s"? y/n: ', file);
end
ans = input(prompt, 's');
% alternate filename
if streq(ans, 'a')
t = sprintf('enter alternate basename (no %s): ', suff);
base = input(t, 's');
keepask = 1;
end
end
if ~isempty(ans) && ans(1) == 'y'
return
end
file = [];
|
github
|
sunhongfu/scripts-master
|
xtick.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/xtick.m
| 482 |
utf_8
|
cf4f7a0e298bed9f6e9808cbf5baafd2
|
function xtick(arg)
%|function xtick(arg)
%| set axis xticks to just end points
if ~nargin
lim = get(gca, 'xlim');
if lim(1) == -lim(2)
lim = [lim(1) 0 lim(2)];
end
set(gca, 'xtick', lim)
elseif nargin == 1
if ischar(arg)
switch arg
case 'off'
set(gca, 'xtick', [])
set(gca, 'xticklabel', [])
case 'test'
xtick_test
otherwise
fail 'bug'
end
else
set(gca, 'xtick', sort(arg))
end
else
error arg
end
function xtick_test
im clf, im(eye(7))
%xtick
|
github
|
sunhongfu/scripts-master
|
jf_mip3.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/jf_mip3.m
| 1,511 |
utf_8
|
ee392bfcbeae0ee1437753a1d74904a1
|
function out = jf_mip3(vol, varargin)
%|function out = jf_mip3(vol, varargin)
%|
%| create a MIP (maximum intensity projection) mosaic from a 3D volume
%| in
%| vol [] [nx ny nz] 3d
%| option
%| 'show' bool default: 1 if no output, 0 else
%| 'type' char 'mip' (default) | 'sum' | 'mid'
%| out
%| out [] [nx+nz ny+nz] 2d
%|
%| if no output, then display it using im()
%|
%| Copyright 2010-02-22, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(vol, 'test'), jf_mip3_test, return, end
arg.show = ~nargout;
arg.type = 'mip';
arg = vararg_pair(arg, varargin);
if ndims(vol) > 3, fail '3D only', end
switch arg.type
case 'mip'
fun = @(v,d) jf_mip3_max(v, d);
case 'sum'
fun = @(v,d) sum(v, d);
case 'mid'
pn = jf_protected_names;
fun = @(v,d) pn.mid3(v, d);
otherwise
fail('unknown type %s', arg.type)
end
xy = fun(vol, 3); % [nx ny]
xz = fun(vol, 2); % [nx nz]
yz = fun(vol, 1); % [ny nz]
xz = permute(xz, [1 3 2]);
zy = permute(yz, [2 3 1])';
nz = size(vol,3);
out = [ xy, xz;
zy, zeros(nz,nz)];
if arg.show
im(out)
end
if ~nargout
clear out
end
function out = jf_mip3_max(in, d)
if isreal(in)
out = max(in, [], d);
else
out = max(abs(in), [], d);
end
function jf_mip3_test
ig = image_geom('nx', 64, 'ny', 60, 'nz', 32, 'dx', 1);
vol = ellipsoid_im(ig, [0 0 0 ig.nx/3 ig.ny/4 ig.nz/3 20 0 1], 'oversample', 2);
mip = jf_mip3(vol);
%im(vol), prompt
im(mip), prompt
jf_mip3(vol, 'type', 'sum')
jf_mip3(vol, 'type', 'mid')
|
github
|
sunhongfu/scripts-master
|
subplot_stack.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/subplot_stack.m
| 1,219 |
utf_8
|
d36068356f2b48aac3c75d89a4584eac
|
function subplot_stack(x, ys, str_title, colors)
%function subplot_stack(x, ys, str_title, colors)
% a tight stack of subplots to show L signal components
% in
% x [N,1]
% ys [N,L] or ?
if nargin == 1 & streq(x, 'test'), subplot_stack_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
if ~isvar('colors') | isempty(colors), colors = {'c', 'y'}; end
if ~isvar('str_title') | isempty(str_title)
str_title = '';
end
if ~iscell(ys)
ys = {ys};
end
L = size(ys{1},2);
apos = get(gca, 'position'); % current axes position
for ll=1:L
% pos = [0.1 0.1+0.8/L*(L-ll) 0.8 0.8/L];
pos = [apos(1) apos(2)+apos(4)/L*(L-ll) apos(3) apos(4)/L];
subplot('position', pos) % l b w h
for ip=1:length(ys)
plot( x, real(ys{ip}(:,ll)), colors{1+2*(ip-1)}, ...
x, imag(ys{ip}(:,ll)), colors{2+2*(ip-1)})
if ip == 1, hold on, end
end
hold off
axis tight
ytick(0), set(gca, 'yticklabel', '')
fontsize = 10;
fontweight = 'normal';
texts(1.02, 0.8, sprintf('%d.', ll), ...
'fontsize', fontsize, 'fontweight', fontweight)
if ll==1, title(str_title), end
if ll<L
xtick off
end
end
function subplot_stack_test
x = linspace(0,1,101)';
y = exp(2i*pi*x*[1:5]);
clf, subplot(121)
subplot_stack(x, y)
|
github
|
sunhongfu/scripts-master
|
movie2.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/movie2.m
| 2,123 |
utf_8
|
cbbaf61f83e762896df3850e8d12ae20
|
function [mov avi] = movie2(x, varargin)
%|function [mov avi] = movie2(x, [options])
%| in
%| x [nx ny nz] sequence of 2d frames
%| option
%| clim "color" limits default: minmax(x)
%| file name of avi file default: [test_dir 'tmp.avi']
%| cmap colormap default: gray(256)
%| fps frames per second in avifile default: 15
%| out
%| mov movie object
%| avi avifile object
%| make matlab movie from 3d array (e.g., iterations)
%| make avi movie from 3d array (e.g., iterations)
%|
%| If no output arguments, then display movie
%| Copyright Aug 2000, Jeff Fessler, University of Michigan
if nargin < 1, help(mfilename), error(mfilename), end
if streq(x, 'test'), movie2_test, return, end
arg.clim = [];
arg.file = [test_dir 'tmp.avi'];
arg.cmap = gray(256);
arg.fps = 15; % default for avifile
arg = vararg_pair(arg, varargin);
if isempty(arg.clim)
arg.clim = minmax(x);
end
%clf
%fig = figure;
%fig = gcf;
%set(fig, 'DoubleBuffer', 'on');
%set(gca, 'NextPlot', 'replace', 'Visible', 'off')
x = max(x, arg.clim(1));
x = min(x, arg.clim(2));
scale = 255. / single(arg.clim(2) - arg.clim(1));
x = scale * single(x - arg.clim(1)); % need single for uint16 inputs
avi = avifile(arg.file, 'fps', arg.fps);
F.colormap = [];
nz = size(x,3);
for iz=1:nz
ticker(mfilename, iz, nz)
% im(x(:,:,iz), clim, sprintf('%d', iz-1))
% drawnow
% F = getframe(gca);
t = x(:,:,iz)';
t = uint8(t);
mov(iz) = im2frame(t, arg.cmap);
F.cdata = repmat(t, [1 1 3]);
avi = addframe(avi,F);
end
avi = close(avi);
if ~nargout
if im
movie(mov, 2);
end
clear mov avi
end
%
% movie2_test()
%
function movie2_test
down = 30;
cg = ct_geom('fan', 'ns', round(888/down), 'nt', 64, 'na', round(984/down), ...
'ds', 1.0*down, 'down', 1, ... % only downsample s and beta
'offset_s', 0.25, ... % quarter detector
'offset_t', 0.0, ...
'ztrans', 1*300, ... % stress test with helix
'dsd', 949, 'dod', 408, 'dfs', inf); % flat detector
% 'dsd', 949, 'dod', 408, 'dfs', 0); % 3rd gen CT
ell = [0*50 0*50 0*50 200 100 100 90 0 10];
proj = ellipsoid_proj(cg, ell, 'oversample', 2);
[mov avi] = movie2(proj);
if im
movie(mov)
% keyboard
end
|
github
|
sunhongfu/scripts-master
|
yaxis_pi.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/yaxis_pi.m
| 1,124 |
utf_8
|
e129c4b8ad40edc7a47f5b0cab53ebd6
|
function yaxis_pi(varargin)
%function yaxis_pi(varargin)
% label y axis with various forms of "pi"
% the argument can be a string with p's in it, or fractions of pi:
% [0 1/2 1] or '0 p/2 p' -> [0 pi/2 pi]
% [-1 0 1] or '-p 0 p' -> [-pi 0 pi]
% etc.
% Jeff Fessler
if length(varargin) == 0
ticks = '0 p';
elseif length(varargin) == 1
ticks = varargin{1};
else
error 'only one arg allowed'
end
if ischar(ticks)
str = ticks;
str = strrep(str, ' ', ' | ');
str = strrep(str, '*', ''); % we don't need the "*" in label
ticks = strrep(ticks, '2p', '2*p');
ticks = strrep(ticks, 'p', 'pi');
ticks = eval(['[' ticks ']']);
else
if same(ticks, [0])
str = '0';
elseif same(ticks, [0 1])
str = '0 | p';
elseif same(ticks, [0 1/2 1])
str = '0 | p/2 | p';
elseif same(ticks, [-1 0 1])
str = '-p | 0 | p';
elseif same(ticks, [0 1 2])
str = '0 | p | 2p';
else
error 'this ticks not done'
end
end
% here is the main part
axisy(min(ticks), max(ticks))
ytick(ticks)
set(gca, 'yticklabel', str, 'fontname', 'symbol')
function is = same(x,y)
if length(x) ~= length(y)
is = 0;
return
end
is = all(x == y);
|
github
|
sunhongfu/scripts-master
|
jf_add_slider.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/jf_add_slider.m
| 2,254 |
utf_8
|
202a6292a4880b44dee34b2b4c51096e
|
function hs = jf_add_slider(varargin)
%|function hs = jf_add_slider([options])
%|
%| add a slider control to the current figure to enable interaction
%|
%| option
%| 'callback' @ (value,data{:}) function to call with
%| slider value [0,1] and data
%| 'pos' [l b w h] slider position
%| 'data' {} data to be passed to callback
%| 'value' 0 <= x <= 1 initial slider value, default 0
%|
%| Copyright 2010-1-11, Jeff Fessler, University of Michigan
if ~nargin && ~nargout, help(mfilename), error(mfilename), end
if nargin && streq(varargin{1}, 'test'), jf_add_slider_test, return, end
arg.callback = @jf_add_slider_call;
arg.pos = [0.1, 0.0, 0.8, 0.03];
arg.data = {};
arg.name = '';
arg.value = 0;
arg.min = [];
arg.max = [];
arg.style = 'slider';
arg.sliderstep = [0.01 0.10];
arg.string = 'button';
arg = vararg_pair(arg, varargin);
args = {};
if ~isempty(arg.min)
args = {args{:}, 'min', arg.min};
end
if ~isempty(arg.max)
args = {args{:}, 'max', arg.max};
end
% construct gui components
hs = uicontrol('style', arg.style, 'string', arg.string, ...
'units', 'normalized', 'position', arg.pos, ...
'value', arg.value, ...
args{:}, ...
'sliderstep', arg.sliderstep, ...
'callback', {@jf_add_slider_callback});
if ~isempty(arg.name)
set(gcf, 'name', arg.name) % assign GUI a name for window title
end
if ~nargout
clear hs
end
% callbacks: these automatically have access to component handles
% and initialized data because they are nested at a lower level.
% slider callback
function jf_add_slider_callback(source, eventdata)
val = get(source, 'value');
arg.callback(val, arg.data{:})
end % jf_add_slider_callback
end % jf_add_slider
function jf_add_slider_call(value)
pr value
end % jf_add_slider_call
function jf_add_slider_test
jf_add_slider_test_call(0.5);
jf_add_slider('callback', @jf_add_slider_test_call, 'data', {gca}, ...
'value', 0.5)
% jf_add_slider_test_call(0);
jf_add_slider('callback', @jf_add_slider_test_call, 'data', {gca}, ...
'pos', [0.1 0.04 0.8 0.03], ...
'value', 0, 'style', 'togglebutton', 'string', 'push me')
end % jf_add_slider_test
function jf_add_slider_test_call(value, h)
if isvar('h')
axes(h)
end
plot([0 value], [0 value], '-')
axis([0 1 0 1])
end % jf_add_slider_test_call
|
github
|
sunhongfu/scripts-master
|
jf_slicer.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/jf_slicer.m
| 1,594 |
utf_8
|
bccf2da9064af86ffb306ec118277cce
|
function jf_slicer(data, varargin)
%|function jf_slicer(data, [options])
%|
%| slice 3d data interactively (along 3rd dimension)
%| uses scroll wheel to sweep through all slices
%|
%| in
%| data [nx ny nz]
%|
%| options
%| clim [1 2] clim arg to im()
%| iz [1] initial slice (default: nz/2+1)
%|
%| Jeff Fessler, University of Michigan
if ~nargin, help(mfilename), error(mfilename), end
if streq(data, 'test'), jf_slicer_test, return, end
arg.clim = [];
arg.iz = [];
arg = vararg_pair(arg, varargin);
if isempty(arg.clim)
arg.clim = minmax(data)';
end
nz = size(data, 3);
if isempty(arg.iz)
iz = ceil((nz+1)/2);
else
iz = arg.iz;
end
clamp = @(iz) max(min(iz, nz), 1);
stuff.data = data;
stuff.arg = arg;
%jf_slicer_call(iz, stuff)
%drawnow
jf_slicer_show
set(gcf, 'WindowScrollWheelFcn', @jf_slicer_scroll)
%h = jf_add_slider('callback', @jf_slicer_call, 'data', {stuff}, ...
% 'min', 1, 'max', nz, 'sliderstep', [1 1]/(nz-1), 'value', iz);
function jf_slicer_scroll(src, event)
iz = iz + event.VerticalScrollCount;
iz = clamp(iz);
jf_slicer_show
end % jf_slicer_scroll
function jf_slicer_show
im(data(:,:,iz), arg.clim), cbar
xlabelf('%d / %d', iz, nz)
end % jf_slicer_show
end % jf_slicer
function jf_slicer_call(iz, stuff)
persistent iz_save
if isempty(iz_save)
iz_save = -1;
end
iz = round(iz);
if iz ~= iz_save
iz_save = iz;
arg = stuff.arg;
im(stuff.data(:,:,iz), arg.clim), cbar
end
end % jf_slicer_call
function jf_slicer_test
data = reshape(1:7*8*9, 7, 8, 9);
im plc 1 2
im subplot 2
if im
jf_slicer(data, 'clim', [0 500])
end
end % jf_slicer_test
|
github
|
sunhongfu/scripts-master
|
label.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/label.m
| 654 |
utf_8
|
6ae74a9fa1ebfb4616a56849758663e3
|
function label(varargin)
% usage:
% label x string
% label y string
% label tex ... todo
narg = length(varargin);
if narg < 2
error 'need x or y'
end
props = {'interpreter', 'none'};
if streq(varargin{1}, 'x')
arg2 = varargin{2};
xlabel(arg2, props{:})
elseif streq(varargin{1}, 'y')
arg2 = varargin{2};
ylabel(arg2, props{:})
else
error 'not done'
end
function xlabeltex(arg)
%function xlabeltex(arg)
% xlabel embedded in \tex{} for psfrag
xlabel(['\tex[t][t]{' arg '}'], 'interpreter', 'none')
function ylabeltex(arg)
%function ylabeltex(arg)
% ylabel embedded in \tex{} for psfrag
ylabel(['\tex[B][B]{' arg '}'], 'interpreter', 'none')
|
github
|
sunhongfu/scripts-master
|
fig_text.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/fig_text.m
| 1,398 |
utf_8
|
20a59fa6097354c841c2f7e7fbf80e9b
|
function hh = fig_text(varargin)
%|function hh = fig_text(...)
%| add text to figure, using coordinates relative to entire window
%| options:
%| '-date' prepend date
%| '-tex' tex parse string
%| x,y coordinates relative to [0 0 1 1]
%| {args} style arguments for text() command
%| jeff fessler
comment = '';
thedate = '';
interpret = 'none';
textarg = {'fontsize', 11};
x = 0.01;
y = 0.01;
while length(varargin)
arg = varargin{1};
if ischar(arg)
if streq(arg, '-date')
thedate = [mydate ' '];
elseif streq(arg, '-tex')
interpret = 'tex';
else
comment = arg;
end
varargin = {varargin{2:end}};
elseif isnumeric(arg)
if length(varargin) < 2, error 'need x, y', end
x = varargin{1};
y = varargin{2};
varargin = {varargin{3:end}};
elseif iscell(arg)
textarg = {textarg{:}, arg{:}};
varargin = {varargin{2:end}};
else
help(mfilename), error 'bad args'
end
end
hh = gca;
hold on
h = axes('position', [0 0 1 1]); axis off
h = text(x, y, [thedate comment], 'interpreter', interpret, textarg{:});
hold off
if nargout
hh = h;
else
axes(hh) % reset axes to the one before the text added
clear hh
end
function s = mydate
%s = datestr(now, 'yyyy-mm-dd HH:MM:SS');
%s = datestr(now, 'yy-mm-dd HH:MM:SS');
t1 = datestr(now, 'yy');
t2 = datestr(now, 'mm');
t3 = datestr(now, 'dd');
t4 = datestr(now, 'HH:MM:SS');
s = sprintf('%s-%s-%s %s', t1, t2, t3, t4);
|
github
|
sunhongfu/scripts-master
|
im_toggle.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/im_toggle.m
| 2,525 |
utf_8
|
dc930a7b6f4278cde007dcf7464e52a0
|
function im_toggle(i1, i2, varargin)
%|function im_toggle(i1, i2, [..., options for im()])
%| toggle between two or more images via keypress
if nargin == 1 && streq(i1, 'test'), im_toggle_test, return, end
if nargin < 2, help(mfilename), error(mfilename), end
% find leading additional arguments corresponding to images
iall = {i1, i2};
names = {inputname(1), inputname(2)};
ii = 3;
while length(varargin) && isequal(size(i2), size(varargin{1}))
iall = {iall{:}, varargin{1}};
varargin = {varargin{2:end}};
names{ii} = inputname(ii);
ii = ii + 1;
end
for ii=1:length(names)
names{ii} = sprintf(['toggle i%d: ' names{ii}], ii);
end
if length(varargin) && ( ...
streq(varargin{1}, 'mip') || ...
streq(varargin{1}, 'sum') || ...
streq(varargin{1}, 'mid') )
for ii=1:length(iall)
iall{ii} = jf_mip3(iall{ii}, 'type', varargin{1});
end
varargin = {varargin{2:end}};
end
if ~im, return, end
% toggle between two or more images
ft.args = {{}, {'horiz', 'right'}};
ft.pos = [0.01, 0.99];
im clf
ht = uicontrol('style', 'text', 'string', 'test', ...
'units', 'normalized', 'position', [0.1 0.03 0.8 0.03]);
data = {iall, ft, varargin, names, ht};
im_toggle_call(0, data{:}, true)
jf_add_slider('callback', @im_toggle_call, 'data', data, ...
'sliderstep', [0.999 1] / (length(iall)-1));
return
while (1) % old way
for ii=1:length(iall)
% im_toggle_call(ii/length(iall), iall, ft, varargin, names)
im clf
im(iall{ii}, varargin{:})
fig_text(ft.pos(2-mod(ii,2)), 0.01, ...
names{ii}, ...
ft.args{2-mod(ii,2)})
% pause
in = input('hit enter for next image, or "q" to quit ', 's');
if streq(in, 'q')
set(gca, 'nextplot', 'replace')
return
end
end
end
function im_toggle_call(value, iall, ft, im_args, names, ht, reset)
persistent counter
persistent last_value
if isempty(last_value)
last_value = value;
end
if isempty(counter) || isvar('reset')
counter = 0;
end
if value == last_value % click
counter = 1 + counter;
if counter > length(iall)
counter = 1;
end
else % slide
counter = 1 + floor(0.9999 * length(iall) * value);
last_value = value;
end
im(iall{counter}, im_args{:})
set(ht, 'string', names{counter})
function im_toggle_test
if 0 % 2d
nx = 20;
i1 = eye(20);
i2 = flipud(i1);
i3 = 1 - i1;
im_toggle(i1, i2, i3, [0 2])
end
if 1 % 3d mip3
ig = image_geom('nx', 2^5, 'ny', 2^5-1', 'nz', 2^5-3, 'dx', 1);
t1 = ellipsoid_im(ig, [4 3 2 ig.fovs ./ [3 3 4] 0 0 1]);
t2 = flipdim(t1, 1);
t3 = flipdim(t1, 2);
im_toggle(t1, t2, t3, 'sum')
end
|
github
|
sunhongfu/scripts-master
|
texts.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/texts.m
| 1,224 |
utf_8
|
855769813da86ffc24b870bc0514a55a
|
function ho = texts(x, y, str, varargin)
%function ho = texts(x, y, str [, center], options)
% put text on current plot using screen coordinates
% user can supply optional name/value object properties.
% for horizontalalign, only the value is needed (e.g., 'center')
% if it is the first option.
if nargin == 1 && streq(x, 'test'), texts_test, return, end
if nargin < 3, help(mfilename), error(mfilename), end
xlim = get(gca, 'xlim');
ylim = get(gca, 'ylim');
xscale = get(gca, 'xscale');
yscale = get(gca, 'yscale');
if streq(xscale, 'log')
xlim = log10(xlim);
end
if streq(yscale, 'log')
ylim = log10(ylim);
end
x = xlim(1) + x * (xlim(2)-xlim(1));
y = ylim(1) + y * (ylim(2)-ylim(1));
if streq(xscale, 'log')
x = 10 ^ x;
end
if streq(yscale, 'log')
y = 10 ^ y;
end
if isfreemat
args = {};
else
args = {'buttondownfcn', 'textmove'};
end
if length(varargin)
arg1 = varargin{1};
if streq(arg1, 'left') | streq(arg1, 'center') | streq(arg1, 'right')
args = {args{:}, 'horizontalalign', varargin{:}};
else
args = {args{:}, varargin{:}};
end
end
h = text(x, y, str, args{:});
if nargout > 0
ho = h;
end
function texts_test
if im
plot(rand(3))
texts(0.5, 0.5, 'test', 'center', 'color', 'blue')
end
|
github
|
sunhongfu/scripts-master
|
im.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/graph/im.m
| 14,093 |
utf_8
|
842e9abbdd9c15e8fc82cb53a7faa718
|
function h = im(varargin)
%|function h = im([options,] [xx,] [yy,] zz, [scale|clim,] [title])
%| show matrix zz as an image, possibly with (x,y) axes labeled by xx,yy
%|
%| options:
%| subplot an integer for subplot
%| 'notick' no axis tick marks
%| 'black0' make sure image value of 0 is black (max white)
%| 'blue0' show zeros as blue
%| 'mid3' show middle 3 planes of 3D volume
%| 'mip3' show 3 MIP (max. intens. proj.) views of 3D volume
%| 'row', n # of rows for 3D montages, for this call
%| 'col', n # of cols for 3D montages, for this call
%|
%| after options:
%| scale scale image by this factor
%| clim limits for colorbar
%| title axis title
%| 'cbar' add colorbar
%|
%| one argument commands:
%| 'off' disable display,
%| 'off-quiet' disable display, and do not print 'disabled' messages
%| 'on' enable display, 'ison' report if enabled
%| 'clf' clear display (if enabled)
%| 'colorneg' show negatives as red
%| 'db40' log grayscale over 40dB range
%| 'nan-warn' warning if nan value(s), 'nan-fail' fail if nan
%| 'drawnow' 'drawnot' toggle immediate drawing
%| 'tickon' 'tickoff' toggle default tick drawing
%| 'state' report state
%|
%| other commands:
%| 'pl' sub_m sub_n specify subplot layout for subsequent plots
%| 'plc' like 'pl' but first clf
%| 'pl-tight' like 'pl' but tight plots with little (if any) spacing
%| 'subplot' plotindex choose a subplot
%| n2min n <= this min # for dim2 we plot instead (def: 1)
%| zero blue replace 1st colormap entry (zero?) with blue
%| row n # of rows for 3D montages - setting state
%| col n # of cols for 3D montages - setting state
%|
%| Copyright 1997, Jeff Fessler, University of Michigan
%
% handle states
%
persistent state
if ~isvar('state') || isempty(state)
state = im_reset;
end
% default is to give help
if ~nargin & ~nargout
help(mfilename)
if im, printm('im enabled'), else, printm('im disabled'), end
error(mfilename)
end
% for conditional of the form 'if im, ..., end'
if ~nargin & nargout
h = state.display;
return
end
% im row 2 or im col 3
if nargin == 2 && (streq(varargin{1}, 'row') | streq(varargin{1}, 'row'))
tmp = varargin{2};
if ischar(tmp), tmp = str2num(tmp); end
state.montage = {varargin{1}, tmp};
return
end
%
% process single string command arguments
%
if nargin == 1 && ischar(varargin{1})
arg = varargin{1};
if streq(arg, 'on')
state.display = true;
state.display_quiet = false;
disp 'enabling images'
elseif streq(arg, 'off')
state.display = false;
state.display_quiet = false;
disp 'disabling images'
elseif streq(arg, 'off-quiet')
state.display = false;
state.display_quiet = true;
elseif streq(arg, 'clf')
if state.display
clf
end
elseif streq(arg, 'drawnow')
state.drawnow = true;
elseif streq(arg, 'drawnot')
state.drawnow = false;
elseif streq(arg, 'tickon')
state.tick = true;
elseif streq(arg, 'tickoff')
state.tick = false;
elseif streq(arg, 'ison') % query
if state.display
h = true;
else
h = false;
end
elseif streq(arg, 'state') % query
h = state;
elseif streq(arg, 'nan-fail')
state.nan_fail = true;
elseif streq(arg, 'nan-warn')
state.nan_fail = false;
elseif streq(arg, 'blue0')
state.blue0 = true;
elseif streq(arg, 'colorneg')
state.colorneg = true;
elseif streq(arg, 'db', 2)
state.db = sscanf(arg, 'db%g');
elseif streq(arg, 'reset')
state = im_reset;
elseif streq(arg, 'test')
im_test, return
else
error(['unknown argument: ' arg])
end
return
end
% 'pl' 'plc' 'pl-tight' option
if streq(varargin{1}, 'pl') || streq(varargin{1}, 'pl-tight') ...
|| streq(varargin{1}, 'plc')
if streq(varargin{1}, 'plc'), im clf, end
if nargin == 3
state.sub_m = ensure_num(varargin{2});
state.sub_n = ensure_num(varargin{3});
elseif nargin == 1
state.sub_m = [];
state.sub_n = [];
else
error 'bad pl usage'
end
state.pl_tight = streq(varargin{1}, 'pl-tight');
return
end
% 'subplot' option
if streq(varargin{1}, 'subplot')
im_subplot(state, ensure_num(varargin{2}))
return
end
% 'n2min' option
if streq(varargin{1}, 'n2min')
state.n2min = ensure_num(varargin{2});
return
end
% 'zero' or 'zero blue'
if streq(varargin{1}, 'zero')
cmap = get(gcf, 'colormap');
cmap(1,:) = [0 0 1];
set(gcf, 'colormap', cmap);
return
end
scale = 1;
titlearg = {};
opt.cbar = false;
clim = [];
xx = [];
yy = [];
opt.blue0 = false; % 1 to color 0 as blue
opt.colorneg = false; % 1 to put negatives in color and 0=blue
opt.db = 0; % nonzero to use a log scale
isxy = false; % 1 if user provides x and y coordinates
isplot = false;
tick = state.tick;
opt.black0 = false;
opt.mid3 = false; % 1 if show mid-plane slices of 3D object
opt.mip3 = false; % 1 if show 3 MIP views of 3D object
opt.montage = state.montage;
if length(varargin) == 1 && isempty(varargin{1})
fail 'empty argument?'
end
%
% optional arguments
%
zz_arg_index = 1;
while length(varargin)
arg = varargin{1};
if isempty(arg)
0; % do nothing
elseif max(size(arg)) == 1
if state.display
arg1 = varargin{1};
if arg1 > 99 % reset
state.sub_m = [];
state.sub_n = [];
end
if isempty(state.sub_m)
if arg1 >= 111
subplot(arg1)
else
printm('ignoring subplot %d', arg1)
end
else
im_subplot(state, arg1)
end
end
elseif streq(arg, 'notick')
tick = false;
elseif streq(arg, 'colorneg')
opt.colorneg = true;
elseif streq(arg, 'db', 2)
opt.db = sscanf(arg, 'db%g');
elseif streq(arg, 'black0')
opt.black0 = true;
elseif streq(arg, 'blue0')
opt.blue0 = true;
elseif streq(arg, 'mid3')
opt.mid3 = true;
elseif streq(arg, 'mip3')
opt.mip3 = true;
elseif streq(arg, 'row') | streq(arg, 'col')
opt.montage = {arg, varargin{2}};
varargin = {varargin{2:end}};
zz_arg_index = 1 + zz_arg_index;
else
break
end
varargin = {varargin{2:end}};
zz_arg_index = 1 + zz_arg_index;
end
if length(varargin) < 1, help(mfilename), error args, end
%
% plotting vector(s)
%
if ndims(varargin{1}) <= 2 && min(size(varargin{1})) <= state.n2min ...
&& length(varargin) < 3
isplot = true;
plot_data = varargin{1};
%
% xx, yy
%
elseif ndims(varargin{1}) <= 2 & min(size(varargin{1})) == 1
xx = col(varargin{1});
if length(varargin) < 2, help(mfilename), error 'need both xx,yy', end
if min(size(varargin{2})) ~= 1, error 'both xx,yy need to be 1D', end
yy = col(varargin{2});
varargin = {varargin{3:end}};
isxy = 1;
zz_arg_index = 2 + zz_arg_index;
end
if ~state.display
if ~state.display_quiet
printm(['disabled: ' inputname(zz_arg_index)])
end
return
end
%
% zz
%
if length(varargin)
zz = varargin{1};
if iscell(zz); zz = stackup(zz{:}); isplot = 0; end % trick
zz = double(zz);
if ndims(zz) > 2 & min(size(zz)) == 1
zz = squeeze(zz); % handle [1 n2 n3] case as [n2 n3]
end
varargin = {varargin{2:end}};
else
error 'no image?'
end
if any(isnan(zz(:)))
tmp = sprintf('image contains %d NaN values of %d!?', ...
sum(isnan(zz(:))), numel(zz));
if state.nan_fail, error(tmp), else, warning(tmp), end
end
if any(isinf(zz(:)))
tmp = sprintf('image contains %d Inf values of %d!?', ...
sum(isinf(zz(:))), numel(zz));
if state.nan_fail, error(tmp), else, warning(tmp), end
end
if opt.mid3
pn = jf_protected_names;
zz = pn.mid3(zz);
end
if opt.mip3
mip3_size = size(zz);
zz = jf_mip3(zz);
end
% title, scale, clim, cbar
while length(varargin)
arg = varargin{1};
if isempty(arg)
% do nothing
elseif ischar(arg)
if streq(arg, 'cbar')
opt.cbar = true;
else
titlearg = {arg};
if ~isempty(strfind(arg, '\tex'))
titlearg = {arg, 'interpreter', 'none'};
end
end
elseif isnumeric(arg) % isa(arg, 'double')
if max(size(arg)) == 1
scale = arg;
elseif all(size(arg) == [1 2])
clim = arg;
else
error 'nonscalar scale / nonpair clim?'
end
% pr scale
else
error 'unknown arg'
end
varargin = {varargin{2:end}};
end
if isplot
plot(plot_data, state.line1type)
if ~isempty(titlearg), titlef(titlearg{:}), end
return
end
if issparse(zz), zz = full(zz); end
if ~isreal(zz)
zz = abs(zz);
printf('warn %s: magnitude of complex image', mfilename)
end
if opt.db | state.db
if ~opt.db & state.db, opt.db = state.db, end
if max(zz(:)) <= 0, error 'db for negatives?', end
zz = abs(zz); zz = max(zz, eps);
zz = 10*log10(abs(zz) / max(abs(zz(:))));
zz(zz < -opt.db) = -opt.db;
end
zmax = max(zz(:));
zmin = min(zz(:));
if opt.black0
if ~isempty(clim)
warning 'black0 overrules clim'
end
clim = [0 zmax];
end
if scale ~= 1
if scale == 0
zmin = 0;
scale = 1;
elseif scale < 0
zmin = 0;
scale = -scale;
end
end
% unfortunately, colormaps affect the entire figure, not just the axes
if opt.blue0 | state.blue0
cmap = [[0 0 1]; gray(256)];
colormap_gca(cmap)
zt = zz;
zz(zt > 0) = 1+floor(255 * zz(zt > 0) / (abs(max(zt(:))) + eps));
zz(zt == 0) = 1;
elseif opt.colorneg | state.colorneg
if 1 % original
cmap = hot(512); cmap = flipud(cmap(1:256,:));
cmap = [cmap; [0 0 1]; gray(256)];
else % +green -red
tmp = [0:255]'/255;
cmap = [flipud(tmp)*[1 0 0]; [0 0 1]; tmp*[0 1 0]];
end
colormap_gca(cmap)
zt = zz;
zz(zt > 0) = 257+1+floor(255 * zz(zt > 0) / (abs(max(zt(:))) + eps));
zz(zt == 0) = 257;
zz(zt < 0) = 1+floor(-255 * zz(zt < 0) / (abs(min(zt(:))) + eps));
else
colormap_gca(gray(256))
end
if scale ~= 1 % fix: use clim?
n = size(colormap,1);
if zmax ~= zmin
zz = (n - 1) * (zz - zmin) / (zmax - zmin); % [0,n-1]
else
if zmin == 0
zz(:) = 0;
clim = [0 1];
else
zz(:) = n - 1;
end
end
zz = 1 + round(scale * zz);
zz = min(zz,n);
zz = max(zz,1);
elseif zmin == zmax
if zmin == 0
clim = [0 1];
else
zz(:) = 1;
clim = [0 1];
end
end
if ndims(zz) < 3 % 2d
zz = zz'; % trick: transpose for consistency with C programs
if isxy
if length(xx) ~= size(zz,2), fail 'xx size', end
if length(yy) ~= size(zz,1), fail 'yy size', end
hh = image(xx, yy, zz, 'CDataMapping', 'scaled');
else
hh = image(zz, 'CDataMapping', 'scaled');
% setgca('CLimMode','auto')
% unclutter axes by only showing end limits
n1 = size(zz,2);
n2 = size(zz,1);
% setgca('xtick', [1 n1], 'ytick', [1 n2])
if tick
setgca('xtick', [], 'ytick', [1 n2])
if is_pre_v7
text(1, 1.04*(n2+0.5), '1', ...
'horizontalalign', 'left', ...
'verticalalign', 'top')
text(n1, 1.04*(n2+0.5), num2str(n1), ...
'horizontalalign', 'right', ...
'verticalalign', 'top')
elseif opt.mip3
tmp = [1 mip3_size(1)+[0 mip3_size(3)]];
setgca('xtick', tmp)
tmp = [1 mip3_size(2)+[0 mip3_size(3)]];
setgca('ytick', tmp)
else
setgca('xtick', [1 n1])
end
end
% problem with this is it fails to register
% space used for 'ylabel'
% so i stick with manual xtick since that is what overlaps
% with the colorbar
if 0 & tick
text(-0.01*n1, n2, '1', ...
'verticalalign', 'bottom', ...
'horizontalalign', 'right')
text(-0.01*n1, 1, num2str(n2), ...
'verticalalign', 'top', ...
'horizontalalign', 'right')
end
end
else % 3d
n1 = size(zz,1);
n2 = size(zz,2);
if 0 % white border
zz(:,end+1,:) = max(zz(:));
zz(end+1,:,:) = max(zz(:));
end
dimz = size(zz);
zz = montager(zz, opt.montage{:});
if isxy
xx3 = [0:size(zz,1)/dimz(1)-1]*(xx(2)-xx(1))*dimz(1);
xx3 = col(outer_sum(xx, xx3));
yy3 = [0:size(zz,2)/dimz(2)-1]*(yy(2)-yy(1))*dimz(2);
yy3 = col(outer_sum(yy, yy3));
hh = image(xx3, yy3, zz', 'CDataMapping', 'scaled');
if tick & n1 > 1 & n2 > 1 % unclutter
setgca('xtick', [xx(1) xx(end)], 'ytick', ...
sort([yy(1) yy(end)]))
end
axis xy
else
hh = image(zz', 'CDataMapping', 'scaled');
if tick & n1 > 1 & n2 > 1 % unclutter
setgca('xtick', [1 n1], 'ytick', [1 n2])
end
if state.line3plot % lines around each sub image
m1 = size(zz,1) / n1;
m2 = size(zz,2) / n2;
plot_box = @(ox,oy,arg) plot(ox+[0 1 1 0 0]*n1+0.5, ...
oy+[0 0 1 1 0]*n2+0.5, state.line3type, arg{:});
n3 = dimz(3);
for ii=0:n3-1
i1 = mod(ii, m1);
i2 = floor(ii / m1);
hold on
plot_box(i1*n1, i2*n2, ...
{'linewidth', state.line3width})
hold off
end
end
end
end
if (zmax == zmin)
% fprintf('Uniform image %g [', zmin)
% fprintf(' %g', size(zz))
% fprintf(' ]\n')
texts(0.5, 0.5, sprintf('Uniform: %g', zmin), 'center', 'color', 'blue')
end
if opt.colorneg | state.colorneg
set(hh, 'CDataMapping', 'direct')
else
if ~isempty(clim),
setgca('CLim', clim)
elseif ~ishold
setgca('CLimMode', 'auto')
end
end
setgca('TickDir', 'out')
if nargout > 0
h = hh;
end
% axis type depends on whether user provides x,y coordinates
if isxy
if length(xx) > 1 && length(yy) > 1 && ...
abs(xx(2)-xx(1)) == abs(yy(2)-yy(1)) % square pixels
axis image
end
axis xy
else
axis image
end
if ~isempty(titlearg)
title(titlearg{:})
else
tmp = sprintf('%s range: [%g %g]', inputname(zz_arg_index), zmin, zmax);
title(tmp, 'interpreter', 'none')
end
if ~tick
setgca('xtick', [], 'ytick', [])
end
if opt.cbar, cbar, end
if state.drawnow, drawnow, end
% im_reset()
% reset state to its defaults
function state = im_reset
state.display = true;
state.display_quiet = false;
state.colorneg = false;
state.db = 0;
state.blue0 = false;
state.nan_fail = false;
state.drawnow = false;
state.tick = true;
state.montage = {}; % for montager
state.sub_m = []; % for subplot
state.sub_n = [];
state.n2min = 1;
state.pl_tight = false;
state.line3plot = true;
state.line3type = 'y-';
state.line3width = 1;
state.line1type = '-'; % for 1D plots
function x = ensure_num(x)
if ischar(x), x = str2num(x); end
function colormap_gca(cmap)
if isfreemat
colormap(cmap)
else
colormap(gca, cmap)
end
function im_test
im clf, im(rand(6))
im clf, im pl-tight 2 3
im(1, rand(3))
im(2, rand(3))
im(5, ones(3))
prompt
im clf, im(rand(2^7,2^7-2,4))
function im_subplot(state, num)
if state.display
if state.pl_tight
num = num - 1;
x = 1 / state.sub_n;
y = 1 / state.sub_m;
ny = floor(num / state.sub_n);
nx = num - ny * state.sub_n;
ny = state.sub_m - ny - 1;
subplot('position', [nx*x ny*y x y])
else
subplot(state.sub_m, state.sub_n, num)
end
end
function setgca(varargin)
set(gca, varargin{:})
|
github
|
sunhongfu/scripts-master
|
mtimes_block.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/@Fatrix/mtimes_block.m
| 1,276 |
utf_8
|
11f89a7167f3f66a965c297a8620dcd5
|
function y = mtimes_block(ob, x, istart, nblock)
%function y = mtimes_block(ob, x, istart, nblock)
% y = G(i'th block) * x or y = G'(i'th block) * x
% in either case the projection data will be "small"
% istart is 1,...,nblock
% support 'exists' option for seeing if this routine is available
if nargin == 2 & ischar(x) & streq(x, 'exists')
y = ~isempty(ob.handle_mtimes_block);
return
end
if nargin ~= 4
error(mfilename)
end
if isempty(ob.handle_mtimes_block)
error 'bug: no mtimes_block() method for this object'
end
if ob.is_transpose
y = Fatrix_mtimes_block_back(ob, x, istart, nblock);
else
y = Fatrix_mtimes_block_forw(ob, x, istart, nblock);
end
% caution: cascade_* may not work except for scalars here
function y = Fatrix_mtimes_block_forw(ob, x, istart, nblock);
x = do_cascade(ob.cascade_before, x, false, istart, nblock, true);
y = feval(ob.handle_mtimes_block, ob.arg, ob.is_transpose, x, istart, nblock);
y = do_cascade(ob.cascade_after, y, false, istart, nblock, false);
function x = Fatrix_mtimes_block_back(ob, y, istart, nblock);
y = do_cascade(ob.cascade_after, y, true, istart, nblock, false);
x = feval(ob.handle_mtimes_block, ob.arg, ob.is_transpose, y, istart, nblock);
x = do_cascade(ob.cascade_before, x, true, istart, nblock, true);
|
github
|
sunhongfu/scripts-master
|
mtimes.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/@Fatrix/mtimes.m
| 1,374 |
utf_8
|
b01e213ce10f513c5f91f944f5e7d1f4
|
function y = mtimes(ob, x)
%function y = mtimes(ob, x)
% y = M * x or x = M' * y
if ~isa(ob, 'Fatrix')
error 'only multiplication on right is done'
end
if isa(x, 'Fatrix') % object1 * object2, tested in Gcascade
y = Gcascade(ob, x);
return
end
%
% partial multiplication?
%
if ob.is_subref
error 'subref not done'
end
%
% block multiplication (if needed)
%
if ~isempty(ob.nblock) % block object
if ~isempty(ob.handle_mtimes_block) % proper block object
if ~isempty(ob.iblock) % Gb{?} * ?
y = mtimes_block(ob, x, ob.iblock, ob.nblock);
return
% else: % Gb * ?
end
% else should be a 1-block object
elseif ob.nblock > 1
error 'nblock > 1 but no mtimes_block?'
end
end
%
% ordinary multiplication
%
if ob.is_transpose
y = Fatrix_mtimes_back(ob, x);
else
y = Fatrix_mtimes_forw(ob, x);
end
%
% full forward multiplication ("projection")
% y = after * ob * before * x;
%
function y = Fatrix_mtimes_forw(ob, x);
x = do_cascade(ob.cascade_before, x, false, 0, 1, true);
y = feval(ob.handle_forw, ob.arg, x);
y = do_cascade(ob.cascade_after, y, false, 0, 1, false);
%
% full transposed multiplication ("back-projection")
% x = before' * ob' * after' * y;
%
function x = Fatrix_mtimes_back(ob, y);
y = do_cascade(ob.cascade_after, y, true, 0, 1, false);
x = feval(ob.handle_back, ob.arg, y);
x = do_cascade(ob.cascade_before, x, true, 0, 1, true);
|
github
|
sunhongfu/scripts-master
|
do_cascade.m
|
.m
|
scripts-master/MRF/recon/_src/_NUFFT/@Fatrix/private/do_cascade.m
| 870 |
utf_8
|
c5e864c129913ce1841a0ce0b0ddacda
|
function y = do_cascade(cascade, x, is_transpose, istart, nblock, is_before)
%function y = do_cascade(cascade, x, is_transpose, istart, nblock, is_before)
% do cascade * x or cascade' * x
if isempty(cascade)
y = x;
elseif isa(cascade, 'function_handle') | isa(cascade, 'inline')
if nargin(cascade) == 4
y = feval(cascade, x, is_transpose, istart, nblock);
elseif nargin(cascade) == 2 | nblock == 1
y = feval(cascade, x, is_transpose);
else
error 'cascade_* should have 2 or 4 arguments?'
end
else % matrix or object
if is_transpose
if is_before
do_cascade_warn(cascade, nblock)
end
y = cascade' * x;
else
if ~is_before
do_cascade_warn(cascade, nblock)
end
y = cascade * x;
end
end
function do_cascade_warn(cascade, nblock)
if max(size(cascade)) > 1 & nblock ~= 1
warning 'non scalar array/object cascade not tested with block!'
end
|
github
|
sunhongfu/scripts-master
|
recon_arc_asset.m
|
.m
|
scripts-master/GERecon/recon_arc_asset.m
| 11,061 |
utf_8
|
eb77545d89bf56e33f277cbd7081dd35
|
function recon_arc_asset(pfilePath, calibrationPfile, outputDir)
% % mac
% cd '/Users/hongfusun/DATA/p-files/oct7/raw/'
% pfilePath='/Users/hongfusun/DATA/p-files/oct7/raw/P31232.7';
% calibrationPfile='/Users/hongfusun/DATA/p-files/oct7/raw/P32328.7';
% pfilePath='/Users/hongfusun/DATA/p-files/oct12/P44544.7';
% pfilePath='/Users/hongfusun/DATA/p-files/oct12/P32256.7';
% linux
% pfilePath='/media/data/p-files/oct12/t1/P44544.7'
% Load Pfile
clear GERecon
pfile = GERecon('Pfile.Load', pfilePath);
GERecon('Pfile.SetActive',pfile);
header = GERecon('Pfile.Header', pfile);
% if length(varargin) == 1
% % Load Arc Sampling Pattern (kacq_yz.txt)
% GERecon('Arc.LoadKacq', varargin{1});
% end
% Load KSpace. Since 3D Arc Pfiles contain space for the zipped
% slices (even though the data is irrelevant), only pull out
% the true acquired K-Space. Z-transform will zip the slices
% out to the expected extent.
acquiredSlices = pfile.slicesPerPass / header.RawHeader.zip_factor;
% 3D Scaling Factor
scaleFactor = header.RawHeader.user0;
if header.RawHeader.a3dscale > 0
scaleFactor = scaleFactor * header.RawHeader.a3dscale;
end
scaleFactor = pfile.slicesPerPass / scaleFactor;
% extract the kSpace
kSpace = zeros(pfile.xRes, pfile.yRes, acquiredSlices, pfile.channels, pfile.echoes, pfile.passes);
for pass = 1:pfile.passes
for echo = 1:pfile.echoes
for slice = 1:acquiredSlices
sliceInfo.pass = pass;
sliceInfo.sliceInPass = slice;
for channel = 1:pfile.channels
% Load K-Space
kSpace(:,:,slice,channel,echo,pass) = GERecon('Pfile.KSpace', sliceInfo, echo, channel, pfile);
end
end
end
end
% Synthesize KSpace to get full kSpace
kSpace_full = zeros(pfile.xRes, pfile.yRes, acquiredSlices, pfile.channels, pfile.echoes, pfile.passes);
for pass = 1:pfile.passes
for echo = 1:pfile.echoes
kSpace_full(:,:,:,:,echo,pass) = GERecon('Arc.Synthesize', kSpace(:,:,:,:,echo,pass));
end
end
clear kSpace
% image recon
% Scale
kSpace_full = kSpace_full * scaleFactor;
%%%%% 1 %%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Default GE method %%%%%%%%%%%%%%%%%%%%%%%
% Transform Across Slices
kSpace_full = ifft(kSpace_full, pfile.slicesPerPass, 3);
for pass = 1:pfile.passes
for echo = 1:pfile.echoes
for slice = 1:pfile.slicesPerPass
for channel = 1:pfile.channels
% Transform K-Space
channelImages(:,:,slice,channel,echo,pass) = GERecon('Transform', kSpace_full(:,:,slice,channel,echo,pass));
end
end
end
end
nii=make_nii(abs(channelImages));
save_nii(nii,'channelImage_mag.nii');
nii=make_nii(angle(channelImages));
save_nii(nii,'channelImage_pha.nii');
clear kSpace_full
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%% 2 %%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%% IFFT method %%%%%%%%%%%%%%%%%%%%%%%
% kSpace_full = padarray(kSpace_full,[18, 18], 'both');
% channelImages = ifft(ifft(ifft(kSpace_full,[],1),[],2),[],3);
% channelImages = fftshift(fftshift(channelImages,1),2);
% channelImages = channelImages*256*sqrt(40);
% nii=make_nii(abs(channelImages(:,:,:,:,4)));
% save_nii(nii,'channelImage_mag_e4.nii');
% nii=make_nii(angle(channelImages(:,:,:,:,4)));
% save_nii(nii,'channelImage_pha_e4.nii');
% clear kSpace_full
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%% 3 %%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%% Hongfu method %%%%%%%%%%%%%%%%%%%%%%%%%%%
% kSpace_full = padarray(kSpace_full,[18, 18], 'both');
% kSpace_full = fftshift(kSpace_full,1);
% kSpace_full = fftshift(kSpace_full,2);
% kSpace_full = fftshift(kSpace_full,3);
% channelImages = fft(fft(fft(kSpace_full,[],1),[],2),[],3);
% channelImages = fftshift(fftshift(channelImages,1),2);
% channelImages = channelImages/256/sqrt(40);
% %%% seems like need flip to be the same as method 1 and 3, also circshift
% channelImages = flipdim(flipdim(flipdim(channelImages,1),2),3);
% channelImages = circshift(channelImages,[1 1 1]);
% nii=make_nii(abs(channelImages(:,:,:,:,4)));
% save_nii(nii,'channelImage_mag_e4.nii');
% nii=make_nii(angle(channelImages(:,:,:,:,4)));
% save_nii(nii,'channelImage_pha_e4.nii');
% clear kSpace_full
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%%%%% 4 %%%%%%%
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %%% Hongfu method no phase checkerboard %%%%%%%%%%%%%%%%%%%%%%%%%%%
% kSpace_full = fftshift(kSpace_full,1);
% kSpace_full = fftshift(kSpace_full,2);
% kSpace_full = fftshift(kSpace_full,3);
% channelImages = fft(fft(fft(kSpace_full,[],1),[],2),[],3);
% channelImages = fftshift(fftshift(channelImages,1),2);
% channelImages = channelImages/256/sqrt(40);
% % %%% seems like need flip to be the same as method 1 and 3, also circshift
% % channelImages = flipdim(flipdim(flipdim(channelImages,1),2),3);
% % channelImages = circshift(channelImages,[1 1 1]);
% nii=make_nii(single(abs(channelImages)));
% save_nii(nii,'channelImage_mag.nii');
% nii=make_nii(single(angle(channelImages)));
% save_nii(nii,'channelImage_pha.nii');
% clear kSpace_full
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % SVD coil combination
% img_cmb = zeros(pfile.xRes, pfile.yRes, acquiredSlices);
% for slice = 1:pfile.slicesPerPass
% [img_cmb(:,:,slice)] = adaptive_cmb_2d(squeeze(channelImages(:,:,slice,:)));
% end
% nii=make_nii(abs(img_cmb));
% save_nii(nii,'combinedImage_mag.nii');
% nii=make_nii(angle(img_cmb));
% save_nii(nii,'combinedImage_pha.nii');
% % combine magnitude images with SoS
% % Apply Channel Combination
% imsize = size(channelImages);
% combinedImage = zeros([imsize(1:3), pfile.echoes, pfile.passes]);
% finalImage = combinedImage;
% for pass = 1:pfile.passes
% for echo = 1:pfile.echoes
% for slice = 1:acquiredSlices
% % Get slice information (corners and orientation) for this slice location
% sliceInfo.pass = pass;
% sliceInfo.sliceInPass = slice;
% info = GERecon('Pfile.Info', sliceInfo);
% combinedImage(:,:,slice,echo,pass) = GERecon('SumOfSquares', squeeze(channelImages(:,:,slice,:,echo,pass)));
% % Create Magnitude Image
% magnitudeImage = abs(combinedImage(:,:,slice,echo,pass));
% % Apply Gradwarp
% gradwarpedImage = GERecon('Gradwarp', magnitudeImage, info.Corners);
% % Orient the image
% finalImage(:,:,slice,echo,pass) = GERecon('Orient', gradwarpedImage, info.Orientation);
% end
% end
% end
% nii=make_nii(abs(combinedImage(:,:,:,4)));
% save_nii(nii,'combinedImage_mag_e4.nii');
% nii=make_nii(abs(finalImage(:,:,:,4)));
% save_nii(nii,'finalImage_mag_e4.nii');
% ASSET recon
% change the p-file header of ASSET
setenv('pfilePath',pfilePath);
unix('/Users/hongfusun/bin/orchestra-sdk-1.7-1/build/BuildOutputs/bin/HS_ModHeader --pfile $pfilePath')
pfilePath=[pfilePath '.mod'];
% Load Pfile
clear GERecon
pfile = GERecon('Pfile.Load', pfilePath);
GERecon('Pfile.SetActive',pfile);
header = GERecon('Pfile.Header', pfile);
% calibrationPfile
GERecon('Calibration.Process', calibrationPfile);
imsize = size(channelImages);
unaliasedImage = zeros([imsize(1:3), pfile.echoes, pfile.passes]);
for pass = 1:pfile.passes
for echo = 1:pfile.echoes
for slice = 1:acquiredSlices
% Get slice information (corners and orientation) for this slice location
sliceInfo.pass = pass;
sliceInfo.sliceInPass = slice;
info = GERecon('Pfile.Info', slice);
unaliasedImage(:,:,slice,echo,pass) = GERecon('Asset.Unalias', squeeze(channelImages(:,:,slice,:,echo,pass)), info);
end
end
end
% correct for phase chopping
unaliasedImage = fft(fft(fft(fftshift(fftshift(fftshift(ifft(ifft(ifft(unaliasedImage,[],1),[],2),[],3),1),2),3),[],1),[],2),[],3);
nii=make_nii(abs(unaliasedImage));
save_nii(nii,'unaliasedImage_mag.nii');
nii=make_nii(angle(unaliasedImage));
save_nii(nii,'unaliasedImage_pha.nii');
% save DICOMs for QSM inputs
for pass = 1:pfile.passes
for echo = 1:pfile.echoes
for slice = 1:acquiredSlices
% Get slice information (corners and orientation) for this slice location
sliceInfo.pass = pass;
sliceInfo.sliceInPass = slice;
info = GERecon('Pfile.Info', sliceInfo);
realImage = real(unaliasedImage_new(:,:,slice,echo,pass));
imagImage = imag(unaliasedImage_new(:,:,slice,echo,pass));
% Apply Gradwarp
gradwarpedRealImage = GERecon('Gradwarp', realImage, info.Corners);
gradwarpedImagImage = GERecon('Gradwarp', imagImage, info.Corners);
% Orient the image
finalRealImage = GERecon('Orient', gradwarpedRealImage, info.Orientation);
finalImagImage = GERecon('Orient', gradwarpedImagImage, info.Orientation);
% Save DICOMs
imageNumber = ImageNumber(pass, info.Number, echo, pfile);
filename = ['DICOMs_real/realImage' num2str(imageNumber) '.dcm'];
GERecon('Dicom.Write', filename, finalRealImage, imageNumber, info.Orientation, info.Corners);
filename = ['DICOMs_imag/imagImage' num2str(imageNumber) '.dcm'];
GERecon('Dicom.Write', filename, finalImagImage, imageNumber, info.Orientation, info.Corners);
end
end
end
end
function number = ImageNumber(pass, slice, echo, pfile)
% Image numbering scheme (P = Phase; S = Slice; E = Echo):
% P0S0E0, P0S0E1, ... P0S0En, P0S1E0, P0S1E1, ... P0S1En, ... P0SnEn, ...
% P1S0E0, P1S0E1, ... PnSnEn
% Need to map the legacy "pass" number to a phase number
numPassesPerPhase = fix(pfile.passes / pfile.phases);
phase = fix(pass / numPassesPerPhase);
slicesPerPhase = pfile.slicesPerPass * numPassesPerPhase * pfile.echoes;
number = (phase-1) * slicesPerPhase + (slice-1) * pfile.echoes + (echo-1) + 1;
end
|
github
|
sunhongfu/scripts-master
|
deleteoutliers.m
|
.m
|
scripts-master/fMRI-QSM/deleteoutliers.m
| 3,493 |
utf_8
|
a97518a30ca50a19dcfb5e180b3089c7
|
function [b,idx,outliers] = deleteoutliers(a,alpha,rep);
% [B, IDX, OUTLIERS] = DELETEOUTLIERS(A, ALPHA, REP)
%
% For input vector A, returns a vector B with outliers (at the significance
% level alpha) removed. Also, optional output argument idx returns the
% indices in A of outlier values. Optional output argument outliers returns
% the outlying values in A.
%
% ALPHA is the significance level for determination of outliers. If not
% provided, alpha defaults to 0.05.
%
% REP is an optional argument that forces the replacement of removed
% elements with NaNs to presereve the length of a. (Thanks for the
% suggestion, Urs.)
%
% This is an iterative implementation of the Grubbs Test that tests one
% value at a time. In any given iteration, the tested value is either the
% highest value, or the lowest, and is the value that is furthest
% from the sample mean. Infinite elements are discarded if rep is 0, or
% replaced with NaNs if rep is 1 (thanks again, Urs).
%
% Appropriate application of the test requires that data can be reasonably
% approximated by a normal distribution. For reference, see:
% 1) "Procedures for Detecting Outlying Observations in Samples," by F.E.
% Grubbs; Technometrics, 11-1:1--21; Feb., 1969, and
% 2) _Outliers in Statistical Data_, by V. Barnett and
% T. Lewis; Wiley Series in Probability and Mathematical Statistics;
% John Wiley & Sons; Chichester, 1994.
% A good online discussion of the test is also given in NIST's Engineering
% Statistics Handbook:
% http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm
%
% ex:
% [B,idx,outliers] = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2], 0.05)
% returns:
% B = 1.1000 1.3000 0.9000 1.2000 1.2000 0.9400 1.3000 1.0000 1.3000 1.2000
% idx = 5 8 11
% outliers = -6.4000 4.2000 6.8000
%
% ex:
% B = deleteoutliers([1.1 1.3 0.9 1.2 -6.4 1.2 0.94 4.2 1.3 1.0 6.8 1.3 1.2
% Inf 1.2 -Inf 1.1], 0.05, 1)
% returns:
% B = 1.1000 1.3000 0.9000 1.2000 NaN 1.2000 0.9400 NaN 1.3000 1.0000 NaN 1.3000 1.2000 NaN 1.2000 NaN 1.1000
% Written by Brett Shoelson, Ph.D.
% [email protected]
% 9/10/03
% Modified 9/23/03 to address suggestions by Urs Schwartz.
% Modified 10/08/03 to avoid errors caused by duplicate "maxvals."
% (Thanks to Valeri Makarov for modification suggestion.)
if nargin == 1
alpha = 0.05;
rep = 0;
elseif nargin == 2
rep = 0;
elseif nargin == 3
if ~ismember(rep,[0 1])
error('Please enter a 1 or a 0 for optional argument rep.')
end
elseif nargin > 3
error('Requires 1,2, or 3 input arguments.');
end
if isempty(alpha)
alpha = 0.05;
end
b = a;
b(isinf(a)) = NaN;
%Delete outliers:
outlier = 1;
while outlier
tmp = b(~isnan(b));
meanval = mean(tmp);
maxval = tmp(find(abs(tmp-mean(tmp))==max(abs(tmp-mean(tmp)))));
maxval = maxval(1);
sdval = std(tmp);
tn = abs((maxval-meanval)/sdval);
critval = zcritical(alpha,length(tmp));
outlier = tn > critval;
if outlier
tmp = find(a == maxval);
b(tmp) = NaN;
end
end
if nargout >= 2
idx = find(isnan(b));
end
if nargout > 2
outliers = a(idx);
end
if ~rep
b=b(~isnan(b));
end
return
function zcrit = zcritical(alpha,n)
%ZCRIT = ZCRITICAL(ALPHA,N)
% Computes the critical z value for rejecting outliers (GRUBBS TEST)
tcrit = tinv(alpha/(2*n),n-2);
zcrit = (n-1)/sqrt(n)*(sqrt(tcrit^2/(n-2+tcrit^2)));
|
github
|
sunhongfu/scripts-master
|
Get_mrd_3D5.m
|
.m
|
scripts-master/XiangFeng/Get_mrd_3D5.m
| 10,379 |
utf_8
|
ba0ba6f33bf17effeafe8a956b00c067
|
% Description: Function to open multidimensional MRD/SUR files given a filename with PPR-parsing
% Inputs: string filename, reordering1, reordering2
% Outputs: complex data, raw dimension [no_expts,no_echoes,no_slices,no_views,no_views_2,no_samples], MRD/PPR parameters
% Author: Ruslan Garipov
% Date: 01/03/2014 - swapped views and views2 dimension - now correct
% 30 April 2014 - support for reading orientations added
% 11 September 2014 - swapped views and views2 in the array (otherwise the images are rotated)
% 13 October 2015 - scaling added as a parameter
% 19 October 2018 - image tags added
function [im,dim,par] = Get_mrd_3D5(filename,reordering1, reordering2)
% Read in MRD and SUR file formats
% reordering1, 2 is 'seq' or 'cen'
% reordering1 is for 2D (views)
% reordering2 is for 3D (views2)
fid = fopen(filename,'r'); % Define the file id
val = fread(fid,4,'int32');
xdim = val(1);
ydim = val(2);
zdim = val(3);
dim4 = val(4);
fseek(fid,18,'bof');
datatype=fread(fid,1, 'uint16');
datatype = dec2hex(datatype);
fseek(fid,48,'bof');
scaling=fread(fid,1, 'float32');
bitsperpixel=fread(fid,1, 'uchar');
fseek(fid,152,'bof');
val = fread(fid,2, 'int32');
dim5 = val(1);
dim6 = val(2);
fseek(fid,256,'bof');
text=fread(fid,256);
no_samples = xdim;
no_views = ydim;
no_views_2=zdim;
no_slices = dim4;
no_echoes = dim5;
no_expts = dim6;
% Read in the complex image data
dim = [no_expts,no_echoes,no_slices,no_views_2,no_views,no_samples];
if size(datatype,2)>1
onlydatatype = datatype(2);
iscomplex = 2;
else
onlydatatype = datatype(1);
iscomplex = 1;
end
switch onlydatatype
case '0'
dataformat = 'uchar'; datasize = 1; % size in bytes
case '1'
dataformat = 'schar'; datasize = 1; % size in bytes
case '2'
dataformat = 'short'; datasize = 2; % size in bytes
case '3'
dataformat = 'int16'; datasize = 2; % size in bytes
case '4'
dataformat = 'int32'; datasize = 4; % size in bytes
case '5'
dataformat = 'float32'; datasize = 4; % size in bytes
case '6'
dataformat = 'double'; datasize = 8; % size in bytes
otherwise
dataformat = 'int32'; datasize = 4; % size in bytes
end
num2read = no_expts*no_echoes*no_slices*no_views_2*no_views*no_samples*iscomplex; %*datasize;
[m_total, count] = fread(fid,num2read,dataformat); % reading all the data at once
if (count~=num2read)
h = msgbox('We have a problem...');
end
if iscomplex == 2
a=1:count/2;
m_real = m_total(2*a-1);
m_imag = m_total(2*a);
clear m_total;
m_C = m_real+m_imag*1i;
clear m_real m_imag;
else
m_C = m_total;
clear m_total;
end
n=0;
% shaping the data manually:
ord=1:no_views;
if reordering1 == 'cen'
for g=1:no_views/2
ord(2*g-1)=no_views/2+g;
ord(2*g)=no_views/2-g+1;
end
end
ord1 = 1:no_views_2;
ord2 = ord1;
if reordering2 == 'cen'
for g=1:no_views_2/2
ord2(2*g-1)=no_views_2/2+g;
ord2(2*g)=no_views_2/2-g+1;
end
end
for a=1:no_expts
for b=1:no_echoes
for c=1:no_slices
for d=1:no_views
for e=1:no_views_2
m_C_1(a,b,c,ord(d),ord2(e),:) = m_C(1+n:no_samples+n); % sequential ordering
n=n+no_samples;
end
end
end
end
end
clear ord;
clear ord2;
m_C = squeeze(m_C_1);
clear m_C_1;
im=m_C;
sample_filename = char(fread(fid,120,'uchar')');
ppr_text = char(fread(fid,Inf,'uchar')');
fclose(fid);
%% parse fields in ppr section of the MRD file
if numel(ppr_text)>0
cell_text = textscan(ppr_text,'%s','delimiter',char(13));
PPR_keywords = {'BUFFER_SIZE','DATA_TYPE','DECOUPLE_FREQUENCY','DISCARD','DSP_ROUTINE','EDITTEXT','EXPERIMENT_ARRAY','FOV','FOV_READ_OFF','FOV_PHASE_OFF','FOV_SLICE_OFF','GRADIENT_STRENGTH','MULTI_ORIENTATION','Multiple Receivers','NO_AVERAGES','NO_ECHOES','NO_RECEIVERS','NO_SAMPLES','NO_SLICES','NO_VIEWS','NO_VIEWS_2','OBLIQUE_ORIENTATION','OBSERVE_FREQUENCY','ORIENTATION','PHASE_CYCLE','READ/PHASE/SLICE_SELECTION','RECEIVER_FILTER','SAMPLE_PERIOD','SAMPLE_PERIOD_2','SCROLLBAR','SLICE_BLOCK','SLICE_FOV','SLICE_INTERLEAVE','SLICE_THICKNESS','SLICE_SEPARATION','SPECTRAL_WIDTH','SWEEP_WIDTH','SWEEP_WIDTH_2','VAR_ARRAY','VIEW_BLOCK','VIEWS_PER_SEGMENT','SMX','SMY','SWX','SWY','SMZ','SWZ','VAR','PHASE_ORIENTATION','X_ANGLE','Y_ANGLE','Z_ANGLE','PPL','IM_ORIENTATION','IM_OFFSETS','IM_SLICE', 'IM_ECHO', 'IM_EXPERIMENT', 'FOV_OFFSETS', 'READ_VAR'};
%PPR_type_0 keywords have text fields only, e.g. ":PPL C:\ppl\smisim\1ge_tagging2_1.PPL"
PPR_type_0 = [23 53];
%PPR_type_1 keywords have single value, e.g. ":FOV 300" and 'IM_SLICE', 'IM_ECHO', 'IM_EXPERIMENT' SUR tags
PPR_type_1 = [8 42:47 56 57];
%PPR_type_2 keywords have single variable and single value, e.g. ":NO_SAMPLES no_samples, 16"
PPR_type_2 = [4 7 9:11 15:21 25 31 33 41 49 60];
PPR_type_3 = 48; % VAR keyword only (syntax same as above)
PPR_type_4 = [28 29]; % :SAMPLE_PERIOD sample_period, 300, 19, "33.3 KHz 30 ?s" and SAMPLE_PERIOD_2 - read the first number=timeincrement in 100ns
%PPR_type_5 keywords have single variable and two values, e.g. ":SLICE_THICKNESS gs_var, -799, 100"
PPR_type_5 = [34 35];
% KEYWORD [pre-prompt,] [post-prompt,] [min,] [max,] default, variable [,scale] [,further parameters ...];
PPR_type_6 = [39 50:52]; % VAR_ARRAY and angles keywords
PPR_type_7 = [54 55]; % IM_ORIENTATION and IM_OFFSETS (SUR only)
PPR_type_8 = 12; % GRADIENT_STRENGTH keyword
PPR_type_9 = 59; % FOV_OFFSETS keyword
par = struct('filename',filename);
for j=1:size(cell_text{1},1)
char1 = char(cell_text{1}(j,:));
field_ = '';
if ~isempty(char1)
C = textscan(char1, '%*c%s %s', 1);
field_ = char(C{1});
end
% find the corresponding number in PPR_keyword array:
num = find(strcmp(field_,PPR_keywords));
if num>0
if find(PPR_type_3==num) % :VAR keyword
C = textscan(char1, '%*s %s %f');
field_title = char(C{1}); field_title(numel(field_title)) = [];
numeric_field = C{2};
par = setfield(par, field_title, numeric_field);
elseif find(PPR_type_1==num)
C = textscan(char1, '%*s %f');
numeric_field = C{1};
par = setfield(par, field_, numeric_field);
elseif find(PPR_type_2==num)
C = textscan(char1, '%*s %s %f');
numeric_field = C{2};
par = setfield(par, field_, numeric_field);
elseif find(PPR_type_4==num)
C = textscan(char1, '%*s %s %n %n %s');
field_title = char(C{1}); field_title(numel(field_title)) = [];
numeric_field = C{2};
par = setfield(par, field_, numeric_field);
elseif find(PPR_type_0==num)
C = textscan(char1, '%*s %[^\n]');
text_field = char(C{1}); %text_field = reshape(text_field,1,[]);
par = setfield(par, field_, text_field);
elseif find(PPR_type_5==num)
C = textscan(char1, '%*s %s %f %c %f');
numeric_field = C{4};
par = setfield(par, field_, numeric_field);
elseif find(PPR_type_6==num)
C = textscan(char1, '%*s %s %f %c %f', 200);
field_ = char(C{1}); field_(end) = [];% the name of the array
num_elements = C{2}; % the number of elements of the array
numeric_field = C{4};
multiplier = [];
for l=4:numel(C)
multiplier = [multiplier C{l}];
end
pattern = ':';
k=1;
tline = char(cell_text{1}(j+k,:));
while (isempty(strfind(tline, pattern)))
tline = char(cell_text{1}(j+k,:));
arr = textscan(tline, '%*s %f', num_elements);
multiplier = [multiplier, arr{1}'];
k = k+1;
tline = char(cell_text{1}(j+k,:));
end
par = setfield(par, field_, multiplier);
elseif find(PPR_type_7==num) % :IM_ORIENTATION keyword
C = textscan(char1, '%s %f %f %f');
field_title = char(C{1}); field_title(1) = [];
numeric_field = [C{2}, C{3}, C{4}];
par = setfield(par, field_title, numeric_field);
elseif find(PPR_type_8==num) % GRADIENT_STRENGTH keyword
C=textscan(char1(20:end), '%s %d %d %d %d %d', 'Delimiter', ',', 'ReturnOnError', 0);
field_ = char(C{1});
multiplier(1) = C{3};
multiplier(2) = C{4};
multiplier(3) = C{5};
multiplier(4) = C{6};
par = setfield(par, field_, multiplier);
elseif find(PPR_type_9==num) % FOV_OFFSETS keyword
C = textscan(char1, '%s %d', 200);
field_ = char(C{1}); field_(1) = [];% the name of the array
num_elements = C{2}; % the number of elements of the array
multiplier = [];
for l=1:num_elements
tline = char(cell_text{1}(j+l,:));
arr = textscan(tline, '%*s %f', 3);
multiplier(l,1) = arr{1}(1);
multiplier(l,2) = arr{1}(2);
multiplier(l,3) = arr{1}(3);
end
par = setfield(par, field_, multiplier);
end
end
end
if isfield('OBSERVE_FREQUENCY','par')
C = textscan(par.OBSERVE_FREQUENCY, '%q');
text_field = char(C{1});
par.Nucleus = text_field(1,:);
else
par.Nucleus = 'Unspecified';
end
par.datatype = datatype;
file_pars = dir(filename);
par.date = file_pars.date;
else par = [];
end
par.scaling = scaling;
|
github
|
yhexie/particle-filter-localization-master
|
bresenham.m
|
.m
|
particle-filter-localization-master/bresenham.m
| 2,568 |
utf_8
|
dc4f9f7fd627abd3521074f046e9271e
|
function [myline,mycoords,outmat,X,Y] = bresenham(mymat,mycoordinates,dispFlag, threshold)
%#codegen
% BRESENHAM: Generate a line profile of a 2d image
% using Bresenham's algorithm
% [myline,mycoords] = bresenham(mymat,mycoordinates,dispFlag)
%
% - For a demo purpose, try >> bresenham();
%
% - mymat is an input image matrix.
%
% - mycoordinates is coordinate of the form: [x1, y1; x2, y2]
% which can be obtained from ginput function
%
% - dispFlag will show the image with a line if it is 1
%
% - myline is the output line
%
% - mycoords is the same as mycoordinates if provided.
% if not it will be the output from ginput()
% Author: N. Chattrapiban
%
% Ref: nprotech: Chackrit Sangkaew; Citec
% Ref: http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
%
% See also: tut_line_algorithm
% if nargin < 1, % for demo purpose
% pxl = 20;
% mymat = 1:pxl^2;
% mymat = reshape(mymat,pxl,pxl);
% disp('This is a demo.')
% end
%
% if nargin < 2, % if no coordinate provided
% imagesc(mymat); axis image;
% disp('Click two points on the image.')
% %[mycoordinates(1:2),mycoordinates(3:4)] = ginput(2);
% mycoordinates = ginput(2);
% end
%
% if nargin < 3, dispFlag = 1; end
outmat = mymat;
mycoords = mycoordinates;
[xmax, ymax] = size(outmat);
x = round(mycoords(:,1));
y = round(mycoords(:,2));
steep = (abs(y(2)-y(1)) > abs(x(2)-x(1)));
if steep,
[x,y] = swap(x,y);
[ymax, xmax] = swap(ymax, xmax);
end
delx = abs(x(2)-x(1));
dely = abs(y(2)-y(1));
myline = zeros(1, delx+dely+1);
X = zeros(1, delx+dely+1);
Y = zeros(1, delx+dely+1);
error = zeros(1, 'uint8');
x_n = x(1);
y_n = y(1);
if y(1) < y(2), ystep = 1; else ystep = -1; end
if x(1) < x(2), xstep = 1; else xstep = -1; end
for n = 1:delx+1
if steep,
myline(n) = mymat(y_n,x_n);
outmat(y_n,x_n) = 0;
X(n) = x_n;
Y(n) = y_n;
else
myline(n) = mymat(x_n,y_n);
outmat(x_n,y_n) = 0;
X(n) = y_n;
Y(n) = x_n;
end
x_n = x_n + xstep;
error = uint8(error + dely);
if bitshift(error,1) >= delx, % same as -> if 2*error >= delx,
y_n = y_n + ystep;
error = error - delx;
end
if myline(n) < threshold
break
end
if (y_n > ymax || y_n < 0 || x_n > xmax || x_n < 0)
break
end
end
% -> a(y,x)
% if dispFlag, imagesc(outmat);
% end
function [q,r] = swap(s,t)
% function SWAP
q = t; r = s;
|
github
|
ccaicedo/SCMBAT-master
|
PropMap_find_piece.m
|
.m
|
SCMBAT-master/Octave/PropMap_find_piece.m
| 4,556 |
utf_8
|
4d3a8b78a9f94ba1b7303735d59cd194
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
PropMap_find_piece.m
Function to find a power given at an azimuth, elevation angle and minimum distance
for a piecewise propagation map.
p: power at given orientation.
theta_0: azimuth angle
phi_0: elevation angle
Min_Dist: breakpoint distance.
PropMap: propagation map for the given transmitter/reciever.
%}
function [n0,d_break,n1] = PropMap_find_piece(theta_0,phi_0,PropMap,Min_Dist)
%disp("Inside the PropMap_find_piece function"), disp("theta_0 is: "), disp(theta_0), disp("phi_0 is:"), disp(phi_0), disp("PropMap is : "), disp(PropMap);
P=PropMap;
c=length(P);
ind_phi_s=0;
ind_phi_e=0;
ind_theta_s=0;
ind_theta_e=0;
%Finding all the indexes of 360 in PropogationMap, the vector index360 shall contain index of all theh 360s present in PowerMap
index360=find(P==360.0);
%This part identifies and marks the phi_s and phi_e, i.e. the block where required elevation resides
index=1;
ind_phi_curr=index;
ind_phi_nxt=index360(index)+1;
while true
if(phi_0>=P(ind_phi_curr) && phi_0<P(ind_phi_nxt))
ind_phi_s=ind_phi_curr;
ind_phi_e=ind_phi_nxt;
break;
end
ind_phi_curr=index360(index)+1;
ind_phi_nxt=index360(index+1)+1;
if(index==c)
break;
end
index++;
end
%This part identifies and marks the theta_s and theta_e indexes i.e. the piece where the required azimuth resides
n0=0;
d_break=0;
n1=0;
%disp("the phi at start is : "), disp(P(ind_phi_s));
%disp("the phi at end is : "), disp(P(ind_phi_e));
%disp("diff is : "), disp(ind_phi_e - ind_phi_s);
if(ind_phi_e - ind_phi_s == 5 || ind_phi_e - ind_phi_s == 7)
ind_theta_curr=ind_phi_s+1;
%disp("the theta current is : "), disp(P(ind_theta_curr));
%disp("the theta current + 1 is : "), disp(P(ind_theta_curr+1));
if(P(ind_theta_curr+1)==0) % 0 refers to linear type
%disp("it's linear type");
n0=P(ind_theta_curr+2);
d_break=0;
n1=0;
end
if(P(ind_theta_curr+1)==1) % 1 refers to piecewise linear
%disp("it's piecewise linear");
n0=P(ind_theta_curr+2);
d_break=P(ind_theta_curr+3);
n1=P(ind_theta_curr+4);
end
%disp("the values are: " ), disp(n0), disp(d_break), disp(n1);
else
ind_theta_next=ind_phi_s+1;
while index <= ind_phi_e-2
ind_theta_curr=ind_theta_next;
%disp("ind_theta_curr is: "), disp(P(ind_theta_curr));
% Finding next theta depends on whether we have linear or piecewise linear
if (P(ind_theta_curr + 1) == 0) % 0 refers to linear type
%disp("setting theta next for linear type");
ind_theta_next=ind_theta_curr+3;
elseif (P(ind_theta_curr + 1) == 1) % 1 refers to piecewise linear
%disp("setting theta next for piecewise linear");
ind_theta_next=ind_theta_curr+5;
endif
index=index+2;
%disp("ind_theta_next is: "), disp(P(ind_theta_next));
if(theta_0 >= P(ind_theta_curr) && theta_0 < P(ind_theta_next))
if(P(ind_theta_curr + 1) == 0) % 0 refers to linear type
%disp("it's linear type");
n0 = P(ind_theta_curr + 2);
d_break = 0;
n1 = 0;
end
if(P(ind_theta_curr + 1) == 1) % 1 refers to piecewise linear
%disp("it's piecewise linear");
n0 = P(ind_theta_curr + 2);
d_break = P(ind_theta_curr + 3);
n1 = P(ind_theta_curr + 4);
end
%disp("the values are: " ), disp(n0), disp(d_break), disp(n1);
break;
end
end
%disp("Exiting the PropMap_find_piece function")
end
|
github
|
ccaicedo/SCMBAT-master
|
BWRatedCompliance.m
|
.m
|
SCMBAT-master/Octave/BWRatedCompliance.m
| 1,425 |
utf_8
|
0bf79533fef231c4f5e1861208309fc3
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
BWRatedCompliance
Function to perform Bandwidth Rated Compatibility analysis
%}
function [epsd,compatBWMask_List] = BWRatedCompliance (bw, maxPSD)
compatBWMask_List=0;
load SCM_receiver_java.txt;
BWRated_BW_List=Rx_BWRatedList(1:2:end-1);
BWRated_Power_List=Rx_BWRatedList(2:2:end);
[ef_bw,epsd] = calculateEPSD (bw, maxPSD);
for i=1:length(BWRated_BW_List)
MaskPowerCriterion = min(Rx_UnderlayMask(2:2:end)+BWRated_Power_List(i));
MaskPowerCriterion=MaskPowerCriterion(1);
[baepsd] = calculateBAEPSD (bw, BWRated_BW_List(i), epsd);
if(baepsd<MaskPowerCriterion)
compatBWMask_List(i) = BWRated_BW_List(i);
else
end
end
endfunction
|
github
|
ccaicedo/SCMBAT-master
|
Coupler.m
|
.m
|
SCMBAT-master/Octave/Coupler.m
| 8,330 |
utf_8
|
ccd504c09378a7084ab7bd214abedccc
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
OctaveLauncher.m
Launcher file to handle all the calculations and processing related to Octave code.
Instead of interacting direct with the specific Octave files, the Java code will inreract with
this file and from here, all the required code will be launched.
execPattern - defines the pattern in which bandwidth and frequency components have to be executed in case of BTP and DC
%}
function [retVal1, retVal2, retVal3, retVal4] = Coupler(report_directory, method, logging, specTag, numOfTransmitterString, execPattern)
disp('displaying from the coupler file.');
disp(report_directory), disp(method), disp(logging), disp(numOfTransmitterString);
%converting string to decimal, so that we may loop over it.
numOfTransmitter = str2num(numOfTransmitterString)
switch (method)
case 'TotalPower'
rename('SCM_transmitter_java1.txt', 'SCM_transmitter_java.txt')
[Spec_mask_new,Underlay_mask] = DSA_TotPow(report_directory);
return;
case 'MaxPower'
rename('SCM_transmitter_java1.txt', 'SCM_transmitter_java.txt')
DSA_MaxPow(report_directory);
return;
case 'PlotBWRated'
disp('inside bandwidth switch case');
fig1=figure;
retval = plotBWRated();
saveas(fig1, 'Analysis_Figure_1.png');
movefile('Analysis_Figure_1.png', report_directory);
disp('inside RatedBW');
%initializing the return values
retVal1 = []
retVal2 = []
retVal3 = []
retVal4 = []
specTagIndex = 1
for i = 1:numOfTransmitter
%changing the name of the file
fileToBeReplaced = strcat('SCM_transmitter_java', num2str(i), '.txt')
disp('file to be replaced is: '), disp(fileToBeReplaced);
rename(fileToBeReplaced, 'SCM_transmitter_java.txt')
disp('rename done');
disp('spec Tag is : '), disp(specTag);
%fetch the specTagName from the specTagList
%get the length of next name
disp('trying to fetch length of specNameTag');
len = str2num(substr(specTag, specTagIndex, 2));
disp('len is '), disp(len);
specTagName = substr(specTag, specTagIndex+2, len);
disp('specTagName is: '), disp(specTagName);
%update the specTagIndex to point to next name
specTagIndex = specTagIndex+2+len
[SpecMask,PSD,BW,compatBWList] = TxMPSD();
plot(SpecMask(1:2:end-1),SpecMask(2:2:end),'r.-','LineWidth',2);
xpoint=(SpecMask(length(SpecMask)/2-1)+SpecMask(length(SpecMask)/2+1))/2;
minSpecPow=min(SpecMask(2:2:end));
text(xpoint,minSpecPow-1,specTagName);
#setting all the values to standard return value variable names
retVal1 = [retVal1, SpecMask]
retVal2 = [retVal2, PSD]
retVal3 = [retVal3, BW]
retVal4 = [retVal4, compatBWList, 123456.789]
disp('compatBWList is:'), disp(compatBWList);
disp('retval4 is:'), disp(retVal4);
endfor
saveas(fig1,'BWRatedAnalysis.png');
movefile('BWRatedAnalysis.png', report_directory);
return;
case 'PlotBTPRated'
disp('inside BTP switch case');
fig2=figure;
retval = plotBTPRated();
saveas(fig2, 'Analysis_Figure_1.png');
movefile('Analysis_Figure_1.png', report_directory);
%initializing the return values
retVal1 = []
retVal2 = []
retVal3 = []
retVal4 = []
%initialize specTagName index
specTagIndex = 1
for i = 1:numOfTransmitter
%changing the name of the file
fileToBeReplaced = strcat('SCM_transmitter_java', num2str(i), '.txt')
disp('file to be replaced is: '), disp(fileToBeReplaced);
rename(fileToBeReplaced, 'SCM_transmitter_java.txt')
disp('spec Tag is : '), disp(specTag);
%fetch the specTagName from the specTagList
%get the length of next name
disp('trying to fetch length of specNameTag');
len = str2num(substr(specTag, specTagIndex, 2));
disp('len is '), disp(len);
specTagName = substr(specTag, specTagIndex+2, len);
disp('specTagName is: '), disp(specTagName);
%update the specTagIndex to point to next name
specTagIndex = specTagIndex+2+len
%fetching whether it's frequency based or bandwidth based system
ch = substr(execPattern, i, 1)
disp('the char is:'), disp(ch);
%in case of freq
if(ch == "f")
[Spec_BTP,ExtSpecMask,compatBTPList] = TxHop_FreqList();
plot(ExtSpecMask(1:2:end-1),ExtSpecMask(2:2:end),'r.-','LineWidth',2);
xpoint=ExtSpecMask(1);
minSpecPow=min(ExtSpecMask(2:2:end));
text(xpoint,minSpecPow-1,specTagName);
#setting all the values to standard return value variable names
retVal1 = [retVal1, Spec_BTP]
retVal2 = [retVal2, ExtSpecMask]
retVal3 = [retVal3, compatBTPList, 123456.789]
endif
%in case of bandwidth
if(ch == "b")
[Spec_BTP,NewBandList,Spec_MaxPower,compatBTPList] = TxHop_BandList();
plot(NewBandList,Spec_MaxPower*ones(1,length(NewBandList)),'r.-','LineWidth',2);
xpoint=NewBandList(1);
minSpecPow=Spec_MaxPower;
text(xpoint,minSpecPow-1,specTagName);
#setting all the values to standard return value variable names
retVal1 = [retVal1, Spec_BTP]
retVal2 = [retVal2, NewBandList]
retVal3 = [retVal3, Spec_MaxPower]
retVal4 = [retVal4, compatBTPList, 123456.789]
endif
endfor
saveas(fig2,'BTPRatedAnalysis.png');
movefile('BTPRatedAnalysis.png', report_directory);
return;
case 'PlotDCRated'
disp('inside PlotDCRated');
fig3=figure;
%initializing the return values
retVal1 = []
retVal2 = []
retVal3 = []
retVal4 = []
for i = 1:numOfTransmitter
% changing the name of the file
fileToBeReplaced = strcat('SCM_transmitter_java', num2str(i), '.txt')
disp('file to be replaced is: '), disp(fileToBeReplaced);
rename(fileToBeReplaced, 'SCM_transmitter_java.txt')
%fetching whether it's frequency based or bandwidth based system
ch = substr(execPattern, i, 1)
disp('the char is:'), disp(ch);
%in case of freq
if(ch == "f")
[Spec_mask_new,p_Tx_new,compatDutyList] = TxDuty_FreqList();
#setting all the values to standard return value variable names
retVal1 = [retVal1, Spec_mask_new]
retVal2 = [retVal2, p_Tx_new]
retVal3 = [retVal3, compatDutyList, 123456.789]
endif
%in case of bandwidth
if(ch == "b")
[Spec_mask_new,p_Tx_new,compatDutyList] = TxDuty_BandList();
#setting all the values to standard return value variable names
retVal1 = [retVal1, Spec_mask_new]
retVal2 = [retVal2, p_Tx_new]
retVal3 = [retVal3, compatDutyList, 123456.789]
endif
endfor
saveas(fig3,'DCRatedAnalysis.png');
movefile('DCRatedAnalysis.png', report_directory);
return;
otherwise
%nothing to do!! We don't have a default case!!
return;
endswitch
|
github
|
ccaicedo/SCMBAT-master
|
TxDuty_FreqList.m
|
.m
|
SCMBAT-master/Octave/TxDuty_FreqList.m
| 5,179 |
utf_8
|
3da5aeb176c3a93dd680333ec55a4a76
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
TxDuty_FreqList.m
Function to perform compatibility computation if the underlay mask is
duty cycle rated and the spectrum mask is frequency listed
%}
function [Spec_mask_new,p_Tx_new,compatDutyList] = TxDuty_FreqList()
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
status=0;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
Power=Power+(10*log10(Rx_ResBW/1e-3));
Power=Power+p2;
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
Underlay_mask=Rx_UnderlayMask;
Underlay_freq_list=Underlay_mask(1:2:end-1);
Underlay_power_list=Underlay_mask(2:2:end);
Underlay_min_pow_freq=Underlay_freq_list( find(Underlay_power_list==min(Underlay_power_list)) );
%--- Start BTP and compatibility Analysis ---
%Compare if the SCMs are operating in the same time duration
%if((Tx_Start<Rx_Start && Tx_End<Rx_Start) || (Tx_Start>Rx_End && Tx_End>Rx_End) )
% disp('System is compatible')
% break;
% else
%end
%Compare frequency range
i0=1;
FreqList=0;
for i=1:length(Tx_FreqList)
if((Tx_SpecMask(1)+Tx_FreqList(i)<=Rx_UnderlayMask(1) && Tx_SpecMask(end-1)+Tx_FreqList(i)<=Rx_UnderlayMask(1)) || (Tx_SpecMask(1)+Tx_FreqList(i)>=Rx_UnderlayMask(end-1) && Tx_SpecMask(end-1)+Tx_FreqList(i)>=Rx_UnderlayMask(end-1)) )
else
FreqList(i0)=Tx_FreqList(i);
i0=i0+1;
end
end
if(FreqList==0)
disp(strcat('result: ', 'System is compatible'));
return;
end
DutyCylceList = Rx_DutyList(1:3:end-2);
DwellList = Rx_DutyList(2:3:end-1);
PowerAdj = Rx_DutyList(3:3:end);
Center_UnderlayFreq=(Underlay_freq_list(end)+Underlay_freq_list(1))/2;
diff=abs(Center_UnderlayFreq-FreqList);
ind = find(diff==min(diff));
Center_UnderlayFreq
FreqList(ind(1))
Spec_mask_new(1:2:end-1)=Spec_mask_new(1:2:end-1)+FreqList(ind(1));
Spec_freq_list=Spec_mask_new(1:2:end-1);
Spec_power_list=Spec_mask_new(2:2:end);
Spec_cent_freq=(Spec_freq_list(1)+Spec_freq_list(end))/2;
Spec_BW=Spec_mask_new(end-1)-Spec_mask_new(1);
Spec_MaxPower=max(Spec_power_list);
Spec_DutyCycle=Tx_DwellTime/Tx_RevisitPeriod;
% Execute total power method with each Duty cycle mask.
compatDutyList=0;
i1=1;
p_Tx_new=0;
for i=1:length(DutyCylceList)
if(Spec_DutyCycle<DutyCylceList(i) && Tx_DwellTime<(DwellList(i)*1000))
DutyUnderlayMask = Underlay_mask;
DutyUnderlayMask(2:2:end)=Underlay_mask(2:2:end)+PowerAdj(i);
%SCM compatibility
[p_Tx_new] = new_spectrum(Spec_mask_new,DutyUnderlayMask);
plot(p_Tx_new(1:2:end-1),p_Tx_new(2:2:end),'LineWidth',2);
hold all
[Power_Tx,Power_Tx_dB] = calculate_power(p_Tx_new,Rx_ResBW);
[p_Rx_new] = calculate_power_3dB(DutyUnderlayMask,Rx_ResBW);
[Power_Rx,Power_Rx_dB] = calculate_power(p_Rx_new,Rx_ResBW);
%Power_Tx_dB
AllowablePower=Power_Rx_dB;
Power_Margin_Difference = AllowablePower-Power_Tx_dB
if(AllowablePower>Power_Tx_dB)
compatDutyList(i1)=DutyCylceList(i);
i1=i1+1;
else
end
else
end
end
if(compatDutyList==0)
disp(strcat('result: ', 'System is not at all compatible'));
return;
else
disp(strcat('result: ', 'System compatible with: '));
disp(strcat('result: ', num2str(compatDutyList)));
return;
end
%figure
%plot(Tx_SpecMask(1:2:end-1),Tx_SpecMask(2:2:end),'b.-','LineWidth',2)
%hold all
%plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%fig1=figure;
%for i=1:length(BTP_BW_List)
%plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+BTP_Power_List(i),'b.-','LineWidth',2)
%hold all
%end
%plot(ExtSpecMask(1:2:end-1),ExtSpecMask(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%saveas(fig1,'BTPRatedFreqList.png')
end
|
github
|
ccaicedo/SCMBAT-master
|
calcNarrowBW.m
|
.m
|
SCMBAT-master/Octave/calcNarrowBW.m
| 1,658 |
utf_8
|
c1ccf20fe3468e32e84452cc6cf24472
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
calcNarrowBW.m
Function to calculate the banwidth of narrow band signals
BW: Bandwidth p0: spectrum mask representation: [f0,p0,f1,p1....fn,pn];
%}
function [BW] = calcNarrowBW(p0)
fv=p0(1:2:end-1);
pv=p0(2:2:end);
f1 = ( fv(1) + fv(end) )/2;
f2 = ( fv(1) + fv(end) )/2;
maxP=max(pv);
p1=find_power(f1,p0);
delP1 = maxP-p1;
while(abs(delP1-20)>0.1)
if(delP1>20)
f1= f1+0.0001;
p1=find_power(f1,p0);
else
f1= f1-0.0001;
p1=find_power(f1,p0);
end
delP1=maxP-p1;
end
maxP=max(pv);
p2=find_power(f2,p0);
delP2 = maxP-p2;
while(abs(delP2-20)>0.1)
if(delP2>20)
f2= f2-0.0001;
p2=find_power(f2,p0);
else
f2= f2+0.0001;
p2=find_power(f2,p0);
end
delP2=maxP-p2;
end
BW=f2-f1;
%fig1 = figure;
%plot(p0(1:2:end-1),p0(2:2:end),'r.-','LineWidth',2)
%hold all;
%stem(f1,p1,'b');
%stem(f2,p2,'b');
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
end
|
github
|
ccaicedo/SCMBAT-master
|
DSA_MaxPow.m
|
.m
|
SCMBAT-master/Octave/DSA_MaxPow.m
| 4,172 |
utf_8
|
dc43fe82b08a7f8b719bf331417d4c1b
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
DSA_MaxPow.m
Function to perform maximum power compatibility computations
%}
function [Spec_mask_new,Underlay_mask] = DSA_MaxPow(report_directory)
disp("the report directory is: " ), disp(report_directory);
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R)
%Compare if the SCMs are operating in the same time duration
%if((Tx_Start<Rx_Start && Tx_End<Rx_Start) || (Tx_Start>Rx_End && Tx_End>Rx_End) )
% disp('System is compatible')
% break;
% else
%end
%Compare frequency range
if((Tx_SpecMask(1)<Rx_UnderlayMask(1) && Tx_SpecMask(end-1)<Rx_UnderlayMask(1)) || (Tx_SpecMask(1)>Rx_UnderlayMask(end-1) && Tx_SpecMask(end-1)>Rx_SpecMask(end-1)) )
disp('System is compatible');
return;
end
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
%%---- Computations for the Receiver Model -------
rx_PowAdj = Rx_TotPow;
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
rx_PowAdj=rx_PowAdj+(10*log10(1e-3/Rx_ResBW));
rx_PowAdj=rx_PowAdj+p2;
Underlay_mask=Rx_UnderlayMask;
Underlay_mask(2:2:end) = Rx_UnderlayMask(2:2:end) + rx_PowAdj;
Underlay_freq_list=Underlay_mask(1:2:end-1);
Spec_freq_list=Spec_mask_new(1:2:end-1);
list_1=find(Underlay_freq_list(end)<Spec_freq_list);
if(isempty(list_1)==0)
Spec_freq_list=[Spec_freq_list(1:list_1(1)-1),Underlay_freq_list(end)];
p = find_power(Underlay_freq_list(end),Spec_mask_new);
Spec_mask_new=[Spec_mask_new(1:2*list_1(1)-2),Underlay_freq_list(end),p];
end
list_2=find(Spec_freq_list<Underlay_freq_list(1))
if(isempty(list_2)==0)
Spec_freq_list=[Underlay_freq_list(1),Spec_freq_list(list_2(end)+1:end)];
p2 = find_power(Underlay_freq_list(1),Spec_mask_new);
Spec_mask_new=[Underlay_freq_list(1),p2,Spec_mask_new(2*list_2(end)+1:end)];
end
fig1 = figure;
plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end),'b.-','LineWidth',2)
hold all
plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
saveas(fig1,'CompatAnalysis.png')
movefile('CompatAnalysis.png', report_directory)
%SCM compatibility
[P_diff] = MaxPow_Diff(Underlay_mask,Spec_mask_new);
ind=find(P_diff<0);
%Power_Tx_dB
PowerMargin = min((P_diff)); % the actual power margin is the negative of this value
if(isempty(ind)==1)
disp('System is compatible');
disp(PowerMargin * -1); % the system is compaitable when the power margin is negative
else
disp('System is not compatible');
disp(PowerMargin * -1);
end
end
|
github
|
ccaicedo/SCMBAT-master
|
freq_sort.m
|
.m
|
SCMBAT-master/Octave/freq_sort.m
| 1,375 |
utf_8
|
9132e23b975d0d792c1289e80d9abd1e
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
freq_sort.m
Function to sort two lists of frequencies f1 and f2 and return
the sorted list in f_new.
%}
function [f_new] = freq_sort(f1,f2)
f=sort([f1,f2]);
u=unique(f);
for i=1:length(u)
ind=find(f==u(i));
switch length(ind)
case 2
ind2=find(f1==u(i));
if(length(ind2)==1)
f(ind(1))=[];
else
end
case 3
f(ind(1))=[];
case 4
f(ind(1))=[];
f(ind(2))=[];
otherwise
end
end
f_new=f;
end
|
github
|
ccaicedo/SCMBAT-master
|
calculate_power_3dB.m
|
.m
|
SCMBAT-master/Octave/calculate_power_3dB.m
| 1,965 |
utf_8
|
6f8a072779b1f31d264978fdccdf4810
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
calculate_power_3dB.m
Function to calculate underlay mask within the 3dB region
p_new: new underlay mask,
p0: underlay mask representation: [f0,p0,f1,p1....fn,pn];
RBW: resolution bandwidth.
%}
function [p_new] = calculate_power_3dB(p0,RBW)
%disp("Inside the function calculate_power_3dB");
%disp("p0 is : ") , disp(p0);
fv=p0(1:2:end-1)*1e+6;
pv=p0(2:2:end);
%plot(fv,pv,'r-','LineWidth',2);
P_net=0;
pl=min(pv);
%po=pl*(10^(.3)); % unused variable
ind=find(pv==pl);
i1=ind(1);
i2=ind(end);
if(fv(i1)~=fv(i1-1))
b1=( pv(i1)-pv(i1-1) )./( fv(i1)-fv(i1-1) );
b0=pv(i1-1) - (b1*fv(i1-1));
f1=((pl+3)-b0)/b1;
p1=pl+3;
else
f1=fv(i1-1);
p1=pv(i1-1);
end
if(fv(i2)~=fv(i2+1))
b1=( pv(i2+1)-pv(i2) )./( fv(i2+1)-fv(i2) );
b0=pv(i2) - (b1*fv(i2));
f2=((pl+3)-b0)/b1;
p2=pl+3;
else
f2=fv(i2+1);
p2=pv(i2+1);
end
p_new=zeros(1,8);
p_new(1:2:end-1)=[f1,fv(i1),fv(i2),f2].*1e-6;
p_new(2:2:end)=[p1,pl,pl,p2];
%figure
%plot(p_new(1:2:end-1),p_new(2:2:end),'b-','LineWidth',2);
%disp("Exiting calculate_power_3dB function");
end
|
github
|
ccaicedo/SCMBAT-master
|
Hop_Analysis.m
|
.m
|
SCMBAT-master/Octave/Hop_Analysis.m
| 1,628 |
utf_8
|
90dab15cd51acf2f80a3ad9dd9a2c35d
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
Hop_Analysis.m
Function to perform BTP analysis for spectrum hopping systems.
%}
function [Hop_Result] = Hop_Analysis(Tx_Spec_mask,Rx_Spec_mask,Rx_BTP,Tx_FreqList,Tx_RevisitPeriod,Tx_DwellTime)
BTP_Data=Rx_BTP(1:2:end-1);
Tx_BW=Tx_Spec_mask(end-1)-Tx_Spec_mask(1);
Rx_BW=Rx_Spec_mask(end-1)-Rx_Spec_mask(1);
Tx_minFreq=Tx_FreqList(find(Tx_FreqList>Rx_Spec_mask(1)));
if(isempty(Tx_minFreq)==1)
Hop_Result=1;
else
Tx_NewFreqList=Tx_minFreq;
Tx_maxFreq=Tx_FreqList(find(Tx_NewFreqList<Rx_Spec_mask(end-1)));
if(isempty(Tx_maxFreq)==1)
Hop_Result=1;
else
Tx_NewFreqList=Tx_maxFreq;
n=length(Tx_NewFreqList);
Tx_BTP = n*Tx_BW*Tx_DwellTime*(1/Tx_RevisitPeriod);
BTP_index=find(BTP_Data>Tx_BTP);
Hop_Result=zeros(1,2*length(BTP_index));
Hop_Result(1:2:end-1)=Rx_BTP((2*BTP_index)-1);
Hop_Result(2:2:end)=Rx_BTP(2*BTP_index);
end
end
end
|
github
|
ccaicedo/SCMBAT-master
|
TxDuty_BandList.m
|
.m
|
SCMBAT-master/Octave/TxDuty_BandList.m
| 5,195 |
utf_8
|
b66c749cd23d988131f81a25f14b01f1
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
TxDuty_BandList.m
Function to perform compatibility computations if the underlay mask
is duty cycle rated and the spectrum mask uses a Band list
%}
function [Spec_mask_new,p_Tx_new,compatDutyList] = TxDuty_BandList()
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
status=0;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
Power=Power+(10*log10(Rx_ResBW/1e-3));
Power=Power+p2;
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
Underlay_mask=Rx_UnderlayMask;
Underlay_freq_list=Underlay_mask(1:2:end-1);
Underlay_power_list=Underlay_mask(2:2:end);
Underlay_min_pow_freq=Underlay_freq_list( find(Underlay_power_list==min(Underlay_power_list)) );
%--- Start BTP and compatibility Analysis ---
%Compare if the SCMs are operating in the same time duration
%if((Tx_Start<Rx_Start && Tx_End<Rx_Start) || (Tx_Start>Rx_End && Tx_End>Rx_End) )
% disp('System is compatible')
% break;
% else
%end
%Compare frequency range
i0=1;
NewBandList=sort([Tx_BandList,Underlay_freq_list(1),Underlay_freq_list(end)]);
ind0=find(NewBandList==Underlay_freq_list(1));
ind1=find(NewBandList==Underlay_freq_list(end));
NewBandList=NewBandList(ind0:ind1);
Center_UnderlayFreq=(Underlay_freq_list(end)+Underlay_freq_list(1))/2;
if(Center_UnderlayFreq>NewBandList(end))
Spec_mask_new(1:2:end-1)=Spec_mask_new(1:2:end-1)+NewBandList(end);
else
if(Center_UnderlayFreq<NewBandList(1))
Spec_mask_new(1:2:end-1)=Spec_mask_new(1:2:end-1)+NewBandList(1);
else
Spec_mask_new(1:2:end-1)=Spec_mask_new(1:2:end-1)+Center_UnderlayFreq;
end
end
if(NewBandList==0)
disp(strcat('result: ', 'System is compatible'));
return;
end
DutyCylceList = Rx_DutyList(1:3:end-2);
DwellList = Rx_DutyList(2:3:end-1);
PowerAdj = Rx_DutyList(3:3:end);
Spec_freq_list=Spec_mask_new(1:2:end-1);
Spec_power_list=Spec_mask_new(2:2:end);
Spec_cent_freq=(Spec_freq_list(1)+Spec_freq_list(end))/2;
Spec_BW=Spec_mask_new(end-1)-Spec_mask_new(1);
Spec_MaxPower=max(Spec_power_list);
Spec_DutyCycle=Tx_DwellTime/Tx_RevisitPeriod;
% Execute total power method with each Duty cycle mask.
compatDutyList=0;
i1=1;
p_Tx_new=0;
for i=1:length(DutyCylceList)
if(Spec_DutyCycle<DutyCylceList(i) && Tx_DwellTime<(DwellList(i)*1000))
DutyUnderlayMask = Underlay_mask;
DutyUnderlayMask(2:2:end)=Underlay_mask(2:2:end)+PowerAdj(i);
%SCM compatibility
[p_Tx_new] = new_spectrum(Spec_mask_new,DutyUnderlayMask);
%plot(p_Tx_new(1:2:end-1),p_Tx_new(2:2:end),'LineWidth',2);
[Power_Tx,Power_Tx_dB] = calculate_power(p_Tx_new,Rx_ResBW);
[p_Rx_new] = calculate_power_3dB(DutyUnderlayMask,Rx_ResBW);
[Power_Rx,Power_Rx_dB] = calculate_power(p_Rx_new,Rx_ResBW);
%Power_Tx_dB
AllowablePower=Power_Rx_dB;
Power_Margin_Difference = AllowablePower-Power_Tx_dB
if(AllowablePower>Power_Tx_dB)
compatDutyList(i1)=DutyCylceList(i);
i1=i1+1;
else
end
else
end
end
if(compatDutyList==0)
disp(strcat('result: ', 'System is not at all compatible'));
return;
else
disp(strcat('result: ', 'System compatible with: '));
disp(strcat('result: ', num2str(compatDutyList)));
return;
end
%figure
%plot(Tx_SpecMask(1:2:end-1),Tx_SpecMask(2:2:end),'b.-','LineWidth',2)
%hold all
%plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%fig1=figure;
%for i=1:length(BTP_BW_List)
%plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+BTP_Power_List(i),'b.-','LineWidth',2)
%hold all
%end
%plot(ExtSpecMask(1:2:end-1),ExtSpecMask(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%saveas(fig1,'BTPRatedFreqList.png')
end
|
github
|
ccaicedo/SCMBAT-master
|
plotBWRated.m
|
.m
|
SCMBAT-master/Octave/plotBWRated.m
| 1,493 |
utf_8
|
16bd8da1a24f69c79fb45500fbabc310
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
plotBWRated.m
Function to plot BW rated underlay masks
%}
function [retval] = plotBWRated ()
load SCM_receiver_java.txt;
BWRated_BW_List=Rx_BWRatedList(1:2:end-1);
BWRated_Power_List=Rx_BWRatedList(2:2:end);
plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end),'b-.','LineWidth',2)
hold all
for i=1:length(BWRated_BW_List)
newPowerList = Rx_UnderlayMask(2:2:end)+BWRated_Power_List(i);
xpoint=(Rx_UnderlayMask((length(Rx_UnderlayMask)/2)-1)+Rx_UnderlayMask((length(Rx_UnderlayMask)/2)+1))/2
plot(Rx_UnderlayMask(1:2:end-1),newPowerList,'b.-','LineWidth',2)
text(xpoint,min(newPowerList)+5,strcat(num2str(BWRated_BW_List(i)*1000), ' KHz'))
hold all
end
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
retval=0;
endfunction
|
github
|
ccaicedo/SCMBAT-master
|
calculate_power.m
|
.m
|
SCMBAT-master/Octave/calculate_power.m
| 1,840 |
utf_8
|
95de70ec56d9271e4aa1521cf86918d0
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
calculate_power.m
Function to calculate power under a spectrum/underlay mask
P_net: power under the spectrum/underlay mask,
P_net_dB: power under the spectrum/underlay mask in dB,
p0: spectrum/underlay mask representation: [f0,p0,f1,p1....fn,pn],
RBW: Resolution Bandwidth
%}
function [P_net,P_net_dB] = calculate_power(p0,RBW)
%disp("************* Inside calculate_power function **************");
RBW = RBW*1e+6; % adjusting RBW to Hertz (previously MHz)
fv=p0(1:2:end-1)*1e+6;
pv=p0(2:2:end);
%plot(fv,pv,'r-','LineWidth',2);
P_net=0;
for i=1:length(fv)-1
if(fv(i)~=fv(i+1))
b1=( pv(i+1)-pv(i) )./( fv(i+1)-fv(i) );
b0=pv(i) - (b1*fv(i));
if(b1~=0)
P_net=P_net + ( 10*( (10^((b0 + (b1*fv(i+1)))/10)) - (10^((b0+(b1*fv(i)))/10)) )./(RBW*log(10)*b1) );
else
P_net= P_net + ( (10^(b0/10)).*((fv(i+1)-fv(i))./RBW) );
end
else
end
P_net_dB=10*log10(P_net);
end
%disp("************* Exiting calculate_power function **************");
end
|
github
|
ccaicedo/SCMBAT-master
|
find_power.m
|
.m
|
SCMBAT-master/Octave/find_power.m
| 2,027 |
utf_8
|
475ad5565b5b74fd112c969fb7cdcf62
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
find_power.m
Function to find power at a given frequency in a spectrum/underlay mask.
p: power at the provided frequency.
f: frequency where power is to be found.
p0: spectrum/underlay mask representation : [f0,p0,f1,p1,...fn,pn]
%}
function [p] = find_power(fo,p0)
fv=p0(1:2:end-1);
pv=p0(2:2:end);
%disp("fv is: "), disp(fv);
%disp("pv is: "), disp(pv);
%plot(fv,pv,'r-','LineWidth',2);
ind=find(fo==fv);
%disp("ind is : " ), disp(ind);
if(isempty(ind)==1)
ind2=find(fv>fo);
%disp("ind2 is: "), disp(ind2);
if(isempty(ind2)==0)
i=min(ind2);
if(i==1)
p=pv(1);
%disp("i==1, and the power is :"), disp(p);
else
if(pv(i)==pv(i-1))
p=pv(i);
%disp("inside if, the power is :"), disp(p);
else
b1=(pv(i)-pv(i-1))./( fv(i)-fv(i-1) );
b0=pv(i-1)-(b1*fv(i-1));
p=b0+(b1*fo);
%disp("inside else, the power is :"), disp(p);
end
end
else
p=pv(end);
end
else
p=pv(ind);
end
%disp("the value of p is: "), disp(p);
end
|
github
|
ccaicedo/SCMBAT-master
|
PowerMap_find.m
|
.m
|
SCMBAT-master/Octave/PowerMap_find.m
| 2,380 |
utf_8
|
5bd83161e7f1b937e3a9d547e33dc599
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
PowerMap_find.m
Function to compute a power level given an azimuth and elevation angle for
a power map.
p: power at given orientation.
theta_0: azimuth angle
phi_0: elevation angle
PowerMap: power map for the given transmitter/reciever.
%}
function [p] = PowerMap_find(theta_0,phi_0,PowerMap)
P=PowerMap;
c=length(P);
ind_phi_s=0;
ind_phi_e=0;
ind_theta_s=0;
ind_theta_e=0;
%Finding all the indexes of 360 in PowerMap, the vector index360 shall contain index of all theh 360s present in PowerMap
index360=find(P==360.0);
%This part identifies and marks the phi_s and phi_e, i.e. the block where required elevation resides
index=1;
ind_phi_curr=index;
ind_phi_nxt=index360(index)+1;
while true
if(phi_0>=P(ind_phi_curr) && phi_0<P(ind_phi_nxt))
ind_phi_s=ind_phi_curr;
ind_phi_e=ind_phi_nxt;
break;
end
ind_phi_curr=index360(index)+1;
ind_phi_nxt=index360(index+1)+1;
if(index==c)
break;
end
index++;
end
%This part identifies and marks the theta_s and theta_e indexes i.e. the piece where the required azimuth resides
index=ind_phi_s+1;
if(ind_phi_e - ind_phi_s==3)
p=P(ind_phi_s+2);
%disp("the value of p(powermap) is: " ), disp(p);
else
while index <= ind_phi_e-2
ind_theta_curr=index;
ind_theta_next=index+2;
if(theta_0 >= P(ind_theta_curr) && theta_0 < P(ind_theta_next))
p=P(ind_theta_curr+1);
%disp("the value of p(powermap) is: " ), disp(p);
break;
end
index=index+2;
end
end
|
github
|
ccaicedo/SCMBAT-master
|
DSA_TotPow.m
|
.m
|
SCMBAT-master/Octave/DSA_TotPow.m
| 9,255 |
utf_8
|
bce88b50b4f3f40260032f4d3cc13ce0
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
DSA_TotPow.m
Function to perform total power method compatibility computations
%}
function [Spec_mask_new,Underlay_mask] = DSA_TotPow(report_directory)
load SCM_transmitter_java.txt;
disp("SCM_transmitter_java.txt loaded successfully");
load SCM_receiver_java.txt;
disp("SCM_receiver_java.txt loaded successfully");
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
disp("Getting the the min distance, elevation and azimuth angle: ");
disp("Calling function find_Compare");
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
disp("Values returned from find_direction are: ");
disp("phi_Txo: "), disp(phi_Txo), disp("theta_Txo: "), disp(theta_Txo), disp("Min_Dist: "), disp(Min_Dist);
%Compare frequency range
disp("Comparing Frequency range.");
if((Tx_SpecMask(1)<Rx_UnderlayMask(1) && Tx_SpecMask(end-1)<Rx_UnderlayMask(1)) || (Tx_SpecMask(1)>Rx_UnderlayMask(end-1) && Tx_SpecMask(end-1)>Rx_UnderlayMask(end-1)) )
disp('System is compatible');
return;
end
%Transmitter Power map attenuation to Total Power;
disp("Transmitter Power map attenuation to Total Power");
disp("Calling function PowerMap_find for Transmitter model with values:");
disp("phi_Txo: "), disp(phi_Txo), disp("theta_Txo: "), disp(theta_Txo), disp("Tx_PowerMap"), disp(Tx_PowerMap);
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
disp("the p (gain) value for transmitter is : "), disp(p);
disp("the total power value is: "), disp(Tx_TotPow);
Power=Tx_TotPow+p;
disp("the total power @ 'Power=Tx_TotPow+p' is : " ), disp(Power);
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
disp("Bringing the Reference Bandwidth to 1 Khz");
disp("the total power after adjustment (10*log10(1e-3/Tx_ResBW)) : " ), disp(Power);
%Attenuation due to Propagation Map
disp("Calling function PropMap_find_piece with values: ");
disp("theta_Txo: "), disp(theta_Txo), disp("phi_Txo: "), disp(phi_Txo), disp("Min_Dist"), disp(Min_Dist);
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
disp("the returned values for n0 is : " ), disp(n0), disp("for d_break: "), disp(d_break), disp("for n1: "), disp(n1);
disp("Checking if(Min_Dist>d_break && d_break!=0.0)");
if(Min_Dist>d_break && d_break!=0.0)
disp("condition is true, calculating 'Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break))'");
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
disp("Condition is false; calculating 'Power = Power - (10*n0*log(Min_Dist))'");
Power = Power - (10*n0*log(Min_Dist));
end
disp("After calculations the Power is : " ), disp(Power);
Spec_mask_new=Tx_SpecMask;
disp("Spec_mask @ 'Spec_mask_new=Tx_SpecMask' is : "), disp(Spec_mask_new);
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
disp("Spec_mask_new(2:2:end) @ 'Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power' is: "), disp(Spec_mask_new(2:2:end));
%%---- Computations for the Receiver Model -------
rx_PowAdj = Rx_TotPow;
%Attenuation due to the Receiver Power Map
disp("Attenuation due to the Receiver Power Map");
phi_Rxo=-phi_Txo;
disp("phi_Rxo after phi_Rxo=-phi_Txo is : "), disp(phi_Rxo);
disp("checking if(theta_Txo>180)");
if(theta_Txo>180)
disp("Condition true calculating 'theta_Rxo=theta_Txo-180'");
theta_Rxo=theta_Txo-180;
else
disp("Condition true, calculating theta_Rxo=theta_Txo+180");
theta_Rxo=theta_Txo+180;
end
disp("Calling function PowerMap_find for Receiver model.");
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
disp("the p (gain) power value for receiver model is : " ), disp(p2);
%Power=Power+(10*log10(Rx_ResBW/1e-3));
rx_PowAdj=rx_PowAdj+(10*log10(1e-3/Rx_ResBW));
%disp("Power @ Power=Power+(10*log10(Rx_ResBW/1e-3)): "), disp(Power);
disp("Power @ Power=Power+(10*log10(1e-3/Rx_ResBW)): "), disp(Power);
rx_PowAdj=rx_PowAdj+p2;
disp("Power @ 'Power=Power+p2' is : "), disp(Power);
% Adjusted Underlay Mask
Underlay_mask=Rx_UnderlayMask;
disp("Underlay_mask is: "), disp(Underlay_mask);
Underlay_mask(2:2:end) = Rx_UnderlayMask(2:2:end) + rx_PowAdj;
disp("Adjusted Underlay_mask is: "), disp(Underlay_mask(2:2:end));
Underlay_freq_list=Underlay_mask(1:2:end-1);
disp("Underlay_freq_list @ 'Underlay_freq_list=Underlay_mask(1:2:end-1)' is "), disp(Underlay_freq_list);
Spec_freq_list=Spec_mask_new(1:2:end-1);
disp("Spec_freq_list @ 'Spec_freq_list=Spec_mask_new(1:2:end-1)' " ), disp(Spec_freq_list);
list_1=find(Underlay_freq_list(end)<Spec_freq_list);
disp("list_1 @ 'list_1=find(Underlay_freq_list(end)<Spec_freq_list)'is: "), disp(list_1);
if(isempty(list_1)==0)
Spec_freq_list=[Spec_freq_list(1:list_1(1)-1),Underlay_freq_list(end)];
disp("Spec_freq_list @ 'Spec_freq_list=[Spec_freq_list(1:list_1(1)-1),Underlay_freq_list(end)'] is: "), disp(Spec_freq_list);
disp("calling find_power with the values: "), disp("Underlay_freq_list(end) :"), disp(Underlay_freq_list(end)), disp("Spec_mask_new"), disp(Spec_mask_new);
p = find_power(Underlay_freq_list(end),Spec_mask_new);
disp("returning from find_power, the value of p is: "), disp(p);
Spec_mask_new=[Spec_mask_new(1:2*list_1(1)-2),Underlay_freq_list(end),p];
disp("Spec_mask_new @ 'Spec_mask_new=[Spec_mask_new(1:2*list_1(1)-2),Underlay_freq_list(end),p]' is : "), disp(Spec_mask_new);
end
list_2=find(Spec_freq_list<Underlay_freq_list(1));
disp("list_2 @ 'list_2=find(Spec_freq_list<Underlay_freq_list(1))' is: "), disp(list_2);
if(isempty(list_2)==0)
Spec_freq_list=[Underlay_freq_list(1),Spec_freq_list(list_2(end)+1:end)];
disp("Spec_freq_list @ 'Spec_freq_list=[Underlay_freq_list(1),Spec_freq_list(list_2(end)+1:end)]"), disp(Spec_freq_list);
disp("calling find_power with the values: "), disp("Underlay_freq_list(1) :"), disp(Underlay_freq_list(1)), disp("Spec_mask_new"), disp(Spec_mask_new);
p2 = find_power(Underlay_freq_list(1),Spec_mask_new);
disp("returning from find_power, the value of p is: "), disp(p2);
Spec_mask_new=[Underlay_freq_list(1),p2,Spec_mask_new(2*list_2(end)+1:end)];
disp("Spec_mask_new @ 'Spec_mask_new=[Underlay_freq_list(1),p2,Spec_mask_new(2*list_2(end)+1:end)]' is : "), disp(Spec_mask_new);
end
disp("Plotting Analysis_Figure_1.png");
fig1 = figure ();
plot(Tx_SpecMask(1:2:end-1),Tx_SpecMask(2:2:end),'b.-','LineWidth',2)
hold all
plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
title("Analysis Figure 1");
saveas(fig1, 'Analysis_Figure_1.png');
movefile('Analysis_Figure_1.png', report_directory);
%this pause value is used to allow the octave code to flush the first figure and create the second figure, in the absense of this pause, the second figure might not get generated.
%this pause value might need to be increased for the slower systems. (initially set to .4 seconds)
pause (.4);
disp("Plotting CompatAnalysis.png");
fig2 = figure ();
plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end),'b.-','LineWidth',2)
hold all
plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
title("Compat Analysis");
saveas(fig2,'CompatAnalysis.png');
movefile('CompatAnalysis.png', report_directory);
%SCM compatibility
[p_Tx_new] = new_spectrum(Spec_mask_new,Underlay_mask);
disp("[p_Tx_new] @ '[p_Tx_new] = new_spectrum(Spec_mask_new,Underlay_mask)' is : "), disp([p_Tx_new]);
[Power_Tx,Power_Tx_dB] = calculate_power(p_Tx_new,Rx_ResBW);
disp("[Power_Tx,Power_Tx_dB] @ [Power_Tx,Power_Tx_dB] = calculate_power(p_Tx_new,Rx_ResBW) is: "), disp([Power_Tx,Power_Tx_dB]);
[p_Rx_new] = calculate_power_3dB(Underlay_mask,Rx_ResBW);
disp("[p_Rx_new] @ [p_Rx_new] = calculate_power_3dB(Underlay_mask,Rx_ResBW)' is : "), disp([p_Rx_new]);
[Power_Rx,Power_Rx_dB] = calculate_power(p_Rx_new,Rx_ResBW);
disp("[Power_Rx,Power_Rx_dB] @ '[Power_Rx,Power_Rx_dB] = calculate_power(p_Rx_new,Rx_ResBW)' is : "), disp([Power_Rx,Power_Rx_dB]);
%Power_Tx_dB
AllowablePower=Power_Rx_dB;
Power_Margin_Difference = Power_Tx_dB-AllowablePower;
if(AllowablePower>Power_Tx_dB)
disp('System is compatible');
disp(Power_Margin_Difference);
else
disp('System is not compatible');
disp(Power_Margin_Difference);
end
end
|
github
|
ccaicedo/SCMBAT-master
|
calculateEPSD.m
|
.m
|
SCMBAT-master/Octave/calculateEPSD.m
| 1,209 |
utf_8
|
5748ff810dea09f6e62c94d935369742
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
calculateEPSD.m
Function to calculate Effective power spectral density of narrow
band signals
ef_bw: Effective Bandwidth,
epsd: Effective power spectral density,
bw: vector of Bandwidth of narrowband signals [bw_0,bw_1,....bw_n],
maxPSD: vector of Maximum power density of narrow band signals [MPSD0,MPSD1,... MPSDn].
%}
function [ef_bw,epsd] = calculateEPSD (bw, maxPSD)
ef_bw=sum(bw);
epsd= 10*log10( sum(bw.*(10.^(maxPSD./10)))/sum(bw) );
endfunction
|
github
|
ccaicedo/SCMBAT-master
|
new_spectrum.m
|
.m
|
SCMBAT-master/Octave/new_spectrum.m
| 2,533 |
utf_8
|
bec979afc4bff8aa6dba4d48d96e0614
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
new_spectrum.m
Function to generate adjusted spectrum mask
pv_new: new spectrum mask [f0,p0,f1,p1,f2,p2...fn,pn]
ps: spectrum mask representation: [f0,p0,f1,p1....fn,pn];
pr: underlay mask representation: [f0,p0,f1,p1....fn,pn];
%}
function [pv_new] = new_spectrum(ps,pr)
%disp("Inside new_spectrum function");
fs=ps(1:2:end-1);
PS=ps(2:2:end);
fr=pr(1:2:end-1);
PR=pr(2:2:end);
%disp("fs is " ), disp(fs);
%disp("PS is "), disp(PS);
%disp("fr is "), disp(fr);
%disp("PR is "), disp(PR);
f_new=freq_sort(fs,fr);
%disp("f_new is :"), disp(f_new);
pl=min(PR);
%disp("pl is " ), disp(pl);
for i=1:length(f_new)
%disp("the value of i is: "), disp(i);
fo=f_new(i);
ps_v=find_power(fo,ps);
if(length(ps_v)>1) %Given that there can't be more than two same frequencies in the frequency vector
if(f_new(i)==f_new(i+1))
ps_i=ps_v(1);
else
ps_i=ps_v(2);
end
else
ps_i=ps_v;
end
%disp("f0 is :"), disp(fo);
%disp("ps_v is :"), disp(ps_v);
%disp("ps_i is :"), disp(ps_i);
pr_v=find_power(fo,pr);
if(length(pr_v)>1) %Given that there can't be more than two same frequencies in the frequency vector
if(f_new(i)==f_new(i+1))
pr_i=pr_v(1);
else
pr_i=pr_v(2);
end
else
pr_i=pr_v;
end
%disp("pr_v is : "), disp(pr_v);
%disp("pr_i is : "), disp(pr_i);
p_new(i)=ps_i+pl-pr_i;
%disp("p_new is : "), disp(p_new);
end
%figure
%plot(f_new,p_new,'r.-','LineWidth',2);
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
pv_new=zeros(1,2*length(f_new));
pv_new(1:2:end-1)=f_new;
pv_new(2:2:end)=p_new;
%disp("Exiting new_spectrum function");
end
|
github
|
ccaicedo/SCMBAT-master
|
compat.m
|
.m
|
SCMBAT-master/Octave/compat.m
| 1,942 |
utf_8
|
3acb27129a17270c97de12952378ac09
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
compat.m
Function to generate adjusted spectrum mask.
p_new: power list for new spectrum mask: [p0,p1,p2...pn]
f_new: frequency list for new spectrum mask: [f0,f1,f2...fn]
ps: spectrum mask representation: [f0,p0,f1,p1....fn,pn];
pr: underlay mask representation: [f0,p0,f1,p1....fn,pn];
%}
function [p_new,f_new] = compat(ps,pr)
fs=ps(1:2:end-1);
PS=ps(2:2:end);
fr=pr(1:2:end-1);
PR=pr(2:2:end);
[f_new] = freq_sort(fs,fr);
pl=min(PR);
for i=1:length(f_new)
fo=f_new(i);
ps_v=find_power(fo,ps);
if(length(ps_v)>1) %Given that there can't be more than two same frequencies in the frequency vector
if(f_new(i)==f_new(i+1))
ps_i=ps_v(1);
else
ps_i=ps_v(2);
end
else
ps_i=ps_v;
end
pr_v=find_power(fo,pr);
if(length(pr_v)>1) %Given that there can't be more than two same frequencies in the frequency vector
if(f_new(i)==f_new(i+1))
pr_i=pr_v(1);
else
pr_i=pr_v(2);
end
else
pr_i=pr_v;
end
p_new(i)=ps_i+pl-pr_i;
end
figure
plot(f_new,p_new,'r-','LineWidth',2);
end
|
github
|
ccaicedo/SCMBAT-master
|
plotBTPRated.m
|
.m
|
SCMBAT-master/Octave/plotBTPRated.m
| 1,606 |
utf_8
|
7ba0ec5f03f638f1b6a7d547a4c1df20
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
plotBTPRated.m
Function to plot BTP rated underlay masks
%}
function [retval] = plotBTPRated ()
load SCM_receiver_java.txt;
BTPRated_BW_List=Rx_BTPRatedList(1:2:end-1);
BTPRated_Power_List=Rx_BTPRatedList(2:2:end);
plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end),'b-.','LineWidth',2)
hold all
for i=1:length(BTPRated_BW_List)
%plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+BTPRated_Power_List(i),'b.-','LineWidth',2)
newPowerList = Rx_UnderlayMask(2:2:end)+BTPRated_Power_List(i);
xpoint=(Rx_UnderlayMask((length(Rx_UnderlayMask)/2)-1)+Rx_UnderlayMask((length(Rx_UnderlayMask)/2)+1))/2;
plot(Rx_UnderlayMask(1:2:end-1),newPowerList,'b.-','LineWidth',2)
text(xpoint,min(newPowerList)+5,strcat(num2str(BTPRated_BW_List(i)), ' MHz.sec'))
hold all
end
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
retval=0;
endfunction
|
github
|
ccaicedo/SCMBAT-master
|
TxMPSD.m
|
.m
|
SCMBAT-master/Octave/TxMPSD.m
| 4,454 |
utf_8
|
16d7efcfa51e5d81835e1db0e94904ac
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
TxMPSD.m
Function to calculate the maximum power spectral density for narrow band
spectrum masks
%}
function [Spec_mask_new,MaxPSD,Spec_BW,compatBWRatedList] = TxMPSD ()
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
status=0;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
disp('orientation');
[phi_Txo,theta_Txo,Min_Dist]
%Compare frequency range
if((Tx_SpecMask(1)<Rx_UnderlayMask(1) && Tx_SpecMask(end-1)<Rx_UnderlayMask(1)) || (Tx_SpecMask(1)>Rx_UnderlayMask(end-1) && Tx_UnderlayMask(end-1)>Rx_SpecMask(end-1)) )
disp(strcat('result: ', 'System is compatible'));
return;
end
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
Power=Power+(10*log10(Rx_ResBW/1e-3));
Power=Power+p2;
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
Underlay_mask=Rx_UnderlayMask
Underlay_freq_list=Underlay_mask(1:2:end-1);
Underlay_power_list=Underlay_mask(2:2:end);
Underlay_min_pow_freq=Underlay_freq_list( find(Underlay_power_list==min(Underlay_power_list)) );
BWRated_BW_List=Rx_BWRatedList(1:2:end-1);
BWRated_Power_List=Rx_BWRatedList(2:2:end);
Spec_freq_list=Spec_mask_new(1:2:end-1);
Spec_power_list=Spec_mask_new(2:2:end);
Spec_cent_freq=(Spec_freq_list(1)+Spec_freq_list(end))/2;
Spec_BW=calcNarrowBW(Spec_mask_new); %Spec_freq_list(end)-Spec_freq_list(1);
Spec_MaxPower=max(Spec_power_list);
Compat_BWRated_Masks1=[];
Compat_BWRated_Masks2=[];
i0=1;
i1=1;
for i=1:length(BWRated_BW_List)
BWRatedMask=Underlay_mask;
BWRatedMask(2:2:end)=BWRatedMask(2:2:end)+BWRated_Power_List(i);
MaxPSD=Spec_MaxPower;
MaxPSD
Underlay_pow_cent=find_power(Spec_cent_freq,BWRatedMask);
if(Spec_MaxPower<Underlay_pow_cent && Spec_BW<=BWRated_BW_List(i))
if(Spec_cent_freq<Underlay_min_pow_freq(1) || Spec_cent_freq>Underlay_min_pow_freq(end))
Compat_BWRated_Masks1((2*i0)-1:(2*i0))=[BWRated_BW_List(i),BWRated_Power_List(i)];
MaxPSD=min(BWRatedMask(2:2:end))-(Underlay_pow_cent-Spec_MaxPower);
i0=i0+1;
else
Compat_BWRated_Masks2((2*i1)-1:(2*i1))=[BWRated_BW_List(i),BWRated_Power_List(i)];
MaxPSD=Spec_MaxPower;
i1=i1+1;
end
else
end
end
MaxPSD=min(MaxPSD);
if(length(Compat_BWRated_Masks1)==length(Rx_BWRatedList) || length(Compat_BWRated_Masks2)==length(Rx_BWRatedList))
compatBWRatedList=1;
disp('1');
disp(MaxPSD);
disp(Spec_BW);
disp(Spec_mask_new);
else
if(isempty(Compat_BWRated_Masks1)==0)
compatBWRatedList=Compat_BWRated_Masks1;
disp(Compat_BWRated_Masks1);
disp(MaxPSD);
disp(Spec_BW);
disp(Spec_mask_new);
else
if(isempty(Compat_BWRated_Masks2)==0)
compatBWRatedList=Compat_BWRated_Masks2;
disp(Compat_BWRated_Masks2);
disp(MaxPSD);
disp(Spec_BW);
disp(Spec_mask_new);
else
compatBWRatedList=0;
disp('0');
disp(MaxPSD);
disp(Spec_BW);
disp(Spec_mask_new);
end
end
end
disp('Spec BW')
Spec_BW
MaxPSD
end
|
github
|
ccaicedo/SCMBAT-master
|
TxHop_FreqList.m
|
.m
|
SCMBAT-master/Octave/TxHop_FreqList.m
| 4,842 |
utf_8
|
5f34647f595fb1e083895f40f609afa0
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
TxHop_FreqList.m
Function to perform compatibility calculation if the underlay mask is
BTP rated and the spectrum mask is frequency listed.
%}
function [Spec_BTP,ExtSpecMask,compatBWList] = TxHop_FreqList()
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
status=0;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
Power=Power+(10*log10(Rx_ResBW/1e-3));
Power=Power+p2;
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
Underlay_mask=Rx_UnderlayMask;
Underlay_freq_list=Underlay_mask(1:2:end-1);
Underlay_power_list=Underlay_mask(2:2:end);
Underlay_min_pow_freq=Underlay_freq_list( find(Underlay_power_list==min(Underlay_power_list)) );
%--- Start BTP and compatibility Analysis ---
%Compare if the SCMs are operating in the same time duration
%if((Tx_Start<Rx_Start && Tx_End<Rx_Start) || (Tx_Start>Rx_End && Tx_End>Rx_End) )
% disp('System is compatible')
% break;
% else
%end
%Compare frequency range
i0=1;
FreqList=0;
ExtSpecMask=zeros(1,length(Spec_mask_new));
for i=1:length(Tx_FreqList)
if((Tx_SpecMask(1)+Tx_FreqList(i)<=Rx_UnderlayMask(1) && Tx_SpecMask(end-1)+Tx_FreqList(i)<=Rx_UnderlayMask(1)) || (Tx_SpecMask(1)+Tx_FreqList(i)>=Rx_UnderlayMask(end-1) && Tx_SpecMask(end-1)+Tx_FreqList(i)>=Rx_UnderlayMask(end-1)) )
else
FreqList(i0)=Tx_FreqList(i);
ExtSpecMask(i0,2:2:end)=Spec_mask_new(2:2:end);
ExtSpecMask(i0,1:2:end-1)=Spec_mask_new(1:2:end-1)+Tx_FreqList(i);
i0=i0+1;
end
end
matrixSize=size(ExtSpecMask);
ExtSpecMask=reshape(ExtSpecMask',1,matrixSize(1)*matrixSize(2));
if(FreqList==0)
disp('FreqList is 0');
disp(strcat('result: ', 'System is compatible'));
return;
end
BTP_BW_List=Rx_BTPRatedList(1:2:end-1);
BTP_Power_List=Rx_BTPRatedList(2:2:end);
Underlay_BW = Underlay_freq_list(end)-Underlay_freq_list(1);
Spec_freq_list=Spec_mask_new(1:2:end-1);
Spec_power_list=Spec_mask_new(2:2:end);
Spec_cent_freq=(Spec_freq_list(1)+Spec_freq_list(end))/2;
Spec_BW=Spec_mask_new(end-1)-Spec_mask_new(1);
Spec_MaxPower=max(Spec_power_list);
bwList=ones(1,length(FreqList))*Spec_BW;
td=ones(1,length(FreqList))*Tx_DwellTime;
tr=ones(1,length(FreqList))*Tx_RevisitPeriod;
Spec_BTP=findBTP(bwList,td,tr);
compatBWList=0;
i2=1;
for i=1:length(BTP_BW_List)
BTPMask=Underlay_mask;
BTPMask(2:2:end)=Underlay_mask(2:2:end)+BTP_Power_List(i);
minBTPMask=min(BTPMask(2:2:end));
if(Spec_MaxPower<minBTPMask && Spec_BTP<BTP_BW_List(i))
compatBWList(i2)=BTP_BW_List(i);
i2=i2+1;
else
end
end
if(compatBWList==0)
disp(strcat('result: ', 'System is not at all compatible'));
return;
else
disp(strcat('result: ', 'System is compatible'));
disp(compatBWList);
return;
end
%figure
%plot(Tx_SpecMask(1:2:end-1),Tx_SpecMask(2:2:end),'b.-','LineWidth',2)
%hold all
%plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%fig1=figure;
%for i=1:length(BTP_BW_List)
%plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+BTP_Power_List(i),'b.-','LineWidth',2)
%hold all
%end
%plot(ExtSpecMask(1:2:end-1),ExtSpecMask(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%saveas(fig1,'BTPRatedFreqList.png')
end
function BTP = findBTP(bw,td,tr)
BTP = sum(bw.*td./tr)*1e+6;
end
|
github
|
ccaicedo/SCMBAT-master
|
plotDutyRated.m
|
.m
|
SCMBAT-master/Octave/plotDutyRated.m
| 1,190 |
utf_8
|
1dfa2e97051ccd11e14fcd557a188e25
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
plotDutyRated.m
Function to plot Duty cycle rated underlay masks.
%}
function [retval] = plotDutyRated ()
load SCM_receiver_java.txt;
DutyRated_List=Rx_DutyList(1:2:end-1);
DutyRated_PowerList=Rx_DutyList(2:2:end);
for i=1:length(DutyRated_List)
plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+DutyRated_PowerList(i),'b.-','LineWidth',2)
hold all
end
grid on
xlabel('Frequency (MHz)');
ylabel('Power (dB)');
retval=0;
endfunction
|
github
|
ccaicedo/SCMBAT-master
|
find_direction.m
|
.m
|
SCMBAT-master/Octave/find_direction.m
| 2,349 |
utf_8
|
10cf744c1dbbb51537d71471489fa466
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
find_direction.m
Function to find distance, azimuth angle and elevation based on
Transmitter and Receiver location (geographical coordinates)
e: elevation angle
az: azimuth angle
d: distance
T: Geographical coordinates for the transmitter
R: Geographical coordinates for the receiver.
%}
function [e,az,d] = find_direction(T,R)
% T(1)-Lat T(2)-Long T(3)-Height
T(1)=T(1)*pi/180;
T(2)=T(2)*pi/180;
R(1)=R(1)*pi/180;
R(2)=R(2)*pi/180;
a=6378137;
E=0.0818191908426;
er=6367495;
v_t=a/( (1-((E*sin(T(1))).^2)).^0.5);
x_t=(v_t+T(3))*cos(T(1))*cos(T(2));
y_t=(v_t+T(3))*cos(T(1))*sin(T(2));
z_t=( (v_t*(1-(E.^2))) + T(3) )*sin(T(1));
v_r=a/( (1-((E*sin(R(1))).^2)).^0.5);
x_r=(v_r+R(3))*cos(R(1))*cos(R(2));
y_r=(v_r+R(3))*cos(R(1))*sin(R(2));
z_r=( (v_r*(1-(E.^2))) + R(3) )*sin(R(1));
%Finding Coordinates
%C_r=[x_r,y_r,z_r]
%C_t=[x_t,y_t,z_t]
%Plotting Coordinates
%figure
%plot3(x_r-x_t,y_r-y_t,z_r-z_t,'rx','Linewidth',2)
%hold all
%plot3(0,0,0,'bo','Linewidth',2)
d=( ((x_t-x_r).^2) + ((y_t-y_r).^2) + ((z_t-z_r).^2) ).^0.5;
% Finding the angle and curvature
d_t=( (x_t^2) + (y_t^2) + (z_t^2) ).^0.5;
d_r=( (x_r^2) + (y_r^2) + (z_r^2) ).^0.5;
w= acos( ( (x_t*x_r)+(y_t*y_r)+(z_t*z_r) )/(d_t*d_r) );
%d= er*w;
tan_theta=(y_r-y_t)./(x_r-x_t);
sin_phi=(z_r-z_t)./d;
if(y_r>y_t && x_r>x_t)
theta=atan(tan_theta)*180/pi;
elseif(y_r>y_t && x_r<x_t)
theta=180 + (atan(tan_theta)*180/pi) ;
elseif(y_r<y_t && x_r<x_t)
theta=180 + (atan(tan_theta)*180/pi);
elseif(y_r<y_t && x_r>x_t)
theta=360 + (atan(tan_theta)*180/pi);
end
phi=asin(sin_phi)*180/pi;
e=phi;
az=theta;
end
|
github
|
ccaicedo/SCMBAT-master
|
TxHop_BandList.m
|
.m
|
SCMBAT-master/Octave/TxHop_BandList.m
| 4,478 |
utf_8
|
31f1fac8825eacd42ba320bb8dddd616
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
TxHop_BandList.m
Function to perform compatibility if the underlay mask is BTP rated,
and the spectrum mask is Band listed.
%}
function [Spec_BTP,NewBandList,Spec_MaxPower,compatBWList] = TxHop_BandList()
load SCM_transmitter_java.txt;
load SCM_receiver_java.txt;
status=0;
%Gets the min distance, elevation and azimuth angle
T=[Tx_Lat,Tx_Long,Tx_Alt];
R=[Rx_Lat,Rx_Long,Rx_Alt];
[phi_Txo,theta_Txo,Min_Dist]=find_direction(T,R);
%Transmitter Power map attenuation to Total Power;
p=PowerMap_find(theta_Txo,phi_Txo,Tx_PowerMap);
Power=Tx_TotPow+p;
Power=Power+(10*log10(1e-3/Tx_ResBW)); % Bringing the Reference Bandwidth to 1 Khz;
%Attenuation due to Propagation Map
[n0,d_break,n1]=PropMap_find_piece(theta_Txo,phi_Txo,Tx_PropMap,Min_Dist);
if(Min_Dist>d_break && d_break!=0.0)
Power = Power - (10*n0*log10(d_break)) - (10*n1*log10(Min_Dist/d_break));
else
Power = Power - (10*n0*log(Min_Dist));
end
%Attenuation due to the Receiver Power Map
phi_Rxo=-phi_Txo;
if(theta_Txo>180)
theta_Rxo=theta_Txo-180;
else
theta_Rxo=theta_Txo+180;
end
p2=PowerMap_find(theta_Rxo,phi_Rxo,Rx_PowerMap);
Power=Power+(10*log10(Rx_ResBW/1e-3));
Power=Power+p2;
Spec_mask_new=Tx_SpecMask;
Spec_mask_new(2:2:end)=Tx_SpecMask(2:2:end)+Power;
Underlay_mask=Rx_UnderlayMask;
Underlay_freq_list=Underlay_mask(1:2:end-1);
Underlay_power_list=Underlay_mask(2:2:end);
Underlay_min_pow_freq=Underlay_freq_list( find(Underlay_power_list==min(Underlay_power_list)) );
%--- Start BTP and compatibility Analysis ---
%Compare if the SCMs are operating in the same time duration
%if((Tx_Start<Rx_Start && Tx_End<Rx_Start) || (Tx_Start>Rx_End && Tx_End>Rx_End) )
% disp('System is compatible')
% break;
% else
%end
%Compare frequency range
i0=1;
ExtSpecMask=zeros(1,length(Spec_mask_new));
NewBandList=sort([Tx_BandList,Underlay_freq_list(1),Underlay_freq_list(end)]);
ind0=find(NewBandList==Underlay_freq_list(1));
ind1=find(NewBandList==Underlay_freq_list(end));
NewBandList=NewBandList(ind0:ind1);
BTP_BW_List=Rx_BTPRatedList(1:2:end-1);
BTP_Power_List=Rx_BTPRatedList(2:2:end);
Underlay_BW = Underlay_freq_list(end)-Underlay_freq_list(1);
Spec_freq_list=Spec_mask_new(1:2:end-1);
Spec_power_list=Spec_mask_new(2:2:end);
Spec_cent_freq=(Spec_freq_list(1)+Spec_freq_list(end))/2;
Spec_BW=Spec_mask_new(end-1)-Spec_mask_new(1);
Spec_MaxPower=max(Spec_power_list);
Band_high=Tx_BandList(2:2:end);
Band_low=Tx_BandList(1:2:end-1);
BW_total=sum(Band_high-Band_low);
NewBand_high=NewBandList(2:2:end);
NewBand_low=NewBandList(1:2:end-1);
NewBW_total=sum(NewBand_high-NewBand_low);
Spec_BTP=NewBW_total*Spec_BW*Tx_DwellTime*1e+6/(BW_total*Tx_RevisitPeriod);
compatBWList=0;
i2=1;
for i=1:length(BTP_BW_List)
BTPMask=Underlay_mask;
BTPMask(2:2:end)=Underlay_mask(2:2:end)+BTP_Power_List(i);
minBTPMask=min(BTPMask(2:2:end));
if(Spec_MaxPower<minBTPMask && Spec_BTP<BTP_BW_List(i))
compatBWList(i2)=BTP_BW_List(i);
i2=i2+1;
else
end
end
if(compatBWList==0)
disp(strcat('result: ', 'System is not at all compatible'));
return;
else
disp(strcat('result: ', 'System compatible with: '));
disp(strcat('result: ', num2str(compatBWList)));
return;
end
%figure
%plot(Tx_SpecMask(1:2:end-1),Tx_SpecMask(2:2:end),'b.-','LineWidth',2)
%hold all
%plot(Spec_mask_new(1:2:end-1),Spec_mask_new(2:2:end),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%fig1=figure;
%for i=1:length(BTP_BW_List)
%plot(Rx_UnderlayMask(1:2:end-1),Rx_UnderlayMask(2:2:end)+BTP_Power_List(i),'b.-','LineWidth',2)
%hold all
%end
%plot(NewBandList,Spec_MaxPower*ones(1,length(NewBandList)),'r.-','LineWidth',2)
%grid on
%xlabel('Frequency (MHz)');
%ylabel('Power (dB)');
%saveas(fig1,'BTPRatedFreqList.png')
end
|
github
|
ccaicedo/SCMBAT-master
|
MaxPow_Diff.m
|
.m
|
SCMBAT-master/Octave/MaxPow_Diff.m
| 1,561 |
utf_8
|
410524f5e50cff3f1e96809b3fc73628
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
MaxPow_Diff.m
Function to find the power difference between a spectrum mask and
and underlay mask using the Max Power Density method.
P_diff: Power difference between the spectrum and underlay mask
pv_s: spectrum mask representation: [f0,p0,f1,p1....fn,pn];
pv_r: underlay mask representation: [f0,p0,f1,p1....fn,pn];
%}
function P_diff = MaxPow_Diff(pv_r,pv_s)
fr=pv_r(1:2:end-1);
fs=pv_s(1:2:end-1);
f_new = freq_sort(fr,fs);
f_new(end+1) = 0;
i=1;
while(i<length(f_new))
if(f_new(i)==f_new(i+1))
P_r=find_power(f_new(i),pv_r);
P_s=find_power(f_new(i),pv_s);
P_diff(i:i+1)=P_r-P_s;
i=i+2;
else
P_r=find_power(f_new(i),pv_r);
P_s=find_power(f_new(i),pv_s);
P_diff(i)=P_r-P_s;
i=i+1;
end
end
f_new(end) =[];
end
|
github
|
ccaicedo/SCMBAT-master
|
calculateBAEPSD.m
|
.m
|
SCMBAT-master/Octave/calculateBAEPSD.m
| 1,189 |
utf_8
|
68a2a4f5cd7024e07751d51cb0245ac8
|
%{
Copyright (C) 2016 Syracuse University
This file is part of the Spectrum Consumption Model Builder and
Analysis Tool
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with program. If not, see <http://www.gnu.org/licenses/>.
%}
%{
calculateBAEPSD.m
Function to calculate the Bandwidth adjusted effective power
spectral density (BAEPSD) for a combination of narrowband
spectrum masks.
baepsd: BAEPSD value,
bw: vector containing bandwidths of narrowband signals
bwMask: bandwidth of the underlay mask.
epsd: Effective Power spectral density.
%}
function [baepsd] = calculateBAEPSD (bw, bwMask, epsd)
baepsd=10*log10( (10.^(epsd/10))*sum(bw)/bwMask);
endfunction
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
edison_wrapper.m
|
.m
|
Segmentation-Using-Superpixels-master/msseg/edison_wrapper.m
| 6,071 |
utf_8
|
e38b90d4d1c4979c05527087208324c4
|
function [varargout] = edison_wrapper(rgbim, featurefun, varargin)
%
% Performing mean_shift operation on image
%
% Usage:
% [fimage labels modes regSize grad conf] = edison_wrapper(rgbim, featurefunc, ...)
%
% Inputs:
% rgbim - original image in RGB space
% featurefunc - converting RGB to some feature space in which to perform
% the segmentation, like @RGB2Lab etc.
%
% Allowed parameters:
% 'steps' - What steps the algorithm should perform:
% 1 - only mean shift filtering
% 2 - filtering and region fusion [default]
% 'synergistic' - perform synergistic segmentation [true]|false
% 'SpatialBandWidth' - segmentation spatial radius (integer) [7]
% 'RangeBandWidth' - segmentation feature space radius (float) [6.5]
% 'MinimumRegionArea'- minimum segment area (integer) [20]
% 'SpeedUp' - algorithm speed up {1,2,3} [2]
% 'GradientWindowRadius' - synergistic parameters (integer) [2]
% 'MixtureParameter' - synergistic parameter (float 0,1) [.3]
% 'EdgeStrengthThreshold'- synergistic parameter (float 0,1) [.3]
%
% Outputs:
% fimage - the result in feature space
% labels - labels of regions [if steps==2]
% modes - list of all modes [if steps==2]
% regSize - size, in pixels, of each region [if steps==2]
% grad - gradient map [if steps==2 and synergistic]
% conf - confidence map [if steps==2 and synergistic]
%
% rgbim must be of type uint8
if ~isa(rgbim,'uint8'),
if max(rgbim(:)) <= 1,
rgbim = im2uint8(rgbim);
else
rgbim = uint8(rgbim);
end
end
imsiz = size(rgbim);
fim = im2single(rgbim);
fim = single(featurefun(fim));
rgbim = permute(rgbim,[3 2 1]);
fim = permute(fim, [3 2 1]);
p = parse_inputs(varargin);
labels = [];
modes =[];
regSize = [];
grad = [];
conf = [];
if p.steps == 1
[fimage] = edison_wrapper_mex(fim, rgbim, p);
else
if p.synergistic
[fimage labels modes regSize grad conf] = edison_wrapper_mex(fim, rgbim, p);
else
[fimage labels modes regSize] = edison_wrapper_mex(fim, rgbim, p);
end
grad = reshape(grad,imsiz([2 1]))';
conf = reshape(conf',imsiz([2 1]))';
end
fimage = permute(fimage, [3 2 1]);
if nargout >= 1, varargout{1} = fimage; end;
if nargout >= 2, varargout{2} = labels'; end;
if nargout >= 3, varargout{3} = modes; end;
if nargout >= 4, varargout{4} = regSize; end;
if nargout >= 5, varargout{5} = grad; end;
if nargout >= 6, varargout{6} = conf; end;
%--------------------------------------------------------%
function [p] = parse_inputs(args)
% Allowed parameters
% 'steps' - What steps the algorithm should perform:
% 1 - only mean shift filtering
% 2 - filtering and region fusion [defualt]
% 'synergistic' - perform synergistic segmentation [true]|false
% 'SpatialBandWidth' - segmentation spatial radius (integer) [7]
% 'RangeBandWidth' - segmentation feature space radius (float) [6.5]
% 'MinimumRegionArea'- minimum segment area (integer) [20]
% 'SpeedUp' - algorithm speed up {0,1,2} [1]
% 'GradientWindowRadius' - synergistic parameters (integer) [2]
% 'MixtureParameter' - synergistic parameter (float 0,1) [.3]
% 'EdgeStrengthThreshold'- synergistic parameter (float 0,1) [.3]
% convert ars to parameters - then init all the rest according to defualts
try
p = struct(args{:});
catch
error('edison_wrapper:parse_inputs','Cannot parse arguments');
end
% % modes of operation
% -. edge detection -- currently unsupported
% 1. Filtering
% 2. Fusing regions
% 3. Segmentation
if ~isfield(p,'steps')
p.steps = 2;
end
if p.steps ~= 1 && p.steps ~=2
error('edison_wrapper:parse_inputs','steps must be either 1 or 2');
end
% % parameters
% Flags
% 1. synergistic
if ~isfield(p,'synergistic')
p.synergistic = true;
end
p.synergistic = logical(p.synergistic);
% Mean Shift Segmentation parameters
% SpatialBandWidth [integer]
if ~isfield(p,'SpatialBandWidth')
p.SpatialBandWidth = 7;
end
if p.SpatialBandWidth < 0 || p.SpatialBandWidth ~= round(p.SpatialBandWidth)
error('edison_wrapper:parse_inputs','SpatialBandWidth must be a positive integer');
end
% RangeBandWidth [float]
if ~isfield(p,'RangeBandWidth')
p.RangeBandWidth = 6.5;
end
if p.RangeBandWidth < 0
error('edison_wrapper:parse_inputs','RangeBandWidth must be positive');
end
% MinimumRegionArea [integer]
if ~isfield(p,'MinimumRegionArea')
p.MinimumRegionArea = 20;
end
if p.MinimumRegionArea < 0 || p.MinimumRegionArea ~= round(p.MinimumRegionArea)
error('edison_wrapper:parse_inputs','MinimumRegionArea must be a positive integer');
end
% SpeedUp
if ~isfield(p,'SpeedUp')
p.SpeedUp = 2;
end
if p.SpeedUp ~=1 && p.SpeedUp ~= 2 && p.SpeedUp ~= 3
error('edison_wrapper:parse_inputs','SpeedUp must be either 1, 2 or 3');
end
% Synergistic Segmentation parameters
% GradientWindowRadius [integer]
if ~isfield(p,'GradientWindowRadius')
p.GradientWindowRadius = 2;
end
if p.GradientWindowRadius < 0 || p.GradientWindowRadius ~= round(p.GradientWindowRadius)
error('edison_wrapper:parse_inputs','GradientWindowRadius must be a positive integer');
end
% MixtureParameter [float (0,1)]
if ~isfield(p,'MixtureParameter')
p.MixtureParameter = .3;
end
if p.MixtureParameter < 0 || p.MixtureParameter > 1
error('edison_wrapper:parse_inputs','MixtureParameter must be between zero and one');
end
% EdgeStrengthThreshold [float (0,1)]
if ~isfield(p,'EdgeStrengthThreshold')
p.EdgeStrengthThreshold = .3;
end
if p.EdgeStrengthThreshold < 0 || p.EdgeStrengthThreshold > 1
error('edison_wrapper:parse_inputs','MixtureParameter must be between zero and one');
end
% % Currently unsupported
% Edge Detection Parameters
% GradientWindowRadius [integer]
% MinimumLength [integer]
% NmxRank [float (0,1)]
% NmxConf [float (0,1)]
% NmxType
% HysterisisHighRank [float (0,1)]
% HysterisisHighConf [float (0,1)]
% HysterisisHighType
% HysterisisLowRank [float (0,1)]
% HysterisisLowConf [float (0,1)]
% HysterisisLowType
% %
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
msseg.m
|
.m
|
Segmentation-Using-Superpixels-master/msseg/msseg.m
| 2,216 |
utf_8
|
704da001d36390de9568b3942400295b
|
% Performing mean_shift image segmentation using EDISON code implementation
% of Comaniciu's paper with a MEX wrapper from Shai Bagon. links at bottom
% of help
%
% Usage:
% [S L] = msseg(I,hs,hr,M)
%
% Inputs:
% I - original image in RGB or grayscale
% hs - spatial bandwith for mean shift analysis
% hr - range bandwidth for mean shift analysis
% M - minimum size of final output regions
%
% Outputs:
% S - segmented image
% L - resulting label map
%
% Links:
% Comaniciu's Paper
% http://www.caip.rutgers.edu/riul/research/papers/abstract/mnshft.html
% EDISON code
% http://www.caip.rutgers.edu/riul/research/code/EDISON/index.html
% Shai's mex wrapper code
% http://www.wisdom.weizmann.ac.il/~bagon/matlab.html
%
% Author:
% This file and re-wrapping by Shawn Lankton (www.shawnlankton.com)
% Nov. 2007
%------------------------------------------------------------------------
function [S L seg seg_vals seg_lab_vals seg_edges] = msseg(img,lab_vals,hs,hr,M,full)
gray = 0;
if(size(img,3)==1)
gray = 1;
I = repmat(img,[1 1 3]);
end
if(nargin < 5)
hs = 10; hr = 7; M = 30;
end
if(nargin < 6)
full = 0;
end
[fimg labels modes regsize grad conf] = edison_wrapper(img,@RGB2Luv,...
'SpatialBandWidth',hs,'RangeBandWidth',hr,...
'MinimumRegionArea',M,'speedup',3);
S = fimg; %Luv2RGB(fimg);
L = labels + 1;
if(gray == 1)
S = rgb2gray(S);
end
[X,Y,Z] = size(img); nseg = max(L(:)); vals = reshape(img,X*Y,Z);
if full == 1,
[x y] = meshgrid(1:nseg,1:nseg);
seg_edges = [x(:) y(:)];
else
[points edges]=lattice(X,Y,0); clear points;
d_edges = edges(find(L(edges(:,1))~=L(edges(:,2))),:);
all_seg_edges = [L(d_edges(:,1)) L(d_edges(:,2))]; all_seg_edges = sort(all_seg_edges,2);
tmp = zeros(nseg,nseg);
tmp(nseg*(all_seg_edges(:,1)-1)+all_seg_edges(:,2)) = 1;
[edges_x edges_y] = find(tmp==1); seg_edges = [edges_x edges_y];
end;
seg_vals = zeros(nseg,Z);
seg_lab_vals = zeros(nseg,size(lab_vals,2));
for i=1:nseg
seg{i} = find(L(:)==i);
seg_vals(i,:) = mean(vals(seg{i},:));
seg_lab_vals(i,:) = mean(lab_vals(seg{i},:));
end;
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
compare_segmentations.m
|
.m
|
Segmentation-Using-Superpixels-master/evals/compare_segmentations.m
| 4,879 |
utf_8
|
9894ac0153bc6ab19440e99ea9a875b0
|
%A MATLAB Toolbox
%
%Compare two segmentation results using
%1. Probabilistic Rand Index
%2. Variation of Information
%3. Global Consistency Error
%
%IMPORTANT: The two input images must have the same size!
%
%Authors: John Wright, and Allen Y. Yang
%Contact: Allen Y. Yang <[email protected]>
%
%(c) Copyright. University of California, Berkeley. 2007.
%
%Notice: The packages should NOT be used for any commercial purposes
%without direct consent of their author(s). The authors are not responsible
%for any potential property loss or damage caused directly or indirectly by the usage of the software.
function [ri,gce,vi]=compare_segmentations(sampleLabels1,sampleLabels2)
% compare_segmentations
%
% Computes several simple segmentation benchmarks. Written for use with
% images, but works for generic segmentation as well (i.e. if the
% sampleLabels inputs are just lists of labels, rather than rectangular
% arrays).
%
% The measures:
% Rand Index
% Global Consistency Error
% Variation of Information
%
% The Rand Index can be easily extended to the Probabilistic Rand Index
% by averaging the result across all human segmentations of a given
% image:
% PRI = 1/K sum_1^K RI( seg, humanSeg_K ).
% With a little more work, this can also be extended to the Normalized
% PRI.
%
% Inputs:
% sampleLabels1 - n x m array whose entries are integers between 1
% and K1
% sampleLabels2 - n x m (sample size as sampleLabels1) array whose
% entries are integers between 1 and K2 (not
% necessarily the same as K1).
% Outputs:
% ri - Rand Index
% gce - Global Consistency Error
% vi - Variation of Information
%
% NOTE:
% There are a few formulas here that look less-straightforward (e.g.
% the log2_quotient function). These exist to handle corner cases
% where some of the groups are empty, and quantities like 0 *
% log(0/0) arise...
%
% Oct. 2006
% Questions? John Wright - [email protected]
[imWidth,imHeight]=size(sampleLabels1);
[imWidth2,imHeight2]=size(sampleLabels2);
N=imWidth*imHeight;
if (imWidth~=imWidth2)||(imHeight~=imHeight2)
disp( 'Input sizes: ' );
disp( size(sampleLabels1) );
disp( size(sampleLabels2) );
error('Input sizes do not match in compare_segmentations.m');
end;
% make the group indices start at 1
if min(min(sampleLabels1)) < 1
sampleLabels1 = sampleLabels1 - min(min(sampleLabels1)) + 1;
end
if min(min(sampleLabels2)) < 1
sampleLabels2 = sampleLabels2 - min(min(sampleLabels2)) + 1;
end
segmentcount1=max(max(sampleLabels1));
segmentcount2=max(max(sampleLabels2));
% compute the count matrix
% from this we can quickly compute rand index, GCE, VOI, ect...
n=zeros(segmentcount1,segmentcount2);
for i=1:imWidth
for j=1:imHeight
u=sampleLabels1(i,j);
v=sampleLabels2(i,j);
n(u,v)=n(u,v)+1;
end;
end;
ri = rand_index(n);
gce = global_consistancy_error(n);
vi = variation_of_information(n);
return;
% the performance measures
% the rand index, in [0,1] ... higher => better
% fast computation is based on equation (2.2) of Rand's paper.
function ri = rand_index(n)
N = sum(sum(n));
n_u=sum(n,2);
n_v=sum(n,1);
N_choose_2=N*(N-1)/2;
ri = 1 - ( sum(n_u .* n_u)/2 + sum(n_v .* n_v)/2 - sum(sum(n.*n)) )/N_choose_2;
% global consistancy error (from BSDS ICCV 01 paper) ... lower => better
function gce = global_consistancy_error(n)
N = sum(sum(n));
marginal_1 = sum(n,2);
marginal_2 = sum(n,1);
% the hackery is to protect against cases where some of the marginals are
% zero (should never happen, but seems to...)
E1 = 1 - sum( sum(n.*n,2) ./ (marginal_1 + (marginal_1 == 0)) ) / N;
E2 = 1 - sum( sum(n.*n,1) ./ (marginal_2 + (marginal_2 == 0)) ) / N;
gce = min( E1, E2 );
% variation of information a "distance", in (0,vi_max] ... lower => better
function vi = variation_of_information(n)
N = sum(sum(n));
joint = n / N; % the joint pmf of the two labels
marginal_2 = sum(joint,1); % row vector
marginal_1 = sum(joint,2); % column vector
H1 = - sum( marginal_1 .* log2(marginal_1 + (marginal_1 == 0) ) ); % entropy of the first label
H2 = - sum( marginal_2 .* log2(marginal_2 + (marginal_2 == 0) ) ); % entropy of the second label
MI = sum(sum( joint .* log2_quotient( joint, marginal_1*marginal_2 ) )); % mutual information
vi = H1 + H2 - 2 * MI;
% log2_quotient
% helper function for computing the mutual information
% returns a matrix whose ij entry is
% log2( a_ij / b_ij ) if a_ij, b_ij > 0
% 0 if a_ij is 0
% log2( a_ij + 1 ) if a_ij > 0 but b_ij = 0 (this behavior should
% not be encountered in practice!
function lq = log2_quotient( A, B )
lq = log2( (A + ((A==0).*B) + (B==0)) ./ (B + (B==0)) );
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
compare_image_boundary_error.m
|
.m
|
Segmentation-Using-Superpixels-master/evals/compare_image_boundary_error.m
| 2,214 |
utf_8
|
df0574848dc09e9cb1903235da501e92
|
%A MATLAB Toolbox
%
%Compare two segmentation results using the Boundary Displacement Error
%
%IMPORTANT: The input two images must have the same size!
%
%Authors: John Wright, and Allen Y. Yang
%Contact: Allen Y. Yang <[email protected]>
%
%(c) Copyright. University of California, Berkeley. 2007.
%
%Notice: The packages should NOT be used for any commercial purposes
%without direct consent of their author(s). The authors are not responsible
%for any potential property loss or damage caused directly or indirectly by the usage of the software.
function [averageError, returnStatus] = compare_image_boundary_error(imageLabels1, imageLabels2);
returnStatus = 0;
[imageX, imageY] = size(imageLabels1);
if imageX~=size(imageLabels2,1) | imageY~=size(imageLabels2,2)
error('The sizes of the two comparing images must be the same.');
end
if isempty(find(imageLabels1~=imageLabels1(1)))
% imageLabels1 only has one group
boundary1 = zeros(size(imageLabels1));
boundary1(1,:) = 1;
boundary1(:,1) = 1;
boundary1(end,:) = 1;
boundary1(:,end) = 1;
else
% Generate boundary maps
[cx,cy] = gradient(imageLabels1);
[boundaryPixelX{1},boundaryPixelY{1}] = find((abs(cx)+abs(cy))~=0);
boundary1 = abs(cx) + abs(cy) > 0;
end
if isempty(find(imageLabels2~=imageLabels2(1)))
% imageLabels2 only has one group
boundary2 = zeros(size(imageLabels2));
boundary2(1,:) = 1;
boundary2(:,1) = 1;
boundary2(end,:) = 1;
boundary2(:,end) = 1;
else
% Generate boundary maps
[cx,cy] = gradient(imageLabels2);
[boundaryPixelX{2},boundaryPixelY{2}] = find((abs(cx)+abs(cy))~=0);
boundary2 = abs(cx) + abs(cy) > 0;
end
% boundary1 and boundary2 are now binary boundary masks. compute their
% distance transforms:
D1 = bwdist(boundary1);
D2 = bwdist(boundary2);
% compute the distance of the pixels in boundary1 to the nearest pixel in
% boundary2:
dist_12 = sum(sum(boundary1 .* D2 ));
dist_21 = sum(sum(boundary2 .* D1 ));
avgError_12 = dist_12 / sum(sum(boundary1));
avgError_21 = dist_21 / sum(sum(boundary2));
averageError = (avgError_12 + avgError_21) / 2;
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
Rand_index.m
|
.m
|
Segmentation-Using-Superpixels-master/evals/Rand_index.m
| 3,073 |
utf_8
|
1908dff37c5ef0f12f9077404f6ed054
|
function ri=Rand_index(sampleLabels1,sampleLabels2)
% compare_segmentations
%
% Computes several simple segmentation benchmarks. Written for use with
% images, but works for generic segmentation as well (i.e. if the
% sampleLabels inputs are just lists of labels, rather than rectangular
% arrays).
%
% The measures:
% Rand Index
%
% The Rand Index can be easily extended to the Probabilistic Rand Index
% by averaging the result across all human segmentations of a given
% image:
% PRI = 1/K sum_1^K RI( seg, humanSeg_K ).
% With a little more work, this can also be extended to the Normalized
% PRI.
%
% Inputs:
% sampleLabels1 - n x m array whose entries are integers between 1
% and K1
% sampleLabels2 - n x m (sample size as sampleLabels1) array whose
% entries are integers between 1 and K2 (not
% necessarily the same as K1).
% Outputs:
% ri - Rand Index
% gce - Global Consistency Error
% vi - Variation of Information
%
% NOTE:
% There are a few formulas here that look less-straightforward (e.g.
% the log2_quotient function). These exist to handle corner cases
% where some of the groups are empty, and quantities like 0 *
% log(0/0) arise...
%
% Oct. 2006
% Questions? John Wright - [email protected]
[imWidth,imHeight]=size(sampleLabels1);
[imWidth2,imHeight2]=size(sampleLabels2);
N=imWidth*imHeight;
if (imWidth~=imWidth2)||(imHeight~=imHeight2)
disp( 'Input sizes: ' );
disp( size(sampleLabels1) );
disp( size(sampleLabels2) );
error('Input sizes do not match in compare_segmentations.m');
end;
% make the group indices start at 1
if min(min(sampleLabels1)) < 1
sampleLabels1 = sampleLabels1 - min(min(sampleLabels1)) + 1;
end
if min(min(sampleLabels2)) < 1
sampleLabels2 = sampleLabels2 - min(min(sampleLabels2)) + 1;
end
segmentcount1=max(max(sampleLabels1));
segmentcount2=max(max(sampleLabels2));
% compute the count matrix
% from this we can quickly compute rand index, GCE, VOI, ect...
n=zeros(segmentcount1,segmentcount2);
for i=1:imWidth
for j=1:imHeight
u=sampleLabels1(i,j);
v=sampleLabels2(i,j);
n(u,v)=n(u,v)+1;
end;
end;
ri = rand_index(n);
return;
% the performance measures
% the rand index, in [0,1] ... higher => better
% fast computation is based on equation (2.2) of Rand's paper.
function ri = rand_index(n)
N = sum(sum(n));
n_u=sum(n,2);
n_v=sum(n,1);
N_choose_2=N*(N-1)/2;
ri = 1 - ( sum(n_u .* n_u)/2 + sum(n_v .* n_v)/2 - sum(sum(n.*n)) )/N_choose_2;
% log2_quotient
% helper function for computing the mutual information
% returns a matrix whose ij entry is
% log2( a_ij / b_ij ) if a_ij, b_ij > 0
% 0 if a_ij is 0
% log2( a_ij + 1 ) if a_ij > 0 but b_ij = 0 (this behavior should
% not be encountered in practice!
function lq = log2_quotient( A, B )
lq = log2( (A + ((A==0).*B) + (B==0)) ./ (B + (B==0)) );
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
colorspace.m
|
.m
|
Segmentation-Using-Superpixels-master/others/colorspace.m
| 14,019 |
utf_8
|
c8d23ed54d9745d5e49e7d99ee1ed95f
|
function varargout = colorspace(Conversion,varargin)
%COLORSPACE Convert a color image between color representations.
% B = COLORSPACE(S,A) converts the color representation of image A
% where S is a string specifying the conversion. S tells the
% source and destination color spaces, S = 'dest<-src', or
% alternatively, S = 'src->dest'. Supported color spaces are
%
% 'RGB' R'G'B' Red Green Blue (ITU-R BT.709 gamma-corrected)
% 'YPbPr' Luma (ITU-R BT.601) + Chroma
% 'YCbCr'/'YCC' Luma + Chroma ("digitized" version of Y'PbPr)
% 'YUV' NTSC PAL Y'UV Luma + Chroma
% 'YIQ' NTSC Y'IQ Luma + Chroma
% 'YDbDr' SECAM Y'DbDr Luma + Chroma
% 'JPEGYCbCr' JPEG-Y'CbCr Luma + Chroma
% 'HSV'/'HSB' Hue Saturation Value/Brightness
% 'HSL'/'HLS'/'HSI' Hue Saturation Luminance/Intensity
% 'XYZ' CIE XYZ
% 'Lab' CIE L*a*b* (CIELAB)
% 'Luv' CIE L*u*v* (CIELUV)
% 'Lch' CIE L*ch (CIELCH)
%
% All conversions assume 2 degree observer and D65 illuminant. Color
% space names are case insensitive. When R'G'B' is the source or
% destination, it can be omitted. For example 'yuv<-' is short for
% 'yuv<-rgb'.
%
% MATLAB uses two standard data formats for R'G'B': double data with
% intensities in the range 0 to 1, and uint8 data with integer-valued
% intensities from 0 to 255. As MATLAB's native datatype, double data is
% the natural choice, and the R'G'B' format used by colorspace. However,
% for memory and computational performance, some functions also operate
% with uint8 R'G'B'. Given uint8 R'G'B' color data, colorspace will
% first cast it to double R'G'B' before processing.
%
% If A is an Mx3 array, like a colormap, B will also have size Mx3.
%
% [B1,B2,B3] = COLORSPACE(S,A) specifies separate output channels.
% COLORSPACE(S,A1,A2,A3) specifies separate input channels.
% Pascal Getreuer 2005-2006
%%% Input parsing %%%
if nargin < 2, error('Not enough input arguments.'); end
[SrcSpace,DestSpace] = parse(Conversion);
if nargin == 2
Image = varargin{1};
elseif nargin >= 3
Image = cat(3,varargin{:});
else
error('Invalid number of input arguments.');
end
FlipDims = (size(Image,3) == 1);
if FlipDims, Image = permute(Image,[1,3,2]); end
if ~isa(Image,'double'), Image = double(Image)/255; end
if size(Image,3) ~= 3, error('Invalid input size.'); end
SrcT = gettransform(SrcSpace);
DestT = gettransform(DestSpace);
if ~ischar(SrcT) & ~ischar(DestT)
% Both source and destination transforms are affine, so they
% can be composed into one affine operation
T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
Temp = zeros(size(Image));
Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
Image = Temp;
elseif ~ischar(DestT)
Image = rgb(Image,SrcSpace);
Temp = zeros(size(Image));
Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);
Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);
Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);
Image = Temp;
else
Image = feval(DestT,Image,SrcSpace);
end
%%% Output format %%%
if nargout > 1
varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};
else
if FlipDims, Image = permute(Image,[1,3,2]); end
varargout = {Image};
end
return;
function [SrcSpace,DestSpace] = parse(Str)
% Parse conversion argument
if isstr(Str)
Str = lower(strrep(strrep(Str,'-',''),' ',''));
k = find(Str == '>');
if length(k) == 1 % Interpret the form 'src->dest'
SrcSpace = Str(1:k-1);
DestSpace = Str(k+1:end);
else
k = find(Str == '<');
if length(k) == 1 % Interpret the form 'dest<-src'
DestSpace = Str(1:k-1);
SrcSpace = Str(k+1:end);
else
error(['Invalid conversion, ''',Str,'''.']);
end
end
SrcSpace = alias(SrcSpace);
DestSpace = alias(DestSpace);
else
SrcSpace = 1; % No source pre-transform
DestSpace = Conversion;
if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
end
return;
function Space = alias(Space)
Space = strrep(Space,'cie','');
if isempty(Space)
Space = 'rgb';
end
switch Space
case {'ycbcr','ycc'}
Space = 'ycbcr';
case {'hsv','hsb'}
Space = 'hsv';
case {'hsl','hsi','hls'}
Space = 'hsl';
case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
return;
end
return;
function T = gettransform(Space)
% Get a colorspace transform: either a matrix describing an affine transform,
% or a string referring to a conversion subroutine
switch Space
case 'ypbpr'
T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];
case 'yuv'
% R'G'B' to NTSC/PAL YUV
% Wikipedia: http://en.wikipedia.org/wiki/YUV
T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];
case 'ydbdr'
% R'G'B' to SECAM YDbDr
% Wikipedia: http://en.wikipedia.org/wiki/YDbDr
T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];
case 'yiq'
% R'G'B' in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];
% Wikipedia: http://en.wikipedia.org/wiki/YIQ
T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];
case 'ycbcr'
% R'G'B' (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
% Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion
T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];
case 'jpegycbcr'
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;
case {'rgb','xyz','hsv','hsl','lab','luv','lch'}
T = Space;
otherwise
error(['Unknown color space, ''',Space,'''.']);
end
return;
function Image = rgb(Image,SrcSpace)
% Convert to Rec. 709 R'G'B' from 'SrcSpace'
switch SrcSpace
case 'rgb'
return;
case 'hsv'
% Convert HSV to R'G'B'
Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
case 'hsl'
% Convert HSL to R'G'B'
L = Image(:,:,3);
Delta = Image(:,:,2).*min(L,1-L);
Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));
case {'xyz','lab','luv','lch'}
% Convert to CIE XYZ
Image = xyz(Image,SrcSpace);
% Convert XYZ to RGB
T = [3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B
% Desaturate and rescale to constrain resulting RGB values to [0,1]
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
% Apply gamma correction to convert RGB to Rec. 709 R'G'B'
Image(:,:,1) = gammacorrection(R); % R'
Image(:,:,2) = gammacorrection(G); % G'
Image(:,:,3) = gammacorrection(B); % B'
otherwise % Conversion is through an affine transform
T = gettransform(SrcSpace);
temp = inv(T(:,1:3));
T = [temp,-temp*T(:,4)];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
Image(:,:,1) = R;
Image(:,:,2) = G;
Image(:,:,3) = B;
end
% Clip to [0,1]
Image = min(max(Image,0),1);
return;
function Image = xyz(Image,SrcSpace)
% Convert to CIE XYZ from 'SrcSpace'
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'xyz'
return;
case 'luv'
% Convert CIE L*uv to XYZ
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
L = Image(:,:,1);
Y = (L + 16)/116;
Y = invf(Y)*WhitePoint(2);
U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;
V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;
Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X
Image(:,:,2) = Y; % Y
Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z
case {'lab','lch'}
Image = lab(Image,SrcSpace);
% Convert CIE L*ab to XYZ
fY = (Image(:,:,1) + 16)/116;
fX = fY + Image(:,:,2)/500;
fZ = fY - Image(:,:,3)/200;
Image(:,:,1) = WhitePoint(1)*invf(fX); % X
Image(:,:,2) = WhitePoint(2)*invf(fY); % Y
Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z
otherwise % Convert from some gamma-corrected space
% Convert to Rec. 701 R'G'B'
Image = rgb(Image,SrcSpace);
% Undo gamma correction
R = invgammacorrection(Image(:,:,1));
G = invgammacorrection(Image(:,:,2));
B = invgammacorrection(Image(:,:,3));
% Convert RGB to XYZ
T = inv([3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311]);
Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y
Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z
end
return;
function Image = hsv(Image,SrcSpace)
% Convert to HSV
Image = rgb(Image,SrcSpace);
V = max(Image,[],3);
S = (V - min(Image,[],3))./(V + (V == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = V;
return;
function Image = hsl(Image,SrcSpace)
% Convert to HSL
switch SrcSpace
case 'hsv'
% Convert HSV to HSL
MaxVal = Image(:,:,3);
MinVal = (1 - Image(:,:,2)).*MaxVal;
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,3) = L;
otherwise
Image = rgb(Image,SrcSpace); % Convert to Rec. 701 R'G'B'
% Convert R'G'B' to HSL
MinVal = min(Image,[],3);
MaxVal = max(Image,[],3);
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = L;
end
return;
function Image = lab(Image,SrcSpace)
% Convert to CIE L*a*b* (CIELAB)
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'lab'
return;
case 'lch'
% Convert CIE L*CH to CIE L*ab
C = Image(:,:,2);
Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a*
Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b*
otherwise
Image = xyz(Image,SrcSpace); % Convert to XYZ
% Convert XYZ to CIE L*a*b*
X = Image(:,:,1)/WhitePoint(1);
Y = Image(:,:,2)/WhitePoint(2);
Z = Image(:,:,3)/WhitePoint(3);
fX = f(X);
fY = f(Y);
fZ = f(Z);
Image(:,:,1) = 116*fY - 16; % L*
Image(:,:,2) = 500*(fX - fY); % a*
Image(:,:,3) = 200*(fY - fZ); % b*
end
return;
function Image = luv(Image,SrcSpace)
% Convert to CIE L*u*v* (CIELUV)
WhitePoint = [0.950456,1,1.088754];
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
Image = xyz(Image,SrcSpace); % Convert to XYZ
U = (4*Image(:,:,1))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
V = (9*Image(:,:,2))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
Y = Image(:,:,2)/WhitePoint(2);
L = 116*f(Y) - 16;
Image(:,:,1) = L; % L*
Image(:,:,2) = 13*L.*(U - WhitePointU); % u*
Image(:,:,3) = 13*L.*(V - WhitePointV); % v*
return;
function Image = lch(Image,SrcSpace)
% Convert to CIE L*ch
Image = lab(Image,SrcSpace); % Convert to CIE L*ab
H = atan2(Image(:,:,3),Image(:,:,2));
H = H*180/pi + 360*(H < 0);
Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C
Image(:,:,3) = H; % H
return;
function Image = huetorgb(m0,m2,H)
% Convert HSV or HSL hue to RGB
N = size(H);
H = min(max(H(:),0),360)/60;
m0 = m0(:);
m2 = m2(:);
F = H - round(H/2)*2;
M = [m0, m0 + (m2-m0).*abs(F), m2];
Num = length(m0);
j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
k = floor(H) + 1;
Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
return;
function H = rgbtohue(Image)
% Convert RGB to HSV or HSL hue
[M,i] = sort(Image,3);
i = i(:,:,3);
Delta = M(:,:,3) - M(:,:,1);
Delta = Delta + (Delta == 0);
R = Image(:,:,1);
G = Image(:,:,2);
B = Image(:,:,3);
H = zeros(size(R));
k = (i == 1);
H(k) = (G(k) - B(k))./Delta(k);
k = (i == 2);
H(k) = 2 + (B(k) - R(k))./Delta(k);
k = (i == 3);
H(k) = 4 + (R(k) - G(k))./Delta(k);
H = 60*H + 360*(H < 0);
H(Delta == 0) = nan;
return;
function Rp = gammacorrection(R)
Rp = real(1.099*R.^0.45 - 0.099);
i = (R < 0.018);
Rp(i) = 4.5138*R(i);
return;
function R = invgammacorrection(Rp)
R = real(((Rp + 0.099)/1.099).^(1/0.45));
i = (R < 0.018);
R(i) = Rp(i)/4.5138;
return;
function fY = f(Y)
fY = real(Y.^(1/3));
i = (Y < 0.008856);
fY(i) = Y(i)*(841/108) + (4/29);
return;
function Y = invf(fY)
Y = fY.^3;
i = (Y < 0.008856);
Y(i) = (fY(i) - 4/29)*(108/841);
return;
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
k_means.m
|
.m
|
Segmentation-Using-Superpixels-master/others/k_means.m
| 1,984 |
utf_8
|
031bae601547fa2a4821a4657bdf547c
|
function [R, M] = k_means(X, K, seed)
%KMEANS: K-means clustering
% idx = KMEANS(X, K) returns M with K columns, one for each mean. Each
% column of X is a datapoint. K is the number of clusters
% [idx, mu] = KMEANS(X, K) also returns mu, a row vector, R(i) is the
% index of the cluster datapoint X(:, i) is assigned to.
% idx = KMEANS(X,K) returns idx where idx(i) is the index of the cluster
% that datapoint X(:,i) is assigned to.
% [idx,mu] = KMEANS(X,K) also returns mu, the K cluster centers.
%
% KMEANS(X, K, SEED) uses SEED (default 1) to randomise initial assignments.
if ~exist('seed', 'var'), seed = 1; end
%
% Initialization
%
[D,N] = size(X);
% if D>N, warning(sprintf('K-means running on %d points in %d dimensions\n',N,D)); end;
M = zeros(D, K);
Dist = zeros(N, K);
M(:, 1) = X(:,seed);
Dist(:, 1) = sum((X - repmat(M(:, 1), 1, N)).^2, 1)';
for ii = 2:K
% maximum, minimum dist
mindist = min(Dist(:,1:ii-1), [], 2);
[junk, jj] = max(mindist);
M(:, ii) = X(:, jj);
Dist(:, ii) = sum((X - repmat(M(:, ii), 1, N)).^2, 1)';
end
% plotfig(X,M);
X2 = sum(X.^2,1)';
converged = 0;
R = zeros(N, 1);
while ~converged
distance = repmat(X2,1,K) - 2 * X' * M + repmat(sum(M.^2, 1), N, 1);
[junk, newR] = min(distance, [], 2);
if norm(R-newR) == 0
converged = 1;
else
R = newR;
end
total = 0;
for ii = 1:K
ix = find(R == ii);
M(:, ii) = mean(X(:, ix), 2);
total = total + sum(distance(ix, ii));
end
% plotfig(X,M);
% fprintf('Distance %f\n', total);
end
% pause; close all;
return
function plotfig(x,M),
figure; plot(x(1,:),x(2,:),'go', 'MarkerFaceColor','g', 'LineWidth',1.5); hold on; plot(M(1,:),M(2,:),'rx','MarkerSize',12, 'LineWidth',2);
w = 2.15; h = 2;
for k=1:size(M,2),
rectangle('Position',[M(1,k) M(2,k) 0 0]+w*[-1 -1 +2 +2], 'Curvature',[1 1], 'EdgeColor','r', 'LineWidth',2);
end;
xlim([floor(min(x(1,:))) ceil(max(x(1,:)))]);
ylim([floor(min(x(2,:))) ceil(max(x(2,:)))]);
return
|
github
|
ColumbiaDVMM/Segmentation-Using-Superpixels-master
|
sc.m
|
.m
|
Segmentation-Using-Superpixels-master/others/sc.m
| 39,501 |
utf_8
|
33abd391190c650fbdfca77620408f4e
|
function I = sc(I, varargin)
%SC Display/output truecolor images with a range of colormaps
%
% Examples:
% sc(image)
% sc(image, limits)
% sc(image, map)
% sc(image, limits, map)
% sc(image, map, limits)
% sc(..., col1, mask1, col2, mask2,...)
% out = sc(...)
% sc
%
% Generates a truecolor RGB image based on the input values in 'image' and
% any maximum and minimum limits specified, using the colormap specified.
% The image is displayed on screen if there is no output argument.
%
% SC has these advantages over MATLAB image rendering functions:
% - images can be displayed or output; makes combining/overlaying images
% simple.
% - images are rendered/output in truecolor (RGB [0,1]); no nasty
% discretization of the input data.
% - many special, built-in colormaps for viewing various types of data.
% - linearly interpolates user defined linear and non-linear colormaps.
% - no border and automatic, integer magnification (unless figure is
% docked or maximized) for better display.
% - multiple images can be generated for export simultaneously.
%
% For a demonstration, simply call SC without any input arguments.
%
% IN:
% image - MxNxCxP or 3xMxNxP image array. MxN are the dimensions of the
% image(s), C is the number of channels, and P the number of
% images. If P > 1, images can only be exported, not displayed.
% limits - [min max] where values in image less than min will be set to
% min and values greater than max will be set to max.
% map - Kx3 or Kx4 user defined colormap matrix, where the optional 4th
% column is the relative distance between colours along the scale,
% or a string containing the name of the colormap to use to create
% the output image. Default: 'none', which is RGB for 3-channel
% images, grayscale otherwise. Conversion of multi-channel images
% to intensity for intensity-based colormaps is done using the L2
% norm. Most MATLAB colormaps are supported. All named colormaps
% can be reversed by prefixing '-' to the string. This maintains
% integrity of the colorbar. Special, non-MATLAB colormaps are:
% 'contrast' - a high contrast colormap for intensity images that
% maintains intensity scale when converted to grayscale,
% for example when printing in black & white.
% 'prob' - first channel is plotted as hue, and the other channels
% modulate intensity. Useful for laying probabilites over
% images.
% 'prob_jet' - first channel is plotted as jet colormap, and the other
% channels modulate intensity.
% 'diff' - intensity values are marked blue for > 0 and red for < 0.
% Darker colour means larger absolute value. For multi-
% channel images, the L2 norm of the other channels sets
% green level. 3 channel images are converted to YUV and
% images with more that 3 channels are projected onto the
% principle components first.
% 'compress' - compress many channels to RGB while maximizing
% variance.
% 'flow' - display two channels representing a 2d Cartesian vector as
% hue for angle and intensity for magnitude (darker colour
% indicates a larger magnitude).
% 'phase' - first channel is intensity, second channel is phase in
% radians. Darker colour means greater intensity, hue
% represents phase from 0 to 2 pi.
% 'stereo' - pair of concatenated images used to generate a red/cyan
% anaglyph.
% 'stereo_col' - pair of concatenated RGB images used to generate a
% colour anaglyph.
% 'rand' - gives an index image a random colormap. Useful for viewing
% segmentations.
% 'rgb2gray' - converts an RGB image to grayscale in the same fashion
% as MATLAB's rgb2gray (in the image processing toolbox).
% col/mask pairs - Pairs of parameters for coloring specific parts of the
% image differently. The first (col) parameter can be
% a MATLAB color specifier, e.g. 'b' or [0.5 0 1], or
% one of the colormaps named above, or an MxNx3 RGB
% image. The second (mask) paramater should be an MxN
% logical array indicating those pixels (true) whose
% color should come from the specified color parameter.
% If there is only one col parameter, without a mask
% pair, then mask = any(isnan(I, 3)), i.e. the mask is
% assumed to indicate the location of NaNs. Note that
% col/mask pairs are applied in order, painting over
% previous pixel values.
%
% OUT:
% out - MxNx3xP truecolour (double) RGB image array in range [0, 1]
%
% See also IMAGE, IMAGESC, IMSHOW, COLORMAP, COLORBAR.
% $Id: sc.m,v 1.84 2009/03/17 10:38:54 ojw Exp $
% Copyright: Oliver Woodford, 2007
%% Check for arguments
if nargin == 0
% If there are no input arguments then run the demo
if nargout > 0
error('Output expected from no inputs!');
end
demo; % Run the demo
return
end
%% Size our image(s)
[y x c n] = size(I);
I = reshape(I, y, x, c, n);
%% Check if image is given with RGB colour along the first dimension
if y == 3 && c > 3
% Flip colour to 3rd dimension
I = permute(I, [2 3 1 4]);
[y x c n] = size(I);
end
%% Don't do much if I is empty
if isempty(I)
if nargout == 0
% Clear the current axes if we were supposed to display the image
cla; axis off;
else
% Create an empty array with the correct dimensions
I = zeros(y, x, (c~=0)*3, n);
end
return
end
%% Check for multiple images
% If we have a non-singleton 4th dimension we want to display the images in
% a 3x4 grid and use buttons to cycle through them
if n > 1
if nargout > 0
% Return transformed images in an YxXx3xN array
A = zeros(y, x, 3, n);
for a = 1:n
A(:,:,:,a) = sc(I(:,:,:,a), varargin{:});
end
I = A;
else
% Removed functionality
fprintf([' SC no longer supports the display of multiple images. The\n'...
' functionality has been incorporated into an improved version\n'...
' of MONTAGE, available on the MATLAB File Exchange at:\n'...
' http://www.mathworks.com/matlabcentral/fileexchange/22387\n']);
clear I;
end
return
end
%% Parse the input arguments coming after I (1st input)
[map limits mask] = parse_inputs(I, varargin, y, x);
%% Call the rendering function
I = reshape(double(real(I)), y*x, c); % Only work with real doubles
if ~ischar(map)
% Table-based colormap
reverseMap = false;
[I limits] = interp_map(I, limits, reverseMap, map);
else
% If map starts with a '-' sign, invert the colourmap
reverseMap = map(1) == '-';
map = lower(map(reverseMap+1:end));
% Predefined colormap
[I limits] = colormap_switch(I, map, limits, reverseMap, c);
end
%% Update any masked pixels
I = reshape(I, y*x, 3);
for a = 1:size(mask, 2)
I(mask{2,a},1) = mask{1,a}(:,1);
I(mask{2,a},2) = mask{1,a}(:,2);
I(mask{2,a},3) = mask{1,a}(:,3);
end
I = reshape(I, [y x 3]); % Reshape to correct size
%% Only display if the output isn't used
if nargout == 0
display_image(I, map, limits, reverseMap);
% Don't print out the matrix if we've forgotten the ";"
clear I
end
return
%% Colormap switch
function [I limits] = colormap_switch(I, map, limits, reverseMap, c)
% Large switch statement for all the colourmaps
switch map
%% Prism
case 'prism'
% Similar to the MATLAB internal prism colormap, but only works on
% index images, assigning each index (or rounded float) to a
% different colour
[I limits] = index_im(I);
% Generate prism colourmap
map = prism(6);
if reverseMap
map = map(end:-1:1,:); % Reverse the map
end
% Lookup the colours
I = mod(I, 6) + 1;
I = map(I,:);
%% Rand
case 'rand'
% Assigns a random colour to each index
[I limits num_vals] = index_im(I);
% Generate random colourmap
map = rand(num_vals, 3);
% Lookup the colours
I = map(I,:);
%% Diff
case 'diff'
% Show positive as blue and negative as red, white is 0
switch c
case 1
I(:,2:3) = 0;
case 2
% Second channel can only have absolute value
I(:,3) = abs(I(:,2));
case 3
% Diff of RGB images - convert to YUV first
I = rgb2yuv(I);
I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(2);
otherwise
% Use difference along principle component, and other
% channels to modulate second channel
I = calc_prin_comps(I);
I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(c - 1);
I(:,4:end) = [];
end
% Generate limits
if isempty(limits)
limits = [min(I(:,1)) max(I(:,1))];
end
limits = max(abs(limits));
if limits
% Scale
if c > 1
I(:,[1 3]) = I(:,[1 3]) / limits;
else
I = I / (limits * 0.5);
end
end
% Colour
M = I(:,1) > 0;
I(:,2) = -I(:,1) .* ~M;
I(:,1) = I(:,1) .* M;
if reverseMap
% Swap first two channels
I = I(:,[2 1 3]);
end
%I = 1 - I * [1 0.4 1; 0.4 1 1; 1 1 0.4]; % (Green/Red)
I = 1 - I * [1 1 0.4; 0.4 1 1; 1 0.4 1]; % (Blue/Red)
I = min(max(I, 0), 1);
limits = [-limits limits]; % For colourbar
%% Flow
case 'flow'
% Calculate amplitude and phase, and use 'phase'
if c ~= 2
error('''flow'' requires two channels');
end
A = sqrt(sum(I .^ 2, 2));
if isempty(limits)
limits = [min(A) max(A)*2];
else
limits = [0 max(abs(limits)*sqrt(2))*2];
end
I(:,1) = atan2(I(:,2), I(:,1));
I(:,2) = A;
if reverseMap
% Invert the amplitude
I(:,2) = -I(:,2);
limits = -limits([2 1]);
end
I = phase_helper(I, limits, 2); % Last parameter tunes how saturated colors can get
% Set NaNs (unknown flow) to 0
I(isnan(I)) = reverseMap;
limits = []; % This colourmap doesn't have a valid colourbar
%% Phase
case 'phase'
% Plot amplitude as intensity and angle as hue
if c < 2
error('''phase'' requires two channels');
end
if isempty(limits)
limits = [min(I(:,1)) max(I(:,1))];
end
if reverseMap
% Invert the phase
I(:,2) = -I(:,2);
end
I = I(:,[2 1]);
if diff(limits)
I = phase_helper(I, limits, 1.3); % Last parameter tunes how saturated colors can get
else
% No intensity - just cycle hsv
I = hsv_helper(mod(I(:,1) / (2 * pi), 1));
end
limits = []; % This colourmap doesn't have a valid colourbar
%% RGB2Grey
case {'rgb2grey', 'rgb2gray'}
% Compress RGB to greyscale
[I limits] = rgb2grey(I, limits, reverseMap);
%% RGB2YUV
case 'rgb2yuv'
% Convert RGB to YUV - not for displaying or saving to disk!
[I limits] = rgb2yuv(I);
%% YUV2RGB
case 'yuv2rgb'
% Convert YUV to RGB - undo conversion of rgb2yuv
if c ~= 3
error('''yuv2rgb'' requires a 3 channel image');
end
I = reshape(I, y*x, 3);
I = I * [1 1 1; 0, -0.39465, 2.03211; 1.13983, -0.58060 0];
I = reshape(I, y, x, 3);
I = sc(I, limits);
limits = []; % This colourmap doesn't have a valid colourbar
%% Prob
case 'prob'
% Plot first channel as grey variation of 'bled' and modulate
% according to other channels
if c > 1
A = rgb2grey(I(:,2:end), [], false);
I = I(:,1);
else
A = 0.5;
end
[I limits] = bled(I, limits, reverseMap);
I = normalize(A + I, [-0.1 1.3]);
%% Prob_jet
case 'prob_jet'
% Plot first channel as 'jet' and modulate according to other
% channels
if c > 1
A = rgb2grey(I(:,2:end), [], false);
I = I(:,1);
else
A = 0.5;
end
[I limits] = jet_helper(I, limits, reverseMap);
I = normalize(A + I, [0.2 1.8]);
%% Compress
case 'compress'
% Compress to RGB, maximizing variance
% Determine and scale to limits
I = normalize(I, limits);
if reverseMap
% Invert after everything
I = 1 - I;
end
% Zero mean
meanCol = mean(I, 1);
isBsx = exist('bsxfun', 'builtin');
if isBsx
I = bsxfun(@minus, I, meanCol);
else
I = I - meanCol(ones(x*y, 1, 'uint8'),:);
end
% Calculate top 3 principle components
I = calc_prin_comps(I, 3);
% Normalize each channel independently
if isBsx
I = bsxfun(@minus, I, min(I, [], 1));
I = bsxfun(@times, I, 1./max(I, [], 1));
else
for a = 1:3
I(:,a) = I(:,a) - min(I(:,a));
I(:,a) = I(:,a) / max(I(:,a));
end
end
% Put components in order of human eyes' response to channels
I = I(:,[2 1 3]);
limits = []; % This colourmap doesn't have a valid colourbar
%% Stereo (anaglyph)
case 'stereo'
% Convert 2 colour images to intensity images
% Show first channel as red and second channel as cyan
A = rgb2grey(I(:,1:floor(end/2)), limits, false);
I = rgb2grey(I(:,floor(end/2)+1:end), limits, false);
if reverseMap
I(:,2:3) = A(:,1:2); % Make first image cyan
else
I(:,1) = A(:,1); % Make first image red
end
limits = []; % This colourmap doesn't have a valid colourbar
%% Coloured anaglyph
case 'stereo_col'
if c ~= 6
error('''stereo_col'' requires a 6 channel image');
end
I = normalize(I, limits);
% Red channel from one image, green and blue from the other
if reverseMap
I(:,1) = I(:,4); % Make second image red
else
I(:,2:3) = I(:,5:6); % Make first image red
end
I = I(:,1:3);
limits = []; % This colourmap doesn't have a valid colourbar
%% None
case 'none'
% No colour map - just output the image
if c ~= 3
[I limits] = grey(I, limits, reverseMap);
else
I = intensity(I(:), limits, reverseMap);
limits = [];
end
%% Grey
case {'gray', 'grey'}
% Greyscale
[I limits] = grey(I, limits, reverseMap);
%% Jet
case 'jet'
% Dark blue to dark red, through green
[I limits] = jet_helper(I, limits, reverseMap);
case 'jet2'
% Like jet, but starts in black and goes to saturated red
[I limits] = interp_map(I, limits, reverseMap, [0 0 0; 0.5 0 0.5; 0 0 0.9; 0 1 1; 0 1 0; 1 1 0; 1 0 0]);
%% Hot
case 'hot'
% Black to white through red and yellow
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 1 0 0 3; 1 1 0 2; 1 1 1 0]);
case 'hot2'
% Like hot, but equally spaced
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = I * 3;
I = [I, I-1, I-2];
I = min(max(I, 0), 1); % Truncate
case {'hotter', 'hot*'}
% Converts to linear greyscale
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 299; 1 0 0 587; 1 1 0 114; 1 1 1 0]);
%% Thermal
case 'thermal'
% Black, purple, red, orange, yellow - typical for thermal imaging
[I limits] = interp_map(I, limits, reverseMap, [0 0 0; 0.3 0 0.7; 1 0.2 0; 1 1 0; 1 1 1]);
case 'thermal*'
% Converts to linear greyscale
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 1695; 0.3 0 0.7 2469; 1 0.2 0 4696; 1 1 0 1140; 1 1 1 0]);
%% Contrast
case 'contrast'
% A high contrast, full-colour map that goes from black to white
% linearly when converted to greyscale, and passes through all the
% corners of the RGB colour cube
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 114; 0 0 1 185; 1 0 0 114; 1 0 1 174;...
0 1 0 114; 0 1 1 185; 1 1 0 114; 1 1 1 0]);
%% HSV
case 'hsv'
% Cycle through hues
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = hsv_helper(I);
%% Bone
case 'bone'
% Greyscale with a blue tint
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 21 21 29 3; 42 50 50 2; 64 64 64 1]/64);
case 'bone2'
% Like bone, but equally spaced
[I limits] = intensity(I, limits, reverseMap); % Intensity map
J = [I-2/3, I-1/3, I];
J = max(min(J, 1/3), 0) * (2 / 5);
I = I * (13 / 15);
I = J + I(:,[1 1 1]);
%% Colourcube
case {'colorcube', 'colourcube'}
% Psychedelic colourmap inspired by MATLAB's version
[I limits] = intensity(I, limits, reverseMap); % Intensity map
step = 4;
I = I * (step * (1 - eps));
J = I * step;
K = floor(J);
I = cat(3, mod(K, step)/(step-1), J - floor(K), mod(floor(I), step)/(step-1));
%% Cool
case 'cool'
% Cyan through to magenta
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I, 1-I, ones(size(I))];
%% Spring
case 'spring'
% Magenta through to yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [ones(size(I)), I, 1-I];
%% Summer
case 'summer'
% Darkish green through to pale yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I, 0.5+I*0.5, 0.4*ones(size(I))];
%% Autumn
case 'autumn'
% Red through to yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [ones(size(I)), I, zeros(size(I))];
%% Winter
case 'winter'
% Blue through to turquoise
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [zeros(size(I)), I, 1-I*0.5];
%% Copper
case 'copper'
% Black through to copper
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I*(1/0.8), I*0.78, I*0.5];
I = min(max(I, 0), 1); % Truncate
case {'copper2', 'copper*'}
% Converts to greyscale
[I limits] = interp_map(I, limits, reverseMap, [0 0 0; 0.2651 0.2426 0.2485; 0.666 0.4399 0.3738; 0.8118 0.7590 0.5417; 1 1 1]);
%% Pink
case 'pink'
% Greyscale with a pink tint
[I limits] = intensity(I, limits, reverseMap); % Intensity map
J = I * (2 / 3);
I = [I, I-1/3, I-2/3];
I = max(min(I, 1/3), 0);
I = I + J(:,[1 1 1]);
I = sqrt(I);
%% Sepia
case 'sepia'
% Greyscale with a brown (sepia) tint
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 5; 0.1 0.05 0 85; 1 0.9 0.8 10; 1 1 1 0]);
%% Bled
case 'bled'
% Black to red, through blue
[I limits] = bled(I, limits, reverseMap);
%% Earth
case 'earth'
% High contrast, converts to linear scale in grey, strong
% shades of green
table = [0 0 0; 0 0.1104 0.0583; 0.1661 0.1540 0.0248; 0.1085 0.2848 0.1286;...
0.2643 0.3339 0.0939; 0.2653 0.4381 0.1808; 0.3178 0.5053 0.3239;...
0.4858 0.5380 0.3413; 0.6005 0.5748 0.4776; 0.5698 0.6803 0.6415;...
0.5639 0.7929 0.7040; 0.6700 0.8626 0.6931; 0.8552 0.8967 0.6585;...
1 0.9210 0.7803; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Pinker
case 'pinker'
% High contrast, converts to linear scale in grey, strong
% shades of pink
table = [0 0 0; 0.0455 0.0635 0.1801; 0.2425 0.0873 0.1677;...
0.2089 0.2092 0.2546; 0.3111 0.2841 0.2274; 0.4785 0.3137 0.2624;...
0.5781 0.3580 0.3997; 0.5778 0.4510 0.5483; 0.5650 0.5682 0.6047;...
0.6803 0.6375 0.5722; 0.8454 0.6725 0.5855; 0.9801 0.7032 0.7007;...
1 0.7777 0.8915; 0.9645 0.8964 1; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Pastel
case 'pastel'
% High contrast, converts to linear scale in grey, strong
% pastel shades
table = [0 0 0; 0.4709 0 0.018; 0 0.3557 0.6747; 0.8422 0.1356 0.8525;
0.4688 0.6753 0.3057; 1 0.6893 0.0934; 0.9035 1 0; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Bright
case 'bright'
% High contrast, converts to linear scale in grey, strong
% saturated shades
table = [0 0 0; 0.3071 0.0107 0.3925; 0.007 0.289 1; 1 0.0832 0.7084;
1 0.4447 0.1001; 0.5776 0.8360 0.4458; 0.9035 1 0; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Unknown colourmap
otherwise
error('Colormap ''%s'' not recognised.', map);
end
return
%% Display image
function display_image(I, map, limits, reverseMap)
% Clear the axes
cla(gca, 'reset');
% Display the image - using image() is fast
hIm = image(I);
% Get handles to the figure and axes (now, as the axes may have
% changed)
hFig = gcf; hAx = gca;
% Axes invisible and equal
set(hFig, 'Units', 'pixels');
set(hAx, 'Visible', 'off', 'DataAspectRatio', [1 1 1], 'DrawMode', 'fast');
% Make title and axis labels visible
set(get(hAx, 'XLabel'), 'Visible', 'on');
set(get(hAx, 'YLabel'), 'Visible', 'on');
set(get(hAx, 'Title'), 'Visible', 'on');
% Set data for a colorbar
if ~isempty(limits) && limits(1) ~= limits(2)
colBar = (0:255) * ((limits(2) - limits(1)) / 255) + limits(1);
colBar = squeeze(sc(colBar, map, limits));
if reverseMap
colBar = colBar(end:-1:1,:);
end
set(hFig, 'Colormap', colBar);
set(hAx, 'CLim', limits);
set(hIm, 'CDataMapping', 'scaled');
end
% Only resize image if it is alone in the figure
if numel(findobj(get(hFig, 'Children'), 'Type', 'axes')) > 1
return
end
% Could still be the first subplot - do another check
axesPos = get(hAx, 'Position');
if isequal(axesPos, get(hFig, 'DefaultAxesPosition'))
% Default position => not a subplot
% Fill the window
set(hAx, 'Units', 'normalized', 'Position', [0 0 1 1]);
axesPos = [0 0 1 1];
end
if ~isequal(axesPos, [0 0 1 1]) || strcmp(get(hFig, 'WindowStyle'), 'docked')
% Figure not alone, or docked. Either way, don't resize.
return
end
% Get the size of the monitor we're on
figPosCur = get(hFig, 'Position');
MonSz = get(0, 'MonitorPositions');
MonOn = size(MonSz, 1);
if MonOn > 1
figCenter = figPosCur(1:2) + figPosCur(3:4) / 2;
figCenter = MonSz - repmat(figCenter, [MonOn 2]);
MonOn = all(sign(figCenter) == repmat([-1 -1 1 1], [MonOn 1]), 2);
MonOn(1) = MonOn(1) | ~any(MonOn);
MonSz = MonSz(MonOn,:);
end
MonSz(3:4) = MonSz(3:4) - MonSz(1:2) + 1;
% Check if the window is maximized
% This is a hack which may only work on Windows! No matter, though.
if isequal(MonSz([1 3]), figPosCur([1 3]))
% Leave maximized
return
end
% Compute the size to set the window
MaxSz = MonSz(3:4) - [20 120];
ImSz = [size(I, 2) size(I, 1)];
RescaleFactor = min(MaxSz ./ ImSz);
if RescaleFactor > 1
% Integer scale for enlarging, but don't make too big
MaxSz = min(MaxSz, [1000 680]);
RescaleFactor = max(floor(min(MaxSz ./ ImSz)), 1);
end
figPosNew = ceil(ImSz * RescaleFactor);
% Don't move the figure if the size isn't changing
if isequal(figPosCur(3:4), figPosNew)
return
end
% Keep the centre of the figure stationary
figPosNew = [max(1, floor(figPosCur(1:2)+(figPosCur(3:4)-figPosNew)/2)) figPosNew];
% Ensure the figure bar is in bounds
figPosNew(1:2) = min(figPosNew(1:2), MonSz(1:2)+MonSz(3:4)-[6 101]-figPosNew(3:4));
set(hFig, 'Position', figPosNew);
return
%% Parse input variables
function [map limits mask] = parse_inputs(I, inputs, y, x)
% Check the first two arguments for the colormap and limits
ninputs = numel(inputs);
map = 'none';
limits = [];
mask = 1;
for a = 1:min(2, ninputs)
if ischar(inputs{a}) && numel(inputs{a}) > 1
% Name of colormap
map = inputs{a};
elseif isnumeric(inputs{a})
[p q r] = size(inputs{a});
if (p * q * r) == 2
% Limits
limits = double(inputs{a});
elseif p > 1 && (q == 3 || q == 4) && r == 1
% Table-based colormap
map = inputs{a};
else
break;
end
else
break;
end
mask = mask + 1;
end
% Check for following inputs
if mask > ninputs
mask = cell(2, 0);
return
end
% Following inputs must either be colour/mask pairs, or a colour for NaNs
if ninputs - mask == 0
mask = cell(2, 1);
mask{1} = inputs{end};
mask{2} = ~all(isfinite(I), 3);
elseif mod(ninputs-mask, 2) == 1
mask = reshape(inputs(mask:end), 2, []);
else
error('Error parsing inputs');
end
% Go through pairs and generate
for a = 1:size(mask, 2)
% Generate any masks from functions
if isa(mask{2,a}, 'function_handle')
mask{2,a} = mask{2,a}(I);
end
if ~islogical(mask{2,a})
error('Mask is not a logical array');
end
if ~isequal(size(mask{2,a}), [y x])
error('Mask does not match image size');
end
if ischar(mask{1,a})
if numel(mask{1,a}) == 1
% Generate colours from MATLAB colour strings
mask{1,a} = rem(floor((strfind('kbgcrmyw', mask{1,a}) - 1) * [0.25 0.5 1]), 2);
else
% Assume it's a colormap name
mask{1,a} = sc(I, mask{1,a});
end
end
mask{1,a} = reshape(mask{1,a}, [], 3);
if size(mask{1,a}, 1) ~= y*x && size(mask{1,a}, 1) ~= 1
error('Replacement color/image of unexpected dimensions');
end
if size(mask{1,a}, 1) ~= 1
mask{1,a} = mask{1,a}(mask{2,a},:);
end
end
return
%% Grey
function [I limits] = grey(I, limits, reverseMap)
% Greyscale
[I limits] = intensity(I, limits, reverseMap);
I = I(:,[1 1 1]);
return
%% RGB2grey
function [I limits] = rgb2grey(I, limits, reverseMap)
% Compress RGB to greyscale
if size(I, 2) == 3
I = I * [0.299; 0.587; 0.114];
end
[I limits] = grey(I, limits, reverseMap);
return
%% RGB2YUV
function [I limits] = rgb2yuv(I)
% Convert RGB to YUV - not for displaying or saving to disk!
if size(I, 2) ~= 3
error('rgb2yuv requires a 3 channel image');
end
I = I * [0.299, -0.14713, 0.615; 0.587, -0.28886, -0.51498; 0.114, 0.436, -0.10001];
limits = []; % This colourmap doesn't have a valid colourbar
return
%% Phase helper
function I = phase_helper(I, limits, n)
I(:,1) = mod(I(:,1)/(2*pi), 1);
I(:,2) = I(:,2) - limits(1);
I(:,2) = I(:,2) * (n / (limits(2) - limits(1)));
I(:,3) = n - I(:,2);
I(:,[2 3]) = min(max(I(:,[2 3]), 0), 1);
I = hsv2rgb(reshape(I, [], 1, 3));
return
%% Jet helper
function [I limits] = jet_helper(I, limits, reverseMap)
% Dark blue to dark red, through green
[I limits] = intensity(I, limits, reverseMap);
I = I * 4;
I = [I-3, I-2, I-1];
I = 1.5 - abs(I);
I = min(max(I, 0), 1);
return
%% HSV helper
function I = hsv_helper(I)
I = I * 6;
I = abs([I-3, I-2, I-4]);
I(:,1) = I(:,1) - 1;
I(:,2:3) = 2 - I(:,2:3);
I = min(max(I, 0), 1);
return
%% Bled
function [I limits] = bled(I, limits, reverseMap)
% Black to red through blue
[I limits] = intensity(I, limits, reverseMap);
J = reshape(hsv_helper(I), [], 3);
if exist('bsxfun', 'builtin')
I = bsxfun(@times, I, J);
else
I = J .* I(:,[1 1 1]);
end
return
%% Normalize
function [I limits] = normalize(I, limits)
if isempty(limits)
limits = isfinite(I);
if ~any(reshape(limits, numel(limits), 1))
% All NaNs, Infs or -Infs
I = double(I > 0);
limits = [0 1];
return
end
limits = [min(I(limits)) max(I(limits))];
I = I - limits(1);
if limits(2) ~= limits(1)
I = I * (1 / (limits(2) - limits(1)));
end
else
I = I - limits(1);
if limits(2) ~= limits(1)
I = I * (1 / (limits(2) - limits(1)));
end
I = min(max(I, 0), 1);
end
return
%% Intensity maps
function [I limits] = intensity(I, limits, reverseMap)
% Squash to 1d using L2 norm
if size(I, 2) > 1
I = sqrt(sum(I .^ 2, 2));
end
% Determine and scale to limits
[I limits] = normalize(I, limits);
if reverseMap
% Invert after everything
I = 1 - I;
end
return
%% Interpolate table-based map
function [I limits] = interp_map(I, limits, reverseMap, map)
% Convert to intensity
[I limits] = intensity(I, limits, reverseMap);
% Compute indices and offsets
if size(map, 2) == 4
bins = map(1:end-1,4);
cbins = cumsum(bins);
bins = bins ./ cbins(end);
cbins = cbins(1:end-1) ./ cbins(end);
if exist('bsxfun', 'builtin')
ind = bsxfun(@gt, I(:)', cbins(:));
else
ind = repmat(I(:)', [numel(cbins) 1]) > repmat(cbins(:), [1 numel(I)]);
end
ind = min(sum(ind), size(map, 1) - 2) + 1;
bins = 1 ./ bins;
cbins = [0; cbins];
I = (I - cbins(ind)) .* bins(ind);
else
n = size(map, 1) - 1;
I = I(:) * n;
ind = min(floor(I), n-1);
I = I - ind;
ind = ind + 1;
end
if exist('bsxfun', 'builtin')
I = bsxfun(@times, map(ind,1:3), 1-I) + bsxfun(@times, map(ind+1,1:3), I);
else
I = map(ind,1:3) .* repmat(1-I, [1 3]) + map(ind+1,1:3) .* repmat(I, [1 3]);
end
I = min(max(I, 0), 1); % Rounding errors can make values slip outside bounds
return
%% Index images
function [J limits num_vals] = index_im(I)
% Returns an index image
if size(I, 2) ~= 1
error('Index maps only work on single channel images');
end
J = round(I);
rescaled = any(abs(I - J) > 0.01);
if rescaled
% Appears not to be an index image. Rescale over 256 indices
m = min(I);
m = m * (1 - sign(m) * eps);
I = I - m;
I = I * (256 / max(I(:)));
J = ceil(I);
num_vals = 256;
elseif nargout > 2
% Output the number of values
J = J - (min(J) - 1);
num_vals = max(J);
end
% These colourmaps don't have valid colourbars
limits = [];
return
%% Calculate principle components
function I = calc_prin_comps(I, numComps)
if nargin < 2
numComps = size(I, 2);
end
% Do SVD
[I S] = svd(I, 0);
% Calculate projection of data onto components
S = diag(S(1:numComps,1:numComps))';
if exist('bsxfun', 'builtin')
I = bsxfun(@times, I(:,1:numComps), S);
else
I = I(:,1:numComps) .* S(ones(size(I, 1), 1, 'uint8'),:);
end
return
%% Demo function to show capabilities of sc
function demo
%% Demo gray & lack of border
figure; fig = gcf; Z = peaks(256); sc(Z);
display_text([...
' Lets take a standard, MATLAB, real-valued function:\n\n peaks(256)\n\n'...
' Calling:\n\n figure\n Z = peaks(256);\n sc(Z)\n\n'...
' gives (see figure). SC automatically scales intensity to fill the\n'...
' truecolor range of [0 1].\n\n'...
' If your figure isn''t docked, then the image will have no border, and\n'...
' will be magnified by an integer factor (in this case, 2) so that the\n'...
' image is a reasonable size.']);
%% Demo colour image display
figure(fig); clf;
load mandrill; mandrill = ind2rgb(X, map); sc(mandrill);
display_text([...
' That wasn''t so interesting. The default colormap is ''none'', which\n'...
' produces RGB images given a 3-channel input image, otherwise it produces\n'...
' a grayscale image. So calling:\n\n load mandrill\n'...
' mandrill = ind2rgb(X, map);\n sc(mandrill)\n\n gives (see figure).']);
%% Demo discretization
figure(fig); clf;
subplot(121); sc(Z, 'jet'); label(Z, 'sc(Z, ''jet'')');
subplot(122); imagesc(Z); axis image off; colormap(jet(64)); % Fix the fact we change the default depth
label(Z, 'imagesc(Z); axis image off; colormap(''jet'');');
display_text([...
' However, if we want to display intensity images in color we can use any\n'...
' of the MATLAB colormaps implemented (most of them) to give truecolor\n'...
' images. For example, to use ''jet'' simply call:\n\n'...
' sc(Z, ''jet'')\n\n'...
' The MATLAB alternative, shown on the right, is:\n\n'...
' imagesc(Z)\n axis equal off\n colormap(jet)\n\n'...
' which generates noticeable discretization artifacts.']);
%% Demo intensity colourmaps
figure(fig); clf;
subplot(221); sc(Z, 'hsv'); label(Z, 'sc(Z, ''hsv'')');
subplot(222); sc(Z, 'colorcube'); label(Z, 'sc(Z, ''colorcube'')');
subplot(223); sc(Z, 'contrast'); label(Z, 'sc(Z, ''contrast'')');
subplot(224); sc(Z-round(Z), 'diff'); label(Z, 'sc(Z-round(Z), ''diff'')');
display_text([...
' There are several other intensity colormaps to choose from. Calling:\n\n'...
' help sc\n\n'...
' will give you a list of them. Here are several others demonstrated.']);
%% Demo saturation limits & colourmap reversal
figure(fig); clf;
subplot(121); sc(Z, [0 max(Z(:))], '-hot'); label(Z, 'sc(Z, [0 max(Z(:))], ''-hot'')');
subplot(122); sc(mandrill, [-0.5 0.5]); label(mandrill, 'sc(mandrill, [-0.5 0.5])');
display_text([...
' SC can also rescale intensity, given an upper and lower bound provided\n'...
' by the user, and invert most colormaps simply by prefixing a ''-'' to the\n'...
' colormap name. For example:\n\n'...
' sc(Z, [0 max(Z(:))], ''-hot'');\n'...
' sc(mandrill, [-0.5 0.5]);\n\n'...
' Note that the order of the colormap and limit arguments are\n'...
' interchangable.']);
%% Demo prob
load gatlin;
gatlin = X;
figure(fig); clf; im = cat(3, abs(Z)', gatlin(1:256,end-255:end)); sc(im, 'prob');
label(im, 'sc(cat(3, prob, gatlin), ''prob'')');
display_text([...
' SC outputs the recolored data as a truecolor RGB image. This makes it\n'...
' easy to combine colormaps, either arithmetically, or by masking regions.\n'...
' For example, we could combine an image and a probability map\n'...
' arithmetically as follows:\n\n'...
' load gatlin\n'...
' gatlin = X(1:256,end-255:end);\n'...
' prob = abs(Z)'';\n'...
' im = sc(prob, ''hsv'') .* sc(prob, ''gray'') + sc(gatlin, ''rgb2gray'');\n'...
' sc(im, [-0.1 1.3]);\n\n'...
' In fact, that particular colormap has already been implemented in SC.\n'...
' Simply call:\n\n'...
' sc(cat(3, prob, gatlin), ''prob'');']);
%% Demo colorbar
colorbar;
display_text([...
' SC also makes possible the generation of a colorbar in the normal way, \n'...
' with all the colours and data values correct. Simply call:\n\n'...
' colorbar\n\n'...
' The colorbar doesn''t work with all colormaps, but when it does,\n'...
' inverting the colormap (using ''-map'') maintains the integrity of the\n'...
' colorbar (i.e. it works correctly) - unlike if you invert the input data.']);
%% Demo combine by masking
figure(fig); clf;
sc(Z, [0 max(Z(:))], '-hot', sc(Z-round(Z), 'diff'), Z < 0);
display_text([...
' It''s just as easy to combine generated images by masking too. Here''s an\n'...
' example:\n\n'...
' im = cat(4, sc(Z, [0 max(Z(:))], ''-hot''), sc(Z-round(Z), ''diff''));\n'...
' mask = repmat(Z < 0, [1 1 3]);\n'...
' mask = cat(4, mask, ~mask);\n'...
' im = sum(im .* mask, 4);\n'...
' sc(im)\n\n'...
' In fact, SC can also do this for you, by adding image/colormap and mask\n'...
' pairs to the end of the argument list, as follows:\n\n'...
' sc(Z, [0 max(Z(:))], ''-hot'', sc(Z-round(Z), ''diff''), Z < 0);\n\n'...
' A benefit of the latter approach is that you can still display a\n'...
' colorbar for the first colormap.']);
%% Demo texture map
figure(fig); clf;
surf(Z, sc(Z, 'contrast'), 'edgecolor', 'none');
display_text([...
' Other benefits of SC outputting the image as an array are that the image\n'...
' can be saved straight to disk using imwrite() (if you have the image\n'...
' processing toolbox), or can be used to texture map a surface, thus:\n\n'...
' tex = sc(Z, ''contrast'');\n'...
' surf(Z, tex, ''edgecolor'', ''none'');']);
%% Demo compress
load mri;
mri = D;
close(fig); % Only way to get round loss of focus (bug?)
figure(fig); clf;
sc(squeeze(mri(:,:,:,1:6)), 'compress');
display_text([...
' For images with more than 3 channels, SC can compress these images to RGB\n'...
' while maintaining the maximum amount of variance in the data. For\n'...
' example, this 6 channel image:\n\n'...
' load mri\n mri = D;\n sc(squeeze(mri(:,:,:,1:6), ''compress'')']);
%% Demo multiple images
figure(fig); clf; im = sc(mri, 'bone');
for a = 1:12
subplot(3, 4, a);
sc(im(:,:,:,a));
end
display_text([...
' SC can process multiple images for export when passed in as a 4d array.\n'...
' For example:\n\n'...
' im = sc(mri, ''bone'')\n'...
' for a = 1:12\n'...
' subplot(3, 4, a);\n'...
' sc(im(:,:,:,a));\n'...
' end']);
%% Demo user defined colormap
figure(fig); clf; sc(abs(Z), rand(10, 3)); colorbar;
display_text([...
' Finally, SC can use user defined colormaps to display indexed images.\n'...
' These can be defined as a linear colormap. For example:\n\n'...
' sc(abs(Z), rand(10, 3))\n colorbar;\n\n'...
' Note that the colormap is automatically linearly interpolated.']);
%% Demo non-linear user defined colormap
figure(fig); clf; sc(abs(Z), [rand(10, 3) exp((1:10)/2)']); colorbar;
display_text([...
' Non-linear colormaps can also be defined by the user, by including the\n'...
' relative distance between the given colormap points on the colormap\n'...
' scale in the fourth column of the colormap matrix. For example:\n\n'...
' sc(abs(Z), [rand(10, 3) exp((1:10)/2)''])\n colorbar;\n\n'...
' Note that the colormap is still linearly interpolated between points.']);
clc; fprintf('End of demo.\n');
return
%% Some helper functions for the demo
function display_text(str)
clc;
fprintf([str '\n\n']);
fprintf('Press a key to go on.\n');
figure(gcf);
waitforbuttonpress;
return
function label(im, str)
text(size(im, 2)/2, size(im, 1)+12, str,...
'Interpreter', 'none', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
return
|
github
|
ma-xu/2PTWSVM-master
|
psvm.m
|
.m
|
2PTWSVM-master/AccuracyPSVM/psvm.m
| 5,947 |
utf_8
|
484a5de502317215d57c1fc439c57533
|
function [w,gamma, trainCorr, testCorr, cpu_time, nu]=psvm(A,d,k,nu,output,bal);
% version 1.1
% last revision: 01/24/03
%===============================================================================
% Usage: [w,gamma,trainCorr, testCorr,cpu_time,nu]=psvm(A,d,k,nu,output,bal)
%
% A and d are both required, everything else has a default
% An example: [w gamma train test time nu] = psvm(A,d,10);
%
% Input:
% A is a matrix containing m data in n dimensions each.
% d is a m dimensional vector of 1's or -1's containing
% the corresponding labels for each example in A.
% k is k-fold for correctness purpose
% nu - the weighting factor.
% -1 - easy estimation
% 0 - hard estimation
% any other value - used as nu by the algorithm
% default - 0
% output - indicates whether you want output
%
% If the input parameter bal is 1
% the algorithm weighs the classes depending on the
% number of points in each class and balance them.
% It is useful when the number of point in each class
% is very unbalanced.
%
% Output:
% w,gamma are the values defining the separating
% Hyperplane w'x-gamma=0 such that:
%
% w'x-gamma>0 => x belongs to A+
% w'x-gamma<0 => x belongs to A-
% w'x-gamma=0 => x can belongs to both classes
% nu - the estimated or specified value of nu
%
% For details refer to the paper:
% "Proximal Support Vector Machine Classifiers"
% available at: www.cs.wisc.edu/~gfung
% For questions or suggestions, please email:
% Glenn Fung, [email protected]
% Sept 2001.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic;
[m,n]=size(A);
r=randperm(size(d,1));d=d(r,:);A=A(r,:); % random permutation
%move one point in A a little if perfectly balanced
AA=A;dd=d;
ma=A(find(d==1),:); mb=A(find(d==-1),:);
[s1 s2]=size(ma);
c1=sum(ma)/s1;
[s1 s2]=size(mb);
c2=sum(mb)/s1;
if (c1==c2)
nu=1;
A(3,:)=A(3,:)+0.01*norm(A(3,:)-c1,inf)*ones(1,n);
end
% default values for input parameters
if nargin<6
bal=0;
end
if nargin<5
output=0;
end
if (nargin<4)
nu=0; % default is hard estimation
end
if (nargin<3)
k=0;
end
[H,v]=HV(A,d,bal); % calculate H and v
trainCorr = 0;
testCorr = 0;
if (nu==0)
nu = EstNuLong(H,d,m);
elseif nu==-1 % easy estimation
nu = EstNuShort(H,d);
end
% if k=0 no correctness is calculated, just run the algorithm
if k==0
[w, gamma] = core(H,v,nu,n);
cpu_time = toc;
return
end
%if k==1 only training set correctness is calculated
if k==1
[w, gamma] = core(H,v,nu,n);
trainCorr = correctness(AA,dd,w,gamma);
cpu_time = toc;
if output == 1
fprintf(1,'\nTraining set correctness: %3.2f%% \n',trainCorr);
fprintf(1,'\nElapse time: %10.2f\n',toc);
end
return
end
[sm sn]=size(A);
accuIter = 0;
lastToc=0; % used for calculating time
indx = [0:k];
indx = floor(sm*indx/k); %last row numbers for all 'segments'
% split trainining set from test set
tic;
for i = 1:k
Ctest = []; dtest = [];Ctrain = []; dtrain = [];
Ctest = A((indx(i)+1:indx(i+1)),:);
dtest = d(indx(i)+1:indx(i+1));
Ctrain = A(1:indx(i),:);
Ctrain = [Ctrain;A(indx(i+1)+1:sm,:)];
dtrain = [d(1:indx(i));d(indx(i+1)+1:sm,:)];
[H, v] = HV(Ctrain,dtrain,bal);
[w, gamma] = core(H,v,nu,n);
tmpTrainCorr = correctness(Ctrain,dtrain,w,gamma);
trainCorr = trainCorr + tmpTrainCorr;
tmpTestCorr = correctness(Ctest,dtest,w,gamma);
testCorr = testCorr + tmpTestCorr;
if output==1
fprintf(1,'________________________________________________\n');
fprintf(1,'Fold %d\n',i);
fprintf(1,'Training set correctness: %3.2f%%\n',tmpTrainCorr);
fprintf(1,'Testing set correctness: %3.2f%%\n',tmpTestCorr);
fprintf(1,'Elapse time: %10.2f\n',toc);
end
end %
trainCorr = trainCorr/k;
testCorr = testCorr/k;
cpu_time = toc/k;
if output == 1
fprintf(1,'___________________________________________________\n');
fprintf(1,'\nTraining set correctness: %3.2f%% \n',trainCorr);
fprintf(1,'\nTesting set correctness: %3.2f%% \n',testCorr);
fprintf(1,'\nAverage CPU time is: %3.2f \n',cpu_time);
end
%y=spdiags(d,0,m,m)*((A*w-gamma)-ones(m,1));
return
%%%%%%%%%%%%%%%% core function to calcuate w and gamma %%%%%%%%
function [w, gamma]=core(H,v,nu,n)
v=(speye(n+1)/nu+H'*H)\v;
w=v(1:n);gamma=v(n+1);
return
%%%%%%%%%%%%%%% correctness calculation %%%%%%%%%%%%%%%%%%%%
function corr = correctness(AA,dd,w,gamma)
p=sign(AA*w-gamma);
corr=length(find(p==dd))/size(AA,1)*100;
return
%%%%%%%%%%%%% EstNuLong %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% use to estimate nu
function lamda=EstNuLong(H,d,m)
if m<201
H2=H;d2=d;
else
r=rand(m,1);
[s1,s2]=sort(r);
H2=H(s2(1:200),:);
d2=d(s2(1:200));
end
lamda=1;
[vu,u]=eig(H2*H2');u=diag(u);p=length(u);
yt=d2'*vu;
lamdaO=lamda+1;
cnt=0;
while (abs(lamdaO-lamda)>10e-4)&(cnt<100)
cnt=cnt+1;
nu1=0;pr=0;ee=0;waw=0;
lamdaO=lamda;
for i=1:p
nu1= nu1 + lamda/(u(i)+lamda);
pr= pr + u(i)/(u(i)+lamda)^2;
ee= ee + u(i)*yt(i)^2/(u(i)+lamda)^3;
waw= waw + lamda^2*yt(i)^2/(u(i)+lamda)^2;
end
lamda=nu1*ee/(pr*waw);
end
value=lamda;
if cnt==100
value=1;
end
%%%%%%%%%%%%%%%%%EstNuShort%%%%%%%%%%%%%%%%%%%%%%%
% easy way to estimate nu if not specified by the user
function value = EstNuShort(C,d)
value = 1/(sum(sum(C.^2))/size(C,2));
return
%%% function to calculate H and v %%%%%%%%%%%%%
function [H,v]=HV(A,d,bal);
[m,n]=size(A);e=ones(m,1);
if (bal==0)
H=[A -e];
v=(d'*H)';
else
H=[A -e];
mm=e;
m1=find(d==-1);
mm(m1)=(1/length(m1));
m2=find(d==1);
mm(m2)=(1/length(m2));
mm=sqrt(mm);
N=spdiags(mm,0,m,m);
H=N*H;
%keyboard
v=(d'*N*H)';
end
|
github
|
ma-xu/2PTWSVM-master
|
psvm2.m
|
.m
|
2PTWSVM-master/AccuracyPSVM/psvm2.m
| 6,063 |
utf_8
|
a401eae3c716fd9565e4fb0c51d9b9d6
|
function [w,gamma, trainCorr, testCorr, cpu_time, nu,testcorrstd]=psvm2(A,d,k,nu,output,bal);
% version 1.1
% last revision: 01/24/03
%===============================================================================
% Usage: [w,gamma,trainCorr, testCorr,cpu_time,nu]=psvm(A,d,k,nu,output,bal)
%
% A and d are both required, everything else has a default
% An example: [w gamma train test time nu] = psvm(A,d,10);
%
% Input:
% A is a matrix containing m data in n dimensions each.
% d is a m dimensional vector of 1's or -1's containing
% the corresponding labels for each example in A.
% k is k-fold for correctness purpose
% nu - the weighting factor.
% -1 - easy estimation
% 0 - hard estimation
% any other value - used as nu by the algorithm
% default - 0
% output - indicates whether you want output
%
% If the input parameter bal is 1
% the algorithm weighs the classes depending on the
% number of points in each class and balance them.
% It is useful when the number of point in each class
% is very unbalanced.
%
% Output:
% w,gamma are the values defining the separating
% Hyperplane w'x-gamma=0 such that:
%
% w'x-gamma>0 => x belongs to A+
% w'x-gamma<0 => x belongs to A-
% w'x-gamma=0 => x can belongs to both classes
% nu - the estimated or specified value of nu
%
% For details refer to the paper:
% "Proximal Support Vector Machine Classifiers"
% available at: www.cs.wisc.edu/~gfung
% For questions or suggestions, please email:
% Glenn Fung, [email protected]
% Sept 2001.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tic;
[m,n]=size(A);
r=randperm(size(d,1));d=d(r,:);A=A(r,:); % random permutation
%move one point in A a little if perfectly balanced
AA=A;dd=d;
ma=A(find(d==1),:); mb=A(find(d==-1),:);
[s1 s2]=size(ma);
c1=sum(ma)/s1;
[s1 s2]=size(mb);
c2=sum(mb)/s1;
if (c1==c2)
nu=1;
A(3,:)=A(3,:)+0.01*norm(A(3,:)-c1,inf)*ones(1,n);
end
% default values for input parameters
if nargin<6
bal=0;
end
if nargin<5
output=0;
end
if (nargin<4)
nu=0; % default is hard estimation
end
if (nargin<3)
k=0;
end
[H,v]=HV(A,d,bal); % calculate H and v
trainCorr = 0;
testCorr = 0;
if (nu==0)
nu = EstNuLong(H,d,m);
elseif nu==-1 % easy estimation
nu = EstNuShort(H,d);
end
% if k=0 no correctness is calculated, just run the algorithm
if k==0
[w, gamma] = core(H,v,nu,n);
cpu_time = toc;
return
end
%if k==1 only training set correctness is calculated
if k==1
[w, gamma] = core(H,v,nu,n);
trainCorr = correctness(AA,dd,w,gamma);
cpu_time = toc;
if output == 1
fprintf(1,'\nTraining set correctness: %3.2f%% \n',trainCorr);
fprintf(1,'\nElapse time: %10.2f\n',toc);
end
return
end
[sm sn]=size(A);
accuIter = 0;
lastToc=0; % used for calculating time
indx = [0:k];
indx = floor(sm*indx/k); %last row numbers for all 'segments'
% split trainining set from test set
testCorrList=[];
tic;
for i = 1:k
Ctest = []; dtest = [];Ctrain = []; dtrain = [];
Ctest = A((indx(i)+1:indx(i+1)),:);
dtest = d(indx(i)+1:indx(i+1));
Ctrain = A(1:indx(i),:);
Ctrain = [Ctrain;A(indx(i+1)+1:sm,:)];
dtrain = [d(1:indx(i));d(indx(i+1)+1:sm,:)];
[H, v] = HV(Ctrain,dtrain,bal);
[w, gamma] = core(H,v,nu,n);
tmpTrainCorr = correctness(Ctrain,dtrain,w,gamma);
trainCorr = trainCorr + tmpTrainCorr;
tmpTestCorr = correctness(Ctest,dtest,w,gamma);
testCorrList=[testCorrList;tmpTestCorr];
testCorr = testCorr + tmpTestCorr;
if output==1
fprintf(1,'________________________________________________\n');
fprintf(1,'Fold %d\n',i);
fprintf(1,'Training set correctness: %3.2f%%\n',tmpTrainCorr);
fprintf(1,'Testing set correctness: %3.2f%%\n',tmpTestCorr);
fprintf(1,'Elapse time: %10.2f\n',toc);
end
end %
trainCorr = trainCorr/k;
testCorr = testCorr/k;
cpu_time = toc/k;
testcorrstd=std(testCorrList,1);
if output == 1
fprintf(1,'___________________________________________________\n');
fprintf(1,'\nTraining set correctness: %3.2f%% \n',trainCorr);
fprintf(1,'\nTesting set correctness: %3.2f%% \n',testCorr);
fprintf(1,'\nAverage CPU time is: %3.2f \n',cpu_time);
end
%y=spdiags(d,0,m,m)*((A*w-gamma)-ones(m,1));
return
%%%%%%%%%%%%%%%% core function to calcuate w and gamma %%%%%%%%
function [w, gamma]=core(H,v,nu,n)
v=(speye(n+1)/nu+H'*H)\v;
w=v(1:n);gamma=v(n+1);
return
%%%%%%%%%%%%%%% correctness calculation %%%%%%%%%%%%%%%%%%%%
function corr = correctness(AA,dd,w,gamma)
p=sign(AA*w-gamma);
corr=length(find(p==dd))/size(AA,1)*100;
return
%%%%%%%%%%%%% EstNuLong %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% use to estimate nu
function lamda=EstNuLong(H,d,m)
if m<201
H2=H;d2=d;
else
r=rand(m,1);
[s1,s2]=sort(r);
H2=H(s2(1:200),:);
d2=d(s2(1:200));
end
lamda=1;
[vu,u]=eig(H2*H2');u=diag(u);p=length(u);
yt=d2'*vu;
lamdaO=lamda+1;
cnt=0;
while (abs(lamdaO-lamda)>10e-4)&(cnt<100)
cnt=cnt+1;
nu1=0;pr=0;ee=0;waw=0;
lamdaO=lamda;
for i=1:p
nu1= nu1 + lamda/(u(i)+lamda);
pr= pr + u(i)/(u(i)+lamda)^2;
ee= ee + u(i)*yt(i)^2/(u(i)+lamda)^3;
waw= waw + lamda^2*yt(i)^2/(u(i)+lamda)^2;
end
lamda=nu1*ee/(pr*waw);
end
value=lamda;
if cnt==100
value=1;
end
%%%%%%%%%%%%%%%%%EstNuShort%%%%%%%%%%%%%%%%%%%%%%%
% easy way to estimate nu if not specified by the user
function value = EstNuShort(C,d)
value = 1/(sum(sum(C.^2))/size(C,2));
return
%%% function to calculate H and v %%%%%%%%%%%%%
function [H,v]=HV(A,d,bal);
[m,n]=size(A);e=ones(m,1);
if (bal==0)
H=[A -e];
v=(d'*H)';
else
H=[A -e];
mm=e;
m1=find(d==-1);
mm(m1)=(1/length(m1));
m2=find(d==1);
mm(m2)=(1/length(m2));
mm=sqrt(mm);
N=spdiags(mm,0,m,m);
H=N*H;
%keyboard
v=(d'*N*H)';
end
|
github
|
ma-xu/2PTWSVM-master
|
monitormatlab.m
|
.m
|
2PTWSVM-master/NEW_TWSVM/monitormatlab.m
| 30,148 |
utf_8
|
702d3e62f38bce4f5547affd49f0de96
|
function monitormatlab(action)
%MONITORMATLAB Displays runtime diagnostic information
% This task manager like tool displays real time memory
% state of MATLAB, HG, and Java using time based strip charts.
%
% The following information is displayed:
% * Memory allocated by MATLAB
% * Memory allocated by Java
% * Memory allocted by the O/S
% * Number of MFiles in MATLAB memory
% * Size of m-file parsing stack
%
% To see real time MATLAB memory allocation, start MATLAB with
% the O/S environment flag "MATLAB_MEM_MGR" set to a "debug"
% as in: set MATLAB_MEM_MGR = debug.
%
% Example:
%
% monitormatlab
% bench
if str2num(version('-release'))<14
error('MATLAB version 14sp2 or later required')
end
if nargin==0
action = 'start';
end
if strcmp(action,'start')
info = localStart;
elseif strcmp(action,'stop')
localStop;
else
error('Invalid input')
end
%----------------------------------------------------------%
function [info] = localStart
drawnow;
[info] = localShowUI;
drawnow;
localSetInfo(info);
localStartPause;
[info] = localStartTimer(info);
localSetInfo(info);
drawnow;
localStopPause;
%----------------------------------------------------------%
function [info] = localShowUI
% Singleton: Only create new UI if current one is stale or empty
info = localGetInfo;
if isempty(info.figure) || ~ishandle(info.figure);
[info] = localRegisterPanels(info);
[info] = localCreateUI(info);
end
%----------------------------------------------------------%
function localOpenRecording(obj,evd)
localStartPause;
info = localGetInfo;
doload = true;
doreset = false;
[filename, pathname] = uigetfile('monitor.mat', 'Open mat file');
if filename ~= 0
s = load(fullfile(pathname,filename),'-mat');
% Loop through and set view
for n = 1:length(info.panel)
% Update each panel
hfunc = info.panel(n).update;
info.panel(n) = feval(hfunc,info.panel(n),s.info.panel(n),doload,doreset);
end
else
localStopPause;
end
localSetInfo(info);
%----------------------------------------------------------%
function localStartPause
h = findall(0,'type','uicontrol','Tag','Pause');
set(h,'Value',1);
%----------------------------------------------------------%
function localStopPause
h = findall(0,'type','uicontrol','Tag','Pause');
set(h,'Value',0);
%----------------------------------------------------------%
function localSaveRecording(obj,evd)
localStartPause
[filename, pathname] = uiputfile('monitor.mat', 'Open mat file');
if filename ~= 0
info = localGetInfo;
info.dorecord = true;
localSetInfo(info);
localUpdateRecording(fullfile(pathname,filename));
end
info = localGetInfo;
info.dorecord = false;
localSetInfo(info);
localStopPause;
%----------------------------------------------------------%
function localRecord(obj,evd)
info = localGetInfo;
p = get(obj,'parent');
ubegin = findall(p,'tag','BeginRecording');
ustop = findall(p,'tag','StopRecording');
if isequal(obj,ustop)
info.dorecord = false;
set(ubegin,'Enable','on');
set(ustop,'Enable','off');
elseif isequal(obj,ubegin)
info.dorecord = true;
set(ubegin,'Enable','off');
set(ustop,'Enable','on');
end
localSetInfo(info);
%----------------------------------------------------------%
function [info] = localCreateUI(info)
fig = figure('resize','off','handlevis','off','toolbar','none',...
'name','MATLAB Monitoring Tool','NumberTitle','off','units','pixels',...
'pos',[100 100 500 340],'DeleteFcn',@localShutDown);
info.figure = fig;
% Create figure menus
delete(findall(fig,'type','uimenu'));
% File Menu
u = uimenu('Parent',fig,'Label','File');
uimenu('Parent',u,'Tag','Load','Label','Open...',...
'Callback',@localOpenRecording);
uimenu('Parent',u,'Tag','Load','Label','Save',...
'Callback',@localSaveRecording);
% Tools menu
u = uimenu('Parent',fig,'Label','Tools');
uimenu('Parent',u,'Tag','BeginRecording',...
'Callback',@localRecord,...
'Label','Begin Recording to ''monitor.mat'' File');
uimenu('Callback',@localRecord,...
'Parent',u,'Tag','StopRecording',...
'Label','Stop Recording','Enable','off');
info.frame_center = uipanel('title','','titleposition','centertop',...
'parent',fig,'units','norm','pos',[0 0 1 1 ]);
info.frame_left = uibuttongroup('parent',info.frame_center,...
'units','norm',...
'pos',[0 0 .3 1 ],...
'BackgroundColor',[.4 .4 .4],...
'SelectionChangeFcn',@localButtonCallback);
uicontrol('style','togglebutton','Parent',info.frame_center,...
'units','norm','pos',[.03 .02 .2 .07],'string','Pause',...
'Tag','Pause');
uicontrol('style','pushbutton','Parent',info.frame_center,...
'units','norm','pos',[.03 .12 .2 .07],'string','Reset',...
'Tag','Reset','Callback',@localReset);
% Toggle button properties
props.style = 'togglebutton';
props.parent = info.frame_left;
props.units = 'norm';
props.position = [.1 1 .66 .07];
% Create each panel and button
for n = 1:length(info.panel)
panel_name = info.panel(n).name;
% Create panel
h = uipanel('parent',info.frame_center,...
'units','norm','pos',[.25 0 1 1],'Visible','off');
if (n==1)
set(h,'Visible','on');
end
info.panel(n).panel = h;
% Add a button for each panel
props.string = panel_name;
props.position(2) = props.position(2) - .1;
u(n) = uicontrol(props);
% Add panel contents
hfunc = info.panel(n).create;
info.panel(n).data = feval(hfunc,info.panel(n));
end
% Set first button to on by default
if length(u)>0
set(u(1),'Value',1);
end
%----------------------------------------------------------%
function [info] = localRegisterPanels(info)
ind = 0;
ind = ind + 1;
info.panel(ind).name = 'General';
info.panel(ind).update = @localUpdatePanelGeneral;
info.panel(ind).create = @localCreatePanelGeneral;
info.panel(ind).data = [];
info.panel(ind).panel = [];
ind = ind + 1;
info.panel(ind).name = 'MATLAB Memory';
info.panel(ind).update = @localUpdatePanelMalloc;
info.panel(ind).create = @localCreatePanelMalloc;
info.panel(ind).data = [];
info.panel(ind).panel = [];
% Don't show this panel on unix
if ispc
try
evalc('feature memstats');
doshow = true;
catch
doshow = false;
end
if(doshow)
ind = ind + 1;
info.panel(ind).name = 'O/S Memory';
info.panel(ind).update = @localUpdatePanelMemory;
info.panel(ind).create = @localCreatePanelMemory;
info.panel(ind).data = [];
info.panel(ind).panel = [];
end
end
% ind = ind + 1;
% info.panel(ind).name = 'Handle Graphics';
% info.panel(ind).update = @localUpdatePanelHG;
% info.panel(ind).create = @localCreatePanelHG;
% info.panel(ind).data = [];
% info.panel(ind).panel = [];
ind = ind + 1;
info.panel(ind).name = 'Java Memory';
info.panel(ind).update = @localUpdatePanelJava;
info.panel(ind).create = @localCreatePanelJava;
info.panel(ind).data = [];
info.panel(ind).panel = [];
%----------------------------------------------------------%
function localButtonCallback(obj,evd)
obj = evd.NewValue;
str = get(obj,'String');
localSetCurrentPanel(str);
%----------------------------------------------------------%
function localSetCurrentPanel(str)
info = localGetInfo;
% Only make the selected panel visible
for n = 1:length(info.panel)
panel_name = info.panel(n).name;
if strcmp(panel_name,str)
set(info.panel(n).panel,'Visible','on');
else
set(info.panel(n).panel,'Visible','off');
end
end
%----------------------------------------------------------%
function [info] = localStartTimer(info)
t = timer('TimerFcn',@localTimerCallback, 'Period', .5);
set(t,'ExecutionMode','fixedRate');
start(t);
info.timer = t;
%localSetHGCreateFcn(@localHGCreateCallback);
%----------------------------------------------------------%
function localTimerCallback(obj,evd)
localUpdateRecording('monitor.mat');
%----------------------------------------------------------%
function localUpdateRecording(filename)
info = localGetInfo;
doload = false;
doreset = info.doreset;
h = findall(0,'type','uicontrol','Tag','Pause');
if get(h,'Value')==0
for n = 1:length(info.panel)
% Update each panel
hfunc = info.panel(n).update;
info.panel(n) = feval(hfunc,info.panel(n),[],doload,doreset);
end
% Save state to file
if info.dorecord
fname = filename;
save(fname,'info','-mat');
end
end
info = localGetInfo;
info.doreset = false;
localSetInfo(info);
%----------------------------------------------------------%
function [retval] = localCreatePanelMalloc(panel_info)
ax = localMakeStripChart(panel_info.panel,'top');
pos = get(ax,'Position');
set(ax,'Position',[pos(1),.2,pos(3),.5]);
retval.ax_malloc = ax;
uicontrol('parent',panel_info.panel,...
'style','pushbutton',...
'string','''clear all''',...
'fontsize',13,...
'units','norm',...
'position',[.23 .05 .3 .09],...
'callback','clear all');
retval.line_malloc = localMakeLine(retval.ax_malloc);
if ~system_dependent('CheckMalloc')
ax = retval.ax_malloc;
axis(ax,'off');
text('Parent',ax,...
'String',...
{'To see MATLAB memory allocation information',...
'Create an O/S environment variable using ''set''',...
'set MATLAB_MEM_MGR = debug',...
'then restart MATLAB.',...
'Remove this O/S variable to restore original settings.'},...
'Units','Norm',...
'Interpreter','None',...
'Position',[.5 .5],...
'HorizontalAlignment','Center',...
'Color','k',...
'FontWeight','Bold');
end
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelMalloc(panel_info, serialize_info, doload, doreset)
if system_dependent('CheckMalloc')
MB = 1048576; % megabyte
hLine = panel_info.data.line_malloc;
hAxes = panel_info.data.ax_malloc;
if doload
ydata = serialize_info.data.data_malloc;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
dispval = system_dependent('CheckMallocMemoryUsage');
dispval = dispval/MB;
system_dependent('CheckMallocClear');
localUpdateLineData(hLine,dispval,doreset);
panel_info.data.data_malloc = get(hLine,'ydata');
str = ['Memory Allocated: ',num2str(dispval,4), ' (MB)'];
title(hAxes,str);
end
end
%----------------------------------------------------------%
function [retval] = localCreatePanelMemory(panel_info)
% Swap Space
str = 'Swap Space Consumed (red = available)';
retval.ax_swap_memory = localMakeStripChart(panel_info.panel,'top',str,'MB');
retval.line_swap_memory = localMakeLine(retval.ax_swap_memory);
retval.line_max_swap_memory = localMakeLine(retval.ax_swap_memory,'r');
% Physical Memory
str = 'Physical Memory Consumed (red = available)';
retval.ax_physical_memory = localMakeStripChart(panel_info.panel,'middle',str,'MB');
retval.line_physical_memory = localMakeLine(retval.ax_physical_memory);
retval.line_max_physical_memory = localMakeLine(retval.ax_physical_memory,'r');
% Block memory
str = 'Largest Contiguous Memory Block';
retval.ax_block_memory = localMakeStripChart(panel_info.panel,'bottom',str,'MB');
retval.line_block_memory = localMakeLine(retval.ax_block_memory);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelMemory(panel_info,serialize_info,doload,doreset)
mem_info = localGetMemoryInfo;
% Swap space
hLine = panel_info.data.line_swap_memory;
if doload
ydata = serialize_info.data.data_swap_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.PageFile.InUse;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_swap_memory = get(hLine,'ydata');
end
hLine = panel_info.data.line_max_swap_memory;
hAxes = panel_info.data.ax_swap_memory;
if doload
ydata = serialize_info.data.data_max_swap_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val2 = mem_info.PageFile.Total;
localUpdateLineData(hLine,val2,doreset);
panel_info.data.data_max_swap_memory = get(hLine,'ydata');
title(hAxes,{'Page File',['Consumed: ', num2str(val),'(MB) Available: ',num2str(val2),'(MB)']});
end
% Physical Memory
hLine = panel_info.data.line_physical_memory;
if doload
ydata = serialize_info.data.data_physical_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.PhysicalMemory.InUse;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_physical_memory = get(hLine,'ydata');
end
hLine = panel_info.data.line_max_physical_memory;
hAxes = panel_info.data.ax_physical_memory;
if doload
ydata = serialize_info.data.data_max_physical_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val2 = mem_info.PhysicalMemory.Total;
localUpdateLineData(hLine,val2,doreset);
panel_info.data.data_max_physical_memory = get(hLine,'ydata');
title(hAxes,{'Physical Memory',['Consumed: ', num2str(val),' (MB) Available: ',num2str(val2),' (MB)']});
end
% Memory Block
hLine = panel_info.data.line_block_memory;
hAxes = panel_info.data.ax_block_memory;
if doload
ydata = serialize_info.data.data_block_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.LargestFreeBlock;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_block_memory = get(hLine,'ydata');
title(hAxes,['Largest Contiguous Memory Block: ',num2str(val),' (MB)']);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelJava(panel_info)
ax = localMakeStripChart(panel_info.panel,...
'top','Java Memory Consumed (red = available)','MB');
pos = get(ax,'Position');
set(ax,'Position',[pos(1),.2,pos(3),.5]);
uicontrol('parent',panel_info.panel,...
'style','pushbutton',...
'string','Garbage Collect',...
'fontsize',13,...
'units','norm',...
'position',[.23 .05 .3 .09],...
'callback','java.lang.System.gc');
retval.ax_java_memory = ax;
% Create lines
retval.line_java_max_memory = localMakeLine(retval.ax_java_memory,'r');
set(retval.line_java_max_memory,'LineStyle',':');
retval.line_java_total_memory = localMakeLine(retval.ax_java_memory,'r');
retval.line_java_used_memory = localMakeLine(retval.ax_java_memory);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelJava(panel_info, serialize_info, doload, doreset)
[free_mem,total_mem,max_mem] = localGetJavaMemory;
consumed = total_mem-free_mem;
% used memory
hLine = panel_info.data.line_java_used_memory;
if doload
ydata = serialize_info.data.data_java_used_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,consumed,doreset);
panel_info.data.data_java_used_memory = get(hLine,'ydata');
end
% total memory
hLine = panel_info.data.line_java_total_memory;
hAxes = panel_info.data.ax_java_memory;
if doload
ydata = serialize_info.data.data_java_total_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,total_mem,doreset);
panel_info.data.data_java_total_memory = get(hLine,'ydata');
title(hAxes,{'Java Memory, Garbage collection will fluctuate',...
['Total: ',num2str(total_mem,3),' (MB), Maximum: ',num2str(max_mem,3),' (MB)'],...
['Consumed: ',num2str(consumed,3),' (MB) ']});
end
% max memory
hLine = panel_info.data.line_java_max_memory;
if doload
ydata = serialize_info.data.data_java_max_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,max_mem,doreset);
panel_info.data.data_java_max_memory = get(hLine,'ydata');
end
% %----------------------------------------------------------%
% function [retval] = localCreatePanelHG(panel_info)
%
% retval.ax_hg_objects = localMakeStripChart(panel_info.panel,'top','Number of HG Objects in Memory');
% retval.line_hg_objects = localMakeLine(retval.ax_hg_objects);
%
% retval.ax_hg_created_objects = localMakeStripChart(panel_info.panel,'middle');
% retval.line_hg_created_objects = localMakeLine(retval.ax_hg_created_objects);
%
% %----------------------------------------------------------%
% function [panel_info] = localUpdatePanelHG(panel_info, serialize_info, doload,doreset)
%
% info = localGetInfo;
% hgmem = info.HGObjectInMemory;
% ind = find(ishandle(hgmem)~=true);
% hgmem(ind) = [];
% info.HGObjectInMemory = hgmem;
%
% hLine = panel_info.data.line_hg_objects;
% hAxes = panel_info.data.ax_hg_objects;
% if doload
% ydata = serialize_info.data.data_hg_objects;
% xdata = 1:length(ydata);
% set(hLine,'xdata',xdata,'ydata',ydata);
% else
% val = length(findall(0));
% localUpdateLineData(hLine,val,doreset);
% panel_info.data.data_hg_objects = get(hLine,'YData');
% title(hAxes,['Number of HG Objects in Memory: ',num2str(val)]);
% end
%
% hLine = panel_info.data.line_hg_created_objects;
% hAxes = panel_info.data.ax_hg_created_objects;
% if doload
% ydata = serialize_info.data.data_hg_created_objects;
% xdata = 1:length(ydata);
% set(hLine,'xdata',xdata,'ydata',ydata);
% else
% val = info.HGObjectCreatedCount;
% localUpdateLineData(hLine,val,doreset);
% panel_info.data.data_hg_created_objects = get(hLine,'YData');
% title(hAxes,...
% { ['HG Objects Created per Unit Time: ', num2str(val)],...
% 'Performance sensitive plotting code should',...
% 'resuse and not create objects during animations.'});
% end
% info.HGObjectCreatedCount = 0;
% localSetInfo(info);
%----------------------------------------------------------%
function [retval] = localCreatePanelGeneral(panel_info)
retval.ax_mfiles = localMakeStripChart(panel_info.panel,'top');
retval.line_mfiles = localMakeLine(retval.ax_mfiles);
retval.ax_dbstack = localMakeStripChart(panel_info.panel,'middle');
retval.line_dbstack = localMakeLine(retval.ax_dbstack);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelGeneral(panel_info, serialize_info, doload, doreset)
hLine = panel_info.data.line_mfiles;
hAxes = panel_info.data.ax_mfiles;
if doload
ydata = serialize_info.data.data_mfiles;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
[val] = inmem;
val = length(val);
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_mfiles = get(hLine,'ydata');
title(hAxes,['Number of M-Files in Memory (''inmem''): ',num2str(val)]);
end
hLine = panel_info.data.line_dbstack;
hAxes = panel_info.data.ax_dbstack;
if doload
ydata = serialize_info.data.data_dbstack;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = length(dbstack);
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_dbstack = get(hLine,'ydata');
title(hAxes,['M-File Call-Stack Size (''dbstack''): ',num2str(val),' ']);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelObjects(panel_info)
retval.ax_objects = localMakeStripChart(panel_info.panel,'top','Number of Oops Objects in Memory');
retval.line_objects = localMakeLine(retval.ax_objects);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelObjects(panel_info, serialize_info, doload,doreset)
hLine = panel_info.data.line_objects;
hAxes = panel_info.data.ax_objects;
if doload
ydata = serialize_info.data.data_objects;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
[val] = localGetOopsCount;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_objects = get(hLine,'ydata');
title(hAxes,['Number of Oops Objects in Memory: ',num2str(val)]);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelAWT(panel_info)
retval.ax_java_awt = localMakeStripChart(panel_info.panel,'top','Number of Events in the AWT Queue');
retval.line_java_awt_events = localMakeLine(retval.ax_java_awt);
retval.ax_java_paint = localMakeStripChart(panel_info.panel,'middle','Number of Paint Events in the AWT Queue');
retval.line_java_paint_events = localMakeLine(retval.ax_java_paint);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelAWT(panel_info, serialize_info, doload, doreset)
h = MonitorEventQueue.getInstance;
val = h.getTotalEventCount;
hLine = panel_info.data.line_java_awt_events;
if doload
ydata = serialize_info.data.data_java_awt_events;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,val,doreset);
panel_info.data.data.data_java_awt_events = get(hLine,'ydata');
end
val = h.getPaintEventCount;
hLine = panel_info.data.line_java_paint_events;
if doload
ydata = serialize_info.data.data_java_paint_events;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,val,doreset);
panel_info.data.data.data_java_paint_events = get(hLine,'ydata');
end
%----------------------------------------------------------%
function [val] = localGetCustom
% val: numeric scalar
% Change this to output scalar value of interest
val = rand(1,1);
% %----------------------------------------------------------%
% function localHGCreateCallback(obj,evd)
% % Callback fires when HG object is created
%
% info = localGetInfo;
% count = info.HGObjectCreatedCount;
% info.HGObjectCreatedCount = count + 1;
%
% list = info.HGObjectInMemory;
% info.HGObjectInMemory = [list,obj];
% localSetInfo(info);
%-----------------------------------------------------
function [ax] = localMakeStripChart(frame,loc,titl,ylab)
pos = [.14 .3 .5 .15];
gray = [.4 .4 .4];
switch(loc)
case 'bottom'
pos(2) = .09;
case 'middle'
pos(2) = .35;
case 'top'
pos(2) = .66;
end
ax = axes('Parent',frame,'units','norm',...
'position',pos,'XLim',[1 200],...
'YScale','linear','XTickLabel','','XMinorGrid','off','XGrid','on',...
'Color','w','XColor',[.4 .4 .4],'YColor',[.4 .4 .4],'box','on');
if nargin>2
title(ax,titl,'FontSize',8);
end
set(ax,'fontsize',8);
if nargin>3
ylabel(ax,ylab);
end
%----------------------------------------------------------%
function [hLine] = localMakeLine(ax,color)
if nargin==1
color= 'b';
end
hLine = line('xdata',nan,'ydata',nan,'Parent',ax,'Color',color,'LineWidth',1.5);
%----------------------------------------------------------%
function localReset(obj,evd)
% reset line data
info = localGetInfo;
info.doreset = true;
localSetInfo(info);
%----------------------------------------------------------%
function localUpdateLineData(hLine,newval,doreset)
if ~ishandle(hLine)
return;
end
if doreset
set(hLine,'xdata',nan,'ydata',nan);
return;
end
MAX = 200;
ydata = get(hLine,'ydata');
% Remove startup noise
if length(ydata)<2
newval = nan;
end
ydata = [ydata,newval];
% Clip out front of data
len = length(ydata);
if len>MAX
ydata = ydata((len-MAX+1):MAX+1);
end
xdata = (MAX-length(ydata)+1):1:MAX;
set(hLine,'xdata',xdata,'ydata',ydata,'Visible','on');
%----------------------------------------------------------%
function localShutDown(obj,evd)
info = localGetInfo;
try,
localStop(info);
end
localSetInfo([]);
%----------------------------------------------------------%
function localStop(info);
try,
t = info.timer;
stop(t);
delete(t);
end
%----------------------------------------------------------%
function val = localGetOopsCount
% Get number of oops objects in memory
val = 0;
s = objectdirectory;
if ~isempty(s)
c = struct2cell(s);
count = 0;
for n = 1:length(c)
count = c{n} + count;
end
val = count;
end
%----------------------------------------------------------%
function val = localGetBaseWorkspaceSize
val = 0;
ret = evalin('base','whos');
for n = 1:length(ret)
val = ret(n).bytes + val;
end
val = val/1e6;
% %----------------------------------------------------------%
% function localSetHGCreateFcn(val)
% Commenting out the code below. This is causing problems
% if a user saves a fig file while the memory tool is up.
% set(0,'DefaultFigureCreateFcn', val);
% set(0,'DefaultAxesCreateFcn', val);
% set(0,'DefaultUIPanelCreateFcn', val);
% set(0,'DefaultPatchCreateFcn', val);
% set(0,'DefaultRectangleCreateFcn', val);
% set(0,'DefaultSurfaceCreateFcn', val);
% set(0,'DefaultImageCreateFcn', val);
% set(0,'DefaultTextCreateFcn', val);
% set(0,'DefaultLineCreateFcn', val);
% set(0,'DefaultUIControlCreateFcn', val);
% set(0,'DefaultUIMenuCreateFcn', val);
%----------------------------------------------------------%
function localUpdateAxesLimits(hAxes,hLine)
min_data = min(get(hLine,'ydata'));
max_data = max(get(hLine,'ydata'));
if max_data<10
newlim = [min_data 10];
else
delta = abs(max_data);
newlim = [min_data - .1*delta, max_data + .1*delta];
end
set(hAxes,'YLim',newlim);
%----------------------------------------------------------%
function [names] = localGetClassLoadingNames
names = [];
try
h = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
cloader = h.getCustomClassLoader;
if ~isempty(cloader)
names = char(cloader.debugGetClassNames);
end
end
%----------------------------------------------------------%
function [val] = localGetClassLoadingSize
val = 0;
try
h = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
cloader = h.getCustomClassLoader;
if ~isempty(cloader)
val = cloader.debugGetCacheSize;
end
end
% hack to keep line visible on log plot
if (val<1)
val = 1;
end
%----------------------------------------------------------%
function [free_memory,total_memory, max_memory] = localGetJavaMemory
MB = 1048576; % megabyte
free_memory = java.lang.Runtime.getRuntime.freeMemory/MB;
total_memory = java.lang.Runtime.getRuntime.totalMemory/MB;
max_memory = java.lang.Runtime.getRuntime.maxMemory/MB;
%-----------------------------------------------------
function retval = localGetIconPath
retval = [];
persistent iconpath;
if isempty(iconpath)
[iconpath,filename,ext] = fileparts(which(mfilename));
iconpath = fullfile(iconpath,'private');
end
retval = iconpath;
%-----------------------------------------------------
function info = localGetMemoryInfo
% Big hack here, parse output of memstats since there
% are no output variables.
str = evalc('feature memstats');
ind = findstr(str,'MB');
LEN = 20;
% Parse output
% Physical Memory (RAM):
% In Use: 483 MB (1e305000)
% Free: 539 MB (21ba3000)
% Total: 1022 MB (3fea8000)
retval = str((ind(1)-2):-1:ind(1)-LEN);
info.PhysicalMemory.InUse = str2num(fliplr(retval));
%retval = str((ind(2)-2):-1:ind(2)-LEN);
%info.PhysicalMemory.Free = str2num(fliplr(retval));
retval = str((ind(3)-2):-1:ind(3)-LEN);
info.PhysicalMemory.Total = str2num(fliplr(retval));
% Page File (Swap space):
% In Use: 571 MB (23b57000)
% Free: 1890 MB (76220000)
% Total: 2461 MB (99d77000)
retval = str((ind(4)-2):-1:ind(4)-LEN);
info.PageFile.InUse = str2num(fliplr(retval));
retval = str((ind(5)-2):-1:ind(5)-LEN);
info.PageFile.Free = str2num(fliplr(retval));
retval = str((ind(6)-2):-1:ind(6)-LEN);
info.PageFile.Total = str2num(fliplr(retval));
% Virtual Memory (Address Space):
% In Use: 536 MB (21851000)
% Free: 1511 MB (5e78f000)
% Total: 2047 MB (7ffe0000)
%retval = str((ind(7)-2):-1:ind(7)-LEN);
%info.VirtualMemory.InUse = str2num(fliplr(retval));
%retval = str((ind(8)-2):-1:ind(8)-LEN);
%info.VirtualMemory.Free = str2num(fliplr(retval));
%retval = str((ind(9)-2):-1:ind(9)-LEN);
%info.VirtualMemory.Total = str2num(fliplr(retval));
% Largest Contiguous Free Blocks:
% 1. [at 25d20000] 859 MB (35b40000)
retval = str((ind(10)-2):-1:ind(10)-LEN);
info.LargestFreeBlock = str2num(fliplr(retval));
%----------------------------------------------------------%
function info = localGetInfo
info = getappdata(0,'MonitorMATLAB');
if isempty(info)
info = struct;
info.figure = [];
%info.HGObjectCreatedCount = [];
%info.HGObjectInMemory = [];
info.dorecord = false;
info.doreset = false;
end
%----------------------------------------------------------%
function localSetInfo(info)
setappdata(0,'MonitorMATLAB',info);
|
github
|
ma-xu/2PTWSVM-master
|
monitormatlab.m
|
.m
|
2PTWSVM-master/NEW_GEPSVM/monitormatlab.m
| 30,148 |
utf_8
|
702d3e62f38bce4f5547affd49f0de96
|
function monitormatlab(action)
%MONITORMATLAB Displays runtime diagnostic information
% This task manager like tool displays real time memory
% state of MATLAB, HG, and Java using time based strip charts.
%
% The following information is displayed:
% * Memory allocated by MATLAB
% * Memory allocated by Java
% * Memory allocted by the O/S
% * Number of MFiles in MATLAB memory
% * Size of m-file parsing stack
%
% To see real time MATLAB memory allocation, start MATLAB with
% the O/S environment flag "MATLAB_MEM_MGR" set to a "debug"
% as in: set MATLAB_MEM_MGR = debug.
%
% Example:
%
% monitormatlab
% bench
if str2num(version('-release'))<14
error('MATLAB version 14sp2 or later required')
end
if nargin==0
action = 'start';
end
if strcmp(action,'start')
info = localStart;
elseif strcmp(action,'stop')
localStop;
else
error('Invalid input')
end
%----------------------------------------------------------%
function [info] = localStart
drawnow;
[info] = localShowUI;
drawnow;
localSetInfo(info);
localStartPause;
[info] = localStartTimer(info);
localSetInfo(info);
drawnow;
localStopPause;
%----------------------------------------------------------%
function [info] = localShowUI
% Singleton: Only create new UI if current one is stale or empty
info = localGetInfo;
if isempty(info.figure) || ~ishandle(info.figure);
[info] = localRegisterPanels(info);
[info] = localCreateUI(info);
end
%----------------------------------------------------------%
function localOpenRecording(obj,evd)
localStartPause;
info = localGetInfo;
doload = true;
doreset = false;
[filename, pathname] = uigetfile('monitor.mat', 'Open mat file');
if filename ~= 0
s = load(fullfile(pathname,filename),'-mat');
% Loop through and set view
for n = 1:length(info.panel)
% Update each panel
hfunc = info.panel(n).update;
info.panel(n) = feval(hfunc,info.panel(n),s.info.panel(n),doload,doreset);
end
else
localStopPause;
end
localSetInfo(info);
%----------------------------------------------------------%
function localStartPause
h = findall(0,'type','uicontrol','Tag','Pause');
set(h,'Value',1);
%----------------------------------------------------------%
function localStopPause
h = findall(0,'type','uicontrol','Tag','Pause');
set(h,'Value',0);
%----------------------------------------------------------%
function localSaveRecording(obj,evd)
localStartPause
[filename, pathname] = uiputfile('monitor.mat', 'Open mat file');
if filename ~= 0
info = localGetInfo;
info.dorecord = true;
localSetInfo(info);
localUpdateRecording(fullfile(pathname,filename));
end
info = localGetInfo;
info.dorecord = false;
localSetInfo(info);
localStopPause;
%----------------------------------------------------------%
function localRecord(obj,evd)
info = localGetInfo;
p = get(obj,'parent');
ubegin = findall(p,'tag','BeginRecording');
ustop = findall(p,'tag','StopRecording');
if isequal(obj,ustop)
info.dorecord = false;
set(ubegin,'Enable','on');
set(ustop,'Enable','off');
elseif isequal(obj,ubegin)
info.dorecord = true;
set(ubegin,'Enable','off');
set(ustop,'Enable','on');
end
localSetInfo(info);
%----------------------------------------------------------%
function [info] = localCreateUI(info)
fig = figure('resize','off','handlevis','off','toolbar','none',...
'name','MATLAB Monitoring Tool','NumberTitle','off','units','pixels',...
'pos',[100 100 500 340],'DeleteFcn',@localShutDown);
info.figure = fig;
% Create figure menus
delete(findall(fig,'type','uimenu'));
% File Menu
u = uimenu('Parent',fig,'Label','File');
uimenu('Parent',u,'Tag','Load','Label','Open...',...
'Callback',@localOpenRecording);
uimenu('Parent',u,'Tag','Load','Label','Save',...
'Callback',@localSaveRecording);
% Tools menu
u = uimenu('Parent',fig,'Label','Tools');
uimenu('Parent',u,'Tag','BeginRecording',...
'Callback',@localRecord,...
'Label','Begin Recording to ''monitor.mat'' File');
uimenu('Callback',@localRecord,...
'Parent',u,'Tag','StopRecording',...
'Label','Stop Recording','Enable','off');
info.frame_center = uipanel('title','','titleposition','centertop',...
'parent',fig,'units','norm','pos',[0 0 1 1 ]);
info.frame_left = uibuttongroup('parent',info.frame_center,...
'units','norm',...
'pos',[0 0 .3 1 ],...
'BackgroundColor',[.4 .4 .4],...
'SelectionChangeFcn',@localButtonCallback);
uicontrol('style','togglebutton','Parent',info.frame_center,...
'units','norm','pos',[.03 .02 .2 .07],'string','Pause',...
'Tag','Pause');
uicontrol('style','pushbutton','Parent',info.frame_center,...
'units','norm','pos',[.03 .12 .2 .07],'string','Reset',...
'Tag','Reset','Callback',@localReset);
% Toggle button properties
props.style = 'togglebutton';
props.parent = info.frame_left;
props.units = 'norm';
props.position = [.1 1 .66 .07];
% Create each panel and button
for n = 1:length(info.panel)
panel_name = info.panel(n).name;
% Create panel
h = uipanel('parent',info.frame_center,...
'units','norm','pos',[.25 0 1 1],'Visible','off');
if (n==1)
set(h,'Visible','on');
end
info.panel(n).panel = h;
% Add a button for each panel
props.string = panel_name;
props.position(2) = props.position(2) - .1;
u(n) = uicontrol(props);
% Add panel contents
hfunc = info.panel(n).create;
info.panel(n).data = feval(hfunc,info.panel(n));
end
% Set first button to on by default
if length(u)>0
set(u(1),'Value',1);
end
%----------------------------------------------------------%
function [info] = localRegisterPanels(info)
ind = 0;
ind = ind + 1;
info.panel(ind).name = 'General';
info.panel(ind).update = @localUpdatePanelGeneral;
info.panel(ind).create = @localCreatePanelGeneral;
info.panel(ind).data = [];
info.panel(ind).panel = [];
ind = ind + 1;
info.panel(ind).name = 'MATLAB Memory';
info.panel(ind).update = @localUpdatePanelMalloc;
info.panel(ind).create = @localCreatePanelMalloc;
info.panel(ind).data = [];
info.panel(ind).panel = [];
% Don't show this panel on unix
if ispc
try
evalc('feature memstats');
doshow = true;
catch
doshow = false;
end
if(doshow)
ind = ind + 1;
info.panel(ind).name = 'O/S Memory';
info.panel(ind).update = @localUpdatePanelMemory;
info.panel(ind).create = @localCreatePanelMemory;
info.panel(ind).data = [];
info.panel(ind).panel = [];
end
end
% ind = ind + 1;
% info.panel(ind).name = 'Handle Graphics';
% info.panel(ind).update = @localUpdatePanelHG;
% info.panel(ind).create = @localCreatePanelHG;
% info.panel(ind).data = [];
% info.panel(ind).panel = [];
ind = ind + 1;
info.panel(ind).name = 'Java Memory';
info.panel(ind).update = @localUpdatePanelJava;
info.panel(ind).create = @localCreatePanelJava;
info.panel(ind).data = [];
info.panel(ind).panel = [];
%----------------------------------------------------------%
function localButtonCallback(obj,evd)
obj = evd.NewValue;
str = get(obj,'String');
localSetCurrentPanel(str);
%----------------------------------------------------------%
function localSetCurrentPanel(str)
info = localGetInfo;
% Only make the selected panel visible
for n = 1:length(info.panel)
panel_name = info.panel(n).name;
if strcmp(panel_name,str)
set(info.panel(n).panel,'Visible','on');
else
set(info.panel(n).panel,'Visible','off');
end
end
%----------------------------------------------------------%
function [info] = localStartTimer(info)
t = timer('TimerFcn',@localTimerCallback, 'Period', .5);
set(t,'ExecutionMode','fixedRate');
start(t);
info.timer = t;
%localSetHGCreateFcn(@localHGCreateCallback);
%----------------------------------------------------------%
function localTimerCallback(obj,evd)
localUpdateRecording('monitor.mat');
%----------------------------------------------------------%
function localUpdateRecording(filename)
info = localGetInfo;
doload = false;
doreset = info.doreset;
h = findall(0,'type','uicontrol','Tag','Pause');
if get(h,'Value')==0
for n = 1:length(info.panel)
% Update each panel
hfunc = info.panel(n).update;
info.panel(n) = feval(hfunc,info.panel(n),[],doload,doreset);
end
% Save state to file
if info.dorecord
fname = filename;
save(fname,'info','-mat');
end
end
info = localGetInfo;
info.doreset = false;
localSetInfo(info);
%----------------------------------------------------------%
function [retval] = localCreatePanelMalloc(panel_info)
ax = localMakeStripChart(panel_info.panel,'top');
pos = get(ax,'Position');
set(ax,'Position',[pos(1),.2,pos(3),.5]);
retval.ax_malloc = ax;
uicontrol('parent',panel_info.panel,...
'style','pushbutton',...
'string','''clear all''',...
'fontsize',13,...
'units','norm',...
'position',[.23 .05 .3 .09],...
'callback','clear all');
retval.line_malloc = localMakeLine(retval.ax_malloc);
if ~system_dependent('CheckMalloc')
ax = retval.ax_malloc;
axis(ax,'off');
text('Parent',ax,...
'String',...
{'To see MATLAB memory allocation information',...
'Create an O/S environment variable using ''set''',...
'set MATLAB_MEM_MGR = debug',...
'then restart MATLAB.',...
'Remove this O/S variable to restore original settings.'},...
'Units','Norm',...
'Interpreter','None',...
'Position',[.5 .5],...
'HorizontalAlignment','Center',...
'Color','k',...
'FontWeight','Bold');
end
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelMalloc(panel_info, serialize_info, doload, doreset)
if system_dependent('CheckMalloc')
MB = 1048576; % megabyte
hLine = panel_info.data.line_malloc;
hAxes = panel_info.data.ax_malloc;
if doload
ydata = serialize_info.data.data_malloc;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
dispval = system_dependent('CheckMallocMemoryUsage');
dispval = dispval/MB;
system_dependent('CheckMallocClear');
localUpdateLineData(hLine,dispval,doreset);
panel_info.data.data_malloc = get(hLine,'ydata');
str = ['Memory Allocated: ',num2str(dispval,4), ' (MB)'];
title(hAxes,str);
end
end
%----------------------------------------------------------%
function [retval] = localCreatePanelMemory(panel_info)
% Swap Space
str = 'Swap Space Consumed (red = available)';
retval.ax_swap_memory = localMakeStripChart(panel_info.panel,'top',str,'MB');
retval.line_swap_memory = localMakeLine(retval.ax_swap_memory);
retval.line_max_swap_memory = localMakeLine(retval.ax_swap_memory,'r');
% Physical Memory
str = 'Physical Memory Consumed (red = available)';
retval.ax_physical_memory = localMakeStripChart(panel_info.panel,'middle',str,'MB');
retval.line_physical_memory = localMakeLine(retval.ax_physical_memory);
retval.line_max_physical_memory = localMakeLine(retval.ax_physical_memory,'r');
% Block memory
str = 'Largest Contiguous Memory Block';
retval.ax_block_memory = localMakeStripChart(panel_info.panel,'bottom',str,'MB');
retval.line_block_memory = localMakeLine(retval.ax_block_memory);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelMemory(panel_info,serialize_info,doload,doreset)
mem_info = localGetMemoryInfo;
% Swap space
hLine = panel_info.data.line_swap_memory;
if doload
ydata = serialize_info.data.data_swap_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.PageFile.InUse;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_swap_memory = get(hLine,'ydata');
end
hLine = panel_info.data.line_max_swap_memory;
hAxes = panel_info.data.ax_swap_memory;
if doload
ydata = serialize_info.data.data_max_swap_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val2 = mem_info.PageFile.Total;
localUpdateLineData(hLine,val2,doreset);
panel_info.data.data_max_swap_memory = get(hLine,'ydata');
title(hAxes,{'Page File',['Consumed: ', num2str(val),'(MB) Available: ',num2str(val2),'(MB)']});
end
% Physical Memory
hLine = panel_info.data.line_physical_memory;
if doload
ydata = serialize_info.data.data_physical_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.PhysicalMemory.InUse;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_physical_memory = get(hLine,'ydata');
end
hLine = panel_info.data.line_max_physical_memory;
hAxes = panel_info.data.ax_physical_memory;
if doload
ydata = serialize_info.data.data_max_physical_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val2 = mem_info.PhysicalMemory.Total;
localUpdateLineData(hLine,val2,doreset);
panel_info.data.data_max_physical_memory = get(hLine,'ydata');
title(hAxes,{'Physical Memory',['Consumed: ', num2str(val),' (MB) Available: ',num2str(val2),' (MB)']});
end
% Memory Block
hLine = panel_info.data.line_block_memory;
hAxes = panel_info.data.ax_block_memory;
if doload
ydata = serialize_info.data.data_block_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = mem_info.LargestFreeBlock;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_block_memory = get(hLine,'ydata');
title(hAxes,['Largest Contiguous Memory Block: ',num2str(val),' (MB)']);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelJava(panel_info)
ax = localMakeStripChart(panel_info.panel,...
'top','Java Memory Consumed (red = available)','MB');
pos = get(ax,'Position');
set(ax,'Position',[pos(1),.2,pos(3),.5]);
uicontrol('parent',panel_info.panel,...
'style','pushbutton',...
'string','Garbage Collect',...
'fontsize',13,...
'units','norm',...
'position',[.23 .05 .3 .09],...
'callback','java.lang.System.gc');
retval.ax_java_memory = ax;
% Create lines
retval.line_java_max_memory = localMakeLine(retval.ax_java_memory,'r');
set(retval.line_java_max_memory,'LineStyle',':');
retval.line_java_total_memory = localMakeLine(retval.ax_java_memory,'r');
retval.line_java_used_memory = localMakeLine(retval.ax_java_memory);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelJava(panel_info, serialize_info, doload, doreset)
[free_mem,total_mem,max_mem] = localGetJavaMemory;
consumed = total_mem-free_mem;
% used memory
hLine = panel_info.data.line_java_used_memory;
if doload
ydata = serialize_info.data.data_java_used_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,consumed,doreset);
panel_info.data.data_java_used_memory = get(hLine,'ydata');
end
% total memory
hLine = panel_info.data.line_java_total_memory;
hAxes = panel_info.data.ax_java_memory;
if doload
ydata = serialize_info.data.data_java_total_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,total_mem,doreset);
panel_info.data.data_java_total_memory = get(hLine,'ydata');
title(hAxes,{'Java Memory, Garbage collection will fluctuate',...
['Total: ',num2str(total_mem,3),' (MB), Maximum: ',num2str(max_mem,3),' (MB)'],...
['Consumed: ',num2str(consumed,3),' (MB) ']});
end
% max memory
hLine = panel_info.data.line_java_max_memory;
if doload
ydata = serialize_info.data.data_java_max_memory;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,max_mem,doreset);
panel_info.data.data_java_max_memory = get(hLine,'ydata');
end
% %----------------------------------------------------------%
% function [retval] = localCreatePanelHG(panel_info)
%
% retval.ax_hg_objects = localMakeStripChart(panel_info.panel,'top','Number of HG Objects in Memory');
% retval.line_hg_objects = localMakeLine(retval.ax_hg_objects);
%
% retval.ax_hg_created_objects = localMakeStripChart(panel_info.panel,'middle');
% retval.line_hg_created_objects = localMakeLine(retval.ax_hg_created_objects);
%
% %----------------------------------------------------------%
% function [panel_info] = localUpdatePanelHG(panel_info, serialize_info, doload,doreset)
%
% info = localGetInfo;
% hgmem = info.HGObjectInMemory;
% ind = find(ishandle(hgmem)~=true);
% hgmem(ind) = [];
% info.HGObjectInMemory = hgmem;
%
% hLine = panel_info.data.line_hg_objects;
% hAxes = panel_info.data.ax_hg_objects;
% if doload
% ydata = serialize_info.data.data_hg_objects;
% xdata = 1:length(ydata);
% set(hLine,'xdata',xdata,'ydata',ydata);
% else
% val = length(findall(0));
% localUpdateLineData(hLine,val,doreset);
% panel_info.data.data_hg_objects = get(hLine,'YData');
% title(hAxes,['Number of HG Objects in Memory: ',num2str(val)]);
% end
%
% hLine = panel_info.data.line_hg_created_objects;
% hAxes = panel_info.data.ax_hg_created_objects;
% if doload
% ydata = serialize_info.data.data_hg_created_objects;
% xdata = 1:length(ydata);
% set(hLine,'xdata',xdata,'ydata',ydata);
% else
% val = info.HGObjectCreatedCount;
% localUpdateLineData(hLine,val,doreset);
% panel_info.data.data_hg_created_objects = get(hLine,'YData');
% title(hAxes,...
% { ['HG Objects Created per Unit Time: ', num2str(val)],...
% 'Performance sensitive plotting code should',...
% 'resuse and not create objects during animations.'});
% end
% info.HGObjectCreatedCount = 0;
% localSetInfo(info);
%----------------------------------------------------------%
function [retval] = localCreatePanelGeneral(panel_info)
retval.ax_mfiles = localMakeStripChart(panel_info.panel,'top');
retval.line_mfiles = localMakeLine(retval.ax_mfiles);
retval.ax_dbstack = localMakeStripChart(panel_info.panel,'middle');
retval.line_dbstack = localMakeLine(retval.ax_dbstack);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelGeneral(panel_info, serialize_info, doload, doreset)
hLine = panel_info.data.line_mfiles;
hAxes = panel_info.data.ax_mfiles;
if doload
ydata = serialize_info.data.data_mfiles;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
[val] = inmem;
val = length(val);
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_mfiles = get(hLine,'ydata');
title(hAxes,['Number of M-Files in Memory (''inmem''): ',num2str(val)]);
end
hLine = panel_info.data.line_dbstack;
hAxes = panel_info.data.ax_dbstack;
if doload
ydata = serialize_info.data.data_dbstack;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
val = length(dbstack);
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_dbstack = get(hLine,'ydata');
title(hAxes,['M-File Call-Stack Size (''dbstack''): ',num2str(val),' ']);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelObjects(panel_info)
retval.ax_objects = localMakeStripChart(panel_info.panel,'top','Number of Oops Objects in Memory');
retval.line_objects = localMakeLine(retval.ax_objects);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelObjects(panel_info, serialize_info, doload,doreset)
hLine = panel_info.data.line_objects;
hAxes = panel_info.data.ax_objects;
if doload
ydata = serialize_info.data.data_objects;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
[val] = localGetOopsCount;
localUpdateLineData(hLine,val,doreset);
panel_info.data.data_objects = get(hLine,'ydata');
title(hAxes,['Number of Oops Objects in Memory: ',num2str(val)]);
end
%----------------------------------------------------------%
function [retval] = localCreatePanelAWT(panel_info)
retval.ax_java_awt = localMakeStripChart(panel_info.panel,'top','Number of Events in the AWT Queue');
retval.line_java_awt_events = localMakeLine(retval.ax_java_awt);
retval.ax_java_paint = localMakeStripChart(panel_info.panel,'middle','Number of Paint Events in the AWT Queue');
retval.line_java_paint_events = localMakeLine(retval.ax_java_paint);
%----------------------------------------------------------%
function [panel_info] = localUpdatePanelAWT(panel_info, serialize_info, doload, doreset)
h = MonitorEventQueue.getInstance;
val = h.getTotalEventCount;
hLine = panel_info.data.line_java_awt_events;
if doload
ydata = serialize_info.data.data_java_awt_events;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,val,doreset);
panel_info.data.data.data_java_awt_events = get(hLine,'ydata');
end
val = h.getPaintEventCount;
hLine = panel_info.data.line_java_paint_events;
if doload
ydata = serialize_info.data.data_java_paint_events;
xdata = 1:length(ydata);
set(hLine,'xdata',xdata,'ydata',ydata);
else
localUpdateLineData(hLine,val,doreset);
panel_info.data.data.data_java_paint_events = get(hLine,'ydata');
end
%----------------------------------------------------------%
function [val] = localGetCustom
% val: numeric scalar
% Change this to output scalar value of interest
val = rand(1,1);
% %----------------------------------------------------------%
% function localHGCreateCallback(obj,evd)
% % Callback fires when HG object is created
%
% info = localGetInfo;
% count = info.HGObjectCreatedCount;
% info.HGObjectCreatedCount = count + 1;
%
% list = info.HGObjectInMemory;
% info.HGObjectInMemory = [list,obj];
% localSetInfo(info);
%-----------------------------------------------------
function [ax] = localMakeStripChart(frame,loc,titl,ylab)
pos = [.14 .3 .5 .15];
gray = [.4 .4 .4];
switch(loc)
case 'bottom'
pos(2) = .09;
case 'middle'
pos(2) = .35;
case 'top'
pos(2) = .66;
end
ax = axes('Parent',frame,'units','norm',...
'position',pos,'XLim',[1 200],...
'YScale','linear','XTickLabel','','XMinorGrid','off','XGrid','on',...
'Color','w','XColor',[.4 .4 .4],'YColor',[.4 .4 .4],'box','on');
if nargin>2
title(ax,titl,'FontSize',8);
end
set(ax,'fontsize',8);
if nargin>3
ylabel(ax,ylab);
end
%----------------------------------------------------------%
function [hLine] = localMakeLine(ax,color)
if nargin==1
color= 'b';
end
hLine = line('xdata',nan,'ydata',nan,'Parent',ax,'Color',color,'LineWidth',1.5);
%----------------------------------------------------------%
function localReset(obj,evd)
% reset line data
info = localGetInfo;
info.doreset = true;
localSetInfo(info);
%----------------------------------------------------------%
function localUpdateLineData(hLine,newval,doreset)
if ~ishandle(hLine)
return;
end
if doreset
set(hLine,'xdata',nan,'ydata',nan);
return;
end
MAX = 200;
ydata = get(hLine,'ydata');
% Remove startup noise
if length(ydata)<2
newval = nan;
end
ydata = [ydata,newval];
% Clip out front of data
len = length(ydata);
if len>MAX
ydata = ydata((len-MAX+1):MAX+1);
end
xdata = (MAX-length(ydata)+1):1:MAX;
set(hLine,'xdata',xdata,'ydata',ydata,'Visible','on');
%----------------------------------------------------------%
function localShutDown(obj,evd)
info = localGetInfo;
try,
localStop(info);
end
localSetInfo([]);
%----------------------------------------------------------%
function localStop(info);
try,
t = info.timer;
stop(t);
delete(t);
end
%----------------------------------------------------------%
function val = localGetOopsCount
% Get number of oops objects in memory
val = 0;
s = objectdirectory;
if ~isempty(s)
c = struct2cell(s);
count = 0;
for n = 1:length(c)
count = c{n} + count;
end
val = count;
end
%----------------------------------------------------------%
function val = localGetBaseWorkspaceSize
val = 0;
ret = evalin('base','whos');
for n = 1:length(ret)
val = ret(n).bytes + val;
end
val = val/1e6;
% %----------------------------------------------------------%
% function localSetHGCreateFcn(val)
% Commenting out the code below. This is causing problems
% if a user saves a fig file while the memory tool is up.
% set(0,'DefaultFigureCreateFcn', val);
% set(0,'DefaultAxesCreateFcn', val);
% set(0,'DefaultUIPanelCreateFcn', val);
% set(0,'DefaultPatchCreateFcn', val);
% set(0,'DefaultRectangleCreateFcn', val);
% set(0,'DefaultSurfaceCreateFcn', val);
% set(0,'DefaultImageCreateFcn', val);
% set(0,'DefaultTextCreateFcn', val);
% set(0,'DefaultLineCreateFcn', val);
% set(0,'DefaultUIControlCreateFcn', val);
% set(0,'DefaultUIMenuCreateFcn', val);
%----------------------------------------------------------%
function localUpdateAxesLimits(hAxes,hLine)
min_data = min(get(hLine,'ydata'));
max_data = max(get(hLine,'ydata'));
if max_data<10
newlim = [min_data 10];
else
delta = abs(max_data);
newlim = [min_data - .1*delta, max_data + .1*delta];
end
set(hAxes,'YLim',newlim);
%----------------------------------------------------------%
function [names] = localGetClassLoadingNames
names = [];
try
h = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
cloader = h.getCustomClassLoader;
if ~isempty(cloader)
names = char(cloader.debugGetClassNames);
end
end
%----------------------------------------------------------%
function [val] = localGetClassLoadingSize
val = 0;
try
h = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
cloader = h.getCustomClassLoader;
if ~isempty(cloader)
val = cloader.debugGetCacheSize;
end
end
% hack to keep line visible on log plot
if (val<1)
val = 1;
end
%----------------------------------------------------------%
function [free_memory,total_memory, max_memory] = localGetJavaMemory
MB = 1048576; % megabyte
free_memory = java.lang.Runtime.getRuntime.freeMemory/MB;
total_memory = java.lang.Runtime.getRuntime.totalMemory/MB;
max_memory = java.lang.Runtime.getRuntime.maxMemory/MB;
%-----------------------------------------------------
function retval = localGetIconPath
retval = [];
persistent iconpath;
if isempty(iconpath)
[iconpath,filename,ext] = fileparts(which(mfilename));
iconpath = fullfile(iconpath,'private');
end
retval = iconpath;
%-----------------------------------------------------
function info = localGetMemoryInfo
% Big hack here, parse output of memstats since there
% are no output variables.
str = evalc('feature memstats');
ind = findstr(str,'MB');
LEN = 20;
% Parse output
% Physical Memory (RAM):
% In Use: 483 MB (1e305000)
% Free: 539 MB (21ba3000)
% Total: 1022 MB (3fea8000)
retval = str((ind(1)-2):-1:ind(1)-LEN);
info.PhysicalMemory.InUse = str2num(fliplr(retval));
%retval = str((ind(2)-2):-1:ind(2)-LEN);
%info.PhysicalMemory.Free = str2num(fliplr(retval));
retval = str((ind(3)-2):-1:ind(3)-LEN);
info.PhysicalMemory.Total = str2num(fliplr(retval));
% Page File (Swap space):
% In Use: 571 MB (23b57000)
% Free: 1890 MB (76220000)
% Total: 2461 MB (99d77000)
retval = str((ind(4)-2):-1:ind(4)-LEN);
info.PageFile.InUse = str2num(fliplr(retval));
retval = str((ind(5)-2):-1:ind(5)-LEN);
info.PageFile.Free = str2num(fliplr(retval));
retval = str((ind(6)-2):-1:ind(6)-LEN);
info.PageFile.Total = str2num(fliplr(retval));
% Virtual Memory (Address Space):
% In Use: 536 MB (21851000)
% Free: 1511 MB (5e78f000)
% Total: 2047 MB (7ffe0000)
%retval = str((ind(7)-2):-1:ind(7)-LEN);
%info.VirtualMemory.InUse = str2num(fliplr(retval));
%retval = str((ind(8)-2):-1:ind(8)-LEN);
%info.VirtualMemory.Free = str2num(fliplr(retval));
%retval = str((ind(9)-2):-1:ind(9)-LEN);
%info.VirtualMemory.Total = str2num(fliplr(retval));
% Largest Contiguous Free Blocks:
% 1. [at 25d20000] 859 MB (35b40000)
retval = str((ind(10)-2):-1:ind(10)-LEN);
info.LargestFreeBlock = str2num(fliplr(retval));
%----------------------------------------------------------%
function info = localGetInfo
info = getappdata(0,'MonitorMATLAB');
if isempty(info)
info = struct;
info.figure = [];
%info.HGObjectCreatedCount = [];
%info.HGObjectInMemory = [];
info.dorecord = false;
info.doreset = false;
end
%----------------------------------------------------------%
function localSetInfo(info)
setappdata(0,'MonitorMATLAB',info);
|
github
|
stoman/MachineLearningKernelMethods-master
|
gradient.m
|
.m
|
MachineLearningKernelMethods-master/functions/gradient.m
| 260 |
utf_8
|
a74bbc7c4ac0e82b40fa580599439977
|
%A gradient computation used for the fminunc function in mnist/learning.m
%for the gradient descent.
%Author: Stefan Toman ([email protected])
function [L, grad] = gradient(w, x, y)
L = 1/2*norm(x*w-y);
if nargout > 1
grad = x'*(x*w-y);
end;
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
euclideankernel.m
|
.m
|
MachineLearningKernelMethods-master/functions/euclideankernel.m
| 700 |
utf_8
|
770d7b069d4fe145d4eeb48087d03f02
|
%This function returns a function handle for a Euclidean kernel. The
%argument nrinputs is optional and defaults to 2. If nrinputs is 1 the
%function will take one argument, if nrinputs is 2 it will take two
%arguments and call the function for one argument with the difference of
%the arguments.
%Author: Stefan Toman ([email protected])
function K = euclideankernel(nrinputs)
%optional argument
if nargin == 0
nrinputs = 2;
end
%create function
if nrinputs == 1
K = @(x) sum(x*x',2);
elseif nrinputs == 2
K1 = euclideankernel(1);
K = @(x,z) K1(bsxfun(@minus, x, z));
else
error('parameter nrinputs should be 1 or 2');
end
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
gaussiankernel.m
|
.m
|
MachineLearningKernelMethods-master/functions/gaussiankernel.m
| 1,120 |
utf_8
|
f155a3486cb007982465902a74eb5c72
|
%This function returns a function handle for a Gaussian kernel using a
%given parameter gamma. The argument nrinputs is optional and defaults to
%2. If nrinputs is 1 the function will take one argument, if nrinputs is 2
%it will take two arguments and call the function for one argument with the
%difference of the arguments. The argument nonormalization is also optional
%and defaults to false. If it is true then the factor (2*pi)^(-size(x,2)/2)
%is ignored.
% Author: Stefan Toman ([email protected])
function K = gaussiankernel(gamma, nrinputs, nonormalization)
%optional arguments
if nargin < 2
nrinputs = 2;
end
if nargin < 3
nonormalization = false;
end
%create function
if nrinputs == 1 && nonormalization
K = @(x) exp(-gamma/2.*sum(x.^2,2));
elseif nrinputs == 1
K1 = gaussiankernel(gamma, 1, true);
K = @(x) (2*pi)^(-size(x,2)/2)*K1(x);
elseif nrinputs == 2
K1 = gaussiankernel(gamma, 1, nonormalization);
K = @(x,z) K1(bsxfun(@minus, x, z));
else
error('parameter nrinputs should be 1 or 2');
end
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
funpredict.m
|
.m
|
MachineLearningKernelMethods-master/functions/funpredict.m
| 790 |
utf_8
|
b9833b2b5c971ba6e44bfd00184cab59
|
%This function returns a handle to a prediction function using kernels
%given a training set X and Y, a regularization parameter lambda and a
%kernel function K. The resulting function can predict single data as row
%vectors or several vectors simultaneously given as a matrix.
%Author: Stefan Toman ([email protected])
function predict = funpredict(X, Y, lambda, K)
%make assertion for inputs
assert(size(X,1) == size(Y,1), 'number of rows of X and Y do not match');
assert(sum(Y.^2 ~= 1) == 0, 'Y contains entries other than +1 and -1');
%solve the regular dual linear regression problem with the given kernel
a = (pdist2(X, X, K) + lambda*eye(size(X, 1)))\Y;
%results can be predicted by multiplying with the vector a
predict = @(Xt) (pdist2(Xt, X, K) * a);
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
defaultkernel.m
|
.m
|
MachineLearningKernelMethods-master/functions/defaultkernel.m
| 175 |
utf_8
|
d3836fdf1ebdd60c998aa84c69161ec6
|
%This function returns a function handle for a default kernel (the inner
%product).
%Author: Stefan Toman ([email protected])
function K = defaultkernel()
K = @(x,z) x*z';
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
printresults.m
|
.m
|
MachineLearningKernelMethods-master/functions/printresults.m
| 522 |
utf_8
|
cdb1adc5a9b9500164e21a66d04fcbef
|
%This function evaluates the quality of predicted results on a test set as
%used in mnist/learning.m. x and y are the test data, w are the parameters
%of the prediction function, name is the name of the method in use and a
%and b are the labels of the two classes of objects.
%Author: Stefan Toman ([email protected])
function printresults(x, y, w, name, a, b)
yy = x*w;
s = sum(abs(sign(y-(a+b)/2)-sign(yy-(a+b)/2)))/2;
percent = 100*(1-s/size(y,1));
fprintf('quality of method %s: %f%%\n', name, percent);
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
predictionquality.m
|
.m
|
MachineLearningKernelMethods-master/functions/predictionquality.m
| 378 |
utf_8
|
b8484f32a6393ed5a1910fc72ee870c3
|
%This function predicts the classes of some objects using a given
%prediction function. predict is the prediction function and X and Y are
%the test data. The return value is the number of correct estimates.
%Author: Stefan Toman ([email protected])
function correct = predictionquality(predict, X, Y)
predictions = predict(X);
correct = sum(Y - sign(predictions) == 0);
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
naivekernel.m
|
.m
|
MachineLearningKernelMethods-master/functions/naivekernel.m
| 828 |
utf_8
|
d038124cec473315638d6f6176b98082
|
%This function returns a function handle for a naive kernel using a
%parameter width. The kernel will create a box above each data point of
%size 1 with length 2*width. The argument nrinputs is optional and
%defaults to 2. If nrinputs is 1 the function will take one argument, if
%nrinputs is 2 it will take two arguments and call the function for one
%argument with the difference of the arguments.
%Author: Stefan Toman ([email protected])
function K = naivekernel(width, nrinputs)
%optional argument
if nargin == 1
nrinputs = 2;
end
%create function
if nrinputs == 1
K = @(x) (sum(x.^2,2)<width)./(2*width);
elseif nrinputs == 2
K1 = naivekernel(gamma, 1);
K = @(x,z) K1(bsxfun(@minus, x, z));
else
error('parameter nrinputs should be 1 or 2');
end
end
|
github
|
stoman/MachineLearningKernelMethods-master
|
testdataset.m
|
.m
|
MachineLearningKernelMethods-master/functions/testdataset.m
| 440 |
utf_8
|
bf12d5a9d596571fe5fe42bf3e5088d4
|
%This function creates a data set given two types of objects. X is the
%concatenation of the rows of both sets, Y is a vector containing 1 for all
%objects in the first set and -1 for all objects in the second set. The
%test data are also converted to doubles.
%Author: Stefan Toman ([email protected])
function [X, Y] = testdataset(seta, setb)
X = [double(seta); double(setb)];
Y = [ones(size(seta,1),1)*-1; ones(size(setb,1),1)*1];
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
patchNormalize.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/patchNormalize.m
| 1,483 |
iso_8859_1
|
bd4717ee5240260998e3b2043d5a7090
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function img = patchNormalize(img, params)
s = params.normalization.sideLength;
n = 1:s:size(img,1)+1;
m = 1:s:size(img,2)+1;
for i=1:length(n)-1
for j=1:length(m)-1
p = img(n(i):n(i+1)-1, m(j):m(j+1)-1);
pp=p(:);
if params.normalization.mode ~=0
pp=double(pp);
img(n(i):n(i+1)-1, m(j):m(j+1)-1) = 127+reshape(round((pp-mean(pp))/std(pp)), s, s);
else
f = 255.0/double(max(pp) - min(pp));
img(n(i):n(i+1)-1, m(j):m(j+1)-1) = round(f * (p-min(pp)));
end
end
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doFindMatchesModified.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/doFindMatchesModified.m
| 6,615 |
utf_8
|
22903cb2aa235535aede7f5513322e82
|
%
%
function results = doFindMatchesModified(results, params)
filename = sprintf('%s/matches-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.matching.load && exist(filename, 'file')
display(sprintf('Loading matchings from file %s ...', filename));
m = load(filename);
results.matches = m.matches;
results.seqValues = m.seqValues;
else
%matches = NaN(size(results.DD,2),2);
display('Searching for matching images ...');
% h_waitbar = waitbar(0, 'Searching for matching images.');
% make sure ds is dividable by two
params.matching.ds = params.matching.ds + mod(params.matching.ds,2);
[matches, seqValues] = findMatchingMatrix(results, params);
% save it
if params.matching.save
save(filename, 'matches','seqValues');
end
results.matches = matches;
results.seqValues = seqValues;% for debugging purpose
end
end
function [matches, seqValues] = findMatchingMatrix(results, params)
DD = (results.DD);
max_val = max(DD(:));
seqMaxValue = max_val*(params.matching.ds+1);
% We shall search for matches using velocities between
% params.matching.vmin and params.matching.vmax.
% However, not every vskip may be neccessary to check. So we first find
% out, which v leads to different trajectories:
move_min = params.matching.vmin * params.matching.ds;
move_max = params.matching.vmax * params.matching.ds;
move = move_min:move_max;
v = move / params.matching.ds;
%adding velocity 1 will go in the next location if
% since all the trajectories will have same difference score
% and it will return the first one
v = [1, v];
%v(1) = 1
ds = params.matching.ds;
idy_add = repmat([-ds:0], size(v,2),1);
% idy_add is y axis indices
% -1 0 1
% 0 0 1
% -1 -1 0
%
length(idy_add)
idy_add = round(idy_add .* repmat(v', 1, size(idy_add,2)));
%score = zeros(2,size(DD,1));
% add a line of inf costs so that we penalize running out of data
%score = zeros(1,size(DD,1));
%[id, vls] = min(DD);
%row padding
DD=[DD];
num_cols = size(DD,2);
row_padding = ones(ds,num_cols)*max_val;
DD=[row_padding;DD];
%col padding
%col padding is 1 more than ds/2 because if we have higher velcity than
%1 then it will create problem
num_rows = size(DD,1);
col_padding = ones(num_rows,ds);
DD = [col_padding, DD];
maxRow = size(DD,1);
maxCol = size(DD,2);
matchingMatrix = ones(size(DD))*seqMaxValue;
y_max = size(DD,1);
% [sortedValues,sortIndex] = sort(results.DD,'ascend');
% max_index = 5;
next_states = [];
if params.N < params.K
K = params.N
else
K =params.K
end
for Col = 2*ds : size(DD,2)
% this is where our trajectory starts
% n_start = Col - ds/2;
% %x is in x axis indices,
% x= repmat([n_start : n_start+ds], length(v), 1);
%indices = find(DD(:,Col) < max_val);
%indices of n lowest values in a column
[sortedValues,sortIndex] = sort(DD(:,Col),'ascend'); %# Sort the values in increasing order
indices = sortIndex(1:K); %# Get a linear index into A of the smallest values
indices = union(indices,next_states);
if size(indices,1) > 1
indices = indices';
end
%indices = sortIndex(1:10);
%lf = find(DD(:,Col) > params.initial_distance)
next_states = [];
for Row=indices
if Col > maxCol || Row > maxRow
break;
end
% score is zero for entering in the while loop
if matchingMatrix(Row,Col) < seqMaxValue
continue;
end
score = 0;
n_start = Col;
%x is in x axis indices, or column indices
x= repmat([n_start-ds : n_start], length(v), 1);
xx = (x-1) * y_max;
%row indices
y = min(idy_add+Row, y_max);
%adding row indices and column indices
idy = xx + y;
[score, velocity_index] = min(sum(DD(idy),2));
%idy = indices are always accessed row wise
%Since we made the indices using colunm by column or assume
%indices will be column by column,
%in sum function, for option 2, column wise indices summation
%otherwise row wise indices summation
%matchingMatrix(R,C) = score;
matchingMatrix(Row,Col) = score;
%DD(R,C) = score/(ds+1);
%[R,C,score,velocity_index]
%current_velocity = v(velocity_index);
%matchingMatrix
R = Row + idy_add(velocity_index,ds+1)-idy_add(velocity_index,ds);
if score < seqMaxValue*.9
next_states = [next_states; R];
end
end
% waitbar(N / size(results.DD,2), h_waitbar);
%break;
end
%normA = matchingMatrix - min(matchingMatrix(:));
%normA = normA ./ max(normA(:)) %
%figure, imshow(normA);
%matchingMatrix = normc(matchingMatrix);
%[scores, id] = min(matchingMatrix)
%matches = [id'+params.matching.ds/2, scores'];
%give up the padding of machingMatrix
%since col padding was 1 more than ds/2
matchingMatrix = matchingMatrix(ds+1:end,ds+1:end);
matches = NaN(size(matchingMatrix,2),2);
for Col = 1: size(matchingMatrix,2)
score= matchingMatrix(1:end,Col);
%score = normc(score);
[min_value, min_idx] = min(score);
window = max(1, min_idx-params.matching.Rwindow/2):min(length(score), min_idx+params.matching.Rwindow/2);
not_window = setxor(1:length(score), window);
min_value_2nd = min(score(not_window));
if min_value >= seqMaxValue
min_idx = NaN;
end
matches(Col,:) = [min_idx; min_value/min_value_2nd ];
%if min_value < params.matching.seqMaxValue
% matches(Col,:) = [min_idx ; min_value];
%end
end
seqValues = matchingMatrix;
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
previous stable_doFindMatchesModified.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/previous stable_doFindMatchesModified.m
| 5,841 |
utf_8
|
02d08b5e18097163ec0485e94f34dfcb
|
%
%
function results = doFindMatchesModified(results, params)
filename = sprintf('%s/matches-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.matching.load && exist(filename, 'file')
display(sprintf('Loading matchings from file %s ...', filename));
m = load(filename);
results.matches = m.matches;
else
%matches = NaN(size(results.DD,2),2);
display('Searching for matching images ...');
% h_waitbar = waitbar(0, 'Searching for matching images.');
% make sure ds is dividable by two
params.matching.ds = params.matching.ds + mod(params.matching.ds,2);
[matches, seqValues] = findMatchingMatrix(results, params);
% save it
if params.matching.save
save(filename, 'matches');
end
results.matches = matches;
results.seqValues = seqValues;% for debugging purpose
end
end
function [matches, seqValues] = findMatchingMatrix(results, params)
DD = (results.DD);
max_val = max(DD(:));
seqMaxValue = max_val*(params.matching.ds+1);
% We shall search for matches using velocities between
% params.matching.vmin and params.matching.vmax.
% However, not every vskip may be neccessary to check. So we first find
% out, which v leads to different trajectories:
move_min = params.matching.vmin * params.matching.ds;
move_max = params.matching.vmax * params.matching.ds;
move = move_min:move_max;
v = move / params.matching.ds;
%v(1) = 1
ds = params.matching.ds;
idy_add = repmat([-ds/2:ds/2], size(v,2),1);
% idy_add = floor(idy_add.*v);
% idy_add is y axis indices
% -1 0 1
% 0 0 1
% -1 -1 0
%
length(idy_add)
idy_add = floor(idy_add .* repmat(v', 1, size(idy_add,2)));
%score = zeros(2,size(DD,1));
% add a line of inf costs so that we penalize running out of data
%score = zeros(1,size(DD,1));
%[id, vls] = min(DD);
DD=[DD; inf(1,size(DD,2))];
maxRow = size(DD,1);
matchingMatrix = ones(size(DD))*seqMaxValue;
y_max = size(DD,1);
% [sortedValues,sortIndex] = sort(results.DD,'ascend');
% max_index = 5;
for Col = 2+ds/2 : size(DD,2)-ds/2
% this is where our trajectory starts
% n_start = Col - ds/2;
% %x is in x axis indices,
% x= repmat([n_start : n_start+ds], length(v), 1);
indices = find(DD(:,Col) < max_val);
% indices of n lowest values in a column
%[sortedValues,sortIndex] = sort(DD(:,Col),'ascend'); %# Sort the values in
%# descending order
%indices = sortIndex(1:10); %# Get a linear index into A of the 5 largest values
%lf = find(DD(:,Col) > params.initial_distance)
for Row=indices'
C = Col;
R = Row;
% score is zero for entering in the while loop
if matchingMatrix(R,C) < seqMaxValue
continue;
end
score = 0;
while score < seqMaxValue
%score = findSingleMatch(DD,x,idy_add,y_max, Col,Row, params);
% if matchingMatrix(R,C) < seqMaxValue
% break;
% end
if C > size(DD,2)-ds/2|| R > size(DD,1)-ds/2||C < ds/2
break;
end
n_start = C;
%x is in x axis indices,
x= repmat([n_start-ds/2 : n_start+ds/2], length(v), 1);
xx = (x-1) * y_max;
y = min(idy_add+R, y_max);
idy = xx + y;
[score, velocity_index] = min(sum(DD(idy),2));
%idy = indices are always accessed row wise
%Since we made the indices using colunm by column or assume
%indices will be column by column,
%in sum function, for option 2, column wise indices summation
%otherwise row wise indices summation
%matchingMatrix(R,C) = score;
if matchingMatrix(R,C) > score
matchingMatrix(R,C) = score;
%[R,C,score,velocity_index]
else
break;
end
%current_velocity = v(velocity_index);
%matchingMatrix
C = C+1;
R = R + idy_add(velocity_index,2+ds/2)-idy_add(velocity_index,1+ds/2);
R
end
end
% waitbar(N / size(results.DD,2), h_waitbar);
%break;
end
%normA = matchingMatrix - min(matchingMatrix(:));
%normA = normA ./ max(normA(:)) %
%figure, imshow(normA);
%matchingMatrix = normc(matchingMatrix);
%[scores, id] = min(matchingMatrix)
%matches = [id'+params.matching.ds/2, scores'];
matches = NaN(size(DD,2),2);
for Col = 2+ds/2 : size(DD,2)-ds/2
score= matchingMatrix(1:maxRow,Col);
%score = normc(score);
[min_value, min_idx] = min(score);
%window = max(1, min_idx-params.matching.Rwindow/2):min(length(score), min_idx+params.matching.Rwindow/2);
%not_window = setxor(1:length(score), window);
%min_value_2nd = min(score(not_window));
matches(Col,:) = [min_idx; min_value ];
%if min_value < params.matching.seqMaxValue
% matches(Col,:) = [min_idx ; min_value];
%end
end
seqValues = matchingMatrix;
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
b_doDifferenceMatrix.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/b_doDifferenceMatrix.m
| 4,516 |
utf_8
|
53f2379567ce2965dee54bf1163a7d93
|
%
%
function results = doDifferenceMatrix(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% 'checks',64));
tic;
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
toc
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
column1 = result2(:);
S2 = table(column1, column2);
[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1) + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
tic;
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
toc
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D';
% --------M1----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M2 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doPreprocessing.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/doPreprocessing.m
| 3,144 |
utf_8
|
88439f0df15bc850c247e25f9338587a
|
%
function results = doPreprocessing(params)
for i = 1:length(params.dataset)
% shall we just load it?
filename = sprintf('%s/preprocessing-%s%s.mat', params.dataset(i).savePath, params.dataset(i).saveFile, params.saveSuffix);
if params.dataset(i).preprocessing.load && exist(filename, 'file');
r = load(filename);
display(sprintf('Loading file %s ...', filename));
results.dataset(i).preprocessing = r.results_preprocessing;
else
% or shall we actually calculate it?
p = params;
p.dataset=params.dataset(i);
results.dataset(i).preprocessing = single(preprocessing(p));
if params.dataset(i).preprocessing.save
results_preprocessing = single(results.dataset(i).preprocessing);
save(filename, 'results_preprocessing');
end
end
end
end
%%
function dhog = preprocessing(params)
display(sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% h_waitbar = waitbar(0,sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% allocate memory for all the processed images
% n = length(params.dataset.imageIndices);
% m = params.downsample.size(1)*params.downsample.size(2);
%
% if ~isempty(params.dataset.crop)
% c = params.dataset.crop;
% m = (c(3)-c(1)+1) * (c(4)-c(2)+1);
% end
%
% images = zeros(m,n, 'uint8');
% j=1;
l = length( params.dataset.imageIndices);
dhog = []*l;
readFormat = strcat('%s/%s%0',num2str(params.dataset.numberFormat),'d%s%s')
% for every image ....
indices = params.dataset.imageIndices;
j = 1;
for i = indices
filename = sprintf(readFormat, params.dataset.imagePath, ...
params.dataset.prefix, ...
i, ...
params.dataset.suffix, ...
params.dataset.extension);
im = imread(filename);
% convert to grayscale
if params.DO_GRAYLEVEL
im = rgb2gray(im);
end
% resize the image
if params.DO_RESIZE
im = imresize(im, params.downsample.size, params.downsample.method);
end
% do patch normalization
% it didn't work well with hog descriptor
if params.DO_PATCHNORMALIZATION
im = patchNormalize(im, params);
end
[d, visualization] = extractHOGFeatures(im,'CellSize',params.dataset.cellSize);
dhog(j,:)= d(:);
j=j+1;
% waitbar((i-params.dataset.imageIndices(1)) / (params.dataset.imageIndices(end)-params.dataset.imageIndices(1)));
end
dhog = dhog';
% close(h_waitbar);
size(dhog)
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
b_doPreprocessing.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/b_doPreprocessing.m
| 3,811 |
iso_8859_1
|
4c79c1ead929d54cc2610f05b48630a1
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doPreprocessing(params)
for i = 1:length(params.dataset)
% shall we just load it?
filename = sprintf('%s/preprocessing-%s%s.mat', params.dataset(i).savePath, params.dataset(i).saveFile, params.saveSuffix);
if params.dataset(i).preprocessing.load && exist(filename, 'file');
r = load(filename);
display(sprintf('Loading file %s ...', filename));
results.dataset(i).preprocessing = r.results_preprocessing;
else
% or shall we actually calculate it?
p = params;
p.dataset=params.dataset(i);
results.dataset(i).preprocessing = single(preprocessing(p));
if params.dataset(i).preprocessing.save
results_preprocessing = single(results.dataset(i).preprocessing);
save(filename, 'results_preprocessing');
end
end
end
end
%%
function images = preprocessing(params)
display(sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% h_waitbar = waitbar(0,sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% allocate memory for all the processed images
n = length(params.dataset.imageIndices);
m = params.downsample.size(1)*params.downsample.size(2);
if ~isempty(params.dataset.crop)
c = params.dataset.crop;
m = (c(3)-c(1)+1) * (c(4)-c(2)+1);
end
images = zeros(m,n, 'uint8');
j=1;
readFormat = strcat('%s/%s%0',num2str(params.dataset.numberFormat),'d%s%s')
% for every image ....
for i = params.dataset.imageIndices
filename = sprintf(readFormat, params.dataset.imagePath, ...
params.dataset.prefix, ...
i, ...
params.dataset.suffix, ...
params.dataset.extension);
filename
img = imread(filename);
% convert to grayscale
if params.DO_GRAYLEVEL
img = rgb2gray(img);
end
% resize the image
if params.DO_RESIZE
img = imresize(img, params.downsample.size, params.downsample.method);
end
% crop the image if necessary
if ~isempty(params.dataset.crop)
img = img(params.dataset.crop(2):params.dataset.crop(4), params.dataset.crop(1):params.dataset.crop(3));
end
% do patch normalization
if params.DO_PATCHNORMALIZATION
img = patchNormalize(img, params);
end
images(:,j) = img(:);
j=j+1;
% waitbar((i-params.dataset.imageIndices(1)) / (params.dataset.imageIndices(end)-params.dataset.imageIndices(1)));
end
% close(h_waitbar);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doContrastEnhancement.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/doContrastEnhancement.m
| 2,015 |
iso_8859_1
|
0fe5d2f80ba01e5d10f64177d2e7695d
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doContrastEnhancement(results, params)
filename = sprintf('%s/differenceEnhanced-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.contrastEnhanced.load && exist(filename, 'file')
display(sprintf('Loading contrast-enhanced image distance matrix from file %s ...', filename));
dd = load(filename);
results.DD = dd.DD;
else
display('Performing local contrast enhancement on difference matrix ...');
% h_waitbar = waitbar(0,'Local contrast enhancement on difference matrix');
%DD = zeros(size(results.D), 'single');
D=results.D;
max_v = max(D(:));
cols = size(D,2);
for i = 1:size(results.D,1)
cnt = sum(D(i,:)< max_v);
if cnt > cols*.2
D(i,:) = ones(cols,1)*max_v;
end
end
% let the minimum distance be 0
%DD = DD-min(min(DD));
results.DD = D;
% save it?
if params.contrastEnhanced.save
DD = results.DD;
save(filename, 'DD');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
b_doContrastEnhancement.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/b_doContrastEnhancement.m
| 2,015 |
iso_8859_1
|
0fe5d2f80ba01e5d10f64177d2e7695d
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doContrastEnhancement(results, params)
filename = sprintf('%s/differenceEnhanced-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.contrastEnhanced.load && exist(filename, 'file')
display(sprintf('Loading contrast-enhanced image distance matrix from file %s ...', filename));
dd = load(filename);
results.DD = dd.DD;
else
display('Performing local contrast enhancement on difference matrix ...');
% h_waitbar = waitbar(0,'Local contrast enhancement on difference matrix');
%DD = zeros(size(results.D), 'single');
D=results.D;
max_v = max(D(:));
cols = size(D,2);
for i = 1:size(results.D,1)
cnt = sum(D(i,:)< max_v);
if cnt > cols*.2
D(i,:) = ones(cols,1)*max_v;
end
end
% let the minimum distance be 0
%DD = DD-min(min(DD));
results.DD = D;
% save it?
if params.contrastEnhanced.save
DD = results.DD;
save(filename, 'DD');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doDifferenceMatrix_noMutualConstraint.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/doDifferenceMatrix_noMutualConstraint.m
| 4,792 |
utf_8
|
39d2472da02c8305260087d5fef5d1be
|
%
%
function results = doDifferenceMatrix_noMutualConstraint(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
tic;
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
size(dhog1)
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1,speedup ] = flann_build_index(dhog1, struct('algorithm',params.algorithm, 'target_precision',...
params.target_precision));%, 'trees',params.trees));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
toc
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2, speedup ] = flann_build_index(dhog2, struct('algorithm',params.algorithm,'target_precision',...
params.target_precision));%, 'trees',params.trees));
results.speedup = speedup;
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% s0e 'checks',64));
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
toc
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
column1 = result2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
S2 = table(column1, column2);
column1 = [1];
column1 = column1';
column2 = column1;
S2 = table(column1,column2);
S = S1;
i1 = 1:height(S1);
%[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1));% + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D';
% --------M1----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M2 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
toc
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
showPrecisionCurve.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/showPrecisionCurve.m
| 3,688 |
utf_8
|
9a33792a410fba51873fd621e129b0d0
|
% Sayem Mohammad Siam
% University of Alberta
% Date 20th March 2016
% Computes empirical statistics based on classification output.
% Modified the following matlab functions prc_stats_empirical(targs, dvs) to compute
% Precision recall for SLAM
function showPrecisionCurve(matches,targs,range,imageSkip,filename)
% Compute empirical curves
dvs = matches(:,2)';
predicted = matches(:,1)';
[TPR_emp, FPR_emp, PPV_emp] = precision_recall(targs, dvs, predicted,range,imageSkip);
points = [TPR_emp;PPV_emp];
filename = strcat('prcurve/',filename)
save(filename,'points');
cols = [200 45 43; 37 64 180; 0 176 80; 0 0 0]/255;
figure,hold on;
plot(TPR_emp, PPV_emp, '-o', 'color', cols(1,:), 'linewidth', 2);
axis([0 1 0 1]);
xlabel('TPR (recall)'); ylabel('PPV (precision)'); title('PR curves');
set(gca, 'box', 'on');
end
% Arguments:
% targs: true image Number which should match(targets)
% dvs: decision values output by the classifier
% predicted: image number which matched by our algorithm
% range: No of images may differ
% imageSkip: if you didn't skip images then it should be 1
% Return values:
% TPR: true positive rate (recall)
% FPR: false positive rate
% PPV: positive predictive value (precision)
% AUC: area under the ROC curve
% AP: area under the PR curve (average precision)
%
% Each of these return vectors has length(desireds)+1 elements.
%
% Literature:
% K.H. Brodersen, C.S. Ong, K.E. Stephan, J.M. Buhmann (2010). The
% binormal assumption on precision-recall curves. In: Proceedings of
% the 20th International Conference on Pattern Recognition (ICPR).
% Modified code of
% Kay H. Brodersen & Cheng Soon Ong, ETH Zurich, Switzerland
% $Id: prc_stats_empirical.m 5529 2010-04-22 21:10:32Z bkay $
% -------------------------------------------------------------------------
function [TPR, FPR, PPV] = precision_recall(targs, dvs,predicted,range,imageSkip)
% Check input
%assert(all(size(targs)==size(dvs)));
%assert(all(targs==-1 | targs==1));
% Sort decision values and true labels according to decision values
n = length(dvs);
[dvs_sorted,idx] = sort(dvs,'descend');
find(idx>645)
idx(166)
targs_sorted = targs(idx*imageSkip);
predicted_sorted = predicted(idx)*imageSkip;
% Inititalize accumulators
TPR = repmat(NaN,1,n+1);
FPR = repmat(NaN,1,n+1);
PPV = repmat(NaN,1,n+1);
% Now slide the threshold along the decision values (the threshold
% always lies in between two values; here, the threshold represents the
% decision value immediately to the right of it)
fn = zeros(size(predicted_sorted));
for thr = 1:length(dvs_sorted)+1
% values greater than thr are positive and smaller than thr are NaN
%
TP = sum((abs(targs_sorted(thr:end)-predicted_sorted(thr:end))<range)&( ~isnan(predicted_sorted(thr:end))));%you have to match whether trgs(i) == dvs(i)
FN = sum(~isnan(targs_sorted(1:thr-1)));% 1 to thr-1 all should be NaN if not NaN they are false negative
TN = sum(isnan(targs_sorted(1:thr-1)));% 1 to thr-1 all should be NaN if they are NaN they are true Negative
FP = sum(abs(targs_sorted(thr:end)-predicted_sorted(thr:end))>=range | isnan(predicted_sorted(thr:end)));
TPR(thr) = TP/(TP+FN);%recall
FPR(thr) = FP/(FP+TN);
PPV(thr) = TP/(TP+FP);%precision
end
% Compute empirical AUC
%[tmp,tmp,tmp,AUC] = perfcurve(targs,dvs,1);
% Compute empirical AP
%AP = abs(trapz(TPR(~isnan(PPV)),PPV(~isnan(PPV))));
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
openSeqSLAM.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/openSeqSLAM.m
| 1,826 |
iso_8859_1
|
a02a94c886b776a5bcb33c971460a2fa
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = openSeqSLAM(params)
results=[];
% try to allocate 3 CPU cores (adjust to your machine) for parallel
% processing
tic;
% begin with preprocessing of the images
if params.DO_PREPROCESSING
results = doPreprocessing(params);
end
results.time_preprocessing = toc;
tic;
% image difference matrix
if params.DO_DIFF_MATRIX
results = doDifferenceMatrix_noMutualConstraint(results, params);
end
results.time_differenceMatrix = toc;
tic;
% contrast enhancement
if params.DO_CONTRAST_ENHANCEMENT
results = doContrastEnhancement(results, params);
else
if params.DO_DIFF_MATRIX
results.DD = results.D;
end
end
results.time_contrastEnhancement = toc;
tic;
% find the matches
if params.DO_FIND_MATCHES
results = doFindMatchesModified(results, params);
end
results.time_findMatches = toc;
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doDifferenceMatrix.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/doDifferenceMatrix.m
| 4,590 |
utf_8
|
2cd561e80b84d7b6d45246cb95eec6e1
|
%
%
function results = doDifferenceMatrix(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
tic;
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1,speedup ] = flann_build_index(dhog1, struct('algorithm',params.algorithm, 'target_precision',...
params.target_precision));%, 'trees',params.trees));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
toc
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2, speedup ] = flann_build_index(dhog2, struct('algorithm',params.algorithm,'target_precision',...
params.target_precision));%, 'trees',params.trees));
results.speedup = speedup;
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% s0e 'checks',64));
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
toc
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
column1 = result2(:);
S2 = table(column1, column2);
[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1) + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
D = D';
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D;
% --------M1----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M2 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
toc
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doFindMatchesModified.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/back_fast/doFindMatchesModified.m
| 6,617 |
utf_8
|
aa817af8acf450d798153c3da4b69fb0
|
%
%
function results = doFindMatchesModified(results, params)
filename = sprintf('%s/matches-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.matching.load && exist(filename, 'file')
display(sprintf('Loading matchings from file %s ...', filename));
m = load(filename);
results.matches = m.matches;
results.seqValues = m.seqValues;
else
%matches = NaN(size(results.DD,2),2);
display('Searching for matching images ...');
% h_waitbar = waitbar(0, 'Searching for matching images.');
% make sure ds is dividable by two
params.matching.ds = params.matching.ds + mod(params.matching.ds,2);
[matches, seqValues] = findMatchingMatrix(results, params);
% save it
if params.matching.save
save(filename, 'matches','seqValues');
end
results.matches = matches;
results.seqValues = seqValues;% for debugging purpose
end
end
function [matches, seqValues] = findMatchingMatrix(results, params)
DD = (results.DD);
max_val = max(DD(:));
seqMaxValue = max_val*(params.matching.ds+1);
% We shall search for matches using velocities between
% params.matching.vmin and params.matching.vmax.
% However, not every vskip may be neccessary to check. So we first find
% out, which v leads to different trajectories:
move_min = params.matching.vmin * params.matching.ds;
move_max = params.matching.vmax * params.matching.ds;
move = move_min:move_max;
v = move / params.matching.ds;
%v(1) = 1
ds = params.matching.ds;
idy_add = repmat([-ds/2:ds/2], size(v,2),1);
% idy_add is y axis indices
% -1 0 1
% 0 0 1
% -1 -1 0
%
length(idy_add)
idy_add = floor(idy_add .* repmat(v', 1, size(idy_add,2)));
%score = zeros(2,size(DD,1));
% add a line of inf costs so that we penalize running out of data
%score = zeros(1,size(DD,1));
%[id, vls] = min(DD);
%row padding
DD=[DD];
num_cols = size(DD,2);
row_padding = ones(ds/2,num_cols)*max_val;
DD=[row_padding;DD;row_padding];
%col padding
%col padding is 1 more than ds/2 because if we have higher velcity than
%1 then it will create problem
num_rows = size(DD,1);
col_padding = ones(num_rows,1+ds/2);
DD = [col_padding, DD, col_padding];
maxRow = size(DD,1);
matchingMatrix = ones(size(DD))*seqMaxValue;
y_max = size(DD,1);
% [sortedValues,sortIndex] = sort(results.DD,'ascend');
% max_index = 5;
for Col = 2+ds/2 : size(DD,2)-1-ds/2
% this is where our trajectory starts
% n_start = Col - ds/2;
% %x is in x axis indices,
% x= repmat([n_start : n_start+ds], length(v), 1);
indices = find(DD(:,Col) < max_val);
%indices of n lowest values in a column
[sortedValues,sortIndex] = sort(DD(:,Col),'ascend'); %# Sort the values in increasing order
indices = intersect(indices,sortIndex(1:10)); %# Get a linear index into A of the smallest values
%indices = sortIndex(1:10);
%lf = find(DD(:,Col) > params.initial_distance)
for Row=indices'
C = Col;
R = Row;
% score is zero for entering in the while loop
if matchingMatrix(R,C) < seqMaxValue
continue;
end
score = 0;
while score < seqMaxValue % at least 1-.x
%score = findSingleMatch(DD,x,idy_add,y_max, Col,Row, params);
% if matchingMatrix(R,C) < seqMaxValue
% break;
% end
if C > size(DD,2)-ds/2|| R > size(DD,1)-ds/2||C < ds/2
break;
end
n_start = C;
%x is in x axis indices, or column indices
x= repmat([n_start-ds/2 : n_start+ds/2], length(v), 1);
xx = (x-1) * y_max;
%row indices
y = min(idy_add+R, y_max);
%adding row indices and column indices
idy = xx + y;
[score, velocity_index] = min(sum(DD(idy),2));
%idy = indices are always accessed row wise
%Since we made the indices using colunm by column or assume
%indices will be column by column,
%in sum function, for option 2, column wise indices summation
%otherwise row wise indices summation
%matchingMatrix(R,C) = score;
if matchingMatrix(R,C) > score
matchingMatrix(R,C) = score;
%DD(R,C) = score/(ds+1);
%[R,C,score,velocity_index]
else
break;
end
%current_velocity = v(velocity_index);
%matchingMatrix
C = C+1;
R = R + idy_add(velocity_index,2+ds/2)-idy_add(velocity_index,1+ds/2);
end
end
% waitbar(N / size(results.DD,2), h_waitbar);
%break;
end
%normA = matchingMatrix - min(matchingMatrix(:));
%normA = normA ./ max(normA(:)) %
%figure, imshow(normA);
%matchingMatrix = normc(matchingMatrix);
%[scores, id] = min(matchingMatrix)
%matches = [id'+params.matching.ds/2, scores'];
%give up the padding of machingMatrix
%since col padding was 1 more than ds/2
matchingMatrix = matchingMatrix(1+ds/2:end-ds/2,2+ds/2:end-1-ds/2);
matches = NaN(size(matchingMatrix,2),2);
for Col = 1: size(matchingMatrix,2)
score= matchingMatrix(1:end,Col);
%score = normc(score);
[min_value, min_idx] = min(score);
window = max(1, min_idx-params.matching.Rwindow/2):min(length(score), min_idx+params.matching.Rwindow/2);
not_window = setxor(1:length(score), window);
min_value_2nd = min(score(not_window));
if min_value >= seqMaxValue
min_idx = NaN;
end
matches(Col,:) = [min_idx; min_value/min_value_2nd ];
%if min_value < params.matching.seqMaxValue
% matches(Col,:) = [min_idx ; min_value];
%end
end
seqValues = matchingMatrix;
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doPreprocessing.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/back_fast/doPreprocessing.m
| 3,144 |
utf_8
|
88439f0df15bc850c247e25f9338587a
|
%
function results = doPreprocessing(params)
for i = 1:length(params.dataset)
% shall we just load it?
filename = sprintf('%s/preprocessing-%s%s.mat', params.dataset(i).savePath, params.dataset(i).saveFile, params.saveSuffix);
if params.dataset(i).preprocessing.load && exist(filename, 'file');
r = load(filename);
display(sprintf('Loading file %s ...', filename));
results.dataset(i).preprocessing = r.results_preprocessing;
else
% or shall we actually calculate it?
p = params;
p.dataset=params.dataset(i);
results.dataset(i).preprocessing = single(preprocessing(p));
if params.dataset(i).preprocessing.save
results_preprocessing = single(results.dataset(i).preprocessing);
save(filename, 'results_preprocessing');
end
end
end
end
%%
function dhog = preprocessing(params)
display(sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% h_waitbar = waitbar(0,sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% allocate memory for all the processed images
% n = length(params.dataset.imageIndices);
% m = params.downsample.size(1)*params.downsample.size(2);
%
% if ~isempty(params.dataset.crop)
% c = params.dataset.crop;
% m = (c(3)-c(1)+1) * (c(4)-c(2)+1);
% end
%
% images = zeros(m,n, 'uint8');
% j=1;
l = length( params.dataset.imageIndices);
dhog = []*l;
readFormat = strcat('%s/%s%0',num2str(params.dataset.numberFormat),'d%s%s')
% for every image ....
indices = params.dataset.imageIndices;
j = 1;
for i = indices
filename = sprintf(readFormat, params.dataset.imagePath, ...
params.dataset.prefix, ...
i, ...
params.dataset.suffix, ...
params.dataset.extension);
im = imread(filename);
% convert to grayscale
if params.DO_GRAYLEVEL
im = rgb2gray(im);
end
% resize the image
if params.DO_RESIZE
im = imresize(im, params.downsample.size, params.downsample.method);
end
% do patch normalization
% it didn't work well with hog descriptor
if params.DO_PATCHNORMALIZATION
im = patchNormalize(im, params);
end
[d, visualization] = extractHOGFeatures(im,'CellSize',params.dataset.cellSize);
dhog(j,:)= d(:);
j=j+1;
% waitbar((i-params.dataset.imageIndices(1)) / (params.dataset.imageIndices(end)-params.dataset.imageIndices(1)));
end
dhog = dhog';
% close(h_waitbar);
size(dhog)
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doDifferenceMatrix.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/CMakeFiles/doDifferenceMatrix.m
| 4,276 |
utf_8
|
df153f88a48c06590dd35c17112304ce
|
%
%
function results = doDifferenceMatrix(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% 'checks',64));
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
column1 = result2(:);
S2 = table(column1, column2);
[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1) + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D;
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doDifferenceMatrix.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/CMakeFiles/mex_nearest_neighbors.dir/doDifferenceMatrix.m
| 4,216 |
utf_8
|
dac48ceba7e3fcece6fa922ed9d95c1b
|
%
%
function results = doDifferenceMatrix(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','kdtree', 'trees',8,...
'checks',64));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','kdtree', 'trees',8,...
'checks',64));
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% 'checks',64));
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
column1 = result2(:);
S2 = table(column1, column2);
[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1) + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D;
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_search.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/flann_search.m
| 3,506 |
utf_8
|
cffd29579f0290f0f680a3f12cb7a671
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function [indices, dists] = flann_search(data, testset, n, search_params)
%NN_SEARCH Fast approximate nearest neighbors search
%
% Performs a fast approximate nearest neighbor search using an
% index constructed using flann_build_index or directly a
% dataset.
% Marius Muja, January 2008
algos = struct( 'linear', 0, 'kdtree', 1, 'kmeans', 2, 'composite', 3, 'saved', 254, 'autotuned', 255 );
center_algos = struct('random', 0, 'gonzales', 1, 'kmeanspp', 2 );
log_levels = struct('none', 0, 'fatal', 1, 'error', 2, 'warning', 3, 'info', 4);
function value = id2value(map, id)
fields = fieldnames(map);
for i = 1:length(fields),
val = cell2mat(fields(i));
if map.(val) == id
value = val;
break;
end
end
end
function id = value2id(map,value)
id = map.(value);
end
default_params = struct('algorithm', 'kdtree' ,'checks', 32, 'trees', 4, 'branching', 32, 'iterations', 5, 'centers_init', 'random', 'cb_index', 0.4, 'target_precision', -1, 'build_weight', 0.01, 'memory_weight', 0, 'sample_fraction', 0.1, 'log_level', 'warning', 'random_seed', 0);
if ~isstruct(search_params)
error('The "search_params" argument must be a structure');
end
params = default_params;
fn = fieldnames(search_params);
for i = [1:length(fn)],
name = cell2mat(fn(i));
params.(name) = search_params.(name);
end
if ~isnumeric(params.algorithm),
params.algorithm = value2id(algos,params.algorithm);
end
if ~isnumeric(params.centers_init),
params.centers_init = value2id(center_algos,params.centers_init);
end
if ~isnumeric(params.log_level),
params.log_level = value2id(log_levels,params.log_level);
end
if (size(data,1)==1 && size(data,2)==1)
% we already have an index
[indices,dists] = nearest_neighbors('index_find_nn', data, testset, n, params);
else
% create the index and search
[indices,dists] = nearest_neighbors('find_nn', data, testset, n, params);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_load_index.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/flann_load_index.m
| 1,578 |
utf_8
|
f9bcc41fd5972c5c987d6a4d41bdc796
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function index = flann_load_index(filename, dataset)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
index = nearest_neighbors('load_index', filename, dataset);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
test_flann.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/test_flann.m
| 10,100 |
utf_8
|
d65a8eac8c411227a355b4ddbe6de38a
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function test_flann
data_path = './';
outcome = {'FAILED!!!!!!!!!', 'PASSED'};
failed = 0;
passed = 0;
cnt = 0;
ok = 1;
function assert(condition)
if (~condition)
ok = 0;
end
end
function run_test(name, test)
ok = 1;
cnt = cnt + 1;
tic;
fprintf('Test %d: %s...',cnt,name);
test();
time = toc;
if (ok)
passed = passed + 1;
else
failed = failed + 1;
end
fprintf('done (%g sec) : %s\n',time,cell2mat(outcome(ok+1)))
end
function status
fprintf('-----------------\n');
fprintf('Passed: %d/%d\nFailed: %d/%d\n',passed,cnt,failed,cnt);
end
dataset = [];
testset = [];
function test_load_data
% load the datasets and testsets
% use single precision for better memory efficiency
% store the features one per column because MATLAB
% uses column major ordering
dataset = single(load([data_path 'dataset.dat']))';
testset = single(load([data_path 'testset.dat']))';
assert(size(dataset,1) == size(testset,1));
end
run_test('Load data',@test_load_data);
match = [];
dists = [];
function test_linear_search
[match,dists] = flann_search(dataset, testset, 10, struct('algorithm','linear'));
assert(size(match,1) ==10 && size(match,2) == size(testset,2));
end
run_test('Linear search',@test_linear_search);
function test_kdtree_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kdtree',...
'trees',8,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('kd-tree search',@test_kdtree_search);
function test_kmeans_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('k-means search',@test_kmeans_search);
function test_composite_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('composite search',@test_composite_search);
function test_autotune_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('search with autotune',@test_autotune_search);
function test_index_kdtree_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kdtree', 'trees',8,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kd-tree search',@test_index_kdtree_search);
function test_index_kmeans_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search',@test_index_kmeans_search);
function test_index_kmeans_search_gonzales
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','gonzales'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search gonzales',@test_index_kmeans_search_gonzales);
function test_index_kmeans_search_kmeanspp
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','kmeanspp'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search kmeanspp',@test_index_kmeans_search_kmeanspp);
function test_index_composite_search
[index, search_params ] = flann_build_index(dataset,struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index composite search',@test_index_composite_search);
function test_index_autotune_search
[index, search_params, speedup ] = flann_build_index(dataset,struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index autotune search',@test_index_autotune_search);
status();
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_free_index.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/flann_free_index.m
| 1,614 |
utf_8
|
5d719d8d60539b6c90bee08d01e458b5
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_free_index(index_id)
%FLANN_FREE_INDEX Deletes the nearest-neighbors index
%
% Deletes an index constructed using flann_build_index.
% Marius Muja, January 2008
nearest_neighbors('free_index',index_id);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_save_index.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/flann_save_index.m
| 1,563 |
utf_8
|
5a44d911827fba5422041529b3c01cf6
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_save_index(index_id, filename)
%FLANN_SAVE_INDEX Saves an index to disk
%
% Marius Muja, March 2010
nearest_neighbors('save_index',index_id, filename);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_set_distance_type.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/flann/flann_set_distance_type.m
| 1,926 |
utf_8
|
8ba72989a4ac1bd6b30bec841b9def25
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_set_distance_type(type, order)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
distances = struct('euclidean', 1, 'manhattan', 2, 'minkowski', 3, 'max_dist', 4, 'hik', 5, 'hellinger', 6, 'chi_square', 7, 'cs', 7, 'kullback_leibler', 8, 'kl', 8);
function id = value2id(map,value)
id = map.(value);
end
if ~isnumeric(type),
type = value2id(distances,type);
end
if type~=3
order = 0;
end
nearest_neighbors('set_distance_type', type, order);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doPreprocessing.m
|
.m
|
Fast-SeqSLAM-master/fast_seqSlam/back_original/doPreprocessing.m
| 3,898 |
iso_8859_1
|
7519d4254e7bd4ce8189bf94ae9117a9
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doPreprocessing(params)
for i = 1:length(params.dataset)
% shall we just load it?
filename = sprintf('%s/preprocessing-%s%s.mat', params.dataset(i).savePath, params.dataset(i).saveFile, params.saveSuffix);
if params.dataset(i).preprocessing.load && exist(filename, 'file');
r = load(filename);
display(sprintf('Loading file %s ...', filename));
results.dataset(i).preprocessing = r.results_preprocessing;
else
% or shall we actually calculate it?
p = params;
p.dataset=params.dataset(i);
results.dataset(i).preprocessing = single(preprocessing(p));
if params.dataset(i).preprocessing.save
results_preprocessing = single(results.dataset(i).preprocessing);
save(filename, 'results_preprocessing');
end
end
end
end
%%
function images = preprocessing(params)
display(sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% h_waitbar = waitbar(0,sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% allocate memory for all the processed images
n = length(params.dataset.imageIndices);
m = params.downsample.size(1)*params.downsample.size(2);
if ~isempty(params.dataset.crop)
c = params.dataset.crop;
m = (c(3)-c(1)+1) * (c(4)-c(2)+1);
end
images = zeros(m,n, 'uint8');
j=1;
readFormat = strcat('%s/%s%0',num2str(params.dataset.numberFormat),'d%s%s')
% for every image ....
for i = params.dataset.imageIndices
filename = sprintf(readFormat, params.dataset.imagePath, ...
params.dataset.prefix, ...
i, ...
params.dataset.suffix, ...
params.dataset.extension);
img = imread(filename);
% convert to grayscale
if params.DO_GRAYLEVEL
img = rgb2gray(img);
end
% resize the image
if params.DO_RESIZE
img = imresize(img, params.downsample.size, params.downsample.method);
end
% crop the image if necessary
if ~isempty(params.dataset.crop)
img = img(params.dataset.crop(2):params.dataset.crop(4), params.dataset.crop(1):params.dataset.crop(3));
end
% do patch normalization
if params.DO_PATCHNORMALIZATION
img = patchNormalize(img, params);
end
% shall we save the result?
if params.DO_SAVE_PREPROCESSED_IMG
end
images(:,j) = img(:);
j=j+1;
% waitbar((i-params.dataset.imageIndices(1)) / (params.dataset.imageIndices(end)-params.dataset.imageIndices(1)));
end
% close(h_waitbar);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
defaultParameters.m
|
.m
|
Fast-SeqSLAM-master/demo/defaultParameters.m
| 1,714 |
utf_8
|
82fece418707dd09e59815fb69b91339
|
%
%
function params=defaultParameters()
% switches
params.DO_PREPROCESSING = 1;
params.DO_RESIZE = 1;
params.DO_GRAYLEVEL = 1;
params.DO_PATCHNORMALIZATION = 0;
params.DO_SAVE_PREPROCESSED_IMG = 1;
params.DO_DIFF_MATRIX = 1;
params.DO_CONTRAST_ENHANCEMENT = 0;%make it 0!!
params.DO_FIND_MATCHES = 1;
%parameters for Flann and building similarity matrix
params.N = 10;
params.initial_distance = 9999;
params.mul_unit = 2;
%%ANN parameters
params.distance_type = 'manhattan';
params.algorithm = 'kdtree';
params.trees = 8;
params.checks = 64;
% parameters for preprocessing
params.downsample.size = [32 32]; % height, width
params.downsample.method = 'lanczos3';
params.normalization.sideLength = 8;
params.normalization.mode = 1;
% parameters regarding the matching between images
params.matching.ds = 30; %always even number
%params.matching.seqMaxValue = params.initial_distance*(params.matching.ds+1);
params.thresh = .90;
params.matching.Rrecent=5;
params.matching.vmin = .8;
%params.matching.vskip = 0.1;
params.matching.vmax = 1.2;
params.matching.Rwindow = 10;
params.matching.save = 1;
params.matching.load = 1;
% parameters for contrast enhancement on difference matrix
params.contrastEnhancement.R = 10;
% load old results or re-calculate? save results?
params.differenceMatrix.save = 0;
params.differenceMatrix.load = 0;
params.contrastEnhanced.save = 1;
params.contrastEnhanced.load = 0;
% suffix appended on files containing the results
params.saveSuffix='';
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
patchNormalize.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/patchNormalize.m
| 1,483 |
iso_8859_1
|
bd4717ee5240260998e3b2043d5a7090
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function img = patchNormalize(img, params)
s = params.normalization.sideLength;
n = 1:s:size(img,1)+1;
m = 1:s:size(img,2)+1;
for i=1:length(n)-1
for j=1:length(m)-1
p = img(n(i):n(i+1)-1, m(j):m(j+1)-1);
pp=p(:);
if params.normalization.mode ~=0
pp=double(pp);
img(n(i):n(i+1)-1, m(j):m(j+1)-1) = 127+reshape(round((pp-mean(pp))/std(pp)), s, s);
else
f = 255.0/double(max(pp) - min(pp));
img(n(i):n(i+1)-1, m(j):m(j+1)-1) = round(f * (p-min(pp)));
end
end
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doFindMatchesModified.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/doFindMatchesModified.m
| 5,881 |
utf_8
|
fa185462c4ee7aa944de7689bb43d7c6
|
%
%
function results = doFindMatchesModified(results, params)
filename = sprintf('%s/matches-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.matching.load && exist(filename, 'file')
display(sprintf('Loading matchings from file %s ...', filename));
m = load(filename);
results.matches = m.matches;
else
%matches = NaN(size(results.DD,2),2);
display('Searching for matching images ...');
% h_waitbar = waitbar(0, 'Searching for matching images.');
% make sure ds is dividable by two
params.matching.ds = params.matching.ds + mod(params.matching.ds,2);
[matches, seqValues] = findMatchingMatrix(results, params);
% save it
if params.matching.save
save(filename, 'matches');
end
results.matches = matches;
results.seqValues = seqValues;% for debugging purpose
end
end
function [matches, seqValues] = findMatchingMatrix(results, params)
DD = (results.DD);
max_val = max(DD(:));
seqMaxValue = max_val*(params.matching.ds+1);
%seqMaxValue = 9999999999;
% We shall search for matches using velocities between
% params.matching.vmin and params.matching.vmax.
% However, not every vskip may be neccessary to check. So we first find
% out, which v leads to different trajectories:
move_min = params.matching.vmin * params.matching.ds;
move_max = params.matching.vmax * params.matching.ds;
move = move_min:move_max;
v = move / params.matching.ds;
%v(1) = 1
ds = params.matching.ds;
idy_add = repmat([-ds/2:ds/2], size(v,2),1);
% idy_add = floor(idy_add.*v);
% idy_add is y axis indices
% -1 0 1
% 0 0 1
% -1 -1 0
%
length(idy_add)
idy_add = floor(idy_add .* repmat(v', 1, size(idy_add,2)));
%score = zeros(2,size(DD,1));
% add a line of inf costs so that we penalize running out of data
%score = zeros(1,size(DD,1));
%[id, vls] = min(DD);
DD=[DD; inf(1,size(DD,2))];
maxRow = size(DD,1);
matchingMatrix = ones(size(DD))*seqMaxValue;
y_max = size(DD,1);
% [sortedValues,sortIndex] = sort(results.DD,'ascend');
% max_index = 5;
for Col = 2+ds/2 : size(DD,2)-ds/2
% this is where our trajectory starts
% n_start = Col - ds/2;
% %x is in x axis indices,
% x= repmat([n_start : n_start+ds], length(v), 1);
indices = find(DD(:,Col) < max_val);
% indices of n lowest values in a column
%[sortedValues,sortIndex] = sort(DD(:,Col),'ascend'); %# Sort the values in
%# descending order
%indices = sortIndex(1:50); %# Get a linear index into A of the 5 largest values
%lf = find(DD(:,Col) > params.initial_distance)
for Row=indices'
C = Col;
R = Row;
% score is zero for entering in the while loop
if matchingMatrix(R,C) < seqMaxValue
continue;
end
score = 0;
while score < seqMaxValue
%score = findSingleMatch(DD,x,idy_add,y_max, Col,Row, params);
% if matchingMatrix(R,C) < seqMaxValue
% break;
% end
if C > size(DD,2)-ds/2|| R > size(DD,1)-ds/2||C < ds/2
break;
end
n_start = C;
%x is in x axis indices,
x= repmat([n_start-ds/2 : n_start+ds/2], length(v), 1);
xx = (x-1) * y_max;
y = min(idy_add+R, y_max);
idy = xx + y;
[score, velocity_index] = min(sum(DD(idy),2));
%idy = indices are always accessed row wise
%Since we made the indices using colunm by column or assume
%indices will be column by column,
%in sum function, for option 2, column wise indices summation
%otherwise row wise indices summation
%matchingMatrix(R,C) = score;
if matchingMatrix(R,C) > score
matchingMatrix(R,C) = score;
%[R,C,score,velocity_index]
else
break;
end
%current_velocity = v(velocity_index);
%matchingMatrix
C = C+1;
R = R + idy_add(velocity_index,2+ds/2)-idy_add(velocity_index,1+ds/2);
R
end
end
% waitbar(N / size(results.DD,2), h_waitbar);
%break;
end
%normA = matchingMatrix - min(matchingMatrix(:));
%normA = normA ./ max(normA(:)) %
%figure, imshow(normA);
%matchingMatrix = normc(matchingMatrix);
%[scores, id] = min(matchingMatrix)
%matches = [id'+params.matching.ds/2, scores'];
matches = NaN(size(DD,2),2);
for Col = 1 : size(DD,2)-params.matching.ds
score= matchingMatrix(1:maxRow,Col);
%score = normc(score);
[min_value, min_idx] = min(score);
%window = max(1, min_idx-params.matching.Rwindow/2):min(length(score), min_idx+params.matching.Rwindow/2);
%not_window = setxor(1:length(score), window);
%min_value_2nd = min(score(not_window));
matches(Col,:) = [min_idx; min_value ];
%if min_value < params.matching.seqMaxValue
% matches(Col,:) = [min_idx ; min_value];
%end
end
seqValues = matchingMatrix;
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doFindMatches.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/doFindMatches.m
| 3,543 |
iso_8859_1
|
d58b1f0451dacccc9bd8fcd447712c2a
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doFindMatches(results, params)
filename = sprintf('%s/matches-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.matching.load && exist(filename, 'file')
display(sprintf('Loading matchings from file %s ...', filename));
m = load(filename);
results.matches = m.matches;
else
matches = NaN(size(results.DD,2),2);
display('Searching for matching images ...');
% h_waitbar = waitbar(0, 'Searching for matching images.');
% make sure ds is dividable by two
params.matching.ds = params.matching.ds + mod(params.matching.ds,2);
DD = results.DD;
parfor N = params.matching.ds/2+1 : size(results.DD,2)-params.matching.ds/2
matches(N,:) = findSingleMatch(DD, N, params);
% waitbar(N / size(results.DD,2), h_waitbar);
end
% save it
if params.matching.save
save(filename, 'matches');
end
results.matches = matches;
end
end
%%
function match = findSingleMatch(DD, N, params)
% We shall search for matches using velocities between
% params.matching.vmin and params.matching.vmax.
% However, not every vskip may be neccessary to check. So we first find
% out, which v leads to different trajectories:
move_min = params.matching.vmin * params.matching.ds;
move_max = params.matching.vmax * params.matching.ds;
move = move_min:move_max;
v = move / params.matching.ds;
idx_add = repmat([0:params.matching.ds], size(v,2),1);
% idx_add = floor(idx_add.*v);
idx_add = floor(idx_add .* repmat(v', 1, length(idx_add)));
% this is where our trajectory starts
n_start = N - params.matching.ds/2;
x= repmat([n_start : n_start+params.matching.ds], length(v), 1);
score = zeros(1,size(DD,1));
% add a line of inf costs so that we penalize running out of data
DD=[DD; inf(1,size(DD,2))];
y_max = size(DD,1);
xx = (x-1) * y_max;
for s=1:size(DD,1)
y = min(idx_add+s, y_max);
idx = xx + y;
score(s) = min(sum(DD(idx),2));
end
% find min score and 2nd smallest score outside of a window
% around the minimum
[min_value, min_idx] = min(score);
window = max(1, min_idx-params.matching.Rwindow/2):min(length(score), min_idx+params.matching.Rwindow/2);
not_window = setxor(1:length(score), window);
min_value_2nd = min(score(not_window));
match = [min_idx + params.matching.ds/2; min_value / min_value_2nd];
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doPreprocessing.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/doPreprocessing.m
| 3,385 |
utf_8
|
8fe0631458856f931c18a870de22ec6d
|
%
function results = doPreprocessing(params)
for i = 1:length(params.dataset)
% shall we just load it?
filename = sprintf('%s/preprocessing-%s%s.mat', params.dataset(i).savePath, params.dataset(i).saveFile, params.saveSuffix);
if params.dataset(i).preprocessing.load && exist(filename, 'file');
r = load(filename);
display(sprintf('Loading file %s ...', filename));
results.dataset(i).preprocessing = r.results_preprocessing;
else
% or shall we actually calculate it?
p = params;
p.dataset=params.dataset(i);
results.dataset(i).preprocessing = single(preprocessing(p));
if params.dataset(i).preprocessing.save
results_preprocessing = single(results.dataset(i).preprocessing);
save(filename, 'results_preprocessing');
end
end
end
end
%%
function dhog = preprocessing(params)
display(sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% h_waitbar = waitbar(0,sprintf('Preprocessing dataset %s, indices %d - %d ...', params.dataset.name, params.dataset.imageIndices(1), params.dataset.imageIndices(end)));
% allocate memory for all the processed images
% n = length(params.dataset.imageIndices);
% m = params.downsample.size(1)*params.downsample.size(2);
%
% if ~isempty(params.dataset.crop)
% c = params.dataset.crop;
% m = (c(3)-c(1)+1) * (c(4)-c(2)+1);
% end
%
% images = zeros(m,n, 'uint8');
% j=1;
l = length( params.dataset.imageIndices);
dhog = []*l;
readFormat = strcat('%s/%s%0',num2str(params.dataset.numberFormat),'d%s%s')
% for every image ....
indices = params.dataset.imageIndices;
j = 1;
for i = indices
filename = sprintf(readFormat, params.dataset.imagePath, ...
params.dataset.prefix, ...
i, ...
params.dataset.suffix, ...
params.dataset.extension);
filename
im = imread(filename);
% convert to grayscale
if params.DO_GRAYLEVEL
im = rgb2gray(im);
end
% resize the image
if params.DO_RESIZE
im = imresize(im, params.downsample.size, params.downsample.method);
end
% do patch normalization
% it didn't work well with hog descriptor
if params.DO_PATCHNORMALIZATION
im = patchNormalize(im, params);
end
%h = size(im, 1);
%w = size(im, 2);
%scale = 1;
% im = imresize(im,scale,'bicubic','AntiAliasing',false);
%reshape = [h/scale, w/scale];
%im = cv.resize(im, reshape, 'Interpolation', 'Cubic');
[d, visualization] = extractHOGFeatures(im,'CellSize',params.dataset.cellSize);
dhog(j,:)= d(:);
j=j+1;
% waitbar((i-params.dataset.imageIndices(1)) / (params.dataset.imageIndices(end)-params.dataset.imageIndices(1)));
end
dhog = dhog';
% close(h_waitbar);
size(dhog)
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doContrastEnhancement.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/doContrastEnhancement.m
| 2,164 |
iso_8859_1
|
3a5452345b7790f53cc34d31bc80b80d
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = doContrastEnhancement(results, params)
filename = sprintf('%s/differenceEnhanced-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.contrastEnhanced.load && exist(filename, 'file')
display(sprintf('Loading contrast-enhanced image distance matrix from file %s ...', filename));
dd = load(filename);
results.DD = dd.DD;
else
display('Performing local contrast enhancement on difference matrix ...');
% h_waitbar = waitbar(0,'Local contrast enhancement on difference matrix');
DD = zeros(size(results.D), 'single');
D=results.D;
parfor i = 1:size(results.D,1)
a=max(1, i-params.contrastEnhancement.R/2);
b=min(size(D,1), i+params.contrastEnhancement.R/2);
v = D(a:b, :);
DD(i,:) = (D(i,:) - mean(v)) ./ std(v);
% waitbar(i/size(results.D, 1));
end
% let the minimum distance be 0
results.DD = DD-min(min(DD));
% save it?
if params.contrastEnhanced.save
DD = results.DD;
save(filename, 'DD');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
showPrecisionCurve.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/showPrecisionCurve.m
| 3,142 |
utf_8
|
a08bcb7a982e8b06ae0f9695de25d40f
|
function showPrecisionCurve(matches,targs,range,imageSkip,filename)
% Compute empirical curves
dvs = matches(:,2)';
predicted = matches(:,1)';
[TPR_emp, FPR_emp, PPV_emp] = precision_recall(targs, dvs, predicted,range,imageSkip);
points = [TPR_emp,PPV_emp];
filename = strcat('prcurve/',filename)
save(filename,'points');
cols = [200 45 43; 37 64 180; 0 176 80; 0 0 0]/255;
figure,hold on;
plot(TPR_emp, PPV_emp, '-o', 'color', cols(1,:), 'linewidth', 2);
axis([0 1 0 1]);
xlabel('TPR (recall)'); ylabel('PPV (precision)'); title('PR curves');
set(gca, 'box', 'on');
end
% Computes empirical statistics based on classification output.
%
% Usage:
% [TPR, FPR, PPV, AUC, AP] = prc_stats_empirical(targs, dvs)
%
% Arguments:
% targs: true class labels (targets)
% dvs: decision values output by the classifier
%
% Return values:
% TPR: true positive rate (recall)
% FPR: false positive rate
% PPV: positive predictive value (precision)
% AUC: area under the ROC curve
% AP: area under the PR curve (average precision)
%
% Each of these return vectors has length(desireds)+1 elements.
%
% Literature:
% K.H. Brodersen, C.S. Ong, K.E. Stephan, J.M. Buhmann (2010). The
% binormal assumption on precision-recall curves. In: Proceedings of
% the 20th International Conference on Pattern Recognition (ICPR).
% Kay H. Brodersen & Cheng Soon Ong, ETH Zurich, Switzerland
% $Id: prc_stats_empirical.m 5529 2010-04-22 21:10:32Z bkay $
% -------------------------------------------------------------------------
function [TPR, FPR, PPV, AUC, AP] = precision_recall(targs, dvs,predicted,range,imageSkip)
% Check input
%assert(all(size(targs)==size(dvs)));
%assert(all(targs==-1 | targs==1));
% Sort decision values and true labels according to decision values
n = length(dvs);
[dvs_sorted,idx] = sort(dvs,'descend');
targs_sorted = targs(idx*imageSkip);
predicted_sorted = predicted(idx)*imageSkip;
% Inititalize accumulators
TPR = repmat(NaN,1,n+1);
FPR = repmat(NaN,1,n+1);
PPV = repmat(NaN,1,n+1);
% Now slide the threshold along the decision values (the threshold
% always lies in between two values; here, the threshold represents the
% decision value immediately to the right of it)
fn = zeros(size(predicted_sorted));
for thr = 1:length(dvs_sorted)+1
% values greater than thr are positive and smaller than thr are NaN
TP = sum(abs(targs_sorted(thr:end)-predicted_sorted(thr:end))<range);%you have to match whether trgs(i) == dvs(i)
FN = sum(~isnan(targs_sorted(1:thr-1)));
TN = sum(isnan(targs_sorted(1:thr-1)));
FP = sum(abs(targs_sorted(thr:end)-predicted_sorted(thr:end))>=range);
TPR(thr) = TP/(TP+FN);%recall
FPR(thr) = FP/(FP+TN);
PPV(thr) = TP/(TP+FP);%precision
end
% Compute empirical AUC
%[tmp,tmp,tmp,AUC] = perfcurve(targs,dvs,1);
% Compute empirical AP
%AP = abs(trapz(TPR(~isnan(PPV)),PPV(~isnan(PPV))));
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
openSeqSLAM.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/openSeqSLAM.m
| 1,771 |
iso_8859_1
|
5dbda8263e359c610136532c81968d9a
|
%
% Copyright 2013, Niko Sünderhauf
% [email protected]
%
% This file is part of OpenSeqSLAM.
%
% OpenSeqSLAM is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% OpenSeqSLAM is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with OpenSeqSLAM. If not, see <http://www.gnu.org/licenses/>.
function results = openSeqSLAM(params)
results=[];
% try to allocate 3 CPU cores (adjust to your machine) for parallel
% processing
try
if matlabpool('size')==0
matlabpool 3
end
catch
display('No parallel computing toolbox installed.');
end
% begin with preprocessing of the images
if params.DO_PREPROCESSING
results = doPreprocessing(params);
end
% image difference matrix
if params.DO_DIFF_MATRIX
results = doDifferenceMatrix(results, params);
end
% contrast enhancement
if params.DO_CONTRAST_ENHANCEMENT
results = doContrastEnhancement(results, params);
else
if params.DO_DIFF_MATRIX
results.DD = results.D;
end
end
% find the matches
if params.DO_FIND_MATCHES
results = doFindMatchesModified(results, params);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
doDifferenceMatrix.m
|
.m
|
Fast-SeqSLAM-master/demo/prcurve/local_fast_seqSlam/doDifferenceMatrix.m
| 4,276 |
utf_8
|
df153f88a48c06590dd35c17112304ce
|
%
%
function results = doDifferenceMatrix(results, params)
addpath(genpath('./flann'));
filename = sprintf('%s/difference-%s-%s%s.mat', params.savePath, params.dataset(1).saveFile, params.dataset(2).saveFile, params.saveSuffix);
if params.differenceMatrix.load && exist(filename, 'file')
display(sprintf('Loading image difference matrix from file %s ...', filename));
d = load(filename);
results.D = d.D;
else
if length(results.dataset)<2
display('Error: Cannot calculate difference matrix with less than 2 datasets.');
return;
end
display('Calculating image difference matrix ...');
% h_waitbar = waitbar(0,'Calculating image difference matrix');
dhog1 = results.dataset(1).preprocessing;
dhog2 = results.dataset(2).preprocessing;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%calcualtion of similarity matrix using FLANN nearest neighbour%%%%%%%%%%%%%%%%%%%%%%%%
flann_set_distance_type(params.distance_type, 0);
N = params.N;
[index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
%
% [index1, search_params1 ] = flann_build_index(dhog1, struct('algorithm','linear'...
% ));
[result1, ndists1] = flann_search(index1, dhog2, N, search_params1);
result1 = result1';
ndists1 = ndists1';
d1 = ndists1(:);
tmp = [1: length(result1)]';
column1 = repmat(tmp, N, 1);
column2 = result1(:);
size(column2)
S1 = table(column1, column2);
%S1
'------------'
%% cross check
[index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm',params.algorithm, 'trees',params.trees,...
'checks',params.checks));
% [index2, search_params2 ] = flann_build_index(dhog2, struct('algorithm','linear', 'trees',8,...
% 'checks',64));
[result2, ndists2] = flann_search(index2, dhog1, N, search_params2);
%result2 contains nodes of M2 for each node 1, 2, 3, .. of M1
%result1 contains nodes of M1 for each node 1, 2, 3, .. of M2
result2 = result2';
ndists2 = ndists2';
d2 = ndists2(:);
tmp = [1: length(result2)]';
column2 = repmat(tmp, N, 1);
column1 = result2(:);
S2 = table(column1, column2);
[S, i1, i2] = intersect(S1, S2);
%S = (N1_i, N2_j)
S_arr = table2array(S);
%[S_arr d1(i1)]
ini_dist = params.initial_distance;
similarity_matrix = (-ini_dist)*ones(length(result1), length(result2));
%S_arr(:,1) = nodes from map 2
%S_arr(:,2) = nodes from map 1
% --------M2----------
% | 4 0 0 0 0 0
% | 1 0 0 0 0 0
% S= M1 0 0 0 3 0 0
% | 0 4 0 0 0 0
% | 0 0 2 0 0 0
% | 0 1 0 0 0 0
ind = sub2ind(size(similarity_matrix), S_arr(:,1), S_arr(:,2));
%similarity_matrix(ind) = 30;
%[S_arr d1(i1)]
%ind = sub2ind(size(similarity_matrix), S_arr(:,2), S_arr(:,1));
similarity_matrix(ind) = (d1(i1) + d2(i2))/2;
%%%%fill the values by max value
max_val = max(similarity_matrix(:));
similarity_matrix(similarity_matrix == -params.initial_distance) = params.mul_unit*max_val;
%params.matching.seqMaxValue = params.mul_unit*max_val*(params.matching.ds+1);
D = similarity_matrix;
%%%%%%%%calculation of similarity matrix%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
results.D=D;
% save it
if params.differenceMatrix.save
save(filename, 'D');
end
% close(h_waitbar);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
pdftops.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/pdftops.m
| 5,528 |
utf_8
|
1042ce73e979a940784d5ea5f57f1ffc
|
function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops (e.g. '-help').
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% 02/05/2016 - Added possible error explanation suggested by Michael Pacer (issue #137)
% 02/05/2016 - Search additional possible paths suggested by Jonas Stein (issue #147)
% 03/05/2016 - Display the specific error message if pdftops fails for some reason (issue #148)
% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
paths = {'C:\Program Files\xpdf\pdftops.exe', 'C:\Program Files (x86)\xpdf\pdftops.exe'};
else
paths = {'/usr/bin/pdftops', '/usr/local/bin/pdftops'};
end
for a = 1:numel(paths)
path_ = paths{a};
if check_store_xpdf_path(path_)
return
end
end
% Ask the user to enter the path
errMsg1 = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url1 = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg1 '<a href="matlab:web(''-browser'',''' url1 ''');">' url1 '</a>']);
errMsg1 = [errMsg1 url1];
%if strncmp(computer,'MAC',3) % Is a Mac
% % Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
% uiwait(warndlg(errMsg1))
%end
% Provide an alternative possible explanation as per issue #137
errMsg2 = 'If you have pdftops installed, perhaps Matlab is shaddowing it as described in ';
url2 = 'https://github.com/altmany/export_fig/issues/137';
fprintf(2, '%s\n', [errMsg2 '<a href="matlab:web(''-browser'',''' url2 ''');">issue #137</a>']);
errMsg2 = [errMsg2 url1];
state = 0;
while 1
if state
option1 = 'Install pdftops';
else
option1 = 'Issue #137';
end
answer = questdlg({errMsg1,'',errMsg2},'Pdftops error',option1,'Locate pdftops','Cancel','Cancel');
drawnow; % prevent a Matlab hang: http://undocumentedmatlab.com/blog/solving-a-matlab-hang-problem
switch answer
case 'Install pdftops'
web('-browser',url1);
case 'Issue #137'
web('-browser',url2);
state = 1;
case 'Locate pdftops'
base = uigetdir('/', errMsg1);
if isequal(base, 0)
% User hit cancel or closed window
break
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break
end
end
if check_store_xpdf_path(path_)
return
end
otherwise % User hit Cancel or closed window
break
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
% Display the error message if the pdftops executable exists but fails for some reason
if ~good && exist(path_,'file') % file exists but generates an error
fprintf('Error running %s:\n', path_);
fprintf(2,'%s\n\n',message);
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.