code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/********************************************************************
*
* fast_median_cimp.cpp
*
* The C++ mex implementation for fast_median.m
*
* Created by Dahua Lin, on Nov 11, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <bcslib/array/array2d.h>
#include <algorithm>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
inline T my_median_inplace(index_t n, T *x)
{
if (n == 1)
{
return *x;
}
else if (n == 2)
{
T x0 = x[0];
T x1 = x[1];
return x0 + (x1 - x0) / 2;
}
else if (n % 2 == 0) // even
{
T *pm = x + (n/2);
std::nth_element(x, pm, x+n);
T v1 = *pm;
T v0 = *(std::max_element(x, pm));
return v0 + (v1 - v0) / 2;
}
else // odd
{
T *pm = x + (n/2);
std::nth_element(x, pm, x+n);
return *pm;
}
}
template<typename T>
inline marray do_median(const_marray mX, int d)
{
if (d == 0) // for vec
{
index_t n = (index_t)mX.nelems();
array1d<T> temp(n, mX.data<T>());
T v = my_median_inplace(n, temp.pbase());
return create_mscalar<T>(v);
}
else // for mat
{
index_t m = (index_t)mX.nrows();
index_t n = (index_t)mX.ncolumns();
array2d<T> temp(m, n, mX.data<T>());
marray mR = create_marray<T>(1, (size_t)n);
aview1d<T> r = view1d<T>(mR);
for (index_t i = 0; i < n; ++i)
{
r(i) = my_median_inplace(m, &(temp(0, i)));
}
return mR;
}
}
/**
* main entry:
* [0] X: the input matrix
* [1] d: d == 0: solve median of a vector
* d == 1: solve median(s) of each column
*
* output entry:
* [0] r: the median values
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const_marray mX(prhs[0]);
const_marray mDim(prhs[1]);
int d = (int)mDim.get_scalar<double>();
if (mX.is_double())
{
plhs[0] = do_median<double>(mX, d).mx_ptr();
}
else if (mX.is_single())
{
plhs[0] = do_median<float>(mX, d).mx_ptr();
}
}
| zzhangumd-smitoolbox | base/data/private/fast_median_cimp.cpp | C++ | mit | 2,308 |
/********************************************************************
*
* aggreg_percol_cimp.cpp
*
* The C++ mex implementation of aggreg.m
*
* Created by Dahua Lin, on Feb 26, 2012
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <limits>
using namespace bcs;
using namespace bcs::matlab;
const int SUM_CODE = 1;
const int MIN_CODE = 2;
const int MAX_CODE = 3;
// aggregators
template<typename T>
struct sum_ag
{
typedef T result_type;
result_type init() const
{
return T(0);
}
void operator() (result_type& r, const T& x) const
{
r += x;
}
};
template<>
struct sum_ag<bool>
{
typedef double result_type;
result_type init() const
{
return false;
}
void operator() (result_type& r, const bool& x) const
{
r += (double)x;
}
};
template<typename T>
struct min_ag
{
typedef T result_type;
result_type init() const
{
if (std::numeric_limits<T>::has_infinity)
{
return std::numeric_limits<T>::infinity();
}
else
{
return std::numeric_limits<T>::max();
}
}
void operator() (result_type& r, const T& x) const
{
if (x < r) r = x;
}
};
template<>
struct min_ag<bool>
{
typedef bool result_type;
result_type init() const
{
return true;
}
void operator() (result_type& r, const bool& x) const
{
r &= x;
}
};
template<typename T>
struct max_ag
{
typedef T result_type;
result_type init() const
{
if (std::numeric_limits<T>::has_infinity)
{
return - std::numeric_limits<T>::infinity();
}
else
{
return std::numeric_limits<T>::min();
}
}
void operator() (result_type& r, const T& x) const
{
if (x > r) r = x;
}
};
template<>
struct max_ag<bool>
{
typedef bool result_type;
result_type init() const
{
return false;
}
void operator() (result_type& r, const bool& x) const
{
r |= x;
}
};
template<typename T, class Aggregator>
marray aggreg(const_marray mX, const_marray mI, int K)
{
typedef typename Aggregator::result_type Tout;
int m = mX.nrows();
int n = mX.ncolumns();
marray mR = create_marray<Tout>(K, n);
Aggregator ag;
const T *X = mX.data<T>();
const int32_t *I = mI.data<int32_t>();
Tout *R = mR.data<Tout>();
Tout v0 = ag.init();
for (int j = 0; j < n; ++j)
{
for (int i = 0; i < K; ++i) R[i] = v0;
for (int i = 0; i < m; ++i)
{
int32_t k = I[i];
if (k >= 0 && k < K)
{
ag(R[k], X[i]);
}
}
X += m;
I += m;
R += K;
}
return mR;
}
template<typename T>
inline marray do_aggreg(const_marray mX, const_marray mI, int K, int code)
{
if (code == 1)
{
return aggreg<T, sum_ag<T> >(mX, mI, K);
}
else if (code == 2)
{
return aggreg<T, min_ag<T> >(mX, mI, K);
}
else // code == 3
{
return aggreg<T, max_ag<T> >(mX, mI, K);
}
}
/**
* main entry:
*
* Inputs:
* [0]: X: data [double|single|int32 matrix]
* [1]: K: #classes [double scalar]
* [2]: I: indices [zero-based int32]
* [3]: code: function code (1-sum, 2-min, 3-max)
*
* Outputs:
* [0]: R: the results
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const_marray mX(prhs[0]);
const_marray mK(prhs[1]);
const_marray mI(prhs[2]);
const_marray mCode(prhs[3]);
int K = (int)mK.get_scalar<double>();
int code = (int)mCode.get_scalar<double>();
// main delegate
marray mR;
if (mX.is_double())
{
mR = do_aggreg<double>(mX, mI, K, code);
}
else if (mX.is_single())
{
mR = do_aggreg<float>(mX, mI, K, code);
}
else if (mX.is_int32())
{
mR = do_aggreg<int32_t>(mX, mI, K, code);
}
else if (mX.is_logical())
{
mR = do_aggreg<bool>(mX, mI, K, code);
}
else
{
throw mexception("aggreg_percol:invalidarg",
"aggreg only supports matrices of type double, single, int32, or logical");
}
// output
plhs[0] = mR.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/aggreg_percol_cimp.cpp | C++ | mit | 4,650 |
/********************************************************************
*
* intcount_cimp.cpp
*
* The C++ mex implementation of integer counting
*
* Created by Dahua Lin, on May 26, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
inline void count_vec(int v0, int v1, const T *data, int len, double *c)
{
for (size_t i = 0; i < len; ++i)
{
int cv = (int)(data[i]);
if (cv >= v0 && cv <= v1)
{
++ c[cv - v0];
}
}
}
template<typename T>
marray count(int v0, int v1, const_marray mA, bool b)
{
int K = v1 - v0 + 1;
const T *data = !mA.is_empty() ? mA.data<T>() : NULL;
if (!b)
{
marray mC = create_marray<double>(1, K);
double *c = mC.data<double>();
count_vec(v0, v1, data, mA.nelems(), c);
return mC;
}
else
{
int m = (int)mA.nrows();
int n = (int)mA.ncolumns();
marray mC = create_marray<double>(K, n);
double *c = mC.data<double>();
for (int j = 0; j < n; ++j, c += K, data += m)
{
count_vec(v0, v1, data, m, c);
}
return mC;
}
}
inline marray do_count(int v0, int v1, const_marray mA, bool b)
{
switch (mA.class_id())
{
case mxDOUBLE_CLASS:
return count<double>(v0, v1, mA, b);
case mxSINGLE_CLASS:
return count<float>(v0, v1, mA, b);
case mxINT32_CLASS:
return count<int32_t>(v0, v1, mA, b);
case mxUINT32_CLASS:
return count<uint32_t>(v0, v1, mA, b);
case mxINT16_CLASS:
return count<int16_t>(v0, v1, mA, b);
case mxUINT16_CLASS:
return count<uint16_t>(v0, v1, mA, b);
case mxINT8_CLASS:
return count<int8_t>(v0, v1, mA, b);
case mxUINT8_CLASS:
return count<uint8_t>(v0, v1, mA, b);
default:
throw mexception("intcount:invalidarg",
"Unsupported value type for V.");
}
}
/***********
*
* Main entry
*
* Input:
* [0]: v0: the lower-end of the integer range [int32]
* [1]: v1: the higher-end of the integer range [int32]
* [2]: A: the value matrix/array [numeric]
* [3]: b: whether to do the counting per-column [logical]
*
* Output:
* [0]: C: the matrix of counts
*
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// check take inputs
const_marray mV0(prhs[0]);
const_marray mV1(prhs[1]);
const_marray mA(prhs[2]);
const_marray mB(prhs[3]);
int v0 = mV0.get_scalar<int32_t>();
int v1 = mV1.get_scalar<int32_t>();
bool b = mB.get_scalar<bool>();
// main
plhs[0] = do_count(v0, v1, mA, b).mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/intcount_cimp.cpp | C++ | mit | 3,155 |
/********************************************************************
*
* wmedian_cimp.cpp
*
* The implementation of the core part of wmedian
*
* Created by Dahua Lin, on Sep 28, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
inline T find_wmedian(
const caview1d<T>& x, // x : sorted values
const caview1d<T>& f) // f : cumsum of sorted weights
{
int n = (int)x.nelems();
T t = f[n-1] / 2;
int i = 0;
while (i < n && f[i] < t) ++i;
if (f[i] > t)
{
return x[i];
}
else
{
return i < n-1 ? (x[i] + x[i+1]) / 2 : x[i];
}
}
template<typename T>
inline marray do_wmedian(const_marray mX, const_marray mF)
{
size_t m = mX.nrows();
size_t n = mX.ncolumns();
if (m > 1)
{
if (n == 1)
{
caview1d<T> x = view1d<T>(mX);
caview1d<T> f = view1d<T>(mF);
T r = find_wmedian(x, f);
return create_mscalar<T>(r);
}
else
{
caview2d<T> X = view2d<T>(mX);
caview2d<T> F = view2d<T>(mF);
marray mR = create_marray<T>(1, n);
aview1d<T> R = view1d<T>(mR);
for (index_t i = 0; i < (index_t)n; ++i)
{
R(i) = find_wmedian(X.column(i), F.column(i));
}
return mR;
}
}
else
{
return duplicate(mX);
}
}
/**
* main entry
*
* Input
* [0]: X (sorted values) (along dim 1)
* [1]: F (cumsum of sorted weights)
* Output
* [0]: R (weighted median values)
*
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const_marray mX(prhs[0]);
const_marray mF(prhs[1]);
marray mR;
if (mX.is_double())
{
mR = do_wmedian<double>(mX, mF);
}
else
{
mR = do_wmedian<float>(mX, mF);
}
plhs[0] = mR.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/wmedian_cimp.cpp | C++ | mit | 2,166 |
/********************************************************************
*
* aggreg_cimp.cpp
*
* The C++ mex implementation of aggreg.m
*
* Created by Dahua Lin, on Nov 10, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <limits>
using namespace bcs;
using namespace bcs::matlab;
const int SUM_CODE = 1;
const int MIN_CODE = 2;
const int MAX_CODE = 3;
// aggregators
template<typename T>
struct sum_ag
{
typedef T result_type;
result_type init() const
{
return T(0);
}
void operator() (result_type& r, const T& x) const
{
r += x;
}
};
template<>
struct sum_ag<bool>
{
typedef double result_type;
result_type init() const
{
return false;
}
void operator() (result_type& r, const bool& x) const
{
r += (double)x;
}
};
template<typename T>
struct min_ag
{
typedef T result_type;
result_type init() const
{
if (std::numeric_limits<T>::has_infinity)
{
return std::numeric_limits<T>::infinity();
}
else
{
return std::numeric_limits<T>::max();
}
}
void operator() (result_type& r, const T& x) const
{
if (x < r) r = x;
}
};
template<>
struct min_ag<bool>
{
typedef bool result_type;
result_type init() const
{
return true;
}
void operator() (result_type& r, const bool& x) const
{
r &= x;
}
};
template<typename T>
struct max_ag
{
typedef T result_type;
result_type init() const
{
if (std::numeric_limits<T>::has_infinity)
{
return - std::numeric_limits<T>::infinity();
}
else
{
return std::numeric_limits<T>::min();
}
}
void operator() (result_type& r, const T& x) const
{
if (x > r) r = x;
}
};
template<>
struct max_ag<bool>
{
typedef bool result_type;
result_type init() const
{
return false;
}
void operator() (result_type& r, const bool& x) const
{
r |= x;
}
};
// core algorithm
template<typename T, class Aggregator>
marray aggreg(const_marray mX, const_marray mI, int dim, int K)
{
typedef typename Aggregator::result_type Tout;
Aggregator ag;
Tout vinit = ag.init();
int m = mX.nrows();
int n = mX.ncolumns();
const int32_t *I = mI.data<int32_t>();
const T *x = mX.data<T>();
if (dim == 1)
{
marray mR = create_marray<Tout>(K, n);
Tout *r = mR.data<Tout>();
int rn = K * n;
for (int i = 0; i < rn; ++i) r[i] = vinit;
if (n == 1)
{
for (int i = 0; i < m; ++i)
{
int32_t k = I[i];
if (k >= 0 && k < K) ag(r[k], x[i]);
}
}
else
{
for (int j = 0; j < n; ++j, x += m, r += K)
{
for (int i = 0; i < m; ++i)
{
int32_t k = I[i];
if (k >= 0 && k < K) ag(r[k], x[i]);
}
}
}
return mR;
}
else // dim == 2
{
marray mR = create_marray<Tout>(m, K);
Tout *R = mR.data<Tout>();
int rn = m * K;
for (int i = 0; i < rn; ++i) R[i] = vinit;
if (m == 1)
{
for (int j = 0; j < n; ++j)
{
int32_t k = I[j];
if (k >= 0 && k < K) ag(R[k], x[j]);
}
}
else
{
for (int j = 0; j < n; ++j, x += m)
{
int32_t k = I[j];
if (k >= 0 && k < K)
{
Tout *r = R + k * m;
for (int i = 0; i < m; ++i) ag(r[i], x[i]);
}
}
}
return mR;
}
}
template<typename T>
inline marray do_aggreg(const_marray mX, const_marray mI, int K, int dim, int code)
{
if (code == 1)
{
return aggreg<T, sum_ag<T> >(mX, mI, dim, K);
}
else if (code == 2)
{
return aggreg<T, min_ag<T> >(mX, mI, dim, K);
}
else // code == 3
{
return aggreg<T, max_ag<T> >(mX, mI, dim, K);
}
}
/**
* main entry:
*
* Inputs:
* [0]: X: data [double|single|int32 matrix]
* [1]: K: #classes [double scalar]
* [2]: I: indices [zero-based int32]
* [3]: dim: the direction along which the aggregation is performed
* [4]: code: function code (1-sum, 2-min, 3-max)
*
* Outputs:
* [0]: R: the results
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const_marray mX(prhs[0]);
const_marray mK(prhs[1]);
const_marray mI(prhs[2]);
const_marray mDim(prhs[3]);
const_marray mCode(prhs[4]);
int K = (int)mK.get_scalar<double>();
int dim = (int)mDim.get_scalar<double>();
int code = (int)mCode.get_scalar<double>();
// main delegate
marray mR;
if (mX.is_double())
{
mR = do_aggreg<double>(mX, mI, K, dim, code);
}
else if (mX.is_single())
{
mR = do_aggreg<float>(mX, mI, K, dim, code);
}
else if (mX.is_int32())
{
mR = do_aggreg<int32_t>(mX, mI, K, dim, code);
}
else if (mX.is_logical())
{
mR = do_aggreg<bool>(mX, mI, K, dim, code);
}
else
{
throw mexception("aggreg:invalidarg",
"aggreg only supports matrices of type double, single, int32, or logical");
}
// output
plhs[0] = mR.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/aggreg_cimp.cpp | C++ | mit | 6,018 |
%VALUESEG divides a vector of numeric values into constant-value segments
%
% [sp, ep] = valueseg(x);
% divides the numeric/logical/char vector x into segments, such that
% the elements in each segments have the same value.
%
% In the output, sp and ep are row vectors of size m, where m is
% the number of segments. In particular, sp(i) is the starting
% index of the i-th value segment, and ep(i) is its last index.
%
% History
% - Created by Dahua Lin, on May 30, 2008
% - Modified by Dahua Lin, on May 26, 2010
% - based on C++-mex implementation
% - Modified by Dahua Lin, on June 6, 2010
% - change to pure C++-mex implementation
%
| zzhangumd-smitoolbox | base/data/valueseg.m | MATLAB | mit | 738 |
function [H, varargout] = uniformhist(X, hsiz, rgn)
% Generate histogram over uniform bins
%
% [H, C] = uniformhist(X, n, [a, b]);
%
% generates a histogram over uniform bins for one-dimensional
% data. Here, X is a matrix comprised of observed values.
%
% The interval [a, b] is divided into n uniform bins.
%
% In the output, H is a vector of size n x 1, in which H(i) is the
% number of values in the i-th bin.
%
% C is also a vector of n x 1, where C(i) is the center
% of the i-th bin.
%
% [H, C1, C2] = uniformdist(X, [m, n], [a1, b1, a2, b2]);
%
% generates a histogram over uniform bins for two-dimensional
% points. Here, X should be a matrix of size N x 2, with
% each row being a point.
%
% The interval [a1, b1] is divided into m uniform bins, and
% the interval [a2, b2] is divided into n uniform bins.
% In this way, we obain m x n rectangle bins over a 2D space.
%
% In the output, H is a matrix of size m x n, in which H(i,j)
% is the number of points in the bin at i-th row and j-th column.
%
% centers is a cell arrray, where centers{1} is a vector of size
% m x 1, where C1(i) is the center of the i-th bin along the first
% dimension, and C2(j) is the center of the j-th bin along the
% second dimension.
%
% [H, C1, ..., Cd] = uniformdist(X, hsiz, rgn);
%
% This function can be applied to the data of arbitrary dimensions.
%
% Input arguments:
% - X: an N x d data matrix, each row is a point
% - rgn: the range, in form of [a1, b1, ..., ad, bd]
% - hsiz: the size of histogram, in form of [n1, ..., nd]
%
% Created by Dahua Lin, on Nov 2, 2011
%
%% veirfy input arguments
if ~(isfloat(X) && ndims(X) == 2 && isreal(X) && ~issparse(X))
error('uniformhist:invalidarg', 'X should be a non-sparse real matrix.');
end
if ~(isnumeric(hsiz) && ndims(hsiz) == 2 && size(hsiz, 1) == 1)
error('uniformhist:invalidarg', 'hsiz should be a numeric row vector.');
end
d = numel(hsiz);
if ~(isnumeric(rgn) && isequal(size(rgn), [1 2*d]))
error('uniformhist:invalidarg', 'rgn is invalid.');
end
if d == 1
if ~isvector(X)
X = X(:);
end
else
if size(X,2) ~= d
error('uniformhist:invalidarg', 'X should have %d columns.', d);
end
end
%% main
if d == 1
a = rgn(1);
b = rgn(2);
n = hsiz;
s = (b - a) / n;
Z = ceil((1 / s) * (X - a));
H = intcount(n, Z)';
C = a + (0.5 + (0:n-1)) * s;
varargout{1} = C;
elseif d == 2
a1 = rgn(1);
b1 = rgn(2);
a2 = rgn(3);
b2 = rgn(4);
n1 = hsiz(1);
n2 = hsiz(2);
s1 = (b1 - a1) / n1;
s2 = (b2 - a2) / n2;
x1 = X(:,1);
x2 = X(:,2);
r = find(x1 >= a2 & x1 <= b2 & x2 >= a2 & x2 <= b2);
x1 = x1(r);
x2 = x2(r);
Z1 = ceil((1 / s1) * (x1 - a1));
Z2 = ceil((1 / s2) * (x2 - a2));
Z = Z1 + (Z2 - 1) * n1;
H = intcount(n1 * n2, Z);
H = reshape(H, n1, n2);
C1 = a1 + (0.5 + (0:n1-1)) * s1;
C2 = a2 + (0.5 + (0:n2-1)) * s2;
varargout = {C1, C2};
else % d > 2
a = rgn(1:2:end);
b = rgn(2:2:end);
N = size(X, 1);
% filter data
r = true(N, 1);
for k = 1 : d
x = X(:, k);
r = r & (x >= a(k) & x <= b(k));
end
X = X(r, :);
% compute H
Zs = cell(1, d);
for k = 1 : d
x = X(:, k);
s = (b(k) - a(k)) / hsiz(k);
z = ceil((1 / s) * (x - a(k)));
Zs{k} = z;
end
Z = sub2ind(hsiz, Zs{:});
H = intcount(prod(hsiz), Z);
H = reshape(H, hsiz);
% compute C
varargout = cell(1, d);
for k = 1 : d
cn = hsiz(k);
s = (b(k) - a(k)) / cn;
c = a(k) + (0.5 + (0:cn-1)) * s;
varargout{k} = c;
end
end
| zzhangumd-smitoolbox | base/data/uniformhist.m | MATLAB | mit | 3,955 |
% Merge several sorted sequences into one
%
% vc = merge_sorted(v1, v2, ...);
%
% merge the sorted vectors v1, v2, ..., into a sorted vector vc.
% Here, v1, v2, ... are all numeric vectors of the same class.
%
% History
% -------
% - Created by Dahua Lin, on Mar 28, 2011
% | zzhangumd-smitoolbox | base/data/merge_sorted.m | MATLAB | mit | 298 |
function d = fnsdim(A)
% Get the first non-singleton dimension of an array
%
% d = fnsdim(A);
% gets the first non-singleton dimension of the array A.
%
% Created by Dahua Lin, on Sep 13, 2010
%
%% main
nd = ndims(A);
if nd == 2
if size(A, 1) > 1
d = 1;
else
d = 2;
end
else
s = size(A);
d = find(s > 1, 1);
if isempty(d)
d = nd;
end
end
| zzhangumd-smitoolbox | base/utils/fnsdim.m | MATLAB | mit | 439 |
function S = parlist(varargin)
% Parses a name/value pair list
%
% S = parlist('name1', value1, 'name2', value2, ...)
% parses a name/value list and return the results as a struct S.
%
% S is a struct with S.name1 = value1, S.name2 = value2, ...
%
% Note that the value names should be valid variable name that can
% serve as a field name in S.
%
% S = parlist(S0, 'name1', value1, 'name2', value2, ...)
% updates the struct S0 with the values provided in the ensuing
% name/value list.
%
% Each name in the name pair list should be a field of S0.
%
% Remarks
% -------
% - If there are repeated names in the list, then the latter value
% corresponding to the same name will override the former one.
%
% History
% -------
% - Created by Dahua Lin, on Nov 10, 2010
% - Modified by Dahua Lin, on Jan 4, 2011
%
%% main
if nargin == 0
S = [];
else
if ischar(varargin{1})
S = make_s([], varargin);
elseif isstruct(varargin{1})
S = make_s(varargin{1}, varargin(2:end));
end
end
%% core
function S = make_s(S, pairs)
% the core function to make the struct
if ~isempty(pairs)
names = pairs(1:2:end);
values = pairs(2:2:end);
n = numel(names);
if ~(n == numel(values) && iscellstr(names))
error('parlist:invalidarg', 'the name/value pair list is invalid.');
end
for i = 1 : n
cname = names{i};
if ~isfield(S, cname)
error('parlist:invalidarg', 'The option name %s is not supported', cname);
end
S.(cname) = values{i};
end
end
| zzhangumd-smitoolbox | base/utils/parlist.m | MATLAB | mit | 1,650 |
function h = impline(a, b, c, rgn, varargin)
%IMPLINE Draw a line given by implicit equation
%
% impline(a, b, c, [], ...);
% impline(a, b, c, rgn, ...);
%
% Draws a 2D line within a range.
% The line is given by the following implicit equation.
%
% a x + b y + c = 0
%
% In the input, rgn is the view range, in form of
% [left right top bottom].
%
% rgn can also be input as [], then the range will be obtained
% from the current axis.
%
% One can specify additional parameters, which will be forwarded
% to the line function that this function actually invokes to
% do the drawing.
%
% Created by Dahua Lin, on Dec 31, 2011
%
%% verify inputs
if ~(isscalar(a) && isscalar(b) && isscalar(c))
error('impline:invalidarg', 'a, b, and c should be all scalars.');
end
if isempty(rgn)
rgn = [get(gca, 'XLim'), get(gca, 'YLim')];
else
if ~(isnumeric(rgn) && isequal(size(rgn), [1 4]))
error('impline:invalidarg', 'rgn should be a 1 x 4 numeric vector.');
end
end
%% main
if abs(a) < abs(b)
x0 = rgn(1);
x1 = rgn(2);
y0 = - (a * x0 + c) / b;
y1 = - (a * x1 + c) / b;
else
y0 = rgn(3);
y1 = rgn(4);
x0 = - (b * y0 + c) / a;
x1 = - (b * y1 + c) / a;
end
if nargout == 0
line([x0 x1], [y0 y1], varargin{:});
else
h = line([x0 x1], [y0 y1], varargin{:});
end
| zzhangumd-smitoolbox | base/utils/impline.m | MATLAB | mit | 1,405 |
function V = pwcc(f, X, Y)
% Perform pairwise computation between columns
%
% V = pwcc(f, X, Y);
% applies the function f to columns in X and Y pairwisely.
%
% f should be a function that can support the following syntax:
%
% v = f(A, B);
%
% where A and B have the same number of columns n, then v has size
% 1 x n, such that v(i) corresponds to A(:,i) and B(:,i).
% Note that the number of rows in A and B need not be equal.
%
% In the output, V has size n1 x n2, where n1 and n2 are respectively
% the number of columns in X and Y.
% Created by Dahua Lin, on Sep 12, 2010
%
%% verify input
if ndims(X) > 2 || ndims(Y) > 2
error('pwcc:invalidarg', 'X and Y should be matrices.');
end
%% main
nx = size(X, 2);
ny = size(Y, 2);
if nx <= ny
if nx == 1
V = f(X(:, ones(1, ny)), Y);
else
x = X(:, 1);
v = f(x(:, ones(1, ny)), Y);
V = zeros(nx, ny, class(v));
V(1, :) = v;
for i = 2 : nx
x = X(:, i);
v = f(x(:, ones(1, ny)), Y);
V(i, :) = v;
end
end
else
if ny == 1
V = f(X, Y(:, ones(1, nx))).';
else
y = Y(:, 1);
v = f(X, y(:, ones(1, nx)));
v = zeros(nx, ny, class(v));
V(:, 1) = v.';
for i = 2 : ny
y = Y(:, i);
v = f(X, y(:, ones(1, nx)));
V(:, i) = v.';
end
end
end
| zzhangumd-smitoolbox | base/utils/pwcc.m | MATLAB | mit | 1,520 |
function clsname = fresult_class(a, b, c)
% determine the class of the floating point computation result
%
% clsname = fresult_class(a, b);
% determines the result class of a * b
%
% clsname = fresult_class(a, b, c);
% determines the result class of a * b * c
%
% Created by Dahua Lin, on Aug 14, 2011
%
%% verify input
if ~isfloat(a)
error('fresult_class:invalidarg', 'a should be of floating-point type.');
end
if ~isfloat(b)
error('fresult_class:invalidarg', 'b should be of floating-point type.');
end
if nargin >= 3
if ~isfloat(c)
error('fresult_class:invalidarg', 'c should be of floating-point type.');
end
end
%% main
if nargin < 3
if isa(a, 'double') && isa(b, 'double')
clsname = 'double';
else
clsname = 'single';
end
else
if isa(a, 'double') && isa(b, 'double') && isa(c, 'double')
clsname = 'double';
else
clsname = 'single';
end
end
| zzhangumd-smitoolbox | base/utils/fresult_class.m | MATLAB | mit | 972 |
function P = cartprod(nums, op)
%CARTPROD Gets the cartesian product of number arrays
%
% P = cartprod([n1, n2, ..., nK]);
% computes the Cartesian product {1:n1} x {1:n2} x ... x {1:nK},
% the results are returned by P, which is a K x (n1 x n2 x ... x nK)
% array, with each column representing a combination of values.
%
% This function can be used in cases involving combination
% traverse.
%
% By default, the first element changes most slowly, and the
% last element changes fastest, in the output.
%
% P = cartprod([n1, n2, ..., nK], 'first-fast');
% computes the Cartesian product. In the contrast to the
% default manner, using the 'first-fast' option, the first
% element changes the fastest in the output.
%
% Example
% cartprod([2, 3, 4]) outputs
% 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2
% 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3 3 3
% 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
%
% cardprod([2, 3, 4], 'first-fast') outputs
% 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
% 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3 1 1 2 2 3 3
% 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4
%
% History
% -------
% - Created by Dahua Lin, on May 30, 2008
% - Modified by Dahua Lin, on Mar 22, 2010
% - add the option for setting whether the first element changes
% the fatest or the last element changes the fastest.
% - refactor the program based on a new sub-function repvec
%
%% parse and verify input
if isempty(nums)
P = [];
return
else
assert(isvector(nums) && isnumeric(nums) && ...
all(nums > 0) && all(nums == fix(nums)), ...
'cartprod:invalidarg', ...
'nums should be a vector of positive integers.');
K = numel(nums);
end
if nargin >= 2
assert(ischar(op) && strcmp(op, 'first-fast'), ...
'cartprod:invalidarg', ...
'The 2nd argument can only be ''first-fast'' if specified.');
ff = true;
else
ff = false;
end
% for K = 1,2,3, use specific simplified implementation
% for K > 3, use generic implementation
if K == 1
P = 1 : nums(1);
elseif K == 2
n1 = nums(1);
n2 = nums(2);
if ~ff
P = [repvec(1:n1, n2, 1); repvec(1:n2, 1, n1)];
else
P = [repvec(1:n1, 1, n2); repvec(1:n2, n1, 1)];
end
elseif K == 3
n1 = nums(1);
n2 = nums(2);
n3 = nums(3);
if ~ff
P = [ ...
repvec(1:n1, n2 * n3, 1); ...
repvec(1:n2, n3, n1); ...
repvec(1:n3, 1, n1 * n2)];
else
P = [ ...
repvec(1:n1, 1, n2 * n3); ...
repvec(1:n2, n1, n3); ...
repvec(1:n3, n1 * n2, 1)];
end
else % K > 3 (generic case)
if size(nums, 1) > 1 % make it a row vector
nums = nums.';
end
fcp = [1, cumprod(nums(1:K-1))]; % forward-cumprod: [1, n1, n1 * n2, ...]
rcp = [1, cumprod(nums(K:-1:2))]; % backward-cumprod: [1, n3, n3 * n2, ...]
if ~ff
irs = rcp(K:-1:1); % irs: inner repeating times
ors = fcp; % ors: outer repeating times
else
irs = fcp;
ors = rcp(K:-1:1);
end
N = fcp(K) * nums(K); % N: the total number
P = zeros(K, N);
for i = 1 : K
P(i, :) = repvec(1:nums(i), irs(i), ors(i));
end
end
function r = repvec(v, m, n)
% v: a row vector of length k
% make a row vector of length m x k x n by repeating each element
% of v by m times, and then repeating the entire one by n times
%
if m > 1
r = v(ones(m, 1), :);
else
r = v;
end
if n > 1
r = r(:);
r = r(:, ones(1, n));
end
if size(r, 1) > 1
r = reshape(r, 1, numel(r));
end
| zzhangumd-smitoolbox | base/utils/cartprod.m | MATLAB | mit | 4,046 |
function devcheck(title, x1, x2, tol)
% Check whether two arrays are close enough, if not raise a warning
%
% devcheck(title, x1, x2, tol);
%
assert(isfloat(x1));
assert(isfloat(x2));
assert(isequal(size(x1), size(x2)));
maxdev = max(abs(x1(:) - x2(:)));
if maxdev > tol
warning('devcheck:largedev', ...
'Large deviation encountered in verifying %s (dev = %g)', ...
title, maxdev);
end
| zzhangumd-smitoolbox | base/utils/devcheck.m | MATLAB | mit | 411 |
function s = strjoin(strs, delim)
% Join multiple strings with a specified delimiter
%
% s = strjoin(strs, delim);
% joins multiple strings in strs, which is a cell array, into
% a string, using delim as the delimiter.
%
% If delim is omitted, it uses '' as delim, which means to
% simply concatenate all strings in strs.
%
% History
% -------
% - Created by Dahua Lin, on Nov 10, 2010
%
%% verify input
if ~iscellstr(strs)
error('strjoin:invalidarg', 'strs should be a cell array of strings.');
end
if nargin < 2
delim = '';
else
if ~ischar(delim)
error('strjoin:invalidarg', 'delim should be a string.');
end
end
%% main
n = numel(strs);
if n == 0
s = '';
elseif n == 1
s = strs{1};
else
if isempty(delim)
ss = strs;
else
ss = cell(1, 2*n-1);
ss(1:2:end) = strs(:);
[ss{2:2:end}] = deal(delim);
end
s = [ss{:}];
end
| zzhangumd-smitoolbox | base/utils/strjoin.m | MATLAB | mit | 978 |
function sch = trainsch(n, n0, gr, rstream)
% Makes a training schedule
%
% sch = trainsch(n, n0, gr);
% sch = trainsch(n, n0, gr, rstream);
%
% In the practice of modeling training, it is sometimes more
% efficient to train a model in several stages. Starting from
% a small random subset to train an initial model, and use it
% as an initial solution for further optimization with large
% sample set.
%
% This function is to produce such a training schedule.
%
% Input arguments:
% - n: the total number of available training samples
% - n0: the size of initial training set
% - gr: the grow ratio. For example, if gr = 2, the training
% set doubles at each stage. (gr > 1)
% - rstream: the random stream for producing the random numbers.
% (this can be omitted).
%
% Output argument:
% - sch: It is a cell array of size K x 1, where K is the
% number of stages. sch{k} is an array of indices
% selected for the k-th stage training.
% sch{K} is always [], which indicates that the entire
% training set is used for the final training.
%
% For each k > 1, sch{k} is a super-set of sch{k-1}.
%
% Note if n0 <= n, sch will be {[]}, which indicates there is just
% one-stage training with all samples.
%
% History
% -------
% - Created by Dahua Lin, on April 24, 2011
%
%% verify input arguments
if ~(isnumeric(n) && isscalar(n) && n > 0 && n == fix(n))
error('trainsch:invalidarg', 'n should be a positive integer scalar.');
end
if ~(isnumeric(n0) && isscalar(n0) && n0 > 0 && n0 == fix(n0))
error('trainsch:invalidarg', 'n0 should be a positive integer scalar.');
end
if ~(isnumeric(gr) && isscalar(gr) && isreal(gr) && gr > 1)
error('trainsch:invalidarg', 'gr should be a real value with gr > 1.');
end
if nargin < 4
rstream = [];
else
if ~isa(rstream, 'RandStream')
error('trainsch:invalidarg', 'rstream should be an object of class RandStream.');
end
end
%% main
if n > n0
K = ceil(log(n / n0) / log(gr)) + 1;
ns = ceil(n0 * (gr.^(0:K-1)));
ds = [ns(1), diff(ns)];
sch = cell(K, 1);
rs = 1 : n;
for k = 1 : K-1
a = randpick(numel(rs), ds(k), rstream);
if k == 1
s = a;
else
s = [s, rs(a)]; %#ok<AGROW>
end
sch{k} = s;
rs(a) = [];
end
sch{K} = [];
else
sch = {[]};
end
| zzhangumd-smitoolbox | base/utils/trainsch.m | MATLAB | mit | 2,637 |
classdef tsuite_pdmat
% The test suite for pdmat_* functions
%
% Created by Dahua Lin, on Aug 25, 2011
% Modified by Dahua Lin, on Sep 3, 2011
%% Properties
properties
types = {'s', 'd', 'f'};
dims = [1 2 5];
nums = [1 3];
end
%% Test cases
methods
function test_construction(obj)
tys = obj.types;
ds = obj.dims;
ns = obj.nums;
% test construction with full spec
for t = 1 : numel(tys)
ty = tys{t};
for d = ds
for n = ns
C = rand_pdmat(ty, d, n, [1 3]);
assert(C.d == d);
assert(C.n == n);
end
end
end
% test construction with simplified spec
pdm_s = rand_pdmat('s', 1, 1, [1 2]);
assert(isequal(pdmat(pdm_s.v), pdm_s));
pdm_d = rand_pdmat('d', 2, 1, [1 2]);
assert(isequal(pdmat(pdm_d.v), pdm_d));
pdm_f = rand_pdmat('f', 2, 1, [1 2]);
assert(isequal(pdmat(pdm_f.v), pdm_f));
end
function test_pick_and_fullform(obj)
run_multi(obj, @tsuite_pdmat.do_test_pick_and_fullform);
end
function test_diag(obj)
run_multi(obj, @tsuite_pdmat.do_test_diag);
end
function test_scale(obj)
run_multi(obj, @tsuite_pdmat.do_test_scale);
end
function test_inv(obj)
run_multi(obj, @tsuite_pdmat.do_test_inv);
end
function test_lndet(obj)
run_multi(obj, @tsuite_pdmat.do_test_lndet);
end
function test_mvmul(obj)
run_multi(obj, @tsuite_pdmat.do_test_mvmul);
end
function test_lsolve(obj)
run_multi(obj, @tsuite_pdmat.do_test_lsolve);
end
function test_quad(obj)
run_multi(obj, @tsuite_pdmat.do_test_quad);
end
function test_pwquad(obj)
run_multi(obj, @tsuite_pdmat.do_test_pwquad);
end
function test_choltrans(obj)
run_multi(obj, @tsuite_pdmat.do_test_choltrans);
end
function test_plus(obj)
run_multi_pairs(obj, @tsuite_pdmat.do_test_plus);
end
function test_dot(obj)
run_multi_pairs(obj, @tsuite_pdmat.do_test_dot);
end
end
methods(Access='private', Static)
function do_test_pick_and_fullform(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
for i = 1 : n
Si = pdmat_pick(S, i);
tsuite_pdmat.check_valid(Si, ty, d, 1);
Fi0 = pdmat_fullform(S, i);
Fi1 = pdmat_fullform(Si);
assert(isa(Fi0, 'double') && isequal(size(Fi0), [d d]));
assert(isa(Fi1, 'double') && isequal(size(Fi1), [d d]));
assert(isequal(Fi0, Fi1));
end
end
function do_test_diag(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
V0 = zeros(d, n);
for i = 1 : n
Ci = pdmat_fullform(S, i);
V0(:, i) = diag(Ci);
end
V1 = pdmat_diag(S);
assert(isequal(V0, V1));
end
function do_test_scale(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
c = pi;
R = pdmat_scale(S, c);
tsuite_pdmat.check_valid(R, ty, d, n);
for i = 1 : n
Sm = pdmat_fullform(S, i);
Rm = pdmat_fullform(R, i);
assert(norm(Sm * c - Rm) < 1e-15);
end
if n == 1
K = 5;
c = rand(1, K);
R = pdmat_scale(S, c);
tsuite_pdmat.check_valid(R, ty, d, K);
Sm = pdmat_fullform(S);
for i = 1 : K
Rm = pdmat_fullform(R, i);
assert(norm(Sm * c(i) - Rm) < 1e-15);
end
else
c = rand(1, n);
R = pdmat_scale(S, c);
tsuite_pdmat.check_valid(R, ty, d, n);
for i = 1 : n
Sm = pdmat_fullform(S, i);
Rm = pdmat_fullform(R, i);
assert(norm(Sm * c(i) - Rm) < 1e-15);
end
end
end
function do_test_inv(ty, d, n)
S = rand_pdmat(ty, d, n, [1 3]);
R = pdmat_inv(S);
tsuite_pdmat.check_valid(R, ty, d, n);
for i = 1 : n
Sm = pdmat_fullform(S, i);
Rm = pdmat_fullform(R, i);
assert(norm(Sm * Rm - eye(d)) < 1e-12);
end
end
function do_test_lndet(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
r = pdmat_lndet(S);
assert(isa(r, 'double') && isreal(r));
assert(isequal(size(r), [1, n]));
for i = 1: n
Sm = pdmat_fullform(S, i);
cr0 = lndet(Sm);
assert(abs(r(i) - cr0) < 1e-12);
end
end
function do_test_mvmul(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
X = rand(d, n);
Y = pdmat_mvmul(S, X);
assert(isa(Y, 'double') && isequal(size(Y), [d, n]));
for i = 1 : n
Sm = pdmat_fullform(S, i);
y0 = Sm * X(:, i);
assert(norm(y0 - Y(:,i)) < 1e-13);
end
if n > 1
return;
end
nx = 5;
X = rand(d, nx);
Y = pdmat_mvmul(S, X);
assert(isa(Y, 'double') && isequal(size(Y), [d, nx]));
Y0 = pdmat_fullform(S) * X;
assert(norm(Y - Y0) < 1e-12);
end
function do_test_lsolve(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
X = rand(d, n);
Y = pdmat_lsolve(S, X);
assert(isa(Y, 'double') && isequal(size(Y), [d, n]));
for i = 1 : n
Sm = pdmat_fullform(S, i);
y0 = Sm \ X(:, i);
assert(norm(y0 - Y(:,i)) < 1e-12);
end
if n > 1
return;
end
nx = 5;
X = rand(d, nx);
Y = pdmat_lsolve(S, X);
assert(isa(Y, 'double') && isequal(size(Y), [d, nx]));
Y0 = pdmat_fullform(S) \ X;
assert(norm(Y - Y0) < 1e-12);
end
function do_test_quad(ty, d, n)
S = rand_pdmat(ty, d, n, [1, 3]);
x = rand(d, 1);
y = rand(d, 1);
rx = pdmat_quad(S, x);
rxy = pdmat_quad(S, x, y);
assert(isa(rx, 'double') && isequal(size(rx), [n, 1]));
assert(isa(rxy, 'double') && isequal(size(rxy), [n, 1]));
for i = 1 : n
Sm = pdmat_fullform(S, i);
crx0 = x' * Sm * x;
crxy0 = x' * Sm * y;
assert(abs(rx(i) - crx0) < 1e-13);
assert(abs(rxy(i) - crxy0) < 1e-13);
end
nx = 5;
X = rand(d, nx);
Y = rand(d, nx);
Rxx = pdmat_quad(S, X);
Rxy = pdmat_quad(S, X, Y);
assert(isa(Rxx, 'double') && isequal(size(Rxx), [n, nx]));
assert(isa(Rxy, 'double') && isequal(size(Rxy), [n, nx]));
for i = 1 : n
Sm = pdmat_fullform(S, i);
crx0 = dot(X, Sm * X, 1);
crxy0 = dot(X, Sm * Y, 1);
assert(norm(Rxx(i, :) - crx0) < 1e-12);
assert(norm(Rxy(i, :) - crxy0) < 1e-12);
end
end
function do_test_pwquad(ty, d, n)
if n > 1
return;
end
S = rand_pdmat(ty, d, n, [1, 3]);
nx = 5; X = rand(d, nx);
ny = 6; Y = rand(d, ny);
Rxx = pdmat_pwquad(S, X);
Rxy = pdmat_pwquad(S, X, Y);
assert(isa(Rxx, 'double') && isequal(size(Rxx), [nx, nx]));
assert(isa(Rxy, 'double') && isequal(size(Rxy), [nx, ny]));
Sm = pdmat_fullform(S);
Rxx0 = X' * Sm * X;
Rxy0 = X' * Sm * Y;
assert(norm(Rxx - Rxx0) < 1e-12);
assert(norm(Rxy - Rxy0) < 1e-12);
end
function do_test_choltrans(ty, d, n)
if n == 1
S = rand_pdmat(ty, d, n, [1, 3]);
nx = 5; X = rand(d, nx);
R = pdmat_choltrans(S, X);
assert(isa(R, 'double') && isequal(size(R), [d, nx]));
Sm = pdmat_fullform(S);
R0 = chol(Sm, 'lower') * X;
assert(norm(R - R0) < 1e-12);
end
end
function do_test_plus(d, ty1, n1, ty2, n2)
S1 = rand_pdmat(ty1, d, n1, [1, 3]);
S2 = rand_pdmat(ty2, d, n2, [1, 3]);
c1 = 2;
c2 = 3;
R = pdmat_plus(S1, S2);
C = pdmat_plus(S1, S2, c1, c2);
nr = max(n1, n2);
tyr = tsuite_pdmat.max_form_ty(ty1, ty2);
tsuite_pdmat.check_valid(R, tyr, d, nr);
tsuite_pdmat.check_valid(C, tyr, d, nr);
for i = 1 : nr
if n1 == 1
Sm1 = pdmat_fullform(S1);
else
Sm1 = pdmat_fullform(S1, i);
end
if n2 == 1
Sm2 = pdmat_fullform(S2);
else
Sm2 = pdmat_fullform(S2, i);
end
Rm = pdmat_fullform(R, i);
Rm0 = Sm1 + Sm2;
assert(norm(Rm - Rm0) < 1e-13);
Cm = pdmat_fullform(C, i);
Cm0 = c1 * Sm1 + c2 * Sm2;
assert(norm(Cm - Cm0) < 1e-13);
end
end
function do_test_dot(d, ty1, n1, ty2, n2)
S1 = rand_pdmat(ty1, d, n1, [1, 3]);
S2 = rand_pdmat(ty2, d, n2, [1, 3]);
V = pdmat_dot(S1, S2);
n = max(n1, n2);
assert(isa(V, 'double'));
assert(isequal(size(V), [1, n]));
V0 = zeros(1, n);
for i = 1 : n
if n1 == 1
Sm1 = pdmat_fullform(S1);
else
Sm1 = pdmat_fullform(S1, i);
end
if n2 == 1
Sm2 = pdmat_fullform(S2);
else
Sm2 = pdmat_fullform(S2, i);
end
V0(i) = trace(Sm1' * Sm2);
end
assert(norm(V - V0) < 1e-13);
end
end
%% Test running functions
methods
function run_multi(obj, tfunc)
% Run a specific test case under different conditions
tys = obj.types;
ds = obj.dims;
ns = obj.nums;
for t = 1 : numel(tys)
ty = tys{t};
for d = ds
for n = ns
tfunc(ty, d, n);
end
end
end
end
function run_multi_pairs(obj, tfunc)
% Run binary func/ops under different conditions
tys = obj.types;
ds = obj.dims;
ns = obj.nums;
for t1 = 1 : numel(tys)
for t2 = 1 : numel(tys)
ty1 = tys{t1};
ty2 = tys{t2};
for d = ds
for n = ns
if n == 1
tfunc(d, ty1, 1, ty2, 1);
else
tfunc(d, ty1, n, ty2, n);
tfunc(d, ty1, 1, ty2, n);
tfunc(d, ty1, n, ty2, 1);
end
end
end
end
end
end
end
%% Auxiliary functions
methods(Static, Access='private')
function check_valid(S, ty, d, n)
assert(is_pdmat(S));
assert(ischar(S.tag) && strcmp(S.tag, 'pdmat'));
assert(ischar(S.ty) && strcmp(S.ty, ty));
assert(isa(S.d, 'double') && isequal(S.d, d));
assert(isa(S.n, 'double') && isequal(S.n, n));
switch ty
case 's'
assert(isequal(size(S.v), [1, S.n]));
case 'd'
assert(isequal(size(S.v), [S.d, S.n]));
case 'f'
if S.n == 1
assert(isequal(size(S.v), [S.d, S.d]));
else
assert(isequal(size(S.v), [S.d, S.d, S.n]));
end
end
end
function tyr = max_form_ty(ty1, ty2)
s = [ty1, ty2];
switch s
case 'ss'
tyr = 's';
case {'sd', 'ds', 'dd'}
tyr = 'd';
case {'sf', 'df', 'fs', 'fd', 'ff'}
tyr = 'f';
otherwise
error('test_pdmat:rterror', 'Invalid types.');
end
end
end
end
| zzhangumd-smitoolbox | base/tests/tsuite_pdmat.m | MATLAB | mit | 15,233 |
function Sr = pdmat_plus(S1, S2, c1, c2)
% Compute the sum or linear combination of two matrices
%
% Sr = pdmat_plus(S1, S2);
% computes the sum of the matrix in S1 and that in S2, and returns
% the resultant matrix in a pdmat struct.
%
% Sr = pdmat_plus(S1, S2, c1, c2);
% computes the linear combination of the matrix in S1 (scaled with
% c1) and that in S2 (scaled with c2).
%
% Several cases are supported, as below.
% - S1.n == S2.n = 1 or any n > 0
% - S1.n == 1 and S2.n > 0
% - S1.n > 0 and S2.n == 1
%
% S1 and S2 may or may not be in the same form, the results are in a
% promoted form as max(S1.ty, S2.ty) under the order 's' < 'd' < 'f'.
% '
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
n1 = S1.n;
n2 = S2.n;
d = S1.d;
if d ~= S2.d
error('pdmat_plus:invalidarg', 'S1.d and S2.d are inconsistent.');
end
if ~(n1 == n2 || n1 == 1 || n2 == 1)
error('pdmat_plus:invalidarg', ...
'The number of matrices in S1 and that in S2 are incompatible.');
end
if nargin == 2
c1 = 1;
c2 = 1;
elseif nargin == 4
if ~(isfloat(c1) && isscalar(c1) && isreal(c1))
error('pdmat_plus:invalidarg', 'c1 must be a real scalar.');
end
if ~(isfloat(c2) && isscalar(c2) && isreal(c2))
error('pdmat_plus:invalidarg', 'c2 must be a real scalar.');
end
else
error('The #arguments to pdmat_plus must be either 2 or 4.');
end
%% main
% extract & scale data
if c1 == 1
v1 = S1.v;
else
v1 = c1 * S1.v;
end
if c2 == 1
v2 = S2.v;
else
v2 = c2 * S2.v;
end
% do addition
ty = max_ty(S1.ty, S2.ty);
if n1 == n2
n = n1;
vr = calc_sn(d, n, S1.ty, S2.ty, v1, v2);
else
if n1 < n2
n = n2;
vr = calc_dn(d, n, S1.ty, S2.ty, v1, v2);
else
n = n1;
vr = calc_dn(d, n, S2.ty, S1.ty, v2, v1);
end
end
% make result
Sr.tag = S1.tag;
Sr.ty = ty;
Sr.d = d;
Sr.n = n;
Sr.v = vr;
%% sub-routines
function ty = max_ty(ty1, ty2)
if ty1 == 's' || (ty1 == 'd' && ty2 == 'f')
ty = ty2;
else
ty = ty1;
end
function vr = calc_sn(d, n, ty1, ty2, v1, v2)
% pre-conditions:
% S1.n == S2.n
if ty1 == ty2
vr = v1 + v2;
else
if ty1 == 's'
if ty2 == 'd'
vr = add_sd(d, n, v1, v2);
elseif ty2 == 'f'
vr = add_sf(d, n, v1, v2);
end
elseif ty1 == 'd'
if ty2 == 's'
vr = add_sd(d, n, v2, v1);
elseif ty2 == 'f'
vr = add_df(d, n, v1, v2);
end
elseif ty1 == 'f'
if ty2 == 's'
vr = add_sf(d, n, v2, v1);
elseif ty2 == 'd'
vr = add_df(d, n, v2, v1);
end
end
end
function vr = add_sd(d, n, v1, v2)
if n == 1 || d == 1
vr = v1 + v2;
else
vr = bsxfun(@plus, v1, v2);
end
function vr = add_sf(d, n, v1, v2)
if d == 1
if n == 1
vr = v1 + v2;
else
vr = reshape(v1, [1, 1, n]) + v2;
end
else
if n == 1
vr = adddiag(v2, v1);
else
r1 = adddiag(v2(:,:,1), v1(1));
vr = zeros(d, d, n, class(r1));
for i = 1 : n
vr(:,:,i) = adddiag(v2(:,:,i), v1(i));
end
end
end
function vr = add_df(d, n, v1, v2)
if n == 1
if d == 1
vr = v1 + v2;
else
vr = adddiag(v2, v1);
end
else
if d == 1
vr = reshape(v1, [1, 1, n]) + v2;
else
r1 = adddiag(v2(:,:,1), v1(:,1));
vr = zeros(d, d, n, class(r1));
for i = 1 : n
vr(:,:,i) = adddiag(v2(:,:,i), v1(:,i));
end
end
end
function vr = calc_dn(d, n, ty1, ty2, v1, v2)
% pre-conditions:
% S1.n == 1
% S2.n == n > 1
if d == 1
vr = v1 + v2;
if ty1 == 'f' && (ty2 == 's' || ty2 == 'd')
vr = reshape(vr, [1, 1, n]);
end
else
if ty1 == 's' || ty1 == 'd'
if ty2 == 's' || ty2 == 'd'
if ty1 == 's'
vr = v1 + v2;
else % d > 1 && ty1 == 'd'
vr = bsxfun(@plus, v1, v2);
end
elseif ty2 == 'f'
r1 = adddiag(v2(:,:,1), v1);
vr = zeros(d, d, n, class(r1));
vr(:,:,1) = r1;
for i = 2 : n
vr(:,:,i) = adddiag(v2(:,:,i), v1);
end
end
elseif ty1 == 'f'
if ty2 == 's' || ty2 == 'd'
r1 = adddiag(v1, v2(:,1));
vr = zeros(d, d, n, class(r1));
vr(:,:,1) = r1;
for i = 2 : n
vr(:,:,i) = adddiag(v1, v2(:,i));
end
elseif ty2 == 'f'
vr = bsxfun(@plus, v1, v2);
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_plus.m | MATLAB | mit | 4,742 |
function S = pdmat(a1, a2, a3)
% Constructs a struct representing a (semi)-positive definite matrix
%
% A pdmat struct can represent a (semi)positive definite matrix
% in three different forms, each form has a single-char tag to
% identify it.
%
% - 's': scalar-form:
% use a scalar to represent a matrix in form of c * eye(d).
% - 'd': diagonal-form:
% use a column-vector of diagonal entries to represent a
% diagonal matrix.
% - 'f': full-form:
% directly represent the matrix using its full matlab form.
%
% Note that one can pack multiple matrices of the same size into
% a single pdmat struct.
%
% A pdmat struct is comprised of the following fields:
%
% - tag: a string, which equals 'pdmat'
% - ty: the char to indicate which form it is in
% - d: the dimension of the matrix (the size of matrix is d x d)
% - n: the number of matrices packed in the struct
% - v: the value in the specified form to represent the matrix
% - scalar-form: v is a scalar or a 1 x n row vector
% - diagonal-form: v is a d x 1 vector or a d x n matrix
% - full-form: v is a d x d matrix or a d x d x n cube
%
% S = pdmat(v);
% creates a pdmat struct to represent a single matrix in a proper
% form.
%
% - If v is a scalar, then it creates a 1 x 1 matrix in scalar-form.
% - If v is a d x 1 vector (d > 1), then it creates a d x d matrix
% in diagonal-form.
% - If v is a d x d matrix (d > 1), then it creates a full-form.
%
% S = pdmat(ty, d, v);
% creates a pdmat struct to represent a single matrix or multiple
% matrices in the specified form.
%
% Input arguments:
% - ty: the type of the representation form: 's', 'd', or 'f'
% - d: the dimension of the matrix/matrices
% - v: the representation.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% single argument with form inference
if isfloat(a1) && nargin == 1
v = a1;
if ~(isreal(v) && ndims(v) == 2)
error('pdmat:invalidarg', ...
'In single-arg input, v should be a real scalar/vector/matrix.');
end
S.tag = 'pdmat';
if isscalar(v)
S.ty = 's';
S.d = 1;
elseif size(v, 2) == 1
S.ty = 'd';
S.d = size(v, 1);
elseif size(v, 2) == size(v, 1)
S.ty = 'f';
S.d = size(v, 1);
else
error('pdmat:invalidarg', 'The size of v is invalid.');
end
S.n = 1;
S.v = v;
%% full specification
elseif ischar(a1) && nargin == 3
ty = a1;
d = a2;
v = a3;
if ~(ischar(ty) && isscalar(ty))
error('pdmat:invalidarg', 'ty should be a char scalar.');
end
if ~(isnumeric(d) && isscalar(d) && d == fix(d) && d >= 1)
error('pdmat:invalidarg', 'd should be a positive integer scalar.');
end
if ~(isreal(v) && ndims(v) <= 3)
error('pdmat:invalidarg', ...
'v should be a real scalar/vector/matrix/cube.');
end
S.tag = 'pdmat';
switch ty
case 's'
if ndims(v) == 2 && size(v, 1) == 1
S.ty = 's';
S.d = d;
S.n = size(v, 2);
S.v = v;
else
error('pdmat:invalidarg', ...
'For scalar-form, v should be a scalar or a row vector.');
end
case 'd'
if ndims(v) == 2 && size(v, 1) == d
S.ty = 'd';
S.d = d;
S.n = size(v, 2);
S.v = v;
else
error('pdmat:invalidarg', ...
'For diagonal-form, the size of v should be d x 1 or d x n.');
end
case 'f'
if size(v, 1) == d && size(v, 2) == d
S.ty = 'f';
S.d = d;
S.n = size(v, 3);
S.v = v;
else
error('pdmat:invalidarg', ...
'For full-form, the size of v should be d x d or d x d x n.');
end
otherwise
error('pdmat:invalidarg', 'ty is invalid.');
end
%% otherwise, error
else
error('pdmat:invalidarg', 'The input arguments to pdmat are invalid.');
end
| zzhangumd-smitoolbox | base/pdmat/pdmat.m | MATLAB | mit | 4,430 |
function V = pdmat_diag(S)
% Get the diagonal entries of the matrices
%
% V = pdmat_diag(S);
%
% returns the diagonal entries of each matrices packed in S
% as columns of V.
%
% Created by Dahua Lin, on Sep 1, 2010
%
switch S.ty
case 's'
if S.d == 1
V = S.v;
else
V = S.v(ones(S.d, 1), :);
end
case 'd'
V = S.v;
case 'f'
if S.d == 1
if S.n == 1
V = S.v;
else
V = reshape(S.v, [1, S.n]);
end
else
if S.n == 1
V = diag(S.v);
else
d = S.d;
di = bsxfun(@plus, (1:(d+1):(d*d)).', (0:S.n-1) * (d*d));
V = S.v(di);
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_diag.m | MATLAB | mit | 799 |
function S = rand_pdmat(ty, d, n, evrgn)
% Generates a random pdmat struct
%
% S = rand_pdmat(ty, d, n, [a, b]);
% generates a random pdmat struct.
%
% Input arguments:
% - ty: The type of matrix form ('s', 'd', or 'ty')
% - d: the dimension (a matrix has size d x d)
% - n: the number of matrices in the struct
% - [a, b]: the range of eigenvalues.
%
% Created by Dahua Lin, on Sep 3, 2011
%
%% verify input
if ~(ischar(ty) && isscalar(ty))
error('rand_pdmat:invalidarg', 'ty should be a char scalar.');
end
if ~(isnumeric(d) && isscalar(d) && d == fix(d) && d >= 1)
error('rand_pdmat:invalidarg', 'd should be a positive integer.');
end
if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 1)
error('rand_pdmat:invalidarg', 'n should be a positive integer.');
end
if ~(isfloat(evrgn) && numel(evrgn) == 2 && isreal(evrgn))
error('rand_pdmat:invalidarg', ...
'The 4th argument should be a pair of real numbers.');
end
%% main
a = evrgn(1);
b = evrgn(2);
switch ty
case 's'
v = a + rand(1, n) * (b-a);
case 'd'
v = a + rand(d, n) * (b-a);
case 'f'
if n == 1
v = make_C(d, a, b);
else
v = zeros(d, d, n);
for i = 1 : n
v(:,:,i) = make_C(d, a, b);
end
end
otherwise
error('test_pdmat:rterror', 'Unknown form type %s', ty);
end
S = pdmat(ty, d, v);
%% Sub routines
function C = make_C(d, a, b)
if d == 1
C = a + rand() * (b - a);
else
r = orth(randn(d, d));
ev = a + rand(d, 1) * (b-a);
C = r' * bsxfun(@times, ev, r);
C = (C + C') * 0.5;
end
| zzhangumd-smitoolbox | base/pdmat/rand_pdmat.m | MATLAB | mit | 1,708 |
function dv = pdmat_dot(A, B)
% Computes the inner product between positive definite matrices
%
% dv = pdmat_dot(A);
% dv = pdmat_dot(A, B);
%
% Computes the inner product (tr(A' * B)) between A and B.
%
% The following cases are supported:
% - A.n == 1 && B.n == 1: return dv as a scalar
% - A.n == 1 && B.n = n > 1: return dv as a 1 x n row vector
% - A.n = n > 1 && B.n == 1: return dv as a 1 x n row vector
% - A.n == B.n = n > 1: return dv as a 1 x n row vector.
%
% If B is omitted, it sets B = A.
%
% Created by Dahua Lin, on Sep 2, 2011
%
%% verify input
d = A.d;
if nargin < 2
B = A;
else
if B.d ~= d
error('pdmat_dot:invalidarg', ...
'The dimensions of A and B are inconsistent.');
end
if ~(A.n == B.n || A.n == 1 || B.n == 1)
error('pdmat_dot:invalidarg', ...
'The numbers of matrices in A and B are inconsistent.');
end
end
%% main
switch A.ty
case 's'
switch B.ty
case 's'
dv = dot_ss(d, A, B);
case 'd'
dv = dot_sd(d, A, B);
case 'f'
dv = dot_sf(d, A, B);
end
case 'd'
switch B.ty
case 's'
dv = dot_sd(d, B, A);
case 'd'
dv = dot_dd(d, A, B);
case 'f'
dv = dot_df(d, A, B);
end
case 'f'
switch B.ty
case 's'
dv = dot_sf(d, B, A);
case 'd'
dv = dot_df(d, B, A);
case 'f'
dv = dot_ff(d, A, B);
end
end
%% Core computation routines
function dv = dot_ss(d, A, B)
dv = A.v .* B.v;
if d > 1
dv = dv * d;
end
function dv = dot_sd(d, A, B)
if d == 1
dv = A.v .* B.v;
else
dv = A.v .* sum(B.v, 1);
end
function dv = dot_dd(d, A, B)
if d == 1
dv = A.v .* B.v;
else
dv = col_dots(A.v, B.v);
end
function dv = dot_sf(d, A, B)
if d == 1
if B.n == 1
bv = B.v;
else
bv = reshape(B.v, 1, B.n);
end
dv = A.v .* bv;
else
bdiagv = get_diagv(B.v);
dv = A.v .* sum(bdiagv, 1);
end
function dv = dot_df(d, A, B)
if d == 1
if B.n == 1
bv = B.v;
else
bv = reshape(B.v, 1, B.n);
end
dv = A.v .* bv;
else
bdiagv = get_diagv(B.v);
dv = col_dots(A.v, bdiagv);
end
function dv = dot_ff(d, A, B)
if A.n == 1
av = A.v(:);
else
av = reshape(A.v, d * d, A.n);
end
if B.n == 1
bv = B.v(:);
else
bv = reshape(B.v, d * d, B.n);
end
if d == 1
dv = av .* bv;
else
dv = col_dots(av, bv);
end
%% Auxiliary functions
function V = get_diagv(A)
% get diagonal entries of fullform matrix or matrices
n = size(A, 3);
if n == 1
V = diag(A);
else
d = size(A, 1);
I = bsxfun(@plus, (1:(d+1):(d*d))', (0:n-1) * (d*d));
V = A(I);
end
function v = col_dots(X, Y)
if size(X, 2) == 1
v = X' * Y;
elseif size(Y, 2) == 1
v = Y' * X;
else
v = dot(X, Y, 1);
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_dot.m | MATLAB | mit | 3,095 |
function R = pdmat_pick(S, i)
% Get a subset from a pack of positive definite matrices
%
% R = pdmat_pick(S, i);
% returns a pdmat struct that is comprised of the i-th matrix
% in S of the same form.
%
% i can also be a index vector or logical vector, in which case,
% R may contain multiple matrices.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% main
switch S.ty
case 's'
v = S.v(1, i);
n = size(v, 2);
case 'd'
v = S.v(:, i);
n = size(v, 2);
case 'f'
v = S.v(:,:,i);
n = size(v, 3);
end
R.tag = S.tag;
R.ty = S.ty;
R.d = S.d;
R.n = n;
R.v = v;
| zzhangumd-smitoolbox | base/pdmat/pdmat_pick.m | MATLAB | mit | 653 |
function R = pdmat_pwquad(S, X, Y)
% computes pairwise quadratic forms w.r.t. positive definite matrices
%
% R = pdmat_pwquad(S, X);
% R = pdmat_pwquad(S, X, Y);
%
% Here, S must be comprised of exactly one matrix (S.n == 1).
%
% Suppose the size of X is S.d x m and that of Y is S.d x n. Then
% R will be an m x n matrix, with R(i, j) = X(:,i)' * A * Y(:,i).
% Here, A denotes the matrix represented by S.
%
% When Y is omitted, it is assumed to be equal to X. In this case,
% R is guaranteed to be exactly symmetric.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
if nargin < 3
is_sym = 1;
else
is_sym = 0;
end
if S.n ~= 1
error('pdmat_pwquad:invalidarg', 'S must be comprised of one matrix.');
end
d = S.d;
if ~(isfloat(X) && ndims(X) == 2 && size(X,1) == d)
error('pdmat_pwquad:invalidarg', ...
'X should be a numeric matrix with size(X,1) == d.');
end
if ~is_sym
if ~(isfloat(Y) && ndims(Y) == 2 && size(Y,1) == d)
error('pdmat_pwquad:invalidarg', ...
'Y should be a numeric matrix with size(Y,1) == d.');
end
end
%% main
switch S.ty
case 's'
if is_sym
R = S.v * (X' * X);
else
R = S.v * (X' * Y);
end
case 'd'
if is_sym
R = X' * bsxfun(@times, S.v, X);
R = (R + R') * 0.5;
else
R = X' * bsxfun(@times, S.v, Y);
end
case 'f'
if is_sym
R = X' * (S.v * X);
R = (R + R') * 0.5;
else
R = X' * (S.v * Y);
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_pwquad.m | MATLAB | mit | 1,644 |
function Y = pdmat_lsolve(S, X)
% Solves linear equation solution w.r.t positive definite matrices
%
% Y = pdmat_lsolve(S, X);
%
% Returns the result Y as pdmat_mvmul(inv(S), X), with the
% calculation implemented in a more efficient way.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
d = S.d;
n = S.n;
if ~(isfloat(X) && ndims(X) == 2 && size(X, 1) == d)
error('pdmat_lsolve:invalidarg', ...
'X should be a numeric matrix with size(X,1) == d.');
end
%% main
if n == 1
switch S.ty
case 's'
Y = X / S.v;
case 'd'
if d == 1
Y = X / S.v;
elseif size(X, 2) == 1
Y = X ./ S.v;
else
Y = bsxfun(@times, 1 ./ S.v, X);
end
case 'f'
Y = S.v \ X;
end
else % n > 1
if size(X, 2) ~= n
error('pdmat_mvmul:invalidarg', ...
'#columns in X is not consistent with S.n.');
end
switch S.ty
case 's'
if d == 1
Y = X ./ S.v;
else
Y = bsxfun(@times, 1 ./ S.v, X);
end
case 'd'
Y = X ./ S.v;
case 'f'
if d == 1
Y = X ./ reshape(S.v, 1, n);
else
v = S.v;
y1 = v(:,:,1) \ X(:,1);
Y = zeros(d, n, class(y1));
Y(:, 1) = y1;
for i = 2 : n
Y(:, i) = v(:,:,i) \ X(:,i);
end
end
end
end | zzhangumd-smitoolbox | base/pdmat/pdmat_lsolve.m | MATLAB | mit | 1,648 |
function Sr = pdmat_scale(S, c)
% Compute a scalar-product of a positive definite matrix
%
% Sr = pdmat_scale(S, c);
% returns Sr, whose matrix is the scalar product of c and
% that in S.
%
% c can be a scalar, or a row vector.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
if ~(isfloat(c) && isreal(c))
error('pdmat_scale:invalidarg', ...
'c should be of real floating-point type.');
end
if ~(isscalar(c) || (ndims(c) == 2 && size(c,1) == 1))
error('pdmat_scale:invalidarg', ...
'c should be either a scalar or a row vector.');
end
if S.n > 1
K = size(c, 2);
if ~(K == 1 || K == S.n)
error('pdmat_scale:invalidarg', ...
'When S.n > 1, length(c) should either 1 or S.n.');
end
end
%% main
if isscalar(c)
Sr = S;
Sr.v = c * S.v;
else % size(c, 2) = K > 1
Sr = S;
ty = S.ty;
d = S.d;
Sr.n = size(c, 2);
switch ty
case 's'
Sr.v = S.v .* c;
case 'd'
if d == 1
Sr.v = S.v .* c;
else
Sr.v = bsxfun(@times, S.v, c);
end
case 'f'
c3 = reshape(c, [1, 1, Sr.n]);
if d == 1
Sr.v = S.v .* c3;
else
Sr.v = bsxfun(@times, S.v, c3);
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_scale.m | MATLAB | mit | 1,382 |
function r = pdmat_lndet(S)
% Compute log-determinant of positive definite matrices
%
% r = pdmat_lndet(S);
% computes the log-determinant of positive definite matrices
% contained in S.
%
% r is a scalar (if S.n == 1) or a row vector of size 1 x S.n,
% with r(i) corresponding to the i-th matrix in S.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% main
d = S.d;
switch S.ty
case 's'
r = d * log(S.v);
case 'd'
if d == 1
r = log(S.v);
else
r = sum(log(S.v), 1);
end
case 'f'
if d == 1
r = log(reshape(S.v, 1, S.n));
elseif d == 2
r = log(det2x2(S.v));
else
n = S.n;
v = S.v;
if n == 1
r = lndet(v);
else
r = zeros(1, n, class(v));
for i = 1 : n
r(i) = lndet(v(:,:,i));
end
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_lndet.m | MATLAB | mit | 1,053 |
function R = pdmat_quad(S, X, Y)
% computes quadratic form with respect to positive definite matrices
%
% R = pdmat_quad(S, X);
% R = pdmat_quad(S, X, Y);
%
% Supposes there are m matrices contained in S, and X and Y
% are matrices of the same size S.d x n.
%
% Then R is a matrix of size m x n, with R(i, j) being equal to
% x(:,i)' * Ai * y(:, i), where Ai is the i-th matrix in S.
%
% When Y is omitted, it is assumed to be equal to X.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
if nargin < 3
Y = X;
end
if ~(isfloat(X) && ndims(X) == 2)
error('pdmat_quad:invalidarg', 'X should be a numeric matrix.');
end
if ~(isfloat(Y) && ndims(Y) == 2)
error('pdmat_quad:invalidarg', 'Y should be a numeric matrix.');
end
d = S.d;
if ~(size(X,1) == d && size(Y,1) == d && size(X,2) == size(Y,2))
error('pdmat_quad:invalidarg', ...
'X and Y should be equal-size matrices with S,d rows.');
end
%% main
m = S.n;
n = size(X, 2);
switch S.ty
case 's'
if d == 1
xyd = X .* Y;
else
xyd = dot(X, Y, 1);
end
R = S.v' * xyd;
case 'd'
R = S.v' * (X .* Y);
case 'f'
v = S.v;
if d == 1
if m > 1
v = reshape(v, m, 1);
end
R = v * (X .* Y);
else
if m == 1
R = dot(X, v * Y, 1);
else
r1 = dot(X, v(:,:,1) * Y, 1);
R = zeros(m, n, class(r1));
R(1,:) = r1;
for k = 2 : m
R(k,:) = dot(X, v(:,:,k) * Y, 1);
end
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_quad.m | MATLAB | mit | 1,718 |
function Y = pdmat_mvmul(S, X)
% Compute product of positive-definite matrix and vectors
%
% Y = pdmat_mvmul(S, X)
% compute the product of the positive definite matrix (matrices)
% and the columns of X.
%
% Several cases are supports (let ns = S.n and nx = size(X, 2))
% - ns == 1 && nx == 1:
% times the matrix represented by S with the vector x.
% size(Y) = [d, 1]
%
% - ns == 1 && nx > 1:
% times the matrix represented by S with all columns of x.
% size(Y) = [d, nx]
%
% - ns == nx > 1:
% times the i-th matrix contained in S with X(:,i).
% size(Y) = [d, nx]
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
d = S.d;
n = S.n;
if ~(isfloat(X) && ndims(X) == 2 && size(X, 1) == d)
error('pdmat_mvmul:invalidarg', ...
'X should be a numeric matrix with size(X,1) == d.');
end
%% main
if n == 1
switch S.ty
case {'s', 'f'}
Y = S.v * X;
case 'd'
if d == 1
Y = S.v * X;
elseif size(X, 2) == 1
Y = S.v .* X;
else
Y = bsxfun(@times, S.v, X);
end
end
else % n > 1
if size(X, 2) ~= n
error('pdmat_mvmul:invalidarg', ...
'#columns in X is not consistent with S.n.');
end
switch S.ty
case 's'
if d == 1
Y = S.v .* X;
else
Y = bsxfun(@times, S.v, X);
end
case 'd'
Y = S.v .* X;
case 'f'
if d == 1
Y = reshape(S.v, 1, n) .* X;
else
v = S.v;
y1 = v(:,:,1) * X(:,1);
Y = zeros(d, n, class(y1));
Y(:, 1) = y1;
for i = 2 : n
Y(:, i) = v(:,:,i) * X(:,i);
end
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_mvmul.m | MATLAB | mit | 2,005 |
function tf = is_pdmat(S)
% Tests whether an argument is a pdmat struct
%
% tf = is_pdmat(S);
% performs a quick check, and returns whether S is a pdmat struct.
%
% Created by Dahua Lin, on Aug 25, 2010
%
tf = isstruct(S) && isscalar(S) && isfield(S, 'tag') && ...
ischar(S.tag) && strcmp(S.tag, 'pdmat');
| zzhangumd-smitoolbox | base/pdmat/is_pdmat.m | MATLAB | mit | 321 |
function Y = pdmat_choltrans(S, X)
% Transform vectors using the result of Cholesky factorization
%
% Y = pdmat_choltrans(S, X);
%
% Here, S should contain only one matrix (denoted by A).
% Let L be a lower-triangular matrix such that A = L * L'.
% Then this function returns Y = L * X, which is computed
% in an efficient manner, depending on the form of S.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% verify input
if S.n ~= 1
error('pdmat_pwquad:invalidarg', 'S must be comprised of one matrix.');
end
d = S.d;
if ~(isfloat(X) && ndims(X) == 2 && size(X,1) == d)
error('pdmat_pwquad:invalidarg', ...
'X should be a numeric matrix with size(X,1) == d.');
end
%% main
switch S.ty
case 's'
Y = sqrt(S.v) * X;
case 'd'
if d == 1
Y = sqrt(S.v) * X;
elseif size(X,2) == 1
Y = sqrt(S.v) .* X;
else
Y = bsxfun(@times, sqrt(S.v), X);
end
case 'f'
if d == 1
Y = sqrt(S.v) * X;
elseif d == 2
Y = chol2x2(S.v) * X;
else
Y = chol(S.v, 'lower') * X;
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_choltrans.m | MATLAB | mit | 1,186 |
function M = pdmat_fullform(S, i)
% Gets the full matrix form of a matrix packed in pdmat
%
% M = pdmat_fullform(S);
% Gets the full matrix representation of the matrix represented
% by a pdmat struct S.
%
% Here, S should contain only one matrix (i.e. S.n == 1)
%
% M = pdmat_fullform(S, i);
% Gets the full matrix representation of the i-th matrix in S.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% main
% verify input and get v (of the selected part)
if nargin < 2
if S.n ~= 1
error('pdmat_fullform:invalidarg', ...
'S should contain only one matrix without i given.');
end
v = S.v;
else
if ~(isnumeric(i) && isscalar(i) && i == fix(i) && i >= 1 && i <= S.n)
error('pdmat_fullform:invalidarg', ...
'i should be an integer scalar in [1, S.n].');
end
switch S.ty
case 's'
v = S.v(i);
case 'd'
v = S.v(:, i);
case 'f'
v = S.v(:,:,i);
end
end
% make the full matrix
switch S.ty
case 's'
M = diag(v * ones(S.d, 1));
case 'd'
M = diag(v);
case 'f'
M = v;
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_fullform.m | MATLAB | mit | 1,173 |
function R = pdmat_inv(S)
% Compute the inverse of the positive definite matrices
%
% R = pdmat_inv(S);
% return the inverse of the positive definite matrices in S.
% The inverse is represented in the same form as in S.
%
% Created by Dahua Lin, on Aug 25, 2010
%
%% main
R.tag = S.tag;
R.ty = S.ty;
R.d = S.d;
R.n = S.n;
switch S.ty
case {'s', 'd'}
R.v = 1 ./ S.v;
case 'f'
if S.d == 1
R.v = 1 ./ S.v;
elseif S.d == 2
R.v = inv2x2(S.v);
else
if S.n == 1
R.v = inv(S.v);
else
v = S.v;
r = zeros(size(S.v), class(S.v));
for i = 1 : S.n
r(:,:,i) = inv(v(:,:,i));
end
R.v = r;
end
end
end
| zzhangumd-smitoolbox | base/pdmat/pdmat_inv.m | MATLAB | mit | 868 |
function A = l2mat(K, L, w, op)
%L2MAT Assignment matrix from labels
%
% A = L2MAT(K, L, w);
%
% Constructs an assignment matrix A based on a label vector L, such
% that
%
% If L is a row vector, then A is a K x n matrix, with
%
% A(L(i), i) = w(i).
%
% If L is a column vector, then A is an n x K matrix, with
%
% A(i, L(i)) = w(i).
%
%
% Input arguments:
% - K: The number of distinct labels.
%
% - L: The vector of labels. The value of L(i) is expected
% in {1, ..., K}. If L(i) is out of this range, it will
% be ignored.
%
% - w: The weights, which can be either a scalar (all weights
% being the same) of a vector of length n.
%
% The class of A will be the same as that of w.
%
% A = L2MAT(K, L, w, 'sparse');
%
% Constructs A as a sparse matrix.
%
% History
% -------
% - Created by Dahua Lin, on Oct 31, 2009
% - Modified by Dahua Lin, on Apr 7, 2010
% - change name to l2mat
% - add support of options: logical and sparse.
% - Modified by Dahua Lin, on Feb 3, 2010
% - support user-supplied weights.
%
%% verify input arguments
if ~(isscalar(K) && isnumeric(K) && K == fix(K) && K >= 1)
error('l2mat:invalidarg', 'K should be a positive integer.');
end
if ~(isnumeric(L) && isvector(L))
error('l2mat:invalidarg', 'L should be a numeric vector.');
end
n = numel(L);
if ~( (isnumeric(w) || islogical(w)) && ...
(isscalar(w) || (isvector(w) && numel(w) == n)) )
error('l2mat:invalidarg', 'w should be a vector of length n.');
end
if nargin >= 4
if ~strcmp(op, 'sparse')
error('l2mat:invalidarg', 'The 4th argument is invalid.');
end
use_sparse = 1;
else
use_sparse = 0;
end
%% main
if size(L, 2) == 1
cf = 1;
else
cf = 0;
L = L.';
end
valid = (L >= 1 & L <= K);
if all(valid)
I = (1:n).';
J = double(L);
else
I = find(valid);
J = L(valid);
if ~isscalar(w)
w = w(valid);
end
end
if size(w, 2) > 1
w = w.';
end
if use_sparse
if cf
A = sparse(I, J, w, n, K);
else
A = sparse(J, I, w, K, n);
end
else
if cf
if islogical(w)
A = false(n, K);
else
A = zeros(n, K, class(w));
end
A(I + (J - 1) * n) = w;
else
if islogical(w)
A = false(K, n);
else
A = zeros(K, n, class(w));
end
A(J + (I - 1) * K) = w;
end
end
| zzhangumd-smitoolbox | base/matrix/l2mat.m | MATLAB | mit | 2,624 |
/********************************************************************
*
* smallmat.h
*
* The common header shared by all small matrix computation routines
*
* Created by Dahua Lin, on June 8, 2010
*
********************************************************************/
#include <mex.h>
#include <cmath>
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
/// The struct to represent small matrices
template<typename T>
struct Vec2
{
T v1;
T v2;
};
template<typename T>
struct Vec3
{
T v1;
T v2;
T v3;
};
template<typename T>
struct Mat2x2
{
T v11;
T v21;
T v12;
T v22;
};
template<typename T>
struct SMat2x2
{
T v11;
T v12;
T v22;
};
template<typename T>
struct Polar2
{
T a;
T b;
T theta;
};
template<typename T>
struct LTMat2x2
{
T v11;
T v21;
T v22;
};
// input manipulation
inline void general_input_check(const mxArray *mxA, const char *msgid)
{
if (mxIsEmpty(mxA) || mxIsSparse(mxA) || mxIsComplex(mxA))
mexErrMsgIdAndTxt(msgid,
"The input array must be a non-empty non-sparse real array.");
}
inline bool test_size(const mxArray *mxA, int nr, int nc, int& n)
{
if (nc == 1)
{
if (mxGetNumberOfDimensions(mxA) == 2 && (int)mxGetM(mxA) == nr)
{
n = mxGetN(mxA);
return true;
}
else
{
return false;
}
}
else
{
int ndim = mxGetNumberOfDimensions(mxA);
if (ndim == 2)
{
if ((int)mxGetM(mxA) == nr && (int)mxGetN(mxA) == nc)
{
n = 1;
return true;
}
else
{
return false;
}
}
else if (ndim == 3)
{
const mwSize *dims = mxGetDimensions(mxA);
if (nr == dims[0] && nc == dims[1])
{
n = (int)(dims[2]);
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
template<typename T> mxArray *create_mat(int m, int n);
template<typename T> mxArray *create_cube(int m, int n, int p);
template<>
inline mxArray* create_mat<double>(int m, int n)
{
return mxCreateDoubleMatrix(m, n, mxREAL);
}
template<>
inline mxArray* create_mat<float>(int m, int n)
{
return mxCreateNumericMatrix(m, n, mxSINGLE_CLASS, mxREAL);
}
template<>
inline mxArray* create_cube<double>(int m, int n, int p)
{
mwSize dims[3] = {(mwSize)m, (mwSize)n, (mwSize)p};
return mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
}
template<>
inline mxArray* create_cube<float>(int m, int n, int p)
{
mwSize dims[3] = {(mwSize)m, (mwSize)n, (mwSize)p};
return mxCreateNumericArray(3, dims, mxSINGLE_CLASS, mxREAL);
}
// computational routines for 2x2 matrices
template<typename T>
inline T det(const Mat2x2<T>& A)
{
return A.v11 * A.v22 - A.v12 * A.v21;
}
template<typename T>
inline T det(const SMat2x2<T>& A)
{
return A.v11 * A.v22 - A.v12 * A.v12;
}
template<typename T>
inline void inv(const Mat2x2<T>& A, Mat2x2<T>& R)
{
T k = 1 / det(A);
R.v11 = k * A.v22;
R.v21 = - k * A.v21;
R.v12 = - k * A.v12;
R.v22 = k * A.v11;
}
template<typename T>
inline void inv(const SMat2x2<T>& A, SMat2x2<T>& R)
{
T k = 1 / det(A);
R.v11 = k * A.v22;
R.v12 = -k * A.v12;
R.v22 = k * A.v11;
}
template<typename T>
inline T trace(const Mat2x2<T>& A)
{
return A.v11 + A.v22;
}
template<typename T>
inline T trace(const SMat2x2<T>& A)
{
return A.v11 + A.v22;
}
template<typename T>
inline void polar_(T v11, T v12, T v22, T& a, T& b, T& theta)
{
if (v12 == 0)
{
if (v11 >= v22)
{
a = v11;
b = v22;
theta = 0;
}
else
{
a = v22;
b = v11;
theta = M_PI_2;
}
}
else
{
T y = 2 * v12;
T x = v11 - v22;
T d = std::sqrt(x * x + y * y);
T s = v11 + v22;
a = (s + d) / 2;
b = (s - d) / 2;
theta = std::atan2(y, x) / 2;
}
}
template<typename T>
inline void polar(const SMat2x2<T>& A, Polar2<T>& R)
{
polar_(A.v11, A.v12, A.v22, R.a, R.b, R.theta);
}
template<typename T>
inline void polar(const Mat2x2<T>& A, Polar2<T>& R)
{
polar_(A.v11, A.v12, A.v22, R.a, R.b, R.theta);
}
template<typename T>
inline void polar2mat(const Polar2<T>& p, SMat2x2<T>& R)
{
T c = std::cos(p.theta);
T s = std::sin(p.theta);
T c2 = c * c;
T s2 = s * s;
T a = p.a;
T b = p.b;
R.v11 = a * c2 + b * s2;
R.v12 = (a - b) * c * s;
R.v22 = a * s2 + b * c2;
}
template<typename T>
inline void polar2mat(const Polar2<T>& p, Mat2x2<T>& R)
{
T c = std::cos(p.theta);
T s = std::sin(p.theta);
T c2 = c * c;
T s2 = s * s;
T a = p.a;
T b = p.b;
R.v11 = a * c2 + b * s2;
R.v12 = R.v21 = (a - b) * c * s;
R.v22 = a * s2 + b * c2;
}
template<typename T>
inline void sqrtm(const SMat2x2<T>& A, SMat2x2<T>& R)
{
Polar2<T> p;
polar(A, p);
p.a = std::sqrt(p.a);
p.b = std::sqrt(p.b);
polar2mat(p, R);
}
template<typename T>
inline void sqrtm(const Mat2x2<T>& A, Mat2x2<T>& R)
{
Polar2<T> p;
polar(A, p);
p.a = std::sqrt(p.a);
p.b = std::sqrt(p.b);
polar2mat(p, R);
}
template<typename T>
inline void chol_(T v11, T v21, T v22, T& r11, T& r21, T& r22)
{
if (v11 == 0 && v21 == 0)
{
r11 = 0;
r21 = 0;
r22 = std::sqrt(v22);
}
else
{
r11 = std::sqrt(v11);
r21 = v21 / r11;
r22 = std::sqrt(v22 - r21 * r21);
}
}
template<typename T>
inline void chol(const Mat2x2<T>& A, Mat2x2<T>& R)
{
chol_(A.v11, A.v21, A.v22, R.v11, R.v21, R.v22);
R.v12 = 0;
}
template<typename T>
inline void chol(const SMat2x2<T>& A, LTMat2x2<T>& R)
{
chol_(A.v11, A.v12, A.v22, R.v11, R.v21, R.v22);
}
// matrix and vector multiplication
template<typename T>
inline void mtimes(const SMat2x2<T>& A, const SMat2x2<T>& B, SMat2x2<T>& C)
{
C.v11 = A.v11 * B.v11 + A.v12 * B.v12;
C.v12 = A.v11 * B.v12 + A.v12 * B.v22;
C.v22 = A.v12 * B.v12 + A.v22 * B.v22;
}
template<typename T>
inline void mtimes(const SMat2x2<T>& A, const Vec2<T>& X, Vec2<T>& Y)
{
Y.v1 = A.v11 * X.v1 + A.v12 * X.v2;
Y.v2 = A.v12 * X.v1 + A.v22 * X.v2;
}
| zzhangumd-smitoolbox | base/matrix/smallmat.h | C++ | mit | 6,725 |
function B = exelem(A, nr, nc)
% Construct a new matrix by expanding its elements into sub-matrices
%
% B = exelem(A, nr, nc);
% creates a new matrix B by expanding each element in matrix A
% into a sub-matrix of size nr x nc.
%
% Let A is a matrix of size m x n, then in the output, B is a
% matrix of the same class as A, whose size is (m x nr) x (n x nc).
%
% Example:
%
% A = [3 4; 5 6];
% B = repelem(A, 2, 3);
%
% B =
%
% 3 3 3 4 4 4
% 5 5 5 6 6 6
%
% History
% -------
% - Created by Dahua Lin, on Apr 6, 2010
% - Modified by Dahua Lin, on Jun 6, 2010
% - change name from repelem to exelem
% - change error handling (make it lightweight)
%
%% verify input
if ndims(A) ~= 2
error('exelem:invalidarg', ...
'A should be a matrix with ndims(A) == 2.');
end
%% main
if isscalar(A)
B = A(ones(nr, nc));
else
if nr == 1
if nc == 1
B = A;
else
J = 1 : size(A, 2);
J = J(ones(nc, 1), :);
B = A(:, J(:));
end
else
if nc == 1
I = 1 : size(A, 1);
I = I(ones(nr, 1), :);
B = A(I(:), :);
else
I = 1 : size(A, 1);
I = I(ones(nr, 1), :);
J = 1 : size(A, 2);
J = J(ones(nc, 1), :);
B = A(I(:), :);
B = B(:, J(:));
end
end
end
| zzhangumd-smitoolbox | base/matrix/exelem.m | MATLAB | mit | 1,566 |
function B = adddiag(A, a)
% Add values to the diagonal of a matrix
%
% B = adddiag(A, a);
% add values in a to the diagonal entries of A, and returns the
% result.
%
% Here, A should be a square matrix (say of size n x n), and
% a can be a scalar or a vector of length n.
%
%% verify input
if ~(isnumeric(A) && ndims(A) == 2)
error('adddiag:invalidarg', 'A should be a numeric matrix.');
end
[m, n] = size(A);
if m ~= n
error('adddiag:invalidarg', 'A should be a square matrix.');
end
if size(a, 1) > 1
a = a.';
end
%% main
if ~issparse(A) % full matrix
di = 1 + (0:n-1) * (n+1);
B = A;
B(di) = B(di) + a;
else % sparse matrix
if isscalar(a)
B = spdiag(n, a) + A;
else
B = spdiag(a) + A;
end
end
| zzhangumd-smitoolbox | base/matrix/adddiag.m | MATLAB | mit | 854 |
/********************************************************************
*
* det2x2.cpp
*
* The C++ mex implementation of trace of 2x2 matrices
*
* Created by Dahua Lin, on Jun 8, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_trace2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = trace(A[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = trace(A[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = trace(A[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("trace2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output vector (of size 1 x n)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("trace2x2:invalidarg",
"The number of input arguments to trace2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "trace2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_trace2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_trace2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("trace2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/trace2x2.cpp | C++ | mit | 2,400 |
% Cholesky decomposition of 2x2 matrices using fast implementation
%
% R = chol2x2(A);
% computes the cholesky decomposition of each matrix in A using a
% fast implementation. The result is a lower triangle matrix L
% such that A = L * L'.
%
% Every matrix in A should be positive definite.
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 2 x (2 x n) matrix, with all matrices juxtaposed
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% The output will be in the same form as the input.
%
% History
% -------
% - Created by Dahua Lin, on Apr 7, 2010.
% - Modified by Dahua Lin, on June 11, 2010.
%
| zzhangumd-smitoolbox | base/matrix/chol2x2.m | MATLAB | mit | 913 |
function B = rmdiag(A, op)
% Remove the diagonal entries of a square matrix
%
% B = rmdiag(A);
% B = rmdiag(A, 'r');
%
% Let A be an n x n matrix, then B will be an (n-1) x n matrix,
% constructed by removing the diagonal entries, anf lifting
% the entries which are below the diagonal.
%
% B = rmdiag(A, 'c');
%
% With this statement, the output B will be an n x (n-1) matrix,
% constructed by removing the diagonal entries, and shifting
% the entries on the right of the diagonal to left.
%
% Examples
% --------
% A = [1 2 3; 4 5 6; 7 8 9]
%
% rmdiag(A, 'r') => [4 2 3; 7 8 6]
% rmdiag(A, 'c') => [2 3; 4 6; 7 8]
%
% Created by Dahua Lin, on Nov 13, 2010
%
%% verify input
if ~(ndims(A) == 2 && size(A,1) == size(A,2))
error('rmdiag:invalidarg', 'A should be a square matrix.');
end
if nargin < 2
op = 'r';
else
if ~(isequal(op, 'r') || isequal(op, 'c'))
error('rmdiag:invalidarg', ...
'The 2nd argument should be either ''r'' or ''o''.');
end
end
%% main
n = size(A, 1);
if ~issparse(A)
if op == 'r'
I = 1 : n*n;
I(1 + (0:n-1) * (n+1)) = [];
I = reshape(I, n-1, n);
else
I = reshape(reshape(1:n*n, n, n).', 1, n*n);
I(1 + (0:n-1) * (n+1)) = [];
I = reshape(I, n-1, n).';
end
B = A(I);
else
[i, j, v] = find(A);
s0 = find(i == j);
if op == 'r'
s1 = find(i > j);
i(s1) = i(s1) - 1;
m1 = n - 1;
n1 = n;
else
s1 = find(j > i);
j(s1) = j(s1) - 1;
m1 = n;
n1 = n - 1;
end
i(s0) = [];
j(s0) = [];
v(s0) = [];
B = sparse(i, j, v, m1, n1);
end
| zzhangumd-smitoolbox | base/matrix/rmdiag.m | MATLAB | mit | 1,768 |
function Y = mvsum(As, X, W, op)
% Compute the (weighted) sum of matrix products
%
% Y = mvsum(As, X, W);
% Y = mvsum(As, X, W, op);
% compute the (weighted sum) of products between matrices and
% vectors, respectively given by As and X, according to the
% formulas below:
%
% When op = 'N':
% y = \sum_{i=1}^n w(i) * A_i * x_i,
% When op = 'T':
% y = \sum_{i=1}^n w(i) * A_i' * x_i,
%
% Here, A_i is given by A(:,:,i) and x_i is given by X(:,i).
% The weights are given in each row of W.
%
% If W is empty or a row vector, then it produces a single column
% vector y. W can also be a matrix that contains m rows, in which
% case, it produces m different y vectors, each corresponding to
% a row in W. In particular, Y(:,k) is computed based on the
% weights given in W(k,:).
%
% If the dimension of x-space is d and that of the y-space is q,
% then when op is 'N', As should be a q x d x n array. If op is
% 'T', As(:,:,i) gives A_i', and in this case, As should be of
% size d x q x n.
%
% History
% -------
% - Created by Dahua Lin, on Apr 5, 2010
% - Modified by Dahua Lin, on Apr 6, 2010
% - support multiple groups of weights.
% - Modified by Dahua Lin, on Apr 15, 2010
% - change error handling.
%
%% parse and verify input arguments
if ~(isfloat(As) && ndims(As) <= 3)
error('mvsum:invalidarg', ...
'As should be a numeric array with ndims(As) <= 3.');
end
if ~(isfloat(X) && ndims(X) == 2)
error('mvsum:invalidarg', ...
'X should be a numeric matrix.');
end
if ~(ischar(op) && isscalar(op) && (op == 'N' || op == 'T'))
error('mvsum:invalidarg', 'op should be either ''N'' or ''T''.');
end
if op == 'N'
[q, d, n] = size(As);
if ~(size(X,1) == d && size(As,3) == n)
error('mvsum:invalidarg', 'The size of As is inconsistent with that of X.');
end
else
[d, q, n] = size(As);
if ~(size(X,1) == d && size(As,3) == n)
error('mvsum:invalidarg', 'The size of As is inconsistent with that of X.');
end
end
if ~isempty(W)
if ~(isfloat(W) && ndims(W) == 2 && size(W,2) == n)
error('mvsum:invalidarg', 'W should be a numeric matrix with n columns.');
end
end
%% main
if op == 'N'
Ae = reshape(As, [q, d * n]);
WX = compute_wx(X, W);
Y = Ae * WX;
else % op == 'T'
I = reshape(1:q*n, q, n).';
Ae = reshape(As(:, I(:)), d * n, q);
WX = compute_wx(X, W);
Y = Ae' * WX;
end
%% sub-functions
function WX = compute_wx(X, W)
m = size(W, 1);
if isempty(W)
WX = X(:);
elseif m == 1
WX = bsxfun(@times, W, X);
WX = WX(:);
else
[d, n] = size(X);
We = reshape(W.', 1, n * m);
We = We(ones(d, 1), :);
We = reshape(We, d * n, m);
WX = bsxfun(@times, X(:), We);
end
| zzhangumd-smitoolbox | base/matrix/mvsum.m | MATLAB | mit | 3,020 |
/********************************************************************
*
* mtimes_sm2v2.cpp
*
* The C++ mex function for multiplication between a 2 x 2 symmetric
* matrix and a generic 2 x n matrix.
*
* Created by Dahua Lin, on June 18, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
mxArray* do_sm2v2(const mxArray *mxA, const mxArray *mxX, mxClassID cid)
{
const SMat2x2<T> *A = (const SMat2x2<T>*)mxGetData(mxA);
const Vec2<T>* X = (const Vec2<T>*)mxGetData(mxX);
int m = (int)mxGetN(mxA);
int n = (int)mxGetN(mxX);
mxArray *mxY = 0;
if (m == 1)
{
mxY = mxCreateNumericMatrix(2, n, cid, mxREAL);
const SMat2x2<T>& cA = A[0];
Vec2<T>* Y = (Vec2<T>*)mxGetData(mxY);
if (n == 1)
{
mtimes(cA, X[0], Y[0]);
}
else
{
for (int i = 0; i < n; ++i)
{
mtimes(cA, X[i], Y[i]);
}
}
}
else if (m == n)
{
mxY = mxCreateNumericMatrix(2, n, cid, mxREAL);
Vec2<T>* Y = (Vec2<T>*)mxGetData(mxY);
for (int i = 0; i < n; ++i)
{
mtimes(A[i], X[i], Y[i]);
}
}
else
{
mexErrMsgIdAndTxt("mtimes_sm2v2:invalidarg",
"The sizes of A and X are inconsistent.");
}
return mxY;
}
/***
* Main entry:
*
* Input
* [0]: A: the 2x2 symmetric matrices [3x1 or 3xn]
* [1]: X: the vectors [2xn]
* Ouput
* [2]: Y: the results
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const mxArray *mxA = prhs[0];
const mxArray *mxX = prhs[1];
if (!(mxGetNumberOfDimensions(mxA) == 2 && !mxIsSparse(mxA) && mxGetM(mxA) == 3))
mexErrMsgIdAndTxt("mtimes_sm2v2:invalidarg",
"A should be a non-sparse matrix with size(A,1) == 3.");
if (!(mxGetNumberOfDimensions(mxX) == 2 && !mxIsSparse(mxX) && mxGetM(mxX) == 2))
mexErrMsgIdAndTxt("mtimes_sm2v2:invalidarg",
"X should be a non-sparse matrix with size(X,1) == 2.");
mxArray *mxY = 0;
if (mxIsDouble(mxA) && mxIsDouble(mxX))
{
mxY = do_sm2v2<double>(mxA, mxX, mxDOUBLE_CLASS);
}
else if (mxIsSingle(mxA) && mxIsSingle(mxX))
{
mxY = do_sm2v2<float>(mxA, mxX, mxSINGLE_CLASS);
}
else
mexErrMsgIdAndTxt("mtimes_sm2v2:invalidarg",
"A and X should be both of class double or both of class single.");
plhs[0] = mxY;
}
| zzhangumd-smitoolbox | base/matrix/mtimes_sm2v2.cpp | C++ | mit | 2,716 |
/********************************************************************
*
* inv2x2.cpp
*
* The C++ mex implementation of inverse of 2x2 matrices
*
* Created by Dahua Lin, on Jun 8, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_inv2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_cube<T>(2, 2, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
inv(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(4, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
inv(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
SMat2x2<T>* R = (SMat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
inv(A[i], R[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("inv2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output array (in the same size of A)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("inv2x2:invalidarg",
"The number of input arguments to inv2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "inv2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_inv2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_inv2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("inv2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/inv2x2.cpp | C++ | mit | 2,426 |
/********************************************************************
*
* inv2x2.cpp
*
* The C++ mex implementation of inverse of 2x2 matrices
*
* Created by Dahua Lin, on Jun 8, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_polarm2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
Polar2<T>* R = (Polar2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
polar(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
Polar2<T>* R = (Polar2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
polar(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
Polar2<T>* R = (Polar2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
polar(A[i], R[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("inv2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output array (in the same size of A)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("polarm2x2:invalidarg",
"The number of input arguments to polarm2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "inv2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_polarm2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_polarm2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("polarm2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/polarm2x2.cpp | C++ | mit | 2,444 |
% Compute the determinant of 2x2 matrices using fast implementation
%
% R = det2x2(A);
% computes the determinant of each matrix in A using a fast
% implementation.
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% The output will be a 1 x n row vector.
%
% History
% -------
% - Created by Dahua Lin, on Apr 7, 2010
% - Modified by Dahua Lin, on June 20, 2010
% - based on pure C++ mex implementation
%
| zzhangumd-smitoolbox | base/matrix/det2x2.m | MATLAB | mit | 748 |
% Matrix square root of 2x2 positive definite matrices using fast
% implementation
%
% R = sqrtm2x2(A);
% computes the cholesky decomposition of each matrix in A using a
% fast implementation. The result is a lower triangle matrix.
% Every matrix in A should be positive definite.
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 2 x (2 x n) matrix, with all matrices juxtaposed
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% The output will be in the same form as the input.
%
% History
% -------
% - Created by Dahua Lin, on Apr 7, 2010
% - Modified by Dahua Lin, on June 10, 2010
%
%
| zzhangumd-smitoolbox | base/matrix/sqrtm2x2.m | MATLAB | mit | 895 |
function R = tilemat(Ms)
% Tile multiple matrices to form a single large one
%
% R = tilemat(Ms);
% Creates a big matrix by tiling the matrices given in Ms.
%
% In the input, Ms can be either of the following form:
% - an array of size p x q x m x n, where M(:,:,i,j) gives a
% sub-matrix.
% - a cell array of size m x n, where each cell is a matrix of
% size p x q.
%
% Then the output R is a matrix of size (p x m) x (q x n), in
% the following form:
%
% M_11, M_12, ..., M_1n
% M_21, M_22, ..., M_2n
% ..., ..., ..., ...
% M_m1, M_m2, ..., M_mn
%
% Here, M_{ij} is the (i, j)-th sub-matrix.
%
% History
% -------
% - Created by Dahua Lin, on Apr 4, 2010
% - Change the error handling, on May 24, 2010
% - Change to support cell array input additionally, on Jun 6, 2010
%
%% main
if isnumeric(Ms)
if ndims(Ms) > 4
error('tilemat:invalidarg', ...
'When it is a numeric array, Ms should have ndims(Ms) <= 4.');
end
if ndims(Ms) == 2
R = Ms;
return;
else
[p, q, m, n] = size(Ms);
end
elseif iscell(Ms)
if ndims(Ms) > 2
error('tilemat:invalidarg', ...
'When it is a cell array, Ms should have ndims(Ms) == 2.');
end
if numel(Ms) == 1
R = Ms{1};
return;
else
[p, q] = size(Ms{1});
[m, n] = size(Ms);
Ms = [Ms{:}];
end
end
if m == 1
R = reshape(Ms, [p, q * n]);
else
R = reshape(Ms, [p, q * m, n]);
I = reshape(1:q*m, q, m).';
R = R(:, I(:), :);
R = reshape(R, [p * m, q * n]);
end
| zzhangumd-smitoolbox | base/matrix/tilemat.m | MATLAB | mit | 1,782 |
% Compute the inverse of 2x2 matrices using fast implementation
%
% R = inv2x2(A);
% computes the inverse of each matrix in A using a fast
% implementation.
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% The output will be in the same form as the input.
%
% History
% -------
% - Created by Dahua Lin, on Apr 7, 2010
% - Modified by Dahua Lin, on June 8, 2010
% - use pure C++ mex implementation
%
| zzhangumd-smitoolbox | base/matrix/inv2x2.m | MATLAB | mit | 746 |
% Generates a vector by repeating numbers
%
% x = repnum(ns);
% generates a vector x, whose length is sum(ns), by repeating i for
% ns(i) times.
%
% For example, repnum([3 3 4]) generates a vector of length 10 as
% [1 1 1 2 2 2 3 3 3 3].
%
% The result of repnum can be used as indices for generating
% other arrays with repeated values.
%
% x = repnum(vs, ns);
% generates a vector x, by repeating vs(i) by ns(i) times.
%
% Example
% -------
% repnum(1:3) is [1 2 2 3 3 3]
%
% repnum([0.1 0.2 0.4], [2 2 3])) is [0.1 0.1 0.2 0.2 0.4 0.4 0.4].
%
% History
% -------
% - Created by Dahua Lin, on Nov 3, 2009
% - Modified by Dahua Lin, on Jun 6, 2010
% - use C++ mex to improve efficiency
% - Modified by Dahua Lin, on Nov 10, 2010
% - support repeating values in vs
%
| zzhangumd-smitoolbox | base/matrix/repnum.m | MATLAB | mit | 875 |
% Compute the trace of 2x2 matrices using fast implementation
%
% R = trace2x2(A);
% computes the trace of each matrix in A using a fast
% implementation.
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% The output will be a 1 x n row vector.
%
% History
% -------
% - Created by Dahua Lin, on June 20, 2010
%
| zzhangumd-smitoolbox | base/matrix/trace2x2.m | MATLAB | mit | 639 |
function R = makediag(v)
% Construct (multiple) diagonal matrices from diagonal elements
%
% R = makediag(v);
% Suppose v is a matrix of size d x n, then it creates a d x d x n
% array, such that R(:,:,i) is diag(v(:,i)) for each i from 1 to n.
%
% Created by Dahua Lin, on April 14, 2010
%
%% main
if ~(isnumeric(v) && ndims(v) == 2)
error('makediag:invalidarg', ...
'v should be a numeric matrix.');
end
[d, n] = size(v);
if d == 1
R = reshape(v, [1 1 n]);
elseif n == 1
R = diag(v);
else
R = zeros(d * d, n, class(v));
i = 1 + (0:d-1) * (d+1);
R(i, :) = v;
R = reshape(R, [d d n]);
end
| zzhangumd-smitoolbox | base/matrix/makediag.m | MATLAB | mit | 645 |
/********************************************************************
*
* inv2x2.cpp
*
* The C++ mex implementation of inverse of 2x2 matrices
*
* Created by Dahua Lin, on Jun 8, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_chol2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_cube<T>(2, 2, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
chol(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(4, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
chol(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
LTMat2x2<T>* R = (LTMat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
chol(A[i], R[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("chol2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output array (in the same size of A)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("chol2x2:invalidarg",
"The number of input arguments to inv2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "inv2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_chol2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_chol2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("chol2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/chol2x2.cpp | C++ | mit | 2,437 |
function v = lndet(C)
% Computes the logarithm of determinant of a positive definite matrix
%
% v = lndet(C);
% returns the log-determinant of the positive definite matrix C.
%
% Remarks
% -------
% This implementation directly computes the log-determinant of
% C based on Cholesky decomposition, and thus can effectively
% avoid the issue of overflow or underflow.
%
% History
% -------
% - Created by Dahua Lin, on June 11, 2009
%
L = chol(C);
v = 2 * sum(log(diag(L)));
| zzhangumd-smitoolbox | base/matrix/lndet.m | MATLAB | mit | 514 |
/********************************************************************
*
* det2x2.cpp
*
* The C++ mex implementation of determinant of 2x2 matrices
*
* Created by Dahua Lin, on Jun 8, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_det2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = det(A[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = det(A[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(1, n);
T *r = (T*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
r[i] = det(A[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("det2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output vector (of size 1 x n)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("det2x2:invalidarg",
"The number of input arguments to det2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "det2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_det2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_det2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("det2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/det2x2.cpp | C++ | mit | 2,384 |
function M = binotable(n)
% Generate a table of binomial coefficients
%
% M = binotable(n);
% generates a table M of size (n+1) x (n+1), where
% when i >= j, M(i, j) = nchoose(i-1, j-1), and
% when i < j, M(i, j) = 0.
%
% M is a lower triangle matrix.
%
% History
% -------
% - Created by Dahua Lin, on June 6, 2010
%
%% verify input
if ~(isnumeric(n) && isscalar(n) && n >= 0)
error('binotable:invalidarg', ...
'n should be a non-negative integer scalar.');
end
%% main
I = repmat((1:n+1).', 1, n+1);
J = repmat(1:n+1, n+1, 1);
si = I >= J;
I = I(si);
J = J(si);
F = [1, cumprod(1:n)];
V = F(I) ./ (F(J) .* F(I - J + 1));
M = zeros(n+1, n+1);
M(I + (n+1) * (J-1)) = V;
| zzhangumd-smitoolbox | base/matrix/binotable.m | MATLAB | mit | 733 |
/********************************************************************
*
* sqrtm2x2.cpp
*
* The C++ mex implementation of matrix square root of 2x2 matrices
*
* Created by Dahua Lin, on Jun 10, 2010
*
********************************************************************/
#include "smallmat.h"
template<typename T>
inline mxArray* do_sqrtm2x2(const mxArray *mxA)
{
int n = 0;
if (test_size(mxA, 2, 2, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_cube<T>(2, 2, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
sqrtm(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 4, 1, n))
{
const Mat2x2<T>* A = (const Mat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(4, n);
Mat2x2<T>* R = (Mat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
sqrtm(A[i], R[i]);
}
return mxR;
}
else if (test_size(mxA, 3, 1, n))
{
const SMat2x2<T>* A = (const SMat2x2<T>*)mxGetData(mxA);
mxArray *mxR = create_mat<T>(3, n);
SMat2x2<T>* R = (SMat2x2<T>*)mxGetData(mxR);
for (int i = 0; i < n; ++i)
{
sqrtm(A[i], R[i]);
}
return mxR;
}
else
{
mexErrMsgIdAndTxt("sqrtm2x2:invalidarg", "The size of input array is invalid.");
}
return NULL;
}
/**
* Main entry
*
* Input:
* [0]: A the input array containing the input matrices
* can be 2 x 2 x n, or 4 x n, or 3 x n.
*
* Output:
* [0]: R the output array (in the same size of A)
*
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 1)
mexErrMsgIdAndTxt("sqrtm2x2:invalidarg",
"The number of input arguments to inv2x2 should be 1.");
const mxArray *mxA = prhs[0];
general_input_check(mxA, "sqrtm2x2:invalidarg");
mxArray *mxR = 0;
if (mxIsDouble(mxA))
{
mxR = do_sqrtm2x2<double>(mxA);
}
else if (mxIsSingle(mxA))
{
mxR = do_sqrtm2x2<float>(mxA);
}
else
{
mexErrMsgIdAndTxt("sqrtm2x2:invalidarg",
"The input array should be of class double or single.");
}
plhs[0] = mxR;
}
| zzhangumd-smitoolbox | base/matrix/sqrtm2x2.cpp | C++ | mit | 2,459 |
/********************************************************************
*
* repnum_cimp.cpp
*
* The C++ mex implementation for repnum
*
* Created by Dahua Lin, on June 6, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <bcslib/array/array1d.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T0>
array1d<int32_t> get_nums(const_marray mNs)
{
size_t n = mNs.nelems();
array1d<int32_t> ns(n);
const T0 *in = mNs.data<T0>();
for (index_t i = 0; i < (index_t)n; ++i)
{
ns(i) = (int32_t)(in[i]);
}
return ns;
}
array1d<int32_t> do_get_nums(const_marray mNs)
{
if (!(mNs.is_vector() && !mNs.is_sparse()))
{
throw mexception("repnum:invalidarg",
"ns should be a non-sparse numeric vector.");
}
switch (mNs.class_id())
{
case mxDOUBLE_CLASS:
return get_nums<double>(mNs);
case mxSINGLE_CLASS:
return get_nums<float>(mNs);
case mxINT32_CLASS:
return get_nums<int32_t>(mNs);
case mxUINT32_CLASS:
return get_nums<uint32_t>(mNs);
case mxINT16_CLASS:
return get_nums<int16_t>(mNs);
case mxUINT16_CLASS:
return get_nums<uint16_t>(mNs);
case mxINT8_CLASS:
return get_nums<int8_t>(mNs);
case mxUINT8_CLASS:
return get_nums<uint8_t>(mNs);
default:
throw mexception("repnum:invalidarg",
"ns should be a non-sparse numeric vector.");
}
}
void check_vs_size(const_marray mNs, const_marray mVs)
{
if (!(mVs.is_vector() && !mVs.is_sparse()))
{
throw mexception("repnum:invalidarg",
"vs should be a non-sparse numeric vector.");
}
if (mVs.nrows() != mNs.nrows() || mVs.ncolumns() != mVs.ncolumns())
{
throw mexception("repnum:invalidarg",
"The sizes of vs and ns are inconsistent.");
}
}
marray do_repnum(const_marray mNs)
{
array1d<int32_t> ns = do_get_nums(mNs);
index_t n = ns.nelems();
int32_t N = 0;
for (index_t i = 0; i < n; ++i) N += ns[i];
marray mR = mNs.nrows() == 1 ?
create_marray<double>(1, (size_t)N) :
create_marray<double>(N, (size_t)1);
double *r = mR.data<double>();
for (index_t i = 0; i < n; ++i)
{
double v = i + 1;
for (int32_t j = 0; j < ns(i); ++j)
{
*(r++) = v;
}
}
return mR;
}
template<typename T>
marray do_repnum_ex(const_marray mVs, const_marray mNs)
{
check_vs_size(mNs, mVs);
array1d<int32_t> ns = do_get_nums(mNs);
caview1d<T> vs = view1d<T>(mVs);
index_t n = ns.nelems();
int32_t N = 0;
for (index_t i = 0; i < n; ++i) N += ns[i];
marray mR = mNs.nrows() == 1 ?
create_marray<T>(1, N) :
create_marray<T>(N, 1);
T *r = mR.data<T>();
for (index_t i = 0; i < n; ++i)
{
T v = vs(i);
for (int32_t j = 0; j < ns(i); ++j)
{
*(r++) = v;
}
}
return mR;
}
/**
*
* main entry:
*
* Input:
* [0] - ns
*
* or
* [0] - vs, [1] - ns
*
* ns: the numbers of repeating times
* vs: the values to be repeated
*
* Output:
* [1]: r: the generated vector
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
marray mR;
if (nrhs == 1)
{
const_marray mNs(prhs[0]);
mR = do_repnum(mNs);
}
else if (nrhs == 2)
{
const_marray mVs(prhs[0]);
const_marray mNs(prhs[1]);
switch (mVs.class_id())
{
case mxDOUBLE_CLASS:
mR = do_repnum_ex<double>(mVs, mNs);
break;
case mxSINGLE_CLASS:
mR = do_repnum_ex<float>(mVs, mNs);
break;
case mxINT32_CLASS:
mR = do_repnum_ex<int32_t>(mVs, mNs);
break;
case mxUINT32_CLASS:
mR = do_repnum_ex<uint32_t>(mVs, mNs);
break;
case mxLOGICAL_CLASS:
mR = do_repnum_ex<bool>(mVs, mNs);
break;
case mxINT8_CLASS:
mR = do_repnum_ex<int8_t>(mVs, mNs);
break;
case mxUINT8_CLASS:
mR = do_repnum_ex<uint8_t>(mVs, mNs);
break;
case mxINT16_CLASS:
mR = do_repnum_ex<int16_t>(mVs, mNs);
break;
case mxUINT16_CLASS:
mR = do_repnum_ex<uint16_t>(mVs, mNs);
break;
default:
throw mexception("repnum:invalidarg",
"vs should be of numeric or logical type");
}
}
else
{
throw mexception("repnum:invalidarg",
"The number of inputs to repnum should be 1 or 2.");
}
plhs[0] = mR.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/matrix/repnum.cpp | C++ | mit | 5,217 |
function C = mmsum(As, Bs, W, op)
% Compute the (weighted) sum of matrix products
%
% C = mmsum(As, Bs, W);
% C = mmsum(As, Bs, W, op);
% compute the (weighted sum) of products between the matrices in
% As and Bs, according to the following formula.
%
% When op = 'NN':
% C = \sum_{i=1}^n w(i) * A_i * B_i,
% When op = 'NT':
% C = \sum_{i=1}^n w(i) * A_i * B_i',
% When op = 'TN':
% C = \sum_{i=1}^n w(i) * A_i' * B_i,
% When op = 'TT':
% C = \sum_{i=1}^n w(i) * A_i' * B_i.
%
% Here, A_i is given by As(:,:,i) and B_i is given by Bs(:,:,i).
% The weights are given by each row of W. W can be a matrix of
% size m x n, then in the output, C has size(C, 3) == 3, and
% C(:,:,k) is computed based on W(k,:).
%
% If W is empty, then there is only one group of weights, in
% which w(i) always equals 1.
%
% The user can input Bs as an empty array to indicate that As and
% Bs are the same. In such cases, more efficient implementation
% may be employed.
%
% If w is omitted or empty, then it assumes w(i) = 1 for all i.
% If op is omitted, then by default, it is set to 'NN'.
%
% History
% -------
% - Created by Dahua Lin, on Apr 5, 2010
% - Modified by Dahua Lin, on Apr 6, 2010
% - support multiple groups of weights.
% - Modified by Dahua Lin, on Apr 15, 2010
% - change error handling.
%
%% verify input arguments
if nargin < 4
op = 'NN';
else
if ~(ischar(op) && numel(op) == 2 && ...
(op(1) == 'N' || op(1) == 'T') && (op(2) == 'N' || op(2) == 'T'))
error('mmsum:invalidarg', ...
'The argument op should be either of ''NN'', ''NT'', ''TN'', ''NN''.');
end
end
if ~(isfloat(As) && ndims(As) <= 3)
error('mmsum:invalidarg', ...
'As should be a numeric array with ndims(As) <= 3.');
end
if ~isempty(Bs)
if ~(isfloat(Bs) && ndims(Bs) <= 3)
error('mmsum:invalidarg', ...
'Bs should be either empty or a numeric array with ndims(Bs) <= 3.');
end
if size(As, 3) ~= size(Bs, 3)
error('mmsum:invalidarg', ...
'As and Bs should have size(As, 3) == size(Bs, 3).');
end
end
% check the consistency of inner dimension
if op(1) == 'N'
di_a = size(As, 2);
else
di_a = size(As, 1);
end
if op(2) == 'N'
if isempty(Bs)
di_b = size(As, 1);
else
di_b = size(Bs, 1);
end
else
if isempty(Bs)
di_b = size(As, 2);
else
di_b = size(Bs, 2);
end
end
if di_a ~= di_b
error('mmsum:invalidarg', ...
'The inner dimension of As and Bs are inconsistent.');
end
n = size(As, 3);
if ~isempty(W)
if ~(isfloat(W) && ndims(W) == 2 && size(W,2) == n)
error('mmsum:invalidarg', 'W should be a numeric matrix with n columns.');
end
m = size(W, 1);
else
m = 1;
end
%% main
if isempty(Bs) && op(1) ~= op(2) % special case with faster implementation
if op(1) == 'N'
HA = horzc(As);
C = make_carr(HA, HA, W, n, di_a, 'NT');
else
VA = vertc(As);
C = make_carr(VA, VA, W, n, di_a, 'TN');
end
% ensure symmetry
if m == 1
C = 0.5 * (C + C');
else
for k = 1 : m
cC = C(:,:,k);
C(:,:,k) = 0.5 * (cC + cC');
end
end
else
if isempty(Bs)
Bs = As;
end
if op(1) == 'N'
if op(2) == 'N' % op = 'NN'
C = make_carr(horzc(As), vertc(Bs), W, n, di_a, 'NN');
else % op = 'NT'
C = make_carr(horzc(As), horzc(Bs), W, n, di_a, 'NT');
end
else
if op(2) == 'N' % op = 'TN'
C = make_carr(vertc(As), vertc(Bs), W, n, di_a, 'TN');
else % op = 'TT'
C = make_carr(vertc(As), horzc(Bs), W, n, di_a, 'TT');
end
end
end
%% Auxiliary functions
function Ae = horzc(As)
[p, q, n] = size(As);
if n == 1
Ae = As;
else
Ae = reshape(As, p, q * n);
end
function Ae = vertc(As)
[p, q, n] = size(As);
if n == 1
Ae = As;
else
I = reshape(1:q*n, q, n).';
Ae = reshape(As(:, I(:)), p * n, q);
end
function C = make_carr(A, B, W, n, di, op)
if isempty(W)
C = do_mm(A, B, op);
else
if di > 1
I = reshape(ones(di, 1) * (1:n), 1, n * di);
W = W(:, I);
end
m = size(W, 1);
if op(1) == 'T'
W = W.';
end
if m == 1
C = do_mm(bsxfun(@times, A, W), B, op);
else
if op(1) == 'N'
C1 = do_mm(bsxfun(@times, A, W(1,:)), B, op);
C = zeros([size(C1) m], class(C1));
C(:,:,1) = C1;
for k = 2 : m
C(:,:,k) = do_mm(bsxfun(@times, A, W(k,:)), B, op);
end
else
C1 = do_mm(bsxfun(@times, A, W(:, 1)), B, op);
C = zeros([size(C1) m], class(C1));
C(:,:,1) = C1;
for k = 2 : m
C(:,:,k) = do_mm(bsxfun(@times, A, W(:, k)), B, op);
end
end
end
end
function C = do_mm(A, B, op)
if op(1) == 'N'
if op(2) == 'N'
C = A * B;
else
C = A * B';
end
else
if op(2) == 'N'
C = A' * B;
else
C = (B * A)';
end
end
| zzhangumd-smitoolbox | base/matrix/mmsum.m | MATLAB | mit | 5,608 |
function test_mat2x2c(varargin)
% Test the correctness of implementation of 2 x 2 matric computation
%
% test_mat2x2c item1 item2 ...
%
% item is the name of the computation to be tested, which can be
% either of the following values:
% 'inv': matrix inverse
% 'det': matrix determinant
% 'trace': matrix trace
% 'polarm': polar representation
% 'sqrtm': matrix square root
% 'chol': Cholesky decomposition
%
% Created by Dahua Lin, on Apr 7, 2010
%
%% verify input arguments
assert(iscellstr(varargin) && ...
all(ismember(varargin, {'inv', 'det', 'trace', 'polarm', 'sqrtm', 'chol'})), ...
'test_mat2x2c:invalidarg', ...
'Invalid item.');
%% main skeleton
items = varargin;
n = length(items);
for i = 1 : n
item = items{i};
feval(['test_' item]);
end
%% Test functions
function test_inv() %#ok<DEFNU>
n = 1000;
X1 = gen_gm(n);
% test 4 x n form
R1 = inv2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(R1), [4 n1]));
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
R2 = inv2x2(X2);
assert(isequal(size(R2), [2 2 n1]));
assert(isequal(R1, reshape(R2, [4 n1])));
% test 3 x n form
X3 = gen_pdm(n);
n3 = size(X3, 2);
R3 = inv2x2(X3);
assert(isequal(size(R3), [3 n3]));
X4 = reshape(X3([1 2 2 3], :), [2 2 n3]);
R4 = reshape(R3([1 2 2 3], :), [2 2 n3]);
% compare result
Z20 = [ones(1, n1); zeros(1, n1); zeros(1, n1); ones(1, n1)];
Z2 = zeros(4, n1);
for i = 1 : n1
M = 0.5 * (R2(:,:,i) * X2(:,:,i) + X2(:,:,i) * R2(:,:,i));
Z2(:,i) = M(:);
end
Z40 = [ones(1, n3); zeros(1, n3); zeros(1, n3); ones(1, n3)];
Z4 = zeros(4, n3);
for i = 1 : n3
M = 0.5 * (R4(:,:,i) * X4(:,:,i) + X4(:,:,i) * R4(:,:,i));
Z4(:,i) = M(:);
end
compare('inv_gm', Z20, Z2, 5e-12);
compare('inv_sm', Z40, Z4, 5e-12);
function test_det() %#ok<DEFNU>
n = 1000;
X1 = gen_gm(n);
% test 4 x n form
r1 = det2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(r1), [1 n1]));
r10 = X1(1,:) .* X1(4,:) - X1(2,:) .* X1(3,:);
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
r2 = det2x2(X2);
assert(isequal(size(r2), [1 n1]));
assert(isequal(r1, r2));
% test 3 x n form
X3 = gen_pdm(n);
n3 = size(X3, 2);
r3 = det2x2(X3);
assert(isequal(size(r3), [1 n3]));
r30 = X3(1,:) .* X3(3,:) - X3(2,:) .* X3(2,:);
% compare result
compare('det_gm', r10, r1, 1e-15);
compare('det_sm', r30, r3, 1e-15);
function test_trace() %#ok<DEFNU>
n = 1000;
X1 = gen_gm(n);
% test 4 x n form
r1 = trace2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(r1), [1 n1]));
r10 = X1(1,:) + X1(4,:);
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
r2 = trace2x2(X2);
assert(isequal(size(r2), [1 n1]));
assert(isequal(r1, r2));
% test 3 x n form
X3 = gen_pdm(n);
n3 = size(X3, 2);
r3 = trace2x2(X3);
assert(isequal(size(r3), [1 n3]));
r30 = X3(1,:) + X3(3,:);
% compare result
compare('trace_gm', r10, r1, 1e-15);
compare('trace_sm', r30, r3, 1e-15);
function test_polarm() %#ok<DEFNU>
n = 1000;
X0 = gen_pdm(n);
% test 4 x n form
X1 = X0([1 2 2 3], :);
R1 = polarm2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(R1), [3 n1]));
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
R2 = polarm2x2(X2);
assert(isequal(size(R2), [3 n1]));
% test 3 x n form
X3 = X0;
R3 = polarm2x2(X3);
assert(isequal(size(R3), [3 n1]));
assert(isequal(R1, R2, R3));
assert(all(R1(1,:) >= R1(2,:)));
% generate ground-truth
M0 = X2;
M1 = zeros(size(M0));
for i = 1 : n1
M1(:,:,i) = from_polar(R1(:,i));
end
% compare result
compare('polarm_sm', M0, M1, 2e-14);
function test_sqrtm() %#ok<DEFNU>
n = 1000;
X0 = gen_pdm(n);
% test 4 x n form
X1 = X0([1 2 2 3], :);
R1 = sqrtm2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(R1), [4 n1]));
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
R2 = sqrtm2x2(X2);
assert(isequal(size(R2), [2 2 n1]));
% test 3 x n form
X3 = X0;
R3 = sqrtm2x2(X3);
assert(isequal(size(R3), [3 n1]));
R2a = reshape(R2, 4, n1);
assert(isequal(R1, R2a, R3([1 2 2 3], :)));
% generate ground-truth
M0 = X2;
M1 = zeros(size(M0));
for i = 1 : n1
M1(:,:,i) = R2(:,:,i) * R2(:,:,i);
end
% compare result
compare('sqrtm_sm', M0, M1, 2e-14);
function test_chol() %#ok<DEFNU>
n = 1000;
X0 = gen_pdm(n);
% test 4 x n form
X1 = X0([1 2 2 3], :);
R1 = chol2x2(X1);
n1 = size(X1, 2);
assert(isequal(size(R1), [4 n1]));
assert(all(R1(3, :) == 0));
% test 2 x 2 x n form
X2 = reshape(X1, [2 2 n1]);
R2 = chol2x2(X2);
assert(isequal(size(R2), [2 2 n1]));
% test 3 x n form
X3 = X0;
R3 = chol2x2(X3);
assert(isequal(size(R3), [3 n1]));
R2a = reshape(R2, 4, n1);
R3a = [R3(1:2, :); zeros(1, n1); R3(3,:)];
assert(isequal(R1, R2a, R3a));
% generate ground-truth
M0 = X2;
M1 = zeros(size(M0));
for i = 1 : n1
M1(:,:,i) = R2(:,:,i) * R2(:,:,i)';
end
% compare result
compare('chol_sm', M0, M1, 2e-14);
%% Data generation
function X = gen_gm(n)
% generate a batch of generic matrix
X = randn(4, n);
dv = X(1,:) .* X(4,:) - X(2,:) .* X(3,:);
si = abs(dv) > 1e-3;
X = X(:, si);
function X = gen_pdm(n)
% generate a batch of positive definite matrix
X = randn(2, 2, n);
for i = 1 : n
X(:,:,i) = X(:,:,i) * X(:,:,i)';
end
X = reshape(X, 4, n);
X = X([1 2 4], :);
dv = X(1,:) .* X(3,:) - X(2,:).^2;
si = abs(dv) > 1e-3;
X = X(:, si);
function M = from_polar(p)
a = p(1);
b = p(2);
t = p(3);
c = cos(t);
s = sin(t);
R = [c -s; s c];
M = R * [a 0; 0 b] * R';
%% Auxiliary functions
function compare(title, A, B, thres)
d = max(abs(A(:) - B(:)));
if d > thres
warning('test_mat2x2c:largedev', ...
'Large observation observed for %s (dev = %g)', title, d);
end
| zzhangumd-smitoolbox | base/matrix/test_mat2x2c.m | MATLAB | mit | 5,605 |
function Y = mmvmult(A, X)
%MMVMULT Performs multiple matrix-vector multiplication
%
% Y = mmvmult(A, X);
% performs multiple matrix-vector multiplication.
% Here, A should be an array of size p x q x n, and X of size q x n,
% then Y is of size p x n, such that
%
% Y(:,i) = A(:,:,i) * X(:,i).
%
% History
% -------
% - Created by Dahua Lin, on Apr 4, 2010
% - Modified by Dahua Lin, on June 11, 2010
% - change the error handling.
%
%% verify input arguments
if ~(isfloat(A) && ndims(A) <= 3)
error('mmvmult:invalidarg', ...
'A should be a numeric array with ndims(A) <= 3');
end
[p, q, n] = size(A);
if ~(isfloat(X) && isequal(size(X), [q n]))
error('mmvmult:invalidarg', ...
'X should be a numeric matrix of size q x n.');
end
%% main
if p == 1
Y = sum(reshape(A, q, n) .* X, 1);
elseif q == 1
Y = bsxfun(@times, reshape(A, p, n), X);
elseif p < n && p < q % small output dimension
Y = zeros(p, n, class(A(1) * X(1)));
for k = 1 : p
Y(k, :) = sum(reshape(A(k,:,:), q, n) .* X, 1);
end
elseif q < n && q < p % small input dimension
Y = bsxfun(@times, reshape(A(:,1,:), p, n), X(1, :));
for k = 2 : q
Y = Y + bsxfun(@times, reshape(A(:,k,:), p, n), X(k, :));
end
else % large output dimension
Y = zeros(p, n, class(A(1) * X(1)));
for i = 1 : n
Y(:,i) = A(:,:,i) * X(:,i);
end
end
| zzhangumd-smitoolbox | base/matrix/mmvmult.m | MATLAB | mit | 1,536 |
function A = constmat(m, n, v)
% Create a matrix whose entries are fixed to a constant value
%
% A = constmat(m, n, v);
% creates a matrix of size m x n, whose entries are fixed to
% a constant value v.
%
% The class of matrix A is is the same as the class of v,
% which can be either numeric or logical.
%
% Example:
%
% A = constmat(2, 3, 10);
%
% it returns a matrix A as [10 10 10; 10 10 10]
%
% History
% -------
% - Created by Dahua Lin, on Jun 5, 2010
%
%% verify input
if ~isscalar(v)
error('constmat:invalidarg', 'v should be a scalar value.');
end
%% main
if isnumeric(v)
A = zeros(m, n, class(v));
A(:) = v;
elseif islogical(v)
if v
A = true(m, n);
else
A = false(m, n);
end
else
error('constmat:invalidarg', ...
'v should be either a numeric or a logical value.');
end
| zzhangumd-smitoolbox | base/matrix/constmat.m | MATLAB | mit | 904 |
% Derive the polar representation of a 2 x 2 positive definite matrix
%
% R = polarm2x2(A);
% computes the polar representation of a 2x2 positive matrix A.
% Each polar representation is a column vector with three
% entries [a; b; theta], such that
%
% A = R * diag([a b]) * R',
%
% where R = [cos(theta), -sin(theta); sin(theta), cos(theta)].
%
% A can be in either of the following forms:
% - 2 x 2 matrix
% - 2 x 2 x n array, with each page being a matrix
% - 2 x (2 x n) matrix, with all matrices juxtaposed
% - 4 x n matrix, each column represents a matrix
% as [a(1,1), a(2,1), a(1,2), a(2,2)].
% - 3 x n matrix, each column represents a symmetric matrix
% as [a(1,1), a(1,2), a(2,2)].
%
% For any input, the output will be a matrix of size 3 x n, where
% R(:, i) corresponds to the i-th matrix.
%
% History
% -------
% - Created by Dahua Lin, on June 11, 2010
%
| zzhangumd-smitoolbox | base/matrix/polarm2x2.m | MATLAB | mit | 983 |
function R = rotmat2(t)
% Gets the rotation matrix given radius values
%
% R = rotmat2(t)
% Returns the rotation matrix [cos(t) -sin(t); sin(t) cos(t)].
% If t contains m elements, then R is a 2 x 2 x m array, with
% R(:,;,i) corresponding to t(i).
%
% History
% -------
% - Created by Dahua Lin, on Apr 7, 2010
%
%% verify input arguments
if ~(isfloat(t) && isvector(t))
error('rotmat2:invalidarg', 't should be a numeric vector.');
end
m = numel(t);
%% compute
if size(t, 1) > 1
t = t.';
end
c = cos(t);
s = sin(t);
if m == 1
R = [c -s; s c];
else
R = reshape([c; s; -s; c], [2 2 m]);
end
| zzhangumd-smitoolbox | base/matrix/rotmat2.m | MATLAB | mit | 645 |
function M = spdiag(v1, v2)
% Creates a sparse diagonal matrix
%
% M = spdiag(dv);
% creates a diagonal matrix with the diagonal elements given by dv.
% Suppose dv is a vector of length n, then M is an n x n matrix,
% with M(i,i) equaling dv(i).
%
% M = spdiag(n, v);
% creates an n x n diagonal matrix with each diagonal element being
% v. Here v is a scalar.
%
% History
% -------
% - Created by Dahua Lin, on Apr 17, 2010
%
%% main
if nargin == 1
dv = v1;
if ~isvector(dv)
error('spdiag:invalidarg', 'dv should be a vector.');
end
n = numel(dv);
if size(dv, 1) > 1
dv = dv.';
end
M = sparse(1:n, 1:n, dv, n, n);
elseif nargin == 2
n = v1;
v = v2;
if ~isscalar(v)
error('spdiag:invalidarg', 'v should be a scalar.');
end
M = sparse(1:n, 1:n, v, n, n);
end
| zzhangumd-smitoolbox | base/matrix/spdiag.m | MATLAB | mit | 924 |
function C = mat2_by_polar(a, b, theta)
% Create 2x2 positive definite matrices from the polar representation
%
% C = mat2_by_polar(a, b, theta);
% creates a 2 x 2 positive definite matrix as
%
% C = R * diag([a b]) * R'.
%
% Here, R is a rotation matrix given by R = rotmat2(theta).
%
% a, b, and theta can be vectors of n elements, then C is an
% array of size 2 x 2 x n, with C(:,:,i) derived from
% a(i), b(i), and theta(i).
%
% History
% -------
% - Created by Dahua Lin, on Jun 11, 2010
%
%% main
if ~(isfloat(a) && isfloat(b) && isfloat(theta))
error('mat2_by_polar:invalidarg', ...
'a, b, and theta should be numeric scalars or vectors.');
end
if isscalar(a) && isscalar(b) && isscalar(theta)
c = cos(theta);
s = sin(theta);
cc = c * c;
ss = s * s;
cs = c * s;
C = [a * cc + b * ss, (a-b) * cs; (a-b) * cs, a * ss + b * cc];
elseif isvector(a) && isequal(size(a), size(b), size(theta))
c = cos(theta);
s = sin(theta);
cc = c .^ 2;
ss = s .^ 2;
cs = c .* s;
v1 = a .* cc + b .* ss;
v2 = (a - b) .* cs;
v3 = a .* ss + b .* cc;
C = reshape([v1; v2; v2; v3], [2 2 numel(a)]);
else
error('mat2_by_polar:invalidarg', ...
'a, b, and theta should be numeric scalars or vectors of the same size.');
end
| zzhangumd-smitoolbox | base/matrix/mat2_by_polar.m | MATLAB | mit | 1,437 |
/********************************************************************
*
* smi_graph_mex.h
*
* The mex interface for SMI graphs
*
* Created by Dahua Lin, on Oct 28, 2011
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <bcslib/graph/gedgelist_view.h>
#include <bcslib/graph/ginclist_view.h>
namespace smi
{
// Typedefs
typedef bcs::int32_t gint;
typedef bcs::gvertex<gint> vertex_t;
typedef bcs::gedge<gint> edge_t;
typedef bcs::gvertex_pair<gint> vertex_pair;
typedef bcs::gedgelist_view<gint> gedgelist_t;
typedef bcs::ginclist_view<gint> ginclist_t;
typedef bcs::natural_vertex_iterator<gint>::type natural_viter_t;
typedef bcs::natural_edge_iterator<gint>::type natural_eiter_t;
// Interoperability
bool isdirected_from_char(char dty)
{
return dty == 'd' || dty == 'D';
}
inline gedgelist_t mx_to_gedgelist(bcs::matlab::const_marray mG)
{
char dty = (char)mG.get_field(0, "dty").get_scalar<mxChar>();
gint n = mG.get_field(0, "n").get_scalar<gint>();
gint m = mG.get_field(0, "m").get_scalar<gint>();
const vertex_pair* edges = mG.get_field(0, "edges").data<vertex_pair>();
bool is_dir = isdirected_from_char(dty);
return gedgelist_t(n, m, is_dir, edges);
}
inline ginclist_t mx_to_ginclist(bcs::matlab::const_marray mG)
{
char dty = (char)mG.get_field(0, "dty").get_scalar<mxChar>();
gint n = mG.get_field(0, "n").get_scalar<gint>();
gint m = mG.get_field(0, "m").get_scalar<gint>();
const vertex_pair* edges = mG.get_field(0, "edges").data<vertex_pair>();
const vertex_t* nbs = mG.get_field(0, "o_nbs").data<vertex_t>();
const edge_t* eds = mG.get_field(0, "o_eds").data<edge_t>();
const gint* degs = mG.get_field(0, "o_degs").data<gint>();
const gint* ofs = mG.get_field(0, "o_os").data<gint>();
bool is_dir = isdirected_from_char(dty);
return ginclist_t(n, m, is_dir, edges, nbs, eds, degs, ofs);
}
} // end namespace smi
| zzhangumd-smitoolbox | graph/clib/smi_graph_mex.h | C++ | mit | 2,027 |
function X = gsembed(g, w, d, k0)
% Spectral embedding of a graph
%
% X = gsembed(g, w, d);
% computes the d-dimensional embedded coordinates of a graph,
% which correspond to the d smallest eigenvalues of the Laplacian
% matrix.
%
% w is the edge weights, which can be either a scalar or a
% vector of length m.
%
% The output X is an n x d matrix, where X(i,:) gives the coordinate
% of the i-th vertex.
%
% X = gsembed(g, w, d, k0);
% extracts the eigenvectors corresponding to (d + k0) smallest one,
% and discards the k0 smallest, returning the remaining.
%
% Created by Dahua Lin, on Nov 5, 2010
%
%% main
if nargin < 4
k0 = 0;
end
L = laplacemat(g, w, 1e-10);
[X, D] = eigs(L, d+k0, 'sm');
dvs = diag(D);
[~, si] = sort(dvs, 1, 'ascend');
X = X(:, si(k0+1:k0+d));
| zzhangumd-smitoolbox | graph/spectral/gsembed.m | MATLAB | mit | 842 |
function laplacesm1d_demo(x0, sigma, w)
% A function to demo 1D Laplacian smoothing
%
% laplacesm1d_demo(x0, noise_mag, mker);
%
% Inputs:
% x0: the sequence of values (not corruped by noise)
% sigma: the standard deviation of noise
% w: the neighboring link weights (size 1 x r)
%
% History
% -------
% - Created by Dahua Lin, on Sep 19, 2010
% - Modified by Dahua Lin, on Nov 2, 2010
% - Modified by Dahua Lin, on Nov 13, 2010
%
%% verify input
if ~(isfloat(x0) && isvector(x0))
error('laplacesm1d_demo:invalidarg', ...
'x0 should be a numeric vector.');
end
if size(x0, 2) > 1
x0 = x0.';
end
if ~(isfloat(sigma) && isscalar(sigma))
error('laplacesm1d_demo:invalidarg', ...
'sigma should be a numeric scalar.');
end
if nargin < 3
w = 1;
else
if ~(isfloat(w) && isreal(w) && ndims(w) == 2 && size(w,1) == 1)
error('laplacemat1d_demo:invalidarg', ...
'w should be a real row vector.');
end
w = w.';
end
r = numel(w);
%% main
% prepare data
n = length(x0);
x = x0 + randn(size(x0)) * sigma;
% construct MRF
[gb, dx] = gr_local(n, r);
ws = repmat(w(abs(dx)), 1, n);
[Gs, ws] = gr_sym(gb, ws, 'max');
% do smooth
a = 1;
xs = laplacesm(Gs, ws, a, x);
% visualize
figure;
plot(x, 'b.', 'MarkerSize', 3);
hold on; plot(x0, 'g-');
hold on; plot(xs, 'r-');
| zzhangumd-smitoolbox | graph/spectral/laplacesm1d_demo.m | MATLAB | mit | 1,398 |
function x = laplacesm(G, w, a, y)
% Performs Laplacian smooth based on a Gaussian MRF
%
% The problem formulation is to minimize the following objective
% function with respect to X:
%
% (1/2) * sum_e w_e ||X(:,e_i) - X(:,e_j)||^2
% + (1/2) * sum_i (1/2) * a_i ||X(:,i) - Y(:,i)||^2.
%
% x = laplacesm(g, w, a, y);
% solves the problem above using (regularized) Laplacian matrix.
%
% Inputs:
% - G: the input graph, in form of either an object of class
% gr_edgelist, or an affinity matrix
% - w: the edge weight vector.
% - a: the regularization coefficients, in form of either
% a scalar or a vector of length n.
% - y: the observation, which can be either a column vector of
% length n, or multiple column vectors arranged into an
% n x K matrix.
%
% Output:
% - x: a matrix of the same size as y (n x K), x(:,k) corresponds
% to the solution based on y(:,k).
%
% History
% -------
% - Created by Dahua Lin, on Apr 17, 2010
% - Modified by Dahua Lin, on Nov 2, 2010
% - based on new graph struct
% - Modified by Dahua Lin, on Nov 13, 2010
% - based on new graph class
% - Modified by Dahua Lin, on Nov 19, 2011
% - based on new graph struct
%
%% verify input
if ~(isfloat(y) && isreal(y) && ndims(y) == 2 && size(y,1) == G.n)
error('laplacesm:invalidarg', 'y should be a real matrix with n rows.');
end
%% main
L = laplacemat(G, w, a); % this will verify the validity of g and a
if size(a, 2) > 1; a = a.'; end % turns a into a column vector
K = size(y, 2);
if K == 1 || isscalar(a)
ay = a .* y;
else
ay = bsxfun(@times, a, y);
end
x = L \ ay;
| zzhangumd-smitoolbox | graph/spectral/laplacesm.m | MATLAB | mit | 1,801 |
function L = laplacemat(varargin)
% Compute the Laplacian matrix of a graph
%
% L = laplacemat(g);
% L = laplacemat(g, w);
% L = laplacemat(g, w, a);
%
% Computes the (regularized) Laplacian matrix for graph G.
%
% Suppose A is the affinity matrix of G, and d is the vector
% of weighted degrees. Then the Laplacian matrix is defined
% as follows:
%
% L = diag(d + a) - A;
%
% Input arguments:
% - g: the graph struct (yielded by make_gr), with g.dty = 'u'
% - w: the edge weights (can be either a scalar or a vector of
% length m)
% - a: the regularization values to be added to the diagonal
% entries (a scalar or a vector of length n)
%
% In the output, L will be a sparse matrix of size n x n.
%
% L = laplacemat(W);
% L = laplacemat(W, a);
%
% Computes the Laplacian matrix based on the edge weight matrix
% W. Here, a is the regularization coefficient (scalar or
% vector).
%
% History
% -------
% - Created by Dahua Lin, on Apr 17, 2010
% - Modified by Dahua Lin, on Nov 2, 2010
% - support new graph structs.
% - Modified by Dahua Lin, on Nov 13, 2010
% - based on new graph class
% - Modified by Dahua Lin, on Oct 27, 2011
% - based on new graph struct.
%
%% verify input arguments
arg1 = varargin{1};
if isstruct(arg1)
g = varargin{1};
if nargin < 2
w = 1;
else
w = varargin{2};
end
if nargin < 3
a = [];
else
a = varargin{3};
end
if ~(is_gr(g) && g.dty == 'u')
error('laplacemat:invalidarg', ...
'g should be an undirected graph struct.');
end
n = double(g.n);
if ~(isfloat(w) && (isscalar(w) || (isvector(w) && numel(w) == g.m)))
error('laplacemat:invalidarg', ...
'w should be a numeric vector of length g.m.');
end
is_wmat = false;
elseif isnumeric(arg1) || islogical(arg1)
W = varargin{1};
n = size(W, 1);
if ~(ndims(W) == 2 && size(W, 2) == n)
error('laplacemat:invalidarg', ...
'W should be a square matrix.');
end
if nargin < 2
a = [];
else
a = varargin{2};
end
is_wmat = true;
else
error('laplacemat:invalidarg', ...
'The 1st argument to laplacemat is invalid.');
end
if ~isempty(a)
if ~(isfloat(a) && (isscalar(a) || (isvector(a) && numel(a) == n)))
error('laplacemat:invalidarg', ...
'a should be a numeric vector of length n.');
end
if size(a, 2) > 1; a = a.'; end
if ~isa(a, 'double'); a = double(a); end
end
%% main
if is_wmat
if issparse(W)
if islogical(W)
[i, j] = find(W);
L = make_spL(n, i, j, 1, a);
else
[i, j, w] = find(W);
L = make_spL(n, i, j, w, a);
end
else
L = -W;
dv = sum(W, 1);
if ~isempty(a)
dv = dv + a;
end
dind = 1 : n+1 : n*n;
L(dind) = L(dind) + dv;
end
else
s = double(g.edges(1,:)).';
t = double(g.edges(2,:)).';
if isscalar(w)
L = make_spL(n, s, t, w, a);
else
if size(w, 2) > 1; w = w.'; end
L = make_spL(n, s, t, [w; w], a);
end
end
%% sub function
function L = make_spL(n, s, t, w, a)
if isscalar(w)
dv = w * intcount(n, s).';
else
dv = aggreg(w, n, s, 'sum');
end
if ~isempty(a)
dv = dv + a;
end
m = numel(s);
if isscalar(w)
w = w(ones(1,m), 1);
end
if isscalar(dv)
dv = dv(ones(1,n), 1);
end
i = [s; (1:n).'];
j = [t; (1:n).'];
v = [-w; dv];
L = sparse(i, j, v, n, n);
| zzhangumd-smitoolbox | graph/spectral/laplacemat.m | MATLAB | mit | 3,788 |
function [x, energy] = minenergy_graphcut(g, w, cp, cn)
%MINENERGY_GRAPHCUT Energy minimization via Graph-cut
%
% [x, energy] = MINENERGY_GRAPHCUT(g, w, cp, cn);
%
% Solves the following energy minimization problem using minimum
% graph cut algorithm.
%
% minimize E(L) = sum_{i in V} cp(i) * I(x_i == 1)
% + sum_{i in V} cn(i) * I(x_i == -1)
% + sum_{(i,j) in E} w_ij I(x_i <> x_j)
%
% x_i can take value of either 1 or -1.
%
% Here, all coefficients cp(i), cn(i), and w_ij need to be
% non-negative.
%
%
% Input arguments:
% - g: The underlying undirected graph
%
% - w: The edge weights (for encouraging smoothness), which
% can be either a scalar or a vector of length g.m.
%
% - cp: The costs of assigning 1 to each vertex.
% (either a scalar or a vector of length g.n)
%
% - cn: The costs of assigning -1 to each vertex.
% (either a scalar or a vector of length g.n)
%
% Output arguments:
% - x: The solution vector [1 x n int32].
% x(i) can be either 1, -1 or 0.
% x(i) == 0 indicates that one can assign either 1 or
% -1 to x(i).
%
% - energy: The minimum energy value.
%
% Created by Dahua Lin, on Jan 29, 2011
%
%% verify input arguments
if ~(is_gr(g) && isequal(g.dty, 'u'))
error('minenergy_graphcut:invalidarg', ...
'g should be a graph struct (for undirected graph).');
end
w = check_cvec('w', w, g.m);
cp = check_cvec('cp', cp, g.n);
cn = check_cvec('cn', cn, g.n);
%% main
[x, energy] = kolmogorov_mincut(g, w, cn, cp);
%% auxiliary functions
function v = check_cvec(name, v, n)
if ~(isfloat(v) && (isscalar(v) || (isvector(v) && isreal(v) && numel(v) == n)))
error('minenergy_graphcut:invalidarg', ...
'%s should be either a scalar or a vector of proper length.', name);
end
if ~all(v >= 0)
error('minenergy_graphcut:invalidarg', ...
'All values in %s need to be non-negative.', name);
end
if isscalar(v)
v = v(ones(1, n));
end
| zzhangumd-smitoolbox | graph/flows/minenergy_graphcut.m | MATLAB | mit | 2,222 |
function [L, cutv] = kolmogorov_mincut(g, caps, src_cap, snk_cap)
%KOLMOGOROV_MINCUT Kolmogorov's Mincut Algorithm
%
% [L, cutv] = KOLMOGOROV_MINCUT(g, caps, src_cap, snk_cap);
% [L, cutv] = KOLMOGOROV_MINCUT(g, caps, tcap);
%
%
% Solve the mincut of a weighted graph, using Kolmogorov's mincut
% algorithm.
%
% Input arguments:
% - g: The graph stuct.
%
% If g is an undirected graph, then each edge
% is associated with capacities in both
% directions.
%
% - caps: The vector of capacities of neighboring links
% (length = g.m)
%
% - src_cap: The capacities from source to all nodes
% (length = g.n)
%
% - dst_cap: The capacities from all nodes to sink
% (length = g.n)
%
% - tcap: The signed capacities from/to terminals.
% (positive: from source, negative: to sink)
%
% Output arguments:
% - L: The resulting label vector.
% L(i) = 1: if node i is assigned to source
% L(i) = -1: if node i is assigned to sink
% L(i) = 0: node i can be assigned to either.
%
% - cutv: The total cut value of the minimum cut.
%
% Created by Dahua Lin, on Jan 29, 2011
%
%% verify input
if ~is_gr(g)
error('kolmogorov_mincut:invalidarg', 'g should be a graph struct.');
end
n = double(g.n);
m = double(g.m);
if ~(isnumeric(caps) && isreal(caps) && isvector(caps) && numel(caps) == g.m)
error('kolmogorov_mincut:invalidarg', ...
'caps should be a real vector of length m.');
end
if nargin == 3
tcap = src_cap;
if ~(isnumeric(tcap) && isreal(tcap) && isvector(tcap) && numel(tcap) == n)
error('kolmogorov_mincut:invalidarg', ...
'tcap should be a real vector of length n.');
end
src_cap(tcap < 0) = 0;
snk_cap = zeros(size(tcap), class(tcap));
snk_cap(tcap < 0) = -tcap(tcap < 0);
else
if ~(isnumeric(src_cap) && isreal(src_cap) && isvector(src_cap) && numel(src_cap) == n)
error('kolmogorov_mincut:invalidarg', ...
'src_cap should be a real vector of length n.');
end
if ~(isnumeric(snk_cap) && isreal(snk_cap) && isvector(snk_cap) && numel(snk_cap) == n)
error('kolmogorov_mincut:invalidarg', ...
'snk_cap should be a real vector of length n.');
end
end
%% main
if g.dty == 'u'
nb_cap = caps;
rv_cap = caps;
else
nb_cap = caps;
rv_cap = zeros(size(caps), class(caps));
end
sv = g.edges(1, 1:g.m);
tv = g.edges(2, 1:g.m);
[L, cutv] = kolmogorov_mincut_cimp(n, m, sv, tv, nb_cap, rv_cap, src_cap, snk_cap);
| zzhangumd-smitoolbox | graph/flows/kolmogorov_mincut.m | MATLAB | mit | 2,895 |
/**********************************************************
*
* kolmogorov_mincut_cimp.cpp
*
* A C++ mex wrapper of Kolmogorov's mincut implementation
* (based on maxflow v3.01)
*
* Created by Dahua Lin, on Jan 29, 2012
*
**********************************************************/
#include <mex.h>
#include "kolmogorov_maxflow.h"
inline mxClassID decide_capacity_type(
const mxArray *mxNc,
const mxArray *mxRc,
const mxArray *mxTcSrc,
const mxArray *mxTcSnk)
{
mxClassID cid_nc = mxGetClassID(mxNc);
mxClassID cid_rc = mxGetClassID(mxRc);
mxClassID cid_tsrc = mxGetClassID(mxTcSrc);
mxClassID cid_tsnk = mxGetClassID(mxTcSnk);
if (!(cid_nc == cid_rc && cid_rc == cid_tsrc && cid_tsrc == cid_tsnk))
{
mexErrMsgIdAndTxt("kolmogorov_mincut:invalidarg",
"The neighbor-link capacities and terminal-link capacities have different types.");
}
return cid_nc;
}
template<typename T>
void do_cut(mxClassID cid, int n, int m, const int *sv, const int *tv,
const T* nb_cap, const T* rv_cap, const T* tsrc_cap, const T* tsnk_cap,
mxArray *plhs[])
{
typedef vkol::Graph<T,T,T> vk_graph_t;
// construct graph
vk_graph_t G(n, m);
G.add_node(n);
// add terminal capacities
for (int i = 0; i < n; ++i)
{
T src_c = tsrc_cap[i];
T snk_c = tsnk_cap[i];
if (src_c > 0 || snk_c > 0)
{
G.add_tweights(i, src_c, snk_c);
}
}
// add neighboring capacities
for (int i = 0; i < m; ++i)
{
T nb_c = nb_cap[i];
T rv_c = rv_cap[i];
if (nb_c > 0 || rv_c > 0)
{
G.add_edge(sv[i]-1, tv[i]-1, nb_c, rv_c);
}
}
// solve max-flow
T fv = G.maxflow();
// extract results
mxArray *mxL = mxCreateNumericMatrix(1, n, mxINT32_CLASS, mxREAL);
int *L = (int*)mxGetData(mxL);
for (int i = 0; i < n; ++i)
{
L[i] = G.what_segment_ex(i);
}
mxArray *mxFlow = mxCreateNumericMatrix(1, 1, cid, mxREAL);
*((T*)mxGetData(mxFlow)) = fv;
plhs[0] = mxL;
plhs[1] = mxFlow;
}
/**
* Input
* [0] n: The number of vertices [double]
* [1] m: The number of links [double]
* [2] sv: The vector of source vertices of edges [int32 one-based]
* [3] tv: The vector of target vertices of edges [int32 one-based]
* [4] nc: The capacities of neighboring-links
* [5] rc: The reverse capacities of neighboring-links
* [6] tc_src: The capacities of links from source
* [7] tc_snk: The capacities of links from sink
*
* Note the type of nc can be double|single|int32|uint32, tc should be
* of the same type as nc
*
* Output
* [0] L: The labeling of the nodes [int32 1 x n]
* - 1: assigned to source
* - -1: assigned to sink
* - 0: can be assigned to either source or sink
*
* [1] maxflow: The value of maxflow
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const mxArray *mxN = prhs[0];
const mxArray *mxM = prhs[1];
const mxArray *mxSv = prhs[2];
const mxArray *mxTv = prhs[3];
const mxArray *mxNc = prhs[4];
const mxArray *mxRc = prhs[5];
const mxArray *mxTcSrc = prhs[6];
const mxArray *mxTcSnk = prhs[7];
int n = (int)mxGetScalar(mxN);
int m = (int)mxGetScalar(mxM);
const int *sv = (const int*)mxGetData(mxSv);
const int *tv = (const int*)mxGetData(mxTv);
mxClassID cid = decide_capacity_type(mxNc, mxRc, mxTcSrc, mxTcSnk);
switch (cid)
{
case mxDOUBLE_CLASS:
{
const double *nb_cap = (const double*)mxGetData(mxNc);
const double *rv_cap = (const double*)mxGetData(mxRc);
const double *tsrc_cap = (const double*)mxGetData(mxTcSrc);
const double *tsnk_cap = (const double*)mxGetData(mxTcSnk);
do_cut(cid, n, m, sv, tv, nb_cap, rv_cap, tsrc_cap, tsnk_cap, plhs);
}
break;
case mxSINGLE_CLASS:
{
const float *nb_cap = (const float*)mxGetData(mxNc);
const float *rv_cap = (const float*)mxGetData(mxRc);
const float *tsrc_cap = (const float*)mxGetData(mxTcSrc);
const float *tsnk_cap = (const float*)mxGetData(mxTcSnk);
do_cut(cid, n, m, sv, tv, nb_cap, rv_cap, tsrc_cap, tsnk_cap, plhs);
}
break;
case mxINT32_CLASS:
{
const int *nb_cap = (const int*)mxGetData(mxNc);
const int *rv_cap = (const int*)mxGetData(mxRc);
const int *tsrc_cap = (const int*)mxGetData(mxTcSrc);
const int *tsnk_cap = (const int*)mxGetData(mxTcSnk);
do_cut(cid, n, m, sv, tv, nb_cap, rv_cap, tsrc_cap, tsnk_cap, plhs);
}
break;
case mxUINT32_CLASS:
{
const unsigned int *nb_cap = (const unsigned int*)mxGetData(mxNc);
const unsigned int *rv_cap = (const unsigned int*)mxGetData(mxRc);
const unsigned int *tsrc_cap = (const unsigned int*)mxGetData(mxTcSrc);
const unsigned int *tsnk_cap = (const unsigned int*)mxGetData(mxTcSnk);
do_cut(cid, n, m, sv, tv, nb_cap, rv_cap, tsrc_cap, tsnk_cap, plhs);
}
break;
default:
mexErrMsgIdAndTxt("kolmogorov_mincut:invalidarg",
"The capacity type is unsupported.");
}
}
| zzhangumd-smitoolbox | graph/flows/private/kolmogorov_mincut_cimp.cpp | C++ | mit | 5,915 |
/*
This is a re-package of the files in maxflow-v3.01 which was
implemented by Vladimir Kolmogorov.
This software library implements the maxflow algorithm
described in
"An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision."
Yuri Boykov and Vladimir Kolmogorov.
In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI),
September 2004
This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov
at Siemens Corporate Research. To make it available for public use,
it was later reimplemented by Vladimir Kolmogorov based on open publications.
If you use this software for research purposes, you should cite
the aforementioned paper in any resulting publication.
----------------------------------------------------------------------
REUSING TREES:
Starting with version 3.0, there is a also an option of reusing search
trees from one maxflow computation to the next, as described in
"Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts."
Pushmeet Kohli and Philip H.S. Torr
International Conference on Computer Vision (ICCV), 2005
If you use this option, you should cite
the aforementioned paper in any resulting publication.
*/
#ifndef SMI_GRAPH_KOLMOGOROV_MAXFLOW_H
#define SMI_GRAPH_KOLMOGOROV_MAXFLOW_H
#include <stdlib.h>
#include <string.h>
// #include <assert.h>
namespace vkol
{
/********************************************
*
* block.h
*
*******************************************/
/*
Template classes Block and DBlock
Implement adding and deleting items of the same type in blocks.
If there there are many items then using Block or DBlock
is more efficient than using 'new' and 'delete' both in terms
of memory and time since
(1) On some systems there is some minimum amount of memory
that 'new' can allocate (e.g., 64), so if items are
small that a lot of memory is wasted.
(2) 'new' and 'delete' are designed for items of varying size.
If all items has the same size, then an algorithm for
adding and deleting can be made more efficient.
(3) All Block and DBlock functions are inline, so there are
no extra function calls.
Differences between Block and DBlock:
(1) DBlock allows both adding and deleting items,
whereas Block allows only adding items.
(2) Block has an additional operation of scanning
items added so far (in the order in which they were added).
(3) Block allows to allocate several consecutive
items at a time, whereas DBlock can add only a single item.
Note that no constructors or destructors are called for items.
Example usage for items of type 'MyType':
///////////////////////////////////////////////////
#include "block.h"
#define BLOCK_SIZE 1024
typedef struct { int a, b; } MyType;
MyType *ptr, *array[10000];
...
Block<MyType> *block = new Block<MyType>(BLOCK_SIZE);
// adding items
for (int i=0; i<sizeof(array); i++)
{
ptr = block -> New();
ptr -> a = ptr -> b = rand();
}
// reading items
for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext())
{
printf("%d %d\n", ptr->a, ptr->b);
}
delete block;
...
DBlock<MyType> *dblock = new DBlock<MyType>(BLOCK_SIZE);
// adding items
for (int i=0; i<sizeof(array); i++)
{
array[i] = dblock -> New();
}
// deleting items
for (int i=0; i<sizeof(array); i+=2)
{
dblock -> Delete(array[i]);
}
// adding items
for (int i=0; i<sizeof(array); i++)
{
array[i] = dblock -> New();
}
delete dblock;
///////////////////////////////////////////////////
Note that DBlock deletes items by marking them as
empty (i.e., by adding them to the list of free items),
so that this memory could be used for subsequently
added items. Thus, at each moment the memory allocated
is determined by the maximum number of items allocated
simultaneously at earlier moments. All memory is
deallocated only when the destructor is called.
*/
/***********************************************************************/
/***********************************************************************/
/***********************************************************************/
template <class Type> class Block
{
public:
/* Constructor. Arguments are the block size and
(optionally) the pointer to the function which
will be called if allocation failed; the message
passed to this function is "Not enough memory!" */
Block(int size, void (*err_function)(const char *) = NULL) { first = last = NULL; block_size = size; error_function = err_function; }
/* Destructor. Deallocates all items added so far */
~Block() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } }
/* Allocates 'num' consecutive items; returns pointer
to the first item. 'num' cannot be greater than the
block size since items must fit in one block */
Type *New(int num = 1)
{
Type *t;
if (!last || last->current + num > last->last)
{
if (last && last->next) last = last -> next;
else
{
block *next = (block *) new char [sizeof(block) + (block_size-1)*sizeof(Type)];
if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
if (last) last -> next = next;
else first = next;
last = next;
last -> current = & ( last -> data[0] );
last -> last = last -> current + block_size;
last -> next = NULL;
}
}
t = last -> current;
last -> current += num;
return t;
}
/* Returns the first item (or NULL, if no items were added) */
Type *ScanFirst()
{
for (scan_current_block=first; scan_current_block; scan_current_block = scan_current_block->next)
{
scan_current_data = & ( scan_current_block -> data[0] );
if (scan_current_data < scan_current_block -> current) return scan_current_data ++;
}
return NULL;
}
/* Returns the next item (or NULL, if all items have been read)
Can be called only if previous ScanFirst() or ScanNext()
call returned not NULL. */
Type *ScanNext()
{
while (scan_current_data >= scan_current_block -> current)
{
scan_current_block = scan_current_block -> next;
if (!scan_current_block) return NULL;
scan_current_data = & ( scan_current_block -> data[0] );
}
return scan_current_data ++;
}
/* Marks all elements as empty */
void Reset()
{
block *b;
if (!first) return;
for (b=first; ; b=b->next)
{
b -> current = & ( b -> data[0] );
if (b == last) break;
}
last = first;
}
/***********************************************************************/
private:
typedef struct block_st
{
Type *current, *last;
struct block_st *next;
Type data[1];
} block;
int block_size;
block *first;
block *last;
block *scan_current_block;
Type *scan_current_data;
void (*error_function)(const char *);
}; // end class Block
/***********************************************************************/
/***********************************************************************/
/***********************************************************************/
template <class Type> class DBlock
{
public:
/* Constructor. Arguments are the block size and
(optionally) the pointer to the function which
will be called if allocation failed; the message
passed to this function is "Not enough memory!" */
DBlock(int size, void (*err_function)(const char *) = NULL) { first = NULL; first_free = NULL; block_size = size; error_function = err_function; }
/* Destructor. Deallocates all items added so far */
~DBlock() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } }
/* Allocates one item */
Type *New()
{
block_item *item;
if (!first_free)
{
block *next = first;
first = (block *) new char [sizeof(block) + (block_size-1)*sizeof(block_item)];
if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
first_free = & (first -> data[0] );
for (item=first_free; item<first_free+block_size-1; item++)
item -> next_free = item + 1;
item -> next_free = NULL;
first -> next = next;
}
item = first_free;
first_free = item -> next_free;
return (Type *) item;
}
/* Deletes an item allocated previously */
void Delete(Type *t)
{
((block_item *) t) -> next_free = first_free;
first_free = (block_item *) t;
}
/***********************************************************************/
private:
typedef union block_item_st
{
Type t;
block_item_st *next_free;
} block_item;
typedef struct block_st
{
struct block_st *next;
block_item data[1];
} block;
int block_size;
block *first;
block_item *first_free;
void (*error_function)(const char *);
}; // end class DBlock
/********************************************
*
* graph.h
*
*******************************************/
/*
This software library implements the maxflow algorithm
described in
"An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision."
Yuri Boykov and Vladimir Kolmogorov.
In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI),
September 2004
This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov
at Siemens Corporate Research. To make it available for public use,
it was later reimplemented by Vladimir Kolmogorov based on open publications.
If you use this software for research purposes, you should cite
the aforementioned paper in any resulting publication.
----------------------------------------------------------------------
REUSING TREES:
Starting with version 3.0, there is a also an option of reusing search
trees from one maxflow computation to the next, as described in
"Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts."
Pushmeet Kohli and Philip H.S. Torr
International Conference on Computer Vision (ICCV), 2005
If you use this option, you should cite
the aforementioned paper in any resulting publication.
*/
// NOTE: in UNIX you need to use -DNDEBUG preprocessor option to supress assert's!!!
// captype: type of edge capacities (excluding t-links)
// tcaptype: type of t-links (edges between nodes and terminals)
// flowtype: type of total flow
//
// Current instantiations are in instances.inc
template <typename captype, typename tcaptype, typename flowtype>
class Graph
{
public:
typedef enum
{
SOURCE = 0,
SINK = 1
} termtype; // terminals
typedef int node_id;
/////////////////////////////////////////////////////////////////////////
// BASIC INTERFACE FUNCTIONS //
// (should be enough for most applications) //
/////////////////////////////////////////////////////////////////////////
// Constructor.
// The first argument gives an estimate of the maximum number of nodes that can be added
// to the graph, and the second argument is an estimate of the maximum number of edges.
// The last (optional) argument is the pointer to the function which will be called
// if an error occurs; an error message is passed to this function.
// If this argument is omitted, exit(1) will be called.
//
// IMPORTANT: It is possible to add more nodes to the graph than node_num_max
// (and node_num_max can be zero). However, if the count is exceeded, then
// the internal memory is reallocated (increased by 50%) which is expensive.
// Also, temporarily the amount of allocated memory would be more than twice than needed.
// Similarly for edges.
// If you wish to avoid this overhead, you can download version 2.2, where nodes and edges are stored in blocks.
Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *) = NULL);
// Destructor
~Graph();
// Adds node(s) to the graph. By default, one node is added (num=1); then first call returns 0, second call returns 1, and so on.
// If num>1, then several nodes are added, and node_id of the first one is returned.
// IMPORTANT: see note about the constructor
node_id add_node(int num = 1);
// Adds a bidirectional edge between 'i' and 'j' with the weights 'cap' and 'rev_cap'.
// IMPORTANT: see note about the constructor
void add_edge(node_id i, node_id j, captype cap, captype rev_cap);
// Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights.
// Can be called multiple times for each node.
// Weights can be negative.
// NOTE: the number of such edges is not counted in edge_num_max.
// No internal memory is allocated by this call.
void add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink);
// Computes the maxflow. Can be called several times.
// FOR DESCRIPTION OF reuse_trees, SEE mark_node().
// FOR DESCRIPTION OF changed_list, SEE remove_from_changed_list().
flowtype maxflow(bool reuse_trees = false, Block<node_id>* changed_list = NULL);
// After the maxflow is computed, this function returns to which
// segment the node 'i' belongs (Graph<captype,tcaptype,flowtype>::SOURCE or Graph<captype,tcaptype,flowtype>::SINK).
//
// Occasionally there may be several minimum cuts. If a node can be assigned
// to both the source and the sink, then default_segm is returned.
termtype what_segment(node_id i, termtype default_segm = SOURCE);
// Return 1: assigned to source
// Return -1: assigned to sink
// Return 0: assigned to either
int what_segment_ex(node_id i) const;
//////////////////////////////////////////////
// ADVANCED INTERFACE FUNCTIONS //
// (provide access to the graph) //
//////////////////////////////////////////////
private:
struct node;
struct arc;
public:
////////////////////////////
// 1. Reallocating graph. //
////////////////////////////
// Removes all nodes and edges.
// After that functions add_node() and add_edge() must be called again.
//
// Advantage compared to deleting Graph and allocating it again:
// no calls to delete/new (which could be quite slow).
//
// If the graph structure stays the same, then an alternative
// is to go through all nodes/edges and set new residual capacities
// (see functions below).
void reset();
////////////////////////////////////////////////////////////////////////////////
// 2. Functions for getting pointers to arcs and for reading graph structure. //
// NOTE: adding new arcs may invalidate these pointers (if reallocation //
// happens). So it's best not to add arcs while reading graph structure. //
////////////////////////////////////////////////////////////////////////////////
// The following two functions return arcs in the same order that they
// were added to the graph. NOTE: for each call add_edge(i,j,cap,cap_rev)
// the first arc returned will be i->j, and the second j->i.
// If there are no more arcs, then the function can still be called, but
// the returned arc_id is undetermined.
typedef arc* arc_id;
arc_id get_first_arc();
arc_id get_next_arc(arc_id a);
// other functions for reading graph structure
int get_node_num() { return node_num; }
int get_arc_num() { return (int)(arc_last - arcs); }
void get_arc_ends(arc_id a, node_id& i, node_id& j); // returns i,j to that a = i->j
///////////////////////////////////////////////////
// 3. Functions for reading residual capacities. //
///////////////////////////////////////////////////
// returns residual capacity of SOURCE->i minus residual capacity of i->SINK
tcaptype get_trcap(node_id i);
// returns residual capacity of arc a
captype get_rcap(arc* a);
/////////////////////////////////////////////////////////////////
// 4. Functions for setting residual capacities. //
// NOTE: If these functions are used, the value of the flow //
// returned by maxflow() will not be valid! //
/////////////////////////////////////////////////////////////////
void set_trcap(node_id i, tcaptype trcap);
void set_rcap(arc* a, captype rcap);
////////////////////////////////////////////////////////////////////
// 5. Functions related to reusing trees & list of changed nodes. //
////////////////////////////////////////////////////////////////////
// If flag reuse_trees is true while calling maxflow(), then search trees
// are reused from previous maxflow computation.
// In this case before calling maxflow() the user must
// specify which parts of the graph have changed by calling mark_node():
// add_tweights(i),set_trcap(i) => call mark_node(i)
// add_edge(i,j),set_rcap(a) => call mark_node(i); mark_node(j)
//
// This option makes sense only if a small part of the graph is changed.
// The initialization procedure goes only through marked nodes then.
//
// mark_node(i) can either be called before or after graph modification.
// Can be called more than once per node, but calls after the first one
// do not have any effect.
//
// NOTE:
// - This option cannot be used in the first call to maxflow().
// - It is not necessary to call mark_node() if the change is ``not essential'',
// i.e. sign(trcap) is preserved for a node and zero/nonzero status is preserved for an arc.
// - To check that you marked all necessary nodes, you can call maxflow(false) after calling maxflow(true).
// If everything is correct, the two calls must return the same value of flow. (Useful for debugging).
void mark_node(node_id i);
// If changed_list is not NULL while calling maxflow(), then the algorithm
// keeps a list of nodes which could potentially have changed their segmentation label.
// Nodes which are not in the list are guaranteed to keep their old segmentation label (SOURCE or SINK).
// Example usage:
//
// typedef Graph<int,int,int> G;
// G* g = new Graph(nodeNum, edgeNum);
// Block<G::node_id>* changed_list = new Block<G::node_id>(128);
//
// ... // add nodes and edges
//
// g->maxflow(); // first call should be without arguments
// for (int iter=0; iter<10; iter++)
// {
// ... // change graph, call mark_node() accordingly
//
// g->maxflow(true, changed_list);
// G::node_id* ptr;
// for (ptr=changed_list->ScanFirst(); ptr; ptr=changed_list->ScanNext())
// {
// G::node_id i = *ptr; assert(i>=0 && i<nodeNum);
// g->remove_from_changed_list(i);
// // do something with node i...
// if (g->what_segment(i) == G::SOURCE) { ... }
// }
// changed_list->Reset();
// }
// delete changed_list;
//
// NOTE:
// - If changed_list option is used, then reuse_trees must be used as well.
// - In the example above, the user may omit calls g->remove_from_changed_list(i) and changed_list->Reset() in a given iteration.
// Then during the next call to maxflow(true, &changed_list) new nodes will be added to changed_list.
// - If the next call to maxflow() does not use option reuse_trees, then calling remove_from_changed_list()
// is not necessary. ("changed_list->Reset()" or "delete changed_list" should still be called, though).
void remove_from_changed_list(node_id i)
{
// assert(i>=0 && i<node_num && nodes[i].is_in_changed_list);
nodes[i].is_in_changed_list = 0;
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
private:
// internal variables and functions
struct node
{
arc *first; // first outcoming arc
arc *parent; // node's parent
node *next; // pointer to the next active node
// (or to itself if it is the last node in the list)
int TS; // timestamp showing when DIST was computed
int DIST; // distance to the terminal
int is_sink : 1; // flag showing whether the node is in the source or in the sink tree (if parent!=NULL)
int is_marked : 1; // set by mark_node()
int is_in_changed_list : 1; // set by maxflow if
tcaptype tr_cap; // if tr_cap > 0 then tr_cap is residual capacity of the arc SOURCE->node
// otherwise -tr_cap is residual capacity of the arc node->SINK
};
struct arc
{
node *head; // node the arc points to
arc *next; // next arc with the same originating node
arc *sister; // reverse arc
captype r_cap; // residual capacity
};
struct nodeptr
{
node *ptr;
nodeptr *next;
};
static const int NODEPTR_BLOCK_SIZE = 128;
node *nodes, *node_last, *node_max; // node_last = nodes+node_num, node_max = nodes+node_num_max;
arc *arcs, *arc_last, *arc_max; // arc_last = arcs+2*edge_num, arc_max = arcs+2*edge_num_max;
int node_num;
DBlock<nodeptr> *nodeptr_block;
void (*error_function)(const char *); // this function is called if a error occurs,
// with a corresponding error message
// (or exit(1) is called if it's NULL)
flowtype flow; // total flow
// reusing trees & list of changed pixels
int maxflow_iteration; // counter
Block<node_id> *changed_list;
/////////////////////////////////////////////////////////////////////////
node *queue_first[2], *queue_last[2]; // list of active nodes
nodeptr *orphan_first, *orphan_last; // list of pointers to orphans
int TIME; // monotonically increasing global counter
/////////////////////////////////////////////////////////////////////////
void reallocate_nodes(int num); // num is the number of new nodes
void reallocate_arcs();
// functions for processing active list
void set_active(node *i);
node *next_active();
// functions for processing orphans list
void set_orphan_front(node* i); // add to the beginning of the list
void set_orphan_rear(node* i); // add to the end of the list
void add_to_changed_list(node* i);
void maxflow_init(); // called if reuse_trees == false
void maxflow_reuse_trees_init(); // called if reuse_trees == true
void augment(arc *middle_arc);
void process_source_orphan(node *i);
void process_sink_orphan(node *i);
void test_consistency(node* current_node=NULL); // debug function
};
///////////////////////////////////////
// Implementation - inline functions //
///////////////////////////////////////
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype,tcaptype,flowtype>::node_id Graph<captype,tcaptype,flowtype>::add_node(int num)
{
// assert(num > 0);
if (node_last + num > node_max) reallocate_nodes(num);
if (num == 1)
{
node_last -> first = NULL;
node_last -> tr_cap = 0;
node_last -> is_marked = 0;
node_last -> is_in_changed_list = 0;
node_last ++;
return node_num ++;
}
else
{
memset(node_last, 0, num*sizeof(node));
node_id i = node_num;
node_num += num;
node_last += num;
return i;
}
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink)
{
// assert(i >= 0 && i < node_num);
tcaptype delta = nodes[i].tr_cap;
if (delta > 0) cap_source += delta;
else cap_sink -= delta;
flow += (cap_source < cap_sink) ? cap_source : cap_sink;
nodes[i].tr_cap = cap_source - cap_sink;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::add_edge(node_id _i, node_id _j, captype cap, captype rev_cap)
{
// assert(_i >= 0 && _i < node_num);
// assert(_j >= 0 && _j < node_num);
// assert(_i != _j);
// assert(cap >= 0);
// assert(rev_cap >= 0);
if (arc_last == arc_max) reallocate_arcs();
arc *a = arc_last ++;
arc *a_rev = arc_last ++;
node* i = nodes + _i;
node* j = nodes + _j;
a -> sister = a_rev;
a_rev -> sister = a;
a -> next = i -> first;
i -> first = a;
a_rev -> next = j -> first;
j -> first = a_rev;
a -> head = j;
a_rev -> head = i;
a -> r_cap = cap;
a_rev -> r_cap = rev_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype,tcaptype,flowtype>::arc* Graph<captype,tcaptype,flowtype>::get_first_arc()
{
return arcs;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype,tcaptype,flowtype>::arc* Graph<captype,tcaptype,flowtype>::get_next_arc(arc* a)
{
return a + 1;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::get_arc_ends(arc* a, node_id& i, node_id& j)
{
// assert(a >= arcs && a < arc_last);
i = (node_id) (a->sister->head - nodes);
j = (node_id) (a->head - nodes);
}
template <typename captype, typename tcaptype, typename flowtype>
inline tcaptype Graph<captype,tcaptype,flowtype>::get_trcap(node_id i)
{
// assert(i>=0 && i<node_num);
return nodes[i].tr_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline captype Graph<captype,tcaptype,flowtype>::get_rcap(arc* a)
{
// assert(a >= arcs && a < arc_last);
return a->r_cap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::set_trcap(node_id i, tcaptype trcap)
{
// assert(i>=0 && i<node_num);
nodes[i].tr_cap = trcap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::set_rcap(arc* a, captype rcap)
{
// assert(a >= arcs && a < arc_last);
a->r_cap = rcap;
}
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype,tcaptype,flowtype>::termtype Graph<captype,tcaptype,flowtype>::what_segment(node_id i, termtype default_segm)
{
if (nodes[i].parent)
{
return (nodes[i].is_sink) ? SINK : SOURCE;
}
else
{
return default_segm;
}
}
template <typename captype, typename tcaptype, typename flowtype>
int Graph<captype,tcaptype,flowtype>::what_segment_ex(node_id i) const
{
if (nodes[i].parent)
{
return (nodes[i].is_sink) ? -1 : 1;
}
else
{
return 0;
}
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::mark_node(node_id _i)
{
node* i = nodes + _i;
if (!i->next)
{
/* it's not in the list yet */
if (queue_last[1]) queue_last[1] -> next = i;
else queue_first[1] = i;
queue_last[1] = i;
i -> next = i;
}
i->is_marked = 1;
}
/******************************************
*
* graph.cpp
*
******************************************/
template <typename captype, typename tcaptype, typename flowtype>
Graph<captype, tcaptype, flowtype>::Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *))
: node_num(0),
nodeptr_block(NULL),
error_function(err_function)
{
if (node_num_max < 16) node_num_max = 16;
if (edge_num_max < 16) edge_num_max = 16;
nodes = (node*) malloc(node_num_max*sizeof(node));
arcs = (arc*) malloc(2*edge_num_max*sizeof(arc));
if (!nodes || !arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
node_last = nodes;
node_max = nodes + node_num_max;
arc_last = arcs;
arc_max = arcs + 2*edge_num_max;
maxflow_iteration = 0;
flow = 0;
}
template <typename captype, typename tcaptype, typename flowtype>
Graph<captype,tcaptype,flowtype>::~Graph()
{
if (nodeptr_block)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
free(nodes);
free(arcs);
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::reset()
{
node_last = nodes;
arc_last = arcs;
node_num = 0;
if (nodeptr_block)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
maxflow_iteration = 0;
flow = 0;
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::reallocate_nodes(int num)
{
int node_num_max = (int)(node_max - nodes);
node* nodes_old = nodes;
node_num_max += node_num_max / 2;
if (node_num_max < node_num + num) node_num_max = node_num + num;
nodes = (node*) realloc(nodes_old, node_num_max*sizeof(node));
if (!nodes) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
node_last = nodes + node_num;
node_max = nodes + node_num_max;
if (nodes != nodes_old)
{
arc* a;
for (a=arcs; a<arc_last; a++)
{
a->head = (node*) ((char*)a->head + (((char*) nodes) - ((char*) nodes_old)));
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::reallocate_arcs()
{
int arc_num_max = (int)(arc_max - arcs);
int arc_num = (int)(arc_last - arcs);
arc* arcs_old = arcs;
arc_num_max += arc_num_max / 2; if (arc_num_max & 1) arc_num_max ++;
arcs = (arc*) realloc(arcs_old, arc_num_max*sizeof(arc));
if (!arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
arc_last = arcs + arc_num;
arc_max = arcs + arc_num_max;
if (arcs != arcs_old)
{
node* i;
arc* a;
for (i=nodes; i<node_last; i++)
{
if (i->first) i->first = (arc*) ((char*)i->first + (((char*) arcs) - ((char*) arcs_old)));
}
for (a=arcs; a<arc_last; a++)
{
if (a->next) a->next = (arc*) ((char*)a->next + (((char*) arcs) - ((char*) arcs_old)));
a->sister = (arc*) ((char*)a->sister + (((char*) arcs) - ((char*) arcs_old)));
}
}
}
/********************************************************
*
* maxflow.cpp
*
********************************************************/
/*
special constants for node->parent
*/
#define TERMINAL ( (arc *) 1 ) /* to terminal */
#define ORPHAN ( (arc *) 2 ) /* orphan */
#define INFINITE_D ((int)(((unsigned)-1)/2)) /* infinite distance to the terminal */
/***********************************************************************/
/*
Functions for processing active list.
i->next points to the next node in the list
(or to i, if i is the last node in the list).
If i->next is NULL iff i is not in the list.
There are two queues. Active nodes are added
to the end of the second queue and read from
the front of the first queue. If the first queue
is empty, it is replaced by the second queue
(and the second queue becomes empty).
*/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::set_active(node *i)
{
if (!i->next)
{
/* it's not in the list yet */
if (queue_last[1]) queue_last[1] -> next = i;
else queue_first[1] = i;
queue_last[1] = i;
i -> next = i;
}
}
/*
Returns the next active node.
If it is connected to the sink, it stays in the list,
otherwise it is removed from the list
*/
template <typename captype, typename tcaptype, typename flowtype>
inline typename Graph<captype,tcaptype,flowtype>::node* Graph<captype,tcaptype,flowtype>::next_active()
{
node *i;
while ( 1 )
{
if (!(i=queue_first[0]))
{
queue_first[0] = i = queue_first[1];
queue_last[0] = queue_last[1];
queue_first[1] = NULL;
queue_last[1] = NULL;
if (!i) return NULL;
}
/* remove it from the active list */
if (i->next == i) queue_first[0] = queue_last[0] = NULL;
else queue_first[0] = i -> next;
i -> next = NULL;
/* a node in the list is active iff it has a parent */
if (i->parent) return i;
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::set_orphan_front(node *i)
{
nodeptr *np;
i -> parent = ORPHAN;
np = nodeptr_block -> New();
np -> ptr = i;
np -> next = orphan_first;
orphan_first = np;
}
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::set_orphan_rear(node *i)
{
nodeptr *np;
i -> parent = ORPHAN;
np = nodeptr_block -> New();
np -> ptr = i;
if (orphan_last) orphan_last -> next = np;
else orphan_first = np;
orphan_last = np;
np -> next = NULL;
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
inline void Graph<captype,tcaptype,flowtype>::add_to_changed_list(node *i)
{
if (changed_list && !i->is_in_changed_list)
{
node_id* ptr = changed_list->New();
*ptr = (node_id)(i - nodes);
i->is_in_changed_list = true;
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::maxflow_init()
{
node *i;
queue_first[0] = queue_last[0] = NULL;
queue_first[1] = queue_last[1] = NULL;
orphan_first = NULL;
TIME = 0;
for (i=nodes; i<node_last; i++)
{
i -> next = NULL;
i -> is_marked = 0;
i -> is_in_changed_list = 0;
i -> TS = TIME;
if (i->tr_cap > 0)
{
/* i is connected to the source */
i -> is_sink = 0;
i -> parent = TERMINAL;
set_active(i);
i -> DIST = 1;
}
else if (i->tr_cap < 0)
{
/* i is connected to the sink */
i -> is_sink = 1;
i -> parent = TERMINAL;
set_active(i);
i -> DIST = 1;
}
else
{
i -> parent = NULL;
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::maxflow_reuse_trees_init()
{
node* i;
node* j;
node* queue = queue_first[1];
arc* a;
nodeptr* np;
queue_first[0] = queue_last[0] = NULL;
queue_first[1] = queue_last[1] = NULL;
orphan_first = orphan_last = NULL;
TIME ++;
while ((i=queue))
{
queue = i->next;
if (queue == i) queue = NULL;
i->next = NULL;
i->is_marked = 0;
set_active(i);
if (i->tr_cap == 0)
{
if (i->parent) set_orphan_rear(i);
continue;
}
if (i->tr_cap > 0)
{
if (!i->parent || i->is_sink)
{
i->is_sink = 0;
for (a=i->first; a; a=a->next)
{
j = a->head;
if (!j->is_marked)
{
if (j->parent == a->sister) set_orphan_rear(j);
if (j->parent && j->is_sink && a->r_cap > 0) set_active(j);
}
}
add_to_changed_list(i);
}
}
else
{
if (!i->parent || !i->is_sink)
{
i->is_sink = 1;
for (a=i->first; a; a=a->next)
{
j = a->head;
if (!j->is_marked)
{
if (j->parent == a->sister) set_orphan_rear(j);
if (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j);
}
}
add_to_changed_list(i);
}
}
i->parent = TERMINAL;
i -> TS = TIME;
i -> DIST = 1;
}
//test_consistency();
/* adoption */
while ((np=orphan_first))
{
orphan_first = np -> next;
i = np -> ptr;
nodeptr_block -> Delete(np);
if (!orphan_first) orphan_last = NULL;
if (i->is_sink) process_sink_orphan(i);
else process_source_orphan(i);
}
/* adoption end */
//test_consistency();
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::augment(arc *middle_arc)
{
node *i;
arc *a;
tcaptype bottleneck;
/* 1. Finding bottleneck capacity */
/* 1a - the source tree */
bottleneck = middle_arc -> r_cap;
for (i=middle_arc->sister->head; ; i=a->head)
{
a = i -> parent;
if (a == TERMINAL) break;
if (bottleneck > a->sister->r_cap) bottleneck = a -> sister -> r_cap;
}
if (bottleneck > i->tr_cap) bottleneck = i -> tr_cap;
/* 1b - the sink tree */
for (i=middle_arc->head; ; i=a->head)
{
a = i -> parent;
if (a == TERMINAL) break;
if (bottleneck > a->r_cap) bottleneck = a -> r_cap;
}
if (bottleneck > - i->tr_cap) bottleneck = - i -> tr_cap;
/* 2. Augmenting */
/* 2a - the source tree */
middle_arc -> sister -> r_cap += bottleneck;
middle_arc -> r_cap -= bottleneck;
for (i=middle_arc->sister->head; ; i=a->head)
{
a = i -> parent;
if (a == TERMINAL) break;
a -> r_cap += bottleneck;
a -> sister -> r_cap -= bottleneck;
if (!a->sister->r_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
}
i -> tr_cap -= bottleneck;
if (!i->tr_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
/* 2b - the sink tree */
for (i=middle_arc->head; ; i=a->head)
{
a = i -> parent;
if (a == TERMINAL) break;
a -> sister -> r_cap += bottleneck;
a -> r_cap -= bottleneck;
if (!a->r_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
}
i -> tr_cap += bottleneck;
if (!i->tr_cap)
{
set_orphan_front(i); // add i to the beginning of the adoption list
}
flow += bottleneck;
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::process_source_orphan(node *i)
{
node *j;
arc *a0, *a0_min = NULL, *a;
int d, d_min = INFINITE_D;
/* trying to find a new parent */
for (a0=i->first; a0; a0=a0->next)
if (a0->sister->r_cap)
{
j = a0 -> head;
if (!j->is_sink && (a=j->parent))
{
/* checking the origin of j */
d = 0;
while ( 1 )
{
if (j->TS == TIME)
{
d += j -> DIST;
break;
}
a = j -> parent;
d ++;
if (a==TERMINAL)
{
j -> TS = TIME;
j -> DIST = 1;
break;
}
if (a==ORPHAN) { d = INFINITE_D; break; }
j = a -> head;
}
if (d<INFINITE_D) /* j originates from the source - done */
{
if (d<d_min)
{
a0_min = a0;
d_min = d;
}
/* set marks along the path */
for (j=a0->head; j->TS!=TIME; j=j->parent->head)
{
j -> TS = TIME;
j -> DIST = d --;
}
}
}
}
if (i->parent = a0_min)
{
i -> TS = TIME;
i -> DIST = d_min + 1;
}
else
{
/* no parent is found */
add_to_changed_list(i);
/* process neighbors */
for (a0=i->first; a0; a0=a0->next)
{
j = a0 -> head;
if (!j->is_sink && (a=j->parent))
{
if (a0->sister->r_cap) set_active(j);
if (a!=TERMINAL && a!=ORPHAN && a->head==i)
{
set_orphan_rear(j); // add j to the end of the adoption list
}
}
}
}
}
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::process_sink_orphan(node *i)
{
node *j;
arc *a0, *a0_min = NULL, *a;
int d, d_min = INFINITE_D;
/* trying to find a new parent */
for (a0=i->first; a0; a0=a0->next)
if (a0->r_cap)
{
j = a0 -> head;
if (j->is_sink && (a=j->parent))
{
/* checking the origin of j */
d = 0;
while ( 1 )
{
if (j->TS == TIME)
{
d += j -> DIST;
break;
}
a = j -> parent;
d ++;
if (a==TERMINAL)
{
j -> TS = TIME;
j -> DIST = 1;
break;
}
if (a==ORPHAN) { d = INFINITE_D; break; }
j = a -> head;
}
if (d<INFINITE_D) /* j originates from the sink - done */
{
if (d<d_min)
{
a0_min = a0;
d_min = d;
}
/* set marks along the path */
for (j=a0->head; j->TS!=TIME; j=j->parent->head)
{
j -> TS = TIME;
j -> DIST = d --;
}
}
}
}
if (i->parent = a0_min)
{
i -> TS = TIME;
i -> DIST = d_min + 1;
}
else
{
/* no parent is found */
add_to_changed_list(i);
/* process neighbors */
for (a0=i->first; a0; a0=a0->next)
{
j = a0 -> head;
if (j->is_sink && (a=j->parent))
{
if (a0->r_cap) set_active(j);
if (a!=TERMINAL && a!=ORPHAN && a->head==i)
{
set_orphan_rear(j); // add j to the end of the adoption list
}
}
}
}
}
/***********************************************************************/
template <typename captype, typename tcaptype, typename flowtype>
flowtype Graph<captype,tcaptype,flowtype>::maxflow(bool reuse_trees, Block<node_id>* _changed_list)
{
node *i, *j, *current_node = NULL;
arc *a;
nodeptr *np, *np_next;
if (!nodeptr_block)
{
nodeptr_block = new DBlock<nodeptr>(NODEPTR_BLOCK_SIZE, error_function);
}
changed_list = _changed_list;
if (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)("reuse_trees cannot be used in the first call to maxflow()!"); exit(1); }
if (changed_list && !reuse_trees) { if (error_function) (*error_function)("changed_list cannot be used without reuse_trees!"); exit(1); }
if (reuse_trees) maxflow_reuse_trees_init();
else maxflow_init();
// main loop
while ( 1 )
{
// test_consistency(current_node);
if ((i=current_node))
{
i -> next = NULL; /* remove active flag */
if (!i->parent) i = NULL;
}
if (!i)
{
if (!(i = next_active())) break;
}
/* growth */
if (!i->is_sink)
{
/* grow source tree */
for (a=i->first; a; a=a->next)
if (a->r_cap)
{
j = a -> head;
if (!j->parent)
{
j -> is_sink = 0;
j -> parent = a -> sister;
j -> TS = i -> TS;
j -> DIST = i -> DIST + 1;
set_active(j);
add_to_changed_list(j);
}
else if (j->is_sink) break;
else if (j->TS <= i->TS &&
j->DIST > i->DIST)
{
/* heuristic - trying to make the distance from j to the source shorter */
j -> parent = a -> sister;
j -> TS = i -> TS;
j -> DIST = i -> DIST + 1;
}
}
}
else
{
/* grow sink tree */
for (a=i->first; a; a=a->next)
if (a->sister->r_cap)
{
j = a -> head;
if (!j->parent)
{
j -> is_sink = 1;
j -> parent = a -> sister;
j -> TS = i -> TS;
j -> DIST = i -> DIST + 1;
set_active(j);
add_to_changed_list(j);
}
else if (!j->is_sink) { a = a -> sister; break; }
else if (j->TS <= i->TS &&
j->DIST > i->DIST)
{
/* heuristic - trying to make the distance from j to the sink shorter */
j -> parent = a -> sister;
j -> TS = i -> TS;
j -> DIST = i -> DIST + 1;
}
}
}
TIME ++;
if (a)
{
i -> next = i; /* set active flag */
current_node = i;
/* augmentation */
augment(a);
/* augmentation end */
/* adoption */
while ((np=orphan_first))
{
np_next = np -> next;
np -> next = NULL;
while ((np=orphan_first))
{
orphan_first = np -> next;
i = np -> ptr;
nodeptr_block -> Delete(np);
if (!orphan_first) orphan_last = NULL;
if (i->is_sink) process_sink_orphan(i);
else process_source_orphan(i);
}
orphan_first = np_next;
}
/* adoption end */
}
else current_node = NULL;
}
// test_consistency();
if (!reuse_trees || (maxflow_iteration % 64) == 0)
{
delete nodeptr_block;
nodeptr_block = NULL;
}
maxflow_iteration ++;
return flow;
}
/***********************************************************************/
/*
template <typename captype, typename tcaptype, typename flowtype>
void Graph<captype,tcaptype,flowtype>::test_consistency(node* current_node)
{
node *i;
arc *a;
int r;
int num1 = 0, num2 = 0;
// test whether all nodes i with i->next!=NULL are indeed in the queue
for (i=nodes; i<node_last; i++)
{
if (i->next || i==current_node) num1 ++;
}
for (r=0; r<3; r++)
{
i = (r == 2) ? current_node : queue_first[r];
if (i)
for ( ; ; i=i->next)
{
num2 ++;
if (i->next == i)
{
if (r<2) assert(i == queue_last[r]);
else assert(i == current_node);
break;
}
}
}
assert(num1 == num2);
for (i=nodes; i<node_last; i++)
{
// test whether all edges in seach trees are non-saturated
if (i->parent == NULL) {}
else if (i->parent == ORPHAN) {}
else if (i->parent == TERMINAL)
{
if (!i->is_sink) assert(i->tr_cap > 0);
else assert(i->tr_cap < 0);
}
else
{
if (!i->is_sink) assert (i->parent->sister->r_cap > 0);
else assert (i->parent->r_cap > 0);
}
// test whether passive nodes in search trees have neighbors in
// a different tree through non-saturated edges
if (i->parent && !i->next)
{
if (!i->is_sink)
{
assert(i->tr_cap >= 0);
for (a=i->first; a; a=a->next)
{
if (a->r_cap > 0) assert(a->head->parent && !a->head->is_sink);
}
}
else
{
assert(i->tr_cap <= 0);
for (a=i->first; a; a=a->next)
{
if (a->sister->r_cap > 0) assert(a->head->parent && a->head->is_sink);
}
}
}
// test marking invariants
if (i->parent && i->parent!=ORPHAN && i->parent!=TERMINAL)
{
assert(i->TS <= i->parent->head->TS);
if (i->TS == i->parent->head->TS) assert(i->DIST > i->parent->head->DIST);
}
}
}
*/
#undef TERMINAL
#undef ORPHAN
#undef INFINITE_D
}
#endif
| zzhangumd-smitoolbox | graph/flows/private/kolmogorov_maxflow.h | C++ | mit | 45,944 |
function W = gr_wmat(g, w)
% Compute the edge-weight matrix from a graph
%
% W = gr_wmat(g);
% W = gr_wmat(g, w);
%
% returns an n x n weight (sparse) matrix W, given by
%
% W(u, v) = w_e if e = (u, v) is an edge of g
% = 0 otherwise.
%
% If w is omitted, it creates a logical matrix.
%
% Here, g can be a graph struct or degree-bounded graph struct.
% For the former, w should be a vector of length m, while for
% the latter, w should be a matrix of size K x n.
%
% In both cases, w can also be a scalar if all edges have the
% same weight.
%
% Created by Dahua Lin, on Oct 28, 2011
%
%% verify input
if is_gr(g)
n = double(g.n);
if nargin < 2
w = [];
else
m = g.m;
if ~(isnumeric(w) && (isscalar(w) || (isvector(w) && numel(w) == m)))
error('gr_wmat:invalidarg', ...
'w should be a either a numeric scalar or a vector of length m.');
end
end
is_gbnd = false;
elseif is_gr_bnd(g)
n = double(g.n);
if nargin < 2
w = [];
else
K = g.K;
if ~(isnumeric(w) && (isscalar(w) || isequal(size(w), [K n])) )
error('gr_wmat:invalidarg', ...
'w should be a numeric matrix of size K x n.');
end
end
is_gbnd = true;
else
error('gr_wmat:invalidarg', ...
'g should be a graph struct or degree-bounded graph struct.');
end
%% main
% preprocess w
if is_gbnd
i = repmat(1:n, g.K, 1);
j = double(g.nbs);
u = find(g.nbs > 0);
i = i(u);
j = j(u);
if ~isempty(w)
if ~isscalar(w)
w = w(u);
end
end
else
i = double(g.edges(1,:));
j = double(g.edges(2,:));
if ~isempty(w)
if ~isscalar(w)
if size(w, 1) > 1
w = w.';
end
if g.dty == 'u'
w = [w, w];
end
end
end
end
% make W
if isempty(w)
W = sparse(i, j, true, n, n);
else
if ~isa(w, 'double')
w = double(w);
end
W = sparse(i, j, w, n, n);
end
| zzhangumd-smitoolbox | graph/common/gr_wmat.m | MATLAB | mit | 2,239 |
function gr_dump(g)
% Dump the information of a graph
%
% gr_dump(g);
%
% Created by Dahua Lin, on Oct 28, 2011
%
%% verify input
if ~is_gr(g)
error('gr_dump:invalidarg', 'The input argument is not a valid graph struct.');
end
%% main
if g.dty == 'd'
dtname = 'Directed';
else
dtname = 'Undirected';
end
% basic information
fprintf('\n');
fprintf('%s graph with %d nodes and %d edges\n', dtname, g.n, g.m);
fprintf('----------------------------------------------\n');
% edges
fprintf('\n');
fprintf('Edges:\n');
if g.dty == 'd'
for i = 1 : g.m
fprintf(' %d --> %d\n', g.edges(1,i), g.edges(2,i));
end
else
for i = 1 : g.m
fprintf(' %d --- %d\n', g.edges(1,i), g.edges(2,i));
end
end
% neighborhood
if g.has_nbs
fprintf('\n');
fprintf('Neighborhoods: \n');
for i = 1 : g.n
deg = g.o_degs(i);
co = g.o_os(i);
fprintf(' [%d] (deg = %d): ', i, deg);
for j = 1 : deg
fprintf('%d ', g.o_nbs(co+j));
end
fprintf('\n');
end
end
fprintf('\n');
| zzhangumd-smitoolbox | graph/common/gr_dump.m | MATLAB | mit | 1,116 |
function C = gr_neighbors(G, vs)
% GR_NEIGHBORS Gets the neighbors of nodes
%
% C = GR_NEIGHBORS(G);
% Gets the neighbors of nodes of a graph and returns them as a cell
% array.
%
% Suppose G has n nodes, then C is a cell array of size n x 1,
% such that C{i} is a row vector of its neighbor node indices.
%
% C = GR_NEIGHBORS(G, vs);
% Gets the neighbors of the nodes whose indices are given in vs.
%
% Created by Dahua Lin, on Nov 10, 2011
%
%% verify input arguments
if ~is_gr(G)
error('gr_neighbors:invalidarg', ...
'G should be a struct with neighbors.');
end
if nargin < 2
vs = 1:G.n;
else
if ~(isnumeric(vs) && isreal(vs))
error('gr_neighbors:invalidarg', 'vs should be a numeric array.');
end
end
%% main
C = cell(size(vs));
os = G.o_os;
ds = G.o_degs;
nbs = G.o_nbs;
n = numel(vs);
for i = 1 : n
C{i} = nbs(os(i) + (1:ds(i)));
end
| zzhangumd-smitoolbox | graph/common/gr_neighbors.m | MATLAB | mit | 931 |
function G = make_gr_bnd(nbs)
% Make a degree-bounded graph struct
%
% The degree-bounded graph struct is a compact representation of
% a directed graph whose (outgoing) degree is upper bounded by K.
%
% The struct contains the following fields:
% - tag: a string: 'gr-bnd'
% - n: the number of nodes
% - K: the upper bound of outgoing degrees
% - nbs: a K x n matrix, where nbs(:, i) lists the outgoing
% neighbors of the i-th node. If the degree of this node
% is less than K, some entries in nbs(:,i) can be set to
% zeros to indicate no connection. (type: int32)
%
% The actual number of edges equals nnz(nbs)
%
% G = make_gr_bnd(nbs);
%
% constructs a degree-bounded graph struct given the neighbor matrix.
%
% Created by Dahua Lin, on Nov 30, 2011
%
%% verify input argument
if ~(isnumeric(nbs) && ndims(nbs) == 2 && isreal(nbs) && ~issparse(nbs))
error('make_gr_nbs:invalidarg', ...
'nbs should be a non-sparse real numeric matrix.');
end
%% main
if ~isa(nbs, 'int32')
nbs = int32(nbs);
end
[K, n] = size(nbs);
G.tag = 'gr-bnd';
G.n = int32(n);
G.K = int32(K);
G.nbs = nbs;
| zzhangumd-smitoolbox | graph/common/make_gr_bnd.m | MATLAB | mit | 1,199 |
function [h, coords] = gr_plot(g, coords, varargin)
% Plot a graph
%
% h = gr_plot(g, 2, ...);
% h = gr_plot(g, 3, ...);
% h = gr_plot(g, coords, ...);
% plots the graph g.
%
% In input, g is a graph struct produced by make_gr
%
% coords is an n x 2 or n x 3 array that gives the coordinates of
% the graph (in 2D or 3D space). If coord is 2 or 3, then the
% function computes a set of 2D or 3D coordinates by spectral
% embedding.
%
% One can additionally specify plotting options.
%
% This function outputs the handle to the plotted lines.
%
% [h, coords] = gr_plot( ... );
% additionally returns the coordinates of the vertices.
%
% History
% -------
% - Created by Dahua Lin, on Nov 5, 2010
% - Modified by Dahua Lin, on Nov 13, 2010
% - use new graph class
% - Modified by Dahua Lin, on Oct 28, 2011
% - use new graph struct
%% verify input arguments
if ~is_gr(g)
error('gr_plot:invalidarg', 'g should be a graph struct.');
end
n = g.n;
if isscalar(coords)
d = coords;
if ~(isequal(d, 2) || isequal(d, 3))
error('gr_plot:invalidarg', 'The 2nd argument is invalid.');
end
coords = [];
else
if ~(isnumeric(coords) && ndims(coords) == 2 && ...
size(coords,1) == n && (size(coords,2) == 2 || size(coords,2) == 3))
error('gr_plot:invalidarg', ...
'coords should be an n x 2 or n x 3 numeric matrix.');
end
end
if nargin < 3
pargs = {};
else
pargs = varargin;
end
%% main
% generate coordinates
if isempty(coords)
coords = gsembed(g, 1, d, 1);
else
d = size(coords, 2);
end
% generate plot
s = g.edges(1, :);
t = g.edges(2, :);
if d == 2
x = gen_coord_seq(coords(:, 1), s, t);
y = gen_coord_seq(coords(:, 2), s, t);
h = plot(x, y, pargs{:});
else
x = gen_coord_seq(coords(:, 1), s, t);
y = gen_coord_seq(coords(:, 2), s, t);
z = gen_coord_seq(coords(:, 3), s, t);
h = plot3(x, y, z, pargs{:});
end
%% sub functions
function xs = gen_coord_seq(x, s, t)
n = length(s);
xs = zeros(n*3, 1);
xs(1:3:end) = x(s);
xs(2:3:end) = x(t);
xs(3:3:end) = nan;
| zzhangumd-smitoolbox | graph/common/gr_plot.m | MATLAB | mit | 2,207 |
function tf = is_gr(g)
% Tests whether the input argument is a valid graph struct
%
% tf = is_gr(g);
%
% Tests whether the input argument g is a valid graph struct
% produced by make_gr.
%
% Created by Dahua Lin, on Oct 28, 2011
%
%% main
tf = isstruct(g) && isscalar(g) && isfield(g, 'tag') && strcmp(g.tag, 'gr');
| zzhangumd-smitoolbox | graph/common/is_gr.m | MATLAB | mit | 334 |
function g = gr_nbs(g)
% Add the neighborhood system to a graph
%
% g = gr_nbs(g);
%
% This function creates or updates the neighborhood system for g.
%
% Created by Dahua Lin, on Nov 30, 2011
%
if ~is_gr(g)
error('gr_nbs:invalidarg', 'g should be a graph struct.');
end
[g.o_nbs, g.o_eds, g.o_degs, g.o_os] = gr_nbs_cimp(g);
g.has_nbs = true;
| zzhangumd-smitoolbox | graph/common/gr_nbs.m | MATLAB | mit | 364 |
function tf = is_gr_bnd(g)
% Tests whether G is a degree-bounded graph struct
%
% tf = is_gr_bnd(g);
% returns whether g is a valid degree-bounded graph struct.
%
% Created by Dahua Lin, on Nov 30, 2011
%
%% main
tf = isstruct(g) && isscalar(g) && isfield(g, 'tag') && strcmp(g.tag, 'gr-bnd'); | zzhangumd-smitoolbox | graph/common/is_gr_bnd.m | MATLAB | mit | 304 |
function [Gs, ws, Ws] = gr_sym(G, w, option)
% Make an undirected graph from a directed one via symmetrization
%
% Gs = gr_sym(G, [], 'max');
% Gs = gr_sym(G, [], 'min');
%
% Make an undirected graph Gs from a directed graph G through
% symmetrization. If the 2nd argument is 'max', then the edge
% {i, j} will be preserved when either (i, j) or (j, i) is in G.
% If the 2nd argument is 'min', then it will be preserved if
% both (i, j) and (j, i) are in G.
%
% G can be either a graph struct or a degree-bounded graph struct.
%
% [Gs, ws] = gr_sym(G, w, 'avg');
% [Gs, ws] = gr_sym(G, w, 'min');
% [Gs, ws] = gr_sym(G, w, 'max');
%
% Make an undirected weighted graph Gs from a directed weighted
% graph G through symmetrization, according to the 2nd argument.
%
% The meaning of the 2nd argument
% 'avg': Gs(i,j) = G(i,j) + G(j,i) / 2
% 'max': Gs(i,j) = max(G(i,j), G(j,i))
% 'min': Gs(i,j) = min(G(i,j), G(j,i))
%
% [Gs, ws, Ws] = gr_sym( ... );
%
% additionally returns the corresponding adjacency weight matrix Ws.
%
% Note that the number of edges can change, if the some edge weights
% change from zero to non-zero, or vice versa.
%
% The output graph has no neighborhood system, and one can call gr_nbs
% to build it.
%
% Created by Dahua Lin, on Nov 30, 2011
%
%% verify input arguments
if is_gr(G) && G.dty == 'd'
if ~isempty(w)
if ~(isnumeric(w) && isvector(w) && numel(w) == G.m)
error('gr_sym:invalidarg', ...
'w should be a numeric vector of length m.');
end
end
elseif is_gr_bnd(G)
if ~isempty(w)
if ~(isnumeric(w) && isequal(size(w), [G.K, G.n]))
error('gr_sym:invalidarg', ...
'w should be a numeric matrix of size K x n');
end
end
else
error('gr_sym:invalidarg', ...
'G should be a directed graph struct or a degree-bounded graph struct.');
end
if ~(ischar(option))
error('gr_sym:invalidarg', 'The 2nd argument is invalid.');
end
%% main
if isempty(w)
switch lower(option)
case 'max'
sym_fun = @or;
case 'min'
sym_fun = @and;
otherwise
error('gr_sym:invalidarg', 'The 2nd argument is invalid.');
end
W = gr_wmat(G);
Ws = sym_fun(W, W.');
[s, t] = find(Ws);
i = find(s <= t);
Gs = make_gr('u', G.n, s(i), t(i));
ws = [];
else
switch lower(option)
case 'max'
sym_fun = @max;
case 'min'
sym_fun = @min;
case 'avg'
sym_fun = @(x,y) (x + y) / 2;
otherwise
error('gr_sym:invalidarg', 'The 2nd argument is invalid.');
end
W = gr_wmat(G, w);
Ws = sym_fun(W, W.');
[s, t, ws] = find(Ws);
i = find(s <= t);
s = s(i);
t = t(i);
ws = ws(i);
Gs = make_gr('u', G.n, s, t);
end
| zzhangumd-smitoolbox | graph/common/gr_sym.m | MATLAB | mit | 2,982 |
function [G, varargout] = gr_local(siz, rgn)
% Create a degree-bounded graph with links between local neighbors
%
% G = gr_local(n, r);
%
% Creates a locally connected graph over one-dimensional
% grid. Here, n is the number of nodes, and r is the local range.
% In this graph, each node is connected to a neighboring node,
% within distance r.
%
% [G, dx] = gr_local(n, r);
%
% additionally returns the distances between sources and targets.
% The size of dx is K x 1. The neighbors in G.nbs(k ,:) have the
% same distance to the centers, which is dx(k).
%
% G = gr_local([m, n], r);
% G = gr_local([m, n], [yr, xr]);
%
% Creates a locally connected graph over two-dimensional
% grid. Here, the grid size is m rows and n columns, and yr and xr
% are respectively the local range along y and x direction.
%
% If xr == yr, one can simply input a single value r that equals
% xr and yr.
%
% G = gr_local([m, n], ker);
%
% Creates a locally connected graph over two-dimensional
% grid. Here, ker is a matrix specifying the connection pattern,
% the node (i, j) is connected to (i+di, j+dj) if ker(di', dj')
% is non-zero. Here, ker is a matrix of size [2*yr+1, 2*xr+1], and
% di' = di+(yr+1) and dj' = dj+(dx+1).
%
% [G, dy, dx] = gr_local([m, n], ...);
%
% additionally returns the distances along y- and x-dimension
% between sources and targets. dy and dx have the same sizes as
% G.nbs.
%
% The size of dx and dy is K x 1. The neighbors in G.nbs(k,:) have
% the same distances to the centers.
%
% Created by Dahua Lin, on Nov 30, 2011
%
%% verify input arguments
if ~(isnumeric(siz) && ndims(siz) == 2 && all(siz == fix(siz)) )
error('gr_local:invalidarg', 'The 1st argument is invalid.');
end
d = numel(siz);
if ~(d == 1 || d == 2)
error('gr_local:invalidarg', 'Only 1D or 2D grid is allowed.');
end
if d == 1
n = siz;
r = rgn;
if ~(isnumeric(r) && isscalar(r) && r == fix(r) && r >= 0)
error('gr_local:invalidarg', 'r should be a positive integer.');
end
else % d == 2
m = siz(1);
n = siz(2);
if ndims(rgn) ~= 2
error('gr_local:invalidarg', 'The 2nd argument is invalid.');
end
if isnumeric(rgn) && numel(rgn) <= 2
if isscalar(rgn)
yr = rgn;
xr = rgn;
else
yr = rgn(1);
xr = rgn(2);
end
ker = true(2*yr+1, 2*xr+1);
ker(yr+1, xr+1) = 0;
elseif islogical(rgn)
ker = rgn;
[kh, kw] = size(ker);
if ~(rem(kh, 2) == 1 && rem(kw, 2) == 1)
error('gr_local:invalidarg', ...
'The dimensions of the kernel should be odd numbers.');
end
yr = (kh - 1) / 2;
xr = (kw - 1) / 2;
else
error('gr_local:invalidarg', 'The 2nd argument is invalid.');
end
end
%% main
if d == 1
delta = [-r:-1, 1:r].';
nbs = bsxfun(@plus, delta, 1:n);
nbs(nbs < 0 | nbs > n) = 0;
if nargout >= 2
varargout{1} = delta;
end
else
[dx, dy] = meshgrid(-xr:xr, -yr:yr);
[x, y] = meshgrid(1:n, 1:m);
dx = dx(ker);
dy = dy(ker);
x = reshape(x, 1, m * n);
y = reshape(y, 1, m * n);
nx = bsxfun(@plus, dx, x);
ny = bsxfun(@plus, dy, y);
is_out = nx < 1 | nx > n | ny < 1 | ny > m;
nbs = ny + (nx - 1) * m;
nbs(is_out) = 0;
if nargout >= 2
varargout = {dy, dx};
end
end
G = make_gr_bnd(nbs);
| zzhangumd-smitoolbox | graph/common/gr_local.m | MATLAB | mit | 3,626 |
function [g, w] = gr_from_wmat(W, dt, op)
% Construct a graph struct from an edge-weight matrix
%
% [g, w] = gr_from_wmat(W, 'u');
% [g, w] = gr_from_wmat(W, 'd');
% [g, w] = gr_from_wmat(W, 'u', 'nbs');
% [g, w] = gr_from_wmat(W, 'd', 'nbs');
%
% Constructs a graph g from W, the edge weight matrix.
%
% The second argument specifies whether to construct an directed
% or undirected graph, depending on its value ('d' or 'u').
% For undirected graph, W needs to be a symmetric matrix.
%
% If the third argument is given as 'nbs', the neighborhood struct
% will also be established.
%
% In the output, g is the graph struct, and w is the vector of
% edge weights.
%
% History
% -------
% - Created by Dahua Lin, on Oct 28, 2011
%
%% verify input arguments
n = size(W, 1);
if ~((isnumeric(W) || islogical(W)) && ndims(W) == 2 && size(W,2) == n)
error('gr_from_wmat:invalidarg', ...
'W should be a square matrix (numeric or logical).');
end
if ~(ischar(dt) && (dt == 'u' || dt == 'd'))
error('gr_from_wmat:invalidarg', ...
'dt should be a char which equals ''u'' or ''d''.');
end
if nargin >= 3
if ~(ischar(op) && strcmpi(op, 'nbs'))
error('gr_from_wmat:invalidarg', ...
'The 3rd argument should be ''nbs'' if given.');
end
use_nbs = true;
else
use_nbs = false;
end
%% main
[s, t, w] = find(W);
if dt == 'u'
r = find(s <= t);
s = s(r);
t = t(r);
w = w(r);
end
if use_nbs
g = make_gr(dt, n, s, t, 'nbs');
else
g = make_gr(dt, n, s, t);
end
| zzhangumd-smitoolbox | graph/common/gr_from_wmat.m | MATLAB | mit | 1,611 |
function [G, V] = knng(D, op, K, thres)
% Construct K-nearest-neighbor graph
%
% [G, V] = knng(D, 'min', K);
% [G, V] = knng(D, 'max', K);
% [G, V] = knng(D, 'min', K, thres);
% [G, V] = knng(D, 'max', K, thres);
%
% constructs a K-nearest-neighbor graph given the
% pairwise distances/similarities.
%
% Inputs:
% - D: the n x n matrix of pairwise distances/similarities.
% Specifically, D(i, j) is the value between the node
% i and node j.
%
% The 2nd argument can be either 'min' or 'max'. If it
% is 'min', D represents distances (smaller value
% indicates closer); if it is 'max', D represents
% similarities (greater value indicates closer).
%
% - K: the (maximum) number of neighbors of each node.
%
% - thres: If 2nd argument is 'min', only those edges whose
% associated distances are below thres are used.
% If 2nd argument is 'max', only those edges whose
% associated similarities are above thres are used.
%
% Outputs:
% - G: the constructed graph, in form of a degree-bounded
% graph struct.
% - V: the corresponding edge distance/similarity matrix,
% of size K x n.
%
% Note that the first row of G.nbs and w correspond to the nearest
% neighbor, and the second row of G.nbs and w correspond to the
% next nearest, and so on.
%
% Moreover, loops (i.e. edges like (i, i)) are excluded.
%
% History
% -------
% - Created by Dahua Lin, on Nov 13, 2010
% - Modified by Dahua Lin, on Oct 28, 2011
% - Modified by Dahua Lin, on Nov 30, 2011
%
%% verify input arguments
if ~(isnumeric(D) && ndims(D) == 2 && ~issparse(D) && isreal(D) && ...
size(D,1) == size(D,2))
error('knng:invalidarg', 'D should be a non-sparse real square matrix.');
end
n = size(D,1);
if ischar(op)
op = lower(op);
if strcmp(op, 'max')
is_max = true;
elseif strcmp(op, 'min')
is_max = false;
else
error('knng:invalidarg', ...
'The 2nd argument should be either ''max'' or ''min''.');
end
else
error('knng:invalidarg', ...
'The 2nd argument should be either ''max'' or ''min''.');
end
if ~(isscalar(K) && isreal(K) && K == fix(K) && K >= 1 && K < n)
error('knng:invalidarg', ...
'K should be an integer in [1, n-1]');
end
if nargin < 4
thres = [];
else
if ~(isscalar(thres) && isreal(thres))
error('knng:invalidarg', 'thres should be a real scalar.');
end
end
%% main
Dr = rmdiag(D.', 'r');
[V, nbs] = top_k(Dr, op, K, 1);
a = bsxfun(@ge, nbs, 1:n);
nbs(a) = nbs(a) + 1;
if ~isempty(thres)
if is_max
nbs(V < thres) = 0;
else
nbs(V > thres) = 0;
end
end
G = make_gr_bnd(nbs);
| zzhangumd-smitoolbox | graph/common/knng.m | MATLAB | mit | 2,956 |
function G = gr_bnd2inclist(G0)
% Convert a degree-bounded graph struct to a incidence list struct
%
% G = gr_bnd2inclist(G0);
%
% converts a degree-bounded graph struct G0 to a directed graph
% struct with neighborhood system.
%
% Note that if G0 is associated with a weight matrix W, the
% corresponding weight vector for G is W(G0.nbs > 0);
%
% Created by Dahua Lin, on Nov 30, 2011
%
%% verify input
if ~is_gr_bnd(G0)
error('gr_bnd2inclist:invalidarg', ...
'G0 should be a degree-bounded graph struct.');
end
%% main
n = G0.n;
K = G0.K;
s = repmat(1:n, K, 1);
t = G0.nbs;
s = s(t > 0);
t = t(t > 0);
G = make_gr('d', n, s, t, 'nbs');
| zzhangumd-smitoolbox | graph/common/gr_bnd2inclist.m | MATLAB | mit | 686 |
/********************************************************************
*
* gr_nbs_cimp.cpp
*
* The C++ mex implementation of part of make_gr functionality
*
* Created by Dahua Lin, on Oct 28, 2011
*
********************************************************************/
#include "../../clib/smi_graph_mex.h"
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
/**
* The main entry
*
* Input
* [0] s: the graph struct (without nbs)
*
* Output
* [0] o_nbs
* [1] o_eds
* [2] o_degs
* [3] o_os
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const_marray mG(prhs[0]);
gedgelist_t E = mx_to_gedgelist(mG);
// prepare storage
gint n = E.nvertices();
gint ma = E.is_directed() ? E.nedges() : 2 * E.nedges();
marray mNbs = create_marray<gint>(1, ma);
marray mEds = create_marray<gint>(1, ma);
marray mDegs = create_marray<gint>(1, n);
marray mOfs = create_marray<gint>(1, n);
vertex_t *nbs = mNbs.data<vertex_t>();
edge_t *eds = mEds.data<edge_t>();
gint *degs = mDegs.data<gint>();
gint *ofs = mOfs.data<gint>();
// build neighborhood
gint *temp = new gint[n];
const vertex_pair* vps = E.vertex_pairs_begin();
prepare_ginclist_arrays(n, ma, vps, nbs, eds, degs, ofs, temp);
delete[] temp;
// export
plhs[0] = mNbs.mx_ptr();
plhs[1] = mEds.mx_ptr();
plhs[2] = mDegs.mx_ptr();
plhs[3] = mOfs.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/common/private/gr_nbs_cimp.cpp | C++ | mit | 1,564 |
function g = make_gr(dty, n, s, t, op)
% Makes a graph with given edges
%
% g = make_gr('d', n, s, t);
%
% makes a directed graph with given edges.
%
% Here, n is the number of nodes, s is the source nodes, t is
% the target nodes. s and t should be vectors of the same size.
%
% g = make_gr('u', n, s, t);
%
% makes an undirected graph with given edges.
%
% For each pair of nodes, only one edge needs to be input.
%
% g = make_gr('d', n, s, t, 'nbs');
% g = make_gr('u', n, s, t, 'nbs');
%
% makes a graph with neighborhood system established.
%
% In the output, g is a struct with the following fields:
%
% - tag: a char string: 'gr'
% - dty: the direction of type: 'd' or 'u'
% - n: the number of nodes
% - m: the number of edges
% - edges: the list of edges (as columns): 2 x m' matrix
% - has_nbs: whether neighborhood system is set up.
%
% If has_nbs is true, it also has the following fields:
%
% - o_nbs: the list of outgoing neighbors: 1 x m'
% - o_eds: the list of outgoing edges: 1 x m'
% - o_degs: the outgoing degrees: 1 x n
% - o_os: the offsets of sections: 1 x n
%
% Here, m' = m when dty == 'd' and m' == 2*m when dty == 'u'
%
% Created by Dahua Lin, on Oct 28, 2011
%
%% verify input arguments
if ~(ischar(dty) && isscalar(dty) && (dty == 'd' || dty == 'u'))
error('make_gr:invalidarg', 'dty should be either ''d'' or ''u''.');
end
if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 0)
error('make_gr:invalidarg', 'n should be a non-negative integer number.');
end
if ~(isnumeric(s) && isvector(s) && isnumeric(t) && isvector(t) && ...
isequal(size(s), size(t)))
error('make_gr:invalidarg', ...
's and t should be a numeric vectors of the same size.');
end
if size(s, 1) > 1; s = s.'; end % turn to row vector
if size(t, 1) > 1; t = t.'; end
if nargin < 5
use_nbs = false;
else
if ~(ischar(op) && strcmpi(op, 'nbs'))
error('make_gr:invalidarg', 'The 5th argument is invalid.');
end
use_nbs = true;
end
%% main
m = numel(s);
g.tag = 'gr';
g.dty = dty;
g.n = int32(n);
g.m = int32(m);
s = int32(s);
t = int32(t);
if dty == 'd'
g.edges = [s; t];
else
g.edges = [s t; t s];
end
g.has_nbs = false;
% setup neighborhood
if use_nbs
g = gr_nbs(g);
end
| zzhangumd-smitoolbox | graph/common/make_gr.m | MATLAB | mit | 2,380 |
function ccs = gr_conncomps(G)
%GR_CONNCOMPS Connected components of undirected graph
%
% ccs = GR_CONNCOMPS(G);
%
% Finds connected components of the graph G.
%
% G should be an undirected graph struct (with neighbor system).
%
% ccs is a 1 x K cell array (K is the number of components), and
% ccs{k} is a row vector of indices of the vertices in the k-th
% component.
%
% Created by Dahua Lin, on Jan 25, 2012
%
%% verify input arguments
if ~(is_gr(G) && isequal(G.dty, 'u') && G.has_nbs)
error('gr_is_connected:invalidarg', ...
'G should be an undirected graph struct (with neighbors).');
end
%% main
ccs = gr_conncomps_cimp(G);
| zzhangumd-smitoolbox | graph/algs/gr_conncomps.m | MATLAB | mit | 683 |
function edges = gr_prim(G, w, rv, msk, max_size, max_w)
%GR_PRIM Prim's Minimum Spanning Tree Algorithm
%
% edges = GR_PRIM(G, w, rv);
% edges = GR_PRIM(G, w, rv, msk);
% edges = GR_PRIM(G, w, rv, msk, max_size);
% edges = GR_PRIM(G, w, rv, msk, max_size, max_w);
%
% Use Prim's algorithm to find a minimum spanning tree with a
% specified root vertex over the given graph G.
%
% The Prim's algorithm grows the tree from a single vertex rv,
% gradually incorporating the edges that connect between a vertex
% that has been in a tree and one that out of the tree.
%
% Input arguments:
% - G: The graph, which should be a undirected graph with
% neighbor system.
%
% - w: The edge weights (a vector of length G.m).
%
% - rv: The root vertex
%
% - msk: The vertex mask. The vertex v is allowed, when
% msk(v) is true. If msk is not specified, then by
% default, all vertices are allowed.
%
% - max_size: The maximum number of vertices in the tree.
% (If not specified, the function grows the tree to
% span the entire connected component that contains rv)
%
% - max_w: The maximum weight of edges that can be incorporated
% in the tree. (If not specified, all edges are allowed)
%
% Note that msk, max_size, and max_w are optional parameters. If
% don't want to enforce one of such constraints, you can input
% the corresponding parameter as an empty array [].
%
% Output arguments:
% - edges: The vertor comprised of the indices of the edges
% included in the tree (in nondecreasing order of
% edge weights)
%
% Created by Dahua Lin, on Jan 26, 2012
%
%% verify input arguments
if ~(is_gr(G) && isequal(G.dty, 'u') && G.has_nbs)
error('gr_prim:invalidarg', ...
'G should be an undirected graph struct (with neighbor system).');
end
n = G.n;
if ~(isfloat(w) && isreal(w) && ~issparse(w) && numel(w) == G.m)
error('gr_prim:invalidarg', ...
'w should be a real vector of length G.m.');
end
w = [w w];
if ~(is_pos_scalar(rv) && rv == fix(rv) && rv <= n)
error('gr_prim:invalidarg', ...
'rv should be a positive integer with rv <= n.');
end
rv = int32(rv);
if nargin < 4 || isempty(msk)
msk = [];
else
if ~(islogical(msk) && isvector(msk) && numel(msk) == n)
error('gr_prim:invalidarg', ...
'msk should be a logical vector of length n.');
end
end
if nargin < 5 || isempty(max_size)
max_size = -1;
else
if ~is_pos_scalar(max_size)
error('gr_prim:invalidarg', ...
'max_size should be a positive scalar.');
end
if max_size >= n
max_size = -1;
end
end
max_size = int32(max_size);
if nargin < 6 || isempty(max_w)
max_w = -1;
else
if ~is_pos_scalar(max_w)
error('gr_prim:invalidarg', ...
'max_size should be a positive scalar.');
end
if isinf(max_w)
max_w = -1;
end
end
max_w = cast(max_w, class(w));
%% main
edges = gr_prim_cimp(G, w, rv, msk, max_size, max_w);
%% Auxiliary function
function tf = is_pos_scalar(x)
tf = isnumeric(x) && isscalar(x) && isreal(x) && x == fix(x) && x > 0;
| zzhangumd-smitoolbox | graph/algs/gr_prim.m | MATLAB | mit | 3,347 |
function [vs, ds] = gr_flood(G, s, msk)
%GR_FLOOD Breadth-first flooding
%
% [vs, ds] = GR_FLOOD(G, s);
% [vs, ds] = GR_FLOOD(G, s, msk);
%
% Performs a breadth-first traversal from specified sources (with
% in allowable region)
%
% Input arguments:
% - G: The graph (with neighbor system)
%
% - s: The source of vector of sources
%
% - msk: The mask of region of interests, which should be
% a logical vector of length G.n.
%
% One can set msk(boundary) to false in order to prevent
% the traversal beyond some boundary.
%
% Output arguments:
% - vs: The vector of vertices listed in the order of visiting.
% (not including the sources)
%
% - ds: The vector of corresponding distances to sources.
%
% Created by Dahua Lin, on Jan 28, 2012
%
%% verify inputs
if ~(is_gr(G) && G.has_nbs)
error('gr_flood:invalidarg', ...
'G should be a graph (with neighbor system).');
end
n = G.n;
if ~(isnumeric(s) && isvector(s) && isreal(s) && ~issparse(s))
error('gr_flood:invalidarg', 's should be a numeric vector.');
end
s = int32(s);
if ~all(s >= 1 & s<= n)
error('gr_flood:invalidarg', 'Some source vertices are not valid.');
end
if nargin < 3 || isempty(msk)
msk = [];
else
if ~(islogical(msk) && numel(msk) == n)
error('gr_flood:invalidarg', ...
'msk should be a logical matrix with n elements.');
end
end
%% main
if nargout <= 1
vs = gr_flood_cimp(G, s, msk);
else
[vs, ds] = gr_flood_cimp(G, s, msk);
end
| zzhangumd-smitoolbox | graph/algs/gr_flood.m | MATLAB | mit | 1,653 |
/***************************************************************
*
* gr_is_connected_cimp.cpp
*
* The C++ mex implementation of gr_is_connected_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/graph/graph_traversal.h>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
/**
* The main entry
*
* Input
* [0] G: the graph struct
*
* Output
* [0] tf: whether G is connected (logical scalar)
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
ginclist_t G = mx_to_ginclist(mG);
// solve
size_t nv = (size_t)G.nvertices();
bool tf = true;
if (nv > 1)
{
size_t cr = count_reachable_vertices(G, make_gvertex(gint(1)));
tf = (cr == nv - 1);
}
// output
plhs[0] = mxCreateLogicalScalar((mxLogical)tf);
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_is_connected_cimp.cpp | C++ | mit | 1,055 |
/***************************************************************
*
* gr_conncomps_cimp.cpp
*
* The C++ mex implementation of gr_conncomps_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/graph/graph_traversal.h>
#include <vector>
#include <list>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
struct ccs_recorder
{
ccs_recorder() : cur_comp(0) { }
void new_component()
{
comp_list.push_back(std::vector<vertex_t>());
cur_comp = &(comp_list.back());
}
void end_component()
{
}
void add_vertex(const vertex_t& v)
{
cur_comp->push_back(v);
}
std::list<std::vector<vertex_t> > comp_list;
std::vector<vertex_t>* cur_comp;
marray moutput() const
{
index_t nc = (index_t)comp_list.size();
marray mCCS = create_mcell_array(1, nc);
std::list<std::vector<vertex_t> >::const_iterator p =
comp_list.begin();
for (index_t i = 0; i < nc; ++i)
{
const std::vector<vertex_t>& vec = *(p++);
caview1d<gint> a((const gint*)(&(vec[0])), (index_t)vec.size());
mCCS.set_cell(i, to_matlab_row(a));
}
return mCCS;
}
};
/**
* The main entry
*
* Input
* [0] G: the graph struct
*
* Output
* [0] ccs: the cell array of components
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
ginclist_t G = mx_to_ginclist(mG);
// solve
ccs_recorder rec;
find_connected_components(G, rec);
// output
marray mCCS = rec.moutput();
plhs[0] = mCCS.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_conncomps_cimp.cpp | C++ | mit | 1,913 |
/***************************************************************
*
* gr_dijkstra_cimp.cpp
*
* The C++ mex implementation of gr_dijkstra_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/graph/graph_shortest_paths.h>
#include <bcslib/array/amap.h>
#include <limits>
#include <vector>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
template<typename T>
struct dijks_agentL1 : public trivial_dijkstra_agent<ginclist_t, T>
{
};
template<typename T>
struct dijks_agentL2 : public trivial_dijkstra_agent<ginclist_t, T>
{
std::vector<gint>& vs;
dijks_agentL2(gint n, std::vector<gint>& vs_) : vs(vs_)
{
vs.reserve(n);
}
bool enroll(const vertex_t& u, const T& )
{
vs.push_back(u.id);
return true;
}
};
template<typename T>
struct dijks_agentL3 : public trivial_dijkstra_agent<ginclist_t, T>
{
std::vector<gint>& vs;
std::vector<gint>& preds;
array_map<vertex_t, vertex_t> pred_map;
dijks_agentL3(gint n, std::vector<gint>& vs_, std::vector<gint>& preds_)
: vs(vs_), preds(preds_), pred_map(n, make_gvertex(0))
{
vs.reserve(n);
}
bool enroll(const vertex_t& u, const T& )
{
vs.push_back(u.id);
preds.push_back(pred_map[u].id);
return true;
}
bool discover(const vertex_t& u, const vertex_t& v, const edge_t&, const T& )
{
pred_map[v] = u;
return true;
}
bool relax(const vertex_t& u, const vertex_t& v, const edge_t&, const T& )
{
pred_map[v] = u;
return true;
}
};
template<typename T>
void do_dijkstra(const ginclist_t& g, const T *w,
index_t ns, const vertex_t *s, int nlhs, mxArray *plhs[])
{
gint n = g.nvertices();
gint m = g.nedges();
// prepare edge-weight map
gint ma = g.is_directed() ? m : 2 * m;
caview_map<edge_t, T> ewmap(w, ma);
// prepare outputs
marray mLens = create_marray<T>(1, n);
aview_map<vertex_t, T> plmap(mLens.data<T>(), n);
std::vector<gint> vs;
std::vector<gint> preds;
// run Dijkstra's algorithm
T inf = std::numeric_limits<T>::infinity();
if (nlhs <= 1)
{
dijks_agentL1<T> agent;
dijkstra_shortest_paths(g, ewmap, plmap, inf, agent, s, s + ns);
}
else if (nlhs == 2)
{
dijks_agentL2<T> agent(n, vs);
dijkstra_shortest_paths(g, ewmap, plmap, inf, agent, s, s + ns);
}
else if (nlhs == 3)
{
dijks_agentL3<T> agent(n, vs, preds);
dijkstra_shortest_paths(g, ewmap, plmap, inf, agent, s, s + ns);
}
// extract outputs
plhs[0] = mLens.mx_ptr();
if (nlhs > 1) plhs[1] = to_matlab_row(vs).mx_ptr();
if (nlhs > 2) plhs[2] = to_matlab_row(preds).mx_ptr();
}
/**
* The main entry
*
* Input
* [0] G: the graph struct
* [1] w: the edge weights
* [2] s: tht vectex of sources
*
* Output
* [0] lens: the shortest path lengths to all vertices
* [1] vs: the vector of vertices in ascending order of shortest
* path lengths
* [2] preds: the vector of corresponding predecessors
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
ginclist_t G = mx_to_ginclist(mG);
const_marray mW(prhs[1]);
const_marray mS(prhs[2]);
index_t ns = mS.nelems();
const vertex_t* s = mS.data<vertex_t>();
// solve
mxClassID cid = mW.class_id();
if (cid == mxDOUBLE_CLASS)
{
do_dijkstra(G, mW.data<double>(), ns, s, nlhs, plhs);
}
else if (cid == mxSINGLE_CLASS)
{
do_dijkstra(G, mW.data<float>(), ns, s, nlhs, plhs);
}
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_dijkstra_cimp.cpp | C++ | mit | 4,019 |
/***************************************************************
*
* gr_flood_cimp.cpp
*
* The C++ mex implementation of gr_dijkstra_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/array/array1d.h>
#include <bcslib/graph/graph_traversal.h>
#include <vector>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
struct whole_roi
{
bool viable(const vertex_t& v)
{
return true;
}
};
struct mask_roi
{
const bool *msk;
mask_roi(const bool *msk_) : msk(msk_)
{
}
bool viable(const vertex_t& v)
{
return msk[v.index()];
}
};
template<class ROI>
struct bfs_vis : public trivial_traversal_agent<ginclist_t>
{
std::vector<gint>& vs;
ROI& roi;
bfs_vis(std::vector<gint>& vs_, ROI& roi_)
: vs(vs_), roi(roi_) { }
bool discover(const vertex_t& u, const vertex_t& v)
{
vs.push_back(v.id);
return true;
}
bool examine(const vertex_t& u, const vertex_t& v, gvisit_status)
{
return roi.viable(v);
}
};
template<class ROI>
struct bfs_visd : public trivial_traversal_agent<ginclist_t>
{
std::vector<gint>& vs;
ROI& roi;
array1d<int32_t>& dmap;
bfs_visd(std::vector<gint>& vs_, ROI& roi_, array1d<int32_t>& dmap_)
: vs(vs_), roi(roi_), dmap(dmap_) { }
bool discover(const vertex_t& u, const vertex_t& v)
{
vs.push_back(v.id);
dmap[v.index()] = dmap[u.index()] + 1;
return true;
}
bool examine(const vertex_t& u, const vertex_t& v, gvisit_status)
{
return roi.viable(v);
}
};
void do_flood(const ginclist_t& G, const vertex_t *s, gint ns, const bool *msk,
int nlhs, mxArray *plhs[])
{
if (nlhs <= 1)
{
std::vector<gint> vs;
if (!msk)
{
whole_roi roi;
bfs_vis<whole_roi> vis(vs, roi);
breadth_first_traverse(G, vis, s, s + ns);
}
else
{
mask_roi roi(msk);
bfs_vis<mask_roi> vis(vs, roi);
breadth_first_traverse(G, vis, s, s + ns);
}
plhs[0] = to_matlab_row(vs).mx_ptr();
}
else
{
std::vector<gint> vs;
array1d<int32_t> dmap(G.nvertices(), int32_t(0));
if (!msk)
{
whole_roi roi;
bfs_visd<whole_roi> vis(vs, roi, dmap);
breadth_first_traverse(G, vis, s, s + ns);
}
else
{
mask_roi roi(msk);
bfs_visd<mask_roi> vis(vs, roi, dmap);
breadth_first_traverse(G, vis, s, s + ns);
}
std::vector<int32_t> ds;
for (std::vector<int32_t>::const_iterator it = vs.begin();
it != vs.end(); ++it)
{
ds.push_back(dmap[(*it) - 1]);
}
plhs[0] = to_matlab_row(vs).mx_ptr();
plhs[1] = to_matlab_row(ds).mx_ptr();
}
}
/**
* Inputs:
*
* [0] G: The graph
* [1] s: The vector of sources
* [2] msk: The mask of ROI
*
* Outputs:
* [0] vs: visited vertices
* [1] ds: distances to sources
*
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
ginclist_t G = mx_to_ginclist(mG);
const_marray mS(prhs[1]);
gint ns = mS.nelems();
const vertex_t* s = mS.data<vertex_t>();
const_marray mMsk(prhs[2]);
const bool *msk = mMsk.is_empty() ? (const bool*)(0) : mMsk.data<bool>();
// solve
do_flood(G, s, ns, msk, nlhs, plhs);
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_flood_cimp.cpp | C++ | mit | 3,827 |
/***************************************************************
*
* gr_kruskal_cimp.cpp
*
* The C++ mex implementation of gr_dijkstra_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/graph/graph_minimum_span_trees.h>
#include <bcslib/array/amap.h>
#include <bcslib/base/smart_ptr.h>
#include <vector>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
// monitor agents
class krus_monitor
{
public:
krus_monitor(std::vector<int32_t>& eds)
: edges(eds)
{
}
bool examine_edge(const vertex_t&, const vertex_t&, const edge_t&)
{
return true;
}
bool add_edge(const vertex_t&, const vertex_t&, const edge_t& e)
{
edges.push_back(e.id);
return true;
}
private:
std::vector<int32_t>& edges;
};
class krus_monitor2
{
public:
krus_monitor2(std::vector<int32_t>& eds,
disjoint_set_forest<vertex_t>& ds, int K_)
: edges(eds), dsets(ds), K(K_)
{
}
bool examine_edge(const vertex_t&, const vertex_t&, const edge_t&)
{
return true;
}
bool add_edge(const vertex_t&, const vertex_t&, const edge_t& e)
{
edges.push_back(e.id);
return dsets.ncomponents() > K;
}
private:
std::vector<int32_t>& edges;
disjoint_set_forest<vertex_t>& dsets;
size_t K;
};
marray get_ccs(disjoint_set_forest<vertex_t>& dsets)
{
typedef std::vector<int32_t> compvec_t;
std::vector<bcs::shared_ptr<compvec_t> > comps;
index_t n = (index_t)dsets.size();
// scan clusters
array1d<int32_t> L(n);
mem<int32_t>::zero((size_t)n, L.pbase());
int32_t m = 0;
for (index_t i = 0; i < n; ++i)
{
vertex_t v;
v.id = i + 1;
index_t r = dsets.find_root(v);
int32_t k = L(r);
if (k == 0)
{
k = (L(r) = ++m);
comps.push_back(bcs::shared_ptr<compvec_t>(new compvec_t()));
}
comps[k-1]->push_back(int32_t(i+1));
}
// convert the results to marray
marray mCCS = create_mcell_array(1, m);
for (int32_t k = 0; k < m; ++k)
{
const compvec_t& cvec = *(comps[k]);
mCCS.set_cell(k, to_matlab_row(cvec));
}
return mCCS;
}
// core function
template<typename T>
void do_kruskal(const gedgelist_t& G, const T* w, int K, int nlhs, mxArray *plhs[])
{
// prepare edge-weight map
caview_map<edge_t, T> ewmap(w, 2 * G.nedges());
// prepare outputs
disjoint_set_forest<vertex_t> dsets(G.nvertices());
std::vector<int32_t> edges;
// run
if (K == 1)
{
krus_monitor mon(edges);
kruskal_minimum_span_tree_ex(G, ewmap, dsets, mon);
}
else
{
krus_monitor2 mon(edges, dsets, K);
kruskal_minimum_span_tree_ex(G, ewmap, dsets, mon);
}
// extract outputs
plhs[0] = to_matlab_row(edges).mx_ptr();
if (nlhs > 1)
{
plhs[1] = get_ccs(dsets).mx_ptr();
}
}
/**
* The main entry
*
* Input
* [0] G: the graph struct
* [1] w: the edge weights
* [2] K: the number of components
*
* Output
* [0] edges: the edges of the spanning tree
* [1] ccs: the cell array of connected components
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
gedgelist_t G = mx_to_gedgelist(mG);
const_marray mW(prhs[1]);
const_marray mK(prhs[2]);
int K = (int)mK.get_scalar<int32_t>();
// solve
mxClassID cid = mW.class_id();
if (cid == mxDOUBLE_CLASS)
{
do_kruskal(G, mW.data<double>(), K, nlhs, plhs);
}
else if (cid == mxSINGLE_CLASS)
{
do_kruskal(G, mW.data<float>(), K, nlhs, plhs);
}
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_kruskal_cimp.cpp | C++ | mit | 4,091 |
/***************************************************************
*
* gr_prim_cimp.cpp
*
* The C++ mex implementation of gr_prim_cimp
*
* Created by Dahua Lin, on Jan 26, 2012
*
***************************************************************/
#include "../../clib/smi_graph_mex.h"
#include <bcslib/graph/graph_minimum_span_trees.h>
#include <bcslib/array/amap.h>
#include <vector>
using namespace bcs;
using namespace bcs::matlab;
using namespace smi;
// agents
template<typename T>
class prim_monitor
{
public:
prim_monitor(std::vector<int32_t>& eds,
const bool *vmsk,
const T* eweights,
const gint& max_size,
const T& max_w)
: edges(eds), m_vmsk(vmsk), m_eweights(eweights)
, m_max_size(max_size), m_max_w(max_w)
{
}
bool examine_edge(const vertex_t&, const vertex_t& v, const edge_t& e)
{
return (!m_vmsk || m_vmsk[v.index()]) &&
(m_max_w < 0 || m_eweights[e.index()] <= m_max_w);
return true;
}
bool add_edge(const vertex_t&, const vertex_t&, const edge_t& e)
{
edges.push_back(e.id);
return m_max_size < 0 || ((gint)edges.size() + 1 < m_max_size);
}
std::vector<int32_t>& edges;
private:
const bool *m_vmsk;
const T* m_eweights;
gint m_max_size;
T m_max_w;
};
// core algorithm
template<typename T>
void do_prim(const ginclist_t& G, const T *w, const vertex_t& rv,
const bool* vmsk, gint max_size, T max_w,
std::vector<int32_t>& edges)
{
size_t ma = max_size < 0 ? G.nvertices() : max_size;
edges.reserve(ma);
caview_map<edge_t, T> ewmap(w, G.nedges() * 2);
prim_monitor<T> mon(edges, vmsk, w, max_size, max_w);
prim_minimum_span_tree_ex(G, ewmap, rv, mon);
}
/**
* The main entry
*
* Input
* [0] G: the graph struct
* [1] w: the edge weights
* [2] rv: the root vertex
* [3] msk: the vertex mask
* [4] max_size: the maximum component size
* [5] max_w: the maximum weight
*
* Output
* [0] edges: the edges of the spanning tree
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take inputs
const_marray mG(prhs[0]);
const_marray mW(prhs[1]);
const_marray mRv(prhs[2]);
const_marray mMsk(prhs[3]);
const_marray mMaxSize(prhs[4]);
const_marray mMaxW(prhs[5]);
ginclist_t G = mx_to_ginclist(mG);
gint rv_id = mRv.get_scalar<gint>();
vertex_t rv = make_gvertex(rv_id);
const bool *vmsk = (mMsk.is_empty() ? (const bool*)(0) : mMsk.data<bool>());
gint max_size = (gint)mMaxSize.get_scalar<gint>();
// solve
mxClassID cid = mW.class_id();
std::vector<int32_t> edges;
if (cid == mxDOUBLE_CLASS)
{
double max_w = mMaxW.get_scalar<double>();
do_prim(G, mW.data<double>(), rv, vmsk, max_size, max_w, edges);
}
else if (cid == mxSINGLE_CLASS)
{
float max_w = mMaxW.get_scalar<float>();
do_prim(G, mW.data<float>(), rv, vmsk, max_size, max_w, edges);
}
// extract output
plhs[0] = to_matlab_row(edges).mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | graph/algs/private/gr_prim_cimp.cpp | C++ | mit | 3,301 |
function [lens, vs, preds] = gr_dijkstra(G, w, s)
%GR_DIJKSTRA Single-source shortest paths
%
% [vs, lens] = GR_DIJKSTRA(G, w, s);
% [vs, lens, preds] = GR_DIJKSTRA(G, w, s);
%
% Find the shortest paths to all vertices of the graph from
% specific source using Dijkstra's algorithm.
%
% Input arguments
% - G: The graph with neighborhood system. Both directed and
% undirected graphs are supported.
%
% - w: The edge weights (a vector of length m)
%
% - s: The source, which can be either a single vertex, or
% multiple vertices (considered as a single source as
% a whole)
%
% Output arguments
% - vs: The list of all visited vertices. The vertices in vs
% are in ascending order of shortest path lengths.
%
% - lens: The vector of corresponding shortest path lengths.
%
% - preds: The vector of corresponding predecessors.
%
% Specifically, lens(i) and preds(i) are respectively the shortest
% path length and predecessor (along the shortest path) of the
% vertex i.
%
% Remarks
% -------
% - The edge weights in w should all be non-negative for using
% Dijkstra's algorithm, otherwise incorrect results might be
% returned.
%
% Created by Dahua Lin, on Jan 26, 2012
%
%% verify input arguments
if ~(is_gr(G) && G.has_nbs)
error('gr_dijkstra:invalidarg', ...
'G should be a graph with neighbor system.');
end
if ~(isfloat(w) && isreal(w) && ~issparse(w) && isvector(w) && length(w) == G.m)
error('gr_dijkstra:invalidarg', ...
'w should be a non-sparse real vector of length G.m.');
end
if G.dty == 'u'
w = [w w]; % no matter whether w is column or row, this is ok
end
if ~(isnumeric(s) && isreal(s) && ~isempty(s) && ~issparse(s) && isvector(s))
error('gr_dijkstra:invalidarg', ...
's should be a non-empty numeric vector of indices.');
end
s = int32(s);
%% main
if nargout <= 1
lens = gr_dijkstra_cimp(G, w, s);
elseif nargout == 2
[lens, vs] = gr_dijkstra_cimp(G, w, s);
else
[lens, vs, preds] = gr_dijkstra_cimp(G, w, s);
end
| zzhangumd-smitoolbox | graph/algs/gr_dijkstra.m | MATLAB | mit | 2,250 |