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
|
virati/SGView-master
|
boundedline.m
|
.m
|
SGView-master/lib/boundedline/kakearney-boundedline-pkg-2112a2b/boundedline/boundedline.m
| 10,932 |
utf_8
|
cda0c1e3f0cd78568120d513ca9571f3
|
function varargout = boundedline(varargin)
%BOUNDEDLINE Plot a line with shaded error/confidence bounds
%
% [hl, hp] = boundedline(x, y, b)
% [hl, hp] = boundedline(x, y, b, linespec)
% [hl, hp] = boundedline(x1, y1, b1, linespec1, x2, y2, b2, linespec2)
% [hl, hp] = boundedline(..., 'alpha')
% [hl, hp] = boundedline(..., ax)
% [hl, hp] = boundedline(..., 'transparency', trans)
% [hl, hp] = boundedline(..., 'orientation', orient)
% [hl, hp] = boundedline(..., 'cmap', cmap)
%
% Input variables:
%
% x, y: x and y values, either vectors of the same length, matrices
% of the same size, or vector/matrix pair where the row or
% column size of the array matches the length of the vector
% (same requirements as for plot function).
%
% b: npoint x nside x nline array. Distance from line to
% boundary, for each point along the line (dimension 1), for
% each side of the line (lower/upper or left/right, depending
% on orientation) (dimension 2), and for each plotted line
% described by the preceding x-y values (dimension 3). If
% size(b,1) == 1, the bounds will be the same for all points
% along the line. If size(b,2) == 1, the bounds will be
% symmetrical on both sides of the lines. If size(b,3) == 1,
% the same bounds will be applied to all lines described by
% the preceding x-y arrays (only applicable when either x or
% y is an array). Bounds cannot include Inf, -Inf, or NaN,
%
% linespec: line specification that determines line type, marker
% symbol, and color of the plotted lines for the preceding
% x-y values.
%
% 'alpha': if included, the bounded area will be rendered with a
% partially-transparent patch the same color as the
% corresponding line(s). If not included, the bounded area
% will be an opaque patch with a lighter shade of the
% corresponding line color.
%
% ax: handle of axis where lines will be plotted. If not
% included, the current axis will be used.
%
% transp: Scalar between 0 and 1 indicating with the transparency or
% intensity of color of the bounded area patch. Default is
% 0.2.
%
% orient: 'vert': add bounds in vertical (y) direction (default)
% 'horiz': add bounds in horizontal (x) direction
%
% cmap: n x 3 colormap array. If included, lines will be colored
% (in order of plotting) according to this colormap,
% overriding any linespec or default colors.
%
% Output variables:
%
% hl: handles to line objects
%
% hp: handles to patch objects
%
% Example:
%
% x = linspace(0, 2*pi, 50);
% y1 = sin(x);
% y2 = cos(x);
% e1 = rand(size(y1))*.5+.5;
% e2 = [.25 .5];
%
% ax(1) = subplot(2,2,1);
% [l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
% outlinebounds(l,p);
% title('Opaque bounds, with outline');
%
% ax(2) = subplot(2,2,2);
% boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
% title('Transparent bounds');
%
% ax(3) = subplot(2,2,3);
% boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
% title('Horizontal bounds');
%
% ax(4) = subplot(2,2,4);
% boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
% 'cmap', cool(4), 'transparency', 0.5);
% title('Multiple bounds using colormap');
% Copyright 2010 Kelly Kearney
%--------------------
% Parse input
%--------------------
% Alpha flag
isalpha = cellfun(@(x) ischar(x) && strcmp(x, 'alpha'), varargin);
if any(isalpha)
usealpha = true;
varargin = varargin(~isalpha);
else
usealpha = false;
end
% Axis
isax = cellfun(@(x) isscalar(x) && ishandle(x) && strcmp('axes', get(x,'type')), varargin);
if any(isax)
hax = varargin{isax};
varargin = varargin(~isax);
else
hax = gca;
end
% Transparency
[found, trans, varargin] = parseparam(varargin, 'transparency');
if ~found
trans = 0.2;
end
if ~isscalar(trans) || trans < 0 || trans > 1
error('Transparency must be scalar between 0 and 1');
end
% Orientation
[found, orient, varargin] = parseparam(varargin, 'orientation');
if ~found
orient = 'vert';
end
if strcmp(orient, 'vert')
isvert = true;
elseif strcmp(orient, 'horiz')
isvert = false;
else
error('Orientation must be ''vert'' or ''horiz''');
end
% Colormap
[hascmap, cmap, varargin] = parseparam(varargin, 'cmap');
% X, Y, E triplets, and linespec
[x,y,err,linespec] = deal(cell(0));
while ~isempty(varargin)
if length(varargin) < 3
error('Unexpected input: should be x, y, bounds triplets');
end
if all(cellfun(@isnumeric, varargin(1:3)))
x = [x varargin(1)];
y = [y varargin(2)];
err = [err varargin(3)];
varargin(1:3) = [];
else
error('Unexpected input: should be x, y, bounds triplets');
end
if ~isempty(varargin) && ischar(varargin{1})
linespec = [linespec varargin(1)];
varargin(1) = [];
else
linespec = [linespec {[]}];
end
end
%--------------------
% Reformat x and y
% for line and patch
% plotting
%--------------------
% Calculate y values for bounding lines
plotdata = cell(0,7);
htemp = figure('visible', 'off');
for ix = 1:length(x)
% Get full x, y, and linespec data for each line (easier to let plot
% check for properly-sized x and y and expand values than to try to do
% it myself)
try
if isempty(linespec{ix})
hltemp = plot(x{ix}, y{ix});
else
hltemp = plot(x{ix}, y{ix}, linespec{ix});
end
catch
close(htemp);
error('X and Y matrices and/or linespec not appropriate for line plot');
end
linedata = get(hltemp, {'xdata', 'ydata', 'marker', 'linestyle', 'color'});
nline = size(linedata,1);
% Expand bounds matrix if necessary
if nline > 1
if ndims(err{ix}) == 3
err2 = squeeze(num2cell(err{ix},[1 2]));
else
err2 = repmat(err(ix),nline,1);
end
else
err2 = err(ix);
end
% Figure out upper and lower bounds
[lo, hi] = deal(cell(nline,1));
for iln = 1:nline
x2 = linedata{iln,1};
y2 = linedata{iln,2};
nx = length(x2);
if isvert
lineval = y2;
else
lineval = x2;
end
sz = size(err2{iln});
if isequal(sz, [nx 2])
lo{iln} = lineval - err2{iln}(:,1)';
hi{iln} = lineval + err2{iln}(:,2)';
elseif isequal(sz, [nx 1])
lo{iln} = lineval - err2{iln}';
hi{iln} = lineval + err2{iln}';
elseif isequal(sz, [1 2])
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
elseif isequal(sz, [1 1])
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(:,1);
hi{iln} = lineval + err2{iln}(:,2);
elseif isequal(sz, [1 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 1]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
else
error('Error bounds must be npt x nside x nline array');
end
end
% Combine all data (xline, yline, marker, linestyle, color, lower bound
% (x or y), upper bound (x or y)
plotdata = [plotdata; linedata lo hi];
end
close(htemp);
% Override colormap
if hascmap
nd = size(plotdata,1);
cmap = repmat(cmap, ceil(nd/size(cmap,1)), 1);
cmap = cmap(1:nd,:);
plotdata(:,5) = num2cell(cmap,2);
end
%--------------------
% Plot
%--------------------
% Setup of x and y, plus line and patch properties
nline = size(plotdata,1);
[xl, yl, xp, yp, marker, lnsty, lncol, ptchcol, alpha] = deal(cell(nline,1));
for iln = 1:nline
xl{iln} = plotdata{iln,1};
yl{iln} = plotdata{iln,2};
% if isvert
% xp{iln} = [plotdata{iln,1} fliplr(plotdata{iln,1})];
% yp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% else
% xp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% yp{iln} = [plotdata{iln,2} fliplr(plotdata{iln,2})];
% end
[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7});
marker{iln} = plotdata{iln,3};
lnsty{iln} = plotdata{iln,4};
if usealpha
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = plotdata{iln,5};
alpha{iln} = trans;
else
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = interp1([0 1], [1 1 1; lncol{iln}], trans);
alpha{iln} = 1;
end
end
% Plot patches and lines
if verLessThan('matlab', '8.4.0')
[hp,hl] = deal(zeros(nline,1));
else
[hp,hl] = deal(gobjects(nline,1));
end
axes(hax);
hold all;
for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln}, ptchcol{iln}, 'facealpha', alpha{iln}, 'edgecolor', 'none');
end
for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln}, 'marker', marker{iln}, 'linestyle', lnsty{iln}, 'color', lncol{iln});
end
%--------------------
% Assign output
%--------------------
nargchk(0, 2, nargout);
if nargout >= 1
varargout{1} = hl;
end
if nargout == 2
varargout{2} = hp;
end
%--------------------
% Parse optional
% parameters
%--------------------
function [found, val, vars] = parseparam(vars, param)
isvar = cellfun(@(x) ischar(x) && strcmpi(x, param), vars);
if sum(isvar) > 1
error('Parameters can only be passed once');
end
if any(isvar)
found = true;
idx = find(isvar);
val = vars{idx+1};
vars([idx idx+1]) = [];
else
found = false;
val = [];
end
%----------------------------
% Calculate patch coordinates
%----------------------------
function [xp, yp] = calcpatch(xl, yl, isvert, lo, hi)
ismissing = any(isnan([xl;yl;lo;hi]),2);
iseq = ~verLessThan('matlab', '8.4.0') && isequal(lo, hi); % deal with zero-width bug in R2014b/R2015a
if isvert
if iseq
xp = [xl nan(size(xl))];
yp = [lo fliplr(hi)];
else
xp = [xl fliplr(xl)];
yp = [lo fliplr(hi)];
end
else
if iseq
xp = [lo fliplr(hi)];
yp = [yl nan(size(yl))];
else
xp = [lo fliplr(hi)];
yp = [yl fliplr(yl)];
end
end
if any(ismissing)
warning('boundedline:NaN', 'NaNs in bounds; inpainting');
xp = inpaint_nans(xp');
yp = inpaint_nans(yp');
end
|
github
|
virati/SGView-master
|
inpaint_nans.m
|
.m
|
SGView-master/lib/boundedline/old/inpaint_nans.m
| 12,719 |
utf_8
|
7407e1e4d4a09317af91014238711e07
|
function B=inpaint_nans(A,method)
% inpaint_nans: in-paints over nans in an array
% usage: B=inpaint_nans(A)
%
% solves approximation to one of several pdes to
% interpolate and extrapolate holes
%
% arguments (input):
% A - nxm array with some NaNs to be filled in
%
% method - (OPTIONAL) scalar numeric flag - specifies
% which approach (or physical metaphor to use
% for the interpolation.) All methods are capable
% of extrapolation, some are better than others.
% There are also speed differences, as well as
% accuracy differences for smooth surfaces.
%
% methods {0,1,2} use a simple plate metaphor
% methods {3} use a better plate equation,
% but will be slower
% methods 4 use a spring metaphor
%
% method == 0 --> (DEFAULT) see method 1, but
% this method does not build as large of a
% linear system in the case of only a few
% NaNs in a large array.
% Extrapolation behavior is linear.
%
% method == 1 --> simple approach, applies del^2
% over the entire array, then drops those parts
% of the array which do not have any contact with
% NaNs. Uses a least squares approach, but it
% does not touch existing points.
% In the case of small arrays, this method is
% quite fast as it does very little extra work.
% Extrapolation behavior is linear.
%
% method == 2 --> uses del^2, but solving a direct
% linear system of equations for nan elements.
% This method will be the fastest possible for
% large systems since it uses the sparsest
% possible system of equations. Not a least
% squares approach, so it may be least robust
% to noise on the boundaries of any holes.
% This method will also be least able to
% interpolate accurately for smooth surfaces.
% Extrapolation behavior is linear.
%
% method == 3 --+ See method 0, but uses del^4 for
% the interpolating operator. This may result
% in more accurate interpolations, at some cost
% in speed.
%
% method == 4 --+ Uses a spring metaphor. Assumes
% springs (with a nominal length of zero)
% connect each node with every neighbor
% (horizontally, vertically and diagonally)
% Since each node tries to be like its neighbors,
% extrapolation is as a constant function where
% this is consistent with the neighboring nodes.
%
%
% arguments (output):
% B - nxm array with NaNs replaced
% I always need to know which elements are NaN,
% and what size the array is for any method
[n,m]=size(A);
nm=n*m;
k=isnan(A(:));
% list the nodes which are known, and which will
% be interpolated
nan_list=find(k);
known_list=find(~k);
% how many nans overall
nan_count=length(nan_list);
% convert NaN indices to (r,c) form
% nan_list==find(k) are the unrolled (linear) indices
% (row,column) form
[nr,nc]=ind2sub([n,m],nan_list);
% both forms of index in one array:
% column 1 == unrolled index
% column 2 == row index
% column 3 == column index
nan_list=[nan_list,nr,nc];
% supply default method
if (nargin<2)|isempty(method)
method = 0;
elseif ~ismember(method,0:4)
error 'If supplied, method must be one of: {0,1,2,3,4}.'
end
% for different methods
switch method
case 0
% The same as method == 1, except only work on those
% elements which are NaN, or at least touch a NaN.
% horizontal and vertical neighbors only
talks_to = [-1 0;0 -1;1 0;0 1];
neighbors_list=identify_neighbors(n,m,nan_list,talks_to);
% list of all nodes we have identified
all_list=[nan_list;neighbors_list];
% generate sparse array with second partials on row
% variable for each element in either list, but only
% for those nodes which have a row index > 1 or < n
L = find((all_list(:,2) > 1) & (all_list(:,2) < n));
nl=length(L);
if nl>0
fda=sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-1 0 1],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
else
fda=spalloc(n*m,n*m,size(all_list,1)*5);
end
% 2nd partials on column index
L = find((all_list(:,3) > 1) & (all_list(:,3) < m));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3)+repmat([-n 0 n],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list(:,1)),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 1
% least squares approach with del^2. Build system
% for every array element as an unknown, and then
% eliminate those which are knowns.
% Build sparse matrix approximating del^2 for
% every element in A.
% Compute finite difference for second partials
% on row variable first
[i,j]=ndgrid(2:(n-1),1:m);
ind=i(:)+(j(:)-1)*n;
np=(n-2)*m;
fda=sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ...
repmat([1 -2 1],np,1),n*m,n*m);
% now second partials on column variable
[i,j]=ndgrid(1:n,2:(m-1));
ind=i(:)+(j(:)-1)*n;
np=n*(m-2);
fda=fda+sparse(repmat(ind,1,3),[ind-n,ind,ind+n], ...
repmat([1 -2 1],np,1),nm,nm);
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 2
% Direct solve for del^2 BVP across holes
% generate sparse array with second partials on row
% variable for each nan element, only for those nodes
% which have a row index > 1 or < n
L = find((nan_list(:,2) > 1) & (nan_list(:,2) < n));
nl=length(L);
if nl>0
fda=sparse(repmat(nan_list(L,1),1,3), ...
repmat(nan_list(L,1),1,3)+repmat([-1 0 1],nl,1), ...
repmat([1 -2 1],nl,1),n*m,n*m);
else
fda=spalloc(n*m,n*m,size(nan_list,1)*5);
end
% 2nd partials on column index
L = find((nan_list(:,3) > 1) & (nan_list(:,3) < m));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(nan_list(L,1),1,3), ...
repmat(nan_list(L,1),1,3)+repmat([-n 0 n],nl,1), ...
repmat([1 -2 1],nl,1),n*m,n*m);
end
% fix boundary conditions at extreme corners
% of the array in case there were nans there
if ismember(1,nan_list(:,1))
fda(1,[1 2 n+1])=[-2 1 1];
end
if ismember(n,nan_list(:,1))
fda(n,[n, n-1,n+n])=[-2 1 1];
end
if ismember(nm-n+1,nan_list(:,1))
fda(nm-n+1,[nm-n+1,nm-n+2,nm-n])=[-2 1 1];
end
if ismember(nm,nan_list(:,1))
fda(nm,[nm,nm-1,nm-n])=[-2 1 1];
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
% and solve...
B=A;
k=nan_list(:,1);
B(k)=fda(k,k)\rhs(k);
case 3
% The same as method == 0, except uses del^4 as the
% interpolating operator.
% del^4 template of neighbors
talks_to = [-2 0;-1 -1;-1 0;-1 1;0 -2;0 -1; ...
0 1;0 2;1 -1;1 0;1 1;2 0];
neighbors_list=identify_neighbors(n,m,nan_list,talks_to);
% list of all nodes we have identified
all_list=[nan_list;neighbors_list];
% generate sparse array with del^4, but only
% for those nodes which have a row & column index
% >= 3 or <= n-2
L = find( (all_list(:,2) >= 3) & ...
(all_list(:,2) <= (n-2)) & ...
(all_list(:,3) >= 3) & ...
(all_list(:,3) <= (m-2)));
nl=length(L);
if nl>0
% do the entire template at once
fda=sparse(repmat(all_list(L,1),1,13), ...
repmat(all_list(L,1),1,13) + ...
repmat([-2*n,-n-1,-n,-n+1,-2,-1,0,1,2,n-1,n,n+1,2*n],nl,1), ...
repmat([1 2 -8 2 1 -8 20 -8 1 2 -8 2 1],nl,1),nm,nm);
else
fda=spalloc(n*m,n*m,size(all_list,1)*5);
end
% on the boundaries, reduce the order around the edges
L = find((((all_list(:,2) == 2) | ...
(all_list(:,2) == (n-1))) & ...
(all_list(:,3) >= 2) & ...
(all_list(:,3) <= (m-1))) | ...
(((all_list(:,3) == 2) | ...
(all_list(:,3) == (m-1))) & ...
(all_list(:,2) >= 2) & ...
(all_list(:,2) <= (n-1))));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,5), ...
repmat(all_list(L,1),1,5) + ...
repmat([-n,-1,0,+1,n],nl,1), ...
repmat([1 1 -4 1 1],nl,1),nm,nm);
end
L = find( ((all_list(:,2) == 1) | ...
(all_list(:,2) == n)) & ...
(all_list(:,3) >= 2) & ...
(all_list(:,3) <= (m-1)));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3) + ...
repmat([-n,0,n],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
L = find( ((all_list(:,3) == 1) | ...
(all_list(:,3) == m)) & ...
(all_list(:,2) >= 2) & ...
(all_list(:,2) <= (n-1)));
nl=length(L);
if nl>0
fda=fda+sparse(repmat(all_list(L,1),1,3), ...
repmat(all_list(L,1),1,3) + ...
repmat([-1,0,1],nl,1), ...
repmat([1 -2 1],nl,1),nm,nm);
end
% eliminate knowns
rhs=-fda(:,known_list)*A(known_list);
k=find(any(fda(:,nan_list(:,1)),2));
% and solve...
B=A;
B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k);
case 4
% Spring analogy
% interpolating operator.
% list of all springs between a node and a horizontal
% or vertical neighbor
hv_list=[-1 -1 0;1 1 0;-n 0 -1;n 0 1];
hv_springs=[];
for i=1:4
hvs=nan_list+repmat(hv_list(i,:),nan_count,1);
k=(hvs(:,2)>=1) & (hvs(:,2)<=n) & (hvs(:,3)>=1) & (hvs(:,3)<=m);
hv_springs=[hv_springs;[nan_list(k,1),hvs(k,1)]];
end
% delete replicate springs
hv_springs=unique(sort(hv_springs,2),'rows');
% build sparse matrix of connections, springs
% connecting diagonal neighbors are weaker than
% the horizontal and vertical springs
nhv=size(hv_springs,1);
springs=sparse(repmat((1:nhv)',1,2),hv_springs, ...
repmat([1 -1],nhv,1),nhv,nm);
% eliminate knowns
rhs=-springs(:,known_list)*A(known_list);
% and solve...
B=A;
B(nan_list(:,1))=springs(:,nan_list(:,1))\rhs;
end
% ====================================================
% end of main function
% ====================================================
% ====================================================
% begin subfunctions
% ====================================================
function neighbors_list=identify_neighbors(n,m,nan_list,talks_to)
% identify_neighbors: identifies all the neighbors of
% those nodes in nan_list, not including the nans
% themselves
%
% arguments (input):
% n,m - scalar - [n,m]=size(A), where A is the
% array to be interpolated
% nan_list - array - list of every nan element in A
% nan_list(i,1) == linear index of i'th nan element
% nan_list(i,2) == row index of i'th nan element
% nan_list(i,3) == column index of i'th nan element
% talks_to - px2 array - defines which nodes communicate
% with each other, i.e., which nodes are neighbors.
%
% talks_to(i,1) - defines the offset in the row
% dimension of a neighbor
% talks_to(i,2) - defines the offset in the column
% dimension of a neighbor
%
% For example, talks_to = [-1 0;0 -1;1 0;0 1]
% means that each node talks only to its immediate
% neighbors horizontally and vertically.
%
% arguments(output):
% neighbors_list - array - list of all neighbors of
% all the nodes in nan_list
if ~isempty(nan_list)
% use the definition of a neighbor in talks_to
nan_count=size(nan_list,1);
talk_count=size(talks_to,1);
nn=zeros(nan_count*talk_count,2);
j=[1,nan_count];
for i=1:talk_count
nn(j(1):j(2),:)=nan_list(:,2:3) + ...
repmat(talks_to(i,:),nan_count,1);
j=j+nan_count;
end
% drop those nodes which fall outside the bounds of the
% original array
L = (nn(:,1)<1)|(nn(:,1)>n)|(nn(:,2)<1)|(nn(:,2)>m);
nn(L,:)=[];
% form the same format 3 column array as nan_list
neighbors_list=[sub2ind([n,m],nn(:,1),nn(:,2)),nn];
% delete replicates in the neighbors list
neighbors_list=unique(neighbors_list,'rows');
% and delete those which are also in the list of NaNs.
neighbors_list=setdiff(neighbors_list,nan_list,'rows');
else
neighbors_list=[];
end
|
github
|
virati/SGView-master
|
boundedline.m
|
.m
|
SGView-master/lib/boundedline/old/boundedline.m
| 10,524 |
utf_8
|
16b1d04028aded72eaf869f149fcddd7
|
function varargout = boundedline(varargin)
%BOUNDEDLINE Plot a line with shaded error/confidence bounds
%
% [hl, hp] = boundedline(x, y, b)
% [hl, hp] = boundedline(x, y, b, linespec)
% [hl, hp] = boundedline(x1, y1, b1, linespec1, x2, y2, b2, linespec2)
% [hl, hp] = boundedline(..., 'alpha')
% [hl, hp] = boundedline(..., ax)
% [hl, hp] = boundedline(..., 'transparency', trans)
% [hl, hp] = boundedline(..., 'orientation', orient)
% [hl, hp] = boundedline(..., 'cmap', cmap)
%
% Input variables:
%
% x, y: x and y values, either vectors of the same length, matrices
% of the same size, or vector/matrix pair where the row or
% column size of the array matches the length of the vector
% (same requirements as for plot function).
%
% b: npoint x nside x nline array. Distance from line to
% boundary, for each point along the line (dimension 1), for
% each side of the line (lower/upper or left/right, depending
% on orientation) (dimension 2), and for each plotted line
% described by the preceding x-y values (dimension 3). If
% size(b,1) == 1, the bounds will be the same for all points
% along the line. If size(b,2) == 1, the bounds will be
% symmetrical on both sides of the lines. If size(b,3) == 1,
% the same bounds will be applied to all lines described by
% the preceding x-y arrays (only applicable when either x or
% y is an array). Bounds cannot include Inf, -Inf, or NaN,
%
% linespec: line specification that determines line type, marker
% symbol, and color of the plotted lines for the preceding
% x-y values.
%
% 'alpha': if included, the bounded area will be rendered with a
% partially-transparent patch the same color as the
% corresponding line(s). If not included, the bounded area
% will be an opaque patch with a lighter shade of the
% corresponding line color.
%
% ax: handle of axis where lines will be plotted. If not
% included, the current axis will be used.
%
% transp: Scalar between 0 and 1 indicating with the transparency or
% intensity of color of the bounded area patch. Default is
% 0.2.
%
% orient: 'vert': add bounds in vertical (y) direction (default)
% 'horiz': add bounds in horizontal (x) direction
%
% cmap: n x 3 colormap array. If included, lines will be colored
% (in order of plotting) according to this colormap,
% overriding any linespec or default colors.
%
% Output variables:
%
% hl: handles to line objects
%
% hp: handles to patch objects
%
% Example:
%
% x = linspace(0, 2*pi, 50);
% y1 = sin(x);
% y2 = cos(x);
% e1 = rand(size(y1))*.5+.5;
% e2 = [.25 .5];
%
% ax(1) = subplot(2,2,1);
% [l,p] = boundedline(x, y1, e1, '-b*', x, y2, e2, '--ro');
% outlinebounds(l,p);
% title('Opaque bounds, with outline');
%
% ax(2) = subplot(2,2,2);
% boundedline(x, [y1;y2], rand(length(y1),2,2)*.5+.5, 'alpha');
% title('Transparent bounds');
%
% ax(3) = subplot(2,2,3);
% boundedline([y1;y2], x, e1(1), 'orientation', 'horiz')
% title('Horizontal bounds');
%
% ax(4) = subplot(2,2,4);
% boundedline(x, repmat(y1, 4,1), permute(0.5:-0.1:0.2, [3 1 2]), ...
% 'cmap', cool(4), 'transparency', 0.5);
% title('Multiple bounds using colormap');
% Copyright 2010 Kelly Kearney
%--------------------
% Parse input
%--------------------
% Alpha flag
isalpha = cellfun(@(x) ischar(x) && strcmp(x, 'alpha'), varargin);
if any(isalpha)
usealpha = true;
varargin = varargin(~isalpha);
else
usealpha = false;
end
% Axis
isax = cellfun(@(x) isscalar(x) && ishandle(x) && strcmp('axes', get(x,'type')), varargin);
if any(isax)
hax = varargin{isax};
varargin = varargin(~isax);
else
hax = gca;
end
% Transparency
[found, trans, varargin] = parseparam(varargin, 'transparency');
if ~found
trans = 0.2;
end
if ~isscalar(trans) || trans < 0 || trans > 1
error('Transparency must be scalar between 0 and 1');
end
% Orientation
[found, orient, varargin] = parseparam(varargin, 'orientation');
if ~found
orient = 'vert';
end
if strcmp(orient, 'vert')
isvert = true;
elseif strcmp(orient, 'horiz')
isvert = false;
else
error('Orientation must be ''vert'' or ''horiz''');
end
% Colormap
[hascmap, cmap, varargin] = parseparam(varargin, 'cmap');
% X, Y, E triplets, and linespec
[x,y,err,linespec] = deal(cell(0));
while ~isempty(varargin)
if length(varargin) < 3
error('Unexpected input: should be x, y, bounds triplets');
end
if all(cellfun(@isnumeric, varargin(1:3)))
x = [x varargin(1)];
y = [y varargin(2)];
err = [err varargin(3)];
varargin(1:3) = [];
else
error('Unexpected input: should be x, y, bounds triplets');
end
if ~isempty(varargin) && ischar(varargin{1})
linespec = [linespec varargin(1)];
varargin(1) = [];
else
linespec = [linespec {[]}];
end
end
%--------------------
% Reformat x and y
% for line and patch
% plotting
%--------------------
% Calculate y values for bounding lines
plotdata = cell(0,7);
htemp = figure('visible', 'off');
for ix = 1:length(x)
% Get full x, y, and linespec data for each line (easier to let plot
% check for properly-sized x and y and expand values than to try to do
% it myself)
try
if isempty(linespec{ix})
hltemp = plot(x{ix}, y{ix});
else
hltemp = plot(x{ix}, y{ix}, linespec{ix});
end
catch
close(htemp);
error('X and Y matrices and/or linespec not appropriate for line plot');
end
linedata = get(hltemp, {'xdata', 'ydata', 'marker', 'linestyle', 'color'});
nline = size(linedata,1);
% Expand bounds matrix if necessary
if nline > 1
if ndims(err{ix}) == 3
err2 = squeeze(num2cell(err{ix},[1 2]));
else
err2 = repmat(err(ix),nline,1);
end
else
err2 = err(ix);
end
% Figure out upper and lower bounds
[lo, hi] = deal(cell(nline,1));
for iln = 1:nline
x2 = linedata{iln,1};
y2 = linedata{iln,2};
nx = length(x2);
if isvert
lineval = y2;
else
lineval = x2;
end
sz = size(err2{iln});
if isequal(sz, [nx 2])
lo{iln} = lineval - err2{iln}(:,1)';
hi{iln} = lineval + err2{iln}(:,2)';
elseif isequal(sz, [nx 1])
lo{iln} = lineval - err2{iln}';
hi{iln} = lineval + err2{iln}';
elseif isequal(sz, [1 2])
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
elseif isequal(sz, [1 1])
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(:,1);
hi{iln} = lineval + err2{iln}(:,2);
elseif isequal(sz, [1 nx]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln};
hi{iln} = lineval + err2{iln};
elseif isequal(sz, [2 1]) % not documented, but accepted anyways
lo{iln} = lineval - err2{iln}(1);
hi{iln} = lineval + err2{iln}(2);
else
error('Error bounds must be npt x nside x nline array');
end
end
% Combine all data (xline, yline, marker, linestyle, color, lower bound
% (x or y), upper bound (x or y)
plotdata = [plotdata; linedata lo hi];
end
close(htemp);
% Override colormap
if hascmap
nd = size(plotdata,1);
cmap = repmat(cmap, ceil(nd/size(cmap,1)), 1);
cmap = cmap(1:nd,:);
plotdata(:,5) = num2cell(cmap,2);
end
%--------------------
% Plot
%--------------------
% Setup of x and y, plus line and patch properties
nline = size(plotdata,1);
[xl, yl, xp, yp, marker, lnsty, lncol, ptchcol, alpha] = deal(cell(nline,1));
for iln = 1:nline
xl{iln} = plotdata{iln,1};
yl{iln} = plotdata{iln,2};
% if isvert
% xp{iln} = [plotdata{iln,1} fliplr(plotdata{iln,1})];
% yp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% else
% xp{iln} = [plotdata{iln,6} fliplr(plotdata{iln,7})];
% yp{iln} = [plotdata{iln,2} fliplr(plotdata{iln,2})];
% end
[xp{iln}, yp{iln}] = calcpatch(plotdata{iln,1}, plotdata{iln,2}, isvert, plotdata{iln,6}, plotdata{iln,7});
marker{iln} = plotdata{iln,3};
lnsty{iln} = plotdata{iln,4};
if usealpha
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = plotdata{iln,5};
alpha{iln} = trans;
else
lncol{iln} = plotdata{iln,5};
ptchcol{iln} = interp1([0 1], [1 1 1; lncol{iln}], trans);
alpha{iln} = 1;
end
end
% Plot patches and lines
[hp,hl] = deal(zeros(nline,1));
axes(hax);
hold all;
for iln = 1:nline
hp(iln) = patch(xp{iln}, yp{iln}, ptchcol{iln}, 'facealpha', alpha{iln}, 'edgecolor', 'none');
end
for iln = 1:nline
hl(iln) = line(xl{iln}, yl{iln}, 'marker', marker{iln}, 'linestyle', lnsty{iln}, 'color', lncol{iln});
end
%--------------------
% Assign output
%--------------------
nargchk(0, 2, nargout);
if nargout >= 1
varargout{1} = hl;
end
if nargout == 2
varargout{2} = hp;
end
%--------------------
% Parse optional
% parameters
%--------------------
function [found, val, vars] = parseparam(vars, param)
isvar = cellfun(@(x) ischar(x) && strcmpi(x, param), vars);
if sum(isvar) > 1
error('Parameters can only be passed once');
end
if any(isvar)
found = true;
idx = find(isvar);
val = vars{idx+1};
vars([idx idx+1]) = [];
else
found = false;
val = [];
end
%----------------------------
% Calculate patch coordinates
%----------------------------
function [xp, yp] = calcpatch(xl, yl, isvert, lo, hi)
ismissing = any(isnan([xl;yl;lo;hi]),2);
if isvert
xp = [xl fliplr(xl)];
yp = [lo fliplr(hi)];
else
xp = [lo fliplr(hi)];
yp = [yl fliplr(yl)];
end
if any(ismissing)
warning('NaNs in bounds; inpainting');
xp = inpaint_nans(xp');
yp = inpaint_nans(yp');
end
|
github
|
icemansina/LSTM-CF-master
|
prepare_batch.m
|
.m
|
LSTM-CF-master/matlab/caffe/prepare_batch.m
| 1,298 |
utf_8
|
68088231982895c248aef25b4886eab0
|
% ------------------------------------------------------------------------
function images = prepare_batch(image_files,IMAGE_MEAN,batch_size)
% ------------------------------------------------------------------------
if nargin < 2
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
end
num_images = length(image_files);
if nargin < 3
batch_size = num_images;
end
IMAGE_DIM = 256;
CROPPED_DIM = 227;
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
center = floor(indices(2) / 2)+1;
num_images = length(image_files);
images = zeros(CROPPED_DIM,CROPPED_DIM,3,batch_size,'single');
parfor i=1:num_images
% read file
fprintf('%c Preparing %s\n',13,image_files{i});
try
im = imread(image_files{i});
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% Transform GRAY to RGB
if size(im,3) == 1
im = cat(3,im,im,im);
end
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% Crop the center of the image
images(:,:,:,i) = permute(im(center:center+CROPPED_DIM-1,...
center:center+CROPPED_DIM-1,:),[2 1 3]);
catch
warning('Problems with file',image_files{i});
end
end
|
github
|
icemansina/LSTM-CF-master
|
matcaffe_demo_vgg.m
|
.m
|
LSTM-CF-master/matlab/caffe/matcaffe_demo_vgg.m
| 3,036 |
utf_8
|
f836eefad26027ac1be6e24421b59543
|
function scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
%
% Demo of the matlab wrapper using the networks described in the BMVC-2014 paper "Return of the Devil in the Details: Delving Deep into Convolutional Nets"
%
% INPUT
% im - color image as uint8 HxWx3
% use_gpu - 1 to use the GPU, 0 to use the CPU
% model_def_file - network configuration (.prototxt file)
% model_file - network weights (.caffemodel file)
% mean_file - mean BGR image as uint8 HxWx3 (.mat file)
%
% OUTPUT
% scores 1000-dimensional ILSVRC score vector
%
% EXAMPLE USAGE
% model_def_file = 'zoo/VGG_CNN_F_deploy.prototxt';
% model_file = 'zoo/VGG_CNN_F.caffemodel';
% mean_file = 'zoo/VGG_mean.mat';
% use_gpu = true;
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file);
%
% NOTES
% the image crops are prepared as described in the paper (the aspect ratio is preserved)
%
% PREREQUISITES
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% init caffe network (spews logging info)
matcaffe_init(use_gpu, model_def_file, model_file);
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im, mean_file)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
% size(scores)
scores = squeeze(scores);
% scores = mean(scores,2);
% [~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im, mean_file)
% ------------------------------------------------------------------------
IMAGE_DIM = 256;
CROPPED_DIM = 224;
d = load(mean_file);
IMAGE_MEAN = d.image_mean;
% resize to fixed input size
im = single(im);
if size(im, 1) < size(im, 2)
im = imresize(im, [IMAGE_DIM NaN]);
else
im = imresize(im, [NaN IMAGE_DIM]);
end
% RGB -> BGR
im = im(:, :, [3 2 1]);
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices_y = [0 size(im,1)-CROPPED_DIM] + 1;
indices_x = [0 size(im,2)-CROPPED_DIM] + 1;
center_y = floor(indices_y(2) / 2)+1;
center_x = floor(indices_x(2) / 2)+1;
curr = 1;
for i = indices_y
for j = indices_x
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :)-IMAGE_MEAN, [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
images(:,:,:,5) = ...
permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:)-IMAGE_MEAN, ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
github
|
icemansina/LSTM-CF-master
|
matcaffe_demo.m
|
.m
|
LSTM-CF-master/matlab/caffe/matcaffe_demo.m
| 3,344 |
utf_8
|
669622769508a684210d164ac749a614
|
function [scores, maxlabel] = matcaffe_demo(im, use_gpu)
% scores = matcaffe_demo(im, use_gpu)
%
% Demo of the matlab wrapper using the ILSVRC network.
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format:
% % convert from uint8 to single
% im = single(im);
% % reshape to a fixed size (e.g., 227x227)
% im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % permute from RGB to BGR and subtract the data mean (already in BGR)
% im = im(:,:,[3 2 1]) - data_mean;
% % flip width and height to make width the fastest dimension
% im = permute(im, [2 1 3]);
% If you have multiple images, cat them with cat(4, ...)
% The actual forward function. It takes in a cell array of 4-D arrays as
% input and outputs a cell array.
% init caffe network (spews logging info)
if exist('use_gpu', 'var')
matcaffe_init(use_gpu);
else
matcaffe_init();
end
if nargin < 1
% For demo purposes we will use the peppers image
im = imread('peppers.png');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
size(scores)
scores = squeeze(scores);
scores = mean(scores,2);
[~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im)
% ------------------------------------------------------------------------
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
curr = 1;
for i = indices
for j = indices
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
center = floor(indices(2) / 2)+1;
images(:,:,:,5) = ...
permute(im(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:), ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
github
|
icemansina/LSTM-CF-master
|
matcaffe_demo_vgg_mean_pix.m
|
.m
|
LSTM-CF-master/matlab/caffe/matcaffe_demo_vgg_mean_pix.m
| 3,069 |
utf_8
|
04b831d0f205ef0932c4f3cfa930d6f9
|
function scores = matcaffe_demo_vgg_mean_pix(im, use_gpu, model_def_file, model_file)
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file)
%
% Demo of the matlab wrapper based on the networks used for the "VGG" entry
% in the ILSVRC-2014 competition and described in the tech. report
% "Very Deep Convolutional Networks for Large-Scale Image Recognition"
% http://arxiv.org/abs/1409.1556/
%
% INPUT
% im - color image as uint8 HxWx3
% use_gpu - 1 to use the GPU, 0 to use the CPU
% model_def_file - network configuration (.prototxt file)
% model_file - network weights (.caffemodel file)
%
% OUTPUT
% scores 1000-dimensional ILSVRC score vector
%
% EXAMPLE USAGE
% model_def_file = 'zoo/deploy.prototxt';
% model_file = 'zoo/model.caffemodel';
% use_gpu = true;
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file);
%
% NOTES
% mean pixel subtraction is used instead of the mean image subtraction
%
% PREREQUISITES
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% init caffe network (spews logging info)
matcaffe_init(use_gpu, model_def_file, model_file);
% mean BGR pixel
mean_pix = [103.939, 116.779, 123.68];
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im, mean_pix)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
% size(scores)
scores = squeeze(scores);
% scores = mean(scores,2);
% [~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im, mean_pix)
% ------------------------------------------------------------------------
IMAGE_DIM = 256;
CROPPED_DIM = 224;
% resize to fixed input size
im = single(im);
if size(im, 1) < size(im, 2)
im = imresize(im, [IMAGE_DIM NaN]);
else
im = imresize(im, [NaN IMAGE_DIM]);
end
% RGB -> BGR
im = im(:, :, [3 2 1]);
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices_y = [0 size(im,1)-CROPPED_DIM] + 1;
indices_x = [0 size(im,2)-CROPPED_DIM] + 1;
center_y = floor(indices_y(2) / 2)+1;
center_x = floor(indices_x(2) / 2)+1;
curr = 1;
for i = indices_y
for j = indices_x
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
images(:,:,:,5) = ...
permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:), ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
% mean BGR pixel subtraction
for c = 1:3
images(:, :, c, :) = images(:, :, c, :) - mean_pix(c);
end
|
github
|
jinw1004/DeepList-master
|
slmetric_pw.m
|
.m
|
DeepList-master/code/patchmatch/slmetric_pw.m
| 5,784 |
utf_8
|
db4423a1315c3056bca4cabf694d42f4
|
function M = slmetric_pw(X1, X2, mtype, varargin)
%SLMETRIC_PW Compute the metric between column vectors pairwisely
%
% $ Syntax $
% - M = slmetric_pw(X1, X2, mtype);
% - M = slmetric_pw(X1, X2, mtype, ...);
%
% $ Description $
% - M = slmetric_pw(X1, X2, mtype) Computes the metrics between
% column vectors of X1 and X2 pairwisely, using the metric
% specified by mtype. If X1 has n1 columns, X2 has n2 columns, then
% the resultant M would be of size n1 x n2. The entry at i-th row
% and j-th column of M represents the metric between X1(:, i) and
% X2(:, j).
%
% - M = slmetric_pw(X1, X2, mtype, ...) Some metric types requires
% extra parameters, which should be specified in params.
%
% - The supported metrics of this function are listed as follows:
% \*
% \t Table 1. The supported metrics \\
% \h name & description \\
% 'eucdist' & Euclidean distance: ||x - y|| \\
% 'sqdist' & Square of Euclidean distance: ||x - y||^2 \\
% 'dotprod' & Canonical dot product: <x,y> = x^T * y \\
% 'nrmcorr' & Normalized correlation (cosine angle):
% (x^T * y ) / (||x|| * ||y||) \\
% 'angle' & Angle between two vectors (in radian) \\
% 'quadfrm' & Quadratic form: x^T * Q * y
% Q is specified in the 1st extra parameter \\
% 'quaddiff' & Quadratic form of difference:
% (x - y)^T * Q * (x - y),
% Q is specified in the 1st extra parameter \\
% 'cityblk' & City block distance (abssum of difference) \\
% 'maxdiff' & Maximum absolute difference \\
% 'mindiff' & Minimum absolute difference \\
% 'wsqdist' & Weighted square of Euclidean distance \\
% \sum_i w_i (x_i - y_i)^2, w = (w_1, ..., w_d)
% the weights w is specified in 1st extra parameter
% as a length-d column vector \\
% \*
%
% $ Remarks $
% - X1 and X2 are both matrices with n1 column vectors and n2 column
% vectors respectively. Then the resultant matrix M will be a n1 * n2
% matrix. The entry at i-th row and j-th column of M is the metric between
% the i-th column vector in X1 and the j-th column vector in X2.
%
% $ History $
% - Created by Dahua Lin on Dec 06th, 2005
% - Modified by Dahua Lin on Apr 21st, 2005
% - regularize the error reporting
% - Modified by Dahua Lin on Sep 11st, 2005
% - completely rewrite the core codes based on new mex computation
% cores, and the runtime efficiency in both time and space is
% significantly increased.
%
%% parse and verify input arguments
if nargin < 3
raise_lackinput('slmetric_pw', 3);
end
mtype = lower(mtype);
%% compute
switch mtype
case {'eucdist', 'sqdist'}
checkdim(X1, X2);
sqs1 = sum(X1 .* X1, 1)';
sqs2 = sum(X2 .* X2, 1);
M = (-2) * X1' * X2;
M = sladdrowcols(M, sqs2, sqs1);
M(M < 0) = 0;
if strcmp(mtype, 'eucdist')
M = sqrt(M);
end
case 'dotprod'
checkdim(X1, X2);
M = X1' * X2;
case {'nrmcorr', 'angle'}
checkdim(X1, X2);
M = X1' * X2;
f1 = sqrt(sum(X1 .* X1, 1))';
f2 = sqrt(sum(X2 .* X2, 1));
f1(f1 < eps) = eps; % prevent from being zeros
f2(f2 < eps) = eps;
f1 = 1 ./ f1;
f2 = 1 ./ f2;
M = slmulrowcols(M, f2, f1);
if strcmp(mtype, 'angle0')
M = real(acos(M));
end
case 'quadfrm'
% parse parameters
Q = varargin{1};
[d1, d2] = size(Q);
if size(X1, 1) ~= d1 || size(X2, 1) ~= d2
error('sltoolbox:sizmismatch', ...
'The dimensions of X1 and X2 are not consistent with Q');
end
% compute
M = X1' * Q * X2;
case 'quaddiff'
% parse parameters
d = checkdim(X1, X2);
Q = varargin{1};
if ~isequal(size(Q), [d, d])
error('sltoolbox:dimmismatch', ...
'The dimensions of X1 and X2 are not consistent with Q');
end
% compute
qs1 = sum(X1 .* (Q * X1), 1)';
qs2 = sum(X2 .* (Q * X2), 1);
M = X1' * (-(Q + Q')) * X2;
M = sladdrowcols(M, qs2, qs1);
case 'cityblk'
M = sldiff_pw(X1, X2, 'abssum');
case 'maxdiff'
M = sldiff_pw(X1, X2, 'maxdiff');
case 'mindiff'
M = sldiff_pw(X1, X2, 'mindiff');
case 'wsqdist'
% parse parameters
d = checkdim(X1, X2);
w = varargin{1};
if ~isequal(size(w), [d, 1])
error('sltoolbox:sizmismatch', ...
'w is not a proper size column vector');
end
% compute
wX1 = slmulvec(X1, w, 1);
qs1 = sum(wX1 .* X1, 1)';
clear wX1;
wX2 = slmulvec(X2, w, 1);
qs2 = sum(wX2 .* X2, 1);
M = (-2) * X1' * wX2;
clear wX2;
M = sladdrowcols(M, qs2, qs1);
otherwise
error('sltoolbox:invalid_type', 'Unknown metric type %s', mtype);
end
%% Auxiliary function
function d = checkdim(X1, X2)
d = size(X1, 1);
if d ~= size(X2, 1)
error('sltoolbox:sizmismatch', ...
'X1 and X2 have different sample dimensions');
end
|
github
|
jinw1004/DeepList-master
|
vl_simplenn_display.m
|
.m
|
DeepList-master/code/matConvNet/vl_simplenn_display.m
| 2,913 |
utf_8
|
a7b610d48d096a3b7dbd70fa131290f0
|
function vl_simplenn_display(net)
% VL_SIMPLENN_DISPLAY Simple CNN statistics
% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.
% Copyright (C) 2014 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
for w={'layer', 'type', 'support', 'stride', 'padding', 'field', 'mem'}
switch char(w)
case 'type', s = 'type' ;
case 'stride', s = 'stride' ;
case 'padding', s = 'pad' ;
case 'field', s = 'field' ;
case 'mem', s = 'c//g mem' ;
otherwise, s = char(w) ;
end
fprintf('%10s',s) ;
for l=1:numel(net.layers)
ly=net.layers{l} ;
switch char(w)
case 'layer', s=sprintf('%d', l) ;
case 'type'
switch ly.type
case 'normalize', s='nrm';
case 'pool', if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
case 'conv', s='cnv' ;
case 'softmax', s='sftm' ;
case 'loss', s='lloss' ;
case 'softmaxloss', 'sftml' ;
otherwise s=ly.type ;
end
case 'support'
switch ly.type
case 'conv', support(1:2,l) = [size(ly.filters,1) ; size(ly.filters,2)] ;
case 'pool', support(1:2,l) = ly.pool(:) ;
otherwise, support(1:2,l) = [1;1] ;
end
s=sprintf('%dx%d', support(1,l), support(2,l)) ;
case 'stride'
switch ly.type
case {'conv', 'pool'}
if numel(ly.stride) == 1
stride(1:2,l) = ly.stride ;
else
stride(1:2,l) = ly.stride(:) ;
end
otherwise, stride(:,l)=1 ;
end
s=sprintf('%dx%d', stride(1,l), stride(2,l)) ;
case 'pad'
switch ly.type
case {'conv', 'pool'}
if numel(ly.pad) == 1
pad(1:2,l) = ly.pad ;
else
pad(1:2,l) = ly.pad(:) ;
end
otherwise, pad(:,l)=1 ;
end
s=sprintf('%dx%d', pad(1,l), pad(2,l)) ;
case 'field'
for i=1:2
field(i,l) = sum(cumprod([1 stride(i,1:l-1)]).*(support(i,1:l)-1))+1 ;
end
s=sprintf('%dx%d', field(1,l), field(2,l)) ;
case 'mem'
[a,b] = xmem(ly) ;
mem(1:2,l) = [a;b] ;
s=sprintf('%.0f/%.0f', a/1024^2, b/1024^2) ;
end
fprintf('|%7s', s) ;
end
fprintf('|\n') ;
end
fprintf('total CPU/GPU memory: %.1f/%1.f MB\n', sum(mem(1,:))/1024^2, sum(mem(2,:))/1024^2) ;
function [cpuMem,gpuMem]=xmem(s)
cpuMem = 0 ;
gpuMem = 0 ;
for f=fieldnames(s)'
f = char(f) ;
t=s.(f) ;
if isstruct(t)
[a,b] = xmem(t) ;
cpuMem = cpuMem + a ;
gpuMem = gpuMem + b ;
m = m + xmem(t) ;
continue ;
end
if isnumeric(t)
if isa(t,'gpuArray')
gpuMem = gpuMem + 4 * numel(t) ;
else
cpuMem = cpuMem + 4 * numel(t) ;
end
end
end
|
github
|
jrterven/MultiKinCalib-master
|
knnsearch.m
|
.m
|
MultiKinCalib-master/knnsearch.m
| 3,976 |
utf_8
|
0f62ce2cf9bcdf736e723a616915f539
|
function [idx,D]=knnsearch(varargin)
% KNNSEARCH Linear k-nearest neighbor (KNN) search
% IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array
% representing n points in a d-dimensional space) to find the k-nearest
% neighbors of each query point represented by eahc row of Q (m x d array).
% The results are stored in the (m x K) index array, IDX.
%
% IDX = knnsearch(Q,R) takes the default value K=1.
%
% IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q.
%
% Rationality
% Linear KNN search is the simplest appraoch of KNN. The search is based on
% calculation of all distances. Therefore, it is normally believed only
% suitable for small data sets. However, other advanced approaches, such as
% kd-tree and delaunary become inefficient when d is large comparing to the
% number of data points. On the other hand, the linear search in MATLAB is
% relatively insensitive to d due to the vectorization. In this code, the
% efficiency of linear search is further improved by using the JIT
% aceeleration of MATLAB. Numerical example shows that its performance is
% comparable with kd-tree algorithm in mex.
%
% See also, kdtree, nnsearch, delaunary, dsearch
% By Yi Cao at Cranfield University on 25 March 2008
% Example 1: small data sets
%{
R=randn(100,2);
Q=randn(3,2);
idx=knnsearch(Q,R);
plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx');
%}
% Example 2: ten nearest points to [0 0]
%{
R=rand(100,2);
Q=[0 0];
K=10;
idx=knnsearch(Q,R,10);
r=max(sqrt(sum(R(idx,:).^2,2)));
theta=0:0.01:pi/2;
x=r*cos(theta);
y=r*sin(theta);
plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2);
%}
% Example 3: cputime comparion with delaunay+dsearch I, a few to look up
%{
R=randn(10000,4);
Q=randn(500,4);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
T=delaunayn(R);
idx1=dsearchn(R,T,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay = %g\n',t2-t1);
%}
% Example 4: cputime comparion with delaunay+dsearch II, lots to look up
%{
Q=randn(10000,4);
R=randn(500,4);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
T=delaunayn(R);
idx1=dsearchn(R,T,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay = %g\n',t2-t1);
%}
% Example 5: cputime comparion with kd-tree by Steven Michael (mex file)
% <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=7030&objectType=file">kd-tree by Steven Michael</a>
%{
Q=randn(10000,10);
R=randn(500,10);
t0=cputime;
idx=knnsearch(Q,R);
t1=cputime;
tree=kdtree(R);
idx1=kdtree_closestpoint(tree,Q);
t2=cputime;
fprintf('Are both indices the same? %d\n',isequal(idx,idx1));
fprintf('CPU time for knnsearch = %g\n',t1-t0);
fprintf('CPU time for delaunay = %g\n',t2-t1);
%}
% Check inputs
[Q,R,K,fident] = parseinputs(varargin{:});
% Check outputs
error(nargoutchk(0,2,nargout));
% C2 = sum(C.*C,2)';
[N,M] = size(Q);
L=size(R,1);
idx = zeros(N,K);
D = idx;
if K==1
% Loop for each query point
for k=1:N
d=zeros(L,1);
for t=1:M
d=d+(R(:,t)-Q(k,t)).^2;
end
if fident
d(k)=inf;
end
[D(k),idx(k)]=min(d);
end
else
for k=1:N
d=zeros(L,1);
for t=1:M
d=d+(R(:,t)-Q(k,t)).^2;
end
if fident
d(k)=inf;
end
[s,t]=sort(d);
idx(k,:)=t(1:K);
D(k,:)=s(1:K);
end
end
if nargout>1
D=sqrt(D);
end
function [Q,R,K,fident] = parseinputs(varargin)
% Check input and output
error(nargchk(1,3,nargin));
Q=varargin{1};
if nargin<2
R=Q;
fident = true;
else
fident = false;
R=varargin{2};
end
if isempty(R)
fident = true;
R=Q;
end
if ~fident
fident = isequal(Q,R);
end
if nargin<3
K=1;
else
K=varargin{3};
end
|
github
|
jrterven/MultiKinCalib-master
|
FinalCalibration.m
|
.m
|
MultiKinCalib-master/FinalCalibration.m
| 7,024 |
utf_8
|
388a97a812a8b549efad527ee6f77ffc
|
% Script:
% proj05_FinalCalibration
%
% Description:
% Perform calibration of a Kinect camera (depth or color) given pairs of
% 3D points and 2D projections.
%
% Dependencies:
% function proj05_costFunVec: this function is the one we wish to minimize
% function tr2eul: converts from rotation matriz to Euler angles.
% calibParameters.mat: file with variables defined in proj0_Multi_Kinect_Calibration.m
% such as distortRad, distortTan, withSkew.
%
% Inputs:
% - preCalibResults: file with initial estimation of rotation and
% translation for each camera. This file is generated in proj0_Multi_Kinect_Calibration.m
% - initIntrinsics: file with initial estimation of intrinsic parameters for each
% camera. This file is generated in proj0_Multi_Kinect_Calibration.m
% - camNum: Number of camera to calibrate.
% - camType: Type of camera to calibrate. 'depth' or 'color'
%
%
% Usage:
% This function is called on the step 5: Final Joint Calibration of the
% calibration process.
%
% Results:
% Intrinsic and extrinsic parameters, radDist (radial distortion) and
% tanDist (tangential distortion).
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
function [outData1 outData2] = FinalCalibration( ...
preCalibResults, initIntrinsics, camNum, camType)
clear proj05_costFunVec3; % clear persistent variables of the cost function
load('calibParameters.mat'); % Load the variables: distortRad, distortTan, withSkew
load(preCalibResults); % Load the estimated extrinsics
load(initIntrinsics); % Load the initial intrinsics
% Generates a file with variables for the cost function
save([dataDir '/variablesForCostFun.mat'],'camNum','camType');
cd(fileparts(mfilename('fullpath')));
% Get intrinsic initial values from initIntrinsics file
if strcmp(camType, 'depth')
if camNum == 1
f = preIntrinsicsD1(1,1);
cx = preIntrinsicsD1(1,3);
cy = preIntrinsicsD1(2,3);
skew = preIntrinsicsD1(1,2);
elseif camNum == 2
f = preIntrinsicsD2(1,1);
cx = preIntrinsicsD2(1,3);
cy = preIntrinsicsD2(2,3);
skew = preIntrinsicsD2(1,2);
elseif camNum == 3
f = preIntrinsicsD3(1,1);
cx = preIntrinsicsD3(1,3);
cy = preIntrinsicsD3(2,3);
skew = preIntrinsicsD3(1,2);
elseif camNum == 4
f = preIntrinsicsD4(1,1);
cx = preIntrinsicsD4(1,3);
cy = preIntrinsicsD4(2,3);
skew = preIntrinsicsD4(1,2);
end
elseif strcmp(camType, 'color')
if camNum == 1
f = preIntrinsicsC1(1,1);
cx = preIntrinsicsC1(1,3);
cy = preIntrinsicsC1(2,3);
skew = preIntrinsicsC1(1,2);
elseif camNum == 2
f = preIntrinsicsC2(1,1);
cx = preIntrinsicsC2(1,3);
cy = preIntrinsicsC2(2,3);
skew = preIntrinsicsC2(1,2);
elseif camNum == 3
f = preIntrinsicsC3(1,1);
cx = preIntrinsicsC3(1,3);
cy = preIntrinsicsC3(2,3);
skew = preIntrinsicsC3(1,2);
elseif camNum == 4
f = preIntrinsicsC4(1,1);
cx = preIntrinsicsC4(1,3);
cy = preIntrinsicsC4(2,3);
skew = preIntrinsicsC4(1,2);
end
end
% Get extrinsics from pre-calibration
if camNum == 1
R = eye(3);
%Rq = qGetQ( R );
%Rq = qNormalize(Rq);
Rq = rotm2quat(R);
t = [0 0 0];
elseif camNum == 2
%Rq = qGetQ( R1_2 );
%Rq = qNormalize(Rq);
Rq = rotm2quat(R1_2);
t = t1_2;
elseif camNum == 3
%Rq = qGetQ( R1_3 );
%Rq = qNormalize(Rq);
Rq = rotm2quat(R1_3);
t = t1_3;
elseif camNum == 4
%Rq = qGetQ( R1_4 );
%Rq = qNormalize(Rq);
Rq = rotm2quat(R1_4);
t = t1_4;
end
% Build the variables vector to be solved
x0 = [f, cx, cy, ...
Rq(1), Rq(2), Rq(3), Rq(4), ...
t(1), t(2), t(3)];
if distortRad > 0
if distortRad == 2
x0 = [x0 0 0];
elseif distortRad == 3
x0 = [x0 0 0 0];
end
if distortTan
x0 = [x0 0 0];
end
end
if withSkew
x0 = [x0 skew];
end
% Non-linear optimization
options = optimset('Algorithm','levenberg-marquardt','MaxFunEvals',100000, ...
'TolFun',1e-100,'TolX',1e-100,'MaxIter', 10000);
x = fsolve('proj05_costFunVec3',x0,options);
% Extract results from results vector
f = x(1); % focal length
cx = x(2); % principal point x
cy = x(3); % principal point y
if withSkew
s = x(end); % skew
else
s = 0;
end
% Get rotation from vector
Rq = [x(4) x(5) x(6) x(7)];
% Convert to rotation matrix
% Rx=[1 0 0;0 cos(Reul(1)) sin(Reul(1));0 -sin(Reul(1)) cos(Reul(1))];
% Ry=[cos(Reul(2)) 0 -sin(Reul(2));0 1 0;sin(Reul(2)) 0 cos(Reul(2))];
% Rz=[cos(Reul(3)) sin(Reul(3)) 0;-sin(Reul(3)) cos(Reul(3)) 0;0 0 1];
% R = Rx*Ry*Rz;
%R = eul2r(Reul(1),Reul(2),Reul(3));
%Rq = qNormalize(Rq);
% Get rotation matrix from quaternion
%R = qGetR(Rq);
R = quat2rotm(Rq);
% Extract translation
t = [x(8); x(9); x(10)];
% Extract radial and tangential distortion coefficients
if distortRad == 2
k1 = x(11);
k2 = x(12);
if distortTan
p1 = x(13);
p2 = x(14);
end
elseif distortRad == 3
k1 = x(11);
k2 = x(12);
k3 = x(13);
if distortTan
p1 = x(14);
p2 = x(15);
end
end
% Display results
disp(['***** ' camType ' Camera ' num2str(camNum) ' Calibration Results *****']);
intrinsics = [f s cx;
0 f cy;
0 0 1];
disp('Intrinsic parameters matrix:');
disp(intrinsics);
% Rotation
disp('R=');
disp(R);
% Test if the rotation is valid
detR = det(R);
if detR ~= 1
disp('Invalid rotation matrix!')
disp(['Determinant = ' num2str(detR)]);
end
% Translation
disp('t=');
disp(t);
% Distortion
radDist = [];
tanDist = [];
if distortRad > 0
if distortRad == 2
disp('Radial Distortion: k1, k2')
radDist = [k1 k2];
disp(radDist);
elseif distortRad == 3
disp('Radial Distortion: k1, k2, k3')
radDist = [k1 k2 k3];
disp(radDist);
end
if distortTan
disp('Tangential Distortion: p1, p2')
tanDist = [p1 p2];
disp(tanDist);
end
end
tanStr = '0';
if distortTan
tanStr = '2';
else
tanStr = '0';
end
% Calculate reproyection error with the pointcloud and point-cloud projections
result = struct('CamType',camType,'CamNum',camNum,'MatchingDist',minDist3D, ...
'Intrinsics',intrinsics,'Rot',R,'t',t,'RadDist',radDist, ...
'TanDist',tanDist);
repError = proj05_calcReprojectionError2(result);
disp(['Error: ' num2str(repError)]);
% Build the name of the struct
name = ['cam' num2str(camNum) '_' camType '_' num2str(minDist3D) 'mm_' ...
'rad' num2str(distortRad) '_tan' tanStr];
% Build the struct with the data
results = struct('CamType',camType,'MatchingDist',minDist3D, ...
'Intrinsics',intrinsics,'Rot',Rq,'t',t,'RadDist',radDist, ...
'TanDist',tanDist,'Error',repError);
outData1.(name) = results;
outData2 = results;
|
github
|
jrterven/MultiKinCalib-master
|
Step03_Matching.m
|
.m
|
MultiKinCalib-master/Step03_Matching.m
| 2,265 |
utf_8
|
84fad680aa977b0e7cf22fbed9cf3048
|
% function:
% Step03_Matching(camCount,dataAcqFile,preCalibResultsFile,minDist3D,matchingResultsFile)
%
% Description:
% Perform the point cloud matching step between all pairs of cameras.
%
% Dependencies:
% - function Find3DMatches: peform the actual matching between a pair of
% pointclouds.
%
% Inputs:
% - camCount: Number of cameras to calibrate
% - dataAcqFile: file containing the data from the acquisition step.
% - preCalibResultsFile: name of the output file containing the results
% of the pre-calibration
% - minDist3D: matching distance
% - matchingResultsFile: out file containing the matching results.
%
% Return:
% Save the results on the matchingResultsFile specified in the arguments
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
function Step03_Matching(camCount,dataAcqFile,minDist3D,matchingResultsFile)
load(dataAcqFile);
disp('Step 3: 3D Pointcloud Matching');
% Finds the 3D matches between pointclouds
% Generates a file called matchingResultsFile
disp('Searching for matchings between Cam1 and Cam2');
[cam2_1Matches,cam2_1depthProj,cam2_1colorProj] = Find3DMatches( ...
pc1, pc2, T1_2, cam2.depthProj, cam2.colorProj, minDist3D);
save(matchingResultsFile,'cam2_1Matches','cam2_1depthProj','cam2_1colorProj');
if camCount > 2
disp('Searching for matchings between Cam1 and Cam3');
[cam3_1Matches,cam3_1depthProj,cam3_1colorProj] = Find3DMatches( ...
pc1, pc3, T1_3, cam3.depthProj, cam3.colorProj, minDist3D);
save(matchingResultsFile,'cam3_1Matches', ...
'cam3_1depthProj','cam3_1colorProj','-append');
disp('Searching for matchings between Cam2 and Cam3');
[cam3_2Matches,cam3_2depthProj,cam3_2colorProj] = Find3DMatches( ...
pc2, pc3, T2_3, cam3.depthProj, cam3.colorProj, minDist3D);
save(matchingResultsFile,'cam3_2Matches', ...
'cam3_2depthProj','cam3_2colorProj','-append');
end
if camCount > 3
disp('Searching for matchings between Cam1 and Cam4');
[cam4_1Matches,cam4_1depthProj,cam4_1colorProj] = Find3DMatches( ...
pc1, pc4, T1_4, cam4.depthProj, cam4.colorProj, minDist3D);
save(matchingResultsFile,'cam4_1Matches', ...
'cam4_1depthProj','cam4_1colorProj','-append');
end
|
github
|
jrterven/MultiKinCalib-master
|
serverGetData.m
|
.m
|
MultiKinCalib-master/serverGetData.m
| 5,485 |
utf_8
|
2bdb052ce46ef892036d2609ccbc24c9
|
% Function:
% serverGetData
%
% Description:
% Communicates with remote clients via TCP/IP to obtain the calibration
% points, pointcloud of the scene, and depth and color projections of the
% 3D calibration points of the current frame
%
% Dependencies:
% TCPIPCommands.mat: mat file with custom defined codes
%
%
% Inputs:
% TCPIPCons: TCP/IP connections
% CapturePC: if true, the clients send all the data to the server and all
% the data is returned by this function.
%
% Usage:
% This function is called inside the dataAcq.m GUI KinectUpdate function.
% When the user presses the "Start Acquisition" button, this function is
% called repeatedly on each frame acquired from the Kinect. Each time
% this function is called with the second parameter on false, the remote
% clients save their data locally. When this function is called with the
% second parameter on true, the remote clients send the data to the
% server and this function returns the whole data.
%
% Returns:
% dataSaved: if true, all the clients were able to collect data, if
% false, an error ocurred.
% camData: cell array of struct arrays with the data for each camera
% Each element of the cell array contains the data of each camera saved
% as a structure containing:
% camPoints: calibration camera points on camera space
% pointcloud: colored point cloud of the scene
% depthProj: depth projections of point cloud
% colorProj: color projections of point cloud
% For example to access to the camPoints of camera 1 use:
% camData{1}.camPoints
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
%
% Date: 26-June-2016
function [dataSaved, camData] = serverGetData(TCPIPCons,CapturePC,pointcloudSize)
load('TCPIPCommands.mat');
% Display input buffer size
%disp(get(tcpipServer1,'InputBufferSize'));
% Number of connections
CON_NUM = size(tcpipServer1,2);
% Send a capture command to all cameras
ack = TCPIPbroadcastCommand(TCPIPCons,CON_NUM, CAPTURE, 'capturing');
% If communication error
if ack == false
disp('Comunication Error on CAPTURE command!!');
dataSaved = false;
return;
end
% At this point, all the cameras capture a frame
% Check if all have valid data
resp = TCPIPgetResponses(TCPIPCons, CON_NUM, 'No valid Kinect frame');
% Before processing the data, we need to make sure that a valid
% frame was acquired on all the cameras
if resp == VALID_FRAME % if valid frame on all cameras
% Send a process command to all cameras
ack = TCPIPbroadcastCommand(TCPIPCons, CON_NUM, PROCESS, 'processing frame');
if ack == false
disp('Comunication Error on PROCESS command!!');
dataSaved = false;
return;
end
% At this point, all the cameras are processing its own frame
% searching for the balls
% Check if all have found the six balls
resp = TCPIPgetResponses(TCPIPCons, CON_NUM, ...
['Not found ' num2str(pointsOnStick) ' balls']);
if resp == VALID_FRAME % if all cameras found the six balls
% Send a save command to all cameras
ack = TCPIPbroadcastCommand(TCPIPCons, CON_NUM, SAVE, 'saving frame');
if ack == false
dataSaved = false;
return;
end
% if we want to collect all the data from the clients
if CapturePC
% Get remote camPoints, pointclouds, depthProj, and
% colorProj
camPointsMetDat = whos('camPoints');
camDataSize = camPointsMetDat.size;
depthProjMetDat = whos('depthProj');
depthProjSize = depthProjMetDat.size;
colorProjMetDat = whos('colorProj');
colorProjSize = colorProjMetDat.size;
[camPoints, pc, depthPr, colorPr] = getCalibDataFromClient(TCPIPCons, ...
CON_NUM, camDataSize, pointcloudSize, ...
depthProjSize,colorProjSize);
if CON_NUM > 1
cam2 = struct('camPoints',camPoints{1}, ...
'pointcloud',pc{1}, 'depthProj',depthPr{1}, ...
'colorProj',colorPr{1});
camData{2} = cam2;
end
if CON_NUM > 2
cam3 = struct('camPoints',camPoints{2}, ...
'pointcloud',pc{2}, 'depthProj',depthPr{2}, ...
'colorProj',colorPr{2});
camData{3} = cam3;
end
if CON_NUM > 3
cam4 = struct('camPoints',camPoints{3}, ...
'pointcloud',pc{3},'depthProj',depthPr{3}, ...
'colorProj',colorPr{3});
camData{4} = cam4;
end
end
else
dataSaved = false;
return;
end
else % if some client were not able to capture data
dataSaved = false;
return;
end
end
|
github
|
jrterven/MultiKinCalib-master
|
PreCalib.m
|
.m
|
MultiKinCalib-master/PreCalib.m
| 2,907 |
utf_8
|
910358ae66170af3240c5f499dc9fd3d
|
% function:
% [Rs, ts, T] = PreCalib(camNum,dataAcqFile)
%
% Description:
% Perform a pre-calibration of the extrinsic parameters between a pair of
% Kinect cameras.
%
% Dependencies:
% - function CostFunPreCalib: this function is the one we wish to
% minimize.
% - file 'calibParameters.mat' created with proj0_ServerMultiKinectCalib.
% From this file we use the variables: 'dataDir', 'minFunType', 'pointsToConsider'
% - file dataAcqFile created with proj01_ServerCapturePointsFromCalibObject.m
% From this file we get the calibration camera points of the camera
% we wish to calibrate i.e. cam2.camPoints, cam3.camPoints, etc.
%
% Inputs:
% - camNum: Number of camera to calibrate wrt the reference camera
% - file dataAcqFile
%
% Usage:
%
% Return:
% - Rs, ts: Estimation of the extrinsic parameters of the camNum wrt the
% reference camera.
% - T: 4x4 transformation matrix composed by Rs and Tt
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
function [Rs, ts, T] = PreCalib(camA,camB,dataAcqFile)
% Load calibration parameters:
%'dataDir', 'minFunType', 'pointsToConsider'
load('calibParameters.mat');
load(dataAcqFile);
%% Calibrate Depth Camera
R = eye(3);
t = [0,0,0];
% Extract the data from the structures located in dataAcqFile
if camA == 1
XwA = cam1.camPoints;
elseif camA == 2
XwA = cam2.camPoints;
elseif camA == 3
XwA = cam3.camPoints;
elseif camA == 4
XwA = cam4.camPoints;
end
if camB == 1
XwB = cam1.camPoints;
elseif camB == 2
XwB = cam2.camPoints;
elseif camB == 3
XwB = cam3.camPoints;
elseif camB == 4
XwB = cam4.camPoints;
end
if strcmp(minFunType,'pointReg')
if pointsToConsider ~= -1
XwA = XwA(1:pointsToConsider,:);
XwB = XwB(1:pointsToConsider,:);
end
[Rs,ts] = rigid_transform_3D(XwA, XwB);
rmse = calculateRegistrationError(XwA',XwB',Rs,ts);
disp(['RMSE of Precalibration:' num2str(rmse)]);
elseif strcmp(minFunType,'fsolve')
% Generates a file with variables for the cost function
save([dataDir '/variablesForCostFunPreCalib.mat'],'camNum','Xw1','Xw2');
x0 = [0, 0, 0, t(1), t(2), t(3)];
options = optimset('MaxFunEvals',100000,'TolFun',1e-100,'TolX',1e-100, 'MaxIter', 10000);
x = fsolve('proj02_CostFunPreCalib',x0,options);
Reul = [x(1) x(2) x(3)];
Rx=[1 0 0;0 cos(Reul(1)) sin(Reul(1));0 -sin(Reul(1)) cos(Reul(1))];
Ry=[cos(Reul(2)) 0 -sin(Reul(2));0 1 0;sin(Reul(2)) 0 cos(Reul(2))];
Rz=[cos(Reul(3)) sin(Reul(3)) 0;-sin(Reul(3)) cos(Reul(3)) 0;0 0 1];
Rs = Rx*Ry*Rz;
ts = [x(4); x(5); x(6)];
else
disp('Invalid minimization function: only supports pointReg or fsolve');
end
% Test if it is a valid rotation matrix
disp('R:'), disp(Rs)
disp('Rotation determinant:')
det(Rs)
disp('t='), disp(ts)
T = [Rs ts; 0 0 0 1];
|
github
|
jrterven/MultiKinCalib-master
|
Step05_FinalCalibration.m
|
.m
|
MultiKinCalib-master/Step05_FinalCalibration.m
| 3,117 |
utf_8
|
5fc8cf44653153f6b7d0f3261fcfe232
|
% function:
% Step05_FinalCalibration(camCount,preCalibResultsFile,initIntrinsicsFile,finalCalibResults)
%
% Description:
% Perform the final calibration of all the cameras using a non-linear
% optimization.
%
% Dependencies:
% - function FinalCalibration: performs the calibration of a single
% camera.
% - file 'calibParameters.mat' created with proj0_ServerMultiKinectCalib.
% From this file we use the variables: 'dataDir', 'minFunType', 'pointsToConsider'
%
% Inputs:
% - camCount: Number of cameras to calibrate
% - preCalibResultsFile: name of the output file containing the results
% of the pre-calibration
% - initIntrinsicsFile: out file with the estimated intrinsic parameters.
%
% Return:
% Save the results on the finalCalibResults specified in the arguments
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: Feb-2016
function Step05_FinalCalibration(camCount,preCalibResultsFile,initIntrinsicsFile,finalCalibResults)
disp('Step 4: Final Joint Calibration');
% Calibrate camera 1
disp('Calibrating Depth camera 1...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 1, 'depth');
save(finalCalibResults,'-struct','result1'); % Save results on .mat
disp('Calibrating Color camera 1...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 1, 'color');
save(finalCalibResults,'-struct','result1','-append');
if camCount > 1
% Calibrate camera 2
disp('Calibrating Depth camera 2...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 2, 'depth');
save(finalCalibResults,'-struct','result1','-append');
disp('Calibrating Color camera 2...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 2, 'color');
save(finalCalibResults,'-struct','result1','-append');
end
if camCount > 2
% Calibrate camera 3
disp('Calibrating Depth camera 3...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 3, 'depth');
save(finalCalibResults,'-struct','result1','-append')
disp('Calibrating Color camera 3...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 3, 'color');
save(finalCalibResults,'-struct','result1','-append')
end
if camCount > 3
% Calibrate camera 4
disp('Calibrating Depth camera 4...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 4, 'depth');
save(finalCalibResults,'-struct','result1','-append');
disp('Calibrating Color camera 4...')
[result1, result2] = FinalCalibration(preCalibResultsFile, ...
initIntrinsicsFile, 4, 'color');
save(finalCalibResults,'-struct','result1','-append')
end
|
github
|
jrterven/MultiKinCalib-master
|
S05_costFunVec.m
|
.m
|
MultiKinCalib-master/S05_costFunVec.m
| 5,888 |
utf_8
|
210560ea349880160a178c88cb754faf
|
% Function:
% proj05_costFunVec
%
% Description:
% Function that we wish to minimize.
%
% Dependencies:
% - calibParameters.mat: file with variables defined in proj0_Multi_Kinect_Calibration.m
% such as: dataDir, distortRad, distortTan, withSkew
% - matchingResults.mat: file containing the 3D matching points
% (cam2_1Matches, cam3_1Matches, etc)and 2D projections
% (cam2_1depthProj, cam2_1colorProj, etc)
% - variablesForCostFun.mat: file with variables 'camNum','camType'
% created in proj05_FinalCalibration.
%
% Inputs:
% x0: parameters that we wish to find by minimizing the function f
%
% Usage:
% This function is called by an optimization function such as fsolve,
% lsqnonlin, fmincon
%
% Results:
% find the values of x0 that minimize f
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
function fun = proj05_costFunVec(x0)
persistent X3d x2d distRad distTan height width with_skew;
% The first iteration loads the data
if isempty(X3d)
X3d = [];
x2d = [];
% Load dataDir, distortRad, distortTan, withSkew
load('calibParameters.mat');
distRad = distortRad;
distTan = distortTan;
with_skew = withSkew;
% Load variables camNum and camType
load([dataDir '/variablesForCostFun.mat']);
if camNum == 1
load(dataAcqFile)
else
% Load the point clouds: cam2_1Matches, cam3_1Matches, etc
load(matchingResultsFile);
end
if strcmp(camType, 'depth')
height = 424;
width = 512;
elseif strcmp(camType, 'color')
height = 1080;
width = 1920;
end
% Get the 3D points from the matching results
% 3D points as a 3 x n matrix
if camNum == 1
X3d = (cam1.pointcloud(1:100:end,:))';
% 2D points as a 2 x n matrix
if strcmp(camType, 'depth')
x2d = double(cam1.depthProj(1:100:end,:))';
elseif strcmp(camType, 'color')
x2d = double(cam1.colorProj(1:100:end,:))';
end
elseif camNum == 2
X3d = cam2_1Matches';
% 2D points as a 2 x n matrix
if strcmp(camType, 'depth')
x2d = double(cam2_1depthProj)';
elseif strcmp(camType, 'color')
x2d = double(cam2_1colorProj)';
end
elseif camNum == 3
X3d = cam3_1Matches';
if strcmp(camType, 'depth')
x2d = double(cam3_1depthProj)';
elseif strcmp(camType, 'color')
x2d = double(cam3_1colorProj)';
end
elseif camNum == 4
X3d = cam4_1Matches';
if strcmp(camType, 'depth')
x2d = double(cam4_1depthProj)';
elseif strcmp(camType, 'color')
x2d = double(cam4_1colorProj)';
end
end
% Remove outliers from X3d in both matrices
% Find columns with invalid values
x2dValidCols = ~any( isnan( x2d ) | isinf( x2d ) | x2d > width | x2d < 0, 1 );
x3dValidCols = ~any( isnan( X3d ) | isinf( X3d ) | X3d > 8, 1 );
validCols = x2dValidCols & x3dValidCols;
x2d = x2d(:,validCols);
X3d = X3d(:,validCols);
% x2d(:,any(X3d > 8)) = []; % remove columns with values greater than 8 meters
% x2d(:,any(X3d == inf)) = [];
% x2d(:,any(X3d == -inf)) = [];
%
% X3d(:,any(X3d > 8)) = []; % remove columns with values greater than 8 meters
% X3d(:,any(X3d == inf)) = [];
% X3d(:,any(X3d == -inf)) = [];
%
% % Now remove outliers from x2d in both matrices
% X3d(:,any(x2d > width)) = [];
% X3d(:,any(x2d < 0)) = []; % remove columns with negative values
% X3d(:,any(x2d == inf)) = [];
% X3d(:,any(x2d == -inf)) = [];
%
% x2d(:,any(x2d > width)) = [];
% x2d(:,any(x2d < 0)) = []; % remove columns with negative values
% x2d(:,any(x2d == inf)) = [];
% x2d(:,any(x2d == -inf)) = [];
end
f = x0(1); % focal length
cx = x0(2); % principal point
cy = x0(3);
% Rotation
R = eul2r(x0(4),x0(5),x0(6));
% Rx=[1 0 0;0 cos(x0(4)) sin(x0(4));0 -sin(x0(4)) cos(x0(4))];
% Ry=[cos(x0(5)) 0 -sin(x0(5));0 1 0;sin(x0(5)) 0 cos(x0(5))];
% Rz=[cos(x0(6)) sin(x0(6)) 0;-sin(x0(6)) cos(x0(6)) 0;0 0 1];
% R = Rx*Ry*Rz;
% Translation
t = [x0(7);x0(8);x0(9)];
if distRad == 2
k1 = x0(10);
k2 = x0(11);
if distTan
p1 = x0(12);
p2 = x0(13);
end
elseif distRad == 3
k1 = x0(10);
k2 = x0(11);
k3 = x0(12);
if distTan
p1 = x0(13);
p2 = x0(14);
end
end
if with_skew
s = x0(end);
else
s = 0;
end
intrinsic = [f s cx;
0 f cy;
0 0 1];
N = size(X3d,2);
Xw = X3d;
xc = x2d;
xc(2,:) = height - xc(2,:);
% Apply extrinsic parameters
proj = R * Xw + repmat(t,1,size(Xw,2));
% Apply Intrinsic parameters to get the projection
proj = intrinsic * proj;
proj = proj ./ repmat(proj(3,:),3,1);
% Distortion correction
if distRad > 0
u = proj(1,:);
v = proj(2,:);
ud=xc(1,:);
vd=xc(2,:);
r = sqrt((u-cx).^2 + (v-cy).^2);
if distRad == 2
compRad(1,:) = 1 + k1*r.^2 + k2*r.^4;
compRad(2,:) = 1 + k1*r.^2 + k2*r.^4;
elseif distRad == 3
compRad(1,:) = 1 + k1*r.^2 + k2*r.^4 + k3*r.^6;
compRad(2,:) = 1 + k1*r.^2 + k2*r.^4 + k3*r.^6;
end
compTan = zeros(2,size(u,2));
if distTan
compTan(1,:) = 2*p1*(u-cx).*(v-cy) + p2*(r.^2+2*(u-cx).^2);
compTan(2,:) = p1*(r.^2+2*(v-cy).^2) + 2*p2*(u-cx).*(v-cy);
end
% Reprojection error with distortion
fun(1,:)= ((u-cx).*compRad(1,:) + compTan(1,:)) - (ud-cx);
fun(2,:)= ((v-cy).*compRad(2,:) + compTan(2,:)) -(vd-cy);
else
% Reprojection error without distortion
fun = proj(1:2,:) - xc;
end
% Display the reproyection error
err = fun .* fun;
err = sum(err(:));
disp(sqrt(err/N));
|
github
|
jrterven/MultiKinCalib-master
|
CostFunPreCalib.m
|
.m
|
MultiKinCalib-master/CostFunPreCalib.m
| 1,477 |
utf_8
|
9c3ffd29db0967fdf9a090a3c1e168a1
|
% Function:
% CostFunPreCalib
%
% Description:
% Function that we wish to minimize using proj02_PreCalib
%
% Dependencies:
% File: calibParameters.mat where we load the variables load dataDir and pointsToConsider
% File: variablesForCostFunPreCalib.mat with the variables camNum, Xw1, Xw2
%
% Inputs:
% 1) x0: parameters that we wish to find by minimizing the function f
%
% Usage:
% This function is called by the proj02_PreCalib script inside the optimization
% function fsolve
%
% Results:
% find the values of x0 that minimize f
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
%
function f= CostFunPreCalib(x0)
persistent Xw1s;
persistent Xw2s;
% Euler angles to Rotation matrix
R = eul2r(x0(1),x0(2),x0(3));
t = [x0(4);x0(5);x0(6)];
% Load the data
if isempty(Xw1s)
% Load dataDir and pointsToConsider
load('calibParameters.mat');
% Load camNum, Xw1, Xw2
load([dataDir '/variablesForCostFunPreCalib.mat']);
Xw1s = Xw1';
Xw2s = Xw2';
if pointsToConsider ~= -1
Xw1s = Xw1s(:,1:pointsToConsider);
Xw2s = Xw2s(:,1:pointsToConsider);
end
end
pos_puntos_ref=[Xw1s(1,:)' Xw1s(2,:)' Xw1s(3,:)'];
pos_puntos_cam=[Xw2s(1,:)' Xw2s(2,:)' Xw2s(3,:)'];
f = [];
for j=1:size(pos_puntos_ref,1)
vec=pos_puntos_ref(j,:);
comp=pos_puntos_cam(j,:);
p_esp=(R*vec')+t;
fun = comp - p_esp';
f=[fun'; f];
end
e=mean(abs(f))
|
github
|
jrterven/MultiKinCalib-master
|
dataAcq.m
|
.m
|
MultiKinCalib-master/dataAcq.m
| 27,025 |
utf_8
|
077af366b281510066728625af90d1dd
|
function varargout = dataAcq(varargin)
% DATAACQ MATLAB code for dataAcq.fig
% DATAACQ, by itself, creates a new DATAACQ or raises the existing
% singleton*.
%
% H = DATAACQ returns the handle to a new DATAACQ or the handle to
% the existing singleton*.
%
% DATAACQ('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DATAACQ.M with the given input arguments.
%
% DATAACQ('Property','Value',...) creates a new DATAACQ or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before dataAcq_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to dataAcq_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help dataAcq
% Last Modified by GUIDE v2.5 05-Jun-2016 18:43:59
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @dataAcq_OpeningFcn, ...
'gui_OutputFcn', @dataAcq_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before dataAcq is made visible.
function dataAcq_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to dataAcq (see VARARGIN)
% Choose default command line output for dataAcq
handles.output = hObject;
% Create timer
handles.timer = timer('ExecutionMode','fixedRate',...
'Period', 0.1,...
'TimerFcn', {@KinectUpdate,handles});
% Update handles structure
guidata(hObject, handles);
set(handles.buttonStopKinects,'Visible','Off');
set(handles.buttonStartAcq,'Enable','Off');
set(handles.buttonStopAcq,'Visible','Off');
set(handles.buttonSaveReference,'Enable','Off');
set(handles.buttonClearReference,'Visible','Off');
% Reference not ready
setappdata(handles.axesCam1,'refAReady',false);
% Acquistion = false
setappdata(handles.buttonStartAcq,'Acquisition',false);
% local adquisitions empty
setappdata(handles.buttonStartAcq,'camPoints',[]);
% Clear the image axes
clearImg = ones(1080,1920) * 255;
imshow(clearImg, 'Parent', handles.axesCam1);
% Get setup data
role = getappdata(0,'role');
camCount = getappdata(0,'camCount');
countImagesToSave = getappdata(0,'countImagesToSave');
set(handles.editCams,'string',num2str(camCount));
set(handles.editAcqs,'string',num2str(countImagesToSave));
if strcmp(role,'client')
clientId = getappdata(0,'clientId');
set(handles.textRole,'string',[role ' ' num2str(clientId)]);
serverIP = getappdata(0,'serverIP');
set(handles.editServerIP,'string',serverIP);
% set(handles.buttonStartKinects,'Enable','Off');
else
% Display 'server' role
set(handles.textRole,'string',role);
% Display local IP address
address = java.net.InetAddress.getLocalHost;
IPaddress = char(address.getHostAddress);
set(handles.editServerIP,'string',IPaddress);
end
% Save the number of connections
setappdata(handles.figure1,'connections',0);
% UIWAIT makes dataAcq wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = dataAcq_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in buttonStartKinects.
function buttonStartKinects_Callback(hObject, eventdata, handles)
% hObject handle to buttonStartKinects (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
addpath('Kin2/Mex');
k2 = Kin2('color','depth','infrared');
%imgWidth = 512; imgHeight = 424; outOfRange = 4000;
setappdata(handles.axesCam1,'k2',k2);
start(handles.timer)
%disp('Timer activated')
set(handles.buttonStartKinects,'Visible','Off');
set(handles.buttonStopKinects,'Visible','On');
set(handles.buttonSaveReference,'Enable','On');
% Save reference flag to false
setappdata(handles.axesCam1,'refAReady',false);
function KinectUpdate(obj,event,handles)
k2 = getappdata(handles.axesCam1,'k2');
refAReady = getappdata(handles.axesCam1,'refAReady');
% Get frames from Kinect and save them on underlying buffer
validData = k2.updateData;
% Before processing the data, we need to make sure that a valid
% frame was acquired.
if validData
% Copy data to Matlab matrices
%depth = k2.getDepth;
colorImg = k2.getColor;
infrared = k2.getInfrared;
% If not reference ready
if ~refAReady
% Search the infrared marker on the infrared image
[refAw, refAc] = findPointAfromInfrared(k2, infrared);
% and save it
setappdata(handles.axesCam1,'refAw',refAw);
setappdata(handles.axesCam1,'refAc', refAc);
% If the reference is ready, get it from memory
else
refAw = getappdata(handles.axesCam1,'refAw');
refAc = getappdata(handles.axesCam1,'refAc');
end
% Read the acqusition flag (see if acquisition is activated)
acquisition = getappdata(handles.buttonStartAcq,'Acquisition');
% If no acquisition activated
if ~acquisition
% Plot the infrared marker on the color image
colorImg = insertShape(colorImg,'FilledCircle',[refAc 10],'color','yellow');
% If acquisition activated,
% get parameters
else
role = getappdata(0,'role');
pointsOnStick = getappdata(0,'pointsOnStick');
sizeStick = getappdata(0,'sizeStick');
refAw = getappdata(handles.axesCam1,'refAw');
pointcloudSize = getappdata(handles.buttonConnect,'pointcloudSize');
% if this computer is the server
if strcmp(role,'server')
% Get the TCPIP connections
TCPIPCons = getappdata(handles.buttonConnect,'TCPIPCons');
% Get the location of the calibration points in color space
% returns points as a 6x2 matrix in the case of six balls or 3x2 in
% the case of three balls
[validBalls, points] = trackCalibPoints(k2,colorImg, ...
pointsOnStick, refAw, sizeStick);
if validBalls
% Plot the balls in color
colorImg = insertShape(colorImg,'FilledCircle',points(1,:),'color','yellow');
%plot(points(1,1),points(1,2),'y*', 'MarkerSize',15)
colorImg = insertShape(colorImg,'FilledCircle',points(2,:),'color','blue');
%plot(points(2,1),points(2,2),'b*','MarkerSize',15)
colorImg = insertShape(colorImg,'FilledCircle',points(3,:),'color','cyan');
%plot(points(3,1),points(3,2),'c*','MarkerSize',15)
if pointsOnStick == 6
plot(points(4,1),points(4,2),'k*','MarkerSize',15)
plot(points(5,1),points(5,2),'g*','MarkerSize',15)
plot(points(6,1),points(6,2),'m*','MarkerSize',15)
end
% read the desired number of acquisitions from GUI
maxAcqs = str2double(get(handles.editAcqs,'String'));
% read the current number of acquistions
camPoints = getappdata(handles.buttonStartAcq,'camPoints');
currAcqs = size(camPoints,1);
finishAcq = false; % flag indicating finishing acquisition
% if the number of acquisitions is less than the
% desired acquisitions, send to clients a command
% gather data and save it locally
if currAcqs < (maxAcqs - 1)
% Send a command to get the calibration points on
% camera space from on each remote camera
[dataSaved, ~] = serverGetData(TCPIPCons,false,pointcloudSize);
% if the current number of acquisitions reached the
% desired acquistions fetch all the data from the
% clients
else
%camData is a cell array of struct arrays with the
% data from each remote camera. Each element of the
% cell array is a structure with the following fields:
% camPoints: calibration camera points on camera space
% pointcloud: colored point cloud of the scene
% depthProj: depth projections of point cloud
% colorProj: color projections of point cloud
% As an example to access to the camPoints of camera 1 use:
% camData{1}.camPoints
[dataSaved, camData] = serverGetData(TCPIPCons,false,pointcloudSize);
if dataSaved, finishAcq = true; end
end
if dataSaved
% Accumulate local data points in camera space. These are
% the calibration points in camera space (n x 3)
camPoints = [camPoints; k2.mapColorPoints2Camera(points)];
setappdata(handles.buttonStartAcq,'camPoints',camPoints);
% update the number of acquisitions
acqs = size(camPoints,1);
set(handles.textAcquisitions,'String',num2str(acqs));
if finishAcq
% Get the local pointcloud
pointcloud = k2.getPointCloud;
% Get the pointcloud's projections on depth space
depthProj = k2.mapCameraPoints2Depth(pointcloud);
% Get the pointcloud's projections on color space
colorProj = k2.mapCameraPoints2Color(pointcloud);
% Save all the data into camData
cam1 = struct('camPoints',camPoints,'pointcloud',pointcloud, ...
'depthProj', depthProj, 'colorProj', colorProj);
camData{1} = cam1;
setappdata(0,'camData',camData);
end
end
end
% if client
else
tcpipClient = getappdata(0,'tcpipClient');
end
end
imshow(colorImg, 'Parent', handles.axesCam1);
end
% --- Executes on button press in buttonStopKinects.
function buttonStopKinects_Callback(hObject, eventdata, handles)
% hObject handle to buttonStopKinects (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isvalid(handles.timer)
stop(handles.timer);
end
% Delete Kinect object
k2 = getappdata(handles.axesCam1,'k2');
k2.delete;
setappdata(handles.axesCam1,'k2',k2);
set(handles.buttonStartKinects,'Visible','On');
set(handles.buttonStopKinects,'Visible','Off');
% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isvalid(handles.timer)
stop(handles.timer);
delete(handles.timer);
end
clear handles.timer;
% Hint: delete(hObject) closes the figure
delete(hObject);
function editCams_Callback(hObject, eventdata, handles)
% hObject handle to editCams (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editCams as text
% str2double(get(hObject,'String')) returns contents of editCams as a double
% --- Executes during object creation, after setting all properties.
function editCams_CreateFcn(hObject, eventdata, handles)
% hObject handle to editCams (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function editAcqs_Callback(hObject, eventdata, handles)
% hObject handle to editAcqs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editAcqs as text
% str2double(get(hObject,'String')) returns contents of editAcqs as a double
% --- Executes during object creation, after setting all properties.
function editAcqs_CreateFcn(hObject, eventdata, handles)
% hObject handle to editAcqs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in buttonStartAcq.
function buttonStartAcq_Callback(hObject, eventdata, handles)
% hObject handle to buttonStartAcq (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.buttonStartAcq,'Enable','Off');
setappdata(handles.buttonStartAcq,'Acquisition',true);
% --- Executes on button press in buttonSaveExit.
function buttonSaveExit_Callback(hObject, eventdata, handles)
% hObject handle to buttonSaveExit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Stop timer
if isvalid(handles.timer)
stop(handles.timer);
delete(handles.timer);
end
% Close network connections, if any
closeConnections(handles);
%figure(main)
close(dataAcq)
function closeConnections(handles)
role = getappdata(0,'role');
connections = getappdata(handles.figure1,'connections');
TCPIPCons = getappdata(handles.buttonConnect,'TCPIPCons');
% close the server connections
if strcmp(role,'server')
if connections == 1
%tcpipServer1 = getappdata(0,'tcpipServer1');
fclose(TCPIPCons{1});
end
if connections == 2
%tcpipServer2 = getappdata(0,'tcpipServer2');
fclose(TCPIPCons{2});
end
if connections == 3
%tcpipServer3 = getappdata(0,'tcpipServer3');
fclose(TCPIPCons{3});
end
% if client, close client connection
else
if connections == 1
tcpipClient = getappdata(0,'tcpipClient');
fclose(tcpipClient);
end
end
% --- Executes on button press in buttonCancel.
function buttonCancel_Callback(hObject, eventdata, handles)
% hObject handle to buttonCancel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Shutdown timer
if isvalid(handles.timer)
stop(handles.timer);
delete(handles.timer);
end
% Close network connections, if any
closeConnections(handles);
figure(main)
close(dataAcq)
% --- Executes on button press in buttonStopAcq.
function buttonStopAcq_Callback(hObject, eventdata, handles)
% hObject handle to buttonStopAcq (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
%setappdata(hObject,'Initialization',false);
function editServerIP_Callback(hObject, eventdata, handles)
% hObject handle to editServerIP (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of editServerIP as text
% str2double(get(hObject,'String')) returns contents of editServerIP as a double
% --- Executes during object creation, after setting all properties.
function editServerIP_CreateFcn(hObject, eventdata, handles)
% hObject handle to editServerIP (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu2
% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in buttonConnect.
function buttonConnect_Callback(hObject, eventdata, handles)
% hObject handle to buttonConnect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.buttonConnect,'Enable','Off');
depth_width = 512; depth_height = 424;
pointcloud = zeros(depth_height*depth_width,3);
pcMetDat = whos('pointcloud');
pointcloudSize = pcMetDat.size;
% Save pointcloud
setappdata(handles.buttonConnect,'pointcloud',pointcloud);
setappdata(handles.buttonConnect,'pointcloudSize',pointcloudSize);
role = getappdata(0,'role');
camCount = getappdata(0,'camCount') - 1;
% Set the number of external clients (cameras), max = 3 (3 clients +
% server)
CON_NUM = camCount; % 1 client + server = 2 Kinects
% Load Camera Network Commands and port numbers
load('TCPIPCommands.mat');
connections = 0;
% If the current computer is the Server
if strcmp(role,'server')
TCPIPCons = cell(0);
% Start a TCP/IP server socket in MATLAB.
% By setting the IP address to '0.0.0.0' the server socket will accept
% connections on the specified port
% (arbitrarily chosen to be 55000 in our case) from any IP address.
% You can restrict the TCP/IP server socket to only accept incoming
% connections from a specific IP address by explicitly specifying the IP address.
if CON_NUM > 0
tcpipServer1 = tcpip('0.0.0.0',PORT1,'NetworkRole','Server');
set(tcpipServer1,'OutputBufferSize',8); % sending one double (8 bytes)
set(tcpipServer1,'InputBufferSize',pcMetDat.bytes); % receive complete pointcloud
set(tcpipServer1,'Timeout',60);
% Save server1
setappdata(0,'tcpipServer1',tcpipServer1);
% Open the server socket and wait indefinitely for a connection.
% This line will cause MATLAB to wait until an incoming connection is established.
disp('TCP Server ready')
disp('Waiting for client 1 ...')
fopen(tcpipServer1);
TCPIPCons{1} = tcpipServer1;
disp('Client 1 connected.')
connections = 1;
end
% If we want more than one client, set up another connection
if CON_NUM > 1
tcpipServer2 = tcpip('0.0.0.0',PORT2,'NetworkRole','Server');
set(tcpipServer2,'OutputBufferSize',8); % sending one double (8 bytes)
set(tcpipServer2,'InputBufferSize',pcMetDat.bytes); % receive complete pointcloud
set(tcpipServer2,'Timeout',30);
% Save server2
setappdata(0,'tcpipServer2',tcpipServer2);
disp('TCP Server ready')
disp('Waiting for client 2...')
fopen(tcpipServer2);
TCPIPCons{2} = tcpipServer2;
disp('Client 2 connected.')
connections = 2;
end
if CON_NUM > 2
tcpipServer3 = tcpip('0.0.0.0',PORT3,'NetworkRole','Server');
set(tcpipServer3,'OutputBufferSize',8); % sending one double (8 bytes)
set(tcpipServer3,'InputBufferSize',pcMetDat.bytes); % receive complete pointcloud
set(tcpipServer3,'Timeout',30);
% Save server3
setappdata(0,'tcpipServer3',tcpipServer3);
disp('TCP Server ready')
disp('Waiting for client 3...')
fopen(tcpipServer3);
TCPIPCons{3} = tcpipServer3;
disp('Client 3 connected.');
connections = 3;
end
% Save the connections
setappdata(handles.buttonConnect,'TCPIPCons',TCPIPCons);
disp(size(TCPIPCons))
% If the computer is a client
else
% get the client ID
clientId = getappdata(0,'clientId');
if clientId == 1
port = PORT1;
elseif clientId == 2
port = PORT2;
elseif clientId == 3
port = PORT3;
end
serverIP = get(handles.editServerIP,'string');
disp(['Trying to connect with server in ' serverIP]);
% Create a MATLAB client connection to our MATLAB server socket.
% The port number of the client must match that selected for the server.
tcpipClient = tcpip(serverIP,port,'NetworkRole','Client');
set(tcpipClient,'InputBufferSize',8);
set(tcpipClient,'OutputBufferSize',pcMetDat.bytes);
set(tcpipClient,'Timeout',60);
% Save client
setappdata(0,'tcpipClient',tcpipClient);
% Open a TCPIP connection to the server
fopen(tcpipClient);
disp('Connected to Server');
disp('Waiting for Commands');
connections = 1;
end % if server
% Save the number of connections
setappdata(handles.figure1,'connections',connections);
% --- Executes on button press in buttonSaveReference.
function buttonSaveReference_Callback(hObject, eventdata, handles)
% hObject handle to buttonSaveReference (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Update the flag
setappdata(handles.axesCam1,'refAReady',true);
% Hide the button and show the clear reference
set(handles.buttonSaveReference,'Visible','Off');
set(handles.buttonClearReference,'Visible','On');
% Enable the start acquisition button if connections > 0
connections = getappdata(handles.figure1,'connections');
if connections > 0
set(handles.buttonStartAcq,'Enable','On');
end
% --- Executes on button press in buttonClearReference.
function buttonClearReference_Callback(hObject, eventdata, handles)
% hObject handle to buttonClearReference (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Update the flag
setappdata(handles.axesCam1,'refAReady',false);
% Hide the button and show the Save reference
set(handles.buttonSaveReference,'Visible','On');
set(handles.buttonClearReference,'Visible','Off');
% Disable the start acquisition button
set(handles.buttonStartAcq,'Enable','Off');
|
github
|
jrterven/MultiKinCalib-master
|
Step02_PreCalibration.m
|
.m
|
MultiKinCalib-master/Step02_PreCalibration.m
| 2,122 |
utf_8
|
431aa2945f529d4c0f09faf5a8c64a1b
|
% function:
% Step02_PreCalibration(camCount,dataAcqFile,preCalibResultsFile)
%
% Description:
% Perform a pre-calibration of the extrinsic parameters of all the
% Kinect cameras.
%
% Dependencies:
% - function proj02_CostFunPreCalib: this function is the one we wish to
% minimize.
% - file 'calibParameters.mat' created with proj0_ServerMultiKinectCalib.
% From this file we use the variables: 'dataDir', 'minFunType', 'pointsToConsider'
% - file dataAcqFile created with proj01_ServerCapturePointsFromCalibObject.m
% From this file we get the calibration camera points of the camera
% we wish to calibrate i.e. cam2.camPoints, cam3.camPoints, etc.
%
% Inputs:
% - camCount: Number of cameras to calibrate
% - dataAcqFile: file containing the data from the acquisition step.
% - preCalibResultsFile: name of the output file containing the results
% of the pre-calibration
%
% Return:
% Save the results on the preCalibResultsFile specified in the arguments
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
function Step02_PreCalibration(camCount,dataAcqFile,preCalibResultsFile)
disp('Step 2: Pre-calibration');
% Estimate extrinsic parameters between camera 1 and camera 2
disp('Estimate extrinsic parameters between camera 1 and camera 2');
[R1_2, t1_2, T1_2] = PreCalib(1,2,dataAcqFile);
save(preCalibResultsFile,'R1_2','t1_2');
if camCount > 2
% Estimate extrinsic parameters between camera 3 and camera 1
disp('Estimate extrinsic parameters between camera 1 and camera 3');
[R1_3, t1_3, T1_3] = PreCalib(1,3,dataAcqFile);
save(preCalibResultsFile,'R1_3','t1_3', '-append');
disp('Estimate extrinsic parameters between camera 2 and 3');
[R2_3, t2_3, T2_3] = PreCalib(2,3,dataAcqFile);
save(preCalibResultsFile,'R2_3','t2_3', '-append');
end
if camCount > 3
% Estimate extrinsic parameters between camera 4 and camera 1
disp('Estimate extrinsic parameters between camera 1 and camera 4');
[R1_4, t1_4, T1_4] = PreCalib(1,4,dataAcqFile);
save(preCalibResultsFile,'R1_4','t1_4', '-append');
end
|
github
|
jrterven/MultiKinCalib-master
|
Step03_Find3DMatches.m
|
.m
|
MultiKinCalib-master/Step03_Find3DMatches.m
| 1,484 |
utf_8
|
f9d34967041fa2644eb59f1ed0f5cad9
|
% function:
% Find3DMatches
%
% Description:
% Find 3D matches
%
% Dependencies:
%
% Inputs:
%
% Usage:
%
% Return:
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: 16-Jan-2016
%
function [cam2_1Matches,cam2_1depthProj,cam2_1colorProj] = Find3DMatches(pc1, pc2, T2_1, ...
cam2DepthProj, cam2ColorProj, minDist3D)
% k2 = Kin2('color','depth');
%
% while true
% validData = k2.updateKin2;
%
% if validData
% break;
% end
% pause(0.03);
% end
% Transform cam2 points to cam1 in order to find matches by distance
pc2 = pc2';
pc2h = [pc2; ones(1,size(pc2,2))];
pc2_1 = T2_1 \ pc2h;
pc2_1 = pc2_1(1:end-1,1:end);
pc2_1 = pc2_1';
% Find matching points between camera 1 and 2
%disp('Searching for Matching Points between cameras');
[cam2_1Matches,cam2_1depthProj,cam2_1colorProj] = matching3DNN(pc1, pc2_1, cam2DepthProj, cam2ColorProj, minDist3D/1000);
disp('Finish finding matching points');
% Transform the matches back to camera 2 and get its 2D projections
% on the depth camera
% cam2PCh = [cam2_1Matches'; ones(1,size(cam2_1Matches,1))];
% cam2PCh = T2_1 * cam2PCh;
% cam2PCh = cam2PCh(1:end-1,1:end)';
% cam2_1depthProj = k2.mapCameraPoints2Depth(cam2PCh);
% and the 2D projections on the color camera
% cam2_1colorProj = k2.mapCameraPoints2Color(cam2PCh);
% k2.delete;
end
|
github
|
jrterven/MultiKinCalib-master
|
main.m
|
.m
|
MultiKinCalib-master/main.m
| 10,290 |
utf_8
|
f65a240ff77f3aa27e9b30e186ff884d
|
function varargout = main(varargin)
% MAIN MATLAB code for main.fig
% MAIN, by itself, creates a new MAIN or raises the existing
% singleton*.
%
% H = MAIN returns the handle to a new MAIN or the handle to
% the existing singleton*.
%
% MAIN('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MAIN.M with the given input arguments.
%
% MAIN('Property','Value',...) creates a new MAIN or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before main_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to main_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help main
% Last Modified by GUIDE v2.5 18-Aug-2016 11:21:17
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @main_OpeningFcn, ...
'gui_OutputFcn', @main_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before main is made visible.
function main_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to main (see VARARGIN)
% Choose default command line output for main
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes main wait for user response (see UIRESUME)
% uiwait(handles.figure1);
displaySetupParams(handles);
% --- Outputs from this function are returned to the command line.
function varargout = main_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in buttonSetup.
function buttonSetup_Callback(hObject, eventdata, handles)
% hObject handle to buttonSetup (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
initialization
% --- Executes on button press in buttonDataAcquisition.
function buttonDataAcquisition_Callback(hObject, eventdata, handles)
% hObject handle to buttonDataAcquisition (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
dataAcq
% --- Executes on button press in buttonPreCalibration.
function buttonPreCalibration_Callback(hObject, eventdata, handles)
% hObject handle to buttonPreCalibration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Step02_PreCalibration(camCount,dataAcqFile,preCalibResultsFile
% --- Executes on button press in buttonMatching.
function buttonMatching_Callback(hObject, eventdata, handles)
% hObject handle to buttonMatching (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Step03_Matching(camCount,dataAcqFile,minDist3D,matchingResultsFile)
% --- Executes on button press in buttonIntrinsicInit.
function buttonIntrinsicInit_Callback(hObject, eventdata, handles)
% hObject handle to buttonIntrinsicInit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Step04_IntrinsicParametersEstimation(camCount,dataAcqFile, ...
preCalibResultsFile,matchingResultsFile,initIntrinsicsFile)
% --- Executes on button press in buttonNonLinearOptim.
function buttonNonLinearOptim_Callback(hObject, eventdata, handles)
% hObject handle to buttonNonLinearOptim (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Step05_FinalCalibration(camCount,preCalibResultsFile,initIntrinsicsFile,finalCalibResults)
% --- Executes on button press in buttonExit.
function buttonExit_Callback(hObject, eventdata, handles)
% hObject handle to buttonExit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close all
function setupData = getSetupData()
role = getappdata(0,'role');
% If server data
if strcmp(role,'server')
camCount = getappdata(0,'clientsCount') + 1;
dataDir = getappdata(0,'dataDir');
countImagesToSave = getappdata(0,'countImagesToSave');
minDist3D = getappdata(0,'minDist3D');
withSkew = getappdata(0,'withSkew');
distortRad = getappdata(0,'distortRad');
distortTan = getappdata(0,'distortTan');
pointsOnStick = getappdata(0,'pointsOnStick');
sizeStick = getappdata(0,'sizeStick');
setupData = struct('role',role,'camCount',camCount, ...
'dataDir',dataDir,'countImagesToSave',countImagesToSave, ...
'minDist3D',minDist3D,'withSkew',withSkew, ...
'distortRad',distortRad,'distortTan',distortTan, ...
'pointsOnStick',pointsOnStick,'sizeStick',sizeStick);
% If client data
else
clientId = getappdata(0,'clientId');
serverIP = getappdata(0,'serverIP');
setupData = struct('role',role,'clientId',clientId,'serverIP',serverIP);
end
function displaySetupParams(handles)
setupDataAvail = getappdata(0,'setupDataAvail');
% If there is not setup data available
if ~setupDataAvail
role = 'server';
camCount = 2;
dataDir = strrep(pwd,'\','/');
countImagesToSave = 10;
minDist3D = 2;
withSkew = logical(1);
distortRad = 0;
distortTan = logical(0);
pointsOnStick = 3;
sizeStick = 30;
% Save data to root directory
setappdata(0,'role',role);
setappdata(0,'camCount',camCount);
setappdata(0,'dataDir',dataDir);
setappdata(0,'countImagesToSave',countImagesToSave);
setappdata(0,'minDist3D',minDist3D);
setappdata(0,'withSkew',withSkew);
setappdata(0,'distortRad',distortRad);
setappdata(0,'distortTan',distortTan);
setappdata(0,'pointsOnStick',pointsOnStick);
setappdata(0,'sizeStick',sizeStick);
[patstr, name, ext] = fileparts(dataDir);
dataDirToShow = name;
sd = struct('role',role,'camCount',camCount, ...
'dataDir',dataDirToShow,'countImagesToSave',countImagesToSave, ...
'minDist3D',minDist3D,'withSkew',withSkew, ...
'distortRad',distortRad,'distortTan',distortTan, ...
'pointsOnStick',pointsOnStick,'sizeStick',sizeStick);
else
sd = getSetupData;
end
% If server
msg = '';
if strcmp(sd.role,'server')
[patstr, name, ext] = fileparts(sd.dataDir);
dataDirToShow = name;
msg = sprintf(['Computer Role: ' sd.role '\n' ...
'Cameras: ' num2str(sd.camCount) '\n' ...
'Images to save: ' num2str(sd.countImagesToSave) '\n' ...
'Output dir: ' dataDirToShow '\n' ...
'Matching distance: ' num2str(sd.minDist3D) '\n' ...
'Skew: ' logical2strYN(sd.withSkew) '\n' ...
'Radial dist coeff: ' num2str(sd.distortRad) '\n' ...
'Tangential dist: ' logical2strYN(sd.distortTan) '\n' ...
'Points on calib object: ' num2str(sd.pointsOnStick) '\n' ...
'Calib object length: ' num2str(sd.sizeStick) 'cm\n']);
% if client
else
msg = sprintf(['Computer Role: ' sd.role '\n' ...
'Client Id: ' num2str(sd.clientId) '\n' ...
'Server IP: ' sd.serverIP '\n']);
end
set(handles.textSetupParams,'string',msg);
function str = logical2strYN(l)
if l
str = 'yes';
else
str = 'no';
end
% --- Executes during object creation, after setting all properties.
function uipanel1_CreateFcn(hObject, eventdata, handles)
% hObject handle to uipanel1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Initialize setupDataAvailable variable
setappdata(0,'setupDataAvail',false);
% --- Executes on button press in buttonPointCloudVis.
function buttonPointCloudVis_Callback(hObject, eventdata, handles)
% hObject handle to buttonPointCloudVis (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
|
github
|
jrterven/MultiKinCalib-master
|
initialization.m
|
.m
|
MultiKinCalib-master/initialization.m
| 24,418 |
utf_8
|
1bdaecd20777d065710faeed395badd0
|
function varargout = initialization(varargin)
% INITIALIZATION MATLAB code for initialization.fig
% INITIALIZATION, by itself, creates a new INITIALIZATION or raises the existing
% singleton*.
%
% H = INITIALIZATION returns the handle to a new INITIALIZATION or the handle to
% the existing singleton*.
%
% INITIALIZATION('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in INITIALIZATION.M with the given input arguments.
%
% INITIALIZATION('Property','Value',...) creates a new INITIALIZATION or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before initialization_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to initialization_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help initialization
% Last Modified by GUIDE v2.5 30-May-2016 23:25:38
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @initialization_OpeningFcn, ...
'gui_OutputFcn', @initialization_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before initialization is made visible.
function initialization_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to initialization (see VARARGIN)
% Choose default command line output for initialization
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes initialization wait for user response (see UIRESUME)
% uiwait(handles.figure1);
initializeServerControls(handles)
% --- Outputs from this function are returned to the command line.
function varargout = initialization_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
sel_val=get(handles.listbox1,'value');
% If Server selected
if sel_val==1
enableServerControls(handles)
% Disable client controls
set(handles.uipanel3,'visible','off');
set(handles.edit8,'string','');
set(handles.edit9,'string','');
% Display the IP address
address = java.net.InetAddress.getLocalHost;
IPaddress = char(address.getHostAddress);
set(handles.text20,'string',IPaddress);
% Else if Client selected
else
set(handles.uipanel3,'visible','on');
disableServerControls(handles)
clearServerControls(handles)
end
function initializeServerControls(handles)
% Initial values
set(handles.edit1,'string','1');
set(handles.edit3,'string',pwd);
set(handles.edit4,'string','10');
set(handles.edit5,'string','2');
set(handles.edit6,'string','3');
set(handles.edit7,'string','60');
set(handles.checkbox1,'value',0);
set(handles.checkbox3,'value',1);
address = java.net.InetAddress.getLocalHost;
IPaddress = char(address.getHostAddress);
set(handles.text20,'string',IPaddress);
function clearServerControls(handles)
set(handles.edit1,'string','');
set(handles.edit3,'string','');
set(handles.edit4,'string','');
set(handles.edit5,'string','');
set(handles.edit6,'string','');
set(handles.edit7,'string','');
set(handles.checkbox1,'value',0);
set(handles.checkbox3,'value',0);
set(handles.text20,'string','');
function disableServerControls(handles)
set(handles.edit1,'enable','off');
set(handles.edit3,'enable','off');
set(handles.edit4,'enable','off');
set(handles.edit5,'enable','off');
set(handles.edit6,'enable','off');
set(handles.edit7,'enable','off');
set(handles.checkbox3,'enable','off');
set(handles.popupmenu1,'enable','off');
set(handles.checkbox1,'enable','off');
function enableServerControls(handles)
set(handles.edit1,'enable','on');
set(handles.edit3,'enable','on');
set(handles.edit4,'enable','on');
set(handles.edit5,'enable','on');
set(handles.edit6,'enable','on');
set(handles.edit7,'enable','on');
set(handles.checkbox3,'enable','on');
set(handles.popupmenu1,'enable','on');
set(handles.checkbox1,'enable','on');
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit3_Callback(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit3 as text
% str2double(get(hObject,'String')) returns contents of edit3 as a double
% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit4_Callback(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit4 as text
% str2double(get(hObject,'String')) returns contents of edit4 as a double
% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit5_Callback(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit5 as text
% str2double(get(hObject,'String')) returns contents of edit5 as a double
% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit6_Callback(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit6 as text
% str2double(get(hObject,'String')) returns contents of edit6 as a double
% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit7_Callback(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit7 as text
% str2double(get(hObject,'String')) returns contents of edit7 as a double
% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
function edit8_Callback(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit8 as text
% str2double(get(hObject,'String')) returns contents of edit8 as a double
% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% read the value from listbox to determine if it was server or client
sel_val=get(handles.listbox1,'value');
% If Server selected
if sel_val==1
% Save data to root directory
setappdata(0,'role','server');
setappdata(0,'clientsCount',str2double(get(handles.edit1,'string')));
dataDir = strrep(get(handles.edit3,'string'),'\','/');
setappdata(0,'dataDir',dataDir);
setappdata(0,'countImagesToSave',str2double(get(handles.edit4,'string')));
setappdata(0,'minDist3D',str2double(get(handles.edit5,'string')));
setappdata(0,'withSkew',logical(get(handles.checkbox3,'value')));
contentsDistortRadMenu = cellstr(get(handles.popupmenu1,'string'));
distortRad = str2double(contentsDistortRadMenu{get(handles.popupmenu1,'Value')});
setappdata(0,'distortRad',distortRad);
setappdata(0,'distortTan',get(handles.checkbox1,'value'));
setappdata(0,'pointsOnStick',str2double(get(handles.edit6,'string')));
setappdata(0,'sizeStick',str2double(get(handles.edit7,'string')));
% if client selected
else
setappdata(0,'role','client');
setappdata(0,'clientId',str2double(get(handles.edit9,'string')));
setappdata(0,'serverIP',get(handles.edit8,'string'));
end
setappdata(0,'setupDataAvail',true);
%on another GUI you want to get the slider properties
%h=findall(0,'tag','textSetupParams');
h = findobj('tag','textSetupParams');
set(h,'String',' ');
figure(main)
close(initialization)
% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject handle to checkbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox1
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in checkbox3.
function checkbox3_Callback(hObject, eventdata, handles)
% hObject handle to checkbox3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox3
% --- Executes on button press in togglebutton2.
function togglebutton2_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton2
function edit9_Callback(hObject, eventdata, handles)
% hObject handle to edit9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit9 as text
% str2double(get(hObject,'String')) returns contents of edit9 as a double
% --- Executes during object creation, after setting all properties.
function edit9_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit10_Callback(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit10 as text
% str2double(get(hObject,'String')) returns contents of edit10 as a double
% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%[filename, pathname]=uiputfile('*.jpeg;*.jpg;*.tiff;*.gif;*.bmp;*.png;*.hdf;*.pcx;*.xwd;*.ico;*.cur;*.ras;*.pbm;*.pgm;*.ppm;', 'Save image');
folder_name = uigetdir;
set(handles.edit3,'string',folder_name);
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
figure(main)
close(initialization)
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[file,path] = uiputfile('*.mat','Save Setup As');
[patstr, name, ext] = fileparts(file);
if strcmp(ext,'.mat') == 0
errordlg('The file must be a .mat')
else
% read the value from listbox to determine if it was server or client
sel_val=get(handles.listbox1,'value');
% If Server selected
if sel_val==1
% get data from controls
role ='server';
camCount = str2double(get(handles.edit1,'string'));
countImagesToSave = str2double(get(handles.edit4,'string'));
dataDir = get(handles.edit3,'string');
minDist3D = str2double(get(handles.edit5,'string'));
withSkew = logical(get(handles.checkbox3,'value'));
contentsDistortRadMenu = cellstr(get(handles.popupmenu1,'string'));
distortRad = str2double(contentsDistortRadMenu{get(handles.popupmenu1,'Value')});
distortRadVal = get(handles.popupmenu1,'Value');
distortTan = get(handles.checkbox1,'value');
pointsOnStick = get(handles.edit6,'string');
sizeStick = str2double(get(handles.edit7,'string'));
% Save the variables in output file
save([path file],'role','camCount','countImagesToSave','dataDir', ...
'minDist3D','withSkew','distortRad','distortRadVal', ...
'distortTan','pointsOnStick','sizeStick');
% if client selected
else
role = 'client';
clientId = str2double(get(handles.edit9,'string'));
serverIP = get(handles.edit8,'string');
% Save the variables in output file
save([path file],'role','clientId','serverIP');
end
msgbox(['File Saved: ' path file],'File Saved')
end
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[FileName,PathName] = uigetfile('*.mat','Select the Setup file');
[patstr, name, ext] = fileparts(FileName);
if strcmp(ext,'.mat') == 0
errordlg('The input file must be a .mat')
else
% load the saved variables into workspace
load([PathName FileName])
% read the value from listbox to determine if it was server or client
currentRole = get(handles.listbox1,'value');
% If the data saved was from server
if strcmp(role,'server')
% If the role read is server, and the current role is client
% display an error
if currentRole ~= 1
errordlg(['Loading Server data with Client role selected. ' ...
'Please select the Server role first']);
% copy the loaded variables into the controls
else
set(handles.edit1,'string',num2str(camCount));
set(handles.edit4,'string',num2str(countImagesToSave));
set(handles.edit3,'string',dataDir);
set(handles.edit5,'string',num2str(minDist3D));
set(handles.checkbox3,'value',withSkew);
set(handles.popupmenu1,'Value',distortRadVal);
set(handles.checkbox1,'value',distortTan);
set(handles.edit6,'string',pointsOnStick);
set(handles.edit7,'string',num2str(sizeStick));
end
else strcmp(role,'client')
% If the role read is client, and the current role is server
% display an error
if currentRole ~= 2
errordlg(['Loading Client data with Server role selected. ' ...
'Please select the Client role first']);
% copy the loaded variables into the controls
else
set(handles.edit9,'string',num2str(clientId));
set(handles.edit8,'string',serverIP);
end
end
end
% --- Executes during object creation, after setting all properties.
function text20_CreateFcn(hObject, eventdata, handles)
% hObject handle to text20 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over text20.
function text20_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to text20 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
address = java.net.InetAddress.getLocalHost;
IPaddress = char(address.getHostAddress);
set(handles.text20,'string',IPaddress);
|
github
|
jrterven/MultiKinCalib-master
|
Step04_IntrinsicParametersEstimation.m
|
.m
|
MultiKinCalib-master/Step04_IntrinsicParametersEstimation.m
| 2,917 |
utf_8
|
1ba76157c5d145557316901747069e5b
|
% function:
% Step04_IntrinsicParametersEstimation(camCount,dataAcqFile,preCalibResultsFile,matchingResultsFile,initIntrinsicsFile)
%
% Description:
% Estimates intrinsics parameters for all the cameras (depth and color
% for each Kinect).
%
% Dependencies:
% - function EstimateIntrins: estimates the camera intrinsics using the method from
% Prince, Simon JD. Computer vision: models, learning, and inference.
% Cambridge University Press, 2012.
%
% Inputs:
% - camCount: Number of cameras to calibrate
% - dataAcqFile: file containing the data from the acquisition step.
% - preCalibResultsFile: name of the output file containing the results
% of the pre-calibration
% - matchingResultsFile: out file containing the matching results.
% - initIntrinsicsFile: out file with the estimated intrinsic parameters.
%
% Return:
% Save the results on the initIntrinsicsFile specified in the arguments.
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
% Date: Feb-2016
function Step04_IntrinsicParametersEstimation(dataAcqFile,matchingResultsFile,preCalibResultsFile,initIntrinsicsFile)
% Initialize Intrinsics of depth cam1 using its pointcloud
preIntrinsicsD1 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,1, 'depth');
% Initialize Intrinsics of color cam1 using its pointcloud
preIntrinsicsC1 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,1, 'color');
save(initIntrinsicsFile,'preIntrinsicsD1','preIntrinsicsC1');
if camCount > 1
% Initialize Intrinsics of depth cam2 using the pointclouds matches with cam1
preIntrinsicsD2 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,2, 'depth');
% Initialize Intrinsics of color cam2 using the pointclouds matches with cam1
preIntrinsicsC2 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,2, 'color');
save(initIntrinsicsFile,'preIntrinsicsD2','preIntrinsicsC2','-append');
end
if camCount > 2
% Initialize Intrinsics of depth cam2 using the pointclouds matches with cam1
preIntrinsicsD3 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,3, 'depth');
% Initialize Intrinsics of color cam2 using the pointclouds matches with cam1
preIntrinsicsC3 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,3, 'color');
save(initIntrinsicsFile,'preIntrinsicsD3','preIntrinsicsC3','-append');
end
if camCount > 3
% Initialize Intrinsics of depth cam2 using the pointclouds matches with cam1
preIntrinsicsD4 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,4, 'depth');
% Initialize Intrinsics of color cam2 using the pointclouds matches with cam1
preIntrinsicsC4 = EstimateIntrins(dataAcqFile,matchingResultsFile,preCalibResultsFile,4, 'color');
save(initIntrinsicsFile,'preIntrinsicsD4','preIntrinsicsC4','-append');
end
|
github
|
jrterven/MultiKinCalib-master
|
matching3DNN.m
|
.m
|
MultiKinCalib-master/matching3DNN.m
| 3,446 |
utf_8
|
65dcfbeedd901cb8df56256989086f61
|
% Function:
% matching3DNN
%
% Description:
% Given two input pointclouds (cam1PC, cam2PC), finds the matching points.
% Matching points are searched using 1-Nearest Neighbor with a threshold
% value of epsilon millimeters.
%
% Usage:
%
%
% Params:
% cam1PC : Pointcloud from camera 1 in n x 3
% cam2PC : Pointcloud from camera 2 in n x 3
% epsilon: Max distance between corresponding points in meters
%
% Return:
% cam1MatchedPoints : Matched points in camera 1 in m x 3
% cam2MatchedPoints : Matched points in camera 2 in m x 3
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
%
% Citation:
% Put the paper here!
%
% Date: 09-Jan-2016
function [cam2_1MatchedPoints, matchedDepthProj, matchedColorProj] = matching3DNN( ...
cam1PC, cam2PC, cam2DepthProj, cam2ColorProj, epsilon)
% Remove inf and NaN values from input pointclouds
cam1PCvalidRows = ~any( isnan( cam1PC ) | isinf( cam1PC ), 2 );
cam2PCvalidRows = ~any( isnan( cam2PC ) | isinf( cam2PC ), 2 );
cam1PC = cam1PC(cam1PCvalidRows,:);
cam2PC = cam2PC(cam2PCvalidRows,:);
cam2DepthProj = cam2DepthProj(cam2PCvalidRows,:);
cam2ColorProj = cam2ColorProj(cam2PCvalidRows,:);
% VERSION 3: Using knnsearch from
%http://www.mathworks.com/matlabcentral/fileexchange/19345-efficient-k-nearest-neighbor-search-using-jit
[idx, D] = knnsearch(cam1PC,cam2PC);
% idx contains the indices of cam2PC with the smallest distance to each
% cam1PC
% Find the points with distance less than epsilon
matchedIdx = idx(D <= epsilon);
cam2_1MatchedPoints = cam2PC(matchedIdx,:);
matchedDepthProj = cam2DepthProj(matchedIdx,:);
matchedColorProj = cam2ColorProj(matchedIdx,:);
% VERSION 2: Using pdist2 Matlab function, partitioning the pointclouds
% in 100 parts for storage
% Brute search for the nearest point to each point from cam1PC in cam2PC
% iout = 1;
%
% elemPerPartition = floor(size(cam1PC,1)/100);
%
% for i1=0:99
% idx = uint32(floor(i1*elemPerPartition + 1:elemPerPartition*(i1+1)));
% cam1PCpart = cam1PC(idx,:);
% D = pdist2(cam1PCpart, cam2PC);
% [r,c] = find(D<epsilon);
%
% cam1MatchedPoints = [cam1MatchedPoints; cam1PC(r + i1*elemPerPartition,:)];
% cam2MatchedPoints = [cam2MatchedPoints; cam2PC(c,:)];
%
% disp(i1);
% end
% VERSION 1: Using vectorized Euclidean distance
% for i1=1:size(cam1PC,1) % for each point in cam1PC
%
% % calculate the distance of point i1 from cam1PC to all the points
% % in cam2PC
%
% % replicate the i1th component of cam1PC cam2PC times in order to
% % vectorize the operation
% pc1 = repmat(cam1PC(i1,:),size(cam2PC,1),1);
% D = sqrt(sum(abs(pc1 - cam2PC).^2,2));
%
% % D have all the distances, find the index of the minimun value
% [m,idx] = min(D);
%
% % If the minimum value is less than the theshold we have a match
% % save the point on both output pointclouds
% % and remove from the cam2PC search
% if m < epsilon
% cam1MatchedPoints(iout,:) = cam1PC(i1,:);
% cam2MatchedPoints(iout,:) = cam2PC(idx,:);
%
% cam2PC(idx,:) = [];
% iout = iout + 1;
% end
% end
end
|
github
|
jrterven/MultiKinCalib-master
|
trackCalibPoints.m
|
.m
|
MultiKinCalib-master/trackCalibPoints.m
| 6,387 |
utf_8
|
14c24c13dab8f66c2f04b7b0b186dfad
|
% Function:
% trackCalibPoints
%
% Description:
% Search for three or six red points in a stick of SIZE_AF. It uses color space
% and camera space to detect the points in the color image and its 3D
% coordinates as well in order to verify that the points lie in a stick
% and that the dimensions of the stick are correct.
%
% a b c d e f
% o--o--o--o--o--o
%
% Dependencies:
% Kin2 class
%
% Inputs:
% kinect: Kin2 object
% colorFrame: color camera frame
% a_refw: Infrared marker position. Used to find point A
% SIZE_AB: Length of the stick
%
% Usage:
% This function is called during the calibration images acquisition step.
%
% Returns:
% validBalls: flag indicating a successful detection
% points: 6x2 vector of 2D position of the balls in color space
%
% Author:
% Juan R. Terven
% Date: 15-Jan-2016
function [validBalls, points] = trackCalibPoints(kinect, colorFrame, ...
pointsOnStick, a_refw, SIZE_AF)
points = zeros(pointsOnStick,2);
validBalls = false;
% To track red objects in real time
% we have to subtract the red component
% from the grayscale image to extract the red components in the image.
diff_im = imsubtract(colorFrame(:,:,1), rgb2gray(colorFrame));
%Use a median filter to filter out noise
diff_im = medfilt2(diff_im, [3 3]);
% Convert the resulting grayscale image into a binary image.
diff_im = im2bw(diff_im,0.18);
% Remove all those pixels less than 300px
diff_im = bwareaopen(diff_im,30);
% Label all the connected components in the image.
bw = bwlabel(diff_im, 8);
% Here we do the image blob analysis.
% We get a set of properties for each labeled region.
stats = regionprops(bw, 'BoundingBox', 'Centroid');
numObjects = length(stats);
temp = zeros(numObjects,2);
for i=1:numObjects
temp(i,:) = stats(i).Centroid;
end
if ~isempty(temp)
hold on
plot(temp(:,1),temp(:,2),'k*', 'MarkerSize',10)
hold off
end
% Continue if it found at least pointsOnStick objects
if numObjects >= pointsOnStick
%disp(['numObjects:' num2str(numObjects)]);
% Get these points on camera space from color to camera
wtemp = kinect.mapColorPoints2Camera(temp);
% Calculate the distance from each point (in camera coordinates)
% to the reference point (extracted from the infrared image)
dist_2_Aw = zeros(numObjects,1);
for i=1:numObjects
dist_2_Aw(i) = sqrt((a_refw(1)-wtemp(i,1))^2 + ...
(a_refw(2)-wtemp(i,2))^2) + ...
(a_refw(3)-wtemp(i,3))^2;
end
% Find a,b,c,d,e,f in order where a is the closest point to a_ref,
% then b, and so on
[~, idx] = sort(dist_2_Aw);
points = temp(idx,:);
pointsw = wtemp(idx,:);
points = points(1:pointsOnStick,:); % select only the first pointsOnStick
% Plot the possible balls in yellow
hold on
plot(points(:,1),points(:,2),'y*', 'MarkerSize',15)
hold off
% Check that all the points are inside a line between a and f
ai = double(points(1,:)); % point a in the image (ai)
bi = double(points(2,:));
ci = double(points(3,:));
if pointsOnStick == 6
di = double(points(4,:));
ei = double(points(5,:));
fi = double(points(6,:));
end
% for this we calculate the slope
if pointsOnStick == 3
m = (ci(2)-ai(2))/(ci(1)-ai(1));
elseif pointsOnStick == 6
m = (fi(2)-ai(2))/(fi(1)-ai(1));
end
% given the point-slope equation of a line
% y - y1 = m(x - x1)
% (x1, y1) will be the coordinates of the A extreme of the line
% and we will calculate the y component of b,c,d,e
yb = m * (bi(1) - ai(1)) + ai(2);
if pointsOnStick == 6
yc = m * (ci(1) - ai(1)) + ai(2);
yd = m * (di(1) - ai(1)) + ai(2);
ye = m * (ei(1) - ai(1)) + ai(2);
end
% The calculated y component of the points (yb, yc, yd, ye) must be
% equal (ideally) of the actual y component of points (bi(2),
% ci(2), di(2) and ei(2)
% lets give it alpha pixels of error
alpha = 20;
if pointsOnStick == 3
if abs(yb-bi(2)) > alpha
disp('No points on a line')
return;
end
elseif pointsOnStick == 6
if abs(yb-bi(2)) > alpha || abs(yc-ci(2)) > alpha || ...
abs(yd-di(2)) > alpha || abs(ye-ei(2)) > alpha
disp('No points on a line')
return;
end
end
% Validate the coordinates of the points by size using its camera
% space values (X,Y,Z)
sizeAB = norm(pointsw(1,:) - pointsw(2,:));
sizeAC = norm(pointsw(1,:) - pointsw(3,:));
if pointsOnStick == 6
sizeAD = norm(pointsw(1,:) - pointsw(4,:));
sizeAE = norm(pointsw(1,:) - pointsw(5,:));
sizeAF = norm(pointsw(1,:) - pointsw(6,:));
end
if pointsOnStick == 3
if sizeAC > (SIZE_AF - 0.2) && sizeAC < (SIZE_AF + 0.2) && ...
sizeAB < sizeAC
validBalls = true;
disp('VALID balls')
end
elseif pointsOnStick == 6
if sizeAF > (SIZE_AF - 0.2) && sizeAF < (SIZE_AF + 0.2) && ...
sizeAB < sizeAF && sizeAC < sizeAF && sizeAD < sizeAF && ...
sizeAE < sizeAF
validBalls = true;
disp('VALID balls')
end
end
%disp(['Distances btw points: ' num2str(sizeAB) ' ' num2str(sizeAC) ' ' num2str(sizeAD) ' ' num2str(sizeAE) ' ' num2str(sizeAF) ' ' ])
else
disp(['Not found at least ' num2str(pointsOnStick) ' objects']);
end % if numObjects >=3
end % end trackBalls function
|
github
|
jrterven/MultiKinCalib-master
|
findPointAfromInfrared.m
|
.m
|
MultiKinCalib-master/findPointAfromInfrared.m
| 2,640 |
utf_8
|
2dbc61d7a6cb99b8a8580f0df3fab990
|
% Function:
% findPointAfromInfrared
%
% Description:
% Finds the nearest 3D world point to the marker.
% The point A is the fixed point, we use a reflective tape on the
% ground near this point. So when detecting the red points, the nearest
% point to this (refAw) will be point A.
%
% Dependencies:
% Kin2 class
%
%
% Inputs:
% kinect: Kin2 object
%
% Usage:
% This function is called at the beggining of the images acquisition for
% calibration. This function returns the location of the infrared marker
% (reflective tape) such that this point be used for detecting the
% reference point in the calibration object.
%
% Returns:
% refAw: position of the infrared marker in camera space (X,Y,Z).
% refAc: poistion of the infrared marker in color space (x,y)
%
% Authors:
% Diana M. Cordova
% Juan R. Terven
%
% Date: 05-June-2016
function [refAw, refAc] = findPointAfromInfrared(kinect, infrared)
imgBW = im2bw(infrared);
% Remove all those pixels less than 300px
imgBW = bwareaopen(imgBW,5);
% calculate the centroid
stat = regionprops(imgBW,'centroid');
refAw = zeros(1,3);
refAc = zeros(1,2);
if length(stat) >= 1
refA = stat(1).Centroid;
% Search for the nearest neighbor that can be mapped to
% camera space
movement = 1; % move 1 pixel
n1 = refA; n2 = refA; n3 = refA; n4 = refA;
for i=1:100
% Move refA on the 4 neighbors
n1(1) = n1(1) + movement; % move in positive x direction
n2(1) = n2(1) - movement; % move in negative x direction
n3(2) = n3(2) + movement;
n4(2) = n4(2) - movement;
ns = [n1;n2;n3;n4];
refAws = kinect.mapDepthPoints2Camera(ns);
if ~isinf(refAws(1,1))
refAw = refAws(1,:);
break;
elseif ~isinf(refAws(2,1))
refAw = refAws(2,:);
break;
elseif ~isinf(refAws(3,1))
refAw = refAws(3,:);
break;
elseif ~isinf(refAws(4,1))
refAw = refAws(4,:);
break;
end
movement = movement + 1;
end
refAc = kinect.mapCameraPoints2Color(refAw);
%plot(refAc(1),refAc(2),'y*')
end
end % findPointAfromInfrared function
|
github
|
jrterven/MultiKinCalib-master
|
calibCostFun.m
|
.m
|
MultiKinCalib-master/Kin2/Mex/calibCostFun.m
| 2,431 |
utf_8
|
971b01fffa44b09203d158efc55dc03e
|
function fun = calibCostFun(x0)
persistent X3d x2d quatRot
height = 1080;
width = 1920;
% The first iteration loads the data
if isempty(X3d)
X3d = [];
x2d = [];
% Get the 3D points from the matching results
% 3D points as a 3 x n matrix
load('calibData.mat');
quatRot = rot;
X3d = pointcloud';
% 2D points as a 2 x n matrix
x2d = double(proj2d)';
% Remove outliers from X3d in both matrices
x2dValidCols = ~any( isnan( x2d ) | isinf( x2d ) | x2d > width | x2d < 0, 1 );
x3dValidCols = ~any( isnan( X3d ) | isinf( X3d ) | X3d > 8, 1 );
validCols = x2dValidCols & x3dValidCols;
x2d = x2d(:,validCols);
X3d = X3d(:,validCols);
end
f = x0(1); % focal length
cx = x0(2); % principal point x
cy = x0(3); % principal point y
% Rotation
Rq = [x0(4) x0(5) x0(6) x0(7)];
if quatRot
R = quat2rotm(Rq);
else
R = eye(3);
end
% Translation
t = [x0(8);x0(9);x0(10)];
% Build camera matrix
intrinsic = [f 0 cx;
0 f cy;
0 0 1];
k1 = x0(11);
k2 = x0(12);
k3 = x0(13);
N = size(X3d,2);
Xw = X3d;
xc = x2d;
xc(2,:) = height - xc(2,:);
% Apply extrinsic parameters
proj = R * Xw + repmat(t,1,size(Xw,2));
% Apply Intrinsic parameters to get the projection
proj = intrinsic * proj;
% Dehomogenization
proj = proj ./ repmat(proj(3,:),3,1);
u = proj(1,:);
v = proj(2,:);
ud=xc(1,:);
vd=xc(2,:);
% Normalized coordinates in the image plane
un = (u - cx)/f;
vn = (v - cy)/f;
% Calculate the Radial Distortion
r = sqrt(un.^2 + vn.^2);
compRad(1,:) = 1 + k1*r.^2 + k2*r.^4 + k3*r.^6;
compRad(2,:) = 1 + k1*r.^2 + k2*r.^4 + k3*r.^6;
% Undistort the normalized point coordinates in the image plane
un_undist = un.*compRad(1,:);
vn_undist = vn.*compRad(2,:);
% Unormalized the points
u_undist = (un_undist * f) + cx;
v_undist = (vn_undist * f) + cy;
% Reprojection error
fun(1,:)= u_undist - ud;
fun(2,:)= v_undist - vd;
err = fun .* fun;
err = sum(err(:));
%disp(sqrt(err/N));
end
|
github
|
bearsroom/mxnet-augmented-master
|
parse_json.m
|
.m
|
mxnet-augmented-master/matlab/+mxnet/private/parse_json.m
| 19,095 |
utf_8
|
2d934e0eae2779e69f5c3883b8f89963
|
function data = parse_json(fname,varargin)
%PARSE_JSON parse a JSON (JavaScript Object Notation) file or string
%
% Based on jsonlab (https://github.com/fangq/jsonlab) created by Qianqian Fang. Jsonlab is lisonced under BSD or GPL v3.
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
function opt=varargin2struct(varargin)
%
% opt=varargin2struct('param1',value1,'param2',value2,...)
% or
% opt=varargin2struct(...,optstruct,...)
%
% convert a series of input parameters into a structure
%
% input:
% 'param', value: the input parameters should be pairs of a string and a value
% optstruct: if a parameter is a struct, the fields will be merged to the output struct
%
% output:
% opt: a struct where opt.param1=value1, opt.param2=value2 ...
%
len=length(varargin);
opt=struct;
if(len==0) return; end
i=1;
while(i<=len)
if(isstruct(varargin{i}))
opt=mergestruct(opt,varargin{i});
elseif(ischar(varargin{i}) && i<len)
opt=setfield(opt,lower(varargin{i}),varargin{i+1});
i=i+1;
else
error('input must be in the form of ...,''name'',value,... pairs or structs');
end
i=i+1;
end
function val=jsonopt(key,default,varargin)
%
% val=jsonopt(key,default,optstruct)
%
% setting options based on a struct. The struct can be produced
% by varargin2struct from a list of 'param','value' pairs
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $
%
% input:
% key: a string with which one look up a value from a struct
% default: if the key does not exist, return default
% optstruct: a struct where each sub-field is a key
%
% output:
% val: if key exists, val=optstruct.key; otherwise val=default
%
val=default;
if(nargin<=2) return; end
opt=varargin{1};
if(isstruct(opt))
if(isfield(opt,key))
val=getfield(opt,key);
elseif(isfield(opt,lower(key)))
val=getfield(opt,lower(key));
end
end
function s=mergestruct(s1,s2)
%
% s=mergestruct(s1,s2)
%
% merge two struct objects into one
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2012/12/22
%
% input:
% s1,s2: a struct object, s1 and s2 can not be arrays
%
% output:
% s: the merged struct object. fields in s1 and s2 will be combined in s.
if(~isstruct(s1) || ~isstruct(s2))
error('input parameters contain non-struct');
end
if(length(s1)>1 || length(s2)>1)
error('can not merge struct arrays');
end
fn=fieldnames(s2);
s=s1;
for i=1:length(fn)
s=setfield(s,fn{i},getfield(s2,fn{i}));
end
function newdata=struct2jdata(data,varargin)
%
% newdata=struct2jdata(data,opt,...)
%
% convert a JData object (in the form of a struct array) into an array
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
%
% input:
% data: a struct array. If data contains JData keywords in the first
% level children, these fields are parsed and regrouped into a
% data object (arrays, trees, graphs etc) based on JData
% specification. The JData keywords are
% "_ArrayType_", "_ArraySize_", "_ArrayData_"
% "_ArrayIsSparse_", "_ArrayIsComplex_"
% opt: (optional) a list of 'Param',value pairs for additional options
% The supported options include
% 'Recursive', if set to 1, will apply the conversion to
% every child; 0 to disable
%
% output:
% newdata: the covnerted data if the input data does contain a JData
% structure; otherwise, the same as the input.
%
% examples:
% obj=struct('_ArrayType_','double','_ArraySize_',[2 3],
% '_ArrayIsSparse_',1 ,'_ArrayData_',null);
% ubjdata=struct2jdata(obj);
fn=fieldnames(data);
newdata=data;
len=length(data);
if(jsonopt('Recursive',0,varargin{:})==1)
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
|
github
|
SholtoForbes/3D-master
|
SPARTANAero.m
|
.m
|
3D-master/SPARTANAero.m
| 2,085 |
utf_8
|
4c8472352b93571e9675cc32a6992ac9
|
% Defines the aerodynamics of the SPARTAN over a range of Mach no.s
% Created by Sholto Forbes-Spyratos
% Uses equations defined in the Aerodynamics section of Aircraft Design: A Conceptual Approach by
% Raymer
% M = 2
% alpha = 0
% v = 2*300
% rho = 0.412707
% mu = 0.0000146884
function CL = SPARTANAero(M,alpha,v,rho,mu)
geom.b = 4.45*2; % Wingspan (m)
geom.c = 9.791; % Root Chord (m)
geom.d = 1.0499*2; % Fuselage Diameter (m)
geom.S_ref = 0.5*4.45*12.8159; % Wing Reference Area (m^2)
geom.A = geom.b^2/geom.S_ref; % Aspect Ratio
geom.S_exposed = 0.5*(4.45 - 1.0499)*9.7910; % Wing Reference Area (m^2)
geom.Lambda = deg2rad(19.1505); % Wing Sweep at Chord Location (rad)
geom.L_tot = 22.94; % Total Length (m)
if M < 0.8
CL = SubSonic(M,alpha,geom)
elseif (0.8 <= M) && (M <= 1.2)
elseif (1.2 < M) && (M < 3)
CL = SuperSonic(M,alpha)
elseif M >= 3
CL = SuperSonic(M,alpha)
end
l_fuselage = geom.L_tot;
l_wing = geom.c/2; % Mean Chord (m)
R_fuselage = rho*v*l_fuselage/mu % Reynolds no. Fuselage
R_wing = rho*v*l_wing/mu % Reynolds no. Wings
% R_tail = rho*v*l_tail/mu; % Reynolds no. Tails
Cf_fuselage = 0.455 / ( log10(R_fuselage)^2.58 * (1 + 0.144*M^2)^0.65) % Fiction Coefficient Fuselage
Cf_wing = 0.455 / ( log10(R_wing)^2.58 * (1 + 0.144*M^2)^0.65) % Fiction Coefficient Fuselage
end
function CL = SuperSonic(M,alpha)
beta = sqrt(M^2 - 1);
CL_alpha = 4/beta; % Lift Coefficient per Unit Angle of Attack (Radians)
CL = CL_alpha * alpha;
end
function CL = SubSonic(M,alpha,geom)
A = geom.A; % Aspect Ratio
b = geom.b; % Wingspan (m)
c = geom.c; % Chord length (m)
d = geom.d; % Fuselage Diameter (m)
S_ref = geom.S_ref; % Wing Reference Area (m^2)
S_exposed = geom.S_exposed; % Wing Reference Area (m^2)
Lambda = geom.Lambda; % Wing Sweep at Chord Location (rad)
cl_alpha = 2*pi;
Cl_alpha = cl_alpha*(0.5*c*(b-d));
beta = sqrt(M^2 - 1);
F = 1.07 * (1 + d/b)^2;
eta = Cl_alpha/(2*pi/beta);
CL_alpha = 2*pi*A / (2 + sqrt(4 + A^2 * beta^2 / eta^2 * (1 + tan(Lambda)^2 / beta^2))) * S_exposed / S_ref * F
CL = CL_alpha * alpha;
end
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_uc.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_uc.m
| 2,149 |
utf_8
|
1e2590e75d2981d64bbabd3d8738a9e1
|
% used in tests of,
% - unit commitment, generator 4 should be de-commited due to high cost
function mpc = case5_uc
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 100.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000 2.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
4 3 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5.m
| 2,695 |
utf_8
|
8055caaf1bbf7650f27dffaf2c09e662
|
% used in tests of,
% - non-contiguous bus ids
% - tranformer orentation swapping
% - dual values
% - clipping cost functions using ncost
% - linear objective function
% - bus type correction
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 0 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000 2.000000;
2 0.0 0.0 3 0.100000 0.000000 0.000000 2.000000; % skipped by powermodels
2 0.0 0.0 3 0.100000 0.000000 0.000000 2.000000; % skipped by powermodels
2 0.0 0.0 3 0.100000 0.000000 0.000000 2.000000; % skipped by powermodels
2 0.0 0.0 3 0.100000 0.000000 0.000000 2.000000; % skipped by powermodels
2 0.0 0.0 3 0.100000 0.000000 0.000000 2.000000; % skipped by powermodels
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
4 3 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case7_tplgy.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case7_tplgy.m
| 2,764 |
utf_8
|
ac81a346a20940f9e41c1ea739b3cd8e
|
%
% Test for component status pre-processing
%
function mpc = case7_tplgy
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0.0 0.0 0.0 0.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
2 2 100.0 50.0 1.0 5.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
3 1 0.0 0.0 0.0 0.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
4 1 100.0 50.0 0.0 0.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
5 2 0.0 0.0 1.0 5.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
6 4 100.0 50.0 1.0 5.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
7 1 50.0 10.0 1.0 5.0 1 1.00000 0.00000 240.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 0.000 0.000 1000.0 -1000.0 1.00000 100.0 1 200.0 0.0;
2 0.000 0.000 1000.0 -1000.0 1.00000 100.0 1 140.0 0.0;
5 0.000 0.000 100.0 -100.0 1.00000 100.0 1 330.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 1.000000 0.000000;
2 0.0 0.0 3 0.000000 1.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 3 0.065 0.62 0.00 30.0 0.0 0.0 0.0 0.0 0 -30.0 30.0;
1 4 0.012 0.53 0.00 60.0 0.0 0.0 0.0 0.0 0 -30.0 30.0;
1 5 0.042 0.90 0.00 60.0 0.0 0.0 0.0 0.0 0 -30.0 30.0;
2 3 0.075 0.51 0.00 45.0 0.0 0.0 0.0 0.0 0 -30.0 30.0;
3 5 0.025 0.75 0.25 30.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
3 6 0.025 0.75 0.25 30.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
5 6 0.025 0.75 0.25 30.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
4 5 0.025 0.07 0.05 300.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
];
%% dcline data
% fbus tbus status Pf Pt Qf Qt Vf Vt Pmin Pmax QminF QmaxF QminT QmaxT loss0 loss1
mpc.dcline = [
1 2 0 10 9.0 99.0 -10.0 1.0000 1.0000 10 100 -100 100 -100 100 10.00 0.00;
5 6 1 10 9.0 99.0 -10.0 1.0000 1.0000 0 200 -100 100 -100 100 10.00 0.00;
7 4 1 10 9.0 99.0 -10.0 1.0000 1.0000 -200 0 -100 100 -100 100 10.00 0.00;
];
%% storage data
% storage_bus ps qs energy energy_rating charge_rating discharge_rating charge_efficiency discharge_efficiency thermal_rating qmin qmax r x p_loss q_loss status
mpc.storage = [
6 0.0 0.0 20.0 100.0 50.0 70.0 0.8 0.9 100.0 -50.0 70.0 0.1 0.0 0.0 0.0 1;
];
%% switch data
% f_bus t_bus psw qsw state thermal_rating status
mpc.switch = [
1 6 0.0 0.00 1 1000.0 0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_db.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_db.m
| 1,886 |
utf_8
|
fbdf969ad340385a2f86ad61d100b724
|
% tests network with dangeling buses, a feature that occurs in many large datasets
function mpc = case5_dc
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 1 300.0 98.61 0.0 0.0 1 1.06355 2.87619 230.0 1 1.10000 0.90000;
2 1 0.0 0.00 0.0 0.0 1 1.08009 -0.79708 230.0 1 1.10000 0.90000;
3 1 0.0 0.00 0.0 0.0 1 1.10000 -0.64925 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000;
5 1 300.0 98.61 0.0 0.0 1 1.05304 3.70099 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.06355 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
4 0.0 -70.8186 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
5 463.5555 -184.9224 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 2 14.000000 0.000000;
2 0.0 0.0 2 15.000000 0.000000;
2 0.0 0.0 2 40.000000 0.000000;
2 0.0 0.0 2 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
%% dcline data
% fbus tbus status Pf Pt Qf Qt Vf Vt Pmin Pmax QminF QmaxF QminT QmaxT loss0 loss1
mpc.dcline = [
3 5 1 10 8.9 99.9934 -10.4049 1.1 1.05555 0 100 -100 100 -100 100 0 0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case14.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case14.m
| 4,769 |
utf_8
|
83581c937c4e1a14e1886d8ecfe80176
|
% Case to test no explicit branch limits
% from matpower - http://www.pserc.cornell.edu/matpower/
function mpc = case14
%CASE14 Power flow data for IEEE 14 bus test case.
% Please see CASEFORMAT for details on the case file format.
% This data was converted from IEEE Common Data Format
% (ieee14cdf.txt) on 15-Oct-2014 by cdf2matp, rev. 2393
% See end of file for warnings generated during conversion.
%
% Converted from IEEE CDF file from:
% http://www.ee.washington.edu/research/pstca/
%
% 08/19/93 UW ARCHIVE 100.0 1962 W IEEE 14 Bus Test Case
% MATPOWER
%% MATPOWER Case Format : Version 2
mpc.version = '2';
%%----- Power Flow Data -----%%
%% system MVA base
mpc.baseMVA = 100;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0 0 0 0 1 1.06 0 0 1 1.06 0.94;
2 2 21.7 12.7 0 0 1 1.045 -4.98 0 1 1.06 0.94;
3 2 94.2 19 0 0 1 1.01 -12.72 0 1 1.06 0.94;
4 1 47.8 -3.9 0 0 1 1.019 -10.33 0 1 1.06 0.94;
5 1 7.6 1.6 0 0 1 1.02 -8.78 0 1 1.06 0.94;
6 2 11.2 7.5 0 0 1 1.07 -14.22 0 1 1.06 0.94;
7 1 0 0 0 0 1 1.062 -13.37 0 1 1.06 0.94;
8 1 0 0 0 0 1 1.09 -13.36 0 1 1.06 0.94;
9 1 29.5 16.6 0 19 1 1.056 -14.94 0 1 1.06 0.94;
10 1 9 5.8 0 0 1 1.051 -15.1 0 1 1.06 0.94;
11 1 3.5 1.8 0 0 1 1.057 -14.79 0 1 1.06 0.94;
12 1 6.1 1.6 0 0 1 1.055 -15.07 0 1 1.06 0.94;
13 1 13.5 5.8 0 0 1 1.05 -15.16 0 1 1.06 0.94;
14 1 14.9 5 0 0 1 1.036 -16.04 0 1 1.06 0.94;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf
mpc.gen = [
1 232.4 -16.9 10 0 1.06 100 1 332.4 0 0 0 0 0 0 0 1.0 0 0 0 0;
2 40 42.4 50 -40 1.045 100 1 140.0 0 0 0 0 0 0 0 0 1.0 0 0 0;
3 0 23.4 40 0 1.01 100 1 100.0 0 0 0 0 0 0 0 0 0 1.0 0 0;
6 0 12.2 24 -6 1.07 100 1 100.0 0 0 0 0 0 0 0 0 0 0 1.0 0;
8 0 17.4 24 -6 1.09 100 1 100.0 0 0 0 0 0 0 0 0 0 0 0 0;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.01938 0.05917 0.0528 0 0 0 0 0 1 -360 360;
1 5 0.05403 0.22304 0.0492 0 0 0 0 0 1 -360 360;
2 3 0.04699 0.19797 0.0438 0 0 0 0 0 1 -360 360;
2 4 0.05811 0.17632 0.034 0 0 0 0 0 1 -360 360;
2 5 0.05695 0.17388 0.0346 0 0 0 0 0 1 -360 360;
3 4 0.06701 0.17103 0.0128 0 0 0 0 0 1 -360 360;
4 5 0.01335 0.04211 0 0 0 0 0 0 1 -360 360;
4 7 0 0.20912 0 0 0 0 0.978 0 1 -360 360;
4 9 0 0.55618 0 0 0 0 0.969 0 1 -360 360;
5 6 0 0.25202 0 0 0 0 0.932 0 1 -360 360;
6 11 0.09498 0.1989 0 0 0 0 0 0 1 -360 360;
6 12 0.12291 0.25581 0 0 0 0 0 0 1 -360 360;
6 13 0.06615 0.13027 0 0 0 0 0 0 1 -360 360;
7 8 0 0.17615 0 0 0 0 0 0 1 -360 360;
7 9 0 0.11001 0 0 0 0 0 0 1 -360 360;
9 10 0.03181 0.0845 0 0 0 0 0 0 1 -360 360;
9 14 0.12711 0.27038 0 0 0 0 0 0 1 -360 360;
10 11 0.08205 0.19207 0 0 0 0 0 0 1 -360 360;
12 13 0.22092 0.19988 0 0 0 0 0 0 1 -360 360;
13 14 0.17093 0.34802 0 0 0 0 0 0 1 -360 360;
];
%%----- OPF Data -----%%
%% generator cost data
% 1 startup shutdown n x1 y1 ... xn yn
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0 0 5 0 0 0.0430292599 20 0;
2 0 0 5 0 0 0.25 20 0;
2 0 0 5 0 0 0.01 40 0;
2 0 0 5 0 0 0.01 40 0;
2 0 0 5 0 0 0.01 40 0;
];
%% bus names
mpc.bus_name = {
'Bus 1 HV';
'Bus 2 HV';
'Bus 3 HV';
'Bus 4 HV';
'Bus 5 HV';
'Bus 6 LV';
'Bus 7 ZV';
'Bus 8 TV';
'Bus 9 LV';
'Bus 10 LV';
'Bus 11 LV';
'Bus 12 LV';
'Bus 13 LV';
'Bus 14 LV';
};
% Warnings from cdf2matp conversion:
%
% ***** check the title format in the first line of the cdf file.
% ***** Qmax = Qmin at generator at bus 1 (Qmax set to Qmin + 10)
% ***** MVA limit of branch 1 - 2 not given, set to 0
% ***** MVA limit of branch 1 - 5 not given, set to 0
% ***** MVA limit of branch 2 - 3 not given, set to 0
% ***** MVA limit of branch 2 - 4 not given, set to 0
% ***** MVA limit of branch 2 - 5 not given, set to 0
% ***** MVA limit of branch 3 - 4 not given, set to 0
% ***** MVA limit of branch 4 - 5 not given, set to 0
% ***** MVA limit of branch 4 - 7 not given, set to 0
% ***** MVA limit of branch 4 - 9 not given, set to 0
% ***** MVA limit of branch 5 - 6 not given, set to 0
% ***** MVA limit of branch 6 - 11 not given, set to 0
% ***** MVA limit of branch 6 - 12 not given, set to 0
% ***** MVA limit of branch 6 - 13 not given, set to 0
% ***** MVA limit of branch 7 - 8 not given, set to 0
% ***** MVA limit of branch 7 - 9 not given, set to 0
% ***** MVA limit of branch 9 - 10 not given, set to 0
% ***** MVA limit of branch 9 - 14 not given, set to 0
% ***** MVA limit of branch 10 - 11 not given, set to 0
% ***** MVA limit of branch 12 - 13 not given, set to 0
% ***** MVA limit of branch 13 - 14 not given, set to 0
|
github
|
lanl-ansi/PowerModels.jl-master
|
case2.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case2.m
| 885 |
utf_8
|
a49e159cc74b520baf5f00877d81355e
|
% Case to test space based matlab matrix
% And other hard to parse cases
% also test data without a generator cost model
function mpc = case2
mpc.version = '2';
mpc.baseMVA = 100.00;
mpc.bus = [
1 3 0.00 0.00 0.00 0.00 1 1.0000 0.00000 20.00 1 1.100 0.900 0.00 0.00 0 0
% comment in a matrix
144 1 184.31 52.53 0.00 0.00 1 1.0000 0.00000 100.00 1 1.100 0.900 0.00 0.00 0 0];
mpc.gen = [1 1098.17 140.74 952.77 -186.22 1.0400 2246.86 1 2042.60 0 612.78 2042.60 -186.22 952.77 -186.22 952.77 0 0 0 0 20.4260 0 0 0 0];
mpc.branch = [
144 1 0.00122 0.04896 0.00000 2042.60 9999.00 9999.00 1.02000 0.000 1 0.00 0.00 -1096.78 -85.26 1098.17 140.74 0 0 0 0 % line comment
];
mpc.bus_name = {
'Bus 1 LV';
'Bus 144 HV';
};
|
github
|
lanl-ansi/PowerModels.jl-master
|
case3.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case3.m
| 2,337 |
utf_8
|
303f1329fa093405df83c5d50a0a0344
|
% Case to test adding data to matpower file
% tests refrence bus detection
% tests basic ac and hvdc modeling
% tests when gencost is present but not dclinecost
% quadratic objective function
function mpc = case3
mpc.version = '2';
mpc.baseMVA = 100.0;
mpc.bus = [
1 2 110.0 40.0 0.0 0.0 1 1.10000 -0.00000 240.0 1 1.10000 0.90000;
2 2 110.0 40.0 0.0 0.0 1 0.92617 7.25883 240.0 1 1.10000 0.90000;
3 2 95.0 50.0 0.0 0.0 1 0.90000 -17.26710 240.0 2 1.10000 0.90000;
];
mpc.gen = [
1 158.067 28.79 1000.0 -1000.0 1.1 100.0 1 2000.0 0.0;
2 160.006 -4.63 1000.0 -1000.0 0.92617 100.0 1 1500.0 0.0;
3 0.0 -4.843 1000.0 -1000.0 0.9 100.0 1 0.0 0.0;
];
mpc.gencost = [
2 0.0 0.0 3 0.110000 5.000000 0.000000;
2 0.0 0.0 3 0.085000 1.200000 0.000000;
2 0.0 0.0 3 0.000000 0.000000 0.000000;
];
mpc.branch = [
1 3 0.065 0.62 0.45 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
3 2 0.025 0.75 0.7 50.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
1 2 0.042 0.9 0.3 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
];
mpc.dcline = [
1 2 1 10 10 25.91 -4.16 1.1 0.92617 10 900 -900 900 -900 900 0 0 Inf -Inf 0 NaN 0 0
]
% matpower data format extentions
% adding single values
mpc.const_int = 123;
mpc.const_float = 4.56
mpc.const_str = 'a string';
% adding extra matrix values
% generic table, comes in a matrix
mpc.areas = [
1 1;
2 3;
];
% named column table
%column_names% area refbus
mpc.areas_named = [
4 5;
5 6;
];
% add two new columns to "branch" matrix
%column_names% rate_i rate_p
mpc.branch_limit = [
50.2 45;
36 60.1;
12 30;
];
% adding extra cell values
mpc.areas_cells = {
'Area 1' 123 987 'Slack \"Bus\" 1' 1.23 ;
'Area 2' 456 987 'Slack Bus 3' 4.56 ;
};
%column_names% area_name area area2 refbus_name refbus
mpc.areas_named_cells = {
'Area 1' 123 987 'Slack Bus 1' 1.23;
'Area 2' 456 987 'Slack Bus 3' 4.56;
};
%column_names% name number_id
mpc.branch_names = {
'Branch 1' 123;
'Branch 2' 456;
'Branch 3' 789;
};
%column_names% number string
mpc.bus_data = {
1 'FAV SPOT 02'
2 'FAV PLACE 05'
3 'FAV PLC 08'
};
%column_names% extra
mpc.load_data = {
100
101
};
%column_names% string number
mpc.component = {
'temp' 1000.0
};
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_pwlc.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_pwlc.m
| 2,241 |
utf_8
|
ee8c39be5886057f9acd8ee9587d60a0
|
% tests pwl cost functions
function mpc = case5_pwlc
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 50.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 100.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 50.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 60.0;
];
%% generator cost data
% 1 startup shutdown n x1 y1 ... xn yn
mpc.gencost = [
1 0.0 0.0 4 -0.1 0.0 0.0 0.0 0.1 0.0 0.2 0.0 2.0; % tests zero cost
1 0.0 0.0 4 0.0 841.0 20.0 841.0 100.0 841.0 150.0 841.0 2.0; % tests constant cost
1 0.0 0.0 4.0 170.0 4772.0 231.0 6203.0 293.0 7855.0 355.0 9738.0 2.0; % tests poorly typed ncost value
1 0.0 0.0 4 22.0 1122.0 33.0 1417.0 44.0 1742.0 55.0 2075.0 2.0;
1 0.0 0.0 4 7.0 897.0 7.0 897.0 9.0 1479.0 10.0 1791.0 2.0;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 0.0 0.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
mpc.dcline = [
1 10 1 10 10 25.91 -4.16 1.1 0.92617 10 900 -900 900 -900 900 0 0 0 0 0 0 0 0
]
|
github
|
lanl-ansi/PowerModels.jl-master
|
case24.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case24.m
| 9,996 |
utf_8
|
b7712ffffdb538c13576fc14f1f3a516
|
% from pglib-opf - https://github.com/power-grid-lib/pglib-opf
% tests missing angmin,angmax data correction
% tests branch orientation data correction
% tests mpc.areas
function mpc = case24
mpc.version = '2';
mpc.baseMVA = 100.0;
%% area data
% area refbus
mpc.areas = [
1 1;
2 3;
3 8;
4 6;
];
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 108.0 22.0 0.0 0.0 1 1.03116 -7.74931 138.0 1 1.05000 0.95000;
2 2 97.0 20.0 0.0 0.0 1 1.02794 -7.72341 138.0 1 1.05000 0.95000;
3 1 180.0 37.0 0.0 0.0 1 1.01395 -9.95875 138.0 1 1.05000 0.95000;
4 1 74.0 15.0 0.0 0.0 1 1.00903 -10.81131 138.0 1 1.05000 0.95000;
5 1 71.0 14.0 0.0 0.0 1 1.02711 -10.74273 138.0 1 1.05000 0.95000;
6 1 136.0 28.0 0.0 -100.0 2 1.02760 -13.28597 138.0 1 1.05000 0.95000;
7 2 125.0 25.0 0.0 0.0 2 1.02956 -3.59164 138.0 1 1.05000 0.95000;
8 1 171.0 35.0 0.0 0.0 2 1.00427 -9.50027 138.0 1 1.05000 0.95000;
9 1 175.0 36.0 0.0 0.0 1 1.02698 -9.27195 138.0 1 1.05000 0.95000;
10 1 195.0 40.0 0.0 0.0 2 1.05000 -10.62235 138.0 1 1.05000 0.95000;
11 1 0.0 0.0 0.0 0.0 3 1.03273 -4.64818 230.0 1 1.05000 0.95000;
12 1 0.0 0.0 0.0 0.0 3 1.02695 -3.52232 230.0 1 1.05000 0.95000;
13 3 265.0 54.0 0.0 0.0 3 1.05000 0.00000 230.0 1 1.05000 0.95000;
14 2 194.0 39.0 0.0 0.0 3 1.05000 -3.71689 230.0 1 1.05000 0.95000;
15 2 317.0 64.0 0.0 0.0 4 1.04479 1.17525 230.0 1 1.05000 0.95000;
16 2 100.0 20.0 0.0 0.0 4 1.04951 1.27626 230.0 1 1.05000 0.95000;
17 1 0.0 0.0 0.0 0.0 4 1.04984 4.77096 230.0 1 1.05000 0.95000;
18 2 333.0 68.0 0.0 0.0 4 1.05000 5.75937 230.0 1 1.05000 0.95000;
19 1 181.0 37.0 0.0 0.0 3 1.04185 0.70319 230.0 1 1.05000 0.95000;
20 1 128.0 26.0 0.0 0.0 3 1.04489 2.06190 230.0 1 1.05000 0.95000;
21 2 0.0 0.0 0.0 0.0 4 1.05000 6.19253 230.0 1 1.05000 0.95000;
22 2 0.0 0.0 0.0 0.0 4 1.05000 11.87100 230.0 1 1.05000 0.95000;
23 2 0.0 0.0 0.0 0.0 3 1.05000 3.51051 230.0 1 1.05000 0.95000;
24 1 0.0 0.0 0.0 0.0 4 1.01424 -2.85872 230.0 1 1.05000 0.95000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 20.0 4.934 10.0 0.0 1.03116 100.0 1 20.0 16.0;
1 20.0 4.934 10.0 0.0 1.03116 100.0 1 20.0 16.0;
1 76.0 0.571 30.0 -25.0 1.03116 100.0 1 76.0 15.2;
1 76.0 0.571 30.0 -25.0 1.03116 100.0 1 76.0 15.2;
2 20.0 2.222 10.0 0.0 1.02794 100.0 1 20.0 16.0;
2 20.0 2.222 10.0 0.0 1.02794 100.0 1 20.0 16.0;
2 76.0 -21.307 30.0 -25.0 1.02794 100.0 1 76.0 15.2;
2 76.0 -21.307 30.0 -25.0 1.02794 100.0 1 76.0 15.2;
7 99.974 10.062 60.0 0.0 1.02956 100.0 1 100.0 25.0;
7 99.974 10.062 60.0 0.0 1.02956 100.0 1 100.0 25.0;
7 99.974 10.062 60.0 0.0 1.02956 100.0 1 100.0 25.0;
13 173.258 34.475 80.0 0.0 1.05 100.0 1 197.0 69.0;
13 173.258 34.475 80.0 0.0 1.05 100.0 1 197.0 69.0;
13 173.258 34.475 80.0 0.0 1.05 100.0 1 197.0 69.0;
14 0.0 110.354 200.0 -50.0 1.05 100.0 1 0.0 0.0;
15 2.4 6.0 6.0 0.0 1.04479 100.0 1 12.0 2.4;
15 2.4 6.0 6.0 0.0 1.04479 100.0 1 12.0 2.4;
15 2.4 6.0 6.0 0.0 1.04479 100.0 1 12.0 2.4;
15 2.4 6.0 6.0 0.0 1.04479 100.0 1 12.0 2.4;
15 2.4 6.0 6.0 0.0 1.04479 100.0 1 12.0 2.4;
15 54.3 80.0 80.0 -50.0 1.04479 100.0 1 155.0 54.3;
16 155.0 80.0 80.0 -50.0 1.04951 100.0 1 155.0 54.3;
18 400.0 54.665 200.0 -50.0 1.05 100.0 1 400.0 100.0;
21 296.31 -15.579 200.0 -50.0 1.05 100.0 1 400.0 100.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
22 47.938 -6.795 16.0 -10.0 1.05 100.0 1 50.0 10.0;
23 113.399 -9.984 80.0 -50.0 1.05 100.0 1 155.0 54.3;
23 113.399 -9.984 80.0 -50.0 1.05 100.0 1 155.0 54.3;
23 248.289 21.208 150.0 -25.0 1.05 100.0 1 350.0 140.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 1500.0 0.0 3 0.000000 130.000000 400.684900;
2 1500.0 0.0 3 0.000000 130.000000 400.684900;
2 1500.0 0.0 3 0.014142 16.081100 212.307600;
2 1500.0 0.0 3 0.014142 16.081100 212.307600;
2 1500.0 0.0 3 0.000000 130.000000 400.684900;
2 1500.0 0.0 3 0.000000 130.000000 400.684900;
2 1500.0 0.0 3 0.014142 16.081100 212.307600;
2 1500.0 0.0 3 0.014142 16.081100 212.307600;
2 1500.0 0.0 3 0.052672 43.661500 781.521000;
2 1500.0 0.0 3 0.052672 43.661500 781.521000;
2 1500.0 0.0 3 0.052672 43.661500 781.521000;
2 1500.0 0.0 3 0.007170 48.580400 832.757500;
2 1500.0 0.0 3 0.007170 48.580400 832.757500;
2 1500.0 0.0 3 0.007170 48.580400 832.757500;
2 1500.0 0.0 3 0.000000 0.000000 0.000000;
2 1500.0 0.0 3 0.328412 56.564000 86.385200;
2 1500.0 0.0 3 0.328412 56.564000 86.385200;
2 1500.0 0.0 3 0.328412 56.564000 86.385200;
2 1500.0 0.0 3 0.328412 56.564000 86.385200;
2 1500.0 0.0 3 0.328412 56.564000 86.385200;
2 1500.0 0.0 3 0.008342 12.388300 382.239100;
2 1500.0 0.0 3 0.008342 12.388300 382.239100;
2 1500.0 0.0 3 0.000213 4.423100 395.374900;
2 1500.0 0.0 3 0.000213 4.423100 395.374900;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.000000 0.001000 0.001000;
2 1500.0 0.0 3 0.008342 12.388300 382.239100;
2 1500.0 0.0 3 0.008342 12.388300 382.239100;
2 1500.0 0.0 3 0.004895 11.849500 665.109400;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.0026 0.0139 0.4611 175.0 193.0 200.0 0.0 0.0 1 -7.100016 7.100016;
1 3 0.0546 0.2112 0.0572 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
1 5 0.0218 0.0845 0.0229 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
2 4 0.0328 0.1267 0.0343 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
2 6 0.0497 0.192 0.052 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
3 9 0.0308 0.119 0.0322 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
3 24 0.0023 0.0839 0.0 400.0 510.0 600.0 1.03 0.0 1 -7.100016 7.100016;
4 9 0.0268 0.1037 0.0281 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
5 10 0.0228 0.0883 0.0239 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
6 10 0.0139 0.0605 2.459 175.0 193.0 200.0 0.0 0.0 1 -7.100016 7.100016;
7 8 0.0159 0.0614 0.0166 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
8 9 0.0427 0.1651 0.0447 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
8 10 0.0427 0.1651 0.0447 175.0 208.0 220.0 0.0 0.0 1 -7.100016 7.100016;
9 11 0.0023 0.0839 0.0 400.0 510.0 600.0 1.03 0.0 1 -7.100016 7.100016;
9 12 0.0023 0.0839 0.0 400.0 510.0 600.0 1.03 0.0 1 -7.100016 7.100016;
10 11 0.0023 0.0839 0.0 400.0 510.0 600.0 1.02 0.0 1 -7.100016 7.100016;
10 12 0.0023 0.0839 0.0 400.0 510.0 600.0 1.02 0.0 1 -7.100016 7.100016;
11 13 0.0061 0.0476 0.0999 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
11 14 0.0054 0.0418 0.0879 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
12 13 0.0061 0.0476 0.0999 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
12 23 0.0124 0.0966 0.203 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
13 23 0.0111 0.0865 0.1818 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
14 16 0.005 0.0389 0.0818 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
15 16 0.0022 0.0173 0.0364 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
15 21 0.0063 0.049 0.103 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
15 21 0.0063 0.049 0.103 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
15 24 0.0067 0.0519 0.1091 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
16 17 0.0033 0.0259 0.0545 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
16 19 0.003 0.0231 0.0485 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
17 18 0.0018 0.0144 0.0303 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
17 22 0.0135 0.1053 0.2212 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
18 21 0.0033 0.0259 0.0545 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
18 21 0.0033 0.0259 0.0545 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
19 20 0.0051 0.0396 0.0833 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
19 20 0.0051 0.0396 0.0833 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
20 23 0.0028 0.0216 0.0455 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
23 20 0.0028 0.0216 0.0455 500.0 600.0 625.0 0.0 0.0 1 -7.100016 7.100016;
21 22 0.0087 0.0678 0.1424 500.0 600.0 625.0 0.0 0.0 1 0.000000 0.000000;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case9.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case9.m
| 2,193 |
utf_8
|
03b837e611021136e7dce6783fe4f738
|
% used in tests of,
% - sparce SDP implementation, possible cholesky PosDefException
function mpc = case9
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
2 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
3 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
4 1 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
5 1 80.0 20.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
6 1 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
7 1 90.0 40.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
8 1 0.0 0.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
9 1 100.0 40.0 0.0 0.0 1 1.00000 0.00000 350.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 0.0 0.0 900.0 -900.0 1.0 100.0 1 250.0 10.0;
2 0.0 0.0 900.0 -900.0 1.0 100.0 1 300.0 10.0;
3 0.0 0.0 900.0 -900.0 1.0 100.0 1 270.0 10.0;
];
%% generator cost data
mpc.gencost = [
2 0.0 0.0 2 4.1 0.0;
2 0.0 0.0 2 2.3 0.0;
2 0.0 0.0 2 1.1 0.0;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 4 0.000 0.058 0.000 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
4 5 0.017 0.092 0.158 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
5 6 0.039 0.170 0.358 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
3 6 0.000 0.059 0.000 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
6 7 0.012 0.101 0.209 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
7 8 0.009 0.072 0.149 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
8 2 0.000 0.063 0.000 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
8 9 0.032 0.161 0.306 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
9 4 0.010 0.085 0.176 900.0 900.0 900.0 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_gap.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_gap.m
| 2,164 |
utf_8
|
671d777e38c28224a04eda98a6ca828c
|
% uses negative generator costs to test convex relaxations
% voltage mag and voltage angle difference bounds are key
function mpc = case5_gap
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.09071 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.09981 0.90000;
5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 -14.000000 0.000000;
2 0.0 0.0 3 0.000000 -15.000000 0.000000;
2 0.0 0.0 3 0.000000 -30.000000 0.000000;
2 0.0 0.0 3 0.000000 -40.000000 0.000000;
2 0.0 0.0 3 0.000000 -10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 1.13502939215 7.37625865451;
1 4 0.00304 0.0304 0.00658 426.0 426.0 426.0 0.0 0.0 1 0.658328506605 4.09149161503;
1 5 0.00064 0.0064 0.03126 426.0 426.0 426.0 0.0 0.0 1 -1.85752917181 0.214859173174;
2 3 0.00108 0.0108 0.01852 426.0 426.0 426.0 0.0 0.0 1 -1.6352215473 0.67895498723;
3 4 0.00297 0.0297 0.00674 426.0 426.0 426.0 0.0 0.0 1 -4.41979643164 2.02540580579;
4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -5.06895761352 -0.827924013964;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case3_tnep.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case3_tnep.m
| 1,278 |
utf_8
|
ead5d883df41cc54bf004737b4210419
|
% tests extra data needed for tnep problems
% test when not all ne_branch branch ids are bus ids
function mpc = case3_tnep
mpc.version = '2';
mpc.baseMVA = 100.0;
mpc.bus = [
2 3 110.0 40.0 0.0 0.0 1 1.10000 -0.00000 240.0 1 1.10000 0.90000;
3 2 110.0 40.0 0.0 0.0 1 0.92617 7.25883 240.0 1 1.10000 0.90000;
4 2 95.0 50.0 0.0 0.0 1 0.90000 -17.26710 240.0 2 1.10000 0.90000;
];
mpc.gen = [
2 148.067 54.697 1000.0 -1000.0 1.1 100.0 1 2000.0 0.0;
3 170.006 -8.791 1000.0 -1000.0 0.92617 100.0 1 2000.0 0.0;
4 0.0 -4.843 1000.0 -1000.0 0.9 100.0 1 0.0 0.0;
];
mpc.gencost = [
2 0.0 0.0 3 0.110000 5.000000 0.000000;
2 0.0 0.0 3 0.085000 1.200000 0.000000;
2 0.0 0.0 3 0.000000 0.000000 0.000000;
];
mpc.branch = [
2 3 0.042 0.9 0.3 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
];
%column_names% f_bus t_bus br_r br_x br_b rate_a rate_b rate_c tap shift br_status angmin angmax construction_cost
mpc.ne_branch = [
2 4 0.065 0.62 0.45 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0 1;
4 3 0.025 0.75 0.7 50.0 0.0 0.0 0.0 0.0 1 -30.0 30.0 1;
4 3 0.025 0.75 0.7 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0 1;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_npg.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_npg.m
| 2,052 |
utf_8
|
624549d328690dfa5c89a8092933627b
|
% used in tests of,
% - negative generator outputs
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 -40.0 -60.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 -200.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 20.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 400.0 0.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 900.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.010000 14.000000 0.000000;
2 0.0 0.0 3 0.020000 15.000000 0.000000;
2 0.0 0.0 3 0.030000 30.000000 0.000000;
2 0.0 0.0 3 0.040000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 -10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_dc.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_dc.m
| 2,344 |
utf_8
|
50a742579b5303513bdd62c528ad9199
|
% tests dc line with costs
% tests generator and dc line voltage setpoint warnings
function mpc = case5_dc
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 1 0.0 0.00 0.0 0.0 1 1.06355 2.87619 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08009 -0.79708 230.0 1 1.10000 0.90000;
3 1 300.0 98.61 0.0 0.0 1 1.10000 -0.64925 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000;
5 1 0.0 0.00 0.0 0.0 1 1.05304 3.70099 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.06355 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 333.6866 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -70.8186 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
5 463.5555 -184.9224 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 0.0 0.0 1 -30.0 30.0;
4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
%% dcline data
% fbus tbus status Pf Pt Qf Qt Vf Vt Pmin Pmax QminF QmaxF QminT QmaxT loss0 loss1
mpc.dcline = [
3 5 1 15 8.9 99.9934 -10.4049 1.1 1.05555 10 100 -100 100 -100 100 1 0.01;
];
%% dcline cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.dclinecost = [
2 0.0 0.0 4 0.000000 0.000000 40.000000 0.000000;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_uc_strg.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_uc_strg.m
| 2,580 |
utf_8
|
3932c3885a84421f33e949f72fc22e31
|
% used in tests of,
% - unit commitment, generator 4 should be de-commited due to high cost
function mpc = case5_uc
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 100.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000 2.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
4 3 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
% hours
mpc.time_elapsed = 1.0
%% storage data
% storage_bus ps qs energy energy_rating charge_rating discharge_rating charge_efficiency discharge_efficiency thermal_rating qmin qmax r x p_loss q_loss status
mpc.storage = [
3 0.0 0.0 20.0 100.0 50.0 70.0 0.8 0.9 100.0 -50.0 70.0 0.1 0.0 0.0 0.0 1;
10 0.0 0.0 30.0 100.0 0.0 70.0 0.9 0.8 100.0 110.0 120.0 0.1 0.0 0.0 0.0 1;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_strg.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_strg.m
| 2,406 |
utf_8
|
277e707bf78cc5ca09132809a8990e99
|
% used in tests of,
% - storage modeling
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
% hours
mpc.time_elapsed = 1.0
%% storage data
% storage_bus ps qs energy energy_rating charge_rating discharge_rating charge_efficiency discharge_efficiency thermal_rating qmin qmax r x p_loss q_loss status
mpc.storage = [
3 0.0 0.0 20.0 100.0 50.0 70.0 0.8 0.9 100.0 -50.0 70.0 0.1 0.0 0.0 0.0 1;
10 0.0 0.0 30.0 100.0 50.0 70.0 0.9 0.8 100.0 -50.0 70.0 0.1 0.0 0.0 0.0 1;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_asym.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_asym.m
| 2,096 |
utf_8
|
13b833127c1a25f144950df06313b47b
|
% tests asymetrical branch voltage angle differences
function mpc = case5_asym
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.09071 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.09981 0.90000;
5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 1.13502939215 7.37625865451;
1 4 0.00304 0.0304 0.00658 426.0 426.0 426.0 0.0 0.0 1 0.658328506605 4.09149161503;
1 5 0.00064 0.0064 0.03126 426.0 426.0 426.0 0.0 0.0 1 -1.85752917181 0.214859173174;
2 3 0.00108 0.0108 0.01852 426.0 426.0 426.0 0.0 0.0 1 -1.6352215473 0.67895498723;
3 4 0.00297 0.0297 0.00674 426.0 426.0 426.0 0.0 0.0 1 -4.41979643164 2.02540580579;
4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -5.06895761352 -0.827924013964;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_sw_nb.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_sw_nb.m
| 3,737 |
utf_8
|
536ee3631a6d31a6f65dd6d7e7ef3503
|
% used in tests of,
% - switch modeling with a node-break representation
% - the encoding of bus ids with numbers over 100 is "branch_id0bus_id"
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 5.0 10.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
5 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
101 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
102 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
201 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
204 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
301 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
305 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
402 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
403 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
503 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
504 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
603 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
604 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
704 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
705 2 0.0 0.0 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.00000 100.0 1 40.0 0.0;
1 170.0 127.0 127.0 -127.5 1.00000 100.0 1 170.0 0.0;
3 324.0 390.0 390.0 -390.0 1.00000 100.0 1 520.0 0.0;
4 0.0 -10.0 150.0 -150.0 1.00000 100.0 1 200.0 0.0;
5 470.0 -165.0 450.0 -450.0 1.00000 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 2 14.0 0.0;
2 0.0 0.0 2 15.0 0.0;
2 0.0 0.0 2 30.0 0.0;
2 0.0 0.0 2 40.0 0.0;
2 0.0 0.0 2 10.0 0.0;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
101 102 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
201 204 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
301 305 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
402 403 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
503 504 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
603 604 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
704 705 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
%% switch data
% f_bus t_bus psw qsw state thermal_rating status
mpc.switch = [
1 101 0.0 0.00 1 1000.0 1;
2 102 0.0 0.00 1 1000.0 1;
1 201 0.0 0.00 1 1000.0 1;
4 204 0.0 0.00 1 1000.0 1;
1 301 0.0 0.00 1 1000.0 1;
5 305 0.0 0.00 1 1000.0 1;
2 402 0.0 0.00 1 1000.0 1;
3 403 0.0 0.00 1 1000.0 1;
3 503 0.0 0.00 1 1000.0 1;
4 504 0.0 0.00 1 1000.0 1;
3 603 0.0 0.00 1 1000.0 1;
4 604 0.0 0.00 1 1000.0 1;
4 704 0.0 0.00 1 1000.0 1;
5 705 0.0 0.00 1 1000.0 1;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_clm.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_clm.m
| 2,229 |
utf_8
|
d9cbef19094b9edd9861e3cb3332a3ee
|
% used in tests of,
% - adding explict current constraints
% - current a ratings tranfered to thermal limits
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 0.0 0.0 0.0 1.05 1.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 0.0 0.0 0.0 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 0.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
];
% adds current ratings to branch matrix
%column_names% c_rating_a
mpc.branch_currents = [
400.0;
426;
426;
426;
426;
426;
240.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_ext.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_ext.m
| 2,405 |
utf_8
|
650212fa5dc2481b6b0dc83d789f7475
|
% used in tests of,
% - inactive bus 11
% - negative branch susceptance
% - power flow slack bus with multiple generators
% - power flow slack bus with non-zero va value
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 1 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
11 4 0.0 0.0 1.0 10.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
10 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000 2.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000 2.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
4 3 0.00297 -0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
10 11 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case6.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case6.m
| 1,905 |
utf_8
|
f3047dc4e17d93d99f563bb737086e85
|
% Case to test two connected components in the network data
% the case is two replicates of the case3 network
function mpc = case6
mpc.version = '2';
mpc.baseMVA = 100.0;
mpc.bus = [
1 3 110.0 40.0 0.0 0.0 1 1.10000 -0.00000 240.0 1 1.10000 0.90000;
2 2 110.0 40.0 0.0 0.0 1 0.92617 7.25883 240.0 1 1.10000 0.90000;
3 2 95.0 50.0 0.0 0.0 1 0.90000 -17.26710 240.0 2 1.10000 0.90000;
4 3 110.0 40.0 0.0 0.0 1 1.10000 -0.00000 240.0 1 1.10000 0.90000;
5 2 110.0 40.0 0.0 0.0 1 0.92617 7.25883 240.0 1 1.10000 0.90000;
6 2 95.0 50.0 0.0 0.0 1 0.90000 -17.26710 240.0 2 1.10000 0.90000;
];
mpc.gen = [
1 148.067 54.697 1000.0 -1000.0 1.1 100.0 1 2000.0 0.0;
2 170.006 -8.791 1000.0 -1000.0 0.92617 100.0 1 1500.0 0.0;
3 0.0 -4.843 1000.0 -1000.0 0.9 100.0 1 0.0 0.0;
4 148.067 54.697 1000.0 -1000.0 1.1 100.0 1 2000.0 0.0;
5 170.006 -8.791 1000.0 -1000.0 0.92617 100.0 1 1500.0 0.0;
6 0.0 -4.843 1000.0 -1000.0 0.9 100.0 1 0.0 0.0;
];
mpc.gencost = [
2 0.0 0.0 3 0.110000 5.000000 0.000000;
2 0.0 0.0 3 0.085000 1.200000 0.000000;
2 0.0 0.0 3 0.000000 0.000000 0.000000;
2 0.0 0.0 3 0.110000 5.000000 0.000000;
2 0.0 0.0 3 0.085000 1.200000 0.000000;
2 0.0 0.0 3 0.000000 0.000000 0.000000;
];
mpc.branch = [
1 3 0.065 0.62 0.45 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
3 2 0.025 0.75 0.7 50.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
1 2 0.042 0.9 0.3 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
4 6 0.065 0.62 0.45 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
6 5 0.025 0.75 0.7 50.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
4 5 0.042 0.9 0.3 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_sw.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_sw.m
| 1,897 |
utf_8
|
6a2e73349d3840c9d7e9938492a88bbf
|
% used in tests of,
% - switch modeling
function mpc = case5
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.00000 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 5.0 10.0 1 1.00000 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.00000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.00000 0.00000 230.0 1 1.10000 0.90000;
10 2 0.0 0.0 0.0 0.0 1 1.00000 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.00000 100.0 1 40.0 0.0;
1 170.0 127.0 127.0 -127.5 1.00000 100.0 1 170.0 0.0;
3 324.0 390.0 390.0 -390.0 1.00000 100.0 1 520.0 0.0;
4 0.0 -10.0 150.0 -150.0 1.00000 100.0 1 200.0 0.0;
10 470.0 -165.0 450.0 -450.0 1.00000 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 2 14.0 0.0;
2 0.0 0.0 2 15.0 0.0;
2 0.0 0.0 2 30.0 0.0;
2 0.0 0.0 2 40.0 0.0;
2 0.0 0.0 2 10.0 0.0;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 10 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 -1.0 1 -30.0 30.0;
4 10 0.00297 0.0297 0.00674 240 240 240 0.0 0.0 1 -30.0 30.0;
];
%% switch data
% f_bus t_bus psw qsw state thermal_rating status
mpc.switch = [
1 2 300.0 98.61 1 1000.0 1;
3 2 0.0 0.00 0 1000.0 1;
3 4 0.0 0.00 1 1000.0 0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case3_oltc_pst.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case3_oltc_pst.m
| 1,496 |
utf_8
|
2850a95f709d111a9d59484fb3331536
|
% Case to test adding data to matpower file
% tests refrence bus detection
% tests basic ac and hvdc modeling
% tests when gencost is present but not dclinecost
% quadratic objective function
function mpc = case3
mpc.version = '2';
mpc.baseMVA = 100.0;
mpc.bus = [
1 2 110.0 40.0 0.0 0.0 1 1.10000 -0.00000 240.0 1 1.10000 0.90000;
2 2 110.0 40.0 0.0 0.0 1 0.92617 7.25883 240.0 1 1.10000 0.90000;
3 2 95.0 50.0 0.0 0.0 1 0.90000 -17.26710 240.0 2 1.10000 0.90000;
];
mpc.gen = [
1 158.067 28.79 1000.0 -1000.0 1.1 100.0 1 2000.0 0.0;
2 160.006 -4.63 1000.0 -1000.0 0.92617 100.0 1 1500.0 0.0;
3 0.0 -4.843 1000.0 -1000.0 0.9 100.0 1 0.0 0.0;
];
mpc.gencost = [
2 0.0 0.0 3 0.110000 5.000000 0.000000;
2 0.0 0.0 3 0.085000 1.200000 0.000000;
2 0.0 0.0 3 0.000000 0.000000 0.000000;
];
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 3 0.065 0.62 0.45 9000.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
3 2 0.025 0.75 0.7 50.0 0.0 0.0 0.0 0.0 1 -30.0 30.0;
1 2 0.042 0.9 0.3 9000.0 0.0 0.0 0.0 5.0 1 -30.0 30.0;
];
mpc.dcline = [
1 2 1 10 10 25.91 -4.16 1.1 0.92617 10 900 -900 900 -900 900 0 0 0 0 0 0 0 0
]
% add new columns to "branch" matrix
%column_names% tm_min tm_max ta_min ta_max
mpc.branch_oltc_pst = [
0.9 1.1 0 0;
0.9 1.1 0.0 0.0;
1.0 1.0 -15.0 15.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
frankenstein_00.m
|
.m
|
PowerModels.jl-master/test/data/matpower/frankenstein_00.m
| 2,010 |
utf_8
|
2eb9f12948ad025400fd4fdb36c530fc
|
% Case saved by PowerWorld Simulator, version 19, build date January 17, 2017
% Case Information Header = 2 lines
% A Frankenstein network for testing all of the core features of v33 data files
% developed by Carleton Coffrin ([email protected]) June 2017
function mpc = frankenstein_00
mpc.version = '2';
mpc.baseMVA = 100.00;
%% bus data
mpc.bus = [
1002 2 0.00 0.00 0.00 0.00 101 0.9989281 2.93603 345.00 201 1.100 0.900
1005 2 0.00 0.00 0.00 0.00 101 1.0199983 0.12982 87.00 201 1.100 0.900
1008 2 18.90 6.90 0.00 0.00 101 1.0203628 -0.00217 87.00 201 1.100 0.900
1009 3 10.50 2.30 0.00 105.30 101 1.0300000 0.00000 87.00 201 1.100 0.900
];
%% generator data
mpc.gen = [
1002 27.50 2.00 2.00 2.00 1.0200 31.30 1 27.50 16.00 0.00 0.00 0.00 0.00 0.00 0.00 0 0 0 0 27.5000
1005 20.00 -242.52 250.00 -250.00 1.0200 320.00 1 200.00 -200.00 0.00 0.00 0.00 0.00 0.00 0.00 0 0 0 0 200.0000
1009 -17.73 109.28 250.00 -250.00 1.0300 100.00 1 250.00 -250.00 0.00 0.00 0.00 0.00 0.00 0.00 0 0 0 0 250.0000
];
%% generator cost data
mpc.gencost = [
2 0 0 4 0 0 1 0
2 0 0 4 0 0 1 0
2 0 0 4 0 0 1 0
];
%% branch data
mpc.branch = [
1005 1002 0.005210 0.177370 0.00000 84.00 84.00 84.00 1.02500 0.000 1 0.00 0.00 -27.46 -0.66 27.50 2.01
1008 1005 0.001278 0.012294 0.22708 1086.00 1195.00 1086.00 0.00000 0.000 1 0.00 0.00 -18.98 -6.80 18.98 -16.79
1005 1009 0.000475 0.004680 0.08200 1044.00 1170.00 1044.00 0.00000 0.000 1 0.00 0.00 28.45 -225.08 -28.23 218.69
];
%% bus names
mpc.bus_name = {
'FAV SPOT 02';
'FAV PLACE 05';
'FAV PLC 08';
'FAV PLACE 09';
};
|
github
|
lanl-ansi/PowerModels.jl-master
|
case30.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case30.m
| 6,660 |
utf_8
|
b2778ec0340deede2b1cd151d52c4b79
|
% from pglib-opf - https://github.com/power-grid-lib/pglib-opf
function mpc = case30
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0.0 0.0 0.0 0.0 1 1.06000 -0.00000 132.0 1 1.06000 0.94000;
2 2 21.7 12.7 0.0 0.0 1 1.03591 -4.11149 132.0 1 1.06000 0.94000;
3 1 2.4 1.2 0.0 0.0 1 1.01502 -6.85372 132.0 1 1.06000 0.94000;
4 1 7.6 1.6 0.0 0.0 1 1.00446 -8.44574 132.0 1 1.06000 0.94000;
5 2 94.2 19.0 0.0 0.0 1 0.99748 -13.13219 132.0 1 1.06000 0.94000;
6 1 0.0 0.0 0.0 0.0 1 1.00170 -10.15671 132.0 1 1.06000 0.94000;
7 1 22.8 10.9 0.0 0.0 1 0.99208 -11.91706 132.0 1 1.06000 0.94000;
8 2 30.0 30.0 0.0 0.0 1 1.00241 -10.93461 132.0 1 1.06000 0.94000;
9 1 0.0 0.0 0.0 0.0 1 1.03671 -13.26615 1.0 1 1.06000 0.94000;
10 1 5.8 2.0 0.0 19.0 1 1.03220 -14.89730 33.0 1 1.06000 0.94000;
11 2 0.0 0.0 0.0 0.0 1 1.06000 -13.26615 11.0 1 1.06000 0.94000;
12 1 11.2 7.5 0.0 0.0 1 1.04625 -14.18878 33.0 1 1.06000 0.94000;
13 2 0.0 0.0 0.0 0.0 1 1.06000 -14.18878 11.0 1 1.06000 0.94000;
14 1 6.2 1.6 0.0 0.0 1 1.03103 -15.09457 33.0 1 1.06000 0.94000;
15 1 8.2 2.5 0.0 0.0 1 1.02621 -15.17834 33.0 1 1.06000 0.94000;
16 1 3.5 1.8 0.0 0.0 1 1.03259 -14.75320 33.0 1 1.06000 0.94000;
17 1 9.0 5.8 0.0 0.0 1 1.02726 -15.07475 33.0 1 1.06000 0.94000;
18 1 3.2 0.9 0.0 0.0 1 1.01602 -15.79032 33.0 1 1.06000 0.94000;
19 1 9.5 3.4 0.0 0.0 1 1.01317 -15.95831 33.0 1 1.06000 0.94000;
20 1 2.2 0.7 0.0 0.0 1 1.01714 -15.75153 33.0 1 1.06000 0.94000;
21 1 17.5 11.2 0.0 0.0 1 1.01982 -15.35269 33.0 1 1.06000 0.94000;
22 1 0.0 0.0 0.0 0.0 1 1.02041 -15.33860 33.0 1 1.06000 0.94000;
23 1 3.2 1.6 0.0 0.0 1 1.01532 -15.56400 33.0 1 1.06000 0.94000;
24 1 8.7 6.7 0.0 4.3 1 1.00930 -15.72597 33.0 1 1.06000 0.94000;
25 1 0.0 0.0 0.0 0.0 1 1.00621 -15.29138 33.0 1 1.06000 0.94000;
26 1 3.5 2.3 0.0 0.0 1 0.98833 -15.72053 33.0 1 1.06000 0.94000;
27 1 0.0 0.0 0.0 0.0 1 1.01294 -14.75624 33.0 1 1.06000 0.94000;
28 1 0.0 0.0 0.0 0.0 1 0.99824 -10.79567 132.0 1 1.06000 0.94000;
29 1 2.4 0.9 0.0 0.0 1 0.99288 -16.01182 33.0 1 1.06000 0.94000;
30 1 10.6 1.9 0.0 0.0 1 0.98128 -16.91371 33.0 1 1.06000 0.94000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 218.839 9.372 10.0 0.0 1.06 100.0 1 784 0.0; % COW
2 80.05 24.589 50.0 -40.0 1.03591 100.0 1 100 0.0; % NG
5 0.0 32.487 40.0 -40.0 0.99748 100.0 1 0 0.0; % SYNC
8 0.0 40.0 40.0 -10.0 1.00241 100.0 1 0 0.0; % SYNC
11 0.0 11.87 24.0 -6.0 1.06 100.0 1 0 0.0; % SYNC
13 0.0 10.414 24.0 -6.0 1.06 100.0 1 0 0.0; % SYNC
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 0.521378 0.000000; % COW
2 0.0 0.0 3 0.000000 1.135166 0.000000; % NG
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.0192 0.0575 0.0528 138 138 138 0.0 0.0 1 -30.0 30.0;
1 3 0.0452 0.1652 0.0408 152 152 152 0.0 0.0 1 -30.0 30.0;
2 4 0.057 0.1737 0.0368 139 139 139 0.0 0.0 1 -30.0 30.0;
3 4 0.0132 0.0379 0.0084 135 135 135 0.0 0.0 1 -30.0 30.0;
2 5 0.0472 0.1983 0.0418 144 144 144 0.0 0.0 1 -30.0 30.0;
2 6 0.0581 0.1763 0.0374 139 139 139 0.0 0.0 1 -30.0 30.0;
4 6 0.0119 0.0414 0.009 148 148 148 0.0 0.0 1 -30.0 30.0;
5 7 0.046 0.116 0.0204 127 127 127 0.0 0.0 1 -30.0 30.0;
6 7 0.0267 0.082 0.017 140 140 140 0.0 0.0 1 -30.0 30.0;
6 8 0.012 0.042 0.009 148 148 148 0.0 0.0 1 -30.0 30.0;
6 9 0.0 0.208 0.0 142 142 142 0.978 0.0 1 -30.0 30.0;
6 10 0.0 0.556 0.0 53 53 53 0.969 0.0 1 -30.0 30.0;
9 11 0.0 0.208 0.0 142 142 142 0.0 0.0 1 -30.0 30.0;
9 10 0.0 0.11 0.0 267 267 267 0.0 0.0 1 -30.0 30.0;
4 12 0.0 0.256 0.0 115 115 115 0.932 0.0 1 -30.0 30.0;
12 13 0.0 0.14 0.0 210 210 210 0.0 0.0 1 -30.0 30.0;
12 14 0.1231 0.2559 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
12 15 0.0662 0.1304 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
12 16 0.0945 0.1987 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
14 15 0.221 0.1997 0.0 20 20 20 0.0 0.0 1 -30.0 30.0;
16 17 0.0524 0.1923 0.0 38 38 38 0.0 0.0 1 -30.0 30.0;
15 18 0.1073 0.2185 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
18 19 0.0639 0.1292 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
19 20 0.034 0.068 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
10 20 0.0936 0.209 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
10 17 0.0324 0.0845 0.0 33 33 33 0.0 0.0 1 -30.0 30.0;
10 21 0.0348 0.0749 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
10 22 0.0727 0.1499 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
21 22 0.0116 0.0236 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
15 23 0.1 0.202 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
22 24 0.115 0.179 0.0 26 26 26 0.0 0.0 1 -30.0 30.0;
23 24 0.132 0.27 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
24 25 0.1885 0.3292 0.0 27 27 27 0.0 0.0 1 -30.0 30.0;
25 26 0.2544 0.38 0.0 25 25 25 0.0 0.0 1 -30.0 30.0;
25 27 0.1093 0.2087 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
28 27 0.0 0.396 0.0 75 75 75 0.968 0.0 1 -30.0 30.0;
27 29 0.2198 0.4153 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
27 30 0.3202 0.6027 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
29 30 0.2399 0.4533 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
8 28 0.0636 0.2 0.0428 140 140 140 0.0 0.0 1 -30.0 30.0;
6 28 0.0169 0.0599 0.013 149 149 149 0.0 0.0 1 -30.0 30.0;
];
|
github
|
lanl-ansi/PowerModels.jl-master
|
case5_tnep.m
|
.m
|
PowerModels.jl-master/test/data/matpower/case5_tnep.m
| 2,658 |
utf_8
|
470d092090807211509fb7dba3d74915
|
% tests extra data needed for tnep problems
function mpc = case5_tnep
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000;
2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000;
3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000;
4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000;
5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin
mpc.gen = [
1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0;
1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0;
3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0;
4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0;
5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0;
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 14.000000 0.000000;
2 0.0 0.0 3 0.000000 15.000000 0.000000;
2 0.0 0.0 3 0.000000 30.000000 0.000000;
2 0.0 0.0 3 0.000000 40.000000 0.000000;
2 0.0 0.0 3 0.000000 10.000000 0.000000;
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
% 1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0;
% 1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0;
1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0;
2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0;
3 4 0.00297 0.0297 0.00674 426 426 426 1.05 1.0 1 -30.0 30.0;
4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0;
];
%column_names% f_bus t_bus br_r br_x br_b rate_a rate_b rate_c tap shift br_status angmin angmax construction_cost
mpc.ne_branch = [
1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0 1;
1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0 1;
1 4 0.00304 0.0304 0.00658 1.0 1.0 1.0 0.0 0.0 1 -30.0 30.0 1;
];
%% dcline data
% fbus tbus status Pf Pt Qf Qt Vf Vt Pmin Pmax QminF QmaxF QminT QmaxT loss0 loss1
mpc.dcline = [
3 5 1 10 8.9 99.9934 -10.4049 1.1 1.05304 10 100 -100 100 -100 100 1 0.01;
];
%% dcline cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.dclinecost = [
2 0.0 0.0 3 0.000000 40.000000 0.000000;
];
|
github
|
ezachar/PeerJ-master
|
parseInputs.m
|
.m
|
PeerJ-master/Code/FeatureExtraction/parseInputs.m
| 1,405 |
utf_8
|
12f34715332fcd1e988e132221c88ae0
|
function [datapath,outpath,ext,kernel,bin, modelfname,list] = parseInputs(varargin)
% function [datapath,outpath,ext,kernel,bin, modelfname,list] = parseInputs(varargin)
%=== Check for the right number of inputs
if rem(nargin,2)== 1
error('IncorrectNumberOfArguments',...
'Incorrect number of arguments to %s.',mfilename);
end
%=== Allowed inputs
okargs = {'datapath','outpath','ext','kernel','bin', 'modelfname','list'};
%=== Defaults
list = fullfile('..','Data','list.txt');
datapath = fullfile('..','Data');
modelfname = fullfile('..','Data','pdbmodel.mat');
outpath = datapath;
if ~exist(outpath,'dir')
mkdir(outpath);
end
ext = ''; %'.pdb'; % extension of the pdb files
kernel = fspecial('gaussian') ; % ones(3, 3) / 9; % 3x3 mean kernel
bin = 20; % width of histogram bins in angles
for j=1:2:nargin
[k, pval] = pvpair(varargin{j}, varargin{j+1}, okargs, mfilename);
switch(k)
case 1 %
datapath = pval;
case 2 %
outpath = pval;
case 3 %
ext = pval;
case 4 %
kernel = str2num(pval);
case 5 %
bin = str2num(pval);
case 6 %
modelfname = pval;
case 7 %
list = pval;
end
end
|
github
|
ezachar/PeerJ-master
|
cnn_proteins_init_perChannel.m
|
.m
|
PeerJ-master/Code/cnn/cnn_proteins_init_perChannel.m
| 3,880 |
utf_8
|
80f57acab2e8cf5d93352d5088c57f76
|
function net = cnn_proteins_init_perChannel(opts, varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
% opts.useSPnorm = false ;
% opts.useDropout = false;
opts = vl_argparse(opts, varargin) ;
rng('default');
rng(0) ;
f=1/100 ;
net.layers = {} ;
numLastFilters = 500;
numFilters = 20; % number of filters
numLabels = 6;
FD=1;
if opts.angles
pad1=1;
else
pad1=0;
end
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,FD,numFilters, 'single'), zeros(1, numFilters, 'single')}}, ...
'stride', 1, ...
'pad', pad1) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(numFilters, 1, 'single'), zeros(numFilters, 1, 'single')}});
if opts.relu
net.layers{end+1} = struct('type', 'relu') ;
end
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,numFilters,50, 'single'),zeros(1,50,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(50, 1, 'single'), zeros(50, 1, 'single')}});
if opts.relu
net.layers{end+1} = struct('type', 'relu') ;
end
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(2,2,50,numLastFilters, 'single'), zeros(1,numLastFilters,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(numLastFilters, 1, 'single'), zeros(numLastFilters, 1, 'single')}});
net.layers{end+1} = struct('type', 'relu') ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(1,1,numLastFilters,numLabels, 'single'), zeros(1,numLabels,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% optionally insert Dropout layer
% if opts.Dropout
% if ~opts.relu
% net = insertDropout(net, 3) ;
% net = insertDropout(net, 7) ;
% net = insertDropout(net, 11) ; %net = insertDropout(net, 10) ;
% else
% net = insertDropout(net, 4) ;
% net = insertDropout(net, 9) ;
% net = insertDropout(net, 14) ;
% end
if opts.Dropout
if ~opts.relu
net = insertDropout(net, 6) ;
net = insertDropout(net, 10) ;
else
net = insertDropout(net, 7) ;
net = insertDropout(net, 12) ;
end
end
% --------------------------------------------------------------------
function net = insertSPnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
layer = struct('type', 'spnorm', 'param', [2 2 1 2]) ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
% --------------------------------------------------------------------
function net = insertDropout(net, l)
% --------------------------------------------------------------------
layer = struct('type', 'dropout','rate', 0.2) ; %0.5
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
|
github
|
ezachar/PeerJ-master
|
cnn_proteins_init.m
|
.m
|
PeerJ-master/Code/cnn/cnn_proteins_init.m
| 3,891 |
utf_8
|
25cea2ab45fc779167b255f5eed4acaf
|
function net = cnn_proteins_init(opts, varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
% opts.useSPnorm = false ;
% opts.useDropout = false;
opts = vl_argparse(opts, varargin) ;
rng('default');
rng(0) ;
f=1/100 ;
net.layers = {} ;
numLastFilters = 500;
numFilters = 20; % number of filters
numLabels = 6;
if opts.angles
FD=23;
pad1=1;
else
FD = 8; % 1;
pad1=0;
end
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,FD,numFilters, 'single'), zeros(1, numFilters, 'single')}}, ...
'stride', 1, ...
'pad', pad1) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(numFilters, 1, 'single'), zeros(numFilters, 1, 'single')}});
if opts.relu
net.layers{end+1} = struct('type', 'relu') ;
end
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,numFilters,50, 'single'),zeros(1,50,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(50, 1, 'single'), zeros(50, 1, 'single')}});
if opts.relu
net.layers{end+1} = struct('type', 'relu') ;
end
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(2,2,50,numLastFilters, 'single'), zeros(1,numLastFilters,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'bnorm', ...
'weights', {{ones(numLastFilters, 1, 'single'), zeros(numLastFilters, 1, 'single')}});
net.layers{end+1} = struct('type', 'relu') ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(1,1,numLastFilters,numLabels, 'single'), zeros(1,numLabels,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% optionally insert Dropout layer
% if opts.Dropout
% if ~opts.relu
% net = insertDropout(net, 3) ;
% net = insertDropout(net, 7) ;
% net = insertDropout(net, 11) ; %net = insertDropout(net, 10) ;
% else
% net = insertDropout(net, 4) ;
% net = insertDropout(net, 9) ;
% net = insertDropout(net, 14) ;
% end
if opts.Dropout
if ~opts.relu
net = insertDropout(net, 6) ;
net = insertDropout(net, 10) ;
else
net = insertDropout(net, 7) ;
net = insertDropout(net, 12) ;
end
end
% --------------------------------------------------------------------
function net = insertSPnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
layer = struct('type', 'spnorm', 'param', [2 2 1 2]) ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
% --------------------------------------------------------------------
function net = insertDropout(net, l)
% --------------------------------------------------------------------
layer = struct('type', 'dropout','rate', 0.2) ; %0.5
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
|
github
|
albertomontesg/computer-vision-exercises-master
|
MCL_Localization_lab.m
|
.m
|
computer-vision-exercises-master/exercise3/code/MCL_Localization_lab.m
| 9,090 |
utf_8
|
da7b928668ef1fbbc50dcf8018575a68
|
% 1DOF ROBOT LOCALIZATION IN A CIRCULAR HALLWAY USING A HISTOGRAM FILTER
function MCLLocalization1DOFRobotInTheHallway
clear all; %close all;
global frame figure_handle plot_handle firstTime;
fprintf('Loading the animation data...\n');
load animation;
fprintf('Animation data loaded\n');
% Algorithm parameters
simpar.circularHallway=1; % 1:yes, 0:no
simpar.animate=1; % 1: Draw the animation of the gaussian. 0: do not draw (speed up the simulation)
simpar.nSteps=500; % number of steps of the algorithm
simpar.domain = 850; % Domain size (in centimeters)
simpar.xTrue_0=[mod(abs(ceil(simpar.domain*randn(1))),850); 20];
simpar.numberOfParticles = 100;
simpar.wk_stdev=1; % stddev of the noise used in acceleration to simulate the robot movement.
simpar.door_locations = [222,326,611]; % Position of the doors (in centimetres). This is the Map definition.
simpar.door_stdev=90/4; % +-2sigma of the door observation is assumend to be 90 cm which is the wide of the door
simpar.odometry_stdev = 2; % Odometry uncertainty. Std. deviation of a Gaussian pdf. [cm]
simpar.T=1; % Simulation sample time
% Fixe the position of the figure to the up left corner
% Fixe the size depending on the screen size
scrsz = get(0,'ScreenSize');
figure_handle=figure('Position',[0 0 scrsz(3)/3.5 scrsz(4)]);
%figure_handle=figure(1);
firstTime=ones(6);
xTrue_k=simpar.xTrue_0
% Initial Robot belief is generated from the uniform distribution
belief_particles = random('unif',0,simpar.domain,1,simpar.numberOfParticles);
% The localization algorithm starts here %%%%%%%%%%%%%%%%%%%%%%%%%%%%
for k = 1:simpar.nSteps
DrawRobot(xTrue_k(1), simpar); %Plots the robot
xTrue_k_1=xTrue_k;
xTrue_k=SimulateRobot(xTrue_k_1,simpar); %Simulates the robot movement
uk=get_odometry(xTrue_k,xTrue_k_1,simpar);
zk=get_measurements(xTrue_k(1),xTrue_k_1(1),simpar);
fprintf('step=%d,zk=%d uk=%f\n',k,zk,uk);
% Aplies the particle filter to localize the robot and draws the
% particles in the figure
belief_particles=MCL(belief_particles,uk,zk,simpar);
end
end
% The Localization Algorith ends here %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simulate how the robot moves %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xTrue_kNew=SimulateRobot(xTrue_k, simpar)
%We will need to update the robot position here taking into account the
%noise in acceleration
wk=randn(1)*simpar.wk_stdev;
xTrue_kNew = [1 simpar.T; 0 1]* xTrue_k + [simpar.T^2/2; simpar.T] * wk;
if simpar.circularHallway,
% the hallway is assumed to be circular
xTrue_kNew=mod(xTrue_kNew,simpar.domain);
else
% the hallway is assumed to be linear
if xTrue_kNew(1)>simpar.domain
xTrue_kNew(1) = simpar.domain-mod(xTrue_kNew(1),simpar.domain);
xTrue_kNew(2) = -xTrue_kNew(2); % change direction of motion
end
if xTrue_kNew(1)<0
xTrue_kNew(1) = -xTrue_kNew(1);
xTrue_kNew(2) = -xTrue_kNew(2); % change direction of motion
end
end
end
% Simulates the odometry measurements including noise%%%%%%%%%%%%%%%%%%
function uk=get_odometry(xTrue_k,xTrue_k_1,simpar)
uk=mod(xTrue_k(1)-xTrue_k_1(1)+simpar.odometry_stdev*randn(1),850);
end
% Simulates the detection of doors by the robot sensor %%%%%%%%%%%%%%%%
function sensor=get_measurements(xTrue_k,xTrue_k_1,simpar)
i=1;
sensor = 0;
while(i<=length(simpar.door_locations) && sensor ~= 1)
if ((xTrue_k(1) >= simpar.door_locations(i) && simpar.door_locations(i)>= xTrue_k_1(1)) || (xTrue_k(1) <= simpar.door_locations(i) && simpar.door_locations(i)<= xTrue_k_1(1))) && (abs(xTrue_k(1)-xTrue_k_1(1))<180)
sensor = 1;
end
i = i + 1;
end
end
% Draws the robot
function DrawRobot(x, simpar)
global frame figure_handle
if simpar.animate
figure(figure_handle);
x = mod(x,simpar.domain);
i=x*332/simpar.domain;
% keep the frame within the correct boundaries
if i<1, i=1; end;
if i>332, i=332; end; if i<1, i=1; end;
subplot(6,1,1);
image(frame(ceil(i)).image); %axis equal;
end
drawnow;
end
% Plots a Gaussian using a bar plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DrawParticles(sp,label,pdf,weight,simpar)
global firstTime plot_handle figure_handle
if simpar.animate
if firstTime(sp)
figure(figure_handle);
subplot(6,1,sp);
firstTime(sp)=0;
plot_handle(sp)=scatter(pdf,zeros(1,simpar.numberOfParticles),weight*20+2, 'filled');
axis([0 simpar.domain -0.1 1]);
xlabel(label);
else
figure(figure_handle);
subplot(6,1,sp);
set(plot_handle(sp),'XData',pdf,'YData',zeros(1,simpar.numberOfParticles),'SizeData',weight*20+2);
end
end
end
function DrawGaussian(sp,label,pdf_values,simpar)
global figure_handle
if simpar.animate
figure(figure_handle);
subplot(6,1,sp);
plot(1:simpar.domain,pdf_values,'-b');
axis([0 simpar.domain 0 max(pdf_values)]);
xlabel(label);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%% COMPLETE THESE FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Aplies the MCL algorithm and plots the results
function updated_belief_particles=MCL(priorbelief_particles,uk,zk,simpar)
% COMPLETE THIS FUNCTION
% This lines must be replaced by your solution to the MCL localization
% problem. They are provided only to allow for the execution of the program
% before solving the lab.
measurement_model_particles=zeros(1,simpar.domain);
for i = 1:size(simpar.door_locations,2)
measurement_model_particles = measurement_model_particles + pdf('norm', 1:simpar.domain,simpar.door_locations(i), simpar.door_stdev);
end
measurement_model_particles = measurement_model_particles / sum(measurement_model_particles);
%measurement_model_particles=pdf('unif',[1:simpar.domain],0,simpar.domain); % change this value for the correct one
predict_particles = sample_motion_model(uk, priorbelief_particles, simpar); % change this value for the correct one
weight_particles = measurement_model(zk, predict_particles, simpar);
% Resampling Algorithm for the Udacity course
index = floor(random('unif', 0, 1) * simpar.numberOfParticles) + 1;
beta = 0.;
mw = max(weight_particles);
updated_belief_particles = zeros(1, simpar.numberOfParticles); % Vector to store the new particles that survive the resampling
for i = 1:simpar.numberOfParticles
beta = beta + random('unif', 0, 1) * 2 * mw;
while beta > weight_particles(index)
beta = beta - weight_particles(index);
index = mod(index + 1, simpar.numberOfParticles) + 1;
end
updated_belief_particles(i) = predict_particles(index);
end
% plotting the pdfs for the animation
DrawParticles(2,'prior',priorbelief_particles,ones(1,simpar.numberOfParticles),simpar);
DrawParticles(3,'predict',predict_particles,ones(1,simpar.numberOfParticles),simpar);
DrawGaussian (4,'measurement model',measurement_model_particles,simpar);
DrawParticles(5,'Weighted Particles',predict_particles,weight_particles, simpar);
DrawParticles(6,'update',updated_belief_particles,ones(1,simpar.numberOfParticles), simpar);
end
function predict_particles=sample_motion_model(uk,prior_belief_particles,simpar)
% COMPLETE THIS FUNCTION
% Here computes the x_t ~ P(x_t|u_k, x_t-1) as a normal distribution
% where the mean is the expected position x_k-1+u_k*T and the std has
% been set to 2
predict_particles = random('norm', prior_belief_particles+uk*simpar.T, 2);
predict_particles = mod(predict_particles, simpar.domain);
end
function particle_weights=measurement_model(zk,pdf_particles,simpar)
% COMPLETE THIS FUNCTION
% wk = P( zk | xk )
% Compute the P(z_k=1|x_k)
particle_weights=zeros(1,simpar.numberOfParticles); % change this value for the correct one
for i = 1:size(simpar.door_locations,2)
particle_weights = particle_weights + pdf('norm', pdf_particles, simpar.door_locations(i), simpar.door_stdev);
end
% In the case z_k = 0, return the P(z_k=0|x_k) = 1 - P(z_k=1|x_k)
if zk == 0
particle_weights = 1 - particle_weights;
end
particle_weights = particle_weights / sum(particle_weights);
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
normalizePoints2d.m
|
.m
|
computer-vision-exercises-master/exercise4/code/normalizePoints2d.m
| 561 |
utf_8
|
abeca945dd1d8512f82c09403c848316
|
% Normalization of 2d-pts
% Inputs:
% x1s = 2d points
% Outputs:
% nxs = normalized points
% T = normalization matrix
function [x_n, T] = normalizePoints2d(x)
centroid = mean(x,2);
dists = sqrt(sum((x - repmat(centroid,1,size(x,2))).^2,1));
mean_dist = mean(dists);
T = [sqrt(2)/mean_dist 0 -sqrt(2)/mean_dist*centroid(1);...
0 sqrt(2)/mean_dist -sqrt(2)/mean_dist*centroid(2);...
0 0 1];
if size(x, 1) == 2
x = [x; ones(1, size(x,2))];
end
x_n = T * x;
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
showFeatureMatches.m
|
.m
|
computer-vision-exercises-master/exercise4/code/showFeatureMatches.m
| 752 |
utf_8
|
6ec133c49f053049c95d2d9ac102bbe6
|
% show feature matches between two images
%
% Input:
% img1 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of first image
% img2 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of second image
% fig - figure id
function showFeatureMatches(img1, corner1, img2, corner2, fig)
[sx, sy, sz] = size(img1);
img = [img1, img2];
corner2 = corner2 + repmat([sy, 0]', [1, size(corner2, 2)]);
figure(fig), imshow(img, []);
hold on, plot(corner1(1,:), corner1(2,:), '+r');
hold on, plot(corner2(1,:), corner2(2,:), '+r');
hold on, plot([corner1(1,:); corner2(1,:)], [corner1(2,:); corner2(2,:)], 'b');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
fundamentalMatrix.m
|
.m
|
computer-vision-exercises-master/exercise4/code/fundamentalMatrix.m
| 630 |
utf_8
|
07af32b81188a8adeaaa944ed949be0e
|
% Compute the fundamental matrix using the eight point algorithm
% Input
% x1s, x2s Point correspondences
%
% Output
% Fh Fundamental matrix with the det F = 0 constraint
% F Initial fundamental matrix obtained from the eight point algorithm
%
function [Fh, F] = fundamentalMatrix(x1s, x2s)
[x1n, T1] = normalizePoints2d(x1s);
[x2n, T2] = normalizePoints2d(x2s);
W = [ repmat(x2n(1,:)',1,3) .* x1n', repmat(x2n(2,:)',1,3) .* x1n', x1n(1:3,:)'];
[~, ~, V] = svd(W);
F = reshape(V(:,end),3,3)';
[u, s, v] = svd(F);
Fh = T2' * u * diag([s(1) s(5) 0]) * v' * T1;
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
showCameras.m
|
.m
|
computer-vision-exercises-master/exercise4/code/showCameras.m
| 950 |
utf_8
|
a6edc052546f1d63e4218438661e1e84
|
% showCameras(Ms, fig)
%
% Input
% Ms cell array of 4x4 transformation matrices ([R|t]) with last row
% equal to [0 0 0 1]
% fig figure id
function showCameras(Ms, fig)
[sx, sy] = size(Ms);
o = [0, 0, 0, 1]';
x = [1, 0, 0, 1]';
y = [0, 1, 0, 1]';
z = [0, 0, 1, 1]';
po = zeros(4, sy);
px = zeros(4, sy);
py = zeros(4, sy);
pz = zeros(4, sy);
for k = 1:sy
po(:, k) = Ms{k}\o;
px(:, k) = Ms{k}\x;
py(:, k) = Ms{k}\y;
pz(:, k) = Ms{k}\z;
end
figure(fig);
hold on, line([po(1, :); px(1,:)], [po(2, :); px(2,:)], [po(3, :); px(3,:)], 'Color', [1, 0, 0]);
hold on, line([po(1, :); py(1,:)], [po(2, :); py(2,:)], [po(3, :); py(3,:)], 'Color', [0, 1, 0]);
hold on, line([po(1, :); pz(1,:)], [po(2, :); pz(2,:)], [po(3, :); pz(3,:)], 'Color', [0, 0, 1]);
%axis equal;
grid on;
axis equal
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
essentialMatrix.m
|
.m
|
computer-vision-exercises-master/exercise4/code/essentialMatrix.m
| 641 |
utf_8
|
c1e2b95eb7c69e621970c485af797883
|
% Compute the essential matrix using the eight point algorithm
% Input
% x1s, x2s Point correspondences 3xn matrices
%
% Output
% Eh Essential matrix with the det E = 0 constraint and the constraint that the first two singular values are equal
% E Initial essential matrix obtained from the eight point algorithm
%
function [Eh, E] = essentialMatrix(x1s, x2s)
W = [ repmat(x2s(1,:)',1,3) .* x1s', repmat(x2s(2,:)',1,3) .* x1s', x1s(1:3,:)'];
[~, ~, V] = svd(W);
E = reshape(V(:,end),3,3)';
[u, s, v] = svd(E);
r = s(1); s = s(5);
Eh = u * diag([(r+s)/2, (r+s)/2, 0]) * v';
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
decomposeE.m
|
.m
|
computer-vision-exercises-master/exercise4/code/decomposeE.m
| 759 |
utf_8
|
1c828ef6f5a1b83b703952cc573c585d
|
% Decompose the essential matrix
% Return P = [R|t] which relates the two views
% Yu will need the point correspondences to find the correct solution for P
function P = decomposeE(E, x1s, x2s)
[U,~,V] = svd(E);
W = [0 -1 0; 1 0 0; 0 0 1];
R1 = -U*W*V'; % minus sign to enforce det(R)=1
R2 = -U*W'*V';
t = U(:,end);
t = t / norm(t);
P_c = [eye(3), zeros(3,1)];
for i = 1:4
PP = (R1*(i<=2) + R2*(i>2)) * [eye(3), t*((-1)^(i-1))];
[XS, ~] = linearTriangulation(P_c, x1s, PP, x2s);
% Check if any of the 3D points is placed behind the camera
% if so, P it will not be valid.
if sum(XS(3,:) < 0) == 0
P = PP;
break;
end
end
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
makehomogeneous.m
|
.m
|
computer-vision-exercises-master/exercise6/code/makehomogeneous.m
| 649 |
utf_8
|
19d1cac5b6483d4dd545ef8b6bca5dcb
|
% MAKEHOMOGENEOUS - Appends a scale of 1 to array inhomogeneous coordinates
%
% Usage: hx = makehomogeneous(x)
%
% Argument:
% x - an N x npts array of inhomogeneous coordinates.
%
% Returns:
% hx - an (N+1) x npts array of homogeneous coordinates with the
% homogeneous scale set to 1
%
% See also: MAKEINHOMOGENEOUS
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% April 2010
function hx = makehomogeneous(x)
[rows, npts] = size(x);
hx = ones(rows+1, npts);
hx(1:rows,:) = x;
|
github
|
albertomontesg/computer-vision-exercises-master
|
drawCameras.m
|
.m
|
computer-vision-exercises-master/exercise6/code/drawCameras.m
| 934 |
utf_8
|
393dbdab07b0a574bb10dd2f69b9ac62
|
%Ms is a cell matrix of 1 to n projection matrices
%Ms{1} = P1;
%Ms{2} = P2;
%...
%fig is the figure number where to draw the cameras
function drawCameras(Ms, fig)
[sx, sy] = size(Ms);
o = [0, 0, 0, 1]';
x = [1, 0, 0, 1]';
y = [0, 1, 0, 1]';
z = [0, 0, 1, 1]';
po = zeros(4, sy);
px = zeros(4, sy);
py = zeros(4, sy);
pz = zeros(4, sy);
for k = 1:sy
po(:, k) = Ms{k}\o;
px(:, k) = Ms{k}\x;
py(:, k) = Ms{k}\y;
pz(:, k) = Ms{k}\z;
end
figure(fig);
hold on, line([po(1, :); px(1,:)], [po(2, :); px(2,:)], [po(3, :); px(3,:)], 'Color', [1, 0, 0]);
hold on, line([po(1, :); py(1,:)], [po(2, :); py(2,:)], [po(3, :); py(3,:)], 'Color', [0, 1, 0]);
hold on, line([po(1, :); pz(1,:)], [po(2, :); pz(2,:)], [po(3, :); pz(3,:)], 'Color', [0, 0, 1]);
axis equal;
grid on;
a = 1;
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
ransacfitprojmatrix.m
|
.m
|
computer-vision-exercises-master/exercise6/code/ransacfitprojmatrix.m
| 4,030 |
utf_8
|
48cf8ea5f6157729c26d62bf1612d89d
|
% RANSACFITPROJMATRIX - fits projection matrix using RANSAC
%
% Usage: [P, inliers] = ransacfitprojmatrix(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 3xN or 4xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not
% (reprojection error in pixels).
%
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% P - The 4x4 projection matrix
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, PROJMATRIX
function [P, inliers] = ransacfitprojmatrix(x1, x2, t, feedback)
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
end
[rows,npts] = size(x2);
if rows~=3 & rows~=4
error('x2 must have 3 or 4 rows');
end
if rows == 3 % Pad data with homogeneous scale factor of 1
x2 = [x2; ones(1,npts)];
end
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise3dpts(x2);
s = 6;
fittingfn = @projmatrix;
distfn = @reprojectiondist;
degenfn = @isdegenerate;
maxDataTrials = 100;
maxTrials = 2000;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[P, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback, maxDataTrials, maxTrials);
% Now do a final least squares fit on the data points considered to
% be inliers.
P = projmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
P = inv(T1)*P*T2;
% make sure the projection matrix fits together with the projection
% matrices computed with the essential matrix
P = ([P./norm(P(1:3,1:3)); 0 0 0 1]);
%--------------------------------------------------------------------------
function [bestInliers, bestP] = reprojectiondist(P, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:7,:);
if iscell(P) % We have several solutions each of which must be tested
nP = length(P); % Number of solutions to test
bestP = P{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nP
proj = zeros(3,length(x1));
for n = 1:length(x1)
proj(:,n) = P{k}*x2(:,n);
proj(1:3,n) = proj(1:3,n)./proj(3,n);
end
error = sqrt(sum((x1(1:2,:) - proj(1:2,:)).^2,1));
inliers = find(abs(error) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestP = P{k};
bestInliers = inliers;
end
end
else % We just have one solution
proj = zeros(3,length(x1));
for n = 1:length(x1)
proj(:,n) = P*x2(:,n);
proj(1:3,n) = proj(1:3,n)./proj(3,n);
end
error = sqrt(sum((x1(1:2,:) - proj(1:2,:)).^2,1));
bestInliers = find(abs(error) < t); % Indices of inlying points
bestP = P; % Copy F directly to bestF
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a projection matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
albertomontesg/computer-vision-exercises-master
|
showFeatureMatches.m
|
.m
|
computer-vision-exercises-master/exercise6/code/showFeatureMatches.m
| 756 |
utf_8
|
59cf88c95fbb9fb5157440341544b30e
|
% show feature matches between two images
%
% Input:
% img1 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of first image
% img2 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of second image
% fig - figure id
function showFeatureMatches(img1, corner1, img2, corner2, fig)
[~, sy, ~] = size(img1);
img = [img1, img2];
corner2 = corner2 + repmat([sy, 0]', [1, size(corner2, 2)]);
figure(fig), imshow(img, []);
hold on, plot(corner1(1,:), corner1(2,:), '+r');
hold on, plot(corner2(1,:), corner2(2,:), '+r');
hold on, plot([corner1(1,:); corner2(1,:)], [corner1(2,:); corner2(2,:)], 'b');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
ransacfitfundmatrix.m
|
.m
|
computer-vision-exercises-master/exercise6/code/ransacfitfundmatrix.m
| 5,681 |
utf_8
|
d636255e269db2be2501f6bd39d651c1
|
% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC
%
% Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, FUNDMATRIX
% Copyright (c) 2004-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2004 Original version
% August 2005 Distance error function changed to match changes in RANSAC
function [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 2
t = 0.00005;
feedback = 0;
end
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'fundmatrix' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 8; % Number of points needed to fit a fundamental matrix. Note that
% only 7 are needed but the function 'fundmatrix' only
% implements the 8-point solution.
fittingfn = @fundmatrix;
distfn = @funddist;
degenfn = @isdegenerate;
maxDataTrials = 100;
maxTrials = 2000;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback, maxDataTrials, maxTrials);
% Now do a final least squares fit on the data points considered to
% be inliers.
F = fundmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
F = T2'*F*T1;
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
%
% Note that this code allows for F being a cell array of fundamental matrices of
% which we have to pick the best one. (A 7 point solution can return up to 3
% solutions)
function [bestInliers, bestF] = funddist(F, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
if iscell(F) % We have several solutions each of which must be tested
nF = length(F); % Number of solutions to test
bestF = F{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nF
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);
end
Fx1 = F{k}*x1;
Ftx2 = F{k}'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
inliers = find(abs(d) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestF = F{k};
bestInliers = inliers;
end
end
else % We just have one solution
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F*x1(:,n);
end
Fx1 = F*x1;
Ftx2 = F'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
bestInliers = find(abs(d) < t); % Indices of inlying points
bestF = F; % Copy F directly to bestF
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
albertomontesg/computer-vision-exercises-master
|
normalise3dpts.m
|
.m
|
computer-vision-exercises-master/exercise6/code/normalise3dpts.m
| 2,182 |
utf_8
|
54c8a965fb92edec39a1f93028771089
|
% NORMALISE3DPTS - normalises 3D homogeneous points
%
% Function translates and normalises a set of 3D homogeneous points
% so that their centroid is at the origin and their mean distance from
% the origin is sqrt(3). This process typically improves the
% conditioning of any equations used to solve homographies, fundamental
% matrices etc.
%
% Usage: [newpts, T] = normalise3dpts(pts)
%
% Argument:
% pts - 4xN array of 4D homogeneous coordinates
%
% Returns:
% newpts - 4xN array of transformed 3D homogeneous coordinates. The
% scaling parameter is normalised to 1 unless the point is at
% infinity.
% T - The 4x4 transformation matrix, newpts = T*pts
%
% If there are some points at infinity the normalisation transform
% is calculated using just the finite points. Being a scaling and
% translating transform this will not affect the points at infinity.
function [newpts, T] = normalise3dpts(pts)
if size(pts,1) ~= 4
error('pts must be 4xN');
end
% Find the indices of the points that are not at infinity
finiteind = find(abs(pts(4,:)) > eps);
if length(finiteind) ~= size(pts,2)
warning('Some points are at infinity');
end
% For the finite points ensure homogeneous coords have scale of 1
pts(1,finiteind) = pts(1,finiteind)./pts(4,finiteind);
pts(2,finiteind) = pts(2,finiteind)./pts(4,finiteind);
pts(3,finiteind) = pts(3,finiteind)./pts(4,finiteind);
pts(4,finiteind) = 1;
c = mean(pts(1:3,finiteind)')'; % Centroid of finite points
newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.
newp(2,finiteind) = pts(2,finiteind)-c(2);
newp(3,finiteind) = pts(3,finiteind)-c(3);
dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2 + newp(3,finiteind).^2);
meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1
scale = sqrt(3)/meandist;
T = [scale 0 0 -scale*c(1);
0 scale 0 -scale*c(2);
0 0 scale -scale*c(3);
0 0 0 1 ];
newpts = T*pts;
|
github
|
albertomontesg/computer-vision-exercises-master
|
projmatrix.m
|
.m
|
computer-vision-exercises-master/exercise6/code/projmatrix.m
| 2,113 |
utf_8
|
790273b38d11e84890a2ae16ec749317
|
% PROJMATRIX - computes projection matrix from 6 or more 3D-2D points
%
% Function computes the projection matrix from 6 or more 3D-2D matching points in
% a stereo pair of images. The normalised 6 point algorithm given by
% Hartley and Zisserman is used. To achieve accurate results it is
% recommended that 12 or more points are used
%
% Usage: [P] = projmatrix(x1, x2)
%
% Arguments:
% x1, x2 - Two sets of corresponding 3xN and 4xN set of homogeneous
% points.
% Returns:
% P - The 3x4 projection matrix.
function [P] = projmatrix(varargin)
[x1, x2, npts] = checkargs(varargin(:));
Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave?
% Normalise each set of points so that the origin
% is at centroid and mean distance from origin is sqrt(2).
% normalise2dpts also ensures the scale parameter is 1.
[xy, T1] = normalise2dpts(x1);
[XYZ, T2] = normalise3dpts(x2);
% Build the constraint matrix
A = [XYZ(1,:)' XYZ(2,:)' XYZ(3,:)' ones(npts,1) zeros(npts,1) zeros(npts,1) zeros(npts,1) zeros(npts,1) -xy(1,:)'.*XYZ(1,:)' -xy(1,:)'.*XYZ(2,:)' -xy(1,:)'.*XYZ(3,:)' -xy(1,:)';
zeros(npts,1) zeros(npts,1) zeros(npts,1) zeros(npts,1) XYZ(1,:)' XYZ(2,:)' XYZ(3,:)' ones(npts,1) -xy(2,:)'.*XYZ(1,:)' -xy(2,:)'.*XYZ(2,:)' -xy(2,:)'.*XYZ(3,:)' -xy(2,:)'];
if Octave
[U,D,V] = svd(A); % Don't seem to be able to use the economy
% decomposition under Octave here
else
[U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition
end
Pvec = V(:, end);
P = [Pvec(1) Pvec(2) Pvec(3) Pvec(4) ;
Pvec(5) Pvec(6) Pvec(7) Pvec(8) ;
Pvec(9) Pvec(10) Pvec(11) Pvec(12)];
% Denormalise
P = inv(T1)*P*T2;
function [x1, x2, npts] = checkargs(arg);
if length(arg) == 2
x1 = arg{1};
x2 = arg{2};
elseif length(arg) == 1
x1 = arg{1}(1:3,:);
x2 = arg{1}(4:7,:);
else
error('Wrong number of arguments supplied');
end
npts = size(x1,2);
|
github
|
albertomontesg/computer-vision-exercises-master
|
hnormalise.m
|
.m
|
computer-vision-exercises-master/exercise6/code/hnormalise.m
| 1,012 |
utf_8
|
ac17ab683e70a6324bb66b10d5e547d0
|
% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1
%
% Usage: nx = hnormalise(x)
%
% Argument:
% x - an Nxnpts array of homogeneous coordinates.
%
% Returns:
% nx - an Nxnpts array of homogeneous coordinates rescaled so
% that the scale values nx(N,:) are all 1.
%
% Note that any homogeneous coordinates at infinity (having a scale value of
% 0) are left unchanged.
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk
%
% February 2004
function nx = hnormalise(x)
[rows,npts] = size(x);
nx = x;
% Find the indices of the points that are not at infinity
finiteind = find(abs(x(rows,:)) > eps);
if length(finiteind) ~= npts
warning('Some points are at infinity');
end
% Normalise points not at infinity
for r = 1:rows-1
nx(r,finiteind) = x(r,finiteind)./x(rows,finiteind);
end
nx(rows,finiteind) = 1;
|
github
|
albertomontesg/computer-vision-exercises-master
|
makeinhomogeneous.m
|
.m
|
computer-vision-exercises-master/exercise6/code/makeinhomogeneous.m
| 791 |
utf_8
|
ce76d362845ed0c7eef257d1d0406795
|
% MAKEINHOMOGENEOUS - Converts homogeneous coords to inhomogeneous coordinates
%
% Usage: x = makehomogeneous(hx)
%
% Argument:
% hx - an N x npts array of homogeneous coordinates.
%
% Returns:
% x - an (N-1) x npts array of inhomogeneous coordinates
%
% Warning: If there are any points at infinity (scale = 0) the coordinates
% of these points are simply returned minus their scale coordinate.
%
% See also: MAKEHOMOGENEOUS, HNORMALISE
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% April 2010
function x = makeinhomogeneous(hx)
hx = hnormalise(hx); % Normalise to scale of one
x = hx(1:end-1,:); % Extract all but the last row
|
github
|
albertomontesg/computer-vision-exercises-master
|
create3DModel.m
|
.m
|
computer-vision-exercises-master/exercise6/code/create3DModel.m
| 1,038 |
utf_8
|
fb590ce1dd28521c85c6d4f32c2866d0
|
%depth image in double
%img - rgb image in double
function create3DModel(depth, img, fig)
skip = 1;
img = img(1:skip:end, 1:skip:end, :);
depth = (depth(1:skip:end, 1:skip:end));
[sx, sy] = size(depth);
K = [1 0 sx/2;
0 1 sy/2;
0 0 1];
Kinv = inv(K);
% Get 3d points.
[Xp Yp] = meshgrid(1:size(depth,2), 1:size(depth,1));
Zp = depth;
figure(fig);
imgR = img(:,:,1);
imgG = img(:,:,2);
imgB = img(:,:,3);
col = [imgR(:), imgG(:), imgB(:)];
%chose either scatter3 or trisurf method to plot
if (true)
Xp = depth .* (Xp*Kinv(1,1) + Yp*Kinv(1,2) + Kinv(1,3));
Yp = depth .* (Yp*Kinv(2,2) + Kinv(2,3));
scatter3(Xp(:), Yp(:), Zp(:), 1, col);
else
tri = delaunay(Xp(:), Yp(:));
trisurf(tri, Xp(:), Yp(:), Zp(:));
trisurf(tri, Xp(:), Yp(:), Zp(:),'FaceVertexCData', col, 'LineStyle', 'none', 'FaceColor', 'interp');
end
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
showFeatureInliers.m
|
.m
|
computer-vision-exercises-master/exercise6/code/showFeatureInliers.m
| 996 |
utf_8
|
d115855b8ec9edc71bf2c7a9954e0037
|
% show feature matches between two images
%
% Input:
% img1 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of first image
% img2 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of second image
% fig - figure id
function showFeatureMatches(img1, corner1, img2, corner2, inliers_pos, fig)
sy = size(img1, 2);
img = [img1, img2];
in_pos = false(1, size(corner1,2));
in_pos(inliers_pos) = true;
corner2 = corner2 + repmat([sy, 0]', [1, size(corner2, 2)]);
figure(fig), imshow(img, []);
hold on, plot(corner1(1,:), corner1(2,:), '+r');
hold on, plot(corner2(1,:), corner2(2,:), '+r');
hold on, plot([corner1(1,in_pos); corner2(1,in_pos)],...
[corner1(2,in_pos); corner2(2,in_pos)], 'g');
hold on, plot([corner1(1,~in_pos); corner2(1,~in_pos)],...
[corner1(2,~in_pos); corner2(2,~in_pos)], 'r');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
fundmatrix.m
|
.m
|
computer-vision-exercises-master/exercise6/code/fundmatrix.m
| 3,975 |
utf_8
|
16d85192930d30a0b89c7e70077c9e5a
|
% FUNDMATRIX - computes fundamental matrix from 8 or more points
%
% Function computes the fundamental matrix from 8 or more matching points in
% a stereo pair of images. The normalised 8 point algorithm given by
% Hartley and Zisserman p265 is used. To achieve accurate results it is
% recommended that 12 or more points are used
%
% Usage: [F, e1, e2] = fundmatrix(x1, x2)
% [F, e1, e2] = fundmatrix(x)
%
% Arguments:
% x1, x2 - Two sets of corresponding 3xN set of homogeneous
% points.
%
% x - If a single argument is supplied it is assumed that it
% is in the form x = [x1; x2]
% Returns:
% F - The 3x3 fundamental matrix such that x2'*F*x1 = 0.
% e1 - The epipole in image 1 such that F*e1 = 0
% e2 - The epipole in image 2 such that F'*e2 = 0
%
% Copyright (c) 2002-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% Feb 2002 - Original version.
% May 2003 - Tidied up and numerically improved.
% Feb 2004 - Single argument allowed to enable use with RANSAC.
% Mar 2005 - Epipole calculation added, 'economy' SVD used.
% Aug 2005 - Octave compatibility
function [F,e1,e2] = fundmatrix(varargin)
[x1, x2, npts] = checkargs(varargin(:));
Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave?
% Normalise each set of points so that the origin
% is at centroid and mean distance from origin is sqrt(2).
% normalise2dpts also ensures the scale parameter is 1.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
% Build the constraint matrix
A = [x2(1,:)'.*x1(1,:)' x2(1,:)'.*x1(2,:)' x2(1,:)' ...
x2(2,:)'.*x1(1,:)' x2(2,:)'.*x1(2,:)' x2(2,:)' ...
x1(1,:)' x1(2,:)' ones(npts,1) ];
if Octave
[U,D,V] = svd(A); % Don't seem to be able to use the economy
% decomposition under Octave here
else
[U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition
end
% Extract fundamental matrix from the column of V corresponding to
% smallest singular value.
F = reshape(V(:,9),3,3)';
% Enforce constraint that fundamental matrix has rank 2 by performing
% a svd and then reconstructing with the two largest singular values.
[U,D,V] = svd(F,0);
F = U*diag([D(1,1) D(2,2) 0])*V';
% Denormalise
F = T2'*F*T1;
if nargout == 3 % Solve for epipoles
[U,D,V] = svd(F,0);
e1 = hnormalise(V(:,3));
e2 = hnormalise(U(:,3));
end
%--------------------------------------------------------------------------
% Function to check argument values and set defaults
function [x1, x2, npts] = checkargs(arg);
if length(arg) == 2
x1 = arg{1};
x2 = arg{2};
if ~all(size(x1)==size(x2))
error('x1 and x2 must have the same size');
elseif size(x1,1) ~= 3
error('x1 and x2 must be 3xN');
end
elseif length(arg) == 1
if size(arg{1},1) ~= 6
error('Single argument x must be 6xN');
else
x1 = arg{1}(1:3,:);
x2 = arg{1}(4:6,:);
end
else
error('Wrong number of arguments supplied');
end
npts = size(x1,2);
if npts < 8
error('At least 8 points are needed to compute the fundamental matrix');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
ransac.m
|
.m
|
computer-vision-exercises-master/exercise6/code/ransac.m
| 9,877 |
utf_8
|
6161d8cc1a602a9c2796433f55d7b6dd
|
% RANSAC - Robustly fits a model to data with the RANSAC algorithm
%
% Usage:
%
% [M, inliers] = ransac(x, fittingfn, distfn, degenfn s, t, feedback, ...
% maxDataTrials, maxTrials)
%
% Arguments:
% x - Data sets to which we are seeking to fit a model M
% It is assumed that x is of size [d x Npts]
% where d is the dimensionality of the data and Npts is
% the number of data points.
%
% fittingfn - Handle to a function that fits a model to s
% data from x. It is assumed that the function is of the
% form:
% M = fittingfn(x)
% Note it is possible that the fitting function can return
% multiple models (for example up to 3 fundamental matrices
% can be fitted to 7 matched points). In this case it is
% assumed that the fitting function returns a cell array of
% models.
% If this function cannot fit a model it should return M as
% an empty matrix.
%
% distfn - Handle to a function that evaluates the
% distances from the model to data x.
% It is assumed that the function is of the form:
% [inliers, M] = distfn(M, x, t)
% This function must evaluate the distances between points
% and the model returning the indices of elements in x that
% are inliers, that is, the points that are within distance
% 't' of the model. Additionally, if M is a cell array of
% possible models 'distfn' will return the model that has the
% most inliers. If there is only one model this function
% must still copy the model to the output. After this call M
% will be a non-cell object representing only one model.
%
% degenfn - Handle to a function that determines whether a
% set of datapoints will produce a degenerate model.
% This is used to discard random samples that do not
% result in useful models.
% It is assumed that degenfn is a boolean function of
% the form:
% r = degenfn(x)
% It may be that you cannot devise a test for degeneracy in
% which case you should write a dummy function that always
% returns a value of 1 (true) and rely on 'fittingfn' to return
% an empty model should the data set be degenerate.
%
% s - The minimum number of samples from x required by
% fittingfn to fit a model.
%
% t - The distance threshold between a data point and the model
% used to decide whether the point is an inlier or not.
%
% feedback - An optional flag 0/1. If set to one the trial count and the
% estimated total number of trials required is printed out at
% each step. Defaults to 0.
%
% maxDataTrials - Maximum number of attempts to select a non-degenerate
% data set. This parameter is optional and defaults to 100.
%
% maxTrials - Maximum number of iterations. This parameter is optional and
% defaults to 1000.
%
% Returns:
% M - The model having the greatest number of inliers.
% inliers - An array of indices of the elements of x that were
% the inliers for the best model.
%
% For an example of the use of this function see RANSACFITHOMOGRAPHY or
% RANSACFITPLANE
% References:
% M.A. Fishler and R.C. Boles. "Random sample concensus: A paradigm
% for model fitting with applications to image analysis and automated
% cartography". Comm. Assoc. Comp, Mach., Vol 24, No 6, pp 381-395, 1981
%
% Richard Hartley and Andrew Zisserman. "Multiple View Geometry in
% Computer Vision". pp 101-113. Cambridge University Press, 2001
% Copyright (c) 2003-2006 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2003 - Original version
% February 2004 - Tidied up.
% August 2005 - Specification of distfn changed to allow model fitter to
% return multiple models from which the best must be selected
% Sept 2006 - Random selection of data points changed to ensure duplicate
% points are not selected.
% February 2007 - Jordi Ferrer: Arranged warning printout.
% Allow maximum trials as optional parameters.
% Patch the problem when non-generated data
% set is not given in the first iteration.
% August 2008 - 'feedback' parameter restored to argument list and other
% breaks in code introduced in last update fixed.
% December 2008 - Octave compatibility mods
% June 2009 - Argument 'MaxTrials' corrected to 'maxTrials'!
function [M, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback, ...
maxDataTrials, maxTrials)
Octave = exist('OCTAVE_VERSION') ~= 0;
% Test number of parameters
error ( nargchk ( 6, 9, nargin ) );
if nargin < 9; maxTrials = 1000; end;
if nargin < 8; maxDataTrials = 100; end;
if nargin < 7; feedback = 0; end;
[rows, npts] = size(x);
p = 0.99; % Desired probability of choosing at least one sample
% free from outliers
bestM = NaN; % Sentinel value allowing detection of solution failure.
trialcount = 0;
bestscore = 0;
N = 1; % Dummy initialisation for number of trials.
while N > trialcount
% Select at random s datapoints to form a trial model, M.
% In selecting these points we have to check that they are not in
% a degenerate configuration.
degenerate = 1;
count = 1;
while degenerate
% Generate s random indicies in the range 1..npts
% (If you do not have the statistics toolbox, or are using Octave,
% use the function RANDOMSAMPLE from my webpage)
if Octave | ~exist('randsample.m')
ind = randomsample(npts, s);
else
ind = randsample(npts, s);
end
% Test that these points are not a degenerate configuration.
degenerate = feval(degenfn, x(:,ind));
if ~degenerate
% Fit model to this random selection of data points.
% Note that M may represent a set of models that fit the data in
% this case M will be a cell array of models
M = feval(fittingfn, x(:,ind));
% Depending on your problem it might be that the only way you
% can determine whether a data set is degenerate or not is to
% try to fit a model and see if it succeeds. If it fails we
% reset degenerate to true.
if isempty(M)
degenerate = 1;
end
end
% Safeguard against being stuck in this loop forever
count = count + 1;
if count > maxDataTrials
warning('Unable to select a nondegenerate data set');
break
end
end
% Once we are out here we should have some kind of model...
% Evaluate distances between points and model returning the indices
% of elements in x that are inliers. Additionally, if M is a cell
% array of possible models 'distfn' will return the model that has
% the most inliers. After this call M will be a non-cell object
% representing only one model.
[inliers, M] = feval(distfn, M, x, t);
% Find the number of inliers to this model.
ninliers = length(inliers);
if ninliers > bestscore % Largest set of inliers so far...
bestscore = ninliers; % Record data for this model
bestinliers = inliers;
bestM = M;
% Update estimate of N, the number of trials to ensure we pick,
% with probability p, a data set with no outliers.
fracinliers = ninliers/npts;
pNoOutliers = 1 - fracinliers^s;
pNoOutliers = max(eps, pNoOutliers); % Avoid division by -Inf
pNoOutliers = min(1-eps, pNoOutliers);% Avoid division by 0.
N = log(1-p)/log(pNoOutliers);
end
trialcount = trialcount+1;
if feedback
fprintf('trial %d out of %d \r',trialcount, ceil(N));
end
% Safeguard against being stuck in this loop forever
if trialcount > maxTrials
warning( ...
sprintf('ransac reached the maximum number of %d trials',...
maxTrials));
break
end
end
fprintf('\n');
if ~isnan(bestM) % We got a solution
M = bestM;
inliers = bestinliers;
else
M = [];
inliers = [];
error('ransac was unable to find a useful solution');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
normalise2dpts.m
|
.m
|
computer-vision-exercises-master/exercise6/code/normalise2dpts.m
| 2,361 |
utf_8
|
2b9d94a3681186006a3fd47a45faf939
|
% NORMALISE2DPTS - normalises 2D homogeneous points
%
% Function translates and normalises a set of 2D homogeneous points
% so that their centroid is at the origin and their mean distance from
% the origin is sqrt(2). This process typically improves the
% conditioning of any equations used to solve homographies, fundamental
% matrices etc.
%
% Usage: [newpts, T] = normalise2dpts(pts)
%
% Argument:
% pts - 3xN array of 2D homogeneous coordinates
%
% Returns:
% newpts - 3xN array of transformed 2D homogeneous coordinates. The
% scaling parameter is normalised to 1 unless the point is at
% infinity.
% T - The 3x3 transformation matrix, newpts = T*pts
%
% If there are some points at infinity the normalisation transform
% is calculated using just the finite points. Being a scaling and
% translating transform this will not affect the points at infinity.
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% May 2003 - Original version
% February 2004 - Modified to deal with points at infinity.
% December 2008 - meandist calculation modified to work with Octave 3.0.1
% (thanks to Ron Parr)
function [newpts, T] = normalise2dpts(pts)
if size(pts,1) ~= 3
error('pts must be 3xN');
end
% Find the indices of the points that are not at infinity
finiteind = find(abs(pts(3,:)) > eps);
if length(finiteind) ~= size(pts,2)
warning('Some points are at infinity');
end
% For the finite points ensure homogeneous coords have scale of 1
pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind);
pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind);
pts(3,finiteind) = 1;
c = mean(pts(1:2,finiteind)')'; % Centroid of finite points
newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.
newp(2,finiteind) = pts(2,finiteind)-c(2);
dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2);
meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1
scale = sqrt(2)/meandist;
T = [scale 0 -scale*c(1)
0 scale -scale*c(2)
0 0 1 ];
newpts = T*pts;
|
github
|
albertomontesg/computer-vision-exercises-master
|
showImageWithSIFT.m
|
.m
|
computer-vision-exercises-master/exercise1/code/showImageWithSIFT.m
| 333 |
utf_8
|
d22d381bd687e62736387ce7fe7483c3
|
% show image with key points
%
% Input:
% img - n x m color image
% corner - 2 x k matrix, holding keypoint coordinates of first image
% fig - figure id
function showImageWithSIFT(img, sift_features, fig)
figure(fig);
imshow(img, []);
hold on
vl_plotframe(sift_features);
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
showFeatureMatches.m
|
.m
|
computer-vision-exercises-master/exercise1/code/showFeatureMatches.m
| 758 |
utf_8
|
8b7d6b5462a35ff1c02e7f0a4db16712
|
% show feature matches between two images
%
% Input:
% img1 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of first image
% img2 - n x m color image
% corner1 - 2 x k matrix, holding keypoint coordinates of second image
% fig - figure id
function showFeatureMatches(img1, corner1, img2, corner2, fig)
[sx, sy, sz] = size(img1);
img = [img1, img2];
corner2 = corner2 + repmat([sy, 0]', [1, size(corner2, 2)]);
figure(fig), imshow(img, []);
hold on, plot(corner1(1,:), corner1(2,:), '+r');
hold on, plot(corner2(1,:), corner2(2,:), '+r');
hold on, plot([corner1(1,:); corner2(1,:)], [corner1(2,:); corner2(2,:)], 'b');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
extractDescriptor.m
|
.m
|
computer-vision-exercises-master/exercise1/code/extractDescriptor.m
| 1,023 |
utf_8
|
8aad6d78974c3f7e5402318b87241581
|
% extract descriptor
%
% Input:
% keyPoints - detected keypoints in a 2 x n matrix holding the key
% point coordinates
% img - the gray scale image
%
% Output:
% descr - w x n matrix, stores for each keypoint a
% descriptor. m is the size of the image patch,
% represented as vector
function descr = extractDescriptor(corners, img)
% Descriptor size: 9x9
patch_size = 9;
pad = (patch_size-1) / 2;
% Apply padding for the descriptors at the edges
img = padarray(img, [pad pad]);
% Initialize th descriptors output
n = size(corners, 2);
descr = zeros(patch_size^2, n);
% Iterate for each corner and extract the corresponding patch
for i = 1:n
r_pos = corners(1,i) + pad;
c_pos = corners(2,i) + pad;
patch = img((r_pos-pad):(r_pos+pad),(c_pos-pad):(c_pos+pad));
descr(:,i) = reshape(patch', patch_size^2, 1);
end
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
showImageWithCorners.m
|
.m
|
computer-vision-exercises-master/exercise1/code/showImageWithCorners.m
| 339 |
utf_8
|
0f689ab81e2bd82f3593f8609335dfb1
|
% show image with key points
%
% Input:
% img - n x m color image
% corner - 2 x k matrix, holding keypoint coordinates of first image
% fig - figure id
function showImageWithCorners(img, corners, fig)
figure(fig);
imshow(img, []);
hold on, plot(corners(1,:), corners(2,:), '+r');
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
extractHarrisCorner.m
|
.m
|
computer-vision-exercises-master/exercise1/code/extractHarrisCorner.m
| 1,249 |
utf_8
|
61d4a4604fc151953c9a3d9ac60beaa4
|
% extract harris corner
%
% Input:
% img - n x m gray scale image
% thresh - scalar value to threshold corner strength
%
% Output:
% corners - 2 x k matrix storing the keypoint coordinates
% H - n x m gray scale image storing the corner strength
function [corners, H] = extractHarrisCorner(img, thresh)
% Define the gradients steps
dx = [-.5 0 .5];
dy = dx';
% Compute the gradient of the image at each axis
IX = conv2(padarray(img, [0, 1], 'symmetric'), dx, 'valid');
IY = conv2(padarray(img, [1, 0], 'symmetric'), dy, 'valid');
% Apply Gaussian Filter and compute all the Harris matrix values
blur_filter = fspecial('gaussian');
IX2 = conv2(IX.^2, blur_filter, 'same');
IY2 = conv2(IY.^2, blur_filter, 'same');
IXIY = conv2(IX.*IY, blur_filter, 'same');
% Compute the Harris Response Measure
H = (IX2.*IY2 - IXIY.^2) ./ (IX2 + IY2 + eps);
% Non-Maximum-Suppression in a 3 pixel radius;
radius = 3;
diam = 2*radius + 1;
mx = ordfilt2(H, diam^2, ones(diam));
cim = (H==mx)&(H>thresh);
% Find the localization of the corners
[r,c] = find(cim);
corners = [r'; c'];
end
|
github
|
albertomontesg/computer-vision-exercises-master
|
matchDescriptors.m
|
.m
|
computer-vision-exercises-master/exercise1/code/matchDescriptors.m
| 847 |
utf_8
|
b4397cccdf4daae9de8506da30242d06
|
% match descriptors
%
% Input:
% descr1 - k x n descriptor of first image
% descr2 - k x m descriptor of second image
% thresh - scalar value to threshold the matches
%
% Output:
% matches - 2 x w matrix storing the indices of the matching
% descriptors
function matches = matchDescriptors(descr1, descr2, thresh)
% Initialize the SSD matrix
n = size(descr1, 2);
m = size(descr2, 2);
ssd = zeros(n, m);
% Compute the Sum of Square Differences
for i = 1:n
for j = 1:m
dif = descr1(:,i) - descr2(:,j);
ssd(i,j) = dif'*dif;
end
end
% Find the positions where the SSD is less than the given thresehold
match = (ssd<thresh);
[r, c] = find(match);
matches = [r'; c'];
end
|
github
|
bradmonk/neuromorph-master
|
neuromorph.m
|
.m
|
neuromorph-master/neuromorph.m
| 31,150 |
utf_8
|
1ca551cd60a803c7cb9a3459cb0fcbf2
|
function varargout = neuromorph(varargin)
%% neuromorph.m - NEURON MORPHOLOGY TOOLBOX
%{
%
% Syntax
% -----------------------------------------------------
% neuromorph()
%
%
% Description
% -----------------------------------------------------
%
% neuromorph() is run with no arguments passed in. The user
% will be prompted to select a directory which contains the image data
% tif stack along with the corresponding xls file.
%
%
% Useage Definitions
% -----------------------------------------------------
%
% neuromorph()
% launches a GUI to process image stack data from GRIN lens
% experiments
%
%
%
% Example
% -----------------------------------------------------
%
% TBD
%
%
% See Also
% -----------------------------------------------------
% >> web('http://bradleymonk.com/neuromorph')
% >> web('http://imagej.net/Miji')
% >> web('http://bigwww.epfl.ch/sage/soft/mij/')
%
%
% Attribution
% -----------------------------------------------------
% % Created by: Bradley Monk
% % email: [email protected]
% % website: bradleymonk.com
% % 2016.07.04
%}
%----------------------------------------------------
%% ESTABLISH STARTING PATHS
clc; close all; clear all; clear java;
disp('WELCOME TO NEUROMORPH - A NEURON MORPHOLOGY TOOLBOX')
global thisfilepath
thisfile = 'neuromorph.m';
thisfilepath = fileparts(which(thisfile));
cd(thisfilepath);
fprintf('\n\n Current working path set to: \n % s \n', thisfilepath)
pathdir0 = thisfilepath;
pathdir1 = [thisfilepath '/neuromorphdata'];
gpath = [pathdir0 ':' pathdir1];
addpath(gpath)
fprintf('\n\n Added folders to path: \n % s \n % s \n % s \n % s \n\n',...
pathdir0,pathdir1)
%% MANUALLY SET PER-SESSION PATH PARAMETERS IF WANTED
global datadir datafile datadate
datadir = '';
datafile = '';
datadate = '';
global imgpath
imgpath = '';
%% CD TO DATA DIRECTORY
%{
if numel(datadir) < 1
datadir = uigetdir;
end
cd(datadir);
home = cd;
disp(['HOME PATH: ' datadir])
if numel(datafile) < 1
datafile = uigetfile('*.tif*; *.bmp');
end
imgpath = [datadir '/' datafile];
%}
%% ESTABLISH GLOBALS AND SET STARTING VALUES
global IMG DENDRITE SPINE SPINEHN ROISAVES ROInum
IMG = [];
ROISAVES = [];
ROISAVES.SpineMask = [];
ROISAVES.SpinePos = [];
ROISAVES.SpineExtentPos = [0 0];
ROISAVES.SpineExtentCenter = [];
ROISAVES.SpineExtentX = [];
ROISAVES.SpineExtentY = [];
ROISAVES.SpineHeadPos = [0 0];
ROISAVES.SpineHeadCenter = [];
ROISAVES.SpineHeadX = [];
ROISAVES.SpineHeadY = [];
ROISAVES.SpineNeckPos = [0 0];
ROISAVES.SpineNeckCenter = [];
ROISAVES.SpineNeckX = [];
ROISAVES.SpineNeckY = [];
ROISAVES.DendritePos = [0 0];
ROISAVES.DendriteCenter = [];
ROISAVES.DendriteX = [];
ROISAVES.DendriteY = [];
ROISAVES.SpineNearPos = [0 0];
ROISAVES.SpineNearCenter = [];
ROISAVES.SpineNearX = [];
ROISAVES.SpineNearY = [];
SPINE.intensity = [];
SPINE.area = [];
SPINEHN.spineextent = [];
SPINEHN.spineextentintensity = [];
SPINEHN.spineextentintensityprofile = [];
SPINEHN.spineextentcenter = [];
SPINEHN.headwidth = [];
SPINEHN.headintensity = [];
SPINEHN.headintensityprofile = [];
SPINEHN.headcenter = [];
SPINEHN.necklength = [];
SPINEHN.neckintensity = [];
SPINEHN.neckintensityprofile = [];
SPINEHN.neckcenter = [];
DENDRITE.size = [];
DENDRITE.intensity = [];
DENDRITE.intensityprofile = [];
DENDRITE.center = [];
DENDRITE.nearestspine = [];
DENDRITE.nearestspineint = [];
DENDRITE.nearestspineprofile = [];
DENDRITE.nearestspinecenter = [];
SPINE.area = 0;
SPINE.intensity = 0;
SPINEHN.spineextent = 0;
SPINEHN.spineextentintensity = 0;
SPINEHN.headwidth = 0;
SPINEHN.headintensity = 0;
SPINEHN.necklength = 0;
SPINEHN.neckintensity = 0;
DENDRITE.size = 0;
DENDRITE.intensity = 0;
DENDRITE.nearestspine = 0;
DENDRITE.nearestspineint = 0;
global haxPRE memos memoboxH
global dotsz cdotsz
dotsz = 30;
cdotsz = 150;
global magnification maglevel
global MORPHdata MORPHdat MORPHtab MORPHd ROInames Datafilename
global hROI ROImask ROIpos dendritesize dpos
global imXlim imYlim VxD dVOL
magnification = 6;
maglevel = 6;
dendritesize = maglevel*5;
dpos = [];
MORPHdata = {};
MORPHdat = [];
MORPHtab = [];
MORPHd = [];
ROInames = '';
Datafilename = '';
hROI = [];
ROImask = [];
ROIpos = [];
ROIarea = [];
ROI_INTENSITY = [];
ROI_INTENSITY_MEAN = [];
VxD = 1;
dVOL = 1;
global MORPHdats ccmap cmmap phCCD
MORPHdats = {};
ccmap = [];
cmmap = [];
% global ROI_INTENSITY ROI_INTENSITY_MEAN ROIarea
%########################################################################
%% MAIN ANALYSIS GUI WINDOW SETUP
%########################################################################
% mainguih.CurrentCharacter = '+';
mainguih = figure('Units', 'normalized','OuterPosition', [.02 .05 .85 .87], 'BusyAction',...
'cancel', 'Name', 'Lifetime image', 'Tag', 'lifetime image','Visible', 'Off', ...
'KeyPressFcn', {@keypresszoom,1},'Color',[.99 .99 .99],'MenuBar','none','Resize','off');
haxCCD = axes('Parent', mainguih, 'NextPlot', 'Add',...
'Position', [0.01 0.01 0.60 0.95], 'PlotBoxAspectRatio', [1 1 1], ...
'XColor','none','YColor','none');
cmapsliderH = uicontrol('Parent', mainguih, 'Units', 'normalized','Style','slider',...
'Max',50,'Min',1,'Value',10,'SliderStep',[.1 .2],...
'Position', [0.02 0.96 0.58 0.03], 'Callback', @cmapslider);
haxPRE = axes('Parent', mainguih, 'NextPlot', 'replacechildren',...
'Position', [0.63 0.03 0.36 0.25]);
axes(haxCCD)
%----------------------------------------------------
% IMAGE PROCESSING PANEL
%----------------------------------------------------
IPpanelH = uipanel('Title','Image Processing','FontSize',10,...
'BackgroundColor',[1 1 1],...
'Position', [0.62 0.60 0.37 0.39]); % 'Visible', 'Off',
getROIH = uicontrol('Parent', IPpanelH, 'Units', 'normalized', ...
'Position', [0.05 0.80 0.45 0.15], 'FontSize', 11, 'String', 'MEASURE ROI',...
'Callback', @getROI);
uicontrol('Parent', IPpanelH, 'Style', 'Text', 'Units', 'normalized','BackgroundColor',[.96 .96 .96],...
'Position', [0.68 0.91 0.25 0.06], 'FontSize', 12,'String', 'ROI ID');
ROIIDh = uicontrol('Parent', IPpanelH, 'Style', 'Edit', 'Units', 'normalized', ...
'Position', [0.68 0.81 0.25 0.10], 'FontSize', 11,'BackgroundColor',[1 1 1]);
measureButtonsH = uipanel('Parent', IPpanelH,'Title','Analyses','FontSize',10,...
'BackgroundColor',[.99 .99 .99],...
'Position', [0.05 0.15 0.90 0.60]); % 'Visible', 'Off',
yp = 1 - ((1/6.2) .* (1:6));
bpos1 = [0.05 yp(1) 0.95 0.14];
bpos2 = [0.05 yp(2) 0.95 0.14];
bpos3 = [0.05 yp(3) 0.95 0.14];
bpos4 = [0.05 yp(4) 0.95 0.14];
bpos5 = [0.05 yp(5) 0.95 0.14];
bpos6 = [0.05 yp(6) 0.95 0.14];
checkbox1H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos1 ,'String','Spine Area', 'Value',1,'BackgroundColor',[1 1 1]);
checkbox2H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos2 ,'String','Spine Total Length', 'Value',1,'BackgroundColor',[1 1 1]);
checkbox3H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos3 ,'String','Spine Head Diameter', 'Value',1,'BackgroundColor',[1 1 1]);
checkbox4H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos4 ,'String','Spine Neck Length', 'Value',1,'BackgroundColor',[1 1 1]);
checkbox5H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos5 ,'String','Dendritic Shaft Diameter', 'Value',1,'BackgroundColor',[1 1 1]);
checkbox6H = uicontrol('Parent', measureButtonsH,'Style','checkbox','Units','normalized',...
'Position', bpos6 ,'String','Nearest Neighbor Spine', 'Value',1,'BackgroundColor',[1 1 1]);
savefileh = uicontrol('Parent', IPpanelH, 'Units', 'normalized', ...
'Position', [0.05 0.02 0.65 0.10], 'String', 'Save Data', 'FontSize', 11,...
'Callback', @saveFile);
loadIMGh = uicontrol('Parent', IPpanelH, 'Units', 'normalized', ...
'Position', [0.70 0.02 0.25 0.10], 'String', 'Import Image', 'FontSize', 11,...
'Callback', @loadIMG);
% %----------------------------------------------------
% % MEMO CONSOLE GUI WINDOW
% %----------------------------------------------------
%
% memopanelH = uipanel('Parent', mainguih,'Title','Memo Log ','FontSize',10,...
% 'BackgroundColor',[.95 .95 .95],...
% 'Position', [0.62 0.30 0.30 0.29]); % 'Visible', 'Off',
%
%
% memos = {' Welcome to Neuromorph', ' ',...
% ' Press MEASURE ROI to start', ' ', ...
% ' ', ' ', ...
% ' ', ' ', ...
% ' ', ' '};
%
% memoboxH = uicontrol('Parent',memopanelH,'Style','listbox','Units','normalized',...
% 'Max',10,'Min',0,'Value',[],'FontSize', 13,'FontName', 'FixedWidth',...
% 'String',memos,'FontWeight', 'bold',...
% 'Position',[.05 .05 .90 .90]);
%----------------------------------------------------
% MEMO CONSOLE GUI WINDOW
%----------------------------------------------------
memopanelH = uipanel('Parent', mainguih,'Title','Memo Log ','FontSize',10,...
'BackgroundColor',[1 1 1],...
'Position', [0.62 0.30 0.37 0.29]); % 'Visible', 'Off',
memes = {' ',' ',' ', ' ',' ',' ',' ', ...
'Welcome to the Neuromorph', 'Ready to Import Image!'};
conboxH = uicontrol('Parent',memopanelH,'Style','listbox','Units','normalized',...
'Max',9,'Min',0,'Value',9,'FontSize', 13,'FontName', 'FixedWidth',...
'String',memes,'FontWeight', 'bold',...
'Position',[.0 .0 1 1]);
memocon('Click the Import Image button above.')
%%
%----------------------------------------------------
% IMPORT IMAGE & LOAD DEFAULT TOOLBOX PARAMETERS
%----------------------------------------------------
% loadfile()
set(mainguih, 'Visible', 'On');
axes(haxCCD)
% -----------------------------------------------------------------------------
%% GUI TOOLBOX FUNCTIONS
% -----------------------------------------------------------------------------
%----------------------------------------------------
% QUANTIFY SPINE ROI
%----------------------------------------------------
function getROI(boxidselecth, eventdata)
ROInum = str2num(ROIIDh.String);
if checkbox1H.Value
MORPHOa(ROInum)
end
if checkbox2H.Value
MORPHOb(ROInum)
end
if checkbox3H.Value
MORPHOc(ROInum)
end
if checkbox4H.Value
MORPHOd(ROInum)
end
if checkbox5H.Value
MORPHOe(ROInum)
end
if checkbox6H.Value
MORPHOf(ROInum)
end
spf1 = sprintf(['\n TOTAL SPINE INTENSITY: % 5.3f '...
'\n TOTAL SPINE AREA: % 5.1f '...
'\n SPINE HEAD WIDTH: % 5.1f '...
'\n SPINE NECK LENGTH: % 5.1f '...
'\n NEAREST SPINE DIST: % 5.1f '...
'\n DENDRITE DIAMETER: % 5.1f '...
'\n DENDRITE INTENSITY: % 5.3f \n\n'],...
SPINE.intensity,SPINE.area,...
SPINEHN.headwidth,SPINEHN.necklength,...
DENDRITE.nearestspine,...
DENDRITE.size, DENDRITE.intensity);
disp(spf1)
% ------
memos(1:end-1) = memos(2:end);
memos{3} = ['TOTAL SPINE INTENSITY: ' num2str(SPINE.intensity)];
memos{4} = ['TOTAL SPINE AREA: ' num2str(SPINE.area)];
memos{5} = ['SPINE HEAD WIDTH: ' num2str(SPINEHN.headwidth)];
memos{6} = ['SPINE NECK LENGTH: ' num2str(SPINEHN.necklength)];
memos{7} = ['DENDRITE DIAMETER: ' num2str(DENDRITE.size)];
memos{8} = ['DENDRITE INTENSITY: ' num2str(DENDRITE.intensity)];
memos{9} = ['NEAREST SPINE DIST: ' num2str(DENDRITE.nearestspine)];
memos{end} = ' ';
memoboxH.String = memos;
pause(.02)
% ------
% ---------------------------------------
% SAVE MORPHOLOGY STATISTICS FOR THIS SPINE:DENDRITE PAIR
% ---------------------------------------
% ROISAVES : saved inside individual MORPHO() functions
MORPHdata{ROInum} = {SPINE, SPINEHN, DENDRITE};
% ---------------------------------------
% QUESTION DIALOGUE TO KEEP DRAWING OR END
% ---------------------------------------
doagainROI = questdlg('Select next ROI?', 'Select next ROI?', 'Yes', 'No', 'No');
switch doagainROI
case 'Yes'
set(ROIIDh,'String',num2str((str2num(ROIIDh.String)+1)) );
getROI
case 'No'
set(ROIIDh,'String',num2str((str2num(ROIIDh.String)+1)) );
% keyboard
end
set(gcf,'Pointer','arrow')
end
%----------------------------------------------------
% QUANTIFY Spine Total Area
%----------------------------------------------------
function MORPHOa(ROInum)
% % ------
% disp('Draw outline around entire spine')
% memos(1:end-1) = memos(2:end);
% memos{end} = 'Draw outline around entire spine';
% memoboxH.String = memos;
% pause(.02)
% % ------
memocon('Draw outline around entire spine.')
hROI = imfreehand(haxCCD);
ROImask = hROI.createMask(phCCD);
ROIpos = hROI.getPosition;
ROIarea = polyarea(ROIpos(:,1),ROIpos(:,2));
ROI_INTENSITY = IMG .* ROImask;
ROI_INTENSITY_MEAN = mean(ROI_INTENSITY(ROI_INTENSITY > 0));
SPINE.area = ROIarea;
SPINE.intensity = ROI_INTENSITY_MEAN;
fprintf('\n TOTAL SPINE INTENSITY: % 5.5g \n TOTAL SPINE AREA: % 5.5g \n\n',...
ROI_INTENSITY_MEAN,ROIarea)
ROISAVES(ROInum).SpineMask = ROImask;
ROISAVES(ROInum).SpinePos = ROIpos;
end
%----------------------------------------------------
% QUANTIFY Spine Total Length
%----------------------------------------------------
function MORPHOb(ROInum)
% % ------
% disp('Draw line from dendritic shaft to spine tip (longest extent of spine)')
% memos(1:end-1) = memos(2:end);
% memos{end} = 'Draw line from spine head tip to dendrite';
% memoboxH.String = memos;
% pause(.02)
% % ------
memocon('Draw line from spine tip to dendrite shaft.')
hline = imline(haxCCD);
dpos = hline.getPosition();
spineextent = sqrt((dpos(1,1)-dpos(2,1))^2 + (dpos(1,2)-dpos(2,2))^2);
spineextentcenter = [mean(dpos(:,1)) mean(dpos(:,2))];
scatter(spineextentcenter(1),spineextentcenter(2), cdotsz,...
'MarkerFaceColor', 'none', 'MarkerEdgeColor', [1 0 0], 'LineWidth', 3)
[cx,cy,c] = improfile(IMG, dpos(:,1), dpos(:,2), round(spineextent));
% sqrt((cx(1)-cx(end))^2 + (cy(1)-cy(end))^2)
scatter(cx,cy, dotsz,'MarkerFaceColor', [1 0 0])
SPINEHN.spineextent = spineextent;
SPINEHN.spineextentintensity = mean(c);
SPINEHN.spineextentintensityprofile = c;
SPINEHN.spineextentcenter = spineextentcenter;
ROISAVES(ROInum).SpineExtentPos = dpos;
ROISAVES(ROInum).SpineExtentCenter = spineextentcenter;
ROISAVES(ROInum).SpineExtentX = cx;
ROISAVES(ROInum).SpineExtentY = cy;
% ------ Plot F Profile ----
plot(haxPRE, c)
axes(haxCCD)
% --------------------------
end
%----------------------------------------------------
% QUANTIFY Spine Head Diameter
%----------------------------------------------------
function MORPHOc(ROInum)
memocon('Draw line across spine head width.')
hline = imline(haxCCD);
dpos = hline.getPosition();
spineheadwidth = sqrt((dpos(1,1)-dpos(2,1))^2 + (dpos(1,2)-dpos(2,2))^2);
spineheadcenter = [mean(dpos(:,1)) mean(dpos(:,2))];
scatter(spineheadcenter(1),spineheadcenter(2), cdotsz,...
'MarkerFaceColor', 'none', 'MarkerEdgeColor', [1 0 1], 'LineWidth', 3)
[cx,cy,c] = improfile(IMG, dpos(:,1), dpos(:,2), round(spineheadwidth));
% sqrt((cx(1)-cx(end))^2 + (cy(1)-cy(end))^2)
scatter(cx,cy, dotsz,'MarkerFaceColor', [1 0 1])
SPINEHN.headwidth = spineheadwidth;
SPINEHN.headintensity = mean(c);
SPINEHN.headintensityprofile = c;
SPINEHN.headcenter = spineheadcenter;
ROISAVES(ROInum).SpineHeadPos = dpos;
ROISAVES(ROInum).SpineHeadCenter = spineheadcenter;
ROISAVES(ROInum).SpineHeadX = cx;
ROISAVES(ROInum).SpineHeadY = cy;
% ------ Plot F Profile ----
plot(haxPRE, c)
axes(haxCCD)
% --------------------------
end
%----------------------------------------------------
% QUANTIFY Spine Neck Length
%----------------------------------------------------
function MORPHOd(ROInum)
memocon('Draw line across spine neck width.')
hline = imline(haxCCD);
dpos = hline.getPosition();
spinenecklength = sqrt((dpos(1,1)-dpos(2,1))^2 + (dpos(1,2)-dpos(2,2))^2);
spineneckcenter = [mean(dpos(:,1)) mean(dpos(:,2))];
scatter(spineneckcenter(1),spineneckcenter(2), cdotsz,...
'MarkerFaceColor', 'none', 'MarkerEdgeColor', [0 1 0], 'LineWidth', 3)
[cx,cy,c] = improfile(IMG, dpos(:,1), dpos(:,2), round(spinenecklength));
% sqrt((cx(1)-cx(end))^2 + (cy(1)-cy(end))^2)
scatter(cx,cy, dotsz,'MarkerFaceColor', [0 1 0])
SPINEHN.necklength = spinenecklength;
SPINEHN.neckintensity = mean(c);
SPINEHN.neckintensityprofile = c;
SPINEHN.neckcenter = spineneckcenter;
ROISAVES(ROInum).SpineNeckPos = dpos;
ROISAVES(ROInum).SpineNeckCenter = spineneckcenter;
ROISAVES(ROInum).SpineNeckX = cx;
ROISAVES(ROInum).SpineNeckY = cy;
% ------ Plot F Profile ----
plot(haxPRE, c)
axes(haxCCD)
% --------------------------
end
%----------------------------------------------------
% QUANTIFY Dendritic Shaft Diameter
%----------------------------------------------------
function MORPHOe(ROInum)
memocon('Draw line to measure dendrite width near spine')
hline = imline(haxCCD);
dpos = hline.getPosition();
% row 1 of dpos is the x,y pos of the line origin
% test this using scatter(dpos(1,1),dpos(1,2),'r')
dendritesize = sqrt((dpos(1,1)-dpos(2,1))^2 + (dpos(1,2)-dpos(2,2))^2);
dendritecenter = [mean(dpos(:,1)) mean(dpos(:,2))];
scatter(dendritecenter(1),dendritecenter(2), cdotsz,...
'MarkerFaceColor', 'none', 'MarkerEdgeColor', [0 0 1], 'LineWidth', 3)
[cx,cy,c] = improfile(IMG, dpos(:,1), dpos(:,2), round(dendritesize));
% sqrt((cx(1)-cx(end))^2 + (cy(1)-cy(end))^2)
scatter(cx,cy, dotsz,'MarkerFaceColor', [0 0 1])
DENDRITE.size = dendritesize;
DENDRITE.intensity = mean(c);
DENDRITE.intensityprofile = c;
DENDRITE.center = dendritecenter;
ROISAVES(ROInum).DendritePos = dpos;
ROISAVES(ROInum).DendriteCenter = dendritecenter;
ROISAVES(ROInum).DendriteX = cx;
ROISAVES(ROInum).DendriteY = cy;
% ------ Plot F Profile ----
plot(haxPRE, c)
axes(haxCCD)
% --------------------------
end
%----------------------------------------------------
% QUANTIFY Nearest Neighbor Spine
%----------------------------------------------------
function MORPHOf(ROInum)
memocon('Draw line from this spine to nearest spine.')
hline = imline(haxCCD);
dpos = hline.getPosition();
nearestspine = sqrt((dpos(1,1)-dpos(2,1))^2 + (dpos(1,2)-dpos(2,2))^2);
nearestspinecenter = [mean(dpos(:,1)) mean(dpos(:,2))];
scatter(nearestspinecenter(1),nearestspinecenter(2), cdotsz,...
'MarkerFaceColor', 'none', 'MarkerEdgeColor', [0 1 0], 'LineWidth', 3)
[cx,cy,c] = improfile(IMG, dpos(:,1), dpos(:,2), round(nearestspine));
% sqrt((cx(1)-cx(end))^2 + (cy(1)-cy(end))^2)
scatter(cx,cy, dotsz,'MarkerFaceColor', [0 1 0])
DENDRITE.nearestspine = nearestspine;
DENDRITE.nearestspineint = mean(c);
DENDRITE.nearestspineprofile = c;
DENDRITE.nearestspinecenter = nearestspinecenter;
ROISAVES(ROInum).SpineNearPos = dpos;
ROISAVES(ROInum).SpineNearCenter = nearestspinecenter;
ROISAVES(ROInum).SpineNearX = cx;
ROISAVES(ROInum).SpineNearY = cy;
% ------ Plot F Profile ----
plot(haxPRE, c)
axes(haxCCD)
% --------------------------
end
%----------------------------------------------------
% KEYBOARD CALLBACKS (ZOOM + PAN)
%----------------------------------------------------
function keypresszoom(hObject, eventData, key)
% --- ZOOM ---
if strcmp(mainguih.CurrentCharacter,'=')
% IN THE FUTURE USE MOUSE LOCATION TO ZOOM
% INTO A SPECIFIC POINT. TO QUERY MOUSE LOCATION
% USE THE METHOD: mainguih.CurrentPoint
zoom(1.5)
drawnow
end
if strcmp(mainguih.CurrentCharacter,'-')
zoom(.5)
drawnow
end
% --- PAN ---
if strcmp(mainguih.CurrentCharacter,'p')
pan('on')
% h = pan;
% h.ActionPreCallback = @myprecallback;
% h.ActionPostCallback = @mypostcallback;
% h.Enable = 'on';
end
if strcmp(mainguih.CurrentCharacter,'o')
pan('off')
end
if strcmp(mainguih.CurrentCharacter,'f')
haxCCD.XLim = haxCCD.XLim+20;
drawnow
end
if strcmp(mainguih.CurrentCharacter,'s')
haxCCD.XLim = haxCCD.XLim-20;
drawnow
end
if strcmp(mainguih.CurrentCharacter,'e')
haxCCD.YLim = haxCCD.YLim+20;
drawnow
end
if strcmp(mainguih.CurrentCharacter,'d')
haxCCD.YLim = haxCCD.YLim-20;
drawnow
end
% --- RESET ZOOM & PAN ---
if strcmp(mainguih.CurrentCharacter,'0')
zoom out
zoom reset
haxCCD.XLim = imXlim;
haxCCD.YLim = imYlim;
end
end
%----------------------------------------------------
% BOX SELECTION
%----------------------------------------------------
function boxselection(source,callbackdata)
% callbackdata.OldValue.String
boxtype = callbackdata.NewValue.String;
end
%----------------------------------------------------
% LOAD FILE
%----------------------------------------------------
function loadIMG(loadIMGh, eventData)
if numel(datafile) < 1
[datafile,datadir,~] = uigetfile('*.tif*; *.bmp');
end
cd(datadir);
imgpath = [datadir '/' datafile];
memocon('Working dir changed to: ')
memocon(datadir)
iminfo = imfinfo(imgpath);
[im, map] = imread(imgpath);
im_size = size(im);
im_nmap = numel(map);
im_ctype = iminfo.ColorType;
if strcmp(im_ctype, 'truecolor') || numel(im_size) > 2
IMG = rgb2gray(im);
IMG = im2double(IMG);
elseif strcmp(im_ctype, 'indexed')
IMG = ind2gray(im,map);
IMG = im2double(IMG);
elseif strcmp(im_ctype, 'grayscale')
IMG = im2double(im);
else
IMG = im;
end
axes(haxCCD)
colormap(haxCCD,bone); % parula
phCCD = imagesc(IMG , 'Parent', haxCCD);
pause(1)
ccmap = bone;
cmmap = [zeros(10,3); ccmap(end-40:end,:)];
colormap(haxCCD,cmmap)
mainguih.Colormap = cmmap;
pause(.2)
imXlim = haxCCD.XLim;
imYlim = haxCCD.YLim;
xdim = size(IMG,2);
ydim = size(IMG,1);
%----------------------------------------------------
% SET USER-EDITABLE GUI VALUES
%----------------------------------------------------
set(mainguih, 'Name', datafile);
set(ROIIDh, 'String', int2str(1));
set(haxCCD, 'XLim', [1 xdim]);
set(haxCCD, 'YLim', [1 ydim]);
%----------------------------------------------------
% axes(haxCCD)
memocon('Finished loading image.')
memocon('Click on the image to make it active.')
memocon('Use the =/- keys to zoom in and out')
memocon('Use s d f e keys to move left down right up')
memocon('Click MEASURE ROI to begin.')
end
%----------------------------------------------------
% SAVE DATA AND ROI COORDINATES
%----------------------------------------------------
function saveFile(savefileh, eventData)
saveDatafilename = inputdlg('Enter a filename to save data','file name',1,...
{datafile(1:end-4)});
Datafilename = char(strcat(saveDatafilename));
MORPHdata = MORPHdata(~cellfun(@isempty, MORPHdata));
%for nn = 1:size(MORPHdats,2)
for nn = 1:size(MORPHdata,2)
MORPHdat(nn,:) = [MORPHdata{1,nn}{1}.area ...
MORPHdata{1,nn}{1}.intensity ...
MORPHdata{1,nn}{2}.spineextent ...
MORPHdata{1,nn}{2}.spineextentintensity ...
MORPHdata{1,nn}{2}.headwidth ...
MORPHdata{1,nn}{2}.headintensity ...
MORPHdata{1,nn}{2}.necklength ...
MORPHdata{1,nn}{2}.neckintensity ...
MORPHdata{1,nn}{3}.size ...
MORPHdata{1,nn}{3}.intensity ...
MORPHdata{1,nn}{3}.nearestspine ...
MORPHdata{1,nn}{3}.nearestspineint ...
];
ROInames{nn} = num2str(nn);
end
MORPHtab = array2table(MORPHdat);
MORPHtab.Properties.VariableNames = {...
'SPINE_AREA' 'SPINE_F' 'SPINE_LEN' 'SPINE_LEN_F' ...
'HEAD_WIDTH' 'HEAD_F' 'NECK_LENGTH' 'NECK_F'...
'DEND_DIAMETER' 'DEND_DIAMETER_F' 'NEARBY_SPINE_DIST' 'LENGTH_SHAFT_F'...
};
MORPHtab.Properties.RowNames = ROInames;
MORPHtab.FILE = repmat(datafile,size(MORPHdata,2),1);
% MORPHtab.DATE = repmat(datadate,size(MORPHdata,2),1);
writetable(MORPHtab,[Datafilename '.csv'],'WriteRowNames',true)
save([Datafilename '.mat'],'MORPHdata','ROISAVES')
memocon('Data saved to: ')
memocon(datadir)
memocon([Datafilename '.csv'])
end
%----------------------------------------------------
% IMAGE SIDER CALLBACK
%----------------------------------------------------
function cmapslider(hObject, eventdata)
% Hints: hObject.Value returns position of slider
% hObject.Min and hObject.Max determine range of slider
% sunel = get(handles.sunelslider,'value'); % Get current light elev.
% sunaz = get(hObject,'value'); % Varies from -180 -> 0 deg
slideVal = ceil(cmapsliderH.Value);
% cmap = colormap(haxCCD);
ccmap = bone; % parula
% cmmap = [zeros(slideVal,3); ccmap(end-40:end,:)];
cmmap = [zeros(slideVal,3); ccmap(slideVal:end,:)];
colormap(haxCCD,cmmap)
pause(.05)
end
%----------------------------------------------------
% LOAD ROI DATA
%----------------------------------------------------
function loadROI(hObject, eventdata)
% ------
disp('Select .mat file with ROI data')
memos(1:end-1) = memos(2:end);
memos{end} = 'Select .mat file with ROI data';
memoboxH.String = memos;
pause(.02)
% ------
[ROIFileName,ROIPathName,ROIFilterIndex] = uigetfile('*.mat');
ROIloaded = load([ROIPathName ROIFileName],'MORPHdata','ROISAVES');
MORPHdata = ROIloaded.MORPHdata;
ROISAVES = ROIloaded.ROISAVES;
% ------
disp('ROI data loaded into workspace!')
memos(1:end-1) = memos(2:end);
memos{end} = 'ROI data loaded into workspace!';
memoboxH.String = memos;
pause(.02)
% ------
lwd = 4;
axes(haxCCD)
for nn = 1:length(ROISAVES)
line(ROISAVES(nn).SpinePos(:,1), ROISAVES(nn).SpinePos(:,2),'Color',[.95 .95 .10],'LineWidth',lwd)
line(ROISAVES(nn).SpineExtentPos(:,1), ROISAVES(nn).SpineExtentPos(:,2),'Color',[.10 .95 .95],'LineWidth',lwd)
line(ROISAVES(nn).SpineHeadPos(:,1), ROISAVES(nn).SpineHeadPos(:,2),'Color',[.95 .10 .95],'LineWidth',lwd)
line(ROISAVES(nn).SpineNeckPos(:,1), ROISAVES(nn).SpineNeckPos(:,2),'Color',[.95 .10 .10],'LineWidth',lwd)
line(ROISAVES(nn).DendritePos(:,1), ROISAVES(nn).DendritePos(:,2),'Color',[.10 .95 .10],'LineWidth',lwd)
line(ROISAVES(nn).SpineNearPos(:,1), ROISAVES(nn).SpineNearPos(:,2),'Color',[.10 .10 .95],'LineWidth',lwd)
end
% ROISAVES.SpinePos
% ROISAVES.SpineExtentPos
% ROISAVES.SpineHeadPos
% ROISAVES.SpineNeckPos
% ROISAVES.DendritePos
% ROISAVES.SpineNearPos
end
%----------------------------------------------------
% MEMO LOG UPDATE
%----------------------------------------------------
function memocon(spf,varargin)
if iscellstr(spf)
spf = [spf{:}];
end
if iscell(spf)
return
keyboard
spf = [spf{:}];
end
if ~ischar(spf)
return
keyboard
spf = [spf{:}];
end
memes(1:end-1) = memes(2:end);
memes{end} = spf;
conboxH.String = memes;
pause(.02)
if nargin == 3
vrs = deal(varargin);
memi = memes;
memes(1:end) = {' '};
memes{end-1} = vrs{1};
memes{end} = spf;
conboxH.String = memes;
conboxH.FontAngle = 'italic';
conboxH.ForegroundColor = [.9 .4 .01];
pause(vrs{2})
conboxH.FontAngle = 'normal';
conboxH.ForegroundColor = [0 0 0];
conboxH.String = memi;
pause(.02)
elseif nargin == 2
vrs = deal(varargin);
pause(vrs{1})
end
disp(spf)
end
end
%% EOF
|
github
|
shenweichen/Coursera-master
|
RunInference.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/RunInference.m
| 1,769 |
utf_8
|
1ba1656e4edc7d51078478fedd09878a
|
function pred = RunInference (factors)
% This function performs inference for a Markov network specified as a list
% of factors.
%
% Input:
% factors: An array of struct factors, each containing 'var', 'card', and
% 'val' fields.
%
% Output:
% pred: An array of predictions for every variable. In particular,
% pred(i) is the predicted value for variable numbered i (as determined
% by the 'var' fields in the input factors).
%
% Copyright (C) Daphne Koller, Stanford University, 2012
binaries = {'.\inference\doinference.exe', ...
'./inference/doinference-mac', ...
'./inference/doinference-linux'};
kFactorsFilename = 'factors.fg';
kStderrFilename = 'inf.log';
kInfBinary = binaries{[ispc ismac isunix]}; % NB: need ismac first so that if ismac and isunix are both 1, then mac is chosen
kInferenceType = 'map'; % choices are 'map' or 'pd'
factorsString = SerializeFactorsFg (factors);
fd = fopen(kFactorsFilename, 'wt');
fprintf (fd, '%s', factorsString);
fclose(fd);
if (isunix && ~ismac)
command = [kInfBinary ' ' kFactorsFilename ' ' kInferenceType];
else
command = [kInfBinary ' ' kFactorsFilename ' ' kInferenceType ' 2> ' kStderrFilename];
end
[retVal, output] = system(command);
if (retVal ~= 0)
error('The doinference command failed. Look at the file %s to diagnose the cause', kStderrFilename);
end
pred = ParseOutput(output);
end
function pred = ParseOutput(output)
lines = strread(output, '%s', 'delimiter', sprintf('\n'));
lines(strcmp(lines, '')) = [];
numVars = str2double(lines{1});
if (numVars ~= length(lines) - 1)
error('Error parsing output: %s', output);
end
pred = zeros(numVars, 1);
for i = 2:(numVars + 1)
line = str2num(lines{i}); %#ok
pred(i-1) = line(end);
end
end
|
github
|
shenweichen/Coursera-master
|
IndexToAssignment.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/IndexToAssignment.m
| 568 |
utf_8
|
506de63bacc99887816fc7288aaa4301
|
% IndexToAssignment Convert index to variable assignment.
%
% A = IndexToAssignment(I, D) converts an index, I, into the .val vector
% into an assignment over variables with cardinality D. If I is a vector,
% then the function produces a matrix of assignments, one assignment
% per row.
%
% See also AssignmentToIndex.m
%
% Copyright (C) Daphne Koller, Stanford University, 2012
function A = IndexToAssignment(I, D)
D = D(:)'; % ensure that D is a row vector
A = bsxfun(@mod, floor(bsxfun(@rdivide, I(:) - 1, cumprod([1, D(1:end - 1)]))), D) + 1;
end
|
github
|
shenweichen/Coursera-master
|
submit.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/submit.m
| 4,874 |
utf_8
|
b28bc742c0663bbf562786d44919f474
|
function submit(part)
addpath('./lib');
conf.assignmentKey = '1RFc-gNfEeapUhL5oS3IIQ';
conf.itemName = 'Markov Networks for OCR';
conf.partArrays = { ...
{ ...
'Ga9CX', ...
{ 'ComputeSingletonFactors.m' }, ...
'', ...
}, ...
{ ...
'Y6ud3', ...
{ 'ComputeSingletonFactors.m' }, ...
'', ...
}, ...
{ ...
'YX6FP', ...
{ 'ComputePairwiseFactors.m' }, ...
'', ...
}, ...
{ ...
'sVpuc', ...
{ 'ComputePairwiseFactors.m' }, ...
'', ...
}, ...
{ ...
'ZzAEz', ...
{ 'ComputeTripletFactors.m' }, ...
'', ...
}, ...
{ ...
'jF5vU', ...
{ 'ComputeTripletFactors.m' }, ...
'', ...
}, ...
{ ...
'IQZRx', ...
{ 'ComputeSimilarityFactor.m' }, ...
'', ...
}, ...
{ ...
'bWL2q', ...
{ 'ComputeSimilarityFactor.m' }, ...
'', ...
}, ...
{ ...
'TfTAH', ...
{ 'ComputeAllSimilarityFactors.m' }, ...
'', ...
}, ...
{ ...
'44rjP', ...
{ 'ComputeAllSimilarityFactors.m' }, ...
'', ...
}, ...
{ ...
'eGTyV', ...
{ 'ChooseTopSimilarityFactors.m' }, ...
'', ...
}, ...
{ ...
'VfH4h', ...
{ 'ChooseTopSimilarityFactors.m' }, ...
'', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
% specifies which parts are test parts
function result = isTest(partIdx)
if (mod(partIdx, 2) == 0)
result = true;
else
result = false;
end
end
function out = output(partIdx, auxstring)
load PA3Models.mat;
if (isTest(partIdx))
load PA3TestCases.mat;
else
load PA3SampleCases.mat;
end
if partIdx == 1
images = Part1SampleImagesInput;
factors = ComputeSingletonFactors(images, imageModel);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 2
images = Part1TestImagesInput;
factors = ComputeSingletonFactors(images, imageModel);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 3
images = Part2SampleImagesInput;
factors = ComputePairwiseFactors(images, pairwiseModel, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 4
images = Part2TestImagesInput;
factors = ComputePairwiseFactors(images, pairwiseModel, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 5
images = Part3SampleImagesInput;
factors = ComputeTripletFactors(images, tripletList, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors, 2);
elseif partIdx == 6
images = Part3TestImagesInput;
factors = ComputeTripletFactors(images, tripletList, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors, 2);
elseif partIdx == 7
images = Part4SampleImagesInput;
factor = ComputeSimilarityFactor(images, imageModel.K, 1, 2);
factor = SortAllFactors(factor);
out = SerializeFactorsFgGrading(factor);
elseif partIdx == 8
images = Part4TestImagesInput;
factor = ComputeSimilarityFactor(images, imageModel.K, 3, 4);
factor = SortAllFactors(factor);
out = SerializeFactorsFgGrading(factor);
elseif partIdx == 9
images = Part5SampleImagesInput;
factors = ComputeAllSimilarityFactors(images, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 10
images = Part5TestImagesInput;
factors = ComputeAllSimilarityFactors(images, imageModel.K);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 11
allFactors = Part6SampleFactorsInput;
factors = ChooseTopSimilarityFactors(allFactors, 2);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
elseif partIdx == 12
allFactors = Part6TestFactorsInput;
factors = ChooseTopSimilarityFactors(allFactors, 2);
factors = SortAllFactors(factors);
out = SerializeFactorsFgGrading(factors);
end
end
function f = SortAllFactors(factors)
for i = 1:length(factors)
factors(i) = SortFactorVars(factors(i));
end
varMat = vertcat(factors(:).var);
[unused, order] = sortrows(varMat);
f = factors(order);
end
function G = SortFactorVars(F)
[sortedVars, order] = sort(F.var);
G.var = sortedVars;
G.card = F.card(order);
G.val = zeros(numel(F.val), 1);
assignmentsInF = IndexToAssignment(1:numel(F.val), F.card);
assignmentsInG = assignmentsInF(:,order);
G.val(AssignmentToIndex(assignmentsInG, G.card)) = F.val;
end
function str = SerializeWordList (words)
str = [];
for i = 1:length(words)
str = [str num2str(words{i}(:)') ' ']; %#ok
end
end
|
github
|
shenweichen/Coursera-master
|
GetValueOfAssignment.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/GetValueOfAssignment.m
| 809 |
utf_8
|
272b9bca5fe98bd4c793e9b6d3bc0c2f
|
%GETVALUEOFASSIGNMENT Gets the value of a variable assignment in a factor.
%
% v = GETVALUEOFASSIGNMENT(F, A) returns the value of a variable assignment,
% A, in factor F. The order of the variables in A are assumed to be the
% same as the order in F.var.
%
% v = GETVALUEOFASSIGNMENT(F, A, VO) gets the value of a variable assignment,
% A, in factor F. The order of the variables in A are given by the vector VO.
%
% See also SETVALUEOFASSIGNMENT
% Copyright (C) Daphne Koller, Stanford University, 2012
function v = GetValueOfAssignment(F, A, VO)
if (nargin == 2),
indx = AssignmentToIndex(A, F.card);
else
map = zeros(length(F.var), 1);
for i = 1:length(F.var),
map(i) = find(VO == F.var(i));
end;
indx = AssignmentToIndex(A(map), F.card);
end;
v = F.val(indx);
|
github
|
shenweichen/Coursera-master
|
AssignmentToIndex.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/AssignmentToIndex.m
| 631 |
utf_8
|
ee3dd64cb42f51f10372074314d48e76
|
% AssignmentToIndex Convert assignment to index.
%
% I = AssignmentToIndex(A, D) converts an assignment, A, over variables
% with cardinality D to an index into the .val vector for a factor.
% If A is a matrix then the function converts each row of A to an index.
%
% See also IndexToAssignment.m and SampleFactors.m
%
% Copyright (C) Daphne Koller, Stanford University, 2012
function I = AssignmentToIndex(A, D)
D = D(:)'; % ensure that D is a row vector
if (any(size(A) == 1)),
I = cumprod([1, D(1:end - 1)]) * (A(:) - 1) + 1;
else
I = sum(bsxfun(@times, A - 1, cumprod([1, D(1:end - 1)])), 2) + 1;
end;
end
|
github
|
shenweichen/Coursera-master
|
SetValueOfAssignment.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/SetValueOfAssignment.m
| 829 |
utf_8
|
1cdbc6dd85db30405ae79f168a884b23
|
%SETVALUEOFASSIGNMENT Sets the value of a variable assignment in a factor.
%
% F = SETVALUEOFASSIGNMENT(F, A, v) sets the value of a variable assignment,
% A, in factor F to v. The order of the variables in A are assumed to be the
% same as the order in F.var.
%
% F = SETVALUEOFASSIGNMENT(F, A, v, VO) sets the value of a variable
% assignment, A, in factor F to v. The order of the variables in A are given
% by the vector VO.
%
% See also GETVALUEOFASSIGNMENT
% Copyright (C) Daphne Koller, Stanford University, 2012
function F = SetValueOfAssignment(F, A, v, VO)
if (nargin == 3),
indx = AssignmentToIndex(A, F.card);
else
map = zeros(length(F.var), 1);
for i = 1:length(F.var),
map(i) = find(VO == F.var(i));
end;
indx = AssignmentToIndex(A(map), F.card);
end;
F.val(indx) = v;
|
github
|
shenweichen/Coursera-master
|
submitWithConfiguration.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/lib/submitWithConfiguration.m
| 3,010 |
utf_8
|
81b617620421b9891908dc9e7fbf6cda
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
fprintf('Submission successful. You can view your grade under My Submission on the programming assignment page.\n\n');
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentKey = conf.assignmentKey;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
partIdx = 0;
for part = parts
partId = part{:}.id;
partIdx = partIdx + 1;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partIdx);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www.coursera.org/api/onDemandProgrammingScriptSubmissionsController.v1';
end
|
github
|
shenweichen/Coursera-master
|
savejson.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
shenweichen/Coursera-master
|
loadjson.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/lib/jsonlab/loadjson.m
| 18,888 |
ibm852
|
f5b550952f123aa7ebbb4cc1e4e1a2ca
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
% str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
str=sprintf('x0x%X_%s',toascii(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
% str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',toascii(str0(pos(i))))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
shenweichen/Coursera-master
|
loadubjson.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
shenweichen/Coursera-master
|
saveubjson.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW3_Markov Networks for OCR/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
shenweichen/Coursera-master
|
IndexToAssignment.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW1_Simple BN Knowledge Engineering/IndexToAssignment.m
| 583 |
utf_8
|
344ed305e4ca7bcf86898725befe1413
|
% IndexToAssignment Convert index to variable assignment.
%
% A = IndexToAssignment(I, D) converts an index, I, into the .val vector
% into an assignment over variables with cardinality D. If I is a vector,
% then the function produces a matrix of assignments, one assignment
% per row.
%
% See also AssignmentToIndex.m and FactorTutorial.m
function A = IndexToAssignment(I, D)
D = D(:)'; % ensure that D is a row vector
A = mod(floor(repmat(I(:) - 1, 1, length(D)) ./ repmat(cumprod([1, D(1:end - 1)]), length(I), 1)), ...
repmat(D, length(I), 1)) + 1;
end
|
github
|
shenweichen/Coursera-master
|
FactorMarginalization.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW1_Simple BN Knowledge Engineering/FactorMarginalization.m
| 1,605 |
utf_8
|
d4123eb1bd128d3be2ea9483ed159e1c
|
% FactorMarginalization Sums given variables out of a factor.
% B = FactorMarginalization(A,V) computes the factor with the variables
% in V summed out. The factor data structure has the following fields:
% .var Vector of variables in the factor, e.g. [1 2 3]
% .card Vector of cardinalities corresponding to .var, e.g. [2 2 2]
% .val Value table of size prod(.card)
%
% The resultant factor should have at least one variable remaining or this
% function will throw an error.
%
% See also FactorProduct.m, IndexToAssignment.m, and AssignmentToIndex.m
function B = FactorMarginalization(A, V)
% Check for empty factor or variable list
if (isempty(A.var) || isempty(V)), B = A; return; end;
% Construct the output factor over A.var \ V (the variables in A.var that are not in V)
% and mapping between variables in A and B
[B.var, mapB] = setdiff(A.var, V);
% Check for empty resultant factor
if isempty(B.var)
error('Error: Resultant factor has empty scope');
end;
% Initialize B.card and B.val
B.card = A.card(mapB);
B.val = zeros(1, prod(B.card));
% Compute some helper indices
% These will be very useful for calculating B.val
% so make sure you understand what these lines are doing
assignments = IndexToAssignment(1:length(A.val), A.card);
indxB = AssignmentToIndex(assignments(:, mapB), B.card);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% YOUR CODE HERE
% Correctly populate the factor values of B
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = 1:length(B.val),
B.val(i) = sum(A.val(indxB==i))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
|
github
|
shenweichen/Coursera-master
|
FactorProduct.m
|
.m
|
Coursera-master/Specialization_Probabilistic_Graphical_Models_Stanford_University/Course1_Probabilistic_Graphical_Models_1_Representation/HW1_Simple BN Knowledge Engineering/FactorProduct.m
| 2,298 |
utf_8
|
1e54a5848d80539d565c6a008e64f656
|
% FactorProduct Computes the product of two factors.
% C = FactorProduct(A,B) computes the product between two factors, A and B,
% where each factor is defined over a set of variables with given dimension.
% The factor data structure has the following fields:
% .var Vector of variables in the factor, e.g. [1 2 3]
% .card Vector of cardinalities corresponding to .var, e.g. [2 2 2]
% .val Value table of size prod(.card)
%
% See also FactorMarginalization.m, IndexToAssignment.m, and
% AssignmentToIndex.m
function C = FactorProduct(A, B)
% Check for empty factors
if (isempty(A.var)), C = B; return; end;
if (isempty(B.var)), C = A; return; end;
% Check that variables in both A and B have the same cardinality
[dummy iA iB] = intersect(A.var, B.var);
if ~isempty(dummy)
% A and B have at least 1 variable in common
assert(all(A.card(iA) == B.card(iB)), 'Dimensionality mismatch in factors');
end
% Set the variables of C
C.var = union(A.var, B.var);
% Construct the mapping between variables in A and B and variables in C.
% In the code below, we have that
%
% mapA(i) = j, if and only if, A.var(i) == C.var(j)
%
% and similarly
%
% mapB(i) = j, if and only if, B.var(i) == C.var(j)
%
% For example, if A.var = [3 1 4], B.var = [4 5], and C.var = [1 3 4 5],
% then, mapA = [2 1 3] and mapB = [3 4]; mapA(1) = 2 because A.var(1) = 3
% and C.var(2) = 3, so A.var(1) == C.var(2).
[dummy, mapA] = ismember(A.var, C.var);
[dummy, mapB] = ismember(B.var, C.var);
% Set the cardinality of variables in C
C.card = zeros(1, length(C.var));
C.card(mapA) = A.card;
C.card(mapB) = B.card;
% Initialize the factor values of C:
% prod(C.card) is the number of entries in C
C.val = zeros(1, prod(C.card));
% Compute some helper indices
% These will be very useful for calculating C.val
% so make sure you understand what these lines are doing.
assignments = IndexToAssignment(1:prod(C.card), C.card);
indxA = AssignmentToIndex(assignments(:, mapA), A.card);
indxB = AssignmentToIndex(assignments(:, mapB), B.card);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% YOUR CODE HERE:
% Correctly populate the factor values of C
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C.val = A.val(indxA) .* B.val(indxB)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.