repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
|---|---|---|---|---|---|---|
null |
LRMI-main/unsupported/Eigen/src/NonLinearOptimization/lmpar.h
|
namespace Eigen {
namespace internal {
template <typename Scalar>
void lmpar(
Matrix< Scalar, Dynamic, Dynamic > &r,
const VectorXi &ipvt,
const Matrix< Scalar, Dynamic, 1 > &diag,
const Matrix< Scalar, Dynamic, 1 > &qtb,
Scalar delta,
Scalar &par,
Matrix< Scalar, Dynamic, 1 > &x)
{
using std::abs;
using std::sqrt;
typedef DenseIndex Index;
/* Local variables */
Index i, j, l;
Scalar fp;
Scalar parc, parl;
Index iter;
Scalar temp, paru;
Scalar gnorm;
Scalar dxnorm;
/* Function Body */
const Scalar dwarf = (std::numeric_limits<Scalar>::min)();
const Index n = r.cols();
eigen_assert(n==diag.size());
eigen_assert(n==qtb.size());
eigen_assert(n==x.size());
Matrix< Scalar, Dynamic, 1 > wa1, wa2;
/* compute and store in x the gauss-newton direction. if the */
/* jacobian is rank-deficient, obtain a least squares solution. */
Index nsing = n-1;
wa1 = qtb;
for (j = 0; j < n; ++j) {
if (r(j,j) == 0. && nsing == n-1)
nsing = j - 1;
if (nsing < n-1)
wa1[j] = 0.;
}
for (j = nsing; j>=0; --j) {
wa1[j] /= r(j,j);
temp = wa1[j];
for (i = 0; i < j ; ++i)
wa1[i] -= r(i,j) * temp;
}
for (j = 0; j < n; ++j)
x[ipvt[j]] = wa1[j];
/* initialize the iteration counter. */
/* evaluate the function at the origin, and test */
/* for acceptance of the gauss-newton direction. */
iter = 0;
wa2 = diag.cwiseProduct(x);
dxnorm = wa2.blueNorm();
fp = dxnorm - delta;
if (fp <= Scalar(0.1) * delta) {
par = 0;
return;
}
/* if the jacobian is not rank deficient, the newton */
/* step provides a lower bound, parl, for the zero of */
/* the function. otherwise set this bound to zero. */
parl = 0.;
if (nsing >= n-1) {
for (j = 0; j < n; ++j) {
l = ipvt[j];
wa1[j] = diag[l] * (wa2[l] / dxnorm);
}
// it's actually a triangularView.solveInplace(), though in a weird
// way:
for (j = 0; j < n; ++j) {
Scalar sum = 0.;
for (i = 0; i < j; ++i)
sum += r(i,j) * wa1[i];
wa1[j] = (wa1[j] - sum) / r(j,j);
}
temp = wa1.blueNorm();
parl = fp / delta / temp / temp;
}
/* calculate an upper bound, paru, for the zero of the function. */
for (j = 0; j < n; ++j)
wa1[j] = r.col(j).head(j+1).dot(qtb.head(j+1)) / diag[ipvt[j]];
gnorm = wa1.stableNorm();
paru = gnorm / delta;
if (paru == 0.)
paru = dwarf / (std::min)(delta,Scalar(0.1));
/* if the input par lies outside of the interval (parl,paru), */
/* set par to the closer endpoint. */
par = (std::max)(par,parl);
par = (std::min)(par,paru);
if (par == 0.)
par = gnorm / dxnorm;
/* beginning of an iteration. */
while (true) {
++iter;
/* evaluate the function at the current value of par. */
if (par == 0.)
par = (std::max)(dwarf,Scalar(.001) * paru); /* Computing MAX */
wa1 = sqrt(par)* diag;
Matrix< Scalar, Dynamic, 1 > sdiag(n);
qrsolv<Scalar>(r, ipvt, wa1, qtb, x, sdiag);
wa2 = diag.cwiseProduct(x);
dxnorm = wa2.blueNorm();
temp = fp;
fp = dxnorm - delta;
/* if the function is small enough, accept the current value */
/* of par. also test for the exceptional cases where parl */
/* is zero or the number of iterations has reached 10. */
if (abs(fp) <= Scalar(0.1) * delta || (parl == 0. && fp <= temp && temp < 0.) || iter == 10)
break;
/* compute the newton correction. */
for (j = 0; j < n; ++j) {
l = ipvt[j];
wa1[j] = diag[l] * (wa2[l] / dxnorm);
}
for (j = 0; j < n; ++j) {
wa1[j] /= sdiag[j];
temp = wa1[j];
for (i = j+1; i < n; ++i)
wa1[i] -= r(i,j) * temp;
}
temp = wa1.blueNorm();
parc = fp / delta / temp / temp;
/* depending on the sign of the function, update parl or paru. */
if (fp > 0.)
parl = (std::max)(parl,par);
if (fp < 0.)
paru = (std::min)(paru,par);
/* compute an improved estimate for par. */
/* Computing MAX */
par = (std::max)(parl,par+parc);
/* end of an iteration. */
}
/* termination. */
if (iter == 0)
par = 0.;
return;
}
template <typename Scalar>
void lmpar2(
const ColPivHouseholderQR<Matrix< Scalar, Dynamic, Dynamic> > &qr,
const Matrix< Scalar, Dynamic, 1 > &diag,
const Matrix< Scalar, Dynamic, 1 > &qtb,
Scalar delta,
Scalar &par,
Matrix< Scalar, Dynamic, 1 > &x)
{
using std::sqrt;
using std::abs;
typedef DenseIndex Index;
/* Local variables */
Index j;
Scalar fp;
Scalar parc, parl;
Index iter;
Scalar temp, paru;
Scalar gnorm;
Scalar dxnorm;
/* Function Body */
const Scalar dwarf = (std::numeric_limits<Scalar>::min)();
const Index n = qr.matrixQR().cols();
eigen_assert(n==diag.size());
eigen_assert(n==qtb.size());
Matrix< Scalar, Dynamic, 1 > wa1, wa2;
/* compute and store in x the gauss-newton direction. if the */
/* jacobian is rank-deficient, obtain a least squares solution. */
// const Index rank = qr.nonzeroPivots(); // exactly double(0.)
const Index rank = qr.rank(); // use a threshold
wa1 = qtb;
wa1.tail(n-rank).setZero();
qr.matrixQR().topLeftCorner(rank, rank).template triangularView<Upper>().solveInPlace(wa1.head(rank));
x = qr.colsPermutation()*wa1;
/* initialize the iteration counter. */
/* evaluate the function at the origin, and test */
/* for acceptance of the gauss-newton direction. */
iter = 0;
wa2 = diag.cwiseProduct(x);
dxnorm = wa2.blueNorm();
fp = dxnorm - delta;
if (fp <= Scalar(0.1) * delta) {
par = 0;
return;
}
/* if the jacobian is not rank deficient, the newton */
/* step provides a lower bound, parl, for the zero of */
/* the function. otherwise set this bound to zero. */
parl = 0.;
if (rank==n) {
wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2)/dxnorm;
qr.matrixQR().topLeftCorner(n, n).transpose().template triangularView<Lower>().solveInPlace(wa1);
temp = wa1.blueNorm();
parl = fp / delta / temp / temp;
}
/* calculate an upper bound, paru, for the zero of the function. */
for (j = 0; j < n; ++j)
wa1[j] = qr.matrixQR().col(j).head(j+1).dot(qtb.head(j+1)) / diag[qr.colsPermutation().indices()(j)];
gnorm = wa1.stableNorm();
paru = gnorm / delta;
if (paru == 0.)
paru = dwarf / (std::min)(delta,Scalar(0.1));
/* if the input par lies outside of the interval (parl,paru), */
/* set par to the closer endpoint. */
par = (std::max)(par,parl);
par = (std::min)(par,paru);
if (par == 0.)
par = gnorm / dxnorm;
/* beginning of an iteration. */
Matrix< Scalar, Dynamic, Dynamic > s = qr.matrixQR();
while (true) {
++iter;
/* evaluate the function at the current value of par. */
if (par == 0.)
par = (std::max)(dwarf,Scalar(.001) * paru); /* Computing MAX */
wa1 = sqrt(par)* diag;
Matrix< Scalar, Dynamic, 1 > sdiag(n);
qrsolv<Scalar>(s, qr.colsPermutation().indices(), wa1, qtb, x, sdiag);
wa2 = diag.cwiseProduct(x);
dxnorm = wa2.blueNorm();
temp = fp;
fp = dxnorm - delta;
/* if the function is small enough, accept the current value */
/* of par. also test for the exceptional cases where parl */
/* is zero or the number of iterations has reached 10. */
if (abs(fp) <= Scalar(0.1) * delta || (parl == 0. && fp <= temp && temp < 0.) || iter == 10)
break;
/* compute the newton correction. */
wa1 = qr.colsPermutation().inverse() * diag.cwiseProduct(wa2/dxnorm);
// we could almost use this here, but the diagonal is outside qr, in sdiag[]
// qr.matrixQR().topLeftCorner(n, n).transpose().template triangularView<Lower>().solveInPlace(wa1);
for (j = 0; j < n; ++j) {
wa1[j] /= sdiag[j];
temp = wa1[j];
for (Index i = j+1; i < n; ++i)
wa1[i] -= s(i,j) * temp;
}
temp = wa1.blueNorm();
parc = fp / delta / temp / temp;
/* depending on the sign of the function, update parl or paru. */
if (fp > 0.)
parl = (std::max)(parl,par);
if (fp < 0.)
paru = (std::min)(paru,par);
/* compute an improved estimate for par. */
par = (std::max)(parl,par+parc);
}
if (iter == 0)
par = 0.;
return;
}
} // end namespace internal
} // end namespace Eigen
| 9,111
| 29.474916
| 109
|
h
|
null |
LRMI-main/unsupported/Eigen/src/NonLinearOptimization/qrsolv.h
|
namespace Eigen {
namespace internal {
// TODO : once qrsolv2 is removed, use ColPivHouseholderQR or PermutationMatrix instead of ipvt
template <typename Scalar>
void qrsolv(
Matrix< Scalar, Dynamic, Dynamic > &s,
// TODO : use a PermutationMatrix once lmpar is no more:
const VectorXi &ipvt,
const Matrix< Scalar, Dynamic, 1 > &diag,
const Matrix< Scalar, Dynamic, 1 > &qtb,
Matrix< Scalar, Dynamic, 1 > &x,
Matrix< Scalar, Dynamic, 1 > &sdiag)
{
typedef DenseIndex Index;
/* Local variables */
Index i, j, k, l;
Scalar temp;
Index n = s.cols();
Matrix< Scalar, Dynamic, 1 > wa(n);
JacobiRotation<Scalar> givens;
/* Function Body */
// the following will only change the lower triangular part of s, including
// the diagonal, though the diagonal is restored afterward
/* copy r and (q transpose)*b to preserve input and initialize s. */
/* in particular, save the diagonal elements of r in x. */
x = s.diagonal();
wa = qtb;
s.topLeftCorner(n,n).template triangularView<StrictlyLower>() = s.topLeftCorner(n,n).transpose();
/* eliminate the diagonal matrix d using a givens rotation. */
for (j = 0; j < n; ++j) {
/* prepare the row of d to be eliminated, locating the */
/* diagonal element using p from the qr factorization. */
l = ipvt[j];
if (diag[l] == 0.)
break;
sdiag.tail(n-j).setZero();
sdiag[j] = diag[l];
/* the transformations to eliminate the row of d */
/* modify only a single element of (q transpose)*b */
/* beyond the first n, which is initially zero. */
Scalar qtbpj = 0.;
for (k = j; k < n; ++k) {
/* determine a givens rotation which eliminates the */
/* appropriate element in the current row of d. */
givens.makeGivens(-s(k,k), sdiag[k]);
/* compute the modified diagonal element of r and */
/* the modified element of ((q transpose)*b,0). */
s(k,k) = givens.c() * s(k,k) + givens.s() * sdiag[k];
temp = givens.c() * wa[k] + givens.s() * qtbpj;
qtbpj = -givens.s() * wa[k] + givens.c() * qtbpj;
wa[k] = temp;
/* accumulate the transformation in the row of s. */
for (i = k+1; i<n; ++i) {
temp = givens.c() * s(i,k) + givens.s() * sdiag[i];
sdiag[i] = -givens.s() * s(i,k) + givens.c() * sdiag[i];
s(i,k) = temp;
}
}
}
/* solve the triangular system for z. if the system is */
/* singular, then obtain a least squares solution. */
Index nsing;
for(nsing=0; nsing<n && sdiag[nsing]!=0; nsing++) {}
wa.tail(n-nsing).setZero();
s.topLeftCorner(nsing, nsing).transpose().template triangularView<Upper>().solveInPlace(wa.head(nsing));
// restore
sdiag = s.diagonal();
s.diagonal() = x;
/* permute the components of z back to components of x. */
for (j = 0; j < n; ++j) x[ipvt[j]] = wa[j];
}
} // end namespace internal
} // end namespace Eigen
| 3,264
| 34.48913
| 108
|
h
|
null |
LRMI-main/unsupported/Eigen/src/NonLinearOptimization/r1updt.h
|
namespace Eigen {
namespace internal {
template <typename Scalar>
void r1updt(
Matrix< Scalar, Dynamic, Dynamic > &s,
const Matrix< Scalar, Dynamic, 1> &u,
std::vector<JacobiRotation<Scalar> > &v_givens,
std::vector<JacobiRotation<Scalar> > &w_givens,
Matrix< Scalar, Dynamic, 1> &v,
Matrix< Scalar, Dynamic, 1> &w,
bool *sing)
{
typedef DenseIndex Index;
const JacobiRotation<Scalar> IdentityRotation = JacobiRotation<Scalar>(1,0);
/* Local variables */
const Index m = s.rows();
const Index n = s.cols();
Index i, j=1;
Scalar temp;
JacobiRotation<Scalar> givens;
// r1updt had a broader usecase, but we don't use it here. And, more
// importantly, we can not test it.
eigen_assert(m==n);
eigen_assert(u.size()==m);
eigen_assert(v.size()==n);
eigen_assert(w.size()==n);
/* move the nontrivial part of the last column of s into w. */
w[n-1] = s(n-1,n-1);
/* rotate the vector v into a multiple of the n-th unit vector */
/* in such a way that a spike is introduced into w. */
for (j=n-2; j>=0; --j) {
w[j] = 0.;
if (v[j] != 0.) {
/* determine a givens rotation which eliminates the */
/* j-th element of v. */
givens.makeGivens(-v[n-1], v[j]);
/* apply the transformation to v and store the information */
/* necessary to recover the givens rotation. */
v[n-1] = givens.s() * v[j] + givens.c() * v[n-1];
v_givens[j] = givens;
/* apply the transformation to s and extend the spike in w. */
for (i = j; i < m; ++i) {
temp = givens.c() * s(j,i) - givens.s() * w[i];
w[i] = givens.s() * s(j,i) + givens.c() * w[i];
s(j,i) = temp;
}
} else
v_givens[j] = IdentityRotation;
}
/* add the spike from the rank 1 update to w. */
w += v[n-1] * u;
/* eliminate the spike. */
*sing = false;
for (j = 0; j < n-1; ++j) {
if (w[j] != 0.) {
/* determine a givens rotation which eliminates the */
/* j-th element of the spike. */
givens.makeGivens(-s(j,j), w[j]);
/* apply the transformation to s and reduce the spike in w. */
for (i = j; i < m; ++i) {
temp = givens.c() * s(j,i) + givens.s() * w[i];
w[i] = -givens.s() * s(j,i) + givens.c() * w[i];
s(j,i) = temp;
}
/* store the information necessary to recover the */
/* givens rotation. */
w_givens[j] = givens;
} else
v_givens[j] = IdentityRotation;
/* test for zero diagonal elements in the output s. */
if (s(j,j) == 0.) {
*sing = true;
}
}
/* move w back into the last column of the output s. */
s(n-1,n-1) = w[n-1];
if (s(j,j) == 0.) {
*sing = true;
}
return;
}
} // end namespace internal
} // end namespace Eigen
| 3,083
| 29.84
| 80
|
h
|
null |
LRMI-main/unsupported/Eigen/src/NonLinearOptimization/rwupdt.h
|
namespace Eigen {
namespace internal {
template <typename Scalar>
void rwupdt(
Matrix< Scalar, Dynamic, Dynamic > &r,
const Matrix< Scalar, Dynamic, 1> &w,
Matrix< Scalar, Dynamic, 1> &b,
Scalar alpha)
{
typedef DenseIndex Index;
const Index n = r.cols();
eigen_assert(r.rows()>=n);
std::vector<JacobiRotation<Scalar> > givens(n);
/* Local variables */
Scalar temp, rowj;
/* Function Body */
for (Index j = 0; j < n; ++j) {
rowj = w[j];
/* apply the previous transformations to */
/* r(i,j), i=0,1,...,j-1, and to w(j). */
for (Index i = 0; i < j; ++i) {
temp = givens[i].c() * r(i,j) + givens[i].s() * rowj;
rowj = -givens[i].s() * r(i,j) + givens[i].c() * rowj;
r(i,j) = temp;
}
/* determine a givens rotation which eliminates w(j). */
givens[j].makeGivens(-r(j,j), rowj);
if (rowj == 0.)
continue; // givens[j] is identity
/* apply the current transformation to r(j,j), b(j), and alpha. */
r(j,j) = givens[j].c() * r(j,j) + givens[j].s() * rowj;
temp = givens[j].c() * b[j] + givens[j].s() * alpha;
alpha = -givens[j].s() * b[j] + givens[j].c() * alpha;
b[j] = temp;
}
}
} // end namespace internal
} // end namespace Eigen
| 1,362
| 26.26
| 74
|
h
|
null |
LRMI-main/unsupported/Eigen/src/NumericalDiff/NumericalDiff.h
|
// -*- coding: utf-8
// vim: set fileencoding=utf-8
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Thomas Capricelli <orzel@freehackers.org>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NUMERICAL_DIFF_H
#define EIGEN_NUMERICAL_DIFF_H
namespace Eigen {
enum NumericalDiffMode {
Forward,
Central
};
/**
* This class allows you to add a method df() to your functor, which will
* use numerical differentiation to compute an approximate of the
* derivative for the functor. Of course, if you have an analytical form
* for the derivative, you should rather implement df() by yourself.
*
* More information on
* http://en.wikipedia.org/wiki/Numerical_differentiation
*
* Currently only "Forward" and "Central" scheme are implemented.
*/
template<typename _Functor, NumericalDiffMode mode=Forward>
class NumericalDiff : public _Functor
{
public:
typedef _Functor Functor;
typedef typename Functor::Scalar Scalar;
typedef typename Functor::InputType InputType;
typedef typename Functor::ValueType ValueType;
typedef typename Functor::JacobianType JacobianType;
NumericalDiff(Scalar _epsfcn=0.) : Functor(), epsfcn(_epsfcn) {}
NumericalDiff(const Functor& f, Scalar _epsfcn=0.) : Functor(f), epsfcn(_epsfcn) {}
// forward constructors
template<typename T0>
NumericalDiff(const T0& a0) : Functor(a0), epsfcn(0) {}
template<typename T0, typename T1>
NumericalDiff(const T0& a0, const T1& a1) : Functor(a0, a1), epsfcn(0) {}
template<typename T0, typename T1, typename T2>
NumericalDiff(const T0& a0, const T1& a1, const T2& a2) : Functor(a0, a1, a2), epsfcn(0) {}
enum {
InputsAtCompileTime = Functor::InputsAtCompileTime,
ValuesAtCompileTime = Functor::ValuesAtCompileTime
};
/**
* return the number of evaluation of functor
*/
int df(const InputType& _x, JacobianType &jac) const
{
using std::sqrt;
using std::abs;
/* Local variables */
Scalar h;
int nfev=0;
const typename InputType::Index n = _x.size();
const Scalar eps = sqrt(((std::max)(epsfcn,NumTraits<Scalar>::epsilon() )));
ValueType val1, val2;
InputType x = _x;
// TODO : we should do this only if the size is not already known
val1.resize(Functor::values());
val2.resize(Functor::values());
// initialization
switch(mode) {
case Forward:
// compute f(x)
Functor::operator()(x, val1); nfev++;
break;
case Central:
// do nothing
break;
default:
eigen_assert(false);
};
// Function Body
for (int j = 0; j < n; ++j) {
h = eps * abs(x[j]);
if (h == 0.) {
h = eps;
}
switch(mode) {
case Forward:
x[j] += h;
Functor::operator()(x, val2);
nfev++;
x[j] = _x[j];
jac.col(j) = (val2-val1)/h;
break;
case Central:
x[j] += h;
Functor::operator()(x, val2); nfev++;
x[j] -= 2*h;
Functor::operator()(x, val1); nfev++;
x[j] = _x[j];
jac.col(j) = (val2-val1)/(2*h);
break;
default:
eigen_assert(false);
};
}
return nfev;
}
private:
Scalar epsfcn;
NumericalDiff& operator=(const NumericalDiff&);
};
} // end namespace Eigen
//vim: ai ts=4 sts=4 et sw=4
#endif // EIGEN_NUMERICAL_DIFF_H
| 4,020
| 29.694656
| 99
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Polynomials/Companion.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMPANION_H
#define EIGEN_COMPANION_H
// This file requires the user to include
// * Eigen/Core
// * Eigen/src/PolynomialSolver.h
namespace Eigen {
namespace internal {
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<int Size>
struct decrement_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size-1 };
};
#endif
template< typename _Scalar, int _Deg >
class companion
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_Deg==Dynamic ? Dynamic : _Deg)
enum {
Deg = _Deg,
Deg_1=decrement_if_fixed_size<Deg>::ret
};
typedef _Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, Deg, 1> RightColumn;
//typedef DiagonalMatrix< Scalar, Deg_1, Deg_1 > BottomLeftDiagonal;
typedef Matrix<Scalar, Deg_1, 1> BottomLeftDiagonal;
typedef Matrix<Scalar, Deg, Deg> DenseCompanionMatrixType;
typedef Matrix< Scalar, _Deg, Deg_1 > LeftBlock;
typedef Matrix< Scalar, Deg_1, Deg_1 > BottomLeftBlock;
typedef Matrix< Scalar, 1, Deg_1 > LeftBlockFirstRow;
typedef DenseIndex Index;
public:
EIGEN_STRONG_INLINE const _Scalar operator()(Index row, Index col ) const
{
if( m_bl_diag.rows() > col )
{
if( 0 < row ){ return m_bl_diag[col]; }
else{ return 0; }
}
else{ return m_monic[row]; }
}
public:
template<typename VectorType>
void setPolynomial( const VectorType& poly )
{
const Index deg = poly.size()-1;
m_monic = -poly.head(deg)/poly[deg];
m_bl_diag.setOnes(deg-1);
}
template<typename VectorType>
companion( const VectorType& poly ){
setPolynomial( poly ); }
public:
DenseCompanionMatrixType denseMatrix() const
{
const Index deg = m_monic.size();
const Index deg_1 = deg-1;
DenseCompanionMatrixType companMat(deg,deg);
companMat <<
( LeftBlock(deg,deg_1)
<< LeftBlockFirstRow::Zero(1,deg_1),
BottomLeftBlock::Identity(deg-1,deg-1)*m_bl_diag.asDiagonal() ).finished()
, m_monic;
return companMat;
}
protected:
/** Helper function for the balancing algorithm.
* \returns true if the row and the column, having colNorm and rowNorm
* as norms, are balanced, false otherwise.
* colB and rowB are respectively the multipliers for
* the column and the row in order to balance them.
* */
bool balanced( RealScalar colNorm, RealScalar rowNorm,
bool& isBalanced, RealScalar& colB, RealScalar& rowB );
/** Helper function for the balancing algorithm.
* \returns true if the row and the column, having colNorm and rowNorm
* as norms, are balanced, false otherwise.
* colB and rowB are respectively the multipliers for
* the column and the row in order to balance them.
* */
bool balancedR( RealScalar colNorm, RealScalar rowNorm,
bool& isBalanced, RealScalar& colB, RealScalar& rowB );
public:
/**
* Balancing algorithm from B. N. PARLETT and C. REINSCH (1969)
* "Balancing a matrix for calculation of eigenvalues and eigenvectors"
* adapted to the case of companion matrices.
* A matrix with non zero row and non zero column is balanced
* for a certain norm if the i-th row and the i-th column
* have same norm for all i.
*/
void balance();
protected:
RightColumn m_monic;
BottomLeftDiagonal m_bl_diag;
};
template< typename _Scalar, int _Deg >
inline
bool companion<_Scalar,_Deg>::balanced( RealScalar colNorm, RealScalar rowNorm,
bool& isBalanced, RealScalar& colB, RealScalar& rowB )
{
if( RealScalar(0) == colNorm || RealScalar(0) == rowNorm
|| !(numext::isfinite)(colNorm) || !(numext::isfinite)(rowNorm)){
return true;
}
else
{
//To find the balancing coefficients, if the radix is 2,
//one finds \f$ \sigma \f$ such that
// \f$ 2^{2\sigma-1} < rowNorm / colNorm \le 2^{2\sigma+1} \f$
// then the balancing coefficient for the row is \f$ 1/2^{\sigma} \f$
// and the balancing coefficient for the column is \f$ 2^{\sigma} \f$
const RealScalar radix = RealScalar(2);
const RealScalar radix2 = RealScalar(4);
rowB = rowNorm / radix;
colB = RealScalar(1);
const RealScalar s = colNorm + rowNorm;
// Find sigma s.t. rowNorm / 2 <= 2^(2*sigma) * colNorm
RealScalar scout = colNorm;
while (scout < rowB)
{
colB *= radix;
scout *= radix2;
}
// We now have an upper-bound for sigma, try to lower it.
// Find sigma s.t. 2^(2*sigma) * colNorm / 2 < rowNorm
scout = colNorm * (colB / radix) * colB; // Avoid overflow.
while (scout >= rowNorm)
{
colB /= radix;
scout /= radix2;
}
// This line is used to avoid insubstantial balancing.
if ((rowNorm + radix * scout) < RealScalar(0.95) * s * colB)
{
isBalanced = false;
rowB = RealScalar(1) / colB;
return false;
}
else
{
return true;
}
}
}
template< typename _Scalar, int _Deg >
inline
bool companion<_Scalar,_Deg>::balancedR( RealScalar colNorm, RealScalar rowNorm,
bool& isBalanced, RealScalar& colB, RealScalar& rowB )
{
if( RealScalar(0) == colNorm || RealScalar(0) == rowNorm ){ return true; }
else
{
/**
* Set the norm of the column and the row to the geometric mean
* of the row and column norm
*/
const RealScalar q = colNorm/rowNorm;
if( !isApprox( q, _Scalar(1) ) )
{
rowB = sqrt( colNorm/rowNorm );
colB = RealScalar(1)/rowB;
isBalanced = false;
return false;
}
else{
return true; }
}
}
template< typename _Scalar, int _Deg >
void companion<_Scalar,_Deg>::balance()
{
using std::abs;
EIGEN_STATIC_ASSERT( Deg == Dynamic || 1 < Deg, YOU_MADE_A_PROGRAMMING_MISTAKE );
const Index deg = m_monic.size();
const Index deg_1 = deg-1;
bool hasConverged=false;
while( !hasConverged )
{
hasConverged = true;
RealScalar colNorm,rowNorm;
RealScalar colB,rowB;
//First row, first column excluding the diagonal
//==============================================
colNorm = abs(m_bl_diag[0]);
rowNorm = abs(m_monic[0]);
//Compute balancing of the row and the column
if( !balanced( colNorm, rowNorm, hasConverged, colB, rowB ) )
{
m_bl_diag[0] *= colB;
m_monic[0] *= rowB;
}
//Middle rows and columns excluding the diagonal
//==============================================
for( Index i=1; i<deg_1; ++i )
{
// column norm, excluding the diagonal
colNorm = abs(m_bl_diag[i]);
// row norm, excluding the diagonal
rowNorm = abs(m_bl_diag[i-1]) + abs(m_monic[i]);
//Compute balancing of the row and the column
if( !balanced( colNorm, rowNorm, hasConverged, colB, rowB ) )
{
m_bl_diag[i] *= colB;
m_bl_diag[i-1] *= rowB;
m_monic[i] *= rowB;
}
}
//Last row, last column excluding the diagonal
//============================================
const Index ebl = m_bl_diag.size()-1;
VectorBlock<RightColumn,Deg_1> headMonic( m_monic, 0, deg_1 );
colNorm = headMonic.array().abs().sum();
rowNorm = abs( m_bl_diag[ebl] );
//Compute balancing of the row and the column
if( !balanced( colNorm, rowNorm, hasConverged, colB, rowB ) )
{
headMonic *= colB;
m_bl_diag[ebl] *= rowB;
}
}
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_COMPANION_H
| 8,076
| 27.743772
| 102
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Polynomials/PolynomialSolver.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_POLYNOMIAL_SOLVER_H
#define EIGEN_POLYNOMIAL_SOLVER_H
namespace Eigen {
/** \ingroup Polynomials_Module
* \class PolynomialSolverBase.
*
* \brief Defined to be inherited by polynomial solvers: it provides
* convenient methods such as
* - real roots,
* - greatest, smallest complex roots,
* - real roots with greatest, smallest absolute real value,
* - greatest, smallest real roots.
*
* It stores the set of roots as a vector of complexes.
*
*/
template< typename _Scalar, int _Deg >
class PolynomialSolverBase
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_Deg==Dynamic ? Dynamic : _Deg)
typedef _Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef std::complex<RealScalar> RootType;
typedef Matrix<RootType,_Deg,1> RootsType;
typedef DenseIndex Index;
protected:
template< typename OtherPolynomial >
inline void setPolynomial( const OtherPolynomial& poly ){
m_roots.resize(poly.size()-1); }
public:
template< typename OtherPolynomial >
inline PolynomialSolverBase( const OtherPolynomial& poly ){
setPolynomial( poly() ); }
inline PolynomialSolverBase(){}
public:
/** \returns the complex roots of the polynomial */
inline const RootsType& roots() const { return m_roots; }
public:
/** Clear and fills the back insertion sequence with the real roots of the polynomial
* i.e. the real part of the complex roots that have an imaginary part which
* absolute value is smaller than absImaginaryThreshold.
* absImaginaryThreshold takes the dummy_precision associated
* with the _Scalar template parameter of the PolynomialSolver class as the default value.
*
* \param[out] bi_seq : the back insertion sequence (stl concept)
* \param[in] absImaginaryThreshold : the maximum bound of the imaginary part of a complex
* number that is considered as real.
* */
template<typename Stl_back_insertion_sequence>
inline void realRoots( Stl_back_insertion_sequence& bi_seq,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
using std::abs;
bi_seq.clear();
for(Index i=0; i<m_roots.size(); ++i )
{
if( abs( m_roots[i].imag() ) < absImaginaryThreshold ){
bi_seq.push_back( m_roots[i].real() ); }
}
}
protected:
template<typename squaredNormBinaryPredicate>
inline const RootType& selectComplexRoot_withRespectToNorm( squaredNormBinaryPredicate& pred ) const
{
Index res=0;
RealScalar norm2 = numext::abs2( m_roots[0] );
for( Index i=1; i<m_roots.size(); ++i )
{
const RealScalar currNorm2 = numext::abs2( m_roots[i] );
if( pred( currNorm2, norm2 ) ){
res=i; norm2=currNorm2; }
}
return m_roots[res];
}
public:
/**
* \returns the complex root with greatest norm.
*/
inline const RootType& greatestRoot() const
{
std::greater<RealScalar> greater;
return selectComplexRoot_withRespectToNorm( greater );
}
/**
* \returns the complex root with smallest norm.
*/
inline const RootType& smallestRoot() const
{
std::less<RealScalar> less;
return selectComplexRoot_withRespectToNorm( less );
}
protected:
template<typename squaredRealPartBinaryPredicate>
inline const RealScalar& selectRealRoot_withRespectToAbsRealPart(
squaredRealPartBinaryPredicate& pred,
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
using std::abs;
hasArealRoot = false;
Index res=0;
RealScalar abs2(0);
for( Index i=0; i<m_roots.size(); ++i )
{
if( abs( m_roots[i].imag() ) <= absImaginaryThreshold )
{
if( !hasArealRoot )
{
hasArealRoot = true;
res = i;
abs2 = m_roots[i].real() * m_roots[i].real();
}
else
{
const RealScalar currAbs2 = m_roots[i].real() * m_roots[i].real();
if( pred( currAbs2, abs2 ) )
{
abs2 = currAbs2;
res = i;
}
}
}
else if(!hasArealRoot)
{
if( abs( m_roots[i].imag() ) < abs( m_roots[res].imag() ) ){
res = i;}
}
}
return numext::real_ref(m_roots[res]);
}
template<typename RealPartBinaryPredicate>
inline const RealScalar& selectRealRoot_withRespectToRealPart(
RealPartBinaryPredicate& pred,
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
using std::abs;
hasArealRoot = false;
Index res=0;
RealScalar val(0);
for( Index i=0; i<m_roots.size(); ++i )
{
if( abs( m_roots[i].imag() ) <= absImaginaryThreshold )
{
if( !hasArealRoot )
{
hasArealRoot = true;
res = i;
val = m_roots[i].real();
}
else
{
const RealScalar curr = m_roots[i].real();
if( pred( curr, val ) )
{
val = curr;
res = i;
}
}
}
else
{
if( abs( m_roots[i].imag() ) < abs( m_roots[res].imag() ) ){
res = i; }
}
}
return numext::real_ref(m_roots[res]);
}
public:
/**
* \returns a real root with greatest absolute magnitude.
* A real root is defined as the real part of a complex root with absolute imaginary
* part smallest than absImaginaryThreshold.
* absImaginaryThreshold takes the dummy_precision associated
* with the _Scalar template parameter of the PolynomialSolver class as the default value.
* If no real root is found the boolean hasArealRoot is set to false and the real part of
* the root with smallest absolute imaginary part is returned instead.
*
* \param[out] hasArealRoot : boolean true if a real root is found according to the
* absImaginaryThreshold criterion, false otherwise.
* \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide
* whether or not a root is real.
*/
inline const RealScalar& absGreatestRealRoot(
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
std::greater<RealScalar> greater;
return selectRealRoot_withRespectToAbsRealPart( greater, hasArealRoot, absImaginaryThreshold );
}
/**
* \returns a real root with smallest absolute magnitude.
* A real root is defined as the real part of a complex root with absolute imaginary
* part smallest than absImaginaryThreshold.
* absImaginaryThreshold takes the dummy_precision associated
* with the _Scalar template parameter of the PolynomialSolver class as the default value.
* If no real root is found the boolean hasArealRoot is set to false and the real part of
* the root with smallest absolute imaginary part is returned instead.
*
* \param[out] hasArealRoot : boolean true if a real root is found according to the
* absImaginaryThreshold criterion, false otherwise.
* \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide
* whether or not a root is real.
*/
inline const RealScalar& absSmallestRealRoot(
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
std::less<RealScalar> less;
return selectRealRoot_withRespectToAbsRealPart( less, hasArealRoot, absImaginaryThreshold );
}
/**
* \returns the real root with greatest value.
* A real root is defined as the real part of a complex root with absolute imaginary
* part smallest than absImaginaryThreshold.
* absImaginaryThreshold takes the dummy_precision associated
* with the _Scalar template parameter of the PolynomialSolver class as the default value.
* If no real root is found the boolean hasArealRoot is set to false and the real part of
* the root with smallest absolute imaginary part is returned instead.
*
* \param[out] hasArealRoot : boolean true if a real root is found according to the
* absImaginaryThreshold criterion, false otherwise.
* \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide
* whether or not a root is real.
*/
inline const RealScalar& greatestRealRoot(
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
std::greater<RealScalar> greater;
return selectRealRoot_withRespectToRealPart( greater, hasArealRoot, absImaginaryThreshold );
}
/**
* \returns the real root with smallest value.
* A real root is defined as the real part of a complex root with absolute imaginary
* part smallest than absImaginaryThreshold.
* absImaginaryThreshold takes the dummy_precision associated
* with the _Scalar template parameter of the PolynomialSolver class as the default value.
* If no real root is found the boolean hasArealRoot is set to false and the real part of
* the root with smallest absolute imaginary part is returned instead.
*
* \param[out] hasArealRoot : boolean true if a real root is found according to the
* absImaginaryThreshold criterion, false otherwise.
* \param[in] absImaginaryThreshold : threshold on the absolute imaginary part to decide
* whether or not a root is real.
*/
inline const RealScalar& smallestRealRoot(
bool& hasArealRoot,
const RealScalar& absImaginaryThreshold = NumTraits<Scalar>::dummy_precision() ) const
{
std::less<RealScalar> less;
return selectRealRoot_withRespectToRealPart( less, hasArealRoot, absImaginaryThreshold );
}
protected:
RootsType m_roots;
};
#define EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( BASE ) \
typedef typename BASE::Scalar Scalar; \
typedef typename BASE::RealScalar RealScalar; \
typedef typename BASE::RootType RootType; \
typedef typename BASE::RootsType RootsType;
/** \ingroup Polynomials_Module
*
* \class PolynomialSolver
*
* \brief A polynomial solver
*
* Computes the complex roots of a real polynomial.
*
* \param _Scalar the scalar type, i.e., the type of the polynomial coefficients
* \param _Deg the degree of the polynomial, can be a compile time value or Dynamic.
* Notice that the number of polynomial coefficients is _Deg+1.
*
* This class implements a polynomial solver and provides convenient methods such as
* - real roots,
* - greatest, smallest complex roots,
* - real roots with greatest, smallest absolute real value.
* - greatest, smallest real roots.
*
* WARNING: this polynomial solver is experimental, part of the unsupported Eigen modules.
*
*
* Currently a QR algorithm is used to compute the eigenvalues of the companion matrix of
* the polynomial to compute its roots.
* This supposes that the complex moduli of the roots are all distinct: e.g. there should
* be no multiple roots or conjugate roots for instance.
* With 32bit (float) floating types this problem shows up frequently.
* However, almost always, correct accuracy is reached even in these cases for 64bit
* (double) floating types and small polynomial degree (<20).
*/
template<typename _Scalar, int _Deg>
class PolynomialSolver : public PolynomialSolverBase<_Scalar,_Deg>
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_Deg==Dynamic ? Dynamic : _Deg)
typedef PolynomialSolverBase<_Scalar,_Deg> PS_Base;
EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( PS_Base )
typedef Matrix<Scalar,_Deg,_Deg> CompanionMatrixType;
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
ComplexEigenSolver<CompanionMatrixType>,
EigenSolver<CompanionMatrixType> >::type EigenSolverType;
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex, Scalar, std::complex<Scalar> >::type ComplexScalar;
public:
/** Computes the complex roots of a new polynomial. */
template< typename OtherPolynomial >
void compute( const OtherPolynomial& poly )
{
eigen_assert( Scalar(0) != poly[poly.size()-1] );
eigen_assert( poly.size() > 1 );
if(poly.size() > 2 )
{
internal::companion<Scalar,_Deg> companion( poly );
companion.balance();
m_eigenSolver.compute( companion.denseMatrix() );
m_roots = m_eigenSolver.eigenvalues();
// cleanup noise in imaginary part of real roots:
// if the imaginary part is rather small compared to the real part
// and that cancelling the imaginary part yield a smaller evaluation,
// then it's safe to keep the real part only.
RealScalar coarse_prec = RealScalar(std::pow(4,poly.size()+1))*NumTraits<RealScalar>::epsilon();
for(Index i = 0; i<m_roots.size(); ++i)
{
if( internal::isMuchSmallerThan(numext::abs(numext::imag(m_roots[i])),
numext::abs(numext::real(m_roots[i])),
coarse_prec) )
{
ComplexScalar as_real_root = ComplexScalar(numext::real(m_roots[i]));
if( numext::abs(poly_eval(poly, as_real_root))
<= numext::abs(poly_eval(poly, m_roots[i])))
{
m_roots[i] = as_real_root;
}
}
}
}
else if(poly.size () == 2)
{
m_roots.resize(1);
m_roots[0] = -poly[0]/poly[1];
}
}
public:
template< typename OtherPolynomial >
inline PolynomialSolver( const OtherPolynomial& poly ){
compute( poly ); }
inline PolynomialSolver(){}
protected:
using PS_Base::m_roots;
EigenSolverType m_eigenSolver;
};
template< typename _Scalar >
class PolynomialSolver<_Scalar,1> : public PolynomialSolverBase<_Scalar,1>
{
public:
typedef PolynomialSolverBase<_Scalar,1> PS_Base;
EIGEN_POLYNOMIAL_SOLVER_BASE_INHERITED_TYPES( PS_Base )
public:
/** Computes the complex roots of a new polynomial. */
template< typename OtherPolynomial >
void compute( const OtherPolynomial& poly )
{
eigen_assert( poly.size() == 2 );
eigen_assert( Scalar(0) != poly[1] );
m_roots[0] = -poly[0]/poly[1];
}
public:
template< typename OtherPolynomial >
inline PolynomialSolver( const OtherPolynomial& poly ){
compute( poly ); }
inline PolynomialSolver(){}
protected:
using PS_Base::m_roots;
};
} // end namespace Eigen
#endif // EIGEN_POLYNOMIAL_SOLVER_H
| 15,683
| 35.559441
| 124
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Polynomials/PolynomialUtils.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_POLYNOMIAL_UTILS_H
#define EIGEN_POLYNOMIAL_UTILS_H
namespace Eigen {
/** \ingroup Polynomials_Module
* \returns the evaluation of the polynomial at x using Horner algorithm.
*
* \param[in] poly : the vector of coefficients of the polynomial ordered
* by degrees i.e. poly[i] is the coefficient of degree i of the polynomial
* e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$.
* \param[in] x : the value to evaluate the polynomial at.
*
* \note for stability:
* \f$ |x| \le 1 \f$
*/
template <typename Polynomials, typename T>
inline
T poly_eval_horner( const Polynomials& poly, const T& x )
{
T val=poly[poly.size()-1];
for(DenseIndex i=poly.size()-2; i>=0; --i ){
val = val*x + poly[i]; }
return val;
}
/** \ingroup Polynomials_Module
* \returns the evaluation of the polynomial at x using stabilized Horner algorithm.
*
* \param[in] poly : the vector of coefficients of the polynomial ordered
* by degrees i.e. poly[i] is the coefficient of degree i of the polynomial
* e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$.
* \param[in] x : the value to evaluate the polynomial at.
*/
template <typename Polynomials, typename T>
inline
T poly_eval( const Polynomials& poly, const T& x )
{
typedef typename NumTraits<T>::Real Real;
if( numext::abs2( x ) <= Real(1) ){
return poly_eval_horner( poly, x ); }
else
{
T val=poly[0];
T inv_x = T(1)/x;
for( DenseIndex i=1; i<poly.size(); ++i ){
val = val*inv_x + poly[i]; }
return numext::pow(x,(T)(poly.size()-1)) * val;
}
}
/** \ingroup Polynomials_Module
* \returns a maximum bound for the absolute value of any root of the polynomial.
*
* \param[in] poly : the vector of coefficients of the polynomial ordered
* by degrees i.e. poly[i] is the coefficient of degree i of the polynomial
* e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$.
*
* \pre
* the leading coefficient of the input polynomial poly must be non zero
*/
template <typename Polynomial>
inline
typename NumTraits<typename Polynomial::Scalar>::Real cauchy_max_bound( const Polynomial& poly )
{
using std::abs;
typedef typename Polynomial::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real Real;
eigen_assert( Scalar(0) != poly[poly.size()-1] );
const Scalar inv_leading_coeff = Scalar(1)/poly[poly.size()-1];
Real cb(0);
for( DenseIndex i=0; i<poly.size()-1; ++i ){
cb += abs(poly[i]*inv_leading_coeff); }
return cb + Real(1);
}
/** \ingroup Polynomials_Module
* \returns a minimum bound for the absolute value of any non zero root of the polynomial.
* \param[in] poly : the vector of coefficients of the polynomial ordered
* by degrees i.e. poly[i] is the coefficient of degree i of the polynomial
* e.g. \f$ 1 + 3x^2 \f$ is stored as a vector \f$ [ 1, 0, 3 ] \f$.
*/
template <typename Polynomial>
inline
typename NumTraits<typename Polynomial::Scalar>::Real cauchy_min_bound( const Polynomial& poly )
{
using std::abs;
typedef typename Polynomial::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real Real;
DenseIndex i=0;
while( i<poly.size()-1 && Scalar(0) == poly(i) ){ ++i; }
if( poly.size()-1 == i ){
return Real(1); }
const Scalar inv_min_coeff = Scalar(1)/poly[i];
Real cb(1);
for( DenseIndex j=i+1; j<poly.size(); ++j ){
cb += abs(poly[j]*inv_min_coeff); }
return Real(1)/cb;
}
/** \ingroup Polynomials_Module
* Given the roots of a polynomial compute the coefficients in the
* monomial basis of the monic polynomial with same roots and minimal degree.
* If RootVector is a vector of complexes, Polynomial should also be a vector
* of complexes.
* \param[in] rv : a vector containing the roots of a polynomial.
* \param[out] poly : the vector of coefficients of the polynomial ordered
* by degrees i.e. poly[i] is the coefficient of degree i of the polynomial
* e.g. \f$ 3 + x^2 \f$ is stored as a vector \f$ [ 3, 0, 1 ] \f$.
*/
template <typename RootVector, typename Polynomial>
void roots_to_monicPolynomial( const RootVector& rv, Polynomial& poly )
{
typedef typename Polynomial::Scalar Scalar;
poly.setZero( rv.size()+1 );
poly[0] = -rv[0]; poly[1] = Scalar(1);
for( DenseIndex i=1; i< rv.size(); ++i )
{
for( DenseIndex j=i+1; j>0; --j ){ poly[j] = poly[j-1] - rv[i]*poly[j]; }
poly[0] = -rv[i]*poly[0];
}
}
} // end namespace Eigen
#endif // EIGEN_POLYNOMIAL_UTILS_H
| 4,806
| 32.381944
| 96
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Skyline/SkylineInplaceLU.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Guillaume Saupin <guillaume.saupin@cea.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SKYLINEINPLACELU_H
#define EIGEN_SKYLINEINPLACELU_H
namespace Eigen {
/** \ingroup Skyline_Module
*
* \class SkylineInplaceLU
*
* \brief Inplace LU decomposition of a skyline matrix and associated features
*
* \param MatrixType the type of the matrix of which we are computing the LU factorization
*
*/
template<typename MatrixType>
class SkylineInplaceLU {
protected:
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::Index Index;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
public:
/** Creates a LU object and compute the respective factorization of \a matrix using
* flags \a flags. */
SkylineInplaceLU(MatrixType& matrix, int flags = 0)
: /*m_matrix(matrix.rows(), matrix.cols()),*/ m_flags(flags), m_status(0), m_lu(matrix) {
m_precision = RealScalar(0.1) * Eigen::dummy_precision<RealScalar > ();
m_lu.IsRowMajor ? computeRowMajor() : compute();
}
/** Sets the relative threshold value used to prune zero coefficients during the decomposition.
*
* Setting a value greater than zero speeds up computation, and yields to an incomplete
* factorization with fewer non zero coefficients. Such approximate factors are especially
* useful to initialize an iterative solver.
*
* Note that the exact meaning of this parameter might depends on the actual
* backend. Moreover, not all backends support this feature.
*
* \sa precision() */
void setPrecision(RealScalar v) {
m_precision = v;
}
/** \returns the current precision.
*
* \sa setPrecision() */
RealScalar precision() const {
return m_precision;
}
/** Sets the flags. Possible values are:
* - CompleteFactorization
* - IncompleteFactorization
* - MemoryEfficient
* - one of the ordering methods
* - etc...
*
* \sa flags() */
void setFlags(int f) {
m_flags = f;
}
/** \returns the current flags */
int flags() const {
return m_flags;
}
void setOrderingMethod(int m) {
m_flags = m;
}
int orderingMethod() const {
return m_flags;
}
/** Computes/re-computes the LU factorization */
void compute();
void computeRowMajor();
/** \returns the lower triangular matrix L */
//inline const MatrixType& matrixL() const { return m_matrixL; }
/** \returns the upper triangular matrix U */
//inline const MatrixType& matrixU() const { return m_matrixU; }
template<typename BDerived, typename XDerived>
bool solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x,
const int transposed = 0) const;
/** \returns true if the factorization succeeded */
inline bool succeeded(void) const {
return m_succeeded;
}
protected:
RealScalar m_precision;
int m_flags;
mutable int m_status;
bool m_succeeded;
MatrixType& m_lu;
};
/** Computes / recomputes the in place LU decomposition of the SkylineInplaceLU.
* using the default algorithm.
*/
template<typename MatrixType>
//template<typename _Scalar>
void SkylineInplaceLU<MatrixType>::compute() {
const size_t rows = m_lu.rows();
const size_t cols = m_lu.cols();
eigen_assert(rows == cols && "We do not (yet) support rectangular LU.");
eigen_assert(!m_lu.IsRowMajor && "LU decomposition does not work with rowMajor Storage");
for (Index row = 0; row < rows; row++) {
const double pivot = m_lu.coeffDiag(row);
//Lower matrix Columns update
const Index& col = row;
for (typename MatrixType::InnerLowerIterator lIt(m_lu, col); lIt; ++lIt) {
lIt.valueRef() /= pivot;
}
//Upper matrix update -> contiguous memory access
typename MatrixType::InnerLowerIterator lIt(m_lu, col);
for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) {
typename MatrixType::InnerUpperIterator uItPivot(m_lu, row);
typename MatrixType::InnerUpperIterator uIt(m_lu, rrow);
const double coef = lIt.value();
uItPivot += (rrow - row - 1);
//update upper part -> contiguous memory access
for (++uItPivot; uIt && uItPivot;) {
uIt.valueRef() -= uItPivot.value() * coef;
++uIt;
++uItPivot;
}
++lIt;
}
//Upper matrix update -> non contiguous memory access
typename MatrixType::InnerLowerIterator lIt3(m_lu, col);
for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) {
typename MatrixType::InnerUpperIterator uItPivot(m_lu, row);
const double coef = lIt3.value();
//update lower part -> non contiguous memory access
for (Index i = 0; i < rrow - row - 1; i++) {
m_lu.coeffRefLower(rrow, row + i + 1) -= uItPivot.value() * coef;
++uItPivot;
}
++lIt3;
}
//update diag -> contiguous
typename MatrixType::InnerLowerIterator lIt2(m_lu, col);
for (Index rrow = row + 1; rrow < m_lu.rows(); rrow++) {
typename MatrixType::InnerUpperIterator uItPivot(m_lu, row);
typename MatrixType::InnerUpperIterator uIt(m_lu, rrow);
const double coef = lIt2.value();
uItPivot += (rrow - row - 1);
m_lu.coeffRefDiag(rrow) -= uItPivot.value() * coef;
++lIt2;
}
}
}
template<typename MatrixType>
void SkylineInplaceLU<MatrixType>::computeRowMajor() {
const size_t rows = m_lu.rows();
const size_t cols = m_lu.cols();
eigen_assert(rows == cols && "We do not (yet) support rectangular LU.");
eigen_assert(m_lu.IsRowMajor && "You're trying to apply rowMajor decomposition on a ColMajor matrix !");
for (Index row = 0; row < rows; row++) {
typename MatrixType::InnerLowerIterator llIt(m_lu, row);
for (Index col = llIt.col(); col < row; col++) {
if (m_lu.coeffExistLower(row, col)) {
const double diag = m_lu.coeffDiag(col);
typename MatrixType::InnerLowerIterator lIt(m_lu, row);
typename MatrixType::InnerUpperIterator uIt(m_lu, col);
const Index offset = lIt.col() - uIt.row();
Index stop = offset > 0 ? col - lIt.col() : col - uIt.row();
//#define VECTORIZE
#ifdef VECTORIZE
Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop);
Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop);
Scalar newCoeff = m_lu.coeffLower(row, col) - rowVal.dot(colVal);
#else
if (offset > 0) //Skip zero value of lIt
uIt += offset;
else //Skip zero values of uIt
lIt += -offset;
Scalar newCoeff = m_lu.coeffLower(row, col);
for (Index k = 0; k < stop; ++k) {
const Scalar tmp = newCoeff;
newCoeff = tmp - lIt.value() * uIt.value();
++lIt;
++uIt;
}
#endif
m_lu.coeffRefLower(row, col) = newCoeff / diag;
}
}
//Upper matrix update
const Index col = row;
typename MatrixType::InnerUpperIterator uuIt(m_lu, col);
for (Index rrow = uuIt.row(); rrow < col; rrow++) {
typename MatrixType::InnerLowerIterator lIt(m_lu, rrow);
typename MatrixType::InnerUpperIterator uIt(m_lu, col);
const Index offset = lIt.col() - uIt.row();
Index stop = offset > 0 ? rrow - lIt.col() : rrow - uIt.row();
#ifdef VECTORIZE
Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop);
Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop);
Scalar newCoeff = m_lu.coeffUpper(rrow, col) - rowVal.dot(colVal);
#else
if (offset > 0) //Skip zero value of lIt
uIt += offset;
else //Skip zero values of uIt
lIt += -offset;
Scalar newCoeff = m_lu.coeffUpper(rrow, col);
for (Index k = 0; k < stop; ++k) {
const Scalar tmp = newCoeff;
newCoeff = tmp - lIt.value() * uIt.value();
++lIt;
++uIt;
}
#endif
m_lu.coeffRefUpper(rrow, col) = newCoeff;
}
//Diag matrix update
typename MatrixType::InnerLowerIterator lIt(m_lu, row);
typename MatrixType::InnerUpperIterator uIt(m_lu, row);
const Index offset = lIt.col() - uIt.row();
Index stop = offset > 0 ? lIt.size() : uIt.size();
#ifdef VECTORIZE
Map<VectorXd > rowVal(lIt.valuePtr() + (offset > 0 ? 0 : -offset), stop);
Map<VectorXd > colVal(uIt.valuePtr() + (offset > 0 ? offset : 0), stop);
Scalar newCoeff = m_lu.coeffDiag(row) - rowVal.dot(colVal);
#else
if (offset > 0) //Skip zero value of lIt
uIt += offset;
else //Skip zero values of uIt
lIt += -offset;
Scalar newCoeff = m_lu.coeffDiag(row);
for (Index k = 0; k < stop; ++k) {
const Scalar tmp = newCoeff;
newCoeff = tmp - lIt.value() * uIt.value();
++lIt;
++uIt;
}
#endif
m_lu.coeffRefDiag(row) = newCoeff;
}
}
/** Computes *x = U^-1 L^-1 b
*
* If \a transpose is set to SvTranspose or SvAdjoint, the solution
* of the transposed/adjoint system is computed instead.
*
* Not all backends implement the solution of the transposed or
* adjoint system.
*/
template<typename MatrixType>
template<typename BDerived, typename XDerived>
bool SkylineInplaceLU<MatrixType>::solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x, const int transposed) const {
const size_t rows = m_lu.rows();
const size_t cols = m_lu.cols();
for (Index row = 0; row < rows; row++) {
x->coeffRef(row) = b.coeff(row);
Scalar newVal = x->coeff(row);
typename MatrixType::InnerLowerIterator lIt(m_lu, row);
Index col = lIt.col();
while (lIt.col() < row) {
newVal -= x->coeff(col++) * lIt.value();
++lIt;
}
x->coeffRef(row) = newVal;
}
for (Index col = rows - 1; col > 0; col--) {
x->coeffRef(col) = x->coeff(col) / m_lu.coeffDiag(col);
const Scalar x_col = x->coeff(col);
typename MatrixType::InnerUpperIterator uIt(m_lu, col);
uIt += uIt.size()-1;
while (uIt) {
x->coeffRef(uIt.row()) -= x_col * uIt.value();
//TODO : introduce --operator
uIt += -1;
}
}
x->coeffRef(0) = x->coeff(0) / m_lu.coeffDiag(0);
return true;
}
} // end namespace Eigen
#endif // EIGEN_SKYLINEINPLACELU_H
| 11,365
| 31.1983
| 126
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Skyline/SkylineMatrixBase.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Guillaume Saupin <guillaume.saupin@cea.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SKYLINEMATRIXBASE_H
#define EIGEN_SKYLINEMATRIXBASE_H
#include "SkylineUtil.h"
namespace Eigen {
/** \ingroup Skyline_Module
*
* \class SkylineMatrixBase
*
* \brief Base class of any skyline matrices or skyline expressions
*
* \param Derived
*
*/
template<typename Derived> class SkylineMatrixBase : public EigenBase<Derived> {
public:
typedef typename internal::traits<Derived>::Scalar Scalar;
typedef typename internal::traits<Derived>::StorageKind StorageKind;
typedef typename internal::index<StorageKind>::type Index;
enum {
RowsAtCompileTime = internal::traits<Derived>::RowsAtCompileTime,
/**< The number of rows at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */
ColsAtCompileTime = internal::traits<Derived>::ColsAtCompileTime,
/**< The number of columns at compile-time. This is just a copy of the value provided
* by the \a Derived type. If a value is not known at compile-time,
* it is set to the \a Dynamic constant.
* \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */
SizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime>::ret),
/**< This is equal to the number of coefficients, i.e. the number of
* rows times the number of columns, or to \a Dynamic if this is not
* known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */
MaxRowsAtCompileTime = RowsAtCompileTime,
MaxColsAtCompileTime = ColsAtCompileTime,
MaxSizeAtCompileTime = (internal::size_at_compile_time<MaxRowsAtCompileTime,
MaxColsAtCompileTime>::ret),
IsVectorAtCompileTime = RowsAtCompileTime == 1 || ColsAtCompileTime == 1,
/**< This is set to true if either the number of rows or the number of
* columns is known at compile-time to be equal to 1. Indeed, in that case,
* we are dealing with a column-vector (if there is only one column) or with
* a row-vector (if there is only one row). */
Flags = internal::traits<Derived>::Flags,
/**< This stores expression \ref flags flags which may or may not be inherited by new expressions
* constructed from this one. See the \ref flags "list of flags".
*/
CoeffReadCost = internal::traits<Derived>::CoeffReadCost,
/**< This is a rough measure of how expensive it is to read one coefficient from
* this expression.
*/
IsRowMajor = Flags & RowMajorBit ? 1 : 0
};
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** This is the "real scalar" type; if the \a Scalar type is already real numbers
* (e.g. int, float or double) then \a RealScalar is just the same as \a Scalar. If
* \a Scalar is \a std::complex<T> then RealScalar is \a T.
*
* \sa class NumTraits
*/
typedef typename NumTraits<Scalar>::Real RealScalar;
/** type of the equivalent square matrix */
typedef Matrix<Scalar, EIGEN_SIZE_MAX(RowsAtCompileTime, ColsAtCompileTime),
EIGEN_SIZE_MAX(RowsAtCompileTime, ColsAtCompileTime) > SquareMatrixType;
inline const Derived& derived() const {
return *static_cast<const Derived*> (this);
}
inline Derived& derived() {
return *static_cast<Derived*> (this);
}
inline Derived& const_cast_derived() const {
return *static_cast<Derived*> (const_cast<SkylineMatrixBase*> (this));
}
#endif // not EIGEN_PARSED_BY_DOXYGEN
/** \returns the number of rows. \sa cols(), RowsAtCompileTime */
inline EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT {
return derived().rows();
}
/** \returns the number of columns. \sa rows(), ColsAtCompileTime*/
inline EIGEN_CONSTEXPR Index cols() const EIGEN_NOEXCEPT {
return derived().cols();
}
/** \returns the number of coefficients, which is \a rows()*cols().
* \sa rows(), cols(), SizeAtCompileTime. */
inline EIGEN_CONSTEXPR Index size() const EIGEN_NOEXCEPT {
return rows() * cols();
}
/** \returns the number of nonzero coefficients which is in practice the number
* of stored coefficients. */
inline Index nonZeros() const {
return derived().nonZeros();
}
/** \returns the size of the storage major dimension,
* i.e., the number of columns for a columns major matrix, and the number of rows otherwise */
Index outerSize() const {
return (int(Flags) & RowMajorBit) ? this->rows() : this->cols();
}
/** \returns the size of the inner dimension according to the storage order,
* i.e., the number of rows for a columns major matrix, and the number of cols otherwise */
Index innerSize() const {
return (int(Flags) & RowMajorBit) ? this->cols() : this->rows();
}
bool isRValue() const {
return m_isRValue;
}
Derived& markAsRValue() {
m_isRValue = true;
return derived();
}
SkylineMatrixBase() : m_isRValue(false) {
/* TODO check flags */
}
inline Derived & operator=(const Derived& other) {
this->operator=<Derived > (other);
return derived();
}
template<typename OtherDerived>
inline void assignGeneric(const OtherDerived& other) {
derived().resize(other.rows(), other.cols());
for (Index row = 0; row < rows(); row++)
for (Index col = 0; col < cols(); col++) {
if (other.coeff(row, col) != Scalar(0))
derived().insert(row, col) = other.coeff(row, col);
}
derived().finalize();
}
template<typename OtherDerived>
inline Derived & operator=(const SkylineMatrixBase<OtherDerived>& other) {
//TODO
}
template<typename Lhs, typename Rhs>
inline Derived & operator=(const SkylineProduct<Lhs, Rhs, SkylineTimeSkylineProduct>& product);
friend std::ostream & operator <<(std::ostream & s, const SkylineMatrixBase& m) {
s << m.derived();
return s;
}
template<typename OtherDerived>
const typename SkylineProductReturnType<Derived, OtherDerived>::Type
operator*(const MatrixBase<OtherDerived> &other) const;
/** \internal use operator= */
template<typename DenseDerived>
void evalTo(MatrixBase<DenseDerived>& dst) const {
dst.setZero();
for (Index i = 0; i < rows(); i++)
for (Index j = 0; j < rows(); j++)
dst(i, j) = derived().coeff(i, j);
}
Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime> toDense() const {
return derived();
}
/** \returns the matrix or vector obtained by evaluating this expression.
*
* Notice that in the case of a plain matrix or vector (not an expression) this function just returns
* a const reference, in order to avoid a useless copy.
*/
EIGEN_STRONG_INLINE const typename internal::eval<Derived, IsSkyline>::type eval() const {
return typename internal::eval<Derived>::type(derived());
}
protected:
bool m_isRValue;
};
} // end namespace Eigen
#endif // EIGEN_SKYLINEMATRIXBASE_H
| 7,837
| 35.798122
| 107
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Skyline/SkylineProduct.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Guillaume Saupin <guillaume.saupin@cea.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SKYLINEPRODUCT_H
#define EIGEN_SKYLINEPRODUCT_H
namespace Eigen {
template<typename Lhs, typename Rhs, int ProductMode>
struct SkylineProductReturnType {
typedef const typename internal::nested_eval<Lhs, Rhs::RowsAtCompileTime>::type LhsNested;
typedef const typename internal::nested_eval<Rhs, Lhs::RowsAtCompileTime>::type RhsNested;
typedef SkylineProduct<LhsNested, RhsNested, ProductMode> Type;
};
template<typename LhsNested, typename RhsNested, int ProductMode>
struct internal::traits<SkylineProduct<LhsNested, RhsNested, ProductMode> > {
// clean the nested types:
typedef typename internal::remove_all<LhsNested>::type _LhsNested;
typedef typename internal::remove_all<RhsNested>::type _RhsNested;
typedef typename _LhsNested::Scalar Scalar;
enum {
LhsCoeffReadCost = _LhsNested::CoeffReadCost,
RhsCoeffReadCost = _RhsNested::CoeffReadCost,
LhsFlags = _LhsNested::Flags,
RhsFlags = _RhsNested::Flags,
RowsAtCompileTime = _LhsNested::RowsAtCompileTime,
ColsAtCompileTime = _RhsNested::ColsAtCompileTime,
InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(_LhsNested::ColsAtCompileTime, _RhsNested::RowsAtCompileTime),
MaxRowsAtCompileTime = _LhsNested::MaxRowsAtCompileTime,
MaxColsAtCompileTime = _RhsNested::MaxColsAtCompileTime,
EvalToRowMajor = (RhsFlags & LhsFlags & RowMajorBit),
ResultIsSkyline = ProductMode == SkylineTimeSkylineProduct,
RemovedBits = ~((EvalToRowMajor ? 0 : RowMajorBit) | (ResultIsSkyline ? 0 : SkylineBit)),
Flags = (int(LhsFlags | RhsFlags) & HereditaryBits & RemovedBits)
| EvalBeforeAssigningBit
| EvalBeforeNestingBit,
CoeffReadCost = HugeCost
};
typedef typename internal::conditional<ResultIsSkyline,
SkylineMatrixBase<SkylineProduct<LhsNested, RhsNested, ProductMode> >,
MatrixBase<SkylineProduct<LhsNested, RhsNested, ProductMode> > >::type Base;
};
namespace internal {
template<typename LhsNested, typename RhsNested, int ProductMode>
class SkylineProduct : no_assignment_operator,
public traits<SkylineProduct<LhsNested, RhsNested, ProductMode> >::Base {
public:
EIGEN_GENERIC_PUBLIC_INTERFACE(SkylineProduct)
private:
typedef typename traits<SkylineProduct>::_LhsNested _LhsNested;
typedef typename traits<SkylineProduct>::_RhsNested _RhsNested;
public:
template<typename Lhs, typename Rhs>
EIGEN_STRONG_INLINE SkylineProduct(const Lhs& lhs, const Rhs& rhs)
: m_lhs(lhs), m_rhs(rhs) {
eigen_assert(lhs.cols() == rhs.rows());
enum {
ProductIsValid = _LhsNested::ColsAtCompileTime == Dynamic
|| _RhsNested::RowsAtCompileTime == Dynamic
|| int(_LhsNested::ColsAtCompileTime) == int(_RhsNested::RowsAtCompileTime),
AreVectors = _LhsNested::IsVectorAtCompileTime && _RhsNested::IsVectorAtCompileTime,
SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(_LhsNested, _RhsNested)
};
// note to the lost user:
// * for a dot product use: v1.dot(v2)
// * for a coeff-wise product use: v1.cwise()*v2
EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes),
INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS)
EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors),
INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION)
EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT)
}
EIGEN_STRONG_INLINE Index rows() const {
return m_lhs.rows();
}
EIGEN_STRONG_INLINE Index cols() const {
return m_rhs.cols();
}
EIGEN_STRONG_INLINE const _LhsNested& lhs() const {
return m_lhs;
}
EIGEN_STRONG_INLINE const _RhsNested& rhs() const {
return m_rhs;
}
protected:
LhsNested m_lhs;
RhsNested m_rhs;
};
// dense = skyline * dense
// Note that here we force no inlining and separate the setZero() because GCC messes up otherwise
template<typename Lhs, typename Rhs, typename Dest>
EIGEN_DONT_INLINE void skyline_row_major_time_dense_product(const Lhs& lhs, const Rhs& rhs, Dest& dst) {
typedef typename remove_all<Lhs>::type _Lhs;
typedef typename remove_all<Rhs>::type _Rhs;
typedef typename traits<Lhs>::Scalar Scalar;
enum {
LhsIsRowMajor = (_Lhs::Flags & RowMajorBit) == RowMajorBit,
LhsIsSelfAdjoint = (_Lhs::Flags & SelfAdjointBit) == SelfAdjointBit,
ProcessFirstHalf = LhsIsSelfAdjoint
&& (((_Lhs::Flags & (UpperTriangularBit | LowerTriangularBit)) == 0)
|| ((_Lhs::Flags & UpperTriangularBit) && !LhsIsRowMajor)
|| ((_Lhs::Flags & LowerTriangularBit) && LhsIsRowMajor)),
ProcessSecondHalf = LhsIsSelfAdjoint && (!ProcessFirstHalf)
};
//Use matrix diagonal part <- Improvement : use inner iterator on dense matrix.
for (Index col = 0; col < rhs.cols(); col++) {
for (Index row = 0; row < lhs.rows(); row++) {
dst(row, col) = lhs.coeffDiag(row) * rhs(row, col);
}
}
//Use matrix lower triangular part
for (Index row = 0; row < lhs.rows(); row++) {
typename _Lhs::InnerLowerIterator lIt(lhs, row);
const Index stop = lIt.col() + lIt.size();
for (Index col = 0; col < rhs.cols(); col++) {
Index k = lIt.col();
Scalar tmp = 0;
while (k < stop) {
tmp +=
lIt.value() *
rhs(k++, col);
++lIt;
}
dst(row, col) += tmp;
lIt += -lIt.size();
}
}
//Use matrix upper triangular part
for (Index lhscol = 0; lhscol < lhs.cols(); lhscol++) {
typename _Lhs::InnerUpperIterator uIt(lhs, lhscol);
const Index stop = uIt.size() + uIt.row();
for (Index rhscol = 0; rhscol < rhs.cols(); rhscol++) {
const Scalar rhsCoeff = rhs.coeff(lhscol, rhscol);
Index k = uIt.row();
while (k < stop) {
dst(k++, rhscol) +=
uIt.value() *
rhsCoeff;
++uIt;
}
uIt += -uIt.size();
}
}
}
template<typename Lhs, typename Rhs, typename Dest>
EIGEN_DONT_INLINE void skyline_col_major_time_dense_product(const Lhs& lhs, const Rhs& rhs, Dest& dst) {
typedef typename remove_all<Lhs>::type _Lhs;
typedef typename remove_all<Rhs>::type _Rhs;
typedef typename traits<Lhs>::Scalar Scalar;
enum {
LhsIsRowMajor = (_Lhs::Flags & RowMajorBit) == RowMajorBit,
LhsIsSelfAdjoint = (_Lhs::Flags & SelfAdjointBit) == SelfAdjointBit,
ProcessFirstHalf = LhsIsSelfAdjoint
&& (((_Lhs::Flags & (UpperTriangularBit | LowerTriangularBit)) == 0)
|| ((_Lhs::Flags & UpperTriangularBit) && !LhsIsRowMajor)
|| ((_Lhs::Flags & LowerTriangularBit) && LhsIsRowMajor)),
ProcessSecondHalf = LhsIsSelfAdjoint && (!ProcessFirstHalf)
};
//Use matrix diagonal part <- Improvement : use inner iterator on dense matrix.
for (Index col = 0; col < rhs.cols(); col++) {
for (Index row = 0; row < lhs.rows(); row++) {
dst(row, col) = lhs.coeffDiag(row) * rhs(row, col);
}
}
//Use matrix upper triangular part
for (Index row = 0; row < lhs.rows(); row++) {
typename _Lhs::InnerUpperIterator uIt(lhs, row);
const Index stop = uIt.col() + uIt.size();
for (Index col = 0; col < rhs.cols(); col++) {
Index k = uIt.col();
Scalar tmp = 0;
while (k < stop) {
tmp +=
uIt.value() *
rhs(k++, col);
++uIt;
}
dst(row, col) += tmp;
uIt += -uIt.size();
}
}
//Use matrix lower triangular part
for (Index lhscol = 0; lhscol < lhs.cols(); lhscol++) {
typename _Lhs::InnerLowerIterator lIt(lhs, lhscol);
const Index stop = lIt.size() + lIt.row();
for (Index rhscol = 0; rhscol < rhs.cols(); rhscol++) {
const Scalar rhsCoeff = rhs.coeff(lhscol, rhscol);
Index k = lIt.row();
while (k < stop) {
dst(k++, rhscol) +=
lIt.value() *
rhsCoeff;
++lIt;
}
lIt += -lIt.size();
}
}
}
template<typename Lhs, typename Rhs, typename ResultType,
int LhsStorageOrder = traits<Lhs>::Flags&RowMajorBit>
struct skyline_product_selector;
template<typename Lhs, typename Rhs, typename ResultType>
struct skyline_product_selector<Lhs, Rhs, ResultType, RowMajor> {
typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType & res) {
skyline_row_major_time_dense_product<Lhs, Rhs, ResultType > (lhs, rhs, res);
}
};
template<typename Lhs, typename Rhs, typename ResultType>
struct skyline_product_selector<Lhs, Rhs, ResultType, ColMajor> {
typedef typename traits<typename remove_all<Lhs>::type>::Scalar Scalar;
static void run(const Lhs& lhs, const Rhs& rhs, ResultType & res) {
skyline_col_major_time_dense_product<Lhs, Rhs, ResultType > (lhs, rhs, res);
}
};
} // end namespace internal
// template<typename Derived>
// template<typename Lhs, typename Rhs >
// Derived & MatrixBase<Derived>::lazyAssign(const SkylineProduct<Lhs, Rhs, SkylineTimeDenseProduct>& product) {
// typedef typename internal::remove_all<Lhs>::type _Lhs;
// internal::skyline_product_selector<typename internal::remove_all<Lhs>::type,
// typename internal::remove_all<Rhs>::type,
// Derived>::run(product.lhs(), product.rhs(), derived());
//
// return derived();
// }
// skyline * dense
template<typename Derived>
template<typename OtherDerived >
EIGEN_STRONG_INLINE const typename SkylineProductReturnType<Derived, OtherDerived>::Type
SkylineMatrixBase<Derived>::operator*(const MatrixBase<OtherDerived> &other) const {
return typename SkylineProductReturnType<Derived, OtherDerived>::Type(derived(), other.derived());
}
} // end namespace Eigen
#endif // EIGEN_SKYLINEPRODUCT_H
| 10,853
| 35.668919
| 125
|
h
|
null |
LRMI-main/unsupported/Eigen/src/Skyline/SkylineUtil.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Guillaume Saupin <guillaume.saupin@cea.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SKYLINEUTIL_H
#define EIGEN_SKYLINEUTIL_H
namespace Eigen {
#ifdef NDEBUG
#define EIGEN_DBG_SKYLINE(X)
#else
#define EIGEN_DBG_SKYLINE(X) X
#endif
const unsigned int SkylineBit = 0x1200;
template<typename Lhs, typename Rhs, int ProductMode> class SkylineProduct;
enum AdditionalProductEvaluationMode {SkylineTimeDenseProduct, SkylineTimeSkylineProduct, DenseTimeSkylineProduct};
enum {IsSkyline = SkylineBit};
#define EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, Op) \
template<typename OtherDerived> \
EIGEN_STRONG_INLINE Derived& operator Op(const Eigen::SkylineMatrixBase<OtherDerived>& other) \
{ \
return Base::operator Op(other.derived()); \
} \
EIGEN_STRONG_INLINE Derived& operator Op(const Derived& other) \
{ \
return Base::operator Op(other); \
}
#define EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, Op) \
template<typename Other> \
EIGEN_STRONG_INLINE Derived& operator Op(const Other& scalar) \
{ \
return Base::operator Op(scalar); \
}
#define EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATORS(Derived) \
EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, =) \
EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, +=) \
EIGEN_SKYLINE_INHERIT_ASSIGNMENT_OPERATOR(Derived, -=) \
EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, *=) \
EIGEN_SKYLINE_INHERIT_SCALAR_ASSIGNMENT_OPERATOR(Derived, /=)
#define _EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(Derived, BaseClass) \
typedef BaseClass Base; \
typedef typename Eigen::internal::traits<Derived>::Scalar Scalar; \
typedef typename Eigen::NumTraits<Scalar>::Real RealScalar; \
typedef typename Eigen::internal::traits<Derived>::StorageKind StorageKind; \
typedef typename Eigen::internal::index<StorageKind>::type Index; \
enum { Flags = Eigen::internal::traits<Derived>::Flags, };
#define EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(Derived) \
_EIGEN_SKYLINE_GENERIC_PUBLIC_INTERFACE(Derived, Eigen::SkylineMatrixBase<Derived>)
template<typename Derived> class SkylineMatrixBase;
template<typename _Scalar, int _Flags = 0> class SkylineMatrix;
template<typename _Scalar, int _Flags = 0> class DynamicSkylineMatrix;
template<typename _Scalar, int _Flags = 0> class SkylineVector;
template<typename _Scalar, int _Flags = 0> class MappedSkylineMatrix;
namespace internal {
template<typename Lhs, typename Rhs> struct skyline_product_mode;
template<typename Lhs, typename Rhs, int ProductMode = skyline_product_mode<Lhs,Rhs>::value> struct SkylineProductReturnType;
template<typename T> class eval<T,IsSkyline>
{
typedef typename traits<T>::Scalar _Scalar;
enum {
_Flags = traits<T>::Flags
};
public:
typedef SkylineMatrix<_Scalar, _Flags> type;
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_SKYLINEUTIL_H
| 3,153
| 34.044444
| 125
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SparseExtra/BlockOfDynamicSparseMatrix.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_BLOCKFORDYNAMICMATRIX_H
#define EIGEN_SPARSE_BLOCKFORDYNAMICMATRIX_H
namespace Eigen {
#if 0
// NOTE Have to be reimplemented as a specialization of BlockImpl< DynamicSparseMatrix<_Scalar, _Options, _Index>, ... >
// See SparseBlock.h for an example
/***************************************************************************
* specialisation for DynamicSparseMatrix
***************************************************************************/
template<typename _Scalar, int _Options, typename _Index, int Size>
class SparseInnerVectorSet<DynamicSparseMatrix<_Scalar, _Options, _Index>, Size>
: public SparseMatrixBase<SparseInnerVectorSet<DynamicSparseMatrix<_Scalar, _Options, _Index>, Size> >
{
typedef DynamicSparseMatrix<_Scalar, _Options, _Index> MatrixType;
public:
enum { IsRowMajor = internal::traits<SparseInnerVectorSet>::IsRowMajor };
EIGEN_SPARSE_PUBLIC_INTERFACE(SparseInnerVectorSet)
class InnerIterator: public MatrixType::InnerIterator
{
public:
inline InnerIterator(const SparseInnerVectorSet& xpr, Index outer)
: MatrixType::InnerIterator(xpr.m_matrix, xpr.m_outerStart + outer), m_outer(outer)
{}
inline Index row() const { return IsRowMajor ? m_outer : this->index(); }
inline Index col() const { return IsRowMajor ? this->index() : m_outer; }
protected:
Index m_outer;
};
inline SparseInnerVectorSet(const MatrixType& matrix, Index outerStart, Index outerSize)
: m_matrix(matrix), m_outerStart(outerStart), m_outerSize(outerSize)
{
eigen_assert( (outerStart>=0) && ((outerStart+outerSize)<=matrix.outerSize()) );
}
inline SparseInnerVectorSet(const MatrixType& matrix, Index outer)
: m_matrix(matrix), m_outerStart(outer), m_outerSize(Size)
{
eigen_assert(Size!=Dynamic);
eigen_assert( (outer>=0) && (outer<matrix.outerSize()) );
}
template<typename OtherDerived>
inline SparseInnerVectorSet& operator=(const SparseMatrixBase<OtherDerived>& other)
{
if (IsRowMajor != ((OtherDerived::Flags&RowMajorBit)==RowMajorBit))
{
// need to transpose => perform a block evaluation followed by a big swap
DynamicSparseMatrix<Scalar,IsRowMajor?RowMajorBit:0> aux(other);
*this = aux.markAsRValue();
}
else
{
// evaluate/copy vector per vector
for (Index j=0; j<m_outerSize.value(); ++j)
{
SparseVector<Scalar,IsRowMajor ? RowMajorBit : 0> aux(other.innerVector(j));
m_matrix.const_cast_derived()._data()[m_outerStart+j].swap(aux._data());
}
}
return *this;
}
inline SparseInnerVectorSet& operator=(const SparseInnerVectorSet& other)
{
return operator=<SparseInnerVectorSet>(other);
}
Index nonZeros() const
{
Index count = 0;
for (Index j=0; j<m_outerSize.value(); ++j)
count += m_matrix._data()[m_outerStart+j].size();
return count;
}
const Scalar& lastCoeff() const
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(SparseInnerVectorSet);
eigen_assert(m_matrix.data()[m_outerStart].size()>0);
return m_matrix.data()[m_outerStart].vale(m_matrix.data()[m_outerStart].size()-1);
}
// template<typename Sparse>
// inline SparseInnerVectorSet& operator=(const SparseMatrixBase<OtherDerived>& other)
// {
// return *this;
// }
EIGEN_STRONG_INLINE Index rows() const { return IsRowMajor ? m_outerSize.value() : m_matrix.rows(); }
EIGEN_STRONG_INLINE Index cols() const { return IsRowMajor ? m_matrix.cols() : m_outerSize.value(); }
protected:
const typename MatrixType::Nested m_matrix;
Index m_outerStart;
const internal::variable_if_dynamic<Index, Size> m_outerSize;
};
#endif
} // end namespace Eigen
#endif // EIGEN_SPARSE_BLOCKFORDYNAMICMATRIX_H
| 4,260
| 33.642276
| 120
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SparseExtra/MarketIO.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2012 Desire NUENTSA WAKAM <desire.nuentsa_wakam@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPARSE_MARKET_IO_H
#define EIGEN_SPARSE_MARKET_IO_H
#include <iostream>
#include <vector>
namespace Eigen {
namespace internal
{
template <typename Scalar, typename StorageIndex>
inline void GetMarketLine (const char* line, StorageIndex& i, StorageIndex& j, Scalar& value)
{
std::stringstream sline(line);
sline >> i >> j >> value;
}
template<> inline void GetMarketLine (const char* line, int& i, int& j, float& value)
{ std::sscanf(line, "%d %d %g", &i, &j, &value); }
template<> inline void GetMarketLine (const char* line, int& i, int& j, double& value)
{ std::sscanf(line, "%d %d %lg", &i, &j, &value); }
template<> inline void GetMarketLine (const char* line, int& i, int& j, std::complex<float>& value)
{ std::sscanf(line, "%d %d %g %g", &i, &j, &numext::real_ref(value), &numext::imag_ref(value)); }
template<> inline void GetMarketLine (const char* line, int& i, int& j, std::complex<double>& value)
{ std::sscanf(line, "%d %d %lg %lg", &i, &j, &numext::real_ref(value), &numext::imag_ref(value)); }
template <typename Scalar, typename StorageIndex>
inline void GetMarketLine (const char* line, StorageIndex& i, StorageIndex& j, std::complex<Scalar>& value)
{
std::stringstream sline(line);
Scalar valR, valI;
sline >> i >> j >> valR >> valI;
value = std::complex<Scalar>(valR,valI);
}
template <typename RealScalar>
inline void GetVectorElt (const std::string& line, RealScalar& val)
{
std::istringstream newline(line);
newline >> val;
}
template <typename RealScalar>
inline void GetVectorElt (const std::string& line, std::complex<RealScalar>& val)
{
RealScalar valR, valI;
std::istringstream newline(line);
newline >> valR >> valI;
val = std::complex<RealScalar>(valR, valI);
}
template<typename Scalar>
inline void putMarketHeader(std::string& header,int sym)
{
header= "%%MatrixMarket matrix coordinate ";
if(internal::is_same<Scalar, std::complex<float> >::value || internal::is_same<Scalar, std::complex<double> >::value)
{
header += " complex";
if(sym == Symmetric) header += " symmetric";
else if (sym == SelfAdjoint) header += " Hermitian";
else header += " general";
}
else
{
header += " real";
if(sym == Symmetric) header += " symmetric";
else header += " general";
}
}
template<typename Scalar, typename StorageIndex>
inline void PutMatrixElt(Scalar value, StorageIndex row, StorageIndex col, std::ofstream& out)
{
out << row << " "<< col << " " << value << "\n";
}
template<typename Scalar, typename StorageIndex>
inline void PutMatrixElt(std::complex<Scalar> value, StorageIndex row, StorageIndex col, std::ofstream& out)
{
out << row << " " << col << " " << value.real() << " " << value.imag() << "\n";
}
template<typename Scalar>
inline void putVectorElt(Scalar value, std::ofstream& out)
{
out << value << "\n";
}
template<typename Scalar>
inline void putVectorElt(std::complex<Scalar> value, std::ofstream& out)
{
out << value.real() << " " << value.imag()<< "\n";
}
} // end namespace internal
inline bool getMarketHeader(const std::string& filename, int& sym, bool& iscomplex, bool& isvector)
{
sym = 0;
iscomplex = false;
isvector = false;
std::ifstream in(filename.c_str(),std::ios::in);
if(!in)
return false;
std::string line;
// The matrix header is always the first line in the file
std::getline(in, line); eigen_assert(in.good());
std::stringstream fmtline(line);
std::string substr[5];
fmtline>> substr[0] >> substr[1] >> substr[2] >> substr[3] >> substr[4];
if(substr[2].compare("array") == 0) isvector = true;
if(substr[3].compare("complex") == 0) iscomplex = true;
if(substr[4].compare("symmetric") == 0) sym = Symmetric;
else if (substr[4].compare("Hermitian") == 0) sym = SelfAdjoint;
return true;
}
template<typename SparseMatrixType>
bool loadMarket(SparseMatrixType& mat, const std::string& filename)
{
typedef typename SparseMatrixType::Scalar Scalar;
typedef typename SparseMatrixType::StorageIndex StorageIndex;
std::ifstream input(filename.c_str(),std::ios::in);
if(!input)
return false;
char rdbuffer[4096];
input.rdbuf()->pubsetbuf(rdbuffer, 4096);
const int maxBuffersize = 2048;
char buffer[maxBuffersize];
bool readsizes = false;
typedef Triplet<Scalar,StorageIndex> T;
std::vector<T> elements;
Index M(-1), N(-1), NNZ(-1);
Index count = 0;
while(input.getline(buffer, maxBuffersize))
{
// skip comments
//NOTE An appropriate test should be done on the header to get the symmetry
if(buffer[0]=='%')
continue;
if(!readsizes)
{
std::stringstream line(buffer);
line >> M >> N >> NNZ;
if(M > 0 && N > 0)
{
readsizes = true;
mat.resize(M,N);
mat.reserve(NNZ);
}
}
else
{
StorageIndex i(-1), j(-1);
Scalar value;
internal::GetMarketLine(buffer, i, j, value);
i--;
j--;
if(i>=0 && j>=0 && i<M && j<N)
{
++count;
elements.push_back(T(i,j,value));
}
else
std::cerr << "Invalid read: " << i << "," << j << "\n";
}
}
mat.setFromTriplets(elements.begin(), elements.end());
if(count!=NNZ)
std::cerr << count << "!=" << NNZ << "\n";
input.close();
return true;
}
template<typename VectorType>
bool loadMarketVector(VectorType& vec, const std::string& filename)
{
typedef typename VectorType::Scalar Scalar;
std::ifstream in(filename.c_str(), std::ios::in);
if(!in)
return false;
std::string line;
int n(0), col(0);
do
{ // Skip comments
std::getline(in, line); eigen_assert(in.good());
} while (line[0] == '%');
std::istringstream newline(line);
newline >> n >> col;
eigen_assert(n>0 && col>0);
vec.resize(n);
int i = 0;
Scalar value;
while ( std::getline(in, line) && (i < n) ){
internal::GetVectorElt(line, value);
vec(i++) = value;
}
in.close();
if (i!=n){
std::cerr<< "Unable to read all elements from file " << filename << "\n";
return false;
}
return true;
}
template<typename SparseMatrixType>
bool saveMarket(const SparseMatrixType& mat, const std::string& filename, int sym = 0)
{
typedef typename SparseMatrixType::Scalar Scalar;
typedef typename SparseMatrixType::RealScalar RealScalar;
std::ofstream out(filename.c_str(),std::ios::out);
if(!out)
return false;
out.flags(std::ios_base::scientific);
out.precision(std::numeric_limits<RealScalar>::digits10 + 2);
std::string header;
internal::putMarketHeader<Scalar>(header, sym);
out << header << std::endl;
out << mat.rows() << " " << mat.cols() << " " << mat.nonZeros() << "\n";
int count = 0;
for(int j=0; j<mat.outerSize(); ++j)
for(typename SparseMatrixType::InnerIterator it(mat,j); it; ++it)
{
++ count;
internal::PutMatrixElt(it.value(), it.row()+1, it.col()+1, out);
}
out.close();
return true;
}
template<typename VectorType>
bool saveMarketVector (const VectorType& vec, const std::string& filename)
{
typedef typename VectorType::Scalar Scalar;
typedef typename VectorType::RealScalar RealScalar;
std::ofstream out(filename.c_str(),std::ios::out);
if(!out)
return false;
out.flags(std::ios_base::scientific);
out.precision(std::numeric_limits<RealScalar>::digits10 + 2);
if(internal::is_same<Scalar, std::complex<float> >::value || internal::is_same<Scalar, std::complex<double> >::value)
out << "%%MatrixMarket matrix array complex general\n";
else
out << "%%MatrixMarket matrix array real general\n";
out << vec.size() << " "<< 1 << "\n";
for (int i=0; i < vec.size(); i++){
internal::putVectorElt(vec(i), out);
}
out.close();
return true;
}
} // end namespace Eigen
#endif // EIGEN_SPARSE_MARKET_IO_H
| 8,416
| 28.742049
| 121
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SparseExtra/MatrixMarketIterator.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Desire NUENTSA WAKAM <desire.nuentsa_wakam@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BROWSE_MATRICES_H
#define EIGEN_BROWSE_MATRICES_H
namespace Eigen {
enum {
SPD = 0x100,
NonSymmetric = 0x0
};
/**
* @brief Iterator to browse matrices from a specified folder
*
* This is used to load all the matrices from a folder.
* The matrices should be in Matrix Market format
* It is assumed that the matrices are named as matname.mtx
* and matname_SPD.mtx if the matrix is Symmetric and positive definite (or Hermitian)
* The right hand side vectors are loaded as well, if they exist.
* They should be named as matname_b.mtx.
* Note that the right hand side for a SPD matrix is named as matname_SPD_b.mtx
*
* Sometimes a reference solution is available. In this case, it should be named as matname_x.mtx
*
* Sample code
* \code
*
* \endcode
*
* \tparam Scalar The scalar type
*/
template <typename Scalar>
class MatrixMarketIterator
{
typedef typename NumTraits<Scalar>::Real RealScalar;
public:
typedef Matrix<Scalar,Dynamic,1> VectorType;
typedef SparseMatrix<Scalar,ColMajor> MatrixType;
public:
MatrixMarketIterator(const std::string &folder)
: m_sym(0), m_isvalid(false), m_matIsLoaded(false), m_hasRhs(false), m_hasrefX(false), m_folder(folder)
{
m_folder_id = opendir(folder.c_str());
if(m_folder_id)
Getnextvalidmatrix();
}
~MatrixMarketIterator()
{
if (m_folder_id) closedir(m_folder_id);
}
inline MatrixMarketIterator& operator++()
{
m_matIsLoaded = false;
m_hasrefX = false;
m_hasRhs = false;
Getnextvalidmatrix();
return *this;
}
inline operator bool() const { return m_isvalid;}
/** Return the sparse matrix corresponding to the current file */
inline MatrixType& matrix()
{
// Read the matrix
if (m_matIsLoaded) return m_mat;
std::string matrix_file = m_folder + "/" + m_matname + ".mtx";
if ( !loadMarket(m_mat, matrix_file))
{
std::cerr << "Warning loadMarket failed when loading \"" << matrix_file << "\"" << std::endl;
m_matIsLoaded = false;
return m_mat;
}
m_matIsLoaded = true;
if (m_sym != NonSymmetric)
{
// Check whether we need to restore a full matrix:
RealScalar diag_norm = m_mat.diagonal().norm();
RealScalar lower_norm = m_mat.template triangularView<Lower>().norm();
RealScalar upper_norm = m_mat.template triangularView<Upper>().norm();
if(lower_norm>diag_norm && upper_norm==diag_norm)
{
// only the lower part is stored
MatrixType tmp(m_mat);
m_mat = tmp.template selfadjointView<Lower>();
}
else if(upper_norm>diag_norm && lower_norm==diag_norm)
{
// only the upper part is stored
MatrixType tmp(m_mat);
m_mat = tmp.template selfadjointView<Upper>();
}
}
return m_mat;
}
/** Return the right hand side corresponding to the current matrix.
* If the rhs file is not provided, a random rhs is generated
*/
inline VectorType& rhs()
{
// Get the right hand side
if (m_hasRhs) return m_rhs;
std::string rhs_file;
rhs_file = m_folder + "/" + m_matname + "_b.mtx"; // The pattern is matname_b.mtx
m_hasRhs = Fileexists(rhs_file);
if (m_hasRhs)
{
m_rhs.resize(m_mat.cols());
m_hasRhs = loadMarketVector(m_rhs, rhs_file);
}
if (!m_hasRhs)
{
// Generate a random right hand side
if (!m_matIsLoaded) this->matrix();
m_refX.resize(m_mat.cols());
m_refX.setRandom();
m_rhs = m_mat * m_refX;
m_hasrefX = true;
m_hasRhs = true;
}
return m_rhs;
}
/** Return a reference solution
* If it is not provided and if the right hand side is not available
* then refX is randomly generated such that A*refX = b
* where A and b are the matrix and the rhs.
* Note that when a rhs is provided, refX is not available
*/
inline VectorType& refX()
{
// Check if a reference solution is provided
if (m_hasrefX) return m_refX;
std::string lhs_file;
lhs_file = m_folder + "/" + m_matname + "_x.mtx";
m_hasrefX = Fileexists(lhs_file);
if (m_hasrefX)
{
m_refX.resize(m_mat.cols());
m_hasrefX = loadMarketVector(m_refX, lhs_file);
}
else
m_refX.resize(0);
return m_refX;
}
inline std::string& matname() { return m_matname; }
inline int sym() { return m_sym; }
bool hasRhs() {return m_hasRhs; }
bool hasrefX() {return m_hasrefX; }
bool isFolderValid() { return bool(m_folder_id); }
protected:
inline bool Fileexists(std::string file)
{
std::ifstream file_id(file.c_str());
if (!file_id.good() )
{
return false;
}
else
{
file_id.close();
return true;
}
}
void Getnextvalidmatrix( )
{
m_isvalid = false;
// Here, we return with the next valid matrix in the folder
while ( (m_curs_id = readdir(m_folder_id)) != NULL) {
m_isvalid = false;
std::string curfile;
curfile = m_folder + "/" + m_curs_id->d_name;
// Discard if it is a folder
if (m_curs_id->d_type == DT_DIR) continue; //FIXME This may not be available on non BSD systems
// struct stat st_buf;
// stat (curfile.c_str(), &st_buf);
// if (S_ISDIR(st_buf.st_mode)) continue;
// Determine from the header if it is a matrix or a right hand side
bool isvector,iscomplex=false;
if(!getMarketHeader(curfile,m_sym,iscomplex,isvector)) continue;
if(isvector) continue;
if (!iscomplex)
{
if(internal::is_same<Scalar, std::complex<float> >::value || internal::is_same<Scalar, std::complex<double> >::value)
continue;
}
if (iscomplex)
{
if(internal::is_same<Scalar, float>::value || internal::is_same<Scalar, double>::value)
continue;
}
// Get the matrix name
std::string filename = m_curs_id->d_name;
m_matname = filename.substr(0, filename.length()-4);
// Find if the matrix is SPD
size_t found = m_matname.find("SPD");
if( (found!=std::string::npos) && (m_sym != NonSymmetric) )
m_sym = SPD;
m_isvalid = true;
break;
}
}
int m_sym; // Symmetry of the matrix
MatrixType m_mat; // Current matrix
VectorType m_rhs; // Current vector
VectorType m_refX; // The reference solution, if exists
std::string m_matname; // Matrix Name
bool m_isvalid;
bool m_matIsLoaded; // Determine if the matrix has already been loaded from the file
bool m_hasRhs; // The right hand side exists
bool m_hasrefX; // A reference solution is provided
std::string m_folder;
DIR * m_folder_id;
struct dirent *m_curs_id;
};
} // end namespace Eigen
#endif
| 7,568
| 29.520161
| 127
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SparseExtra/RandomSetter.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_RANDOMSETTER_H
#define EIGEN_RANDOMSETTER_H
#if defined(EIGEN_GOOGLEHASH_SUPPORT)
// Ensure the ::google namespace exists, required for checking existence of
// ::google::dense_hash_map and ::google::sparse_hash_map.
namespace google {}
#endif
namespace Eigen {
/** Represents a std::map
*
* \see RandomSetter
*/
template<typename Scalar> struct StdMapTraits
{
typedef int KeyType;
typedef std::map<KeyType,Scalar> Type;
enum {
IsSorted = 1
};
static void setInvalidKey(Type&, const KeyType&) {}
};
#ifdef EIGEN_UNORDERED_MAP_SUPPORT
/** Represents a std::unordered_map
*
* To use it you need to both define EIGEN_UNORDERED_MAP_SUPPORT and include the unordered_map header file
* yourself making sure that unordered_map is defined in the std namespace.
*
* For instance, with current version of gcc you can either enable C++0x standard (-std=c++0x) or do:
* \code
* #include <tr1/unordered_map>
* #define EIGEN_UNORDERED_MAP_SUPPORT
* namespace std {
* using std::tr1::unordered_map;
* }
* \endcode
*
* \see RandomSetter
*/
template<typename Scalar> struct StdUnorderedMapTraits
{
typedef int KeyType;
typedef std::unordered_map<KeyType,Scalar> Type;
enum {
IsSorted = 0
};
static void setInvalidKey(Type&, const KeyType&) {}
};
#endif // EIGEN_UNORDERED_MAP_SUPPORT
#if defined(EIGEN_GOOGLEHASH_SUPPORT)
namespace google {
// Namespace work-around, since sometimes dense_hash_map and sparse_hash_map
// are in the global namespace, and other times they are under ::google.
using namespace ::google;
template<typename KeyType, typename Scalar>
struct DenseHashMap {
typedef dense_hash_map<KeyType, Scalar> type;
};
template<typename KeyType, typename Scalar>
struct SparseHashMap {
typedef sparse_hash_map<KeyType, Scalar> type;
};
} // namespace google
/** Represents a google::dense_hash_map
*
* \see RandomSetter
*/
template<typename Scalar> struct GoogleDenseHashMapTraits
{
typedef int KeyType;
typedef typename google::DenseHashMap<KeyType,Scalar>::type Type;
enum {
IsSorted = 0
};
static void setInvalidKey(Type& map, const KeyType& k)
{ map.set_empty_key(k); }
};
/** Represents a google::sparse_hash_map
*
* \see RandomSetter
*/
template<typename Scalar> struct GoogleSparseHashMapTraits
{
typedef int KeyType;
typedef typename google::SparseHashMap<KeyType,Scalar>::type Type;
enum {
IsSorted = 0
};
static void setInvalidKey(Type&, const KeyType&) {}
};
#endif
/** \class RandomSetter
*
* \brief The RandomSetter is a wrapper object allowing to set/update a sparse matrix with random access
*
* \tparam SparseMatrixType the type of the sparse matrix we are updating
* \tparam MapTraits a traits class representing the map implementation used for the temporary sparse storage.
* Its default value depends on the system.
* \tparam OuterPacketBits defines the number of rows (or columns) manage by a single map object
* as a power of two exponent.
*
* This class temporarily represents a sparse matrix object using a generic map implementation allowing for
* efficient random access. The conversion from the compressed representation to a hash_map object is performed
* in the RandomSetter constructor, while the sparse matrix is updated back at destruction time. This strategy
* suggest the use of nested blocks as in this example:
*
* \code
* SparseMatrix<double> m(rows,cols);
* {
* RandomSetter<SparseMatrix<double> > w(m);
* // don't use m but w instead with read/write random access to the coefficients:
* for(;;)
* w(rand(),rand()) = rand;
* }
* // when w is deleted, the data are copied back to m
* // and m is ready to use.
* \endcode
*
* Since hash_map objects are not fully sorted, representing a full matrix as a single hash_map would
* involve a big and costly sort to update the compressed matrix back. To overcome this issue, a RandomSetter
* use multiple hash_map, each representing 2^OuterPacketBits columns or rows according to the storage order.
* To reach optimal performance, this value should be adjusted according to the average number of nonzeros
* per rows/columns.
*
* The possible values for the template parameter MapTraits are:
* - \b StdMapTraits: corresponds to std::map. (does not perform very well)
* - \b GnuHashMapTraits: corresponds to __gnu_cxx::hash_map (available only with GCC)
* - \b GoogleDenseHashMapTraits: corresponds to google::dense_hash_map (best efficiency, reasonable memory consumption)
* - \b GoogleSparseHashMapTraits: corresponds to google::sparse_hash_map (best memory consumption, relatively good performance)
*
* The default map implementation depends on the availability, and the preferred order is:
* GoogleSparseHashMapTraits, GnuHashMapTraits, and finally StdMapTraits.
*
* For performance and memory consumption reasons it is highly recommended to use one of
* Google's hash_map implementations. To enable the support for them, you must define
* EIGEN_GOOGLEHASH_SUPPORT. This will include both <google/dense_hash_map> and
* <google/sparse_hash_map> for you.
*
* \see https://github.com/sparsehash/sparsehash
*/
template<typename SparseMatrixType,
template <typename T> class MapTraits =
#if defined(EIGEN_GOOGLEHASH_SUPPORT)
GoogleDenseHashMapTraits
#elif defined(_HASH_MAP)
GnuHashMapTraits
#else
StdMapTraits
#endif
,int OuterPacketBits = 6>
class RandomSetter
{
typedef typename SparseMatrixType::Scalar Scalar;
typedef typename SparseMatrixType::StorageIndex StorageIndex;
struct ScalarWrapper
{
ScalarWrapper() : value(0) {}
Scalar value;
};
typedef typename MapTraits<ScalarWrapper>::KeyType KeyType;
typedef typename MapTraits<ScalarWrapper>::Type HashMapType;
static const int OuterPacketMask = (1 << OuterPacketBits) - 1;
enum {
SwapStorage = 1 - MapTraits<ScalarWrapper>::IsSorted,
TargetRowMajor = (SparseMatrixType::Flags & RowMajorBit) ? 1 : 0,
SetterRowMajor = SwapStorage ? 1-TargetRowMajor : TargetRowMajor
};
public:
/** Constructs a random setter object from the sparse matrix \a target
*
* Note that the initial value of \a target are imported. If you want to re-set
* a sparse matrix from scratch, then you must set it to zero first using the
* setZero() function.
*/
inline RandomSetter(SparseMatrixType& target)
: mp_target(&target)
{
const Index outerSize = SwapStorage ? target.innerSize() : target.outerSize();
const Index innerSize = SwapStorage ? target.outerSize() : target.innerSize();
m_outerPackets = outerSize >> OuterPacketBits;
if (outerSize&OuterPacketMask)
m_outerPackets += 1;
m_hashmaps = new HashMapType[m_outerPackets];
// compute number of bits needed to store inner indices
Index aux = innerSize - 1;
m_keyBitsOffset = 0;
while (aux)
{
++m_keyBitsOffset;
aux = aux >> 1;
}
KeyType ik = (1<<(OuterPacketBits+m_keyBitsOffset));
for (Index k=0; k<m_outerPackets; ++k)
MapTraits<ScalarWrapper>::setInvalidKey(m_hashmaps[k],ik);
// insert current coeffs
for (Index j=0; j<mp_target->outerSize(); ++j)
for (typename SparseMatrixType::InnerIterator it(*mp_target,j); it; ++it)
(*this)(TargetRowMajor?j:it.index(), TargetRowMajor?it.index():j) = it.value();
}
/** Destructor updating back the sparse matrix target */
~RandomSetter()
{
KeyType keyBitsMask = (1<<m_keyBitsOffset)-1;
if (!SwapStorage) // also means the map is sorted
{
mp_target->setZero();
mp_target->makeCompressed();
mp_target->reserve(nonZeros());
Index prevOuter = -1;
for (Index k=0; k<m_outerPackets; ++k)
{
const Index outerOffset = (1<<OuterPacketBits) * k;
typename HashMapType::iterator end = m_hashmaps[k].end();
for (typename HashMapType::iterator it = m_hashmaps[k].begin(); it!=end; ++it)
{
const Index outer = (it->first >> m_keyBitsOffset) + outerOffset;
const Index inner = it->first & keyBitsMask;
if (prevOuter!=outer)
{
for (Index j=prevOuter+1;j<=outer;++j)
mp_target->startVec(j);
prevOuter = outer;
}
mp_target->insertBackByOuterInner(outer, inner) = it->second.value;
}
}
mp_target->finalize();
}
else
{
VectorXi positions(mp_target->outerSize());
positions.setZero();
// pass 1
for (Index k=0; k<m_outerPackets; ++k)
{
typename HashMapType::iterator end = m_hashmaps[k].end();
for (typename HashMapType::iterator it = m_hashmaps[k].begin(); it!=end; ++it)
{
const Index outer = it->first & keyBitsMask;
++positions[outer];
}
}
// prefix sum
StorageIndex count = 0;
for (Index j=0; j<mp_target->outerSize(); ++j)
{
StorageIndex tmp = positions[j];
mp_target->outerIndexPtr()[j] = count;
positions[j] = count;
count += tmp;
}
mp_target->makeCompressed();
mp_target->outerIndexPtr()[mp_target->outerSize()] = count;
mp_target->resizeNonZeros(count);
// pass 2
for (Index k=0; k<m_outerPackets; ++k)
{
const Index outerOffset = (1<<OuterPacketBits) * k;
typename HashMapType::iterator end = m_hashmaps[k].end();
for (typename HashMapType::iterator it = m_hashmaps[k].begin(); it!=end; ++it)
{
const Index inner = (it->first >> m_keyBitsOffset) + outerOffset;
const Index outer = it->first & keyBitsMask;
// sorted insertion
// Note that we have to deal with at most 2^OuterPacketBits unsorted coefficients,
// moreover those 2^OuterPacketBits coeffs are likely to be sparse, an so only a
// small fraction of them have to be sorted, whence the following simple procedure:
Index posStart = mp_target->outerIndexPtr()[outer];
Index i = (positions[outer]++) - 1;
while ( (i >= posStart) && (mp_target->innerIndexPtr()[i] > inner) )
{
mp_target->valuePtr()[i+1] = mp_target->valuePtr()[i];
mp_target->innerIndexPtr()[i+1] = mp_target->innerIndexPtr()[i];
--i;
}
mp_target->innerIndexPtr()[i+1] = internal::convert_index<StorageIndex>(inner);
mp_target->valuePtr()[i+1] = it->second.value;
}
}
}
delete[] m_hashmaps;
}
/** \returns a reference to the coefficient at given coordinates \a row, \a col */
Scalar& operator() (Index row, Index col)
{
const Index outer = SetterRowMajor ? row : col;
const Index inner = SetterRowMajor ? col : row;
const Index outerMajor = outer >> OuterPacketBits; // index of the packet/map
const Index outerMinor = outer & OuterPacketMask; // index of the inner vector in the packet
const KeyType key = internal::convert_index<KeyType>((outerMinor<<m_keyBitsOffset) | inner);
return m_hashmaps[outerMajor][key].value;
}
/** \returns the number of non zero coefficients
*
* \note According to the underlying map/hash_map implementation,
* this function might be quite expensive.
*/
Index nonZeros() const
{
Index nz = 0;
for (Index k=0; k<m_outerPackets; ++k)
nz += static_cast<Index>(m_hashmaps[k].size());
return nz;
}
protected:
HashMapType* m_hashmaps;
SparseMatrixType* mp_target;
Index m_outerPackets;
unsigned char m_keyBitsOffset;
};
} // end namespace Eigen
#endif // EIGEN_RANDOMSETTER_H
| 12,423
| 34.497143
| 130
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsArrayAPI.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BESSELFUNCTIONS_ARRAYAPI_H
#define EIGEN_BESSELFUNCTIONS_ARRAYAPI_H
namespace Eigen {
/** \returns an expression of the coefficient-wise i0(\a x) to the given
* arrays.
*
* It returns the modified Bessel function of the first kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of i0(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_i0()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i0_op<typename Derived::Scalar>, const Derived>
bessel_i0(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i0_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise i0e(\a x) to the given
* arrays.
*
* It returns the exponentially scaled modified Bessel
* function of the first kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of i0e(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_i0e()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i0e_op<typename Derived::Scalar>, const Derived>
bessel_i0e(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i0e_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise i1(\a x) to the given
* arrays.
*
* It returns the modified Bessel function of the first kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of i1(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_i1()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i1_op<typename Derived::Scalar>, const Derived>
bessel_i1(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i1_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise i1e(\a x) to the given
* arrays.
*
* It returns the exponentially scaled modified Bessel
* function of the first kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of i1e(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_i1e()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i1e_op<typename Derived::Scalar>, const Derived>
bessel_i1e(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_i1e_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise k0(\a x) to the given
* arrays.
*
* It returns the modified Bessel function of the second kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of k0(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_k0()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k0_op<typename Derived::Scalar>, const Derived>
bessel_k0(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k0_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise k0e(\a x) to the given
* arrays.
*
* It returns the exponentially scaled modified Bessel
* function of the second kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of k0e(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_k0e()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k0e_op<typename Derived::Scalar>, const Derived>
bessel_k0e(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k0e_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise k1(\a x) to the given
* arrays.
*
* It returns the modified Bessel function of the second kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of k1(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_k1()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k1_op<typename Derived::Scalar>, const Derived>
bessel_k1(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k1_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise k1e(\a x) to the given
* arrays.
*
* It returns the exponentially scaled modified Bessel
* function of the second kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of k1e(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_k1e()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k1e_op<typename Derived::Scalar>, const Derived>
bessel_k1e(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_k1e_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise j0(\a x) to the given
* arrays.
*
* It returns the Bessel function of the first kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of j0(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_j0()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_j0_op<typename Derived::Scalar>, const Derived>
bessel_j0(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_j0_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise y0(\a x) to the given
* arrays.
*
* It returns the Bessel function of the second kind of order zero.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of y0(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_y0()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_y0_op<typename Derived::Scalar>, const Derived>
bessel_y0(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_y0_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise j1(\a x) to the given
* arrays.
*
* It returns the modified Bessel function of the first kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of j1(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_j1()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_j1_op<typename Derived::Scalar>, const Derived>
bessel_j1(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_j1_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
/** \returns an expression of the coefficient-wise y1(\a x) to the given
* arrays.
*
* It returns the Bessel function of the second kind of order one.
*
* \param x is the argument
*
* \note This function supports only float and double scalar types. To support
* other scalar types, the user has to provide implementations of y1(T) for
* any scalar type T to be supported.
*
* \sa ArrayBase::bessel_y1()
*/
template <typename Derived>
EIGEN_STRONG_INLINE const Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_y1_op<typename Derived::Scalar>, const Derived>
bessel_y1(const Eigen::ArrayBase<Derived>& x) {
return Eigen::CwiseUnaryOp<
Eigen::internal::scalar_bessel_y1_op<typename Derived::Scalar>,
const Derived>(x.derived());
}
} // end namespace Eigen
#endif // EIGEN_BESSELFUNCTIONS_ARRAYAPI_H
| 10,015
| 33.898955
| 83
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsBFloat16.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BESSELFUNCTIONS_BFLOAT16_H
#define EIGEN_BESSELFUNCTIONS_BFLOAT16_H
namespace Eigen {
namespace numext {
#if EIGEN_HAS_C99_MATH
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i0(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_i0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i0e(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_i0e(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i1(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_i1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_i1e(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_i1e(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_j0(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_j0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_j1(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_j1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_y0(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_y0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_y1(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_y1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k0(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_k0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k0e(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_k0e(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k1(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_k1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::bfloat16 bessel_k1e(const Eigen::bfloat16& x) {
return Eigen::bfloat16(Eigen::numext::bessel_k1e(static_cast<float>(x)));
}
#endif
} // end namespace numext
} // end namespace Eigen
#endif // EIGEN_BESSELFUNCTIONS_BFLOAT16_H
| 2,724
| 38.492754
| 92
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsFunctors.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Eugene Brevdo <ebrevdo@gmail.com>
// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BESSELFUNCTIONS_FUNCTORS_H
#define EIGEN_BESSELFUNCTIONS_FUNCTORS_H
namespace Eigen {
namespace internal {
/** \internal
* \brief Template functor to compute the modified Bessel function of the first
* kind of order zero.
* \sa class CwiseUnaryOp, Cwise::bessel_i0()
*/
template <typename Scalar>
struct scalar_bessel_i0_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_i0_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_i0;
return bessel_i0(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_i0(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_i0_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=20 is computed.
// The cost is N multiplications and 2N additions. We also add
// the cost of an additional exp over i0e.
Cost = 28 * NumTraits<Scalar>::MulCost + 48 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the exponentially scaled modified Bessel
* function of the first kind of order zero
* \sa class CwiseUnaryOp, Cwise::bessel_i0e()
*/
template <typename Scalar>
struct scalar_bessel_i0e_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_i0e_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_i0e;
return bessel_i0e(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_i0e(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_i0e_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=20 is computed.
// The cost is N multiplications and 2N additions.
Cost = 20 * NumTraits<Scalar>::MulCost + 40 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the modified Bessel function of the first
* kind of order one
* \sa class CwiseUnaryOp, Cwise::bessel_i1()
*/
template <typename Scalar>
struct scalar_bessel_i1_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_i1_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_i1;
return bessel_i1(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_i1(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_i1_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=20 is computed.
// The cost is N multiplications and 2N additions. We also add
// the cost of an additional exp over i1e.
Cost = 28 * NumTraits<Scalar>::MulCost + 48 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the exponentially scaled modified Bessel
* function of the first kind of order zero
* \sa class CwiseUnaryOp, Cwise::bessel_i1e()
*/
template <typename Scalar>
struct scalar_bessel_i1e_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_i1e_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_i1e;
return bessel_i1e(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_i1e(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_i1e_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=20 is computed.
// The cost is N multiplications and 2N additions.
Cost = 20 * NumTraits<Scalar>::MulCost + 40 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the Bessel function of the second kind of
* order zero
* \sa class CwiseUnaryOp, Cwise::bessel_j0()
*/
template <typename Scalar>
struct scalar_bessel_j0_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_j0_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_j0;
return bessel_j0(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_j0(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_j0_op<Scalar> > {
enum {
// 6 polynomial of order ~N=8 is computed.
// The cost is N multiplications and N additions each, along with a
// sine, cosine and rsqrt cost.
Cost = 63 * NumTraits<Scalar>::MulCost + 48 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the Bessel function of the second kind of
* order zero
* \sa class CwiseUnaryOp, Cwise::bessel_y0()
*/
template <typename Scalar>
struct scalar_bessel_y0_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_y0_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_y0;
return bessel_y0(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_y0(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_y0_op<Scalar> > {
enum {
// 6 polynomial of order ~N=8 is computed.
// The cost is N multiplications and N additions each, along with a
// sine, cosine, rsqrt and j0 cost.
Cost = 126 * NumTraits<Scalar>::MulCost + 96 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the Bessel function of the first kind of
* order one
* \sa class CwiseUnaryOp, Cwise::bessel_j1()
*/
template <typename Scalar>
struct scalar_bessel_j1_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_j1_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_j1;
return bessel_j1(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_j1(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_j1_op<Scalar> > {
enum {
// 6 polynomial of order ~N=8 is computed.
// The cost is N multiplications and N additions each, along with a
// sine, cosine and rsqrt cost.
Cost = 63 * NumTraits<Scalar>::MulCost + 48 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the Bessel function of the second kind of
* order one
* \sa class CwiseUnaryOp, Cwise::bessel_j1e()
*/
template <typename Scalar>
struct scalar_bessel_y1_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_y1_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_y1;
return bessel_y1(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_y1(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_y1_op<Scalar> > {
enum {
// 6 polynomial of order ~N=8 is computed.
// The cost is N multiplications and N additions each, along with a
// sine, cosine, rsqrt and j1 cost.
Cost = 126 * NumTraits<Scalar>::MulCost + 96 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the modified Bessel function of the second
* kind of order zero
* \sa class CwiseUnaryOp, Cwise::bessel_k0()
*/
template <typename Scalar>
struct scalar_bessel_k0_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_k0_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_k0;
return bessel_k0(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_k0(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_k0_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=10 is computed.
// The cost is N multiplications and 2N additions. In addition we compute
// i0, a log, exp and prsqrt and sin and cos.
Cost = 68 * NumTraits<Scalar>::MulCost + 88 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the exponentially scaled modified Bessel
* function of the second kind of order zero
* \sa class CwiseUnaryOp, Cwise::bessel_k0e()
*/
template <typename Scalar>
struct scalar_bessel_k0e_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_k0e_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_k0e;
return bessel_k0e(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_k0e(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_k0e_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=10 is computed.
// The cost is N multiplications and 2N additions. In addition we compute
// i0, a log, exp and prsqrt and sin and cos.
Cost = 68 * NumTraits<Scalar>::MulCost + 88 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the modified Bessel function of the
* second kind of order one
* \sa class CwiseUnaryOp, Cwise::bessel_k1()
*/
template <typename Scalar>
struct scalar_bessel_k1_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_k1_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_k1;
return bessel_k1(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_k1(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_k1_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=10 is computed.
// The cost is N multiplications and 2N additions. In addition we compute
// i1, a log, exp and prsqrt and sin and cos.
Cost = 68 * NumTraits<Scalar>::MulCost + 88 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
/** \internal
* \brief Template functor to compute the exponentially scaled modified Bessel
* function of the second kind of order one
* \sa class CwiseUnaryOp, Cwise::bessel_k1e()
*/
template <typename Scalar>
struct scalar_bessel_k1e_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_bessel_k1e_op)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& x) const {
using numext::bessel_k1e;
return bessel_k1e(x);
}
typedef typename packet_traits<Scalar>::type Packet;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& x) const {
return internal::pbessel_k1e(x);
}
};
template <typename Scalar>
struct functor_traits<scalar_bessel_k1e_op<Scalar> > {
enum {
// On average, a Chebyshev polynomial of order N=10 is computed.
// The cost is N multiplications and 2N additions. In addition we compute
// i1, a log, exp and prsqrt and sin and cos.
Cost = 68 * NumTraits<Scalar>::MulCost + 88 * NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasBessel
};
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_BESSELFUNCTIONS_FUNCTORS_H
| 12,641
| 34.312849
| 88
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsHalf.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BESSELFUNCTIONS_HALF_H
#define EIGEN_BESSELFUNCTIONS_HALF_H
namespace Eigen {
namespace numext {
#if EIGEN_HAS_C99_MATH
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i0(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_i0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i0e(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_i0e(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i1(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_i1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_i1e(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_i1e(static_cast<float>(x)));
}
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_j0(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_j0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_j1(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_j1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_y0(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_y0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_y1(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_y1(static_cast<float>(x)));
}
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k0(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_k0(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k0e(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_k0e(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k1(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_k1(static_cast<float>(x)));
}
template <>
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Eigen::half bessel_k1e(const Eigen::half& x) {
return Eigen::half(Eigen::numext::bessel_k1e(static_cast<float>(x)));
}
#endif
} // end namespace numext
} // end namespace Eigen
#endif // EIGEN_BESSELFUNCTIONS_HALF_H
| 2,544
| 36.985075
| 84
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/BesselFunctionsPacketMath.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BESSELFUNCTIONS_PACKETMATH_H
#define EIGEN_BESSELFUNCTIONS_PACKETMATH_H
namespace Eigen {
namespace internal {
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero i0(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_i0(const Packet& x) {
return numext::bessel_i0(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero i0e(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_i0e(const Packet& x) {
return numext::bessel_i0e(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one i1(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_i1(const Packet& x) {
return numext::bessel_i1(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one i1e(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_i1e(const Packet& x) {
return numext::bessel_i1e(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero j0(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_j0(const Packet& x) {
return numext::bessel_j0(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero j1(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_j1(const Packet& x) {
return numext::bessel_j1(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one y0(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_y0(const Packet& x) {
return numext::bessel_y0(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one y1(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_y1(const Packet& x) {
return numext::bessel_y1(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero k0(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_k0(const Packet& x) {
return numext::bessel_k0(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order zero k0e(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_k0e(const Packet& x) {
return numext::bessel_k0e(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one k1e(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_k1(const Packet& x) {
return numext::bessel_k1(x);
}
/** \internal \returns the exponentially scaled modified Bessel function of
* order one k1e(\a a) (coeff-wise) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pbessel_k1e(const Packet& x) {
return numext::bessel_k1e(x);
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_BESSELFUNCTIONS_PACKETMATH_H
| 4,006
| 32.672269
| 75
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/HipVectorCompatibility.h
|
#ifndef HIP_VECTOR_COMPATIBILITY_H
#define HIP_VECTOR_COMPATIBILITY_H
namespace hip_impl {
template <typename, typename, unsigned int> struct Scalar_accessor;
} // end namespace hip_impl
namespace Eigen {
namespace internal {
#define HIP_SCALAR_ACCESSOR_BUILDER(NAME) \
template <typename T, typename U, unsigned int n> \
struct NAME <hip_impl::Scalar_accessor<T, U, n>> : NAME <T> {};
#define HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(NAME) \
template <typename T, typename U, unsigned int n> \
struct NAME##_impl <hip_impl::Scalar_accessor<T, U, n>> : NAME##_impl <T> {}; \
template <typename T, typename U, unsigned int n> \
struct NAME##_retval <hip_impl::Scalar_accessor<T, U, n>> : NAME##_retval <T> {};
#define HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(NAME) \
template <typename T, typename U, unsigned int n, IgammaComputationMode mode> \
struct NAME <hip_impl::Scalar_accessor<T, U, n>, mode> : NAME <T, mode> {};
#if EIGEN_HAS_C99_MATH
HIP_SCALAR_ACCESSOR_BUILDER(betainc_helper)
HIP_SCALAR_ACCESSOR_BUILDER(incbeta_cfe)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(erf)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(erfc)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igammac)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(lgamma)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(ndtri)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(polygamma)
HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igamma_generic_impl)
#endif
HIP_SCALAR_ACCESSOR_BUILDER(digamma_impl_maybe_poly)
HIP_SCALAR_ACCESSOR_BUILDER(zeta_impl_series)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i0)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i0e)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i1)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_i1e)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_j0)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_j1)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k0)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k0e)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k1)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_k1e)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_y0)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(bessel_y1)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(betainc)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(digamma)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(gamma_sample_der_alpha)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igamma_der_a)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(igamma)
HIP_SCALAR_ACCESSOR_BUILDER_RETVAL(zeta)
HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igamma_series_impl)
HIP_SCALAR_ACCESSOR_BUILDER_IGAMMA(igammac_cf_impl)
} // end namespace internal
} // end namespace Eigen
#endif // HIP_VECTOR_COMPATIBILITY_H
| 2,489
| 35.617647
| 81
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsPacketMath.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SPECIALFUNCTIONS_PACKETMATH_H
#define EIGEN_SPECIALFUNCTIONS_PACKETMATH_H
namespace Eigen {
namespace internal {
/** \internal \returns the ln(|gamma(\a a)|) (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet plgamma(const Packet& a) { using numext::lgamma; return lgamma(a); }
/** \internal \returns the derivative of lgamma, psi(\a a) (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pdigamma(const Packet& a) { using numext::digamma; return digamma(a); }
/** \internal \returns the zeta function of two arguments (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pzeta(const Packet& x, const Packet& q) { using numext::zeta; return zeta(x, q); }
/** \internal \returns the polygamma function (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet ppolygamma(const Packet& n, const Packet& x) { using numext::polygamma; return polygamma(n, x); }
/** \internal \returns the erf(\a a) (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet perf(const Packet& a) { using numext::erf; return erf(a); }
/** \internal \returns the erfc(\a a) (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet perfc(const Packet& a) { using numext::erfc; return erfc(a); }
/** \internal \returns the ndtri(\a a) (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pndtri(const Packet& a) {
typedef typename unpacket_traits<Packet>::type ScalarType;
using internal::generic_ndtri; return generic_ndtri<Packet, ScalarType>(a);
}
/** \internal \returns the incomplete gamma function igamma(\a a, \a x) */
template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Packet pigamma(const Packet& a, const Packet& x) { using numext::igamma; return igamma(a, x); }
/** \internal \returns the derivative of the incomplete gamma function
* igamma_der_a(\a a, \a x) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pigamma_der_a(const Packet& a, const Packet& x) {
using numext::igamma_der_a; return igamma_der_a(a, x);
}
/** \internal \returns compute the derivative of the sample
* of Gamma(alpha, 1) random variable with respect to the parameter a
* gamma_sample_der_alpha(\a alpha, \a sample) */
template <typename Packet>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet pgamma_sample_der_alpha(const Packet& alpha, const Packet& sample) {
using numext::gamma_sample_der_alpha; return gamma_sample_der_alpha(alpha, sample);
}
/** \internal \returns the complementary incomplete gamma function igammac(\a a, \a x) */
template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Packet pigammac(const Packet& a, const Packet& x) { using numext::igammac; return igammac(a, x); }
/** \internal \returns the complementary incomplete gamma function betainc(\a a, \a b, \a x) */
template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Packet pbetainc(const Packet& a, const Packet& b,const Packet& x) { using numext::betainc; return betainc(a, b, x); }
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_SPECIALFUNCTIONS_PACKETMATH_H
| 3,713
| 45.425
| 117
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/arch/AVX/BesselFunctions.h
|
#ifndef EIGEN_AVX_BESSELFUNCTIONS_H
#define EIGEN_AVX_BESSELFUNCTIONS_H
namespace Eigen {
namespace internal {
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i0)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i0)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i0e)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i0e)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i1)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i1)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_i1e)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_i1e)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_j0)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_j0)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_j1)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_j1)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k0)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k0)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k0e)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k0e)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k1)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k1)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_k1e)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_k1e)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_y0)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_y0)
F16_PACKET_FUNCTION(Packet8f, Packet8h, pbessel_y1)
BF16_PACKET_FUNCTION(Packet8f, Packet8bf, pbessel_y1)
} // namespace internal
} // namespace Eigen
#endif // EIGEN_AVX_BESSELFUNCTIONS_H
| 1,492
| 30.765957
| 54
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/arch/AVX512/BesselFunctions.h
|
#ifndef EIGEN_AVX512_BESSELFUNCTIONS_H
#define EIGEN_AVX512_BESSELFUNCTIONS_H
namespace Eigen {
namespace internal {
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i0)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i0)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i0e)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i0e)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i1)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i1)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_i1e)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_i1e)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_j0)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_j0)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_j1)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_j1)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k0)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k0)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k0e)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k0e)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k1)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k1)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_k1e)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_k1e)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_y0)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_y0)
F16_PACKET_FUNCTION(Packet16f, Packet16h, pbessel_y1)
BF16_PACKET_FUNCTION(Packet16f, Packet16bf, pbessel_y1)
} // namespace internal
} // namespace Eigen
#endif // EIGEN_AVX512_BESSELFUNCTIONS_H
| 1,549
| 31.978723
| 56
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/arch/GPU/SpecialFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GPU_SPECIALFUNCTIONS_H
#define EIGEN_GPU_SPECIALFUNCTIONS_H
namespace Eigen {
namespace internal {
// Make sure this is only available when targeting a GPU: we don't want to
// introduce conflicts between these packet_traits definitions and the ones
// we'll use on the host side (SSE, AVX, ...)
#if defined(EIGEN_GPUCC) && defined(EIGEN_USE_GPU)
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 plgamma<float4>(const float4& a)
{
return make_float4(lgammaf(a.x), lgammaf(a.y), lgammaf(a.z), lgammaf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 plgamma<double2>(const double2& a)
{
using numext::lgamma;
return make_double2(lgamma(a.x), lgamma(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pdigamma<float4>(const float4& a)
{
using numext::digamma;
return make_float4(digamma(a.x), digamma(a.y), digamma(a.z), digamma(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pdigamma<double2>(const double2& a)
{
using numext::digamma;
return make_double2(digamma(a.x), digamma(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pzeta<float4>(const float4& x, const float4& q)
{
using numext::zeta;
return make_float4(zeta(x.x, q.x), zeta(x.y, q.y), zeta(x.z, q.z), zeta(x.w, q.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pzeta<double2>(const double2& x, const double2& q)
{
using numext::zeta;
return make_double2(zeta(x.x, q.x), zeta(x.y, q.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 ppolygamma<float4>(const float4& n, const float4& x)
{
using numext::polygamma;
return make_float4(polygamma(n.x, x.x), polygamma(n.y, x.y), polygamma(n.z, x.z), polygamma(n.w, x.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 ppolygamma<double2>(const double2& n, const double2& x)
{
using numext::polygamma;
return make_double2(polygamma(n.x, x.x), polygamma(n.y, x.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 perf<float4>(const float4& a)
{
return make_float4(erff(a.x), erff(a.y), erff(a.z), erff(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 perf<double2>(const double2& a)
{
using numext::erf;
return make_double2(erf(a.x), erf(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 perfc<float4>(const float4& a)
{
using numext::erfc;
return make_float4(erfc(a.x), erfc(a.y), erfc(a.z), erfc(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 perfc<double2>(const double2& a)
{
using numext::erfc;
return make_double2(erfc(a.x), erfc(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pndtri<float4>(const float4& a)
{
using numext::ndtri;
return make_float4(ndtri(a.x), ndtri(a.y), ndtri(a.z), ndtri(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pndtri<double2>(const double2& a)
{
using numext::ndtri;
return make_double2(ndtri(a.x), ndtri(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pigamma<float4>(const float4& a, const float4& x)
{
using numext::igamma;
return make_float4(
igamma(a.x, x.x),
igamma(a.y, x.y),
igamma(a.z, x.z),
igamma(a.w, x.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pigamma<double2>(const double2& a, const double2& x)
{
using numext::igamma;
return make_double2(igamma(a.x, x.x), igamma(a.y, x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pigamma_der_a<float4>(
const float4& a, const float4& x) {
using numext::igamma_der_a;
return make_float4(igamma_der_a(a.x, x.x), igamma_der_a(a.y, x.y),
igamma_der_a(a.z, x.z), igamma_der_a(a.w, x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pigamma_der_a<double2>(const double2& a, const double2& x) {
using numext::igamma_der_a;
return make_double2(igamma_der_a(a.x, x.x), igamma_der_a(a.y, x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pgamma_sample_der_alpha<float4>(
const float4& alpha, const float4& sample) {
using numext::gamma_sample_der_alpha;
return make_float4(
gamma_sample_der_alpha(alpha.x, sample.x),
gamma_sample_der_alpha(alpha.y, sample.y),
gamma_sample_der_alpha(alpha.z, sample.z),
gamma_sample_der_alpha(alpha.w, sample.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pgamma_sample_der_alpha<double2>(const double2& alpha, const double2& sample) {
using numext::gamma_sample_der_alpha;
return make_double2(
gamma_sample_der_alpha(alpha.x, sample.x),
gamma_sample_der_alpha(alpha.y, sample.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pigammac<float4>(const float4& a, const float4& x)
{
using numext::igammac;
return make_float4(
igammac(a.x, x.x),
igammac(a.y, x.y),
igammac(a.z, x.z),
igammac(a.w, x.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pigammac<double2>(const double2& a, const double2& x)
{
using numext::igammac;
return make_double2(igammac(a.x, x.x), igammac(a.y, x.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pbetainc<float4>(const float4& a, const float4& b, const float4& x)
{
using numext::betainc;
return make_float4(
betainc(a.x, b.x, x.x),
betainc(a.y, b.y, x.y),
betainc(a.z, b.z, x.z),
betainc(a.w, b.w, x.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pbetainc<double2>(const double2& a, const double2& b, const double2& x)
{
using numext::betainc;
return make_double2(betainc(a.x, b.x, x.x), betainc(a.y, b.y, x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i0e<float4>(const float4& x) {
using numext::bessel_i0e;
return make_float4(bessel_i0e(x.x), bessel_i0e(x.y), bessel_i0e(x.z), bessel_i0e(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_i0e<double2>(const double2& x) {
using numext::bessel_i0e;
return make_double2(bessel_i0e(x.x), bessel_i0e(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i0<float4>(const float4& x) {
using numext::bessel_i0;
return make_float4(bessel_i0(x.x), bessel_i0(x.y), bessel_i0(x.z), bessel_i0(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_i0<double2>(const double2& x) {
using numext::bessel_i0;
return make_double2(bessel_i0(x.x), bessel_i0(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i1e<float4>(const float4& x) {
using numext::bessel_i1e;
return make_float4(bessel_i1e(x.x), bessel_i1e(x.y), bessel_i1e(x.z), bessel_i1e(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_i1e<double2>(const double2& x) {
using numext::bessel_i1e;
return make_double2(bessel_i1e(x.x), bessel_i1e(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_i1<float4>(const float4& x) {
using numext::bessel_i1;
return make_float4(bessel_i1(x.x), bessel_i1(x.y), bessel_i1(x.z), bessel_i1(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_i1<double2>(const double2& x) {
using numext::bessel_i1;
return make_double2(bessel_i1(x.x), bessel_i1(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k0e<float4>(const float4& x) {
using numext::bessel_k0e;
return make_float4(bessel_k0e(x.x), bessel_k0e(x.y), bessel_k0e(x.z), bessel_k0e(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_k0e<double2>(const double2& x) {
using numext::bessel_k0e;
return make_double2(bessel_k0e(x.x), bessel_k0e(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k0<float4>(const float4& x) {
using numext::bessel_k0;
return make_float4(bessel_k0(x.x), bessel_k0(x.y), bessel_k0(x.z), bessel_k0(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_k0<double2>(const double2& x) {
using numext::bessel_k0;
return make_double2(bessel_k0(x.x), bessel_k0(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k1e<float4>(const float4& x) {
using numext::bessel_k1e;
return make_float4(bessel_k1e(x.x), bessel_k1e(x.y), bessel_k1e(x.z), bessel_k1e(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_k1e<double2>(const double2& x) {
using numext::bessel_k1e;
return make_double2(bessel_k1e(x.x), bessel_k1e(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_k1<float4>(const float4& x) {
using numext::bessel_k1;
return make_float4(bessel_k1(x.x), bessel_k1(x.y), bessel_k1(x.z), bessel_k1(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_k1<double2>(const double2& x) {
using numext::bessel_k1;
return make_double2(bessel_k1(x.x), bessel_k1(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_j0<float4>(const float4& x) {
using numext::bessel_j0;
return make_float4(bessel_j0(x.x), bessel_j0(x.y), bessel_j0(x.z), bessel_j0(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_j0<double2>(const double2& x) {
using numext::bessel_j0;
return make_double2(bessel_j0(x.x), bessel_j0(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_j1<float4>(const float4& x) {
using numext::bessel_j1;
return make_float4(bessel_j1(x.x), bessel_j1(x.y), bessel_j1(x.z), bessel_j1(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_j1<double2>(const double2& x) {
using numext::bessel_j1;
return make_double2(bessel_j1(x.x), bessel_j1(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_y0<float4>(const float4& x) {
using numext::bessel_y0;
return make_float4(bessel_y0(x.x), bessel_y0(x.y), bessel_y0(x.z), bessel_y0(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_y0<double2>(const double2& x) {
using numext::bessel_y0;
return make_double2(bessel_y0(x.x), bessel_y0(x.y));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pbessel_y1<float4>(const float4& x) {
using numext::bessel_y1;
return make_float4(bessel_y1(x.x), bessel_y1(x.y), bessel_y1(x.z), bessel_y1(x.w));
}
template <>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2
pbessel_y1<double2>(const double2& x) {
using numext::bessel_y1;
return make_double2(bessel_y1(x.x), bessel_y1(x.y));
}
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_GPU_SPECIALFUNCTIONS_H
| 10,864
| 28.364865
| 107
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/arch/NEON/BesselFunctions.h
|
#ifndef EIGEN_NEON_BESSELFUNCTIONS_H
#define EIGEN_NEON_BESSELFUNCTIONS_H
namespace Eigen {
namespace internal {
#if EIGEN_HAS_ARM64_FP16_VECTOR_ARITHMETIC
#define NEON_HALF_TO_FLOAT_FUNCTIONS(METHOD) \
template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \
Packet8hf METHOD<Packet8hf>(const Packet8hf& x) { \
const Packet4f lo = METHOD<Packet4f>(vcvt_f32_f16(vget_low_f16(x))); \
const Packet4f hi = METHOD<Packet4f>(vcvt_f32_f16(vget_high_f16(x))); \
return vcombine_f16(vcvt_f16_f32(lo), vcvt_f16_f32(hi)); \
} \
\
template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \
Packet4hf METHOD<Packet4hf>(const Packet4hf& x) { \
return vcvt_f16_f32(METHOD<Packet4f>(vcvt_f32_f16(x))); \
}
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i0)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i0e)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i1)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_i1e)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_j0)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_j1)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k0)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k0e)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k1)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_k1e)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_y0)
NEON_HALF_TO_FLOAT_FUNCTIONS(pbessel_y1)
#undef NEON_HALF_TO_FLOAT_FUNCTIONS
#endif
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i0)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i0e)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i1)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_i1e)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_j0)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_j1)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k0)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k0e)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k1)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_k1e)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_y0)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pbessel_y1)
} // namespace internal
} // namespace Eigen
#endif // EIGEN_NEON_BESSELFUNCTIONS_H
| 2,258
| 40.072727
| 73
|
h
|
null |
LRMI-main/unsupported/Eigen/src/SpecialFunctions/arch/NEON/SpecialFunctions.h
|
#ifndef EIGEN_NEON_SPECIALFUNCTIONS_H
#define EIGEN_NEON_SPECIALFUNCTIONS_H
namespace Eigen {
namespace internal {
#if EIGEN_HAS_ARM64_FP16_VECTOR_ARITHMETIC
#define NEON_HALF_TO_FLOAT_FUNCTIONS(METHOD) \
template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \
Packet8hf METHOD<Packet8hf>(const Packet8hf& x) { \
const Packet4f lo = METHOD<Packet4f>(vcvt_f32_f16(vget_low_f16(x))); \
const Packet4f hi = METHOD<Packet4f>(vcvt_f32_f16(vget_high_f16(x))); \
return vcombine_f16(vcvt_f16_f32(lo), vcvt_f16_f32(hi)); \
} \
\
template <> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE \
Packet4hf METHOD<Packet4hf>(const Packet4hf& x) { \
return vcvt_f16_f32(METHOD<Packet4f>(vcvt_f32_f16(x))); \
}
NEON_HALF_TO_FLOAT_FUNCTIONS(perf)
NEON_HALF_TO_FLOAT_FUNCTIONS(pndtri)
#undef NEON_HALF_TO_FLOAT_FUNCTIONS
#endif
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, perf)
BF16_PACKET_FUNCTION(Packet4f, Packet4bf, pndtri)
} // namespace internal
} // namespace Eigen
#endif // EIGEN_NEON_SPECIALFUNCTIONS_H
| 1,283
| 35.685714
| 73
|
h
|
zpdgen
|
zpdgen-master/ctest.c
|
#include <complex.h>
#include <stdio.h>
#include <stdlib.h>
#include "gpdf.h"
int main(int argc, char *argv[]){
unsigned long int t,tc;
complex res;
int lx,ly,l;
int n,m;
complex *F;
complex *za,om;
complex za_min, za_max, dza;
int numx,numy;
char buf[50];
int nms[]={1,0,1,2,3,0};
za_min=-6.0-6.0i;
za_max=6.0+6.0i;
dza=0.1+0.1i;
numx=creal(za_max-za_min)/creal(dza);
numy=cimag(za_max-za_min)/cimag(dza);
F=malloc(sizeof(complex)*numx*numy);
za=malloc(sizeof(complex)*numx*numy);
for(l=0;l<3;l++){
n=nms[l*2];
m=nms[l*2+1];
printf("computing I_%i%i...\n",n,m);
tc=clock();
for(lx=0;lx<numx;lx++){
for(ly=0;ly<numy;ly++){
za[lx*numy+ly]=za_min+creal(dza)*lx+I*cimag(dza)*ly;
F[lx*numy+ly]=gpdf_inm(za[lx*numy+ly],0.0,0.09,n,m);
}
}
printf("\n%lu msecs cpu time\n",clock()-tc);
}
exit(0);
}
| 873
| 22
| 53
|
c
|
zpdgen
|
zpdgen-master/gpdf_inmzpd.c
|
#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include "gpdf.h"
extern void inmzpd_(double*, double*, double*,double *, int*, int*, double*, double*, int*);
extern void epszpd_(double*, double*, double*, double*, double*, int*);
complex gpdf_inm(complex za, double zb, double bi, int n, int m){
complex res;
double zr=creal(za);
double zi=cimag(za);
double *cyr=malloc(sizeof(double)*1);
double *cyi=malloc(sizeof(double)*1);
int *flag=malloc(sizeof(int)*1);
inmzpd_(&zr,&zi, &zb, &bi, &n,&m, cyr,cyi,flag);
if(flag[0]!=0){
printf("error in inmzpd!\n");
printf("za=(%f,%f)\n",creal(za),cimag(za));
exit(-1);
}
res=cyr[0]+I*cyi[0];
free(cyr);
free(cyi);
return res;
}
complex gpdf_eps(complex om, gpdf_eps_pars *pars){
complex res;
double zr=creal(om);
double zi=cimag(om);
double *cyr=malloc(sizeof(double)*1);
double *cyi=malloc(sizeof(double)*1);
int *flag=malloc(sizeof(int)*1);
epszpd_(&zr,&zi, (double *) pars, cyr,cyi,flag);
if(flag[0]!=0){
printf("error in epszpd!\n");
printf("om=(%f,%f)\n",creal(om),cimag(om));
exit(-1);
}
res=cyr[0]+I*cyi[0];
free(cyr);
free(cyi);
return res;
}
| 1,183
| 24.73913
| 92
|
c
|
null |
fairseq-main/examples/operators/utils.h
|
/**
* Copyright 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <torch/extension.h> // @manual=//caffe2:torch_extension
#define CHECK_CUDA(x) \
TORCH_CHECK(x.type().is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) \
TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) \
CHECK_CUDA(x); \
CHECK_CONTIGUOUS(x)
| 528
| 25.45
| 64
|
h
|
null |
fairseq-main/fairseq/clib/libnat_cuda/edit_dist.h
|
/**
* Copyright 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <torch/extension.h>
torch::Tensor LevenshteinDistanceCuda(
torch::Tensor source,
torch::Tensor target,
torch::Tensor source_length,
torch::Tensor target_length);
torch::Tensor GenerateDeletionLabelCuda(
torch::Tensor source,
torch::Tensor operations);
std::pair<torch::Tensor, torch::Tensor> GenerateInsertionLabelCuda(
torch::Tensor source,
torch::Tensor operations);
| 627
| 23.153846
| 67
|
h
|
libgp
|
libgp-master/include/cov.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_H__
#define __COV_H__
#include <iostream>
#include <vector>
#include <Eigen/Dense>
namespace libgp
{
/** Covariance function base class.
* @author Manuel Blum
* @ingroup cov_group
* @todo implement more covariance functions */
class CovarianceFunction
{
public:
/** Constructor. */
CovarianceFunction() {};
/** Destructor. */
virtual ~CovarianceFunction() {};
/** Initialization method for atomic covariance functions.
* @param input_dim dimensionality of the input vectors */
virtual bool init(int input_dim)
{
return false;
};
/** Initialization method for compound covariance functions.
* @param input_dim dimensionality of the input vectors
* @param first first covariance function of compound
* @param second second covariance function of compound */
virtual bool init(int input_dim, CovarianceFunction * first, CovarianceFunction * second)
{
return false;
};
virtual bool init(int input_dim, int filter, CovarianceFunction * covf)
{
return false;
};
/** Computes the covariance of two input vectors.
* @param x1 first input vector
* @param x2 second input vector
* @return covariance of x1 and x2 */
virtual double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2) = 0;
/** Covariance gradient of two input vectors with respect to the hyperparameters.
* @param x1 first input vector
* @param x2 second input vector
* @param grad covariance gradient */
virtual void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad) = 0;
/** Update parameter vector.
* @param p new parameter vector */
virtual void set_loghyper(const Eigen::VectorXd &p);
/** Update parameter vector.
* @param p new parameter vector */
virtual void set_loghyper(const double p[]);
/** Get number of parameters for this covariance function.
* @return parameter vector dimensionality */
size_t get_param_dim();
/** Get input dimensionality.
* @return input dimensionality */
size_t get_input_dim();
/** Get log-hyperparameter of covariance function.
* @return log-hyperparameter */
Eigen::VectorXd get_loghyper();
/** Returns a string representation of this covariance function.
* @return string containing the name of this covariance function */
virtual std::string to_string() = 0;
/** Draw random target values from this covariance function for input X. */
Eigen::VectorXd draw_random_sample(Eigen::MatrixXd &X);
bool loghyper_changed;
protected:
/** Input dimensionality. */
size_t input_dim;
/** Size of parameter vector. */
size_t param_dim;
/** Parameter vector containing the log hyperparameters of the covariance function.
* The number of necessary parameters is given in param_dim. */
Eigen::VectorXd loghyper;
};
}
#endif /* __COV_H__ */
/** Covariance functions available for Gaussian process models.
* There are atomic and composite covariance functions.
* @defgroup cov_group Covariance Functions */
| 3,454
| 30.126126
| 105
|
h
|
libgp
|
libgp-master/include/cov_factory.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_FACTORY_H__
#define __COV_FACTORY_H__
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include "cov.h"
namespace libgp {
template <typename ClassName> CovarianceFunction * create_func()
{
return new ClassName();
}
/** Factory class for generating instances of CovarianceFunction.
* @author Manuel Blum */
class CovFactory
{
public:
CovFactory ();
virtual ~CovFactory ();
/** Create an instance of CovarianceFunction.
* @param input_dim input vector dimensionality
* @param key string representation of covariance function
* @return instance of CovarianceFunction */
libgp::CovarianceFunction* create(size_t input_dim, const std::string key);
/** Returns a string vector of available covariance functions. */
std::vector<std::string> list();
private:
typedef CovarianceFunction*(*create_func_def)();
std::map<std::string , CovFactory::create_func_def> registry;
};
}
#endif /* __COV_FACTORY_H__ */
| 1,195
| 24.446809
| 79
|
h
|
libgp
|
libgp-master/include/cov_linear_ard.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_LINEAR_ARD_H__
#define __COV_LINEAR_ARD_H__
#include "cov.h"
namespace libgp
{
/** Linear covariance function with automatic relevance detection.
* Parameters: \f$l_1^2, \dots, l_n^2\f$
* @ingroup cov_group
* @author Manuel Blum
*/
class CovLinearard : public CovarianceFunction
{
public:
CovLinearard ();
virtual ~CovLinearard ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
Eigen::VectorXd ell;
};
}
#endif /* __COV_LINEAR_ARD_H__ */
| 885
| 24.314286
| 91
|
h
|
libgp
|
libgp-master/include/cov_linear_one.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_LINEAR_ONE__
#define __COV_LINEAR_ONE__
#include "cov.h"
namespace libgp
{
/** Linear covariance function.
* Parameter: \f$\theta^2\f$
* @ingroup cov_group
* @author Manuel Blum
*/
class CovLinearone : public CovarianceFunction
{
public:
CovLinearone ();
virtual ~CovLinearone ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double it2;
};
}
#endif /* __COV_LINEAR_ONE__ */
| 823
| 22.542857
| 91
|
h
|
libgp
|
libgp-master/include/cov_matern3_iso.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_MATERN3_ISO_H__
#define __COV_MATERN3_ISO_H__
#include "cov.h"
namespace libgp
{
/** Matern covariance function with \f$\nu = \frac{3}{2}\f$ and isotropic distance measure.
* Parameters: \f$l^2, \sigma_f^2\f$
* @ingroup cov_group
* @author Manuel Blum
*/
class CovMatern3iso : public CovarianceFunction
{
public:
CovMatern3iso ();
virtual ~CovMatern3iso ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
double sqrt3;
};
}
#endif /* __COV_MATERN3_ISO_H__ */
| 934
| 24.972222
| 93
|
h
|
libgp
|
libgp-master/include/cov_matern5_iso.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_MATERN5_ISO_H__
#define __COV_MATERN5_ISO_H__
#include "cov.h"
namespace libgp
{
/** Matern covariance function with \f$\nu = \frac{5}{2}\f$ and isotropic distance measure.
* Parameter: \f$l^2, \sigma_f^2\f$
* @ingroup cov_group
* @author Manuel Blum
*/
class CovMatern5iso : public CovarianceFunction
{
public:
CovMatern5iso ();
virtual ~CovMatern5iso ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
double sqrt5;
};
}
#endif /* __COV_MATERN5_ISO_H__ */
| 933
| 24.944444
| 93
|
h
|
libgp
|
libgp-master/include/cov_noise.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_NOISE_H__
#define __COV_NOISE_H__
#include "cov.h"
namespace libgp
{
/** Independent covariance function (white noise).
* Parameters: signal noise, \f$\sigma^2\f$
* @author Manuel Blum
* @ingroup cov_group
*/
class CovNoise : public CovarianceFunction
{
public:
CovNoise ();
virtual ~CovNoise ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
virtual double get_threshold();
virtual void set_threshold(double threshold);
private:
double s2;
};
}
#endif /* __COV_NOISE_H__ */
| 922
| 23.945946
| 91
|
h
|
libgp
|
libgp-master/include/cov_periodic.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_PERIODIC_H__
#define __COV_PERIODIC_H__
#include "cov.h"
namespace libgp
{
class CovPeriodic : public CovarianceFunction
{
public:
CovPeriodic ();
virtual ~CovPeriodic ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
double T;
};
}
#endif
| 699
| 21.580645
| 91
|
h
|
libgp
|
libgp-master/include/cov_periodic_matern3_iso.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_PERIODIC_MATERN3_ISO_H__
#define __COV_PERIODIC_MATERN3_ISO_H__
#include "cov.h"
namespace libgp
{
class CovPeriodicMatern3iso : public CovarianceFunction
{
public:
CovPeriodicMatern3iso ();
virtual ~CovPeriodicMatern3iso ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
double sqrt3;
double T;
};
}
#endif
| 771
| 23.125
| 91
|
h
|
libgp
|
libgp-master/include/cov_prod.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_PROD_H__
#define __COV_PROD_H__
#include "cov.h"
namespace libgp
{
/** Sums of covariance functions.
* @author Manuel Blum
* @ingroup cov_group */
class CovProd : public CovarianceFunction
{
public:
CovProd ();
virtual ~CovProd ();
bool init(int n, CovarianceFunction * first, CovarianceFunction * second);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
size_t param_dim_first;
size_t param_dim_second;
CovarianceFunction * first;
CovarianceFunction * second;
};
}
#endif /* __COV_PROD_H__ */
| 924
| 25.428571
| 91
|
h
|
libgp
|
libgp-master/include/cov_rq_iso.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_RQ_ISO_H__
#define __COV_RQ_ISO_H__
#include "cov.h"
namespace libgp
{
/** Isotropic rational quadratic covariance function.
* Parameters: \f$l^2, \sigma_f^2, \alpha\f$
* @ingroup cov_group
* @author Manuel Blum
*/
class CovRQiso : public CovarianceFunction
{
public:
CovRQiso ();
virtual ~CovRQiso ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
double alpha;
};
}
#endif /* __COV_RQ_ISO_H__ */
| 874
| 23.305556
| 91
|
h
|
libgp
|
libgp-master/include/cov_se_ard.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_SE_ARD_H__
#define __COV_SE_ARD_H__
#include "cov.h"
namespace libgp
{
/** Squared exponential covariance function with automatic relevance detection.
* Computes the squared exponential covariance
* \f$k_{SE}(x, y) := \alpha^2 \exp(-\frac{1}{2}(x-y)^T\Lambda^{-1}(x-y))\f$,
* with \f$\Lambda = diag(l_1^2, \dots, l_n^2)\f$ being the characteristic
* length scales and \f$\alpha\f$ describing the variability of the latent
* function. The parameters \f$l_1^2, \dots, l_n^2, \alpha\f$ are expected
* in this order in the parameter array.
* @ingroup cov_group
* @author Manuel Blum
*/
class CovSEard : public CovarianceFunction
{
public:
CovSEard ();
virtual ~CovSEard ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
Eigen::VectorXd ell;
double sf2;
};
}
#endif /* __COV_SE_ARD_H__ */
| 1,256
| 28.928571
| 91
|
h
|
libgp
|
libgp-master/include/cov_se_iso.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_SE_ISO_H__
#define __COV_SE_ISO_H__
#include "cov.h"
namespace libgp
{
/** Squared exponential covariance function with isotropic distance measure.
* Computes the squared exponential covariance
* \f$k_{SE}(x, y) := \alpha^2 \exp(-\frac{1}{2}(x-y)^T\Lambda^{-1}(x-y))\f$,
* with \f$\Lambda = diag(l^2, \dots, l^2)\f$ being the characteristic
* length scale and \f$\alpha\f$ describing the variability of the latent
* function (signal variance). The parameters \f$l^2, \alpha\f$ are expected
* in this order in the parameter array.
* @ingroup cov_group
* @author Manuel Blum
*/
class CovSEiso : public CovarianceFunction
{
public:
CovSEiso ();
virtual ~CovSEiso ();
bool init(int n);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
double ell;
double sf2;
};
}
#endif /* __COV_SE_ISO_H__ */
| 1,240
| 29.268293
| 91
|
h
|
libgp
|
libgp-master/include/cov_sum.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_SUM_H__
#define __COV_SUM_H__
#include "cov.h"
namespace libgp
{
/** Sums of covariance functions.
* @author Manuel Blum
* @ingroup cov_group */
class CovSum : public CovarianceFunction
{
public:
CovSum ();
virtual ~CovSum ();
bool init(int n, CovarianceFunction * first, CovarianceFunction * second);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
size_t param_dim_first;
size_t param_dim_second;
CovarianceFunction * first;
CovarianceFunction * second;
};
}
#endif /* __COV_SUM_H__ */
| 918
| 25.257143
| 91
|
h
|
libgp
|
libgp-master/include/gp.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
/*!
*
* \page licence Licensing
*
* libgp - Gaussian process library for Machine Learning
*
* \verbinclude "../COPYING"
*/
#ifndef __GP_H__
#define __GP_H__
#define _USE_MATH_DEFINES
#include <cmath>
#include <Eigen/Dense>
#include "cov.h"
#include "sampleset.h"
namespace libgp {
/** Gaussian process regression.
* @author Manuel Blum */
class GaussianProcess
{
public:
/** Empty initialization */
GaussianProcess ();
/** Create and instance of GaussianProcess with given input dimensionality
* and covariance function. */
GaussianProcess (size_t input_dim, std::string covf_def);
/** Create and instance of GaussianProcess from file. */
GaussianProcess (const char * filename);
/** Copy constructor */
GaussianProcess (const GaussianProcess& gp);
virtual ~GaussianProcess ();
/** Write current gp model to file. */
void write(const char * filename);
/** Predict target value for given input.
* @param x input vector
* @return predicted value */
virtual double f(const double x[]);
/** Predict variance of prediction for given input.
* @param x input vector
* @return predicted variance */
virtual double var(const double x[]);
/** Add input-output-pair to sample set.
* Add a copy of the given input-output-pair to sample set.
* @param x input array
* @param y output value
*/
void add_pattern(const double x[], double y);
bool set_y(size_t i, double y);
/** Get number of samples in the training set. */
size_t get_sampleset_size();
/** Clear sample set and free memory. */
void clear_sampleset();
/** Get reference on currently used covariance function. */
CovarianceFunction & covf();
/** Get input vector dimensionality. */
size_t get_input_dim();
double log_likelihood();
Eigen::VectorXd log_likelihood_gradient();
protected:
/** The covariance function of this Gaussian process. */
CovarianceFunction * cf;
/** The training sample set. */
SampleSet * sampleset;
/** Alpha is cached for performance. */
Eigen::VectorXd alpha;
/** Last test kernel vector. */
Eigen::VectorXd k_star;
/** Linear solver used to invert the covariance matrix. */
// Eigen::LLT<Eigen::MatrixXd> solver;
Eigen::MatrixXd L;
/** Input vector dimensionality. */
size_t input_dim;
/** Update test input and cache kernel vector. */
void update_k_star(const Eigen::VectorXd &x_star);
void update_alpha();
/** Compute covariance matrix and perform cholesky decomposition. */
virtual void compute();
bool alpha_needs_update;
private:
/** No assignement */
GaussianProcess& operator=(const GaussianProcess&);
};
}
#endif /* __GP_H__ */
| 3,070
| 23.373016
| 79
|
h
|
libgp
|
libgp-master/include/gp_sparse.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2011, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __GP_SPARSE_H__
#define __GP_SPARSE_H__
#include <Eigen/Sparse>
#include <Eigen/SparseCholesky>
#include "gp.h"
namespace libgp {
/** Sparse Gaussian process regression.
* @author Manuel Blum */
class SparseGaussianProcess : public GaussianProcess
{
public:
/** Create an instance of SparseGaussianProcess with given input dimensionality and covariance function. */
SparseGaussianProcess (size_t input_dim, std::string covf_def);
/** Create an instance of SparseGaussianProcess from file. */
SparseGaussianProcess (const char * filename);
virtual ~SparseGaussianProcess ();
virtual void compute();
protected:
};
}
#endif /* __GP_SPARSE_H__ */
| 876
| 22.702703
| 111
|
h
|
libgp
|
libgp-master/include/gp_utils.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __GP_UTILS_H__
#define __GP_UTILS_H__
#include <cstdlib>
#include <cmath>
#include <cassert>
namespace libgp {
/** Various auxiliary functions. */
class Utils {
public:
/** Generate independent standard normally distributed (zero mean,
* unit variance) random numbers using the Box–Muller transform. */
static double randn();
/** Generate random permutation of array 0, ..., n-1 using
* Fisher–Yates shuffle algorithm. */
static int * randperm(int n);
/** Pseudorandom integers from a uniform discrete distribution.
* Returns a random integer drawn from the discrete uniform
* distribution on 0, ..., n-1. */
static size_t randi(size_t n);
/** Double precision numerical approximation to the standard normal
* cumulative distribution function. The cumulative standard normal
* integral is the function:
* \f$ cdf\_norm(x)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{x}
* \exp{\frac{-x^2}{2}}dx \f$ */
static double cdf_norm (double x);
/** Computes values of first Friedman dataset from 10-D input.
* \f$ f(\mathbf{x}) = 10\sin(\pi x_1 x_2) + 20(x_3 -0.5)^2 + 10x_4+5x_5 \f$ */
static double friedman (double x[]);
/** Hill function.
* \f$ f(\mathbf{x}) = \sin(x-y)+0.2y^3 + \cos(xy - 0.5y) \f$ */
static double hill(double x, double y);
/** Sign function.
*/
static double sign(double x);
// drand48() is not aviable under win
#if defined(WIN32) || defined(WIN64)
inline double drand48()
{
return (rand() / (RAND_MAX + 1.0));
}
#endif
};
}
#endif /* __GP_UTILS_H__ */
| 1,825
| 28.934426
| 84
|
h
|
libgp
|
libgp-master/include/input_dim_filter.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __COV_INPUT_DIM_FILTER__
#define __COV_INPUT_DIM_FILTER__
#include "cov.h"
namespace libgp
{
/** Linear covariance function.
* @ingroup cov_group
* @author Manuel Blum
*/
class InputDimFilter : public CovarianceFunction
{
public:
InputDimFilter ();
virtual ~InputDimFilter ();
bool init(int input_dim, int filter, CovarianceFunction * covf);
double get(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2);
void grad(const Eigen::VectorXd &x1, const Eigen::VectorXd &x2, Eigen::VectorXd &grad);
void set_loghyper(const Eigen::VectorXd &p);
virtual std::string to_string();
private:
int filter;
CovarianceFunction *nested;
};
}
#endif /* __COV_LINEAR_ONE__ */
| 888
| 24.4
| 91
|
h
|
libgp
|
libgp-master/include/sampleset.h
|
// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.
#ifndef __SAMPLESET_H__
#define __SAMPLESET_H__
#include <Eigen/Dense>
#include <vector>
namespace libgp {
/** Container holding training patterns.
* @author Manuel Blum */
class SampleSet
{
public:
/** Constructor.
* @param input_dim dimensionality of input vectors */
SampleSet (int input_dim);
/** Copy constructor */
SampleSet ( const SampleSet& ss );
/** Destructor. */
virtual ~SampleSet();
/** Add input-output pattern to sample set.
* @param x input array
* @param y target value */
void add(const double x[], double y);
void add(const Eigen::VectorXd x, double y);
/** Get input vector at index k. */
const Eigen::VectorXd & x (size_t k);
/** Get target value at index k. */
double y (size_t k);
/** Set target value at index i. */
bool set_y(size_t i, double y);
/** Get reference to vector of target values. */
const std::vector<double>& y();
/** Get number of samples. */
size_t size();
/** Clear sample set. */
void clear();
/** Check if sample set is empty. */
bool empty ();
private:
/** Container holding input vectors. */
std::vector<Eigen::VectorXd *> inputs;
/** Container holding target values. */
std::vector<double> targets;
/** Dimensionality of input vectors. */
size_t input_dim;
/** Number of samples. */
size_t n;
};
}
#endif /* __SAMPLESET_H__ */
| 1,643
| 21.520548
| 69
|
h
|
sent2vec
|
sent2vec-master/src/dictionary.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_DICTIONARY_H
#define FASTTEXT_DICTIONARY_H
#include <vector>
#include <string>
#include <istream>
#include <ostream>
#include <random>
#include <memory>
#include <unordered_map>
#include "args.h"
#include "real.h"
namespace fasttext {
typedef int32_t id_type;
enum class entry_type : int8_t {word=0, label=1};
struct entry {
std::string word;
int64_t count;
entry_type type;
std::vector<int32_t> subwords;
};
class Dictionary {
private:
static const int32_t MAX_VOCAB_SIZE = 30000000;
static const int32_t MAX_LINE_SIZE = 1024;
int32_t find(const std::string&) const;
void initTableDiscard();
void initNgrams();
std::shared_ptr<Args> args_;
std::vector<int32_t> word2int_;
std::vector<entry> words_;
std::vector<real> pdiscard_;
int32_t size_;
int32_t nwords_;
int32_t nlabels_;
int64_t ntokens_;
int64_t pruneidx_size_ = -1;
std::unordered_map<int32_t, int32_t> pruneidx_;
void addNgrams(
std::vector<int32_t>& line,
const std::vector<int32_t>& hashes,
int32_t n) const;
public:
static const std::string EOS;
static const std::string BOW;
static const std::string EOW;
explicit Dictionary(std::shared_ptr<Args>);
int32_t nwords() const;
int32_t nlabels() const;
int64_t ntokens() const;
real getPDiscard(int32_t) const;
int32_t getId(const std::string&) const;
int64_t getTokenCount(int32_t) const;
entry_type getType(int32_t) const;
entry_type getType(const std::string&) const;
bool discard(int32_t, real) const;
std::string getWord(int32_t) const;
const std::vector<int32_t>& getNgrams(int32_t) const;
const std::vector<int32_t> getNgrams(const std::string&) const;
void getNgrams(const std::string&, std::vector<int32_t>&,
std::vector<std::string>&) const;
void computeNgrams(const std::string&, std::vector<int32_t>&) const;
void computeNgrams(const std::string&, std::vector<int32_t>&,
std::vector<std::string>&) const;
uint32_t hash(const std::string& str) const;
void add(const std::string&);
bool readWord(std::istream&, std::string&) const;
void readFromFile(std::istream&);
std::string getLabel(int32_t) const;
void save(std::ostream&) const;
void load(std::istream&);
std::vector<int64_t> getCounts(entry_type) const;
std::vector<std::string> getVocab() const;
void addNgrams(std::vector<int32_t>&, int32_t, int32_t, std::minstd_rand&) const;
void addNgrams(std::vector<int32_t>&, std::vector<int32_t>&e, int32_t, int32_t, int32_t, int32_t, std::minstd_rand&);
void addNgrams(std::vector<int32_t>&, int32_t) const;
int32_t getLine(std::istream&, std::vector<int32_t>&, std::vector<int32_t>&,
std::vector<int32_t>&, std::minstd_rand&) const;
int32_t getLine(std::istream&, std::vector<int32_t>&,
std::vector<int32_t>&, std::minstd_rand&) const;
void threshold(int64_t, int64_t);
void truncate(int64_t);
void prune(std::vector<int32_t>&);
void convertNgrams(std::vector<int32_t>&);
};
}
#endif
| 3,477
| 30.618182
| 121
|
h
|
sent2vec
|
sent2vec-master/src/fasttext.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_FASTTEXT_H
#define FASTTEXT_FASTTEXT_H
#define FASTTEXT_VERSION 11 /* Version 1a */
#define FASTTEXT_FILEFORMAT_MAGIC_INT32 793712314
#include <time.h>
#include <atomic>
#include <memory>
#include <set>
#include "args.h"
#include "dictionary.h"
#include "matrix.h"
#include "qmatrix.h"
#include "model.h"
#include "real.h"
#include "utils.h"
#include "vector.h"
namespace fasttext {
class FastText {
private:
std::shared_ptr<Args> args_;
std::shared_ptr<Dictionary> dict_;
std::shared_ptr<Matrix> input_;
std::shared_ptr<Matrix> output_;
std::shared_ptr<QMatrix> qinput_;
std::shared_ptr<QMatrix> qoutput_;
std::shared_ptr<Model> model_;
std::atomic<int64_t> tokenCount;
clock_t start;
void signModel(std::ostream&);
bool checkModel(std::istream&);
bool quant_;
public:
FastText();
void getVector(Vector&, const std::string&) const;
void getVector(Vector&, int32_t) const;
void saveVectors();
void saveOutput();
void saveModel();
void saveModel(int32_t);
void saveDict();
void loadModel(const std::string&, const bool inference_mode = false, const bool shared_mem_enabled = true,
const int timeout_sec = -1);
void loadModel(std::istream&, bool load_output_matrix = true);
void loadModelWithSharedMemory(std::istream&, const std::string&, const int);
void loadDict(const std::string&);
void loadDict(std::istream&);
void printInfo(real, real);
void supervised(Model&, real, const std::vector<int32_t>&,
const std::vector<int32_t>&);
void cbow(Model&, real, const std::vector<int32_t>&);
void sent2vec(Model&, real, const std::vector<int32_t>&);
void cbowCWNgrams(Model&, real, std::vector<int32_t>&);
void skipgram(Model&, real, const std::vector<int32_t>&);
std::vector<int32_t> selectEmbeddings(int32_t) const;
void quantize(std::shared_ptr<Args>);
void test(std::istream&, int32_t);
void predict(std::istream&, int32_t, bool);
void predict(std::istream&, int32_t, std::vector<std::pair<real,std::string>>&) const;
void wordVectors();
void sentenceVectors();
void ngramVectors(std::string);
void textVectors();
void textVectorThread(int, std::shared_ptr<std::vector<std::string>>, std::shared_ptr<Matrix>, int);
void textVectors(std::vector<std::string>&, int, std::vector<real>&);
void textVector(std::string, Vector&, std::vector<int32_t>&, std::vector<int32_t>&);
void printWordVectors();
void printVocabularyVectors(bool);
void printSentenceVectors();
std::vector<std::string> getVocab();
std::vector<int64_t> getUnigramsCounts();
void trainThread(int32_t);
void savedDictTrain(std::shared_ptr<Args>);
void trainDict(std::shared_ptr<Args>);
void train(std::shared_ptr<Args>);
void precomputeWordVectors(Matrix&);
void precomputeSentenceVectors(Matrix&,std::ifstream&);
void findNN(const Matrix&, const Vector&, int32_t,
const std::set<std::string>&);
void findNNSent(const Matrix&, const Vector&, int32_t,
const std::set<std::string>&, int64_t, const std::vector<std::string>&);
void nn(int32_t);
void analogies(int32_t);
void nnSent(int32_t, std::string );
void analogiesSent(int32_t, std::string );
void loadVectors(std::string);
int getDimension() const;
};
}
#endif
| 3,746
| 30.225
| 111
|
h
|
sent2vec
|
sent2vec-master/src/matrix.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_MATRIX_H
#define FASTTEXT_MATRIX_H
#include <cstdint>
#include <istream>
#include <ostream>
#include "real.h"
namespace fasttext {
class Vector;
class Matrix {
public:
real* data_;
int64_t m_;
int64_t n_;
Matrix();
Matrix(int64_t, int64_t);
Matrix(const Matrix&);
Matrix& operator=(const Matrix&);
~Matrix();
inline const real& at(int64_t i, int64_t j) const {return data_[i * n_ + j];};
inline real& at(int64_t i, int64_t j) {return data_[i * n_ + j];};
void zero();
void uniform(real);
real dotRow(const Vector&, int64_t) const;
void addRow(const Vector&, int64_t, real);
void multiplyRow(const Vector& nums, int64_t ib = 0, int64_t ie = -1);
void divideRow(const Vector& denoms, int64_t ib = 0, int64_t ie = -1);
real l2NormRow(int64_t i) const;
void l2NormRow(Vector& norms) const;
void save(std::ostream&);
void load(std::istream&);
};
}
#endif
| 1,274
| 20.982759
| 82
|
h
|
sent2vec
|
sent2vec-master/src/model.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_MODEL_H
#define FASTTEXT_MODEL_H
#include <vector>
#include <random>
#include <utility>
#include <memory>
#include "args.h"
#include "matrix.h"
#include "vector.h"
#include "qmatrix.h"
#include "real.h"
#define SIGMOID_TABLE_SIZE 512
#define MAX_SIGMOID 8
#define LOG_TABLE_SIZE 512
namespace fasttext {
struct Node {
int32_t parent;
int32_t left;
int32_t right;
int64_t count;
bool binary;
};
class Model {
private:
std::shared_ptr<Matrix> wi_;
std::shared_ptr<Matrix> wo_;
std::shared_ptr<QMatrix> qwi_;
std::shared_ptr<QMatrix> qwo_;
std::shared_ptr<Args> args_;
Vector hidden_;
Vector output_;
Vector grad_;
int32_t hsz_;
int32_t isz_;
int32_t osz_;
real loss_;
int64_t nexamples_;
real* t_sigmoid;
real* t_log;
// used for negative sampling:
std::vector<int32_t> negatives;
size_t negpos;
// used for hierarchical softmax:
std::vector< std::vector<int32_t> > paths;
std::vector< std::vector<bool> > codes;
std::vector<Node> tree;
static bool comparePairs(const std::pair<real, int32_t>&,
const std::pair<real, int32_t>&);
int32_t getNegative(int32_t target);
void initSigmoid();
void initLog();
static const int32_t NEGATIVE_TABLE_SIZE = 10000000;
public:
Model(std::shared_ptr<Matrix>, std::shared_ptr<Matrix>,
std::shared_ptr<Args>, int32_t);
~Model();
real binaryLogistic(int32_t, bool, real);
real negativeSampling(int32_t, real);
real hierarchicalSoftmax(int32_t, real);
real softmax(int32_t, real);
void predict(const std::vector<int32_t>&, int32_t,
std::vector<std::pair<real, int32_t>>&,
Vector&, Vector&) const;
void predict(const std::vector<int32_t>&, int32_t,
std::vector<std::pair<real, int32_t>>&);
void dfs(int32_t, int32_t, real,
std::vector<std::pair<real, int32_t>>&,
Vector&) const;
void findKBest(int32_t, std::vector<std::pair<real, int32_t>>&,
Vector&, Vector&) const;
void update(const std::vector<int32_t>&, int32_t, real);
void update(const std::vector<int32_t>&, int32_t, real, real, int32_t, int32_t);
void computeHidden(const std::vector<int32_t>&, Vector&) const;
void computeOutputSoftmax(Vector&, Vector&) const;
void computeOutputSoftmax();
void setTargetCounts(const std::vector<int64_t>&);
void initTableNegatives(const std::vector<int64_t>&);
void buildTree(const std::vector<int64_t>&);
real getLoss() const;
real sigmoid(real) const;
real log(real) const;
std::minstd_rand rng;
bool quant_;
void setQuantizePointer(std::shared_ptr<QMatrix>, std::shared_ptr<QMatrix>, bool);
};
}
#endif
| 3,124
| 26.654867
| 86
|
h
|
sent2vec
|
sent2vec-master/src/productquantizer.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_PRODUCT_QUANTIZER_H
#define FASTTEXT_PRODUCT_QUANTIZER_H
#include <cstring>
#include <istream>
#include <ostream>
#include <vector>
#include <random>
#include "real.h"
#include "vector.h"
namespace fasttext {
class ProductQuantizer {
private:
const int32_t nbits_ = 8;
const int32_t ksub_ = 1 << nbits_;
const int32_t max_points_per_cluster_ = 256;
const int32_t max_points_ = max_points_per_cluster_ * ksub_;
const int32_t seed_ = 1234;
const int32_t niter_ = 25;
const real eps_ = 1e-7;
int32_t dim_;
int32_t nsubq_;
int32_t dsub_;
int32_t lastdsub_;
std::vector<real> centroids_;
std::minstd_rand rng;
public:
ProductQuantizer() {}
ProductQuantizer(int32_t, int32_t);
real* get_centroids (int32_t, uint8_t);
const real* get_centroids(int32_t, uint8_t) const;
real assign_centroid(const real*, const real*, uint8_t*, int32_t) const;
void Estep(const real*, const real*, uint8_t*, int32_t, int32_t) const;
void MStep(const real*, real*, const uint8_t*, int32_t, int32_t);
void kmeans(const real*, real*, int32_t, int32_t);
void train(int, const real*);
real mulcode(const Vector&, const uint8_t*, int32_t, real) const;
void addcode(Vector&, const uint8_t*, int32_t, real) const;
void compute_code(const real*, uint8_t*) const;
void compute_codes(const real*, uint8_t*, int32_t) const;
void save(std::ostream&);
void load(std::istream&);
};
}
#endif
| 1,809
| 25.617647
| 78
|
h
|
sent2vec
|
sent2vec-master/src/shmem_matrix.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_SHMEM_MATRIX_H
#define FASTTEXT_SHMEM_MATRIX_H
#include <cstdint>
#include <istream>
#include <memory>
#include <ostream>
#include <string>
#include "matrix.h"
#include "real.h"
namespace fasttext {
class ShmemMatrix : public Matrix {
public:
ShmemMatrix(const char*, const int64_t, const int64_t, const int);
~ShmemMatrix();
Matrix& operator=(const Matrix&) = delete;
void save(std::ostream&) = delete;
void load(std::istream&) = delete;
static std::shared_ptr<ShmemMatrix> load(std::istream&, const std::string&, const int);
};
}
#endif
| 900
| 22.102564
| 91
|
h
|
sent2vec
|
sent2vec-master/src/vector.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FASTTEXT_VECTOR_H
#define FASTTEXT_VECTOR_H
#include <cstdint>
#include <ostream>
#include "real.h"
namespace fasttext {
class Matrix;
class QMatrix;
class Vector {
public:
int64_t m_;
real* data_;
explicit Vector(int64_t);
~Vector();
real& operator[](int64_t);
const real& operator[](int64_t) const;
int64_t size() const;
void zero();
void mul(real);
real norm() const;
void addVector(const Vector& source);
void addVector(const Vector&, real);
void addRow(const Matrix&, int64_t);
void addRow(const QMatrix&, int64_t);
void addRow(const Matrix&, int64_t, real);
void mul(const QMatrix&, const Vector&);
void mul(const Matrix&, const Vector&);
int64_t argmax();
};
std::ostream& operator<<(std::ostream&, const Vector&);
}
#endif
| 1,135
| 20.037037
| 78
|
h
|
null |
Detectron-main/detectron/ops/zero_even_op.h
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ZERO_EVEN_OP_H_
#define ZERO_EVEN_OP_H_
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
namespace caffe2 {
/**
* ZeroEven operator. Zeros elements at even indices of an 1D array.
* Elements at odd indices are preserved.
*
* This toy operator is an example of a custom operator and may be a useful
* reference for adding new custom operators to the Detectron codebase.
*/
template <typename T, class Context>
class ZeroEvenOp final : public Operator<Context> {
public:
// Introduce Operator<Context> helper members.
USE_OPERATOR_CONTEXT_FUNCTIONS;
ZeroEvenOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws) {}
bool RunOnDevice() override;
};
} // namespace caffe2
#endif // ZERO_EVEN_OP_H_
| 1,395
| 28.702128
| 75
|
h
|
tensor2tensor
|
tensor2tensor-master/tensor2tensor/data_generators/ops/subword_text_encoder.h
|
#ifndef TENSOR2TESNOR_DATA_GENERATORS_OPS_SUBWORD_TEXT_ENCODER_H_
#define TENSOR2TESNOR_DATA_GENERATORS_OPS_SUBWORD_TEXT_ENCODER_H_
#include "third_party/absl/container/flat_hash_map.h"
#include "third_party/absl/container/flat_hash_set.h"
#include "third_party/absl/strings/string_view.h"
#include "third_party/icu/include/unicode/uchar.h"
#include "third_party/tensorflow/core/framework/tensor.h"
namespace tensor2tensor {
// A subword text encoder with built in tokenizer.
//
// Equivalent to tensor2tensor's subword text
// https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/text_encoder.py,
// This code (or a suitable replacement) should eventually move into tfds
// and should be deleted from tensor2tensor.
class SubwordTextEncoder {
public:
explicit SubwordTextEncoder(const std::string& vocab_filename);
virtual ~SubwordTextEncoder() {}
// Breaks up input text into subtokens.
void Encode(absl::string_view text, std::vector<int>* ids);
private:
// Given a full token as input, breaks the token up into subtokens and appends
// corresponding IDs to the ids vector.
void EncodeSubtokens(absl::string_view token, std::vector<int>* ids);
// Escapes a token so unencodable characters are replaced by escape sequences.
std::string EscapeToken(absl::string_view token);
// Maps subword tokens to IDs.
absl::flat_hash_map<std::string, int64> vocab_;
// A set containing all valid unicode code points that can be encoded without
// being escaped.
absl::flat_hash_set<UChar32> alphabet_;
};
} // namespace tensor2tensor
#endif // TENSOR2TESNOR_DATA_GENERATORS_OPS_SUBWORD_TEXT_ENCODER_H_
| 1,668
| 36.088889
| 105
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/algorithms.h
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
/** @defgroup c_api cuGraph C API
* @{
*/
#include <cugraph_c/centrality_algorithms.h>
#include <cugraph_c/community_algorithms.h>
#include <cugraph_c/core_algorithms.h>
#include <cugraph_c/labeling_algorithms.h>
#include <cugraph_c/sampling_algorithms.h>
#include <cugraph_c/similarity_algorithms.h>
#include <cugraph_c/traversal_algorithms.h>
/**
* @}
*/
| 1,091
| 27.736842
| 75
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/array.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/array.h
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int32_t align_;
} cugraph_type_erased_device_array_t;
typedef struct {
int32_t align_;
} cugraph_type_erased_device_array_view_t;
typedef struct {
int32_t align_;
} cugraph_type_erased_host_array_t;
typedef struct {
int32_t align_;
} cugraph_type_erased_host_array_view_t;
/**
* @brief Create a type erased device array
*
* @param [in] handle Handle for accessing resources
* @param [in] n_elems The number of elements in the array
* @param [in] dtype The type of array to create
* @param [out] array Pointer to the location to store the pointer to the device array
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_create(
const cugraph_resource_handle_t* handle,
size_t n_elems,
cugraph_data_type_id_t dtype,
cugraph_type_erased_device_array_t** array,
cugraph_error_t** error);
/**
* @brief Create a type erased device array from a view
*
* Copies the data from the view into the new device array
*
* @param [in] handle Handle for accessing resources
* @param [in] view Type erased device array view to copy from
* @param [out] array Pointer to the location to store the pointer to the device array
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_create_from_view(
const cugraph_resource_handle_t* handle,
const cugraph_type_erased_device_array_view_t* view,
cugraph_type_erased_device_array_t** array,
cugraph_error_t** error);
/**
* @brief Destroy a type erased device array
*
* @param [in] p Pointer to the type erased device array
*/
void cugraph_type_erased_device_array_free(cugraph_type_erased_device_array_t* p);
#if 0
// FIXME: Not implemented, need to discuss if this can work. We will either implement
// this later or delete it from the interface once we resolve how to handle this
/**
* @brief Release the raw pointer of the type erased device array
*
* The caller is now responsible for freeing the device pointer
*
* @param [in] p Pointer to the type erased device array
* @return Pointer (device memory) for the data in the array
*/
void* cugraph_type_erased_device_array_release(cugraph_type_erased_device_array_t* p);
#endif
/**
* @brief Create a type erased device array view from
* a type erased device array
*
* @param [in] array Pointer to the type erased device array
* @return Pointer to the view of the host array
*/
cugraph_type_erased_device_array_view_t* cugraph_type_erased_device_array_view(
cugraph_type_erased_device_array_t* array);
/**
* @brief Create a type erased device array view with a different type
*
* Create a type erased device array view from
* a type erased device array treating the underlying
* pointer as a different type.
*
* Note: This is only viable when the underlying types are the same size. That
* is, you can switch between INT32 and FLOAT32, or between INT64 and FLOAT64.
* But if the types are different sizes this will be an error.
*
* @param [in] array Pointer to the type erased device array
* @param [in] dtype The type to cast the pointer to
* @param [out] result_view Address where to put the allocated device view
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_view_as_type(
cugraph_type_erased_device_array_t* array,
cugraph_data_type_id_t dtype,
cugraph_type_erased_device_array_view_t** result_view,
cugraph_error_t** error);
/**
* @brief Create a type erased device array view from
* a raw device pointer.
*
* @param [in] pointer Raw device pointer
* @param [in] n_elems The number of elements in the array
* @param [in] dtype The type of array to create
* @return Pointer to the view of the host array
*/
cugraph_type_erased_device_array_view_t* cugraph_type_erased_device_array_view_create(
void* pointer, size_t n_elems, cugraph_data_type_id_t dtype);
/**
* @brief Destroy a type erased device array view
*
* @param [in] p Pointer to the type erased device array view
*/
void cugraph_type_erased_device_array_view_free(cugraph_type_erased_device_array_view_t* p);
/**
* @brief Get the size of a type erased device array view
*
* @param [in] p Pointer to the type erased device array view
* @return The number of elements in the array
*/
size_t cugraph_type_erased_device_array_view_size(const cugraph_type_erased_device_array_view_t* p);
/**
* @brief Get the type of a type erased device array view
*
* @param [in] p Pointer to the type erased device array view
* @return The type of the elements in the array
*/
cugraph_data_type_id_t cugraph_type_erased_device_array_view_type(
const cugraph_type_erased_device_array_view_t* p);
/**
* @brief Get the raw pointer of the type erased device array view
*
* @param [in] p Pointer to the type erased device array view
* @return Pointer (device memory) for the data in the array
*/
const void* cugraph_type_erased_device_array_view_pointer(
const cugraph_type_erased_device_array_view_t* p);
/**
* @brief Create a type erased host array
*
* @param [in] handle Handle for accessing resources
* @param [in] n_elems The number of elements in the array
* @param [in] dtype The type of array to create
* @param [out] array Pointer to the location to store the pointer to the host array
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_host_array_create(const cugraph_resource_handle_t* handle,
size_t n_elems,
cugraph_data_type_id_t dtype,
cugraph_type_erased_host_array_t** array,
cugraph_error_t** error);
/**
* @brief Destroy a type erased host array
*
* @param [in] p Pointer to the type erased host array
*/
void cugraph_type_erased_host_array_free(cugraph_type_erased_host_array_t* p);
#if 0
// FIXME: Not implemented, need to discuss if this can work. We will either implement
// this later or delete it from the interface once we resolve how to handle this
/**
* @brief Release the raw pointer of the type erased host array
*
* The caller is now responsible for freeing the host pointer
*
* @param [in] p Pointer to the type erased host array
* @return Pointer (host memory) for the data in the array
*/
void* cugraph_type_erased_host_array_release(cugraph_type_erased_host_array_t* p);
#endif
/**
* @brief Create a type erased host array view from
* a type erased host array
*
* @param [in] array Pointer to the type erased host array
* @return Pointer to the view of the host array
*/
cugraph_type_erased_host_array_view_t* cugraph_type_erased_host_array_view(
cugraph_type_erased_host_array_t* array);
/**
* @brief Create a type erased host array view from
* a raw host pointer.
*
* @param [in] pointer Raw host pointer
* @param [in] n_elems The number of elements in the array
* @param [in] dtype The type of array to create
* @return pointer to the view of the host array
*/
cugraph_type_erased_host_array_view_t* cugraph_type_erased_host_array_view_create(
void* pointer, size_t n_elems, cugraph_data_type_id_t dtype);
/**
* @brief Destroy a type erased host array view
*
* @param [in] p Pointer to the type erased host array view
*/
void cugraph_type_erased_host_array_view_free(cugraph_type_erased_host_array_view_t* p);
/**
* @brief Get the size of a type erased host array view
*
* @param [in] p Pointer to the type erased host array view
* @return The number of elements in the array
*/
size_t cugraph_type_erased_host_array_size(const cugraph_type_erased_host_array_view_t* p);
/**
* @brief Get the type of a type erased host array view
*
* @param [in] p Pointer to the type erased host array view
* @return The type of the elements in the array
*/
cugraph_data_type_id_t cugraph_type_erased_host_array_type(
const cugraph_type_erased_host_array_view_t* p);
/**
* @brief Get the raw pointer of the type erased host array view
*
* @param [in] p Pointer to the type erased host array view
* @return Pointer (host memory) for the data in the array
*/
void* cugraph_type_erased_host_array_pointer(const cugraph_type_erased_host_array_view_t* p);
/**
* @brief Copy data between two type erased device array views
*
* @param [in] handle Handle for accessing resources
* @param [out] dst Pointer to type erased host array view destination
* @param [in] src Pointer to type erased host array view source
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_host_array_view_copy(
const cugraph_resource_handle_t* handle,
cugraph_type_erased_host_array_view_t* dst,
const cugraph_type_erased_host_array_view_t* src,
cugraph_error_t** error);
/**
* @brief Copy data from host to a type erased device array view
*
* @param [in] handle Handle for accessing resources
* @param [out] dst Pointer to the type erased device array view
* @param [in] h_src Pointer to host array to copy into device memory
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_view_copy_from_host(
const cugraph_resource_handle_t* handle,
cugraph_type_erased_device_array_view_t* dst,
const byte_t* h_src,
cugraph_error_t** error);
/**
* @brief Copy data from device to a type erased host array
*
* @param [in] handle Handle for accessing resources
* @param [out] h_dst Pointer to host array
* @param [in] src Pointer to the type erased device array view source
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_view_copy_to_host(
const cugraph_resource_handle_t* handle,
byte_t* h_dst,
const cugraph_type_erased_device_array_view_t* src,
cugraph_error_t** error);
/**
* @brief Copy data between two type erased device array views
*
* @param [in] handle Handle for accessing resources
* @param [out] dst Pointer to type erased device array view destination
* @param [in] src Pointer to type erased device array view source
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_type_erased_device_array_view_copy(
const cugraph_resource_handle_t* handle,
cugraph_type_erased_device_array_view_t* dst,
const cugraph_type_erased_device_array_view_t* src,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
| 12,744
| 36.931548
| 100
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/community_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/community_algorithms.h
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/graph_functions.h>
#include <cugraph_c/random.h>
#include <cugraph_c/resource_handle.h>
/** @defgroup community Community algorithms
* @ingroup c_api
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque triangle counting result type
*/
typedef struct {
int32_t align_;
} cugraph_triangle_count_result_t;
/**
* @brief Triangle Counting
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] start Device array of vertices we want to count triangles for. If NULL
* the entire set of vertices in the graph is processed
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Output from the triangle_count call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_triangle_count(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start,
bool_t do_expensive_check,
cugraph_triangle_count_result_t** result,
cugraph_error_t** error);
/**
* @brief Get triangle counting vertices
*/
cugraph_type_erased_device_array_view_t* cugraph_triangle_count_result_get_vertices(
cugraph_triangle_count_result_t* result);
/**
* @brief Get triangle counting counts
*/
cugraph_type_erased_device_array_view_t* cugraph_triangle_count_result_get_counts(
cugraph_triangle_count_result_t* result);
/**
* @brief Free a triangle count result
*
* @param [in] result The result from a sampling algorithm
*/
void cugraph_triangle_count_result_free(cugraph_triangle_count_result_t* result);
/**
* @brief Opaque hierarchical clustering output
*/
typedef struct {
int32_t align_;
} cugraph_hierarchical_clustering_result_t;
/**
* @brief Compute Louvain
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] max_level Maximum level in hierarchy
* @param [in] resolution Resolution parameter (gamma) in modularity formula.
* This changes the size of the communities. Higher resolutions
* lead to more smaller communities, lower resolutions lead to
* fewer larger communities.
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Output from the Louvain call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_louvain(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t max_level,
double resolution,
bool_t do_expensive_check,
cugraph_hierarchical_clustering_result_t** result,
cugraph_error_t** error);
/**
* @brief Compute Leiden
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in] max_level Maximum level in hierarchy
* @param [in] resolution Resolution parameter (gamma) in modularity formula.
* This changes the size of the communities. Higher resolutions
* lead to more smaller communities, lower resolutions lead to
* fewer larger communities.
* @param[in] theta (optional) The value of the parameter to scale modularity
* gain in Leiden refinement phase. It is used to compute
* the probability of joining a random leiden community.
* Called theta in the Leiden algorithm.
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Output from the Leiden call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_leiden(const cugraph_resource_handle_t* handle,
cugraph_rng_state_t* rng_state,
cugraph_graph_t* graph,
size_t max_level,
double resolution,
double theta,
bool_t do_expensive_check,
cugraph_hierarchical_clustering_result_t** result,
cugraph_error_t** error);
/**
* @brief Get hierarchical clustering vertices
*/
cugraph_type_erased_device_array_view_t* cugraph_hierarchical_clustering_result_get_vertices(
cugraph_hierarchical_clustering_result_t* result);
/**
* @brief Get hierarchical clustering clusters
*/
cugraph_type_erased_device_array_view_t* cugraph_hierarchical_clustering_result_get_clusters(
cugraph_hierarchical_clustering_result_t* result);
/**
* @brief Get modularity
*/
double cugraph_hierarchical_clustering_result_get_modularity(
cugraph_hierarchical_clustering_result_t* result);
/**
* @brief Free a hierarchical clustering result
*
* @param [in] result The result from a sampling algorithm
*/
void cugraph_hierarchical_clustering_result_free(cugraph_hierarchical_clustering_result_t* result);
/**
* @brief Compute ECG clustering of the given graph
*
* ECG runs truncated Louvain on an ensemble of permutations of the input graph,
* then uses the ensemble partitions to determine weights for the input graph.
* The final result is found by running full Louvain on the input graph using
* the determined weights. See https://arxiv.org/abs/1809.05578 for further
* information.
*
* NOTE: This currently wraps the legacy ECG clustering implementation which is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* @param [in] min_weight The minimum weight parameter
* @param [in] ensemble_size The ensemble size parameter
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result The result from the clustering algorithm
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_ecg(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
double min_weight,
size_t ensemble_size,
bool_t do_expensive_check,
cugraph_hierarchical_clustering_result_t** result,
cugraph_error_t** error);
/**
* @brief Extract ego graphs
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] source_vertices Device array of vertices we want to extract egonets for.
* @param [in] radius The number of hops to go out from each source vertex
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Opaque object containing the extracted subgraph
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_extract_ego(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* source_vertices,
size_t radius,
bool_t do_expensive_check,
cugraph_induced_subgraph_result_t** result,
cugraph_error_t** error);
/**
* @brief Opaque clustering output
*/
typedef struct {
int32_t align_;
} cugraph_clustering_result_t;
/**
* @brief Balanced cut clustering
*
* NOTE: This currently wraps the legacy balanced cut clustering implementation and is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] n_clusters The desired number of clusters
* @param [in] n_eigenvectors The number of eigenvectors to use
* @param [in] evs_tolerance The tolerance to use for the eigenvalue solver
* @param [in] evs_max_iterations The maximum number of iterations of the eigenvalue solver
* @param [in] k_means_tolerance The tolerance to use for the k-means solver
* @param [in] k_means_max_iterations The maximum number of iterations of the k-means solver
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Opaque object containing the clustering result
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_balanced_cut_clustering(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t n_clusters,
size_t n_eigenvectors,
double evs_tolerance,
int evs_max_iterations,
double k_means_tolerance,
int k_means_max_iterations,
bool_t do_expensive_check,
cugraph_clustering_result_t** result,
cugraph_error_t** error);
/**
* @brief Spectral clustering
*
* NOTE: This currently wraps the legacy spectral clustering implementation and is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] n_clusters The desired number of clusters
* @param [in] n_eigenvectors The number of eigenvectors to use
* @param [in] evs_tolerance The tolerance to use for the eigenvalue solver
* @param [in] evs_max_iterations The maximum number of iterations of the eigenvalue solver
* @param [in] k_means_tolerance The tolerance to use for the k-means solver
* @param [in] k_means_max_iterations The maximum number of iterations of the k-means solver
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Opaque object containing the clustering result
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_spectral_modularity_maximization(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t n_clusters,
size_t n_eigenvectors,
double evs_tolerance,
int evs_max_iterations,
double k_means_tolerance,
int k_means_max_iterations,
bool_t do_expensive_check,
cugraph_clustering_result_t** result,
cugraph_error_t** error);
/**
* @brief Compute modularity of the specified clustering
*
* NOTE: This currently wraps the legacy spectral modularity implementation and is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] n_clusters The desired number of clusters
* @param [in] vertices Vertex ids from the clustering result
* @param [in] clusters Cluster ids from the clustering result
* @param [out] score The modularity score for this clustering
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_analyze_clustering_modularity(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t n_clusters,
const cugraph_type_erased_device_array_view_t* vertices,
const cugraph_type_erased_device_array_view_t* clusters,
double* score,
cugraph_error_t** error);
/**
* @brief Compute edge cut of the specified clustering
*
* NOTE: This currently wraps the legacy spectral edge cut implementation and is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] n_clusters The desired number of clusters
* @param [in] vertices Vertex ids from the clustering result
* @param [in] clusters Cluster ids from the clustering result
* @param [out] score The edge cut score for this clustering
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_analyze_clustering_edge_cut(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t n_clusters,
const cugraph_type_erased_device_array_view_t* vertices,
const cugraph_type_erased_device_array_view_t* clusters,
double* score,
cugraph_error_t** error);
/**
* @brief Compute ratio cut of the specified clustering
*
* NOTE: This currently wraps the legacy spectral ratio cut implementation and is only
* available in Single GPU implementation.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] n_clusters The desired number of clusters
* @param [in] vertices Vertex ids from the clustering result
* @param [in] clusters Cluster ids from the clustering result
* @param [out] score The ratio cut score for this clustering
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_analyze_clustering_ratio_cut(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t n_clusters,
const cugraph_type_erased_device_array_view_t* vertices,
const cugraph_type_erased_device_array_view_t* clusters,
double* score,
cugraph_error_t** error);
/**
* @brief Get clustering vertices
*/
cugraph_type_erased_device_array_view_t* cugraph_clustering_result_get_vertices(
cugraph_clustering_result_t* result);
/**
* @brief Get clustering clusters
*/
cugraph_type_erased_device_array_view_t* cugraph_clustering_result_get_clusters(
cugraph_clustering_result_t* result);
/**
* @brief Free a clustering result
*
* @param [in] result The result from a sampling algorithm
*/
void cugraph_clustering_result_free(cugraph_clustering_result_t* result);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
| 18,223
| 43.666667
| 100
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/core_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/core_algorithms.h
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/array.h>
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque core number result type
*/
typedef struct {
int32_t align_;
} cugraph_core_result_t;
/**
* @brief Opaque k-core result type
*/
typedef struct {
int32_t align_;
} cugraph_k_core_result_t;
/**
* @brief Create a core_number result (in case it was previously extracted)
*
* @param [in] handle Handle for accessing resources
* @param [in] vertices The result from core number
* @param [in] core_numbers The result from core number
* @param [out] result Opaque pointer to core number results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_core_result_create(
const cugraph_resource_handle_t* handle,
cugraph_type_erased_device_array_view_t* vertices,
cugraph_type_erased_device_array_view_t* core_numbers,
cugraph_core_result_t** core_result,
cugraph_error_t** error);
/**
* @brief Get the vertex ids from the core result
*
* @param [in] result The result from core number
* @return type erased array of vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_core_result_get_vertices(
cugraph_core_result_t* result);
/**
* @brief Get the core numbers from the core result
*
* @param [in] result The result from core number
* @return type erased array of core numbers
*/
cugraph_type_erased_device_array_view_t* cugraph_core_result_get_core_numbers(
cugraph_core_result_t* result);
/**
* @brief Free core result
*
* @param [in] result The result from core number
*/
void cugraph_core_result_free(cugraph_core_result_t* result);
/**
* @brief Get the src vertex ids from the k-core result
*
* @param [in] result The result from k-core
* @return type erased array of src vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_k_core_result_get_src_vertices(
cugraph_k_core_result_t* result);
/**
* @brief Get the dst vertex ids from the k-core result
*
* @param [in] result The result from k-core
* @return type erased array of dst vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_k_core_result_get_dst_vertices(
cugraph_k_core_result_t* result);
/**
* @brief Get the weights from the k-core result
*
* Returns NULL if the graph is unweighted
*
* @param [in] result The result from k-core
* @return type erased array of weights
*/
cugraph_type_erased_device_array_view_t* cugraph_k_core_result_get_weights(
cugraph_k_core_result_t* result);
/**
* @brief Free k-core result
*
* @param [in] result The result from k-core
*/
void cugraph_k_core_result_free(cugraph_k_core_result_t* result);
/**
* @brief Enumeration for computing core number
*/
typedef enum {
K_CORE_DEGREE_TYPE_IN = 0, /** Compute core_number using incoming edges */
K_CORE_DEGREE_TYPE_OUT = 1, /** Compute core_number using outgoing edges */
K_CORE_DEGREE_TYPE_INOUT = 2 /** Compute core_number using both incoming and outgoing edges */
} cugraph_k_core_degree_type_t;
/**
* @brief Perform core number.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] degree_type Compute core_number using in, out or both in and out edges
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to core number results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_core_number(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
cugraph_k_core_degree_type_t degree_type,
bool_t do_expensive_check,
cugraph_core_result_t** result,
cugraph_error_t** error);
/**
* @brief Perform k_core using output from core_number
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] k The value of k to use
* @param [in] degree_type Compute core_number using in, out or both in and out edges.
* Ignored if core_result is specified.
* @param [in] core_result Result from calling cugraph_core_number, if NULL then
* call core_number inside this function call.
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to k_core results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_k_core(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t k,
cugraph_k_core_degree_type_t degree_type,
const cugraph_core_result_t* core_result,
bool_t do_expensive_check,
cugraph_k_core_result_t** result,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
| 6,472
| 35.162011
| 97
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/error.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/error.h
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum cugraph_error_code_ {
CUGRAPH_SUCCESS = 0,
CUGRAPH_UNKNOWN_ERROR,
CUGRAPH_INVALID_HANDLE,
CUGRAPH_ALLOC_ERROR,
CUGRAPH_INVALID_INPUT,
CUGRAPH_NOT_IMPLEMENTED,
CUGRAPH_UNSUPPORTED_TYPE_COMBINATION
} cugraph_error_code_t;
typedef struct cugraph_error_ {
int32_t align_;
} cugraph_error_t;
/**
* @brief Return an error message
*
* @param [in] error The error object from some cugraph function call
* @return a C-style string that provides detail for the error
*/
const char* cugraph_error_message(const cugraph_error_t* error);
/**
* @brief Destroy an error message
*
* @param [in] error The error object from some cugraph function call
*/
void cugraph_error_free(cugraph_error_t* error);
#ifdef __cplusplus
}
#endif
| 1,466
| 24.736842
| 76
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph.h
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/array.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int32_t align_;
} cugraph_graph_t;
typedef struct {
int32_t align_;
} cugraph_data_mask_t;
typedef struct {
bool_t is_symmetric;
bool_t is_multigraph;
} cugraph_graph_properties_t;
// FIXME: Add support for specifying isolated vertices
/**
* @brief Construct an SG graph
*
* @param [in] handle Handle for accessing resources
* @param [in] properties Properties of the constructed graph
* @param [in] src Device array containing the source vertex ids.
* @param [in] dst Device array containing the destination vertex ids
* @param [in] weights Device array containing the edge weights. Note that an unweighted
* graph can be created by passing weights == NULL.
* @param [in] edge_ids Device array containing the edge ids for each edge. Optional
argument that can be NULL if edge ids are not used.
* @param [in] edge_type_ids Device array containing the edge types for each edge. Optional
argument that can be NULL if edge types are not used.
* @param [in] store_transposed If true create the graph initially in transposed format
* @param [in] renumber If true, renumber vertices to make an efficient data structure.
* If false, do not renumber. Renumbering is required if the vertices are not sequential
* integer values from 0 to num_vertices.
* @param [in] do_expensive_check If true, do expensive checks to validate the input data
* is consistent with software assumptions. If false bypass these checks.
* @param [in] properties Properties of the graph
* @param [out] graph A pointer to the graph object
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*
* @return error code
*/
cugraph_error_code_t cugraph_sg_graph_create(
const cugraph_resource_handle_t* handle,
const cugraph_graph_properties_t* properties,
const cugraph_type_erased_device_array_view_t* src,
const cugraph_type_erased_device_array_view_t* dst,
const cugraph_type_erased_device_array_view_t* weights,
const cugraph_type_erased_device_array_view_t* edge_ids,
const cugraph_type_erased_device_array_view_t* edge_type_ids,
bool_t store_transposed,
bool_t renumber,
bool_t do_expensive_check,
cugraph_graph_t** graph,
cugraph_error_t** error);
/**
* @brief Construct an SG graph from a CSR input
*
* @param [in] handle Handle for accessing resources
* @param [in] properties Properties of the constructed graph
* @param [in] offsets Device array containing the CSR offsets array
* @param [in] indices Device array containing the destination vertex ids
* @param [in] weights Device array containing the edge weights. Note that an unweighted
* graph can be created by passing weights == NULL.
* @param [in] edge_ids Device array containing the edge ids for each edge. Optional
argument that can be NULL if edge ids are not used.
* @param [in] edge_type_ids Device array containing the edge types for each edge. Optional
argument that can be NULL if edge types are not used.
* @param [in] store_transposed If true create the graph initially in transposed format
* @param [in] renumber If true, renumber vertices to make an efficient data structure.
* If false, do not renumber. Renumbering is required if the vertices are not sequential
* integer values from 0 to num_vertices.
* @param [in] do_expensive_check If true, do expensive checks to validate the input data
* is consistent with software assumptions. If false bypass these checks.
* @param [in] properties Properties of the graph
* @param [out] graph A pointer to the graph object
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*
* @return error code
*/
cugraph_error_code_t cugraph_sg_graph_create_from_csr(
const cugraph_resource_handle_t* handle,
const cugraph_graph_properties_t* properties,
const cugraph_type_erased_device_array_view_t* offsets,
const cugraph_type_erased_device_array_view_t* indices,
const cugraph_type_erased_device_array_view_t* weights,
const cugraph_type_erased_device_array_view_t* edge_ids,
const cugraph_type_erased_device_array_view_t* edge_type_ids,
bool_t store_transposed,
bool_t renumber,
bool_t do_expensive_check,
cugraph_graph_t** graph,
cugraph_error_t** error);
/**
* @brief Destroy an SG graph
*
* @param [in] graph A pointer to the graph object to destroy
*/
// FIXME: This should probably just be cugraph_graph_free
// but didn't want to confuse with original cugraph_free_graph
void cugraph_sg_graph_free(cugraph_graph_t* graph);
// FIXME: Add support for specifying isolated vertices
/**
* @brief Construct an MG graph
*
* @param [in] handle Handle for accessing resources
* @param [in] properties Properties of the constructed graph
* @param [in] src Device array containing the source vertex ids
* @param [in] dst Device array containing the destination vertex ids
* @param [in] weights Device array containing the edge weights. Note that an unweighted
* graph can be created by passing weights == NULL. If a weighted
* graph is to be created, the weights device array should be created
* on each rank, but the pointer can be NULL and the size 0
* if there are no inputs provided by this rank
* @param [in] edge_ids Device array containing the edge ids for each edge. Optional
argument that can be NULL if edge ids are not used.
* @param [in] edge_type_ids Device array containing the edge types for each edge. Optional
argument that can be NULL if edge types are not used.
* @param [in] store_transposed If true create the graph initially in transposed format
* @param [in] num_edges Number of edges
* @param [in] do_expensive_check If true, do expensive checks to validate the input data
* is consistent with software assumptions. If false bypass these checks.
* @param [out] graph A pointer to the graph object
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_mg_graph_create(
const cugraph_resource_handle_t* handle,
const cugraph_graph_properties_t* properties,
const cugraph_type_erased_device_array_view_t* src,
const cugraph_type_erased_device_array_view_t* dst,
const cugraph_type_erased_device_array_view_t* weights,
const cugraph_type_erased_device_array_view_t* edge_ids,
const cugraph_type_erased_device_array_view_t* edge_type_ids,
bool_t store_transposed,
size_t num_edges,
bool_t do_expensive_check,
cugraph_graph_t** graph,
cugraph_error_t** error);
/**
* @brief Destroy an MG graph
*
* @param [in] graph A pointer to the graph object to destroy
*/
// FIXME: This should probably just be cugraph_graph_free
// but didn't want to confuse with original cugraph_free_graph
void cugraph_mg_graph_free(cugraph_graph_t* graph);
/**
* @brief Create a data mask
*
* @param [in] handle Handle for accessing resources
* @param [in] vertex_bit_mask Device array containing vertex bit mask
* @param [in] edge_bit_mask Device array containing edge bit mask
* @param [in] complement If true, a 0 in one of the bit masks implies
* the vertex/edge should be included and a 1 should
* be excluded. If false a 1 in one of the bit masks
* implies the vertex/edge should be included and a 0
* should be excluded.
* @param [out] mask An opaque pointer to the constructed mask object
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_data_mask_create(
const cugraph_resource_handle_t* handle,
const cugraph_type_erased_device_array_view_t* vertex_bit_mask,
const cugraph_type_erased_device_array_view_t* edge_bit_mask,
bool_t complement,
cugraph_data_mask_t** mask,
cugraph_error_t** error);
/**
* @brief Get the data mask currently associated with a graph
*
* @param [in] graph The input graph
* @param [out] mask Opaque pointer where we should store the
* current mask. Will be NULL if there is no mask
* currently assigned to the graph.
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_graph_get_data_mask(cugraph_graph_t* graph,
cugraph_data_mask_t** mask,
cugraph_error_t** error);
/**
* @brief Associate a data mask with a graph
*
* NOTE: This function will fail if there is already a data mask associated with this graph
*
* @param [in] graph The input graph
* @param [out] mask Opaque pointer of the new data mask
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_graph_add_data_mask(cugraph_graph_t* graph,
cugraph_data_mask_t* mask,
cugraph_error_t** error);
/**
* @brief Release the data mask currently associated with a graph
*
* This function will remove the associated of the current data mask
* with this graph. The caller will be responsible for destroying the data
* mask using graph_data_mask_destroy.
*
* If this function is not called and the graph is destroyed, the act of destroying
* the graph will also destroy the data mask.
*
* If this function is called on a graph that is not currently associated with
* a graph, then the mask will be set to NULL.
*
* @param [in] graph The input graph
* @param [out] mask Opaque pointer where we should store the
* current mask.
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_graph_release_data_mask(cugraph_graph_t* graph,
cugraph_data_mask_t** mask,
cugraph_error_t** error);
/**
* @brief Destroy a data mask
*
* @param [in] mask A pointer to the data mask to destroy
*/
void cugraph_data_mask_destroy(cugraph_data_mask_t* mask);
#ifdef __cplusplus
}
#endif
| 12,328
| 45.524528
| 98
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph_functions.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph_functions.h
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/array.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque vertex pair type
*/
typedef struct {
int32_t align_;
} cugraph_vertex_pairs_t;
/**
* @brief Create vertex_pairs
*
* Input data will be shuffled to the proper GPU and stored in the
* output vertex_pairs.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Graph to operate on
* @param [in] first Type erased array of vertex ids for the first vertex of the pair
* @param [in] second Type erased array of vertex ids for the second vertex of the pair
* @param [out] vertex_pairs Opaque pointer to vertex_pairs
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_create_vertex_pairs(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* first,
const cugraph_type_erased_device_array_view_t* second,
cugraph_vertex_pairs_t** vertex_pairs,
cugraph_error_t** error);
/**
* @brief Get the first vertex id array
*
* @param [in] vertex_pairs A vertex_pairs
* @return type erased array of vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_vertex_pairs_get_first(
cugraph_vertex_pairs_t* vertex_pairs);
/**
* @brief Get the second vertex id array
*
* @param [in] vertex_pairs A vertex_pairs
* @return type erased array of vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_vertex_pairs_get_second(
cugraph_vertex_pairs_t* vertex_pairs);
/**
* @brief Free vertex pair
*
* @param [in] vertex_pairs The vertex pairs
*/
void cugraph_vertex_pairs_free(cugraph_vertex_pairs_t* vertex_pairs);
/**
* @brief Find all 2-hop neighbors in the graph
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] start_vertices Optional type erased array of starting vertices
* If NULL use all, if specified compute two-hop
* neighbors for these starting vertices
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [out] result Opaque pointer to resulting vertex pairs
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_two_hop_neighbors(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start_vertices,
bool_t do_expensive_check,
cugraph_vertex_pairs_t** result,
cugraph_error_t** error);
/**
* @brief Opaque induced subgraph type
*/
typedef struct {
int32_t align_;
} cugraph_induced_subgraph_result_t;
/**
* @brief Get the source vertex ids
*
* @param [in] induced_subgraph Opaque pointer to induced subgraph
* @return type erased array view of source vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_induced_subgraph_get_sources(
cugraph_induced_subgraph_result_t* induced_subgraph);
/**
* @brief Get the destination vertex ids
*
* @param [in] induced_subgraph Opaque pointer to induced subgraph
* @return type erased array view of destination vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_induced_subgraph_get_destinations(
cugraph_induced_subgraph_result_t* induced_subgraph);
/**
* @brief Get the edge weights
*
* @param [in] induced_subgraph Opaque pointer to induced subgraph
* @return type erased array view of edge weights
*/
cugraph_type_erased_device_array_view_t* cugraph_induced_subgraph_get_edge_weights(
cugraph_induced_subgraph_result_t* induced_subgraph);
/**
* @brief Get the subgraph offsets
*
* @param [in] induced_subgraph Opaque pointer to induced subgraph
* @return type erased array view of subgraph identifiers
*/
cugraph_type_erased_device_array_view_t* cugraph_induced_subgraph_get_subgraph_offsets(
cugraph_induced_subgraph_result_t* induced_subgraph);
/**
* @brief Free induced subgraph
*
* @param [in] induced subgraph Opaque pointer to induced subgraph
*/
void cugraph_induced_subgraph_result_free(cugraph_induced_subgraph_result_t* induced_subgraph);
/**
* @brief Extract induced subgraph(s)
*
* Given a list of vertex ids, extract a list of edges that represent the subgraph
* containing only the specified vertex ids.
*
* This function will do multiple subgraph extractions concurrently. The vertex ids
* are specified in CSR-style, with @p subgraph_vertices being a list of vertex ids
* and @p subgraph_offsets[i] identifying the start offset for each extracted subgraph
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] subgraph_offsets Type erased array of subgraph offsets into
* @p subgraph_vertices
* @param [in] subgraph_vertices Type erased array of vertices to include in
* extracted subgraph.
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to induced subgraph result
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_extract_induced_subgraph(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* subgraph_offsets,
const cugraph_type_erased_device_array_view_t* subgraph_vertices,
bool_t do_expensive_check,
cugraph_induced_subgraph_result_t** result,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
| 6,867
| 35.147368
| 98
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph_generators.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/graph_generators.h
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/array.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/random.h>
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { POWER_LAW = 0, UNIFORM } cugraph_generator_distribution_t;
/**
* @brief Opaque COO definition
*/
typedef struct {
int32_t align_;
} cugraph_coo_t;
/**
* @brief Opaque COO list definition
*/
typedef struct {
int32_t align_;
} cugraph_coo_list_t;
/**
* @brief Get the source vertex ids
*
* @param [in] coo Opaque pointer to COO
* @return type erased array view of source vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_coo_get_sources(cugraph_coo_t* coo);
/**
* @brief Get the destination vertex ids
*
* @param [in] coo Opaque pointer to COO
* @return type erased array view of destination vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_coo_get_destinations(cugraph_coo_t* coo);
/**
* @brief Get the edge weights
*
* @param [in] coo Opaque pointer to COO
* @return type erased array view of edge weights, NULL if no edge weights in COO
*/
cugraph_type_erased_device_array_view_t* cugraph_coo_get_edge_weights(cugraph_coo_t* coo);
/**
* @brief Get the edge id
*
* @param [in] coo Opaque pointer to COO
* @return type erased array view of edge id, NULL if no edge ids in COO
*/
cugraph_type_erased_device_array_view_t* cugraph_coo_get_edge_id(cugraph_coo_t* coo);
/**
* @brief Get the edge type
*
* @param [in] coo Opaque pointer to COO
* @return type erased array view of edge type, NULL if no edge types in COO
*/
cugraph_type_erased_device_array_view_t* cugraph_coo_get_edge_type(cugraph_coo_t* coo);
/**
* @brief Get the number of coo object in the list
*
* @param [in] coo_list Opaque pointer to COO list
* @return number of elements
*/
size_t cugraph_coo_list_size(const cugraph_coo_list_t* coo_list);
/**
* @brief Get a COO from the list
*
* @param [in] coo_list Opaque pointer to COO list
* @param [in] index Index of desired COO from list
* @return a cugraph_coo_t* object from the list
*/
cugraph_coo_t* cugraph_coo_list_element(cugraph_coo_list_t* coo_list, size_t index);
/**
* @brief Free coo object
*
* @param [in] coo Opaque pointer to COO
*/
void cugraph_coo_free(cugraph_coo_t* coo);
/**
* @brief Free coo list
*
* @param [in] coo_list Opaque pointer to list of COO objects
*/
void cugraph_coo_list_free(cugraph_coo_list_t* coo_list);
/**
* @brief Generate RMAT edge list
*
* Returns a COO containing edges generated from the RMAT generator.
*
* Vertex types will be int32 if scale < 32 and int64 if scale >= 32
*
* @param [in] handle Handle for accessing resources
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in] scale Scale factor to set the number of vertices in the graph. Vertex IDs have
* values in [0, V), where V = 1 << @p scale.
* @param [in] num_edges Number of edges to generate.
* @param [in] a a, b, c, d (= 1.0 - (a + b + c)) in the R-mat graph generator
* (vist https://graph500.org for additional details). a, b, c, d should be non-negative and a + b +
* c should be no larger than 1.0.
* @param [in] b a, b, c, d (= 1.0 - (a + b + c)) in the R-mat graph generator
* (vist https://graph500.org for additional details). a, b, c, d should be non-negative and a + b +
* c should be no larger than 1.0.
* @param [in] c a, b, c, d (= 1.0 - (a + b + c)) in the R-mat graph generator
* (vist https://graph500.org for additional details). a, b, c, d should be non-negative and a + b +
* c should be no larger than 1.0.
* @param [in] clip_and_flip Flag controlling whether to generate edges only in the lower
* triangular part (including the diagonal) of the graph adjacency matrix (if set to `true`) or not
* (if set to `false`).
* @param [out] result Opaque pointer to generated coo
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_generate_rmat_edgelist(const cugraph_resource_handle_t* handle,
cugraph_rng_state_t* rng_state,
size_t scale,
size_t num_edges,
double a,
double b,
double c,
bool_t clip_and_flip,
cugraph_coo_t** result,
cugraph_error_t** error);
/**
* @brief Generate RMAT edge lists
*
* Returns a COO list containing edges generated from the RMAT generator.
*
* Vertex types will be int32 if scale < 32 and int64 if scale >= 32
*
* @param [in] handle Handle for accessing resources
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in] n_edgelists Number of edge lists (graphs) to generate
* @param [in] min_scale Scale factor to set the minimum number of verties in the graph.
* @param [in] max_scale Scale factor to set the maximum number of verties in the graph.
* @param [in] edge_factor Average number of edges per vertex to generate.
* @param [in] size_distribution Distribution of the graph sizes, impacts the scale parameter of
* the R-MAT generator
* @param [in] edge_distribution Edges distribution for each graph, impacts how R-MAT parameters
* a,b,c,d, are set.
* @param [in] clip_and_flip Flag controlling whether to generate edges only in the lower
* triangular part (including the diagonal) of the graph adjacency matrix (if set to `true`) or not
* (if set to `false`).
* @param [out] result Opaque pointer to generated coo list
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_generate_rmat_edgelists(
const cugraph_resource_handle_t* handle,
cugraph_rng_state_t* rng_state,
size_t n_edgelists,
size_t min_scale,
size_t max_scale,
size_t edge_factor,
cugraph_generator_distribution_t size_distribution,
cugraph_generator_distribution_t edge_distribution,
bool_t clip_and_flip,
cugraph_coo_list_t** result,
cugraph_error_t** error);
/**
* @brief Generate edge weights and add to an rmat edge list
*
* Updates a COO to contain random edge weights
*
* @param [in] handle Handle for accessing resources
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in/out] coo Opaque pointer to the coo, weights will be added (overwriting
* any existing weights)
* @param [in] dtype The type of weight to generate (FLOAT32 or FLOAT64), ignored
* unless include_weights is true
* @param [in] minimum_weight Minimum weight value to generate
* @param [in] maximum_weight Maximum weight value to generate
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*/
cugraph_error_code_t cugraph_generate_edge_weights(const cugraph_resource_handle_t* handle,
cugraph_rng_state_t* rng_state,
cugraph_coo_t* coo,
cugraph_data_type_id_t dtype,
double minimum_weight,
double maximum_weight,
cugraph_error_t** error);
/**
* @brief Add edge ids to an COO
*
* Updates a COO to contain edge ids. Edges will be numbered from 0 to n-1 where n is the number of
* edges
*
* @param [in] handle Handle for accessing resources
* @param [in/out] coo Opaque pointer to the coo, weights will be added (overwriting
* any existing weights)
* @param [in] multi_gpu Flag if the COO is being created on multiple GPUs
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*/
cugraph_error_code_t cugraph_generate_edge_ids(const cugraph_resource_handle_t* handle,
cugraph_coo_t* coo,
bool_t multi_gpu,
cugraph_error_t** error);
/**
* @brief Generate random edge types, add them to an COO
*
* Updates a COO to contain edge types. Edges types will be randomly generated.
*
* @param [in] handle Handle for accessing resources
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in/out] coo Opaque pointer to the coo, weights will be added (overwriting
* any existing weights)
* @param [in] max_edge_type Edge types will be randomly generated between min_edge_type
* and max_edge_type
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*/
cugraph_error_code_t cugraph_generate_edge_types(const cugraph_resource_handle_t* handle,
cugraph_rng_state_t* rng_state,
cugraph_coo_t* coo,
int32_t min_edge_type,
int32_t max_edge_type,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
| 11,160
| 42.092664
| 100
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/labeling_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/labeling_algorithms.h
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup labeling Labeling algorithms
* @ingroup c_api
* @{
*/
/**
* @brief Opaque labeling result type
*/
typedef struct {
int32_t align_;
} cugraph_labeling_result_t;
/**
* @brief Get the vertex ids from the labeling result
*
* @param [in] result The result from a labeling algorithm
* @return type erased array of vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_labeling_result_get_vertices(
cugraph_labeling_result_t* result);
/**
* @brief Get the label values from the labeling result
*
* @param [in] result The result from a labeling algorithm
* @return type erased array of label values
*/
cugraph_type_erased_device_array_view_t* cugraph_labeling_result_get_labels(
cugraph_labeling_result_t* result);
/**
* @brief Free labeling result
*
* @param [in] result The result from a labeling algorithm
*/
void cugraph_labeling_result_free(cugraph_labeling_result_t* result);
/**
* @brief Labels each vertex in the input graph with its (weakly-connected-)component ID
*
* The input graph must be symmetric. Component IDs can be arbitrary integers (they can be
* non-consecutive and are not ordered by component size or any other criterion).
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to labeling results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*/
cugraph_error_code_t cugraph_weakly_connected_components(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
bool_t do_expensive_check,
cugraph_labeling_result_t** result,
cugraph_error_t** error);
/**
* @brief Labels each vertex in the input graph with its (strongly-connected-)component ID
*
* The input graph may be asymmetric. Component IDs can be arbitrary integers (they can be
* non-consecutive and are not ordered by component size or any other criterion).
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to labeling results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
*/
cugraph_error_code_t cugraph_strongly_connected_components(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
bool_t do_expensive_check,
cugraph_labeling_result_t** result,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
| 4,096
| 35.90991
| 99
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/random.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/random.h
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int32_t align_;
} cugraph_rng_state_t;
/**
* @brief Create a Random Number Generator State
*
* @param [in] seed Initial value for seed. In MG this should be different
* on each GPU
* @param [out] state Pointer to the location to store the pointer to the RngState
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_rng_state_create(const cugraph_resource_handle_t* handle,
uint64_t seed,
cugraph_rng_state_t** state,
cugraph_error_t** error);
/**
* @brief Destroy a Random Number Generator State
*
* @param [in] p Pointer to the Random Number Generator State
*/
void cugraph_rng_state_free(cugraph_rng_state_t* p);
#ifdef __cplusplus
}
#endif
| 1,738
| 31.203704
| 90
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/resource_handle.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/resource_handle.h
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum bool_ { FALSE = 0, TRUE = 1 } bool_t;
typedef int8_t byte_t;
/**
* @deprecated - use cugraph_data_type_id_t;
*/
typedef enum data_type_id_ { INT32 = 0, INT64, FLOAT32, FLOAT64, SIZE_T, NTYPES } data_type_id_t;
/**
* @brief - Enumeration of data types
*/
typedef data_type_id_t cugraph_data_type_id_t;
typedef struct cugraph_resource_handle_ {
int32_t align_;
} cugraph_resource_handle_t;
// FIXME: Don't really want a raft handle here. We really want to be able to
// configure the resource handle ourselves. But that requires a bunch
// of logic that's currently only available in python.
/**
* @brief Construct a resource handle
*
* @param [in] raft_handle Handle for accessing resources
* If NULL, we will create a raft handle
* internally
*
* @return A graph resource handle
*/
cugraph_resource_handle_t* cugraph_create_resource_handle(void* raft_handle);
/**
* @brief get rank from resource handle
*
* If the resource handle has been configured for multi-gpu, this will return
* the rank for this worker. If the resource handle has not been configured for
* multi-gpu this will always return 0.
*
* @param [in] handle Handle for accessing resources
* @return rank
*/
int cugraph_resource_handle_get_rank(const cugraph_resource_handle_t* handle);
/**
* @brief Free resources in the resource handle
*
* @param [in] handle Handle for accessing resources
*/
void cugraph_free_resource_handle(cugraph_resource_handle_t* handle);
#ifdef __cplusplus
}
#endif
| 2,346
| 27.621951
| 97
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/sampling_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/sampling_algorithms.h
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/random.h>
#include <cugraph_c/resource_handle.h>
/** @defgroup sampling Sampling algorithms
* @ingroup c_api
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque random walk result type
*/
typedef struct {
int32_t align_;
} cugraph_random_walk_result_t;
/**
* @brief Compute uniform random walks
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] start_vertices Array of source vertices
* @param [in] max_length Maximum length of the generated path
* @param [in] result Output from the node2vec call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_uniform_random_walks(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start_vertices,
size_t max_length,
cugraph_random_walk_result_t** result,
cugraph_error_t** error);
/**
* @brief Compute biased random walks
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] start_vertices Array of source vertices
* @param [in] max_length Maximum length of the generated path
* @param [in] result Output from the node2vec call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_biased_random_walks(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start_vertices,
size_t max_length,
cugraph_random_walk_result_t** result,
cugraph_error_t** error);
/**
* @brief Compute random walks using the node2vec framework.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] start_vertices Array of source vertices
* @param [in] max_length Maximum length of the generated path
* @param [in] compress_result If true, return the paths as a compressed sparse row matrix,
* otherwise return as a dense matrix
* @param [in] p The return parameter
* @param [in] q The in/out parameter
* @param [in] result Output from the node2vec call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_node2vec_random_walks(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start_vertices,
size_t max_length,
double p,
double q,
cugraph_random_walk_result_t** result,
cugraph_error_t** error);
/**
* @brief Compute random walks using the node2vec framework.
* @deprecated This call should be replaced with cugraph_node2vec_random_walks
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] sources Array of source vertices
* @param [in] max_depth Maximum length of the generated path
* @param [in] compress_result If true, return the paths as a compressed sparse row matrix,
* otherwise return as a dense matrix
* @param [in] p The return parameter
* @param [in] q The in/out parameter
* @param [in] result Output from the node2vec call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_node2vec(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* sources,
size_t max_depth,
bool_t compress_result,
double p,
double q,
cugraph_random_walk_result_t** result,
cugraph_error_t** error);
/**
* @brief Get the max path length from random walk result
*
* @param [in] result The result from random walks
* @return maximum path length
*/
size_t cugraph_random_walk_result_get_max_path_length(cugraph_random_walk_result_t* result);
// FIXME: Should this be the same as extract_paths_result_t? The only
// difference at the moment is that RW results contain weights
// and extract_paths results don't. But that's probably wrong.
/**
* @brief Get the matrix (row major order) of vertices in the paths
*
* @param [in] result The result from a random walk algorithm
* @return type erased array pointing to the path matrix in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_random_walk_result_get_paths(
cugraph_random_walk_result_t* result);
/**
* @brief Get the matrix (row major order) of edge weights in the paths
*
* @param [in] result The result from a random walk algorithm
* @return type erased array pointing to the path edge weights in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_random_walk_result_get_weights(
cugraph_random_walk_result_t* result);
/**
* @brief If the random walk result is compressed, get the path sizes
* @deprecated This call will no longer be relevant once the new node2vec are called
*
* @param [in] result The result from a random walk algorithm
* @return type erased array pointing to the path sizes in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_random_walk_result_get_path_sizes(
cugraph_random_walk_result_t* result);
/**
* @brief Free random walks result
*
* @param [in] result The result from random walks
*/
void cugraph_random_walk_result_free(cugraph_random_walk_result_t* result);
/**
* @brief Opaque neighborhood sampling result type
*/
typedef struct {
int32_t align_;
} cugraph_sample_result_t;
/**
* @brief Uniform Neighborhood Sampling
*
* Returns a sample of the neighborhood around specified start vertices. Optionally, each
* start vertex can be associated with a label, allowing the caller to specify multiple batches
* of sampling requests in the same function call - which should improve GPU utilization.
*
* If label is NULL then all start vertices will be considered part of the same batch and the
* return value will not have a label column.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] start_vertices Device array of start vertices for the sampling
* @param [in] start_vertex_labels Device array of start vertex labels for the sampling. The
* labels associated with each start vertex will be included in the output associated with results
* that were derived from that start vertex. We only support label of type INT32. If label is
* NULL, the return data will not be labeled.
* @param [in] label_list Device array of the labels included in @p start_vertex_labels. If
* @p label_to_comm_rank is not specified this parameter is ignored. If specified, label_list
* must be sorted in ascending order.
* @param [in] label_to_comm_rank Device array identifying which comm rank the output for a
* particular label should be shuffled in the output. If not specifed the data is not organized in
* output. If specified then the all data from @p label_list[i] will be shuffled to rank @p
* label_to_comm_rank[i]. If not specified then the output data will not be shuffled between ranks.
* @param [in] fanout Host array defining the fan out at each step in the sampling algorithm.
* We only support fanout values of type INT32
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in] with_replacement
* Boolean value. If true selection of edges is done with
* replacement. If false selection is done without replacement.
* @param [in] return_hops Boolean value. If true include the hop number in the result,
* If false the hop number will not be included in result.
* @param [in] do_expensive_check
* A flag to run expensive checks for input arguments (if set to true)
* @param [in] result Output from the uniform_neighbor_sample call
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_uniform_neighbor_sample_with_edge_properties(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* start_vertices,
const cugraph_type_erased_device_array_view_t* start_vertex_labels,
const cugraph_type_erased_device_array_view_t* label_list,
const cugraph_type_erased_device_array_view_t* label_to_comm_rank,
const cugraph_type_erased_host_array_view_t* fan_out,
cugraph_rng_state_t* rng_state,
bool_t with_replacement,
bool_t return_hops,
bool_t do_expensive_check,
cugraph_sample_result_t** result,
cugraph_error_t** error);
/**
* @brief Get the source vertices from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the source vertices in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_sources(
const cugraph_sample_result_t* result);
/**
* @brief Get the destination vertices from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the destination vertices in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_destinations(
const cugraph_sample_result_t* result);
/**
* @brief Get the start labels from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the start labels
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_start_labels(
const cugraph_sample_result_t* result);
/**
* @brief Get the edge_id from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the edge_id
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_edge_id(
const cugraph_sample_result_t* result);
/**
* @brief Get the edge_type from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the edge_type
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_edge_type(
const cugraph_sample_result_t* result);
/**
* @brief Get the edge_weight from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the edge_weight
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_edge_weight(
const cugraph_sample_result_t* result);
/**
* @brief Get the hop from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the hop
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_hop(
const cugraph_sample_result_t* result);
/**
* @brief Get the index from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the index
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_index(
const cugraph_sample_result_t* result);
/**
* @brief Get the result offsets from the sampling algorithm result
*
* @param [in] result The result from a sampling algorithm
* @return type erased array pointing to the result offsets
*/
cugraph_type_erased_device_array_view_t* cugraph_sample_result_get_offsets(
const cugraph_sample_result_t* result);
/**
* @brief Free a sampling result
*
* @param [in] result The result from a sampling algorithm
*/
void cugraph_sample_result_free(cugraph_sample_result_t* result);
/**
* @brief Create a sampling result (testing API)
*
* @param [in] handle Handle for accessing resources
* @param [in] srcs Device array view to populate srcs
* @param [in] dsts Device array view to populate dsts
* @param [in] edge_id Device array view to populate edge_id (can be NULL)
* @param [in] edge_type Device array view to populate edge_type (can be NULL)
* @param [in] wgt Device array view to populate wgt (can be NULL)
* @param [in] hop Device array view to populate hop
* @param [in] label Device array view to populate label (can be NULL)
* @param [out] result Pointer to the location to store the
* cugraph_sample_result_t*
* @param [out] error Pointer to an error object storing details of
* any error. Will be populated if error code is
* not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_test_sample_result_create(
const cugraph_resource_handle_t* handle,
const cugraph_type_erased_device_array_view_t* srcs,
const cugraph_type_erased_device_array_view_t* dsts,
const cugraph_type_erased_device_array_view_t* edge_id,
const cugraph_type_erased_device_array_view_t* edge_type,
const cugraph_type_erased_device_array_view_t* wgt,
const cugraph_type_erased_device_array_view_t* hop,
const cugraph_type_erased_device_array_view_t* label,
cugraph_sample_result_t** result,
cugraph_error_t** error);
/**
* @brief Create a sampling result (testing API)
*
* @param [in] handle Handle for accessing resources
* @param [in] srcs Device array view to populate srcs
* @param [in] dsts Device array view to populate dsts
* @param [in] edge_id Device array view to populate edge_id
* @param [in] edge_type Device array view to populate edge_type
* @param [in] weight Device array view to populate weight
* @param [in] hop Device array view to populate hop
* @param [in] label Device array view to populate label
* @param [out] result Pointer to the location to store the
* cugraph_sample_result_t*
* @param [out] error Pointer to an error object storing details of
* any error. Will be populated if error code is
* not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_test_uniform_neighborhood_sample_result_create(
const cugraph_resource_handle_t* handle,
const cugraph_type_erased_device_array_view_t* srcs,
const cugraph_type_erased_device_array_view_t* dsts,
const cugraph_type_erased_device_array_view_t* edge_id,
const cugraph_type_erased_device_array_view_t* edge_type,
const cugraph_type_erased_device_array_view_t* weight,
const cugraph_type_erased_device_array_view_t* hop,
const cugraph_type_erased_device_array_view_t* label,
cugraph_sample_result_t** result,
cugraph_error_t** error);
/**
* @brief Select random vertices from the graph
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in/out] rng_state State of the random number generator, updated with each call
* @param [in] num_vertices Number of vertices to sample
* @param [out] vertices Device array view to populate label
* @param [out] error Pointer to an error object storing details of
* any error. Will be populated if error code is
* not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_select_random_vertices(const cugraph_resource_handle_t* handle,
const cugraph_graph_t* graph,
cugraph_rng_state_t* rng_state,
size_t num_vertices,
cugraph_type_erased_device_array_t** vertices,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
| 18,375
| 42.752381
| 100
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/similarity_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/similarity_algorithms.h
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/array.h>
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/graph_functions.h>
#include <cugraph_c/resource_handle.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque similarity result type
*/
typedef struct {
int32_t align_;
} cugraph_similarity_result_t;
/**
* @brief Get the similarity coefficient array
*
* @param [in] result The result from a similarity algorithm
* @return type erased array of similarity coefficients
*/
cugraph_type_erased_device_array_view_t* cugraph_similarity_result_get_similarity(
cugraph_similarity_result_t* result);
/**
* @brief Free similarity result
*
* @param [in] result The result from a similarity algorithm
*/
void cugraph_similarity_result_free(cugraph_similarity_result_t* result);
/**
* @brief Perform Jaccard similarity computation
*
* Compute the similarity for the specified vertex_pairs
*
* Note that Jaccard similarity must run on a symmetric graph.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] vertex_pairs Vertex pair for input
* @param [in] use_weight If true consider the edge weight in the graph, if false use an
* edge weight of 1
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to similarity results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_jaccard_coefficients(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_vertex_pairs_t* vertex_pairs,
bool_t use_weight,
bool_t do_expensive_check,
cugraph_similarity_result_t** result,
cugraph_error_t** error);
/**
* @brief Perform Sorensen similarity computation
*
* Compute the similarity for the specified vertex_pairs
*
* Note that Sorensen similarity must run on a symmetric graph.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] vertex_pairs Vertex pair for input
* @param [in] use_weight If true consider the edge weight in the graph, if false use an
* edge weight of 1
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to similarity results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_sorensen_coefficients(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_vertex_pairs_t* vertex_pairs,
bool_t use_weight,
bool_t do_expensive_check,
cugraph_similarity_result_t** result,
cugraph_error_t** error);
/**
* @brief Perform overlap similarity computation
*
* Compute the similarity for the specified vertex_pairs
*
* Note that overlap similarity must run on a symmetric graph.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] vertex_pairs Vertex pair for input
* @param [in] use_weight If true consider the edge weight in the graph, if false use an
* edge weight of 1
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to similarity results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_overlap_coefficients(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_vertex_pairs_t* vertex_pairs,
bool_t use_weight,
bool_t do_expensive_check,
cugraph_similarity_result_t** result,
cugraph_error_t** error);
#ifdef __cplusplus
}
#endif
| 5,757
| 41.338235
| 96
|
h
|
cugraph-branch-23.08/cpp/include/cugraph_c/traversal_algorithms.h
|
cugraph-branch-23.08/cpp/include/cugraph_c/traversal_algorithms.h
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
/** @defgroup traversal Traversal Algorithms
* @ingroup c_api
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Opaque paths result type
*
* Store the output of BFS or SSSP, computing predecessors and distances
* from a seed.
*/
typedef struct {
int32_t align_;
} cugraph_paths_result_t;
/**
* @brief Get the vertex ids from the paths result
*
* @param [in] result The result from bfs or sssp
* @return type erased array of vertex ids
*/
cugraph_type_erased_device_array_view_t* cugraph_paths_result_get_vertices(
cugraph_paths_result_t* result);
/**
* @brief Get the distances from the paths result
*
* @param [in] result The result from bfs or sssp
* @return type erased array of distances
*/
cugraph_type_erased_device_array_view_t* cugraph_paths_result_get_distances(
cugraph_paths_result_t* result);
/**
* @brief Get the predecessors from the paths result
*
* @param [in] result The result from bfs or sssp
* @return type erased array of predecessors. Value will be NULL if
* compute_predecessors was FALSE in the call to bfs or sssp that
* produced this result.
*/
cugraph_type_erased_device_array_view_t* cugraph_paths_result_get_predecessors(
cugraph_paths_result_t* result);
/**
* @brief Free paths result
*
* @param [in] result The result from bfs or sssp
*/
void cugraph_paths_result_free(cugraph_paths_result_t* result);
/**
* @brief Perform a breadth first search from a set of seed vertices.
*
* This function computes the distances (minimum number of hops to reach the vertex) from the source
* vertex. If @p predecessors is not NULL, this function calculates the predecessor of each
* vertex (parent vertex in the breadth-first search tree) as well.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* FIXME: Make this just [in], copy it if I need to temporarily modify internally
* @param [in/out] sources Array of source vertices. NOTE: Array might be modified if
* renumbering is enabled for the graph
* @param [in] direction_optimizing If set to true, this algorithm switches between the push based
* breadth-first search and pull based breadth-first search depending on the size of the
* breadth-first search frontier (currently unsupported). This option is valid only for symmetric
* input graphs.
* @param depth_limit Sets the maximum number of breadth-first search iterations. Any vertices
* farther than @p depth_limit hops from @p source_vertex will be marked as unreachable.
* @param [in] compute_predecessors A flag to indicate whether to compute the predecessors in the
* result
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to paths results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_bfs(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
// FIXME: Make this const, copy it if I need to temporarily modify internally
cugraph_type_erased_device_array_view_t* sources,
bool_t direction_optimizing,
size_t depth_limit,
bool_t compute_predecessors,
bool_t do_expensive_check,
cugraph_paths_result_t** result,
cugraph_error_t** error);
/**
* @brief Perform single-source shortest-path to compute the minimum distances
* (and predecessors) from the source vertex.
*
* This function computes the distances (minimum edge weight sums) from the source
* vertex. If @p predecessors is not NULL, this function calculates the predecessor of each
* vertex (parent vertex in the breadth-first search tree) as well.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph
* @param [in] source Source vertex id
* @param [in] cutoff Maximum edge weight sum to consider
* @param [in] compute_predecessors A flag to indicate whether to compute the predecessors in the
* result
* @param [in] do_expensive_check A flag to run expensive checks for input arguments (if set to
* `true`).
* @param [out] result Opaque pointer to paths results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_sssp(const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
size_t source,
double cutoff,
bool_t compute_predecessors,
bool_t do_expensive_check,
cugraph_paths_result_t** result,
cugraph_error_t** error);
/**
* @brief Opaque extract_paths result type
*/
typedef struct {
int32_t align_;
} cugraph_extract_paths_result_t;
/**
* @brief Extract BFS or SSSP paths from a cugraph_paths_result_t
*
* This function extracts paths from the BFS or SSSP output. BFS and SSSP output
* distances and predecessors. The path from a vertex v back to the original
* source vertex can be extracted by recursively looking up the predecessor
* vertex until you arrive back at the original source vertex.
*
* @param [in] handle Handle for accessing resources
* @param [in] graph Pointer to graph. NOTE: Graph might be modified if the storage
* needs to be transposed
* @param [in] sources Array of source vertices
* @param [in] result Output from the BFS call
* @param [in] destinations Array of destination vertices.
* @param [out] result Opaque pointer to extract_paths results
* @param [out] error Pointer to an error object storing details of any error. Will
* be populated if error code is not CUGRAPH_SUCCESS
* @return error code
*/
cugraph_error_code_t cugraph_extract_paths(
const cugraph_resource_handle_t* handle,
cugraph_graph_t* graph,
const cugraph_type_erased_device_array_view_t* sources,
const cugraph_paths_result_t* paths_result,
const cugraph_type_erased_device_array_view_t* destinations,
cugraph_extract_paths_result_t** result,
cugraph_error_t** error);
/**
* @brief Get the max path length from extract_paths result
*
* @param [in] result The result from extract_paths
* @return maximum path length
*/
size_t cugraph_extract_paths_result_get_max_path_length(cugraph_extract_paths_result_t* result);
/**
* @brief Get the matrix (row major order) of paths
*
* @param [in] result The result from extract_paths
* @return type erased array pointing to the matrix in device memory
*/
cugraph_type_erased_device_array_view_t* cugraph_extract_paths_result_get_paths(
cugraph_extract_paths_result_t* result);
/**
* @brief Free extract_paths result
*
* @param [in] result The result from extract_paths
*/
void cugraph_extract_paths_result_free(cugraph_extract_paths_result_t* result);
#ifdef __cplusplus
}
#endif
/**
* @}
*/
| 8,105
| 37.056338
| 100
|
h
|
cugraph-branch-23.08/cpp/src/components/legacy/utils.h
|
cugraph-branch-23.08/cpp/src/components/legacy/utils.h
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cstdio>
#include <cuda_runtime.h>
#include <execinfo.h>
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <raft/util/cudart_utils.hpp>
#include <cugraph/utilities/error.hpp>
namespace MLCommon {
/** base exception class for the cuML or ml-prims project */
class Exception : public std::exception {
public:
/** default ctor */
Exception() throw() : std::exception(), msg() {}
/** copy ctor */
Exception(const Exception& src) throw() : std::exception(), msg(src.what())
{
collectCallStack();
}
/** ctor from an input message */
Exception(const std::string& _msg) throw() : std::exception(), msg(_msg) { collectCallStack(); }
/** dtor */
virtual ~Exception() throw() {}
/** get the message associated with this exception */
virtual const char* what() const throw() { return msg.c_str(); }
private:
/** message associated with this exception */
std::string msg;
/** append call stack info to this exception's message for ease of debug */
// Courtesy: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html
void collectCallStack() throw()
{
#ifdef __GNUC__
const int MaxStackDepth = 64;
void* stack[MaxStackDepth];
auto depth = backtrace(stack, MaxStackDepth);
std::ostringstream oss;
oss << std::endl << "Obtained " << depth << " stack frames" << std::endl;
std::unique_ptr<char*, decltype(&::free)> strings(backtrace_symbols(stack, depth), &::free);
if (strings.get() == nullptr) {
oss << "But no stack trace could be found!" << std::endl;
msg += oss.str();
return;
}
///@todo: support for demangling of C++ symbol names
for (int i = 0; i < depth; ++i) {
oss << "#" << i << " in " << strings.get()[i] << std::endl;
}
msg += oss.str();
#endif // __GNUC__
}
};
/**
* @brief Generic copy method for all kinds of transfers
* @tparam Type data type
* @param dst destination pointer
* @param src source pointer
* @param len lenth of the src/dst buffers in terms of number of elements
* @param stream cuda stream
*/
template <typename Type>
void copy(Type* dst, const Type* src, size_t len, cudaStream_t stream)
{
RAFT_CUDA_TRY(cudaMemcpyAsync(dst, src, len * sizeof(Type), cudaMemcpyDefault, stream));
}
/**
* @defgroup Copy Copy methods
* These are here along with the generic 'copy' method in order to improve
* code readability using explicitly specified function names
* @{
*/
/** performs a host to device copy */
template <typename Type>
void updateDevice(Type* dPtr, const Type* hPtr, size_t len, cudaStream_t stream)
{
copy(dPtr, hPtr, len, stream);
}
/** performs a device to host copy */
template <typename Type>
void updateHost(Type* hPtr, const Type* dPtr, size_t len, cudaStream_t stream)
{
copy(hPtr, dPtr, len, stream);
}
template <typename Type>
void copyAsync(Type* dPtr1, const Type* dPtr2, size_t len, cudaStream_t stream)
{
RAFT_CUDA_TRY(
cudaMemcpyAsync(dPtr1, dPtr2, len * sizeof(Type), cudaMemcpyDeviceToDevice, stream));
}
/** @} */
/** Helper function to calculate need memory for allocate to store dense matrix.
* @param rows number of rows in matrix
* @param columns number of columns in matrix
* @return need number of items to allocate via allocate()
* @sa allocate()
*/
inline size_t allocLengthForMatrix(size_t rows, size_t columns) { return rows * columns; }
/** Helper function to check alignment of pointer.
* @param ptr the pointer to check
* @param alignment to be checked for
* @return true if address in bytes is a multiple of alignment
*/
template <typename Type>
bool is_aligned(Type* ptr, size_t alignment)
{
return reinterpret_cast<uintptr_t>(ptr) % alignment == 0;
}
/** calculate greatest common divisor of two numbers
* @a integer
* @b integer
* @ return gcd of a and b
*/
template <typename IntType>
IntType gcd(IntType a, IntType b)
{
while (b != 0) {
IntType tmp = b;
b = a % b;
a = tmp;
}
return a;
}
/**
* @defgroup Debug utils for debug device code
* @{
*/
template <class T, class OutStream>
void myPrintHostVector(const char* variableName,
const T* hostMem,
size_t componentsCount,
OutStream& out)
{
out << variableName << "=[";
for (size_t i = 0; i < componentsCount; ++i) {
if (i != 0) out << ",";
out << hostMem[i];
}
out << "];\n";
}
template <class T>
void myPrintHostVector(const char* variableName, const T* hostMem, size_t componentsCount)
{
myPrintHostVector(variableName, hostMem, componentsCount, std::cout);
std::cout.flush();
}
template <class T, class OutStream>
void myPrintDevVector(const char* variableName,
const T* devMem,
size_t componentsCount,
OutStream& out)
{
std::vector<T> hostMem(componentsCount);
RAFT_CUDA_TRY(
cudaMemcpy(hostMem.data(), devMem, componentsCount * sizeof(T), cudaMemcpyDeviceToHost));
myPrintHostVector(variableName, hostMem.data(), componentsCount, out);
}
template <class T>
void myPrintDevVector(const char* variableName, const T* devMem, size_t componentsCount)
{
myPrintDevVector(variableName, devMem, componentsCount, std::cout);
std::cout.flush();
}
/** @} */
}; // end namespace MLCommon
| 5,979
| 27.888889
| 98
|
h
|
cugraph-branch-23.08/cpp/tests/c_api/betweenness_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/betweenness_centrality_test.c
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/random.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_betweenness_centrality_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
bool_t store_transposed,
bool_t is_symmetric,
bool_t normalized,
bool_t include_endpoints,
size_t num_vertices_to_sample)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
cugraph_rng_state_t* rng_state = NULL;
cugraph_type_erased_device_array_t* seeds = NULL;
cugraph_type_erased_device_array_view_t* seeds_view = NULL;
handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, handle != NULL, "resource handle creation failed.");
ret_code = cugraph_rng_state_create(handle, 0, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "failed to create rng_state.");
ret_code = create_test_graph(handle,
h_src,
h_dst,
h_wgt,
num_edges,
store_transposed,
FALSE,
is_symmetric,
&p_graph,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
if (h_seeds == NULL) {
ret_code = cugraph_select_random_vertices(
handle, p_graph, rng_state, num_vertices_to_sample, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "select random seeds failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
} else {
ret_code =
cugraph_type_erased_device_array_create(handle, num_seeds, INT32, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds create failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, seeds_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds copy_from_host failed.");
}
ret_code = cugraph_betweenness_centrality(
handle, p_graph, seeds_view, normalized, include_endpoints, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_betweenness_centrality failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.00001),
"centralities results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_type_erased_device_array_view_free(seeds_view);
cugraph_type_erased_device_array_free(seeds);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_betweenness_centrality_full()
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, 3.66667, 0.833333, 2.16667, 0.833333, 0.5};
return generic_betweenness_centrality_test(
h_src, h_dst, h_wgt, NULL, h_result, num_vertices, num_edges, 0, FALSE, TRUE, FALSE, FALSE, 6);
}
int test_betweenness_centrality_full_directed()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, 4, 0, 2, 1, 0};
return generic_betweenness_centrality_test(
h_src, h_dst, h_wgt, NULL, h_result, num_vertices, num_edges, 0, FALSE, FALSE, FALSE, FALSE, 6);
}
int test_betweenness_centrality_specific_normalized()
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_seeds[] = {0, 3};
weight_t h_result[] = {0, 0.475, 0.2, 0.1, 0.05, 0.075};
return generic_betweenness_centrality_test(h_src,
h_dst,
h_wgt,
h_seeds,
h_result,
num_vertices,
num_edges,
num_seeds,
FALSE,
FALSE,
TRUE,
FALSE,
num_seeds);
}
int test_betweenness_centrality_specific_unnormalized()
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_seeds[] = {0, 3};
weight_t h_result[] = {0, 3.16667, 1.33333, 0.666667, 0.333333, 0.5};
return generic_betweenness_centrality_test(h_src,
h_dst,
h_wgt,
h_seeds,
h_result,
num_vertices,
num_edges,
num_seeds,
FALSE,
FALSE,
FALSE,
FALSE,
num_seeds);
}
int test_betweenness_centrality_test_endpoints()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.166667, 0.3, 0.166667, 0.2, 0.166667, 0.166667};
return generic_betweenness_centrality_test(
h_src, h_dst, h_wgt, NULL, h_result, num_vertices, num_edges, 0, FALSE, FALSE, TRUE, TRUE, 6);
}
int test_betweenness_centrality_full_directed_normalized_karate()
{
size_t num_edges = 156;
size_t num_vertices = 34;
vertex_t h_src[] = {
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 2, 3, 7, 13, 17, 19, 21,
30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10, 6, 10, 16, 16, 30, 32, 33, 33, 33,
32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 31, 29, 33, 33,
31, 33, 32, 33, 32, 33, 32, 33, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4,
5, 5, 5, 6, 8, 8, 8, 9, 13, 14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23,
23, 23, 24, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32};
vertex_t h_dst[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 8, 8, 8, 9, 13,
14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 26, 26, 27,
28, 28, 29, 29, 30, 30, 31, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19,
21, 31, 2, 3, 7, 13, 17, 19, 21, 30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10,
6, 10, 16, 16, 30, 32, 33, 33, 33, 32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29,
32, 33, 25, 27, 31, 31, 29, 33, 33, 31, 33, 32, 33, 32, 33, 32, 33, 33};
weight_t h_wgt[] = {
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f};
weight_t h_result[] = {462.142914, 56.957146, 151.701584, 12.576191, 0.666667, 31.666668,
31.666668, 0.000000, 59.058739, 0.895238, 0.666667, 0.000000,
0.000000, 48.431747, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 34.293652, 0.000000, 0.000000, 0.000000, 18.600000,
2.333333, 4.055556, 0.000000, 23.584126, 1.895238, 3.085714,
15.219049, 146.019043, 153.380981, 321.103180};
return generic_betweenness_centrality_test(h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
FALSE,
FALSE,
FALSE,
34);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_betweenness_centrality_full);
result |= RUN_TEST(test_betweenness_centrality_full_directed);
result |= RUN_TEST(test_betweenness_centrality_specific_normalized);
result |= RUN_TEST(test_betweenness_centrality_specific_unnormalized);
result |= RUN_TEST(test_betweenness_centrality_test_endpoints);
result |= RUN_TEST(test_betweenness_centrality_full_directed_normalized_karate);
return result;
}
| 13,679
| 44.448505
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/bfs_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/bfs_test.c
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_bfs_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
vertex_t const* expected_distances,
vertex_t const* expected_predecessors,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
size_t depth_limit,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error = NULL;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_paths_result_t* p_result = NULL;
cugraph_type_erased_device_array_t* p_sources = NULL;
cugraph_type_erased_device_array_view_t* p_source_view = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &p_graph, &ret_error);
/*
* FIXME: in create_graph_test.c, variables are defined but then hard-coded to
* the constant INT32. It would be better to pass the types into the functions
* in both cases so that the test cases could be parameterized in the main.
*/
ret_code =
cugraph_type_erased_device_array_create(p_handle, num_seeds, INT32, &p_sources, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "p_sources create failed.");
p_source_view = cugraph_type_erased_device_array_view(p_sources);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, p_source_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_bfs(
p_handle, p_graph, p_source_view, FALSE, depth_limit, TRUE, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_bfs failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* distances;
cugraph_type_erased_device_array_view_t* predecessors;
vertices = cugraph_paths_result_get_vertices(p_result);
distances = cugraph_paths_result_get_distances(p_result);
predecessors = cugraph_paths_result_get_predecessors(p_result);
vertex_t h_vertices[num_vertices];
vertex_t h_distances[num_vertices];
vertex_t h_predecessors[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_distances, distances, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_predecessors, predecessors, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
expected_distances[h_vertices[i]] == h_distances[i],
"bfs distances don't match");
TEST_ASSERT(test_ret_value,
expected_predecessors[h_vertices[i]] == h_predecessors[i],
"bfs predecessors don't match");
}
cugraph_type_erased_device_array_free(p_sources);
cugraph_paths_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_bfs_exceptions()
{
size_t num_edges = 8;
size_t num_vertices = 6;
size_t depth_limit = 1;
size_t num_seeds = 1;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
int64_t seeds[] = {0};
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error = NULL;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_paths_result_t* p_result = NULL;
cugraph_type_erased_device_array_t* p_sources = NULL;
cugraph_type_erased_device_array_view_t* p_source_view = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, src, dst, wgt, num_edges, FALSE, FALSE, FALSE, &p_graph, &ret_error);
/*
* FIXME: in create_graph_test.c, variables are defined but then hard-coded to
* the constant INT32. It would be better to pass the types into the functions
* in both cases so that the test cases could be parameterized in the main.
*/
ret_code =
cugraph_type_erased_device_array_create(p_handle, num_seeds, INT64, &p_sources, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "p_sources create failed.");
p_source_view = cugraph_type_erased_device_array_view(p_sources);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, p_source_view, (byte_t*)seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_bfs(
p_handle, p_graph, p_source_view, FALSE, depth_limit, TRUE, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_INVALID_INPUT, "cugraph_bfs expected to fail");
return test_ret_value;
}
int test_bfs()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t seeds[] = {0};
vertex_t expected_distances[] = {0, 1, 2147483647, 2, 2, 3};
vertex_t expected_predecessors[] = {-1, 0, -1, 1, 1, 3};
// Bfs wants store_transposed = FALSE
return generic_bfs_test(src,
dst,
wgt,
seeds,
expected_distances,
expected_predecessors,
num_vertices,
num_edges,
1,
10,
FALSE);
}
int test_bfs_with_transpose()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t seeds[] = {0};
vertex_t expected_distances[] = {0, 1, 2147483647, 2, 2, 3};
vertex_t expected_predecessors[] = {-1, 0, -1, 1, 1, 3};
// Bfs wants store_transposed = FALSE
// This call will force cugraph_bfs to transpose the graph
return generic_bfs_test(src,
dst,
wgt,
seeds,
expected_distances,
expected_predecessors,
num_vertices,
num_edges,
1,
10,
TRUE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_bfs);
result |= RUN_TEST(test_bfs_with_transpose);
result |= RUN_TEST(test_bfs_exceptions);
return result;
}
| 8,806
| 36.636752
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/c_test_utils.h
|
cugraph-branch-23.08/cpp/tests/c_api/c_test_utils.h
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cugraph_c/error.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/resource_handle.h>
#include <cuda_runtime_api.h>
#include <stdio.h>
#include <time.h>
#define TEST_ASSERT(RETURN_VALUE, STATEMENT, MESSAGE) \
{ \
if (!(RETURN_VALUE)) { \
(RETURN_VALUE) = !(STATEMENT); \
if ((RETURN_VALUE)) { printf("ASSERTION FAILED: %s\n", (MESSAGE)); } \
} \
}
#define TEST_ALWAYS_ASSERT(STATEMENT, MESSAGE) \
{ \
int tmp = !(STATEMENT); \
if (tmp) { printf("ASSERTION FAILED: %s\n", (MESSAGE)); } \
}
#ifdef __cplusplus
extern "C" {
#endif
/*
* Runs the function pointed to by "test" and returns the return code. Also
* prints reporting info (using "test_name"): pass/fail and run time, to stdout.
*
* Intended to be used by the RUN_TEST macro.
*/
int run_sg_test(int (*test)(), const char* test_name);
#define RUN_TEST(test_name) run_sg_test(test_name, #test_name)
int run_sg_test_new(int (*test)(const cugraph_resource_handle_t*),
const char* test_name,
const cugraph_resource_handle_t* handle);
#define RUN_TEST_NEW(test_name, handle) run_sg_test_new(test_name, #test_name, handle)
int nearlyEqual(float a, float b, float epsilon);
int nearlyEqualDouble(double a, double b, double epsilon);
int create_test_graph(const cugraph_resource_handle_t* p_handle,
int32_t* h_src,
int32_t* h_dst,
float* h_wgt,
size_t num_edges,
bool_t store_transposed,
bool_t renumber,
bool_t is_symmetric,
cugraph_graph_t** p_graph,
cugraph_error_t** ret_error);
int create_test_graph_double(const cugraph_resource_handle_t* p_handle,
int32_t* h_src,
int32_t* h_dst,
double* h_wgt,
size_t num_edges,
bool_t store_transposed,
bool_t renumber,
bool_t is_symmetric,
cugraph_graph_t** p_graph,
cugraph_error_t** ret_error);
int create_sg_test_graph(const cugraph_resource_handle_t* handle,
data_type_id_t vertex_tid,
data_type_id_t edge_tid,
void* h_src,
void* h_dst,
data_type_id_t weight_tid,
void* h_wgt,
data_type_id_t edge_type_tid,
void* h_edge_type,
data_type_id_t edge_id_tid,
void* h_edge_id,
size_t num_edges,
bool_t store_transposed,
bool_t renumber,
bool_t is_symmetric,
bool_t is_multigraph,
cugraph_graph_t** graph,
cugraph_error_t** ret_error);
#ifdef __cplusplus
}
#endif
| 4,111
| 37.429907
| 86
|
h
|
cugraph-branch-23.08/cpp/tests/c_api/core_number_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/core_number_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/array.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_core_number_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_core_result_t* p_result = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, TRUE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_core_number(p_handle, p_graph, K_CORE_DEGREE_TYPE_IN, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_core_number failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* core_numbers;
vertices = cugraph_core_result_get_vertices(p_result);
core_numbers = cugraph_core_result_get_core_numbers(p_result);
vertex_t h_vertices[num_vertices];
vertex_t h_core_numbers[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_core_numbers, core_numbers, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_core_numbers[i], 0.001),
"core number results don't match");
}
cugraph_core_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_core_number()
{
size_t num_edges = 22;
size_t num_vertices = 7;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5, 3, 1, 4, 5, 5, 6};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4, 4, 5, 3, 1, 6, 5};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
vertex_t h_result[] = {2, 3, 2, 3, 3, 3, 1};
return generic_core_number_test(h_src, h_dst, h_wgt, h_result, num_vertices, num_edges, FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_core_number);
return result;
}
| 4,075
| 35.392857
| 105
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/edge_betweenness_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/edge_betweenness_centrality_test.c
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <cugraph_c/random.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_edge_betweenness_centrality_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
bool_t store_transposed,
size_t num_vertices_to_sample)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* handle = NULL;
cugraph_graph_t* graph = NULL;
cugraph_edge_centrality_result_t* result = NULL;
cugraph_rng_state_t* rng_state = NULL;
cugraph_type_erased_device_array_t* seeds = NULL;
cugraph_type_erased_device_array_view_t* seeds_view = NULL;
handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, handle != NULL, "resource handle creation failed.");
ret_code = cugraph_rng_state_create(handle, 0, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "failed to create rng_state.");
ret_code = create_test_graph(handle,
h_src,
h_dst,
h_wgt,
num_edges,
store_transposed,
FALSE,
FALSE,
&graph,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
if (h_seeds == NULL) {
ret_code = cugraph_select_random_vertices(
handle, graph, rng_state, num_vertices_to_sample, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "select random seeds failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
} else {
ret_code =
cugraph_type_erased_device_array_create(handle, num_seeds, INT32, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds create failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, seeds_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds copy_from_host failed.");
}
ret_code = cugraph_edge_betweenness_centrality(
handle, graph, seeds_view, FALSE, FALSE, &result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_edge_betweenness_centrality failed.");
cugraph_type_erased_device_array_view_t* srcs;
cugraph_type_erased_device_array_view_t* dsts;
cugraph_type_erased_device_array_view_t* centralities;
srcs = cugraph_edge_centrality_result_get_src_vertices(result);
dsts = cugraph_edge_centrality_result_get_dst_vertices(result);
centralities = cugraph_edge_centrality_result_get_values(result);
size_t num_local_edges = cugraph_type_erased_device_array_view_size(srcs);
vertex_t h_cugraph_src[num_local_edges];
vertex_t h_cugraph_dst[num_local_edges];
weight_t h_centralities[num_local_edges];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_cugraph_src, srcs , &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_cugraph_dst, dsts, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
weight_t M[num_vertices][num_vertices];
for (int i = 0; i < num_vertices; ++i)
for (int j = 0; j < num_vertices; ++j) {
M[i][j] = 0.0;
}
for (int i = 0; i < num_edges; ++i) {
M[h_src[i]][h_dst[i]] = h_result[i];
}
for (int i = 0; (i < num_local_edges) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(M[h_cugraph_src[i]][h_cugraph_dst[i]], h_centralities[i], 0.001),
"betweenness centrality results don't match");
}
cugraph_edge_centrality_result_free(result);
cugraph_sg_graph_free(graph);
cugraph_free_resource_handle(handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_edge_betweenness_centrality()
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = { 0, 2, 3, 1.83333, 2, 2, 3, 2, 3.16667, 2.83333, 4.33333, 0, 2, 2.83333, 3.66667, 2.33333 };
double epsilon = 1e-6;
size_t max_iterations = 200;
// Eigenvector centrality wants store_transposed = TRUE
return generic_edge_betweenness_centrality_test(
h_src, h_dst, h_wgt, NULL, h_result, num_vertices, num_edges, 0, TRUE, 5);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_edge_betweenness_centrality);
return result;
}
| 6,846
| 38.578035
| 117
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/eigenvector_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/eigenvector_centrality_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_eigenvector_centrality_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_eigenvector_centrality(
p_handle, p_graph, epsilon, max_iterations, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_eigenvector_centrality failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.001),
"centralities results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_eigenvector_centrality()
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.236325, 0.292055, 0.458457, 0.60533, 0.190498, 0.495942};
double epsilon = 1e-6;
size_t max_iterations = 200;
// Eigenvector centrality wants store_transposed = TRUE
return generic_eigenvector_centrality_test(
h_src, h_dst, h_wgt, h_result, num_vertices, num_edges, TRUE, epsilon, max_iterations);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_eigenvector_centrality);
return result;
}
| 4,460
| 36.175
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/extract_paths_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/extract_paths_test.c
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_bfs_test_with_extract_paths(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
vertex_t* h_destinations,
vertex_t expected_max_path_length,
vertex_t const* expected_paths,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
size_t num_destinations,
size_t depth_limit,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_paths_result_t* p_paths_result = NULL;
cugraph_extract_paths_result_t* p_extract_paths_result = NULL;
cugraph_type_erased_device_array_t* p_sources = NULL;
cugraph_type_erased_device_array_t* p_destinations = NULL;
cugraph_type_erased_device_array_view_t* p_sources_view = NULL;
cugraph_type_erased_device_array_view_t* p_destinations_view = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &p_graph, &ret_error);
ret_code =
cugraph_type_erased_device_array_create(p_handle, num_seeds, INT32, &p_sources, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "p_sources create failed.");
p_sources_view = cugraph_type_erased_device_array_view(p_sources);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, p_sources_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_create(
p_handle, num_destinations, INT32, &p_destinations, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "p_destinations create failed.");
p_destinations_view = cugraph_type_erased_device_array_view(p_destinations);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, p_destinations_view, (byte_t*)h_destinations, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_bfs(p_handle,
p_graph,
p_sources_view,
FALSE,
depth_limit,
TRUE,
FALSE,
&p_paths_result,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_bfs failed.");
ret_code = cugraph_extract_paths(p_handle,
p_graph,
p_sources_view,
p_paths_result,
p_destinations_view,
&p_extract_paths_result,
&ret_error);
size_t max_path_length = cugraph_extract_paths_result_get_max_path_length(p_extract_paths_result);
TEST_ASSERT(
test_ret_value, max_path_length == expected_max_path_length, "path lengths don't match");
cugraph_type_erased_device_array_view_t* paths_view =
cugraph_extract_paths_result_get_paths(p_extract_paths_result);
size_t paths_size = cugraph_type_erased_device_array_view_size(paths_view);
vertex_t h_paths[paths_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_paths, paths_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < paths_size) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value, expected_paths[i] == h_paths[i], "paths don't match");
}
cugraph_type_erased_device_array_view_free(paths_view);
cugraph_type_erased_device_array_view_free(p_sources_view);
cugraph_type_erased_device_array_view_free(p_destinations_view);
cugraph_type_erased_device_array_free(p_sources);
cugraph_type_erased_device_array_free(p_destinations);
cugraph_extract_paths_result_free(p_extract_paths_result);
cugraph_paths_result_free(p_paths_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_bfs_with_extract_paths()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t seeds[] = {0};
vertex_t destinations[] = {5};
vertex_t expected_max_path_length = 4;
vertex_t expected_paths[] = {0, 1, 3, 5};
// Bfs wants store_transposed = FALSE
return generic_bfs_test_with_extract_paths(src,
dst,
wgt,
seeds,
destinations,
expected_max_path_length,
expected_paths,
num_vertices,
num_edges,
1,
1,
10,
FALSE);
}
int test_bfs_with_extract_paths_with_transpose()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t seeds[] = {0};
vertex_t destinations[] = {5};
vertex_t expected_max_path_length = 4;
vertex_t expected_paths[] = {0, 1, 3, 5};
// Bfs wants store_transposed = FALSE
// This call will force cugraph_bfs to transpose the graph
return generic_bfs_test_with_extract_paths(src,
dst,
wgt,
seeds,
destinations,
expected_max_path_length,
expected_paths,
num_vertices,
num_edges,
1,
1,
10,
TRUE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_bfs_with_extract_paths);
result |= RUN_TEST(test_bfs_with_extract_paths_with_transpose);
return result;
}
| 8,529
| 41.227723
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/generate_rmat_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/generate_rmat_test.c
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/graph_generators.h>
#include <stdio.h>
/*
* Simple rmat generator test
*/
int test_rmat_generation()
{
int test_ret_value = 0;
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
vertex_t expected_src[] = { 17, 18, 0, 16, 1, 24, 16, 1, 6, 4, 2, 1, 14, 2, 16, 2, 5, 23, 4, 10, 4, 3, 0, 4, 11, 0, 0, 2, 24, 0};
vertex_t expected_dst[] = { 0, 10, 23, 0, 26, 0, 2, 1, 27, 8, 1, 0, 21, 21, 0, 4, 8, 14, 10, 17, 0, 16, 0, 16, 25, 5, 8, 8, 4, 19};
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* handle = NULL;
cugraph_rng_state_t *rng_state = NULL;;
cugraph_coo_t *coo = NULL;
handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, handle != NULL, "resource handle creation failed.");
ret_code = cugraph_rng_state_create(handle, 0, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_generate_rmat_edgelist(handle,
rng_state,
5,
30,
0.57,
0.19,
0.19,
FALSE,
&coo,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "generate_rmat_edgelist failed.");
cugraph_type_erased_device_array_view_t* src_view;
cugraph_type_erased_device_array_view_t* dst_view;
src_view = cugraph_coo_get_sources(coo);
dst_view = cugraph_coo_get_destinations(coo);
size_t src_size = cugraph_type_erased_device_array_view_size(src_view);
vertex_t h_src[src_size];
vertex_t h_dst[src_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_src, src_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_dst, dst_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst copy_to_host failed.");
for (int i = 0 ; i < src_size ; ++i) {
TEST_ASSERT(test_ret_value,
expected_src[i] == h_src[i],
"generated edges don't match");
TEST_ASSERT(test_ret_value,
expected_dst[i] == h_dst[i],
"generated edges don't match");
}
cugraph_type_erased_device_array_view_free(dst_view);
cugraph_type_erased_device_array_view_free(src_view);
cugraph_coo_free(coo);
cugraph_free_resource_handle(handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_rmat_list_generation()
{
int test_ret_value = 0;
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* handle = NULL;
cugraph_rng_state_t *rng_state = NULL;;
cugraph_coo_list_t *coo_list = NULL;
handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, handle != NULL, "resource handle creation failed.");
ret_code = cugraph_rng_state_create(handle, 0, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
//
// NOTE: We can't exactly compare results for functions that make multiple RNG calls
// within them. When the RNG state is advanced, it is advanced by a multiple of
// the number of possible threads involved, not based on how many of the values
// were actually used. So different GPU versions will result in subtly different
// random sequences.
//
size_t num_lists = 3;
vertex_t max_vertex_id[] = { 32, 16, 32 };
size_t expected_len[] = { 20, 16, 20 };
ret_code = cugraph_rng_state_create(handle, 0, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_generate_rmat_edgelists(handle,
rng_state,
num_lists,
4,
6,
4,
UNIFORM,
POWER_LAW,
FALSE,
&coo_list,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "generate_rmat_edgelist failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(test_ret_value, cugraph_coo_list_size(coo_list) == num_lists, "generated wrong number of results");
for (size_t i = 0 ; (i < num_lists) && (test_ret_value == 0) ; i++) {
cugraph_coo_t *coo = NULL;
coo = cugraph_coo_list_element(coo_list, i);
cugraph_type_erased_device_array_view_t* src_view;
cugraph_type_erased_device_array_view_t* dst_view;
src_view = cugraph_coo_get_sources(coo);
dst_view = cugraph_coo_get_destinations(coo);
size_t src_size = cugraph_type_erased_device_array_view_size(src_view);
TEST_ASSERT(test_ret_value, src_size == expected_len[i], "wrong number of edges");
vertex_t h_src[src_size];
vertex_t h_dst[src_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_src, src_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_dst, dst_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst copy_to_host failed.");
for (size_t j = 0 ; (j < src_size) && (test_ret_value == 0) ; ++j) {
TEST_ASSERT(test_ret_value,
h_src[j] < max_vertex_id[i],
"generated edges don't match");
TEST_ASSERT(test_ret_value,
h_dst[j] < max_vertex_id[i],
"generated edges don't match");
}
cugraph_type_erased_device_array_view_free(dst_view);
cugraph_type_erased_device_array_view_free(src_view);
}
cugraph_coo_list_free(coo_list);
cugraph_free_resource_handle(handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_rmat_generation);
result |= RUN_TEST(test_rmat_list_generation);
return result;
}
| 7,824
| 36.620192
| 134
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/hits_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/hits_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_hits_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
size_t num_vertices,
size_t num_edges,
vertex_t* h_initial_vertices,
weight_t* h_initial_hubs,
size_t num_initial_vertices,
weight_t* h_result_hubs,
weight_t* h_result_authorities,
bool_t store_transposed,
bool_t renumber,
bool_t normalize,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_hits_result_t* p_result = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, renumber, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
if (h_initial_vertices == NULL) {
ret_code = cugraph_hits(p_handle,
p_graph,
epsilon,
max_iterations,
NULL,
NULL,
normalize,
FALSE,
&p_result,
&ret_error);
} else {
cugraph_type_erased_device_array_t* initial_vertices;
cugraph_type_erased_device_array_t* initial_hubs;
cugraph_type_erased_device_array_view_t* initial_vertices_view;
cugraph_type_erased_device_array_view_t* initial_hubs_view;
ret_code = cugraph_type_erased_device_array_create(
p_handle, num_initial_vertices, INT32, &initial_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "initial_vertices create failed.");
ret_code = cugraph_type_erased_device_array_create(
p_handle, num_initial_vertices, FLOAT32, &initial_hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "initial_hubs create failed.");
initial_vertices_view = cugraph_type_erased_device_array_view(initial_vertices);
initial_hubs_view = cugraph_type_erased_device_array_view(initial_hubs);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, initial_vertices_view, (byte_t*)h_initial_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, initial_hubs_view, (byte_t*)h_initial_hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_hits(p_handle,
p_graph,
epsilon,
max_iterations,
initial_vertices_view,
initial_hubs_view,
normalize,
FALSE,
&p_result,
&ret_error);
}
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_hits failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* hubs;
cugraph_type_erased_device_array_view_t* authorities;
vertices = cugraph_hits_result_get_vertices(p_result);
hubs = cugraph_hits_result_get_hubs(p_result);
authorities = cugraph_hits_result_get_authorities(p_result);
double score_differences = cugraph_hits_result_get_hub_score_differences(p_result);
size_t num_iterations = cugraph_hits_result_get_number_of_iterations(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_hubs[num_vertices];
weight_t h_authorities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code =
cugraph_type_erased_device_array_view_copy_to_host(p_handle, (byte_t*)h_hubs, hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_authorities, authorities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result_hubs[h_vertices[i]], h_hubs[i], 0.001),
"hubs results don't match");
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result_authorities[h_vertices[i]], h_authorities[i], 0.001),
"authorities results don't match");
}
cugraph_hits_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_hits()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608, 0};
weight_t h_authorities[] = {0.652703, 0.879385, 0, 1, 0.347296, 0.00009136};
double epsilon = 0.0001;
size_t max_iterations = 20;
// hits wants store_transposed = TRUE
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
TRUE,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_with_transpose()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608, 0};
weight_t h_authorities[] = {0.652703, 0.879385, 0, 1, 0.347296, 0.00009136};
double epsilon = 0.0001;
size_t max_iterations = 20;
// Hits wants store_transposed = TRUE
// This call will force cugraph_hits to transpose the graph
// But we're passing src/dst backwards so the results will be the same
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_with_initial()
{
size_t num_edges = 8;
size_t num_vertices = 6;
size_t num_initial_hubs = 5;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00000959, 0.00000959, 0};
weight_t h_authorities[] = {0.652704, 0.879385, 0, 1, 0.347296, 0.00002428};
vertex_t h_initial_vertices[] = {0, 1, 2, 3, 4};
weight_t h_initial_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608};
double epsilon = 0.0001;
size_t max_iterations = 20;
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
h_initial_vertices,
h_initial_hubs,
num_initial_hubs,
h_hubs,
h_authorities,
FALSE,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_bigger()
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {0, 0, 0, 0, 0, 0, 0.323569, 0, 0.156401, 0, 0,
0, 0, 0, 0, 0, 0.253312, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.110617, 0, 0, 0,
0, 0, 0, 0, 0, 0.365733, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0.156401, 0, 0, 0, 0, 0.0782005};
weight_t h_authorities[] = {0, 0, 0, 0, 0, 0, 0.321874, 0, 0.123424, 0, 0,
0, 0, 0, 0, 0, 0.595522, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.0292397, 0, 0, 0,
0, 0, 0, 0, 0, 0.314164, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0.100368};
double epsilon = 0.000001;
size_t max_iterations = 100;
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_bigger_unnormalized()
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {0, 0, 0, 0, 0, 0, 0.323569, 0, 0.156401, 0, 0,
0, 0, 0, 0, 0, 0.253312, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.110617, 0, 0, 0,
0, 0, 0, 0, 0, 0.365733, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0.156401, 0, 0, 0, 0, 0.0782005};
weight_t h_authorities[] = {0, 0, 0, 0, 0, 0, 0.321874, 0, 0.123424, 0, 0,
0, 0, 0, 0, 0, 0.595522, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.0292397, 0, 0, 0,
0, 0, 0, 0, 0, 0.314164, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0.100368};
double epsilon = 0.000001;
size_t max_iterations = 100;
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_bigger_normalized()
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {
0, 0, 0, 0, 0, 0, 0.132381, 0, 0.0639876, 0, 0, 0, 0, 0,
0, 0, 0.103637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.0452563, 0, 0, 0, 0, 0, 0, 0, 0, 0.149631, 0, 0, 0,
0, 0, 0, 0.409126, 0, 0, 0.0639876, 0, 0, 0, 0, 0.0319938};
weight_t h_authorities[] = {
0, 0, 0, 0, 0, 0, 0.129548, 0, 0.0496755, 0, 0, 0, 0, 0,
0, 0, 0.239688, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.0117691, 0, 0, 0, 0, 0, 0, 0, 0, 0.126445, 0, 0, 0,
0, 0, 0, 0.402479, 0, 0, 0, 0, 0, 0, 0, 0.0403963};
double epsilon = 0.000001;
size_t max_iterations = 100;
return generic_hits_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
TRUE,
epsilon,
max_iterations);
}
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_hits);
result |= RUN_TEST(test_hits_with_transpose);
result |= RUN_TEST(test_hits_with_initial);
result |= RUN_TEST(test_hits_bigger);
result |= RUN_TEST(test_hits_bigger_normalized);
result |= RUN_TEST(test_hits_bigger_unnormalized);
return result;
}
| 17,633
| 42.326781
| 103
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/induced_subgraph_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/induced_subgraph_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/graph.h>
#include <cugraph_c/graph_functions.h>
#include <stdio.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
/*
* Simple check of creating a graph from a COO on device memory.
*/
int generic_induced_subgraph_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
size_t* h_subgraph_offsets,
vertex_t* h_subgraph_vertices,
size_t num_subgraph_offsets,
vertex_t* h_result_src,
vertex_t* h_result_dst,
weight_t* h_result_wgt,
size_t* h_result_offsets,
size_t num_results)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* handle = NULL;
cugraph_graph_t* graph = NULL;
cugraph_type_erased_device_array_t* subgraph_offsets = NULL;
cugraph_type_erased_device_array_t* subgraph_vertices = NULL;
cugraph_type_erased_device_array_view_t* subgraph_offsets_view = NULL;
cugraph_type_erased_device_array_view_t* subgraph_vertices_view = NULL;
cugraph_induced_subgraph_result_t* result = NULL;
data_type_id_t vertex_tid = INT32;
data_type_id_t size_t_tid = SIZE_T;
handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_type_erased_device_array_create(
handle, num_subgraph_offsets, size_t_tid, &subgraph_offsets, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets create failed.");
ret_code = cugraph_type_erased_device_array_create(handle,
h_subgraph_offsets[num_subgraph_offsets - 1],
vertex_tid,
&subgraph_vertices,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets create failed.");
subgraph_offsets_view = cugraph_type_erased_device_array_view(subgraph_offsets);
subgraph_vertices_view = cugraph_type_erased_device_array_view(subgraph_vertices);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, subgraph_offsets_view, (byte_t*)h_subgraph_offsets, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, subgraph_vertices_view, (byte_t*)h_subgraph_vertices, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_vertices copy_from_host failed.");
ret_code = cugraph_extract_induced_subgraph(
handle, graph, subgraph_offsets_view, subgraph_vertices_view, FALSE, &result, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_extract_induced_subgraph failed.");
cugraph_type_erased_device_array_view_t* extracted_src;
cugraph_type_erased_device_array_view_t* extracted_dst;
cugraph_type_erased_device_array_view_t* extracted_wgt;
cugraph_type_erased_device_array_view_t* extracted_graph_offsets;
extracted_src = cugraph_induced_subgraph_get_sources(result);
extracted_dst = cugraph_induced_subgraph_get_destinations(result);
extracted_wgt = cugraph_induced_subgraph_get_edge_weights(result);
extracted_graph_offsets = cugraph_induced_subgraph_get_subgraph_offsets(result);
size_t extracted_size = cugraph_type_erased_device_array_view_size(extracted_src);
vertex_t h_extracted_src[extracted_size];
vertex_t h_extracted_dst[extracted_size];
weight_t h_extracted_wgt[extracted_size];
size_t h_extracted_graph_offsets[num_subgraph_offsets];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_src, extracted_src, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_dst, extracted_dst, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_wgt, extracted_wgt, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_graph_offsets, extracted_graph_offsets, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
TEST_ASSERT(test_ret_value, extracted_size == num_results, "results not the same size");
for (size_t i = 0; (i < num_subgraph_offsets) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
h_extracted_graph_offsets[i] == h_result_offsets[i],
"graph offsets should match");
}
for (size_t i = 0; (i < num_results) && (test_ret_value == 0); ++i) {
bool_t found = FALSE;
for (size_t j = 0; (j < num_results) && !found; ++j) {
if ((h_extracted_src[i] == h_result_src[j]) && (h_extracted_dst[i] == h_result_dst[j]) &&
(nearlyEqual(h_extracted_wgt[i], h_result_wgt[j], 0.001)))
found = TRUE;
}
TEST_ASSERT(test_ret_value, found, "extracted an edge that doesn't match");
}
return test_ret_value;
}
int test_induced_subgraph()
{
size_t num_edges = 8;
size_t num_vertices = 6;
size_t num_subgraph_offsets = 2;
size_t num_results = 5;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
size_t h_subgraph_offsets[] = {0, 4};
vertex_t h_subgraph_vertices[] = {0, 1, 2, 3};
vertex_t h_result_src[] = {0, 1, 2, 2, 2};
vertex_t h_result_dst[] = {1, 3, 0, 1, 3};
weight_t h_result_wgt[] = {0.1f, 2.1f, 5.1f, 3.1f, 4.1f};
size_t h_result_offsets[] = {0, 5};
return generic_induced_subgraph_test(h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
FALSE,
h_subgraph_offsets,
h_subgraph_vertices,
num_subgraph_offsets,
h_result_src,
h_result_dst,
h_result_wgt,
h_result_offsets,
num_results);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_induced_subgraph);
return result;
}
| 8,557
| 42.663265
| 98
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/katz_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/katz_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/array.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_katz_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
double alpha,
double beta,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
cugraph_type_erased_device_array_view_t* betas_view = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_katz_centrality(p_handle,
p_graph,
betas_view,
alpha,
beta,
epsilon,
max_iterations,
FALSE,
&p_result,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_katz_centrality failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.001),
"katz centrality results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_katz()
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.410614, 0.403211, 0.390689, 0.415175, 0.395125, 0.433226};
double alpha = 0.01;
double beta = 1.0;
double epsilon = 0.000001;
size_t max_iterations = 1000;
// Katz wants store_transposed = TRUE
return generic_katz_test(h_src,
h_dst,
h_wgt,
h_result,
num_vertices,
num_edges,
TRUE,
alpha,
beta,
epsilon,
max_iterations);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_katz);
return result;
}
| 4,927
| 34.2
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/legacy_ecg_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/legacy_ecg_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_ecg_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_result,
size_t num_vertices,
size_t num_edges,
double minimum_weight,
size_t ensemble_size,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_hierarchical_clustering_result_t* p_result = NULL;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = create_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code =
cugraph_ecg(p_handle, p_graph, minimum_weight, ensemble_size, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, "cugraph_ecg failed.");
if (test_ret_value == 0) {
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* clusters;
vertices = cugraph_hierarchical_clustering_result_get_vertices(p_result);
clusters = cugraph_hierarchical_clustering_result_get_clusters(p_result);
vertex_t h_vertices[num_vertices];
edge_t h_clusters[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_clusters, clusters, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(
test_ret_value, h_result[h_vertices[i]] == h_clusters[i], "cluster results don't match");
}
cugraph_hierarchical_clustering_result_free(p_result);
}
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_ecg()
{
size_t num_edges = 8;
size_t num_vertices = 6;
weight_t min_weight = 0.05;
size_t ensemble_size = 16;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_result[] = {0, 1, 0, 1, 1, 1};
// Louvain wants store_transposed = FALSE
return generic_ecg_test(h_src,
h_dst,
h_wgt,
h_result,
num_vertices,
num_edges,
min_weight,
ensemble_size,
FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_ecg);
return result;
}
| 4,428
| 33.601563
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/leiden_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/leiden_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_leiden_test(vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_result,
weight_t expected_modularity,
size_t num_vertices,
size_t num_edges,
size_t max_level,
double resolution,
double theta,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_resource_handle_t* p_handle = NULL;
cugraph_rng_state_t* p_rng_state = NULL;
cugraph_graph_t* p_graph = NULL;
cugraph_hierarchical_clustering_result_t* p_result = NULL;
data_type_id_t vertex_tid = INT32;
data_type_id_t edge_tid = INT32;
data_type_id_t weight_tid = FLOAT32;
data_type_id_t edge_id_tid = INT32;
data_type_id_t edge_type_tid = INT32;
p_handle = cugraph_create_resource_handle(NULL);
TEST_ASSERT(test_ret_value, p_handle != NULL, "resource handle creation failed.");
ret_code = cugraph_rng_state_create(p_handle, 0, &p_rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = create_sg_test_graph(p_handle,
vertex_tid,
edge_tid,
h_src,
h_dst,
weight_tid,
h_wgt,
edge_type_tid,
NULL,
edge_id_tid,
NULL,
num_edges,
store_transposed,
FALSE,
FALSE,
FALSE,
&p_graph,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_leiden(
p_handle, p_rng_state, p_graph, max_level, resolution, theta, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, "cugraph_leiden failed.");
if (test_ret_value == 0) {
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* clusters;
vertices = cugraph_hierarchical_clustering_result_get_vertices(p_result);
clusters = cugraph_hierarchical_clustering_result_get_clusters(p_result);
double modularity = cugraph_hierarchical_clustering_result_get_modularity(p_result);
vertex_t h_vertices[num_vertices];
edge_t h_clusters[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_clusters, clusters, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
TEST_ASSERT(test_ret_value,
nearlyEqual(modularity, expected_modularity, 0.001),
"modularity doesn't match");
cugraph_hierarchical_clustering_result_free(p_result);
}
cugraph_sg_graph_free(p_graph);
cugraph_free_resource_handle(p_handle);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_leiden()
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t max_level = 10;
weight_t resolution = 1.0;
weight_t theta = 1.0;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_result[] = {0, 0, 0, 1, 1, 1};
weight_t expected_modularity = 0.215969;
// Louvain wants store_transposed = FALSE
return generic_leiden_test(h_src,
h_dst,
h_wgt,
h_result,
expected_modularity,
num_vertices,
num_edges,
max_level,
resolution,
theta,
FALSE);
}
int test_leiden_no_weights()
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t max_level = 10;
weight_t resolution = 1.0;
weight_t theta = 1.0;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_result[] = {1, 1, 1, 2, 0, 0};
weight_t expected_modularity = 0.0859375;
// Louvain wants store_transposed = FALSE
return generic_leiden_test(h_src,
h_dst,
NULL,
h_result,
expected_modularity,
num_vertices,
num_edges,
max_level,
resolution,
theta,
FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
int result = 0;
result |= RUN_TEST(test_leiden);
result |= RUN_TEST(test_leiden_no_weights);
return result;
}
| 6,917
| 35.603175
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_betweenness_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_betweenness_centrality_test.c
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_betweenness_centrality_test(const cugraph_resource_handle_t* handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
bool_t store_transposed,
bool_t is_symmetric,
bool_t normalized,
bool_t include_endpoints,
size_t num_vertices_to_sample)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
cugraph_rng_state_t* rng_state = NULL;
cugraph_type_erased_device_array_t* seeds = NULL;
cugraph_type_erased_device_array_view_t* seeds_view = NULL;
int rank = cugraph_resource_handle_get_rank(handle);
ret_code = cugraph_rng_state_create(handle, rank, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "failed to create rng_state.");
ret_code = create_mg_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, is_symmetric, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
if (h_seeds == NULL) {
ret_code = cugraph_select_random_vertices(
handle, p_graph, rng_state, num_vertices_to_sample, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "select random seeds failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
} else {
if (rank > 0) num_seeds = 0;
ret_code =
cugraph_type_erased_device_array_create(handle, num_seeds, INT32, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds create failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, seeds_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds copy_from_host failed.");
}
ret_code = cugraph_betweenness_centrality(
handle, p_graph, seeds_view, normalized, include_endpoints, FALSE, &p_result, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_betweenness_centrality failed.");
// NOTE: Because we get back vertex ids and centralities, we can simply compare
// the returned values with the expected results for the entire
// graph. Each GPU will have a subset of the total vertices, so
// they will do a subset of the comparisons.
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.00001),
"betweenness centrality results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_type_erased_device_array_view_free(seeds_view);
cugraph_type_erased_device_array_free(seeds);
cugraph_mg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_betweenness_centrality(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, 3.66667, 0.83333, 2.16667, 0.83333, 0.5};
// NOTE: Randomly selecting vertices in MG varies by the GPU topology,
// so we'll specify selecting all to get deterministic results for the test.
//
// Betweenness centrality wants store_transposed = FALSE
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
TRUE,
FALSE,
FALSE,
num_vertices);
}
int test_betweenness_centrality_normalized(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, .366667, .083333, .216667, 0.0833333, 0.05};
// NOTE: Randomly selecting vertices in MG varies by the GPU topology,
// so we'll specify selecting all to get deterministic results for the test.
//
// Betweenness centrality wants store_transposed = FALSE
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
TRUE,
TRUE,
FALSE,
num_vertices);
}
int test_betweenness_centrality_full(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, 3.66667, 0.833333, 2.16667, 0.833333, 0.5};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
TRUE,
FALSE,
FALSE,
6);
}
int test_betweenness_centrality_full_directed(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0, 4, 0, 2, 1, 0};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
FALSE,
FALSE,
FALSE,
6);
}
int test_betweenness_centrality_specific_normalized(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_seeds[] = {0, 3};
weight_t h_result[] = {0, 0.475, 0.2, 0.1, 0.05, 0.075};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
h_seeds,
h_result,
num_vertices,
num_edges,
num_seeds,
FALSE,
FALSE,
TRUE,
FALSE,
num_seeds);
}
int test_betweenness_centrality_specific_unnormalized(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t h_seeds[] = {0, 3};
weight_t h_result[] = {0, 3.16667, 1.33333, 0.666667, 0.333333, 0.5};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
h_seeds,
h_result,
num_vertices,
num_edges,
num_seeds,
FALSE,
FALSE,
FALSE,
FALSE,
num_seeds);
}
int test_betweenness_centrality_test_endpoints(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.166667, 0.3, 0.166667, 0.2, 0.166667, 0.166667};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
FALSE,
TRUE,
TRUE,
6);
}
int test_betweenness_centrality_full_directed_normalized_karate(
const cugraph_resource_handle_t* handle)
{
size_t num_edges = 156;
size_t num_vertices = 34;
vertex_t h_src[] = {
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 2, 3, 7, 13, 17, 19, 21,
30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10, 6, 10, 16, 16, 30, 32, 33, 33, 33,
32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 31, 29, 33, 33,
31, 33, 32, 33, 32, 33, 32, 33, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4,
5, 5, 5, 6, 8, 8, 8, 9, 13, 14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23,
23, 23, 24, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32};
vertex_t h_dst[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1,
1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 8, 8, 8, 9, 13,
14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 26, 26, 27,
28, 28, 29, 29, 30, 30, 31, 31, 32, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19,
21, 31, 2, 3, 7, 13, 17, 19, 21, 30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10,
6, 10, 16, 16, 30, 32, 33, 33, 33, 32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29,
32, 33, 25, 27, 31, 31, 29, 33, 33, 31, 33, 32, 33, 32, 33, 32, 33, 33};
weight_t h_wgt[] = {
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f};
weight_t h_result[] = {462.142914, 56.957146, 151.701584, 12.576191, 0.666667, 31.666668,
31.666668, 0.000000, 59.058739, 0.895238, 0.666667, 0.000000,
0.000000, 48.431747, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 34.293652, 0.000000, 0.000000, 0.000000, 18.600000,
2.333333, 4.055556, 0.000000, 23.584126, 1.895238, 3.085714,
15.219049, 146.019043, 153.380981, 321.103180};
return generic_betweenness_centrality_test(handle,
h_src,
h_dst,
h_wgt,
NULL,
h_result,
num_vertices,
num_edges,
0,
FALSE,
FALSE,
FALSE,
FALSE,
34);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_betweenness_centrality, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_normalized, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_full, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_full_directed, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_specific_normalized, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_specific_unnormalized, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_test_endpoints, handle);
result |= RUN_MG_TEST(test_betweenness_centrality_full_directed_normalized_karate, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 18,981
| 45.753695
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_bfs_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_bfs_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_bfs_test(const cugraph_resource_handle_t* p_handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
vertex_t const* expected_distances,
vertex_t const* expected_predecessors,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
size_t depth_limit,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_paths_result_t* paths_result = NULL;
cugraph_type_erased_device_array_t* p_sources = NULL;
cugraph_type_erased_device_array_view_t* p_source_view = NULL;
ret_code =
cugraph_type_erased_device_array_create(p_handle, num_seeds, INT32, &p_sources, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "p_sources create failed.");
p_source_view = cugraph_type_erased_device_array_view(p_sources);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, p_source_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = create_mg_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
ret_code = cugraph_bfs(
p_handle, p_graph, p_source_view, FALSE, 10000000, TRUE, TRUE, &paths_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_bfs failed.");
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* distances;
cugraph_type_erased_device_array_view_t* predecessors;
vertices = cugraph_paths_result_get_vertices(paths_result);
predecessors = cugraph_paths_result_get_predecessors(paths_result);
distances = cugraph_paths_result_get_distances(paths_result);
vertex_t h_vertices[num_vertices];
vertex_t h_predecessors[num_vertices];
vertex_t h_distances[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_distances, distances, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_predecessors, predecessors, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
expected_distances[h_vertices[i]] == h_distances[i],
"bfs distances don't match");
TEST_ASSERT(test_ret_value,
expected_predecessors[h_vertices[i]] == h_predecessors[i],
"bfs predecessors don't match");
}
cugraph_paths_result_free(paths_result);
cugraph_mg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_bfs(const cugraph_resource_handle_t* p_handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
vertex_t seeds[] = {0};
vertex_t expected_distances[] = {0, 1, 2147483647, 2, 2, 3};
vertex_t expected_predecessors[] = {-1, 0, -1, 1, 1, 3};
// Bfs wants store_transposed = FALSE
return generic_bfs_test(p_handle,
src,
dst,
wgt,
seeds,
expected_distances,
expected_predecessors,
num_vertices,
num_edges,
1,
10,
FALSE);
}
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_bfs, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 5,775
| 36.264516
| 96
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_core_number_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_core_number_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_core_number_test(const cugraph_resource_handle_t* p_handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_core_result_t* p_result = NULL;
ret_code = create_mg_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, TRUE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code =
cugraph_core_number(p_handle, p_graph, K_CORE_DEGREE_TYPE_IN, FALSE, &p_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_core_number failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* core_numbers;
vertices = cugraph_core_result_get_vertices(p_result);
core_numbers = cugraph_core_result_get_core_numbers(p_result);
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
vertex_t h_vertices[num_local_vertices];
vertex_t h_core_numbers[num_local_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_core_numbers, core_numbers, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_core_numbers[i], 0.001),
"core number results don't match");
}
cugraph_core_result_free(p_result);
cugraph_sg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_core_number(const cugraph_resource_handle_t* p_handle)
{
size_t num_edges = 22;
size_t num_vertices = 7;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5, 3, 1, 4, 5, 5, 6};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4, 4, 5, 3, 1, 6, 5};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
vertex_t h_result[] = {2, 3, 2, 3, 3, 3, 1};
return generic_core_number_test(
p_handle, h_src, h_dst, h_wgt, h_result, num_vertices, num_edges, FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_core_number, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 4,294
| 35.398305
| 96
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_create_graph_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_create_graph_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "c_test_utils.h" /* RUN_TEST */
#include "mg_test_utils.h" /* RUN_TEST */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/*
* Simple check of creating a graph from a COO on device memory.
*/
int test_create_mg_graph_simple(const cugraph_resource_handle_t* handle)
{
int test_ret_value = 0;
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
cugraph_graph_t* p_graph = NULL;
cugraph_graph_properties_t properties;
properties.is_symmetric = FALSE;
properties.is_multigraph = FALSE;
data_type_id_t vertex_tid = INT32;
data_type_id_t edge_tid = INT32;
data_type_id_t weight_tid = FLOAT32;
cugraph_type_erased_device_array_t* src;
cugraph_type_erased_device_array_t* dst;
cugraph_type_erased_device_array_t* wgt;
cugraph_type_erased_device_array_view_t* src_view;
cugraph_type_erased_device_array_view_t* dst_view;
cugraph_type_erased_device_array_view_t* wgt_view;
int my_rank = cugraph_resource_handle_get_rank(handle);
for (int i = 0; i < num_edges; ++i) {
h_src[i] += 10 * my_rank;
h_dst[i] += 10 * my_rank;
}
ret_code =
cugraph_type_erased_device_array_create(handle, num_edges, vertex_tid, &src, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src create failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code =
cugraph_type_erased_device_array_create(handle, num_edges, vertex_tid, &dst, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst create failed.");
ret_code =
cugraph_type_erased_device_array_create(handle, num_edges, weight_tid, &wgt, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "wgt create failed.");
src_view = cugraph_type_erased_device_array_view(src);
dst_view = cugraph_type_erased_device_array_view(dst);
wgt_view = cugraph_type_erased_device_array_view(wgt);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, src_view, (byte_t*)h_src, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, dst_view, (byte_t*)h_dst, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, wgt_view, (byte_t*)h_wgt, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "wgt copy_from_host failed.");
ret_code = cugraph_mg_graph_create(handle,
&properties,
src_view,
dst_view,
wgt_view,
NULL,
NULL,
FALSE,
num_edges,
TRUE,
&p_graph,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "graph creation failed.");
cugraph_mg_graph_free(p_graph);
cugraph_type_erased_device_array_view_free(wgt_view);
cugraph_type_erased_device_array_view_free(dst_view);
cugraph_type_erased_device_array_view_free(src_view);
cugraph_type_erased_device_array_free(wgt);
cugraph_type_erased_device_array_free(dst);
cugraph_type_erased_device_array_free(src);
cugraph_error_free(ret_error);
return test_ret_value;
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_create_mg_graph_simple, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 4,984
| 34.607143
| 93
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_edge_betweenness_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_edge_betweenness_centrality_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_edge_betweenness_centrality_test(const cugraph_resource_handle_t* handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
bool_t store_transposed,
size_t num_vertices_to_sample)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* graph = NULL;
cugraph_edge_centrality_result_t* result = NULL;
cugraph_rng_state_t* rng_state = NULL;
cugraph_type_erased_device_array_t* seeds = NULL;
cugraph_type_erased_device_array_view_t* seeds_view = NULL;
ret_code = create_mg_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
int rank = cugraph_resource_handle_get_rank(handle);
ret_code = cugraph_rng_state_create(handle, rank, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "failed to create rng_state.");
if (h_seeds == NULL) {
ret_code = cugraph_select_random_vertices(
handle, graph, rng_state, num_vertices_to_sample, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "select random seeds failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
} else {
if (rank > 0) num_seeds = 0;
ret_code =
cugraph_type_erased_device_array_create(handle, num_seeds, INT32, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds create failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, seeds_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds copy_from_host failed.");
}
ret_code = cugraph_edge_betweenness_centrality(
handle, graph, seeds_view, FALSE, FALSE, &result, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_edge_betweenness_centrality failed.");
// NOTE: Because we get back vertex ids and centralities, we can simply compare
// the returned values with the expected results for the entire
// graph. Each GPU will have a subset of the total vertices, so
// they will do a subset of the comparisons.
cugraph_type_erased_device_array_view_t* srcs;
cugraph_type_erased_device_array_view_t* dsts;
cugraph_type_erased_device_array_view_t* centralities;
srcs = cugraph_edge_centrality_result_get_src_vertices(result);
dsts = cugraph_edge_centrality_result_get_dst_vertices(result);
centralities = cugraph_edge_centrality_result_get_values(result);
size_t num_local_edges = cugraph_type_erased_device_array_view_size(srcs);
vertex_t h_cugraph_src[num_local_edges];
vertex_t h_cugraph_dst[num_local_edges];
weight_t h_centralities[num_local_edges];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_cugraph_src, srcs , &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_cugraph_dst, dsts, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
weight_t M[num_vertices][num_vertices];
for (int i = 0; i < num_vertices; ++i)
for (int j = 0; j < num_vertices; ++j) {
M[i][j] = 0.0;
}
for (int i = 0; i < num_edges; ++i) {
M[h_src[i]][h_dst[i]] = h_result[i];
}
for (int i = 0; (i < num_local_edges) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(M[h_cugraph_src[i]][h_cugraph_dst[i]], h_centralities[i], 0.001),
"betweenness centrality results don't match");
}
cugraph_edge_centrality_result_free(result);
cugraph_mg_graph_free(graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_edge_betweenness_centrality(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = { 3.16667, 2.83333, 4.33333, 1.83333, 2, 2.83333, 3.66667, 2.33333,
3.16667, 2.83333, 4.33333, 1.83333, 2, 2.83333, 3.66667, 2.33333 };
double epsilon = 1e-6;
size_t max_iterations = 200;
// Eigenvector centrality wants store_transposed = TRUE
return generic_edge_betweenness_centrality_test(
handle, h_src, h_dst, h_wgt, NULL, h_result, num_vertices, num_edges, 0, TRUE, 6);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_edge_betweenness_centrality, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 6,935
| 38.634286
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_egonet_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_egonet_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_egonet_test(const cugraph_resource_handle_t* resource_handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_seeds,
vertex_t* h_expected_src,
vertex_t* h_expected_dst,
size_t* h_expected_offsets,
size_t num_vertices,
size_t num_edges,
size_t num_seeds,
size_t radius,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* graph = NULL;
cugraph_type_erased_device_array_t* seeds = NULL;
cugraph_type_erased_device_array_view_t* seeds_view = NULL;
cugraph_induced_subgraph_result_t* result = NULL;
int rank = cugraph_resource_handle_get_rank(resource_handle);
ret_code = create_mg_test_graph_with_properties(resource_handle,
h_src,
h_dst,
NULL,
NULL,
h_wgt,
num_edges,
store_transposed,
FALSE,
&graph,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
size_t num_seeds_to_use = num_seeds;
if (rank != 0) { num_seeds_to_use = 0; }
ret_code =
cugraph_type_erased_device_array_create(resource_handle, num_seeds_to_use, INT32, &seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "seeds create failed.");
seeds_view = cugraph_type_erased_device_array_view(seeds);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
resource_handle, seeds_view, (byte_t*)h_seeds, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code =
cugraph_extract_ego(resource_handle, graph, seeds_view, radius, FALSE, &result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, "cugraph_egonet failed.");
if (test_ret_value == 0) {
cugraph_type_erased_device_array_view_t* src;
cugraph_type_erased_device_array_view_t* dst;
cugraph_type_erased_device_array_view_t* wgt;
cugraph_type_erased_device_array_view_t* offsets;
src = cugraph_induced_subgraph_get_sources(result);
dst = cugraph_induced_subgraph_get_destinations(result);
wgt = cugraph_induced_subgraph_get_edge_weights(result);
offsets = cugraph_induced_subgraph_get_subgraph_offsets(result);
size_t num_result_edges = cugraph_type_erased_device_array_view_size(src);
size_t num_result_offsets = cugraph_type_erased_device_array_view_size(offsets);
vertex_t h_result_src[num_result_edges];
vertex_t h_result_dst[num_result_edges];
weight_t h_result_wgt[num_result_edges];
size_t h_result_offsets[num_result_offsets];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_result_src, src, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_result_dst, dst, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
if (h_wgt != NULL) {
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_result_wgt, wgt, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
}
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_result_offsets, offsets, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
printf("rank = %d, num_result_offsets = %lu, num_seeds = %lu\n", rank, num_result_offsets, num_seeds);
TEST_ASSERT(
test_ret_value, (num_seeds + 1) == num_result_offsets, "number of offsets doesn't match");
#if 0
for (int i = 0; (i < num_result_offsets) && (test_ret_value == 0); ++i) {
TEST_ASSERT(
test_ret_value, h_result_offsets[i] == h_expected_offsets[i], "offsets don't match");
}
#endif
weight_t M[num_vertices][num_vertices];
for (int i = 0; (i < num_seeds) && (test_ret_value == 0); ++i) {
for (int r = 0; r < num_vertices; ++r)
for (int c = 0; c < num_vertices; ++c)
M[r][c] = 0;
for (size_t e = h_expected_offsets[i]; e < h_expected_offsets[i + 1]; ++e)
M[h_expected_src[e]][h_expected_dst[e]] = 1;
for (size_t e = h_result_offsets[i]; (e < h_result_offsets[i + 1]) && (test_ret_value == 0);
++e) {
TEST_ASSERT(
test_ret_value, (M[h_result_src[e]][h_result_dst[e]] > 0), "found different edges");
}
}
cugraph_type_erased_device_array_view_free(src);
cugraph_type_erased_device_array_view_free(dst);
cugraph_type_erased_device_array_view_free(wgt);
cugraph_type_erased_device_array_view_free(offsets);
cugraph_induced_subgraph_result_free(result);
}
cugraph_sg_graph_free(graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_egonet(const cugraph_resource_handle_t* resource_handle)
{
size_t num_edges = 9;
size_t num_vertices = 6;
size_t radius = 2;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 4, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 6.1f};
vertex_t h_seeds[] = {0, 1};
vertex_t h_result_src[] = {0, 1, 1, 3, 1, 1, 3, 3, 4};
vertex_t h_result_dst[] = {1, 3, 4, 4, 3, 4, 4, 5, 5};
size_t h_result_offsets[] = {0, 4, 9};
// Egonet wants store_transposed = FALSE
return generic_egonet_test(resource_handle,
h_src,
h_dst,
h_wgt,
h_seeds,
h_result_src,
h_result_dst,
h_result_offsets,
num_vertices,
num_edges,
num_seeds,
radius,
FALSE);
}
int test_egonet_no_weights(const cugraph_resource_handle_t* resource_handle)
{
size_t num_edges = 9;
size_t num_vertices = 6;
size_t radius = 2;
size_t num_seeds = 2;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 4, 5, 5};
vertex_t h_seeds[] = {0, 1};
vertex_t h_result_src[] = {0, 1, 1, 3, 1, 1, 3, 3, 4};
vertex_t h_result_dst[] = {1, 3, 4, 4, 3, 4, 4, 5, 5};
size_t h_result_offsets[] = {0, 4, 9};
// Egonet wants store_transposed = FALSE
return generic_egonet_test(resource_handle,
h_src,
h_dst,
NULL,
h_seeds,
h_result_src,
h_result_dst,
h_result_offsets,
num_vertices,
num_edges,
num_seeds,
radius,
FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_egonet, handle);
result |= RUN_MG_TEST(test_egonet_no_weights, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 9,369
| 37.089431
| 106
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_eigenvector_centrality_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_eigenvector_centrality_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_eigenvector_centrality_test(const cugraph_resource_handle_t* handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
ret_code = create_mg_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
ret_code = cugraph_eigenvector_centrality(
handle, p_graph, epsilon, max_iterations, FALSE, &p_result, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_eigenvector_centrality failed.");
// NOTE: Because we get back vertex ids and centralities, we can simply compare
// the returned values with the expected results for the entire
// graph. Each GPU will have a subset of the total vertices, so
// they will do a subset of the comparisons.
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.001),
"eigenvector centrality results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_mg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_eigenvector_centrality(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 16;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4};
weight_t h_wgt[] = {
0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f, 0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.236374, 0.292046, 0.458369, 0.605472, 0.190544, 0.495814};
double epsilon = 1e-6;
size_t max_iterations = 200;
// Eigenvector centrality wants store_transposed = TRUE
return generic_eigenvector_centrality_test(
handle, h_src, h_dst, h_wgt, h_result, num_vertices, num_edges, TRUE, epsilon, max_iterations);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_eigenvector_centrality, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 4,793
| 36.748031
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_generate_rmat_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_generate_rmat_test.c
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/graph_generators.h>
#include <stdio.h>
/*
* Simple rmat generator test
*/
int test_rmat_generation(const cugraph_resource_handle_t* handle)
{
// FIXME: this should be re-implemented (this test doesn't work for more than 8 GPUs, and this
// assumes that the underlying random number generator produces a known sequence)
#if 1
return CUGRAPH_SUCCESS;
#else
int test_ret_value = 0;
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
vertex_t expected_src_0[] = {17, 18, 0, 16, 1, 24, 16, 1, 6, 4, 2, 1, 14, 2, 16,
2, 5, 23, 4, 10, 4, 3, 0, 4, 11, 0, 0, 2, 24, 0};
vertex_t expected_dst_0[] = {0, 10, 23, 0, 26, 0, 2, 1, 27, 8, 1, 0, 21, 21, 0,
4, 8, 14, 10, 17, 0, 16, 0, 16, 25, 5, 8, 8, 4, 19};
vertex_t expected_src_1[] = {1, 0, 2, 25, 0, 5, 18, 0, 0, 2, 4, 0, 8, 9, 2,
2, 9, 16, 4, 1, 0, 2, 0, 0, 9, 5, 4, 6, 4, 9};
vertex_t expected_dst_1[] = {4, 1, 4, 0, 16, 16, 16, 3, 2, 0, 1, 0, 7, 0, 2,
13, 6, 8, 18, 16, 0, 4, 27, 16, 24, 17, 21, 25, 1, 0};
vertex_t expected_src_2[] = {4, 4, 4, 0, 2, 8, 6, 0, 0, 0, 0, 16, 8, 18, 1,
19, 16, 0, 24, 4, 0, 17, 0, 8, 5, 8, 8, 12, 10, 1};
vertex_t expected_dst_2[] = {9, 2, 3, 18, 0, 24, 2, 4, 0, 0, 25, 0, 0, 4, 20,
0, 16, 10, 17, 16, 25, 16, 1, 1, 4, 24, 6, 6, 0, 0};
vertex_t expected_src_3[] = {9, 16, 0, 1, 4, 26, 7, 20, 0, 0, 0, 25, 2, 16, 4,
12, 18, 2, 16, 24, 5, 20, 1, 4, 1, 22, 9, 1, 2, 16};
vertex_t expected_dst_3[] = {18, 0, 16, 2, 1, 2, 16, 0, 5, 2, 22, 8, 6, 11, 0,
17, 0, 2, 0, 6, 9, 1, 0, 8, 8, 9, 4, 2, 3, 18};
vertex_t expected_src_4[] = {16, 24, 25, 0, 18, 0, 0, 0, 0, 0, 16, 0, 1, 8, 8,
0, 4, 0, 4, 0, 5, 8, 0, 2, 21, 11, 0, 24, 0, 4};
vertex_t expected_dst_4[] = {8, 13, 16, 0, 0, 2, 17, 18, 16, 14, 4, 0, 0, 1, 4,
2, 1, 0, 1, 0, 0, 0, 26, 0, 20, 1, 14, 21, 2, 28};
vertex_t expected_src_5[] = {0, 24, 8, 2, 6, 0, 10, 4, 4, 0, 10, 4, 17, 0, 17,
0, 10, 20, 26, 0, 6, 0, 11, 2, 1, 0, 17, 2, 4, 8};
vertex_t expected_dst_5[] = {2, 24, 0, 18, 0, 0, 1, 0, 14, 18, 16, 19, 1, 0, 8,
29, 12, 1, 8, 8, 0, 22, 4, 12, 2, 1, 0, 0, 8, 8};
vertex_t expected_src_6[] = {4, 4, 10, 8, 26, 0, 20, 2, 14, 1, 8, 1, 0, 16, 24,
28, 8, 18, 7, 5, 16, 2, 12, 22, 8, 4, 1, 1, 12, 8};
vertex_t expected_dst_6[] = {4, 2, 6, 1, 3, 16, 5, 8, 5, 0, 19, 9, 0, 1, 0,
0, 8, 26, 0, 9, 16, 0, 3, 6, 2, 24, 8, 0, 4, 10};
vertex_t expected_src_7[] = {5, 0, 16, 0, 16, 21, 1, 3, 8, 4, 0, 22, 25, 8, 0,
4, 0, 6, 0, 0, 0, 0, 2, 0, 0, 4, 8, 0, 0, 0};
vertex_t expected_dst_7[] = {0, 4, 30, 10, 5, 0, 24, 0, 0, 4, 18, 8, 3, 10, 9,
1, 0, 10, 2, 0, 2, 16, 3, 0, 14, 16, 1, 26, 8, 8};
vertex_t* expected_src[] = {expected_src_0,
expected_src_1,
expected_src_2,
expected_src_3,
expected_src_4,
expected_src_5,
expected_src_6,
expected_src_7};
vertex_t* expected_dst[] = {expected_dst_0,
expected_dst_1,
expected_dst_2,
expected_dst_3,
expected_dst_4,
expected_dst_5,
expected_dst_6,
expected_dst_7};
size_t expected_len[] = {sizeof(expected_src_0) / sizeof(expected_src_0[0]),
sizeof(expected_src_1) / sizeof(expected_src_1[0]),
sizeof(expected_src_2) / sizeof(expected_src_2[0]),
sizeof(expected_src_3) / sizeof(expected_src_3[0]),
sizeof(expected_src_4) / sizeof(expected_src_4[0]),
sizeof(expected_src_5) / sizeof(expected_src_5[0]),
sizeof(expected_src_6) / sizeof(expected_src_6[0]),
sizeof(expected_src_7) / sizeof(expected_src_7[0])};
size_t max_rank_to_validate = sizeof(expected_src) / sizeof(expected_src[0]);
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_rng_state_t* rng_state = NULL;
;
cugraph_coo_t* coo = NULL;
int rank = cugraph_resource_handle_get_rank(handle);
ret_code = cugraph_rng_state_create(handle, rank, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
data_type_id_t vertex_tid = INT32;
data_type_id_t edge_tid = INT32;
data_type_id_t weight_tid = FLOAT32;
ret_code = cugraph_generate_rmat_edgelist(
handle, rng_state, 5, 30, 0.57, 0.19, 0.19, FALSE, &coo, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "generate_rmat_edgelist failed.");
if (rank < max_rank_to_validate) {
cugraph_type_erased_device_array_view_t* src_view;
cugraph_type_erased_device_array_view_t* dst_view;
src_view = cugraph_coo_get_sources(coo);
dst_view = cugraph_coo_get_destinations(coo);
size_t src_size = cugraph_type_erased_device_array_view_size(src_view);
vertex_t h_src[src_size];
vertex_t h_dst[src_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_src, src_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_dst, dst_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst copy_to_host failed.");
TEST_ASSERT(test_ret_value, src_size == expected_len[rank], "incorrect number of edges");
for (int i = 0; (i < src_size) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value, expected_src[rank][i] == h_src[i], "generated edges don't match");
TEST_ASSERT(test_ret_value, expected_dst[rank][i] == h_dst[i], "generated edges don't match");
}
cugraph_type_erased_device_array_view_free(dst_view);
cugraph_type_erased_device_array_view_free(src_view);
}
cugraph_coo_free(coo);
cugraph_error_free(ret_error);
return test_ret_value;
#endif
}
int test_rmat_list_generation(const cugraph_resource_handle_t* handle)
{
// FIXME: this should be re-implemented (this test doesn't work for more than 8 GPUs, and this
// assumes that the underlying random number generator produces a known sequence)
#if 1
return CUGRAPH_SUCCESS;
#else
int test_ret_value = 0;
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
size_t num_lists = 3;
vertex_t expected_src_0_rank_0[] = {29, 16, 16, 5, 6, 1, 20, 5, 22, 14,
3, 12, 4, 0, 10, 0, 4, 16, 20, 16};
vertex_t expected_dst_0_rank_0[] = {0, 18, 0, 8, 1, 0, 11, 8, 21, 16,
0, 2, 2, 0, 17, 0, 9, 0, 8, 0};
vertex_t expected_src_1_rank_0[] = {2, 6, 8, 0, 8, 0, 0, 2, 8, 0, 12, 0, 2, 9, 4, 8};
vertex_t expected_dst_1_rank_0[] = {10, 5, 0, 4, 10, 5, 4, 1, 0, 1, 11, 0, 0, 6, 2, 14};
vertex_t expected_src_2_rank_0[] = {5, 0, 24, 11, 2, 20, 2, 1, 0, 18,
2, 0, 0, 0, 8, 4, 1, 22, 0, 1};
vertex_t expected_dst_2_rank_0[] = {16, 4, 0, 1, 8, 0, 0, 0, 8, 7,
3, 15, 0, 0, 4, 26, 16, 0, 8, 2};
vertex_t expected_src_0_rank_1[] = {0, 21, 10, 17, 8, 0, 21, 24, 0, 0,
0, 1, 2, 16, 0, 2, 2, 24, 0, 27};
vertex_t expected_dst_0_rank_1[] = {0, 2, 4, 0, 19, 12, 0, 18, 4, 16,
8, 0, 1, 4, 5, 4, 18, 16, 20, 24};
vertex_t expected_src_1_rank_1[] = {12, 0, 0, 0, 8, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
vertex_t expected_dst_1_rank_1[] = {12, 8, 1, 0, 8, 0, 1, 0, 6, 13, 0, 0, 0, 0, 0, 2};
vertex_t expected_src_2_rank_1[] = {4, 12, 0, 0, 1, 12, 2, 0, 16, 0,
20, 8, 14, 0, 16, 9, 24, 8, 10, 1};
vertex_t expected_dst_2_rank_1[] = {16, 0, 0, 4, 0, 13, 0, 1, 2, 0,
0, 8, 8, 4, 1, 3, 5, 16, 2, 0};
vertex_t expected_src_0_rank_2[] = {8, 4, 4, 4, 1, 6, 9, 4, 6, 0, 13, 3, 0, 0, 8, 13};
vertex_t expected_dst_0_rank_2[] = {6, 0, 6, 2, 0, 0, 1, 0, 6, 0, 10, 0, 2, 2, 12, 0};
vertex_t expected_src_1_rank_2[] = {18, 12, 2, 0, 12, 4, 1, 18, 0, 4,
0, 3, 0, 0, 18, 22, 3, 4, 2, 8};
vertex_t expected_dst_1_rank_2[] = {2, 1, 8, 22, 1, 28, 4, 11, 0, 0,
12, 24, 8, 3, 8, 6, 1, 16, 0, 2};
vertex_t expected_src_2_rank_2[] = {1, 2, 12, 3, 1, 0, 4, 5, 1, 3, 5, 3, 1, 2, 8, 0};
vertex_t expected_dst_2_rank_2[] = {8, 0, 0, 4, 4, 4, 2, 10, 1, 13, 0, 0, 0, 4, 0, 4};
vertex_t expected_src_0_rank_3[] = {0, 13, 0, 2, 16, 4, 10, 1, 20, 2,
0, 0, 1, 0, 16, 3, 6, 10, 0, 0};
vertex_t expected_dst_0_rank_3[] = {9, 16, 0, 8, 9, 1, 0, 1, 3, 0,
0, 2, 8, 0, 12, 2, 20, 8, 29, 3};
vertex_t expected_src_1_rank_3[] = {2, 13, 3, 2, 18, 8, 0, 0, 8, 10,
17, 0, 2, 26, 9, 28, 1, 0, 10, 17};
vertex_t expected_dst_1_rank_3[] = {2, 8, 0, 14, 16, 20, 8, 8, 0, 0,
7, 0, 16, 4, 20, 16, 5, 3, 0, 3};
vertex_t expected_src_2_rank_3[] = {0, 1, 3, 0, 9, 1, 5, 0, 4, 4, 0, 6, 0, 12, 0, 2};
vertex_t expected_dst_2_rank_3[] = {4, 1, 0, 12, 6, 2, 2, 8, 2, 10, 8, 0, 4, 4, 0, 1};
vertex_t expected_src_0_rank_4[] = {0, 1, 1, 0, 0, 1, 4, 3, 14, 3, 0, 4, 0, 2, 9, 0};
vertex_t expected_dst_0_rank_4[] = {0, 2, 8, 0, 2, 0, 13, 0, 0, 8, 1, 12, 0, 9, 0, 0};
vertex_t expected_src_1_rank_4[] = {2, 2, 2, 6, 4, 6, 4, 10, 0, 2, 2, 8, 4, 0, 4, 9};
vertex_t expected_dst_1_rank_4[] = {0, 1, 6, 1, 1, 0, 10, 2, 0, 0, 0, 0, 0, 1, 0, 0};
vertex_t expected_src_2_rank_4[] = {9, 2, 0, 20, 0, 3, 5, 22, 2, 8,
26, 0, 18, 16, 12, 0, 0, 18, 8, 2};
vertex_t expected_dst_2_rank_4[] = {2, 8, 6, 18, 16, 16, 19, 0, 16, 1,
0, 0, 12, 0, 8, 0, 0, 8, 22, 4};
vertex_t expected_src_0_rank_5[] = {8, 11, 4, 4, 8, 0, 8, 15, 12, 6, 1, 0, 7, 4, 3, 2};
vertex_t expected_dst_0_rank_5[] = {5, 4, 12, 8, 4, 8, 8, 1, 0, 3, 0, 8, 8, 0, 1, 5};
vertex_t expected_src_1_rank_5[] = {16, 0, 8, 17, 9, 8, 2, 1, 0, 24,
8, 2, 0, 0, 16, 22, 16, 0, 0, 2};
vertex_t expected_dst_1_rank_5[] = {8, 10, 2, 0, 0, 6, 8, 2, 8, 16,
1, 0, 24, 26, 0, 0, 2, 3, 8, 24};
vertex_t expected_src_2_rank_5[] = {21, 5, 10, 24, 1, 16, 10, 0, 2, 2,
5, 4, 2, 0, 0, 8, 2, 0, 4, 4};
vertex_t expected_dst_2_rank_5[] = {4, 14, 20, 0, 0, 8, 20, 1, 8, 21,
16, 2, 0, 2, 14, 0, 10, 24, 9, 5};
vertex_t expected_src_0_rank_6[] = {8, 16, 2, 8, 0, 24, 20, 10, 8, 0,
0, 0, 20, 8, 10, 0, 4, 8, 12, 4};
vertex_t expected_dst_0_rank_6[] = {21, 25, 6, 6, 2, 0, 12, 1, 8, 8,
16, 28, 8, 1, 10, 0, 1, 0, 16, 2};
vertex_t expected_src_1_rank_6[] = {4, 0, 1, 13, 0, 1, 10, 8, 2, 0, 9, 8, 3, 6, 4, 12};
vertex_t expected_dst_1_rank_6[] = {9, 2, 5, 6, 8, 0, 4, 0, 0, 10, 2, 6, 14, 0, 0, 2};
vertex_t expected_src_2_rank_6[] = {2, 4, 18, 18, 0, 24, 4, 16, 5, 18,
17, 13, 16, 28, 24, 0, 28, 0, 13, 1};
vertex_t expected_dst_2_rank_6[] = {8, 24, 24, 1, 16, 2, 0, 4, 1, 0,
10, 10, 18, 0, 18, 18, 2, 26, 8, 0};
vertex_t expected_src_0_rank_7[] = {0, 5, 0, 4, 2, 3, 4, 4, 20, 18,
0, 0, 29, 17, 0, 0, 0, 1, 0, 8};
vertex_t expected_dst_0_rank_7[] = {4, 0, 24, 0, 0, 18, 8, 0, 0, 9,
3, 12, 4, 8, 17, 1, 0, 28, 22, 1};
vertex_t expected_src_1_rank_7[] = {0, 8, 5, 2, 4, 0, 0, 5, 0, 0, 0, 9, 2, 0, 2, 8};
vertex_t expected_dst_1_rank_7[] = {3, 0, 1, 9, 9, 8, 7, 12, 1, 12, 5, 0, 0, 8, 13, 8};
vertex_t expected_src_2_rank_7[] = {8, 9, 2, 4, 4, 0, 25, 0, 0, 0,
8, 6, 0, 0, 8, 4, 21, 0, 16, 0};
vertex_t expected_dst_2_rank_7[] = {4, 4, 1, 1, 4, 0, 16, 1, 0, 16,
5, 25, 24, 8, 16, 2, 2, 0, 4, 16};
vertex_t* expected_src_0[] = {expected_src_0_rank_0,
expected_src_0_rank_1,
expected_src_0_rank_2,
expected_src_0_rank_3,
expected_src_0_rank_4,
expected_src_0_rank_5,
expected_src_0_rank_6,
expected_src_0_rank_7};
vertex_t* expected_dst_0[] = {expected_dst_0_rank_0,
expected_dst_0_rank_1,
expected_dst_0_rank_2,
expected_dst_0_rank_3,
expected_dst_0_rank_4,
expected_dst_0_rank_5,
expected_dst_0_rank_6,
expected_dst_0_rank_7};
vertex_t* expected_src_1[] = {expected_src_1_rank_0,
expected_src_1_rank_1,
expected_src_1_rank_2,
expected_src_1_rank_3,
expected_src_1_rank_4,
expected_src_1_rank_5,
expected_src_1_rank_6,
expected_src_1_rank_7};
vertex_t* expected_dst_1[] = {expected_dst_1_rank_0,
expected_dst_1_rank_1,
expected_dst_1_rank_2,
expected_dst_1_rank_3,
expected_dst_1_rank_4,
expected_dst_1_rank_5,
expected_dst_1_rank_6,
expected_dst_1_rank_7};
vertex_t* expected_src_2[] = {expected_src_2_rank_0,
expected_src_2_rank_1,
expected_src_2_rank_2,
expected_src_2_rank_3,
expected_src_2_rank_4,
expected_src_2_rank_5,
expected_src_2_rank_6,
expected_src_2_rank_7};
vertex_t* expected_dst_2[] = {expected_dst_2_rank_0,
expected_dst_2_rank_1,
expected_dst_2_rank_2,
expected_dst_2_rank_3,
expected_dst_2_rank_4,
expected_dst_2_rank_5,
expected_dst_2_rank_6,
expected_dst_2_rank_7};
size_t expected_len_0[] = {sizeof(expected_src_0_rank_0) / sizeof(expected_src_0_rank_0[0]),
sizeof(expected_src_0_rank_1) / sizeof(expected_src_0_rank_1[0]),
sizeof(expected_src_0_rank_2) / sizeof(expected_src_0_rank_2[0]),
sizeof(expected_src_0_rank_3) / sizeof(expected_src_0_rank_3[0]),
sizeof(expected_src_0_rank_4) / sizeof(expected_src_0_rank_4[0]),
sizeof(expected_src_0_rank_5) / sizeof(expected_src_0_rank_5[0]),
sizeof(expected_src_0_rank_6) / sizeof(expected_src_0_rank_6[0]),
sizeof(expected_src_0_rank_7) / sizeof(expected_src_0_rank_7[0])};
size_t expected_len_1[] = {sizeof(expected_src_1_rank_0) / sizeof(expected_src_1_rank_0[0]),
sizeof(expected_src_1_rank_1) / sizeof(expected_src_1_rank_1[0]),
sizeof(expected_src_1_rank_2) / sizeof(expected_src_1_rank_2[0]),
sizeof(expected_src_1_rank_3) / sizeof(expected_src_1_rank_3[0]),
sizeof(expected_src_1_rank_4) / sizeof(expected_src_1_rank_4[0]),
sizeof(expected_src_1_rank_5) / sizeof(expected_src_1_rank_5[0]),
sizeof(expected_src_1_rank_6) / sizeof(expected_src_1_rank_6[0]),
sizeof(expected_src_1_rank_7) / sizeof(expected_src_1_rank_7[0])};
size_t expected_len_2[] = {sizeof(expected_src_2_rank_0) / sizeof(expected_src_2_rank_0[0]),
sizeof(expected_src_2_rank_1) / sizeof(expected_src_2_rank_1[0]),
sizeof(expected_src_2_rank_2) / sizeof(expected_src_2_rank_2[0]),
sizeof(expected_src_2_rank_3) / sizeof(expected_src_2_rank_3[0]),
sizeof(expected_src_2_rank_4) / sizeof(expected_src_2_rank_4[0]),
sizeof(expected_src_2_rank_5) / sizeof(expected_src_2_rank_5[0]),
sizeof(expected_src_2_rank_6) / sizeof(expected_src_2_rank_6[0]),
sizeof(expected_src_2_rank_7) / sizeof(expected_src_2_rank_7[0])};
vertex_t** expected_src[] = {expected_src_0, expected_src_1, expected_src_2};
vertex_t** expected_dst[] = {expected_dst_0, expected_dst_1, expected_dst_2};
size_t* expected_len[] = {expected_len_0, expected_len_1, expected_len_2};
size_t max_rank_to_validate = sizeof(expected_src_0) / sizeof(expected_src_0[0]);
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_rng_state_t* rng_state = NULL;
;
cugraph_coo_list_t* coo_list = NULL;
int rank = cugraph_resource_handle_get_rank(handle);
ret_code = cugraph_rng_state_create(handle, rank, &rng_state, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "rng_state create failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
data_type_id_t vertex_tid = INT32;
data_type_id_t edge_tid = INT32;
data_type_id_t weight_tid = FLOAT32;
ret_code = cugraph_generate_rmat_edgelists(
handle, rng_state, num_lists, 4, 6, 4, UNIFORM, POWER_LAW, FALSE, &coo_list, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "generate_rmat_edgelist failed.");
TEST_ASSERT(test_ret_value,
cugraph_coo_list_size(coo_list) == num_lists,
"generated wrong number of results");
if (rank < max_rank_to_validate) {
for (size_t i = 0; (i < num_lists) && (test_ret_value == 0); i++) {
cugraph_coo_t* coo = NULL;
coo = cugraph_coo_list_element(coo_list, i);
cugraph_type_erased_device_array_view_t* src_view;
cugraph_type_erased_device_array_view_t* dst_view;
src_view = cugraph_coo_get_sources(coo);
dst_view = cugraph_coo_get_destinations(coo);
size_t src_size = cugraph_type_erased_device_array_view_size(src_view);
TEST_ASSERT(test_ret_value, src_size == expected_len[i][rank], "wrong number of edges");
vertex_t h_src[src_size];
vertex_t h_dst[src_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_src, src_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_dst, dst_view, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "dst copy_to_host failed.");
for (size_t j = 0; (j < src_size) && (test_ret_value == 0); ++j) {
TEST_ASSERT(
test_ret_value, expected_src[i][rank][j] == h_src[j], "generated edges don't match");
TEST_ASSERT(
test_ret_value, expected_dst[i][rank][j] == h_dst[j], "generated edges don't match");
}
cugraph_type_erased_device_array_view_free(dst_view);
cugraph_type_erased_device_array_view_free(src_view);
}
}
cugraph_coo_list_free(coo_list);
cugraph_error_free(ret_error);
return test_ret_value;
#endif
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_rmat_generation, handle);
result |= RUN_MG_TEST(test_rmat_list_generation, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 22,185
| 51.949881
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_hits_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_hits_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_hits_test(const cugraph_resource_handle_t* p_handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
size_t num_vertices,
size_t num_edges,
vertex_t* h_initial_vertices,
weight_t* h_initial_hubs,
size_t num_initial_vertices,
weight_t* h_result_hubs,
weight_t* h_result_authorities,
bool_t store_transposed,
bool_t normalize,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_hits_result_t* p_result = NULL;
ret_code = create_mg_test_graph(
p_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
if (h_initial_vertices == NULL) {
ret_code = cugraph_hits(p_handle,
p_graph,
epsilon,
max_iterations,
NULL,
NULL,
normalize,
FALSE,
&p_result,
&ret_error);
} else {
int rank = cugraph_resource_handle_get_rank(p_handle);
if (rank != 0) {
// Only initialize the vertices on rank 0
num_initial_vertices = 0;
}
cugraph_type_erased_device_array_t* initial_vertices;
cugraph_type_erased_device_array_t* initial_hubs;
cugraph_type_erased_device_array_view_t* initial_vertices_view;
cugraph_type_erased_device_array_view_t* initial_hubs_view;
ret_code = cugraph_type_erased_device_array_create(
p_handle, num_initial_vertices, INT32, &initial_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "initial_vertices create failed.");
ret_code = cugraph_type_erased_device_array_create(
p_handle, num_initial_vertices, FLOAT32, &initial_hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "initial_hubs create failed.");
initial_vertices_view = cugraph_type_erased_device_array_view(initial_vertices);
initial_hubs_view = cugraph_type_erased_device_array_view(initial_hubs);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, initial_vertices_view, (byte_t*)h_initial_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
p_handle, initial_hubs_view, (byte_t*)h_initial_hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "src copy_from_host failed.");
ret_code = cugraph_hits(p_handle,
p_graph,
epsilon,
max_iterations,
initial_vertices_view,
initial_hubs_view,
normalize,
FALSE,
&p_result,
&ret_error);
}
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_hits failed.");
// NOTE: Because we get back vertex ids, hubs and authorities, we can
// simply compare the returned values with the expected results
// for the entire graph. Each GPU will have a subset of the
// total vertices, so they will do a subset of the comparisons.
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* hubs;
cugraph_type_erased_device_array_view_t* authorities;
vertices = cugraph_hits_result_get_vertices(p_result);
hubs = cugraph_hits_result_get_hubs(p_result);
authorities = cugraph_hits_result_get_authorities(p_result);
double score_differences = cugraph_hits_result_get_hub_score_differences(p_result);
size_t num_iterations = cugraph_hits_result_get_number_of_iterations(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_hubs[num_vertices];
weight_t h_authorities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code =
cugraph_type_erased_device_array_view_copy_to_host(p_handle, (byte_t*)h_hubs, hubs, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
p_handle, (byte_t*)h_authorities, authorities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result_hubs[h_vertices[i]], h_hubs[i], 0.001),
"hubs results don't match");
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result_authorities[h_vertices[i]], h_authorities[i], 0.001),
"authorities results don't match");
}
cugraph_hits_result_free(p_result);
cugraph_mg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_hits(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608, 0};
weight_t h_authorities[] = {0.652703, 0.879385, 0, 1, 0.347296, 0.00009136};
double epsilon = 0.0001;
size_t max_iterations = 20;
// hits wants store_transposed = TRUE
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
TRUE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_with_transpose(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608, 0};
weight_t h_authorities[] = {0.652703, 0.879385, 0, 1, 0.347296, 0.00009136};
double epsilon = 0.0001;
size_t max_iterations = 20;
// Hits wants store_transposed = TRUE
// This call will force cugraph_hits to transpose the graph
// But we're passing src/dst backwards so the results will be the same
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_with_initial(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
size_t num_initial_hubs = 5;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_hubs[] = {0.347296, 0.532089, 1, 0.00000959, 0.00000959, 0};
weight_t h_authorities[] = {0.652704, 0.879385, 0, 1, 0.347296, 0.00002428};
vertex_t h_initial_vertices[] = {0, 1, 2, 3, 4};
weight_t h_initial_hubs[] = {0.347296, 0.532089, 1, 0.00003608, 0.00003608};
double epsilon = 0.0001;
size_t max_iterations = 20;
// Hits wants store_transposed = TRUE
// This call will force cugraph_hits to transpose the graph
// But we're passing src/dst backwards so the results will be the same
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
h_initial_vertices,
h_initial_hubs,
num_initial_hubs,
h_hubs,
h_authorities,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_bigger(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {0, 0, 0, 0, 0, 0, 0.323569, 0, 0.156401, 0, 0,
0, 0, 0, 0, 0, 0.253312, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.110617, 0, 0, 0,
0, 0, 0, 0, 0, 0.365733, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0.156401, 0, 0, 0, 0, 0.0782005};
weight_t h_authorities[] = {0, 0, 0, 0, 0, 0, 0.321874, 0, 0.123424, 0, 0,
0, 0, 0, 0, 0, 0.595522, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.0292397, 0, 0, 0,
0, 0, 0, 0, 0, 0.314164, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0.100368};
double epsilon = 0.0001;
size_t max_iterations = 20;
// Hits wants store_transposed = TRUE
// This call will force cugraph_hits to transpose the graph
// But we're passing src/dst backwards so the results will be the same
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
epsilon,
max_iterations);
}
int test_hits_bigger_normalized(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {
0, 0, 0, 0, 0, 0, 0.132381, 0, 0.0639876, 0, 0, 0, 0, 0,
0, 0, 0.103637, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.0452563, 0, 0, 0, 0, 0, 0, 0, 0, 0.149631, 0, 0, 0,
0, 0, 0, 0.409126, 0, 0, 0.0639876, 0, 0, 0, 0, 0.0319938};
weight_t h_authorities[] = {
0, 0, 0, 0, 0, 0, 0.129548, 0, 0.0496755, 0, 0, 0, 0, 0,
0, 0, 0.239688, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0.0117691, 0, 0, 0, 0, 0, 0, 0, 0, 0.126445, 0, 0, 0,
0, 0, 0, 0.402479, 0, 0, 0, 0, 0, 0, 0, 0.0403963};
double epsilon = 0.000001;
size_t max_iterations = 100;
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
TRUE,
epsilon,
max_iterations);
}
int test_hits_bigger_unnormalized(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 48;
size_t num_vertices = 54;
vertex_t h_src[] = {29, 45, 6, 8, 16, 45, 8, 16, 6, 38, 45, 45, 48, 45, 45, 45,
45, 48, 53, 45, 6, 45, 38, 45, 38, 45, 16, 45, 38, 16, 45, 45,
38, 6, 38, 45, 45, 45, 16, 38, 6, 45, 29, 45, 29, 6, 38, 6};
vertex_t h_dst[] = {45, 45, 16, 45, 6, 45, 45, 16, 45, 38, 45, 6, 45, 38, 16, 45,
45, 45, 45, 53, 29, 16, 45, 8, 8, 16, 45, 38, 45, 6, 45, 45,
6, 6, 16, 38, 16, 45, 45, 6, 16, 6, 53, 16, 38, 45, 45, 16};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
weight_t h_hubs[] = {0, 0, 0, 0, 0, 0, 0.323569, 0, 0.156401, 0, 0,
0, 0, 0, 0, 0, 0.253312, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.110617, 0, 0, 0,
0, 0, 0, 0, 0, 0.365733, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0.156401, 0, 0, 0, 0, 0.0782005};
weight_t h_authorities[] = {0, 0, 0, 0, 0, 0, 0.321874, 0, 0.123424, 0, 0,
0, 0, 0, 0, 0, 0.595522, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0.0292397, 0, 0, 0,
0, 0, 0, 0, 0, 0.314164, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0, 0, 0.100368};
double epsilon = 0.000001;
size_t max_iterations = 100;
return generic_hits_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
NULL,
NULL,
0,
h_hubs,
h_authorities,
FALSE,
FALSE,
epsilon,
max_iterations);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_hits, handle);
result |= RUN_MG_TEST(test_hits_with_transpose, handle);
result |= RUN_MG_TEST(test_hits_with_initial, handle);
result |= RUN_MG_TEST(test_hits_bigger_normalized, handle);
result |= RUN_MG_TEST(test_hits_bigger_unnormalized, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 18,899
| 42.953488
| 100
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_induced_subgraph_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_induced_subgraph_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/graph.h>
#include <cugraph_c/graph_functions.h>
#include <stdio.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
/*
* Simple check of creating a graph from a COO on device memory.
*/
int generic_induced_subgraph_test(const cugraph_resource_handle_t* handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
size_t* h_subgraph_offsets,
vertex_t* h_subgraph_vertices,
size_t num_subgraph_offsets,
vertex_t* h_result_src,
vertex_t* h_result_dst,
weight_t* h_result_wgt,
size_t* h_result_offsets,
size_t num_results)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* graph = NULL;
cugraph_type_erased_device_array_t* subgraph_offsets = NULL;
cugraph_type_erased_device_array_t* subgraph_vertices = NULL;
cugraph_type_erased_device_array_view_t* subgraph_offsets_view = NULL;
cugraph_type_erased_device_array_view_t* subgraph_vertices_view = NULL;
cugraph_induced_subgraph_result_t* result = NULL;
data_type_id_t vertex_tid = INT32;
data_type_id_t size_t_tid = SIZE_T;
size_t num_subgraph_vertices = h_subgraph_offsets[num_subgraph_offsets - 1];
ret_code = create_mg_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
if (cugraph_resource_handle_get_rank(handle) != 0) {
num_subgraph_vertices = 0;
for (int i = 0; i < num_subgraph_offsets; ++i) {
h_subgraph_offsets[i] = 0;
}
}
ret_code = cugraph_type_erased_device_array_create(
handle, num_subgraph_offsets, size_t_tid, &subgraph_offsets, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets create failed.");
ret_code = cugraph_type_erased_device_array_create(
handle, num_subgraph_vertices, vertex_tid, &subgraph_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets create failed.");
subgraph_offsets_view = cugraph_type_erased_device_array_view(subgraph_offsets);
subgraph_vertices_view = cugraph_type_erased_device_array_view(subgraph_vertices);
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, subgraph_offsets_view, (byte_t*)h_subgraph_offsets, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_offsets copy_from_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_from_host(
handle, subgraph_vertices_view, (byte_t*)h_subgraph_vertices, &ret_error);
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "subgraph_vertices copy_from_host failed.");
ret_code = cugraph_extract_induced_subgraph(handle,
graph,
subgraph_offsets_view,
subgraph_vertices_view,
// FALSE,
TRUE,
&result,
&ret_error);
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
TEST_ASSERT(
test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_extract_induced_subgraph failed.");
cugraph_type_erased_device_array_view_t* extracted_src;
cugraph_type_erased_device_array_view_t* extracted_dst;
cugraph_type_erased_device_array_view_t* extracted_wgt;
cugraph_type_erased_device_array_view_t* extracted_graph_offsets;
extracted_src = cugraph_induced_subgraph_get_sources(result);
extracted_dst = cugraph_induced_subgraph_get_destinations(result);
extracted_wgt = cugraph_induced_subgraph_get_edge_weights(result);
extracted_graph_offsets = cugraph_induced_subgraph_get_subgraph_offsets(result);
size_t extracted_size = cugraph_type_erased_device_array_view_size(extracted_src);
vertex_t h_extracted_src[extracted_size];
vertex_t h_extracted_dst[extracted_size];
weight_t h_extracted_wgt[extracted_size];
vertex_t h_extracted_graph_offsets[extracted_size];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_src, extracted_src, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_dst, extracted_dst, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_wgt, extracted_wgt, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_extracted_graph_offsets, extracted_graph_offsets, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
for (size_t i = 0; (i < extracted_size) && (test_ret_value == 0); ++i) {
bool_t found = FALSE;
for (size_t j = 0; (j < num_results) && !found; ++j) {
if ((h_extracted_src[i] == h_result_src[j]) && (h_extracted_dst[i] == h_result_dst[j]) &&
(h_extracted_wgt[i] == h_result_wgt[j]))
found = TRUE;
}
TEST_ASSERT(test_ret_value, found, "extracted an edge that doesn't match");
}
cugraph_type_erased_device_array_free(subgraph_offsets);
cugraph_type_erased_device_array_free(subgraph_vertices);
cugraph_induced_subgraph_result_free(result);
cugraph_mg_graph_free(graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_induced_subgraph(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
size_t num_subgraph_offsets = 2;
size_t num_results = 5;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
size_t h_subgraph_offsets[] = {0, 4};
vertex_t h_subgraph_vertices[] = {0, 1, 2, 3};
vertex_t h_result_src[] = {0, 1, 2, 2, 2};
vertex_t h_result_dst[] = {1, 3, 0, 1, 3};
weight_t h_result_wgt[] = {0.1f, 2.1f, 5.1f, 3.1f, 4.1f};
size_t h_result_offsets[] = {0, 5};
// Pagerank wants store_transposed = TRUE
return generic_induced_subgraph_test(handle,
h_src,
h_dst,
h_wgt,
num_vertices,
num_edges,
TRUE,
h_subgraph_offsets,
h_subgraph_vertices,
num_subgraph_offsets,
h_result_src,
h_result_dst,
h_result_wgt,
h_result_offsets,
num_results);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_induced_subgraph, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 9,133
| 42.2891
| 95
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_k_core_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_k_core_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/array.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_k_core_test(const cugraph_resource_handle_t* resource_handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
vertex_t* h_result_src,
vertex_t* h_result_dst,
weight_t* h_result_wgt,
size_t num_vertices,
size_t num_edges,
size_t num_result_edges,
size_t k,
bool_t store_transposed)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* graph = NULL;
cugraph_core_result_t* core_result = NULL;
cugraph_k_core_result_t* k_core_result = NULL;
ret_code = create_mg_test_graph(
resource_handle, h_src, h_dst, h_wgt, num_edges, store_transposed, TRUE, &graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_test_graph failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_core_number(
resource_handle, graph, K_CORE_DEGREE_TYPE_IN, FALSE, &core_result, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_core_number failed.");
TEST_ALWAYS_ASSERT(ret_code == CUGRAPH_SUCCESS, cugraph_error_message(ret_error));
ret_code = cugraph_k_core(resource_handle,
graph,
k,
K_CORE_DEGREE_TYPE_IN,
core_result,
FALSE,
&k_core_result,
&ret_error);
cugraph_type_erased_device_array_view_t* src_vertices;
cugraph_type_erased_device_array_view_t* dst_vertices;
cugraph_type_erased_device_array_view_t* weights;
src_vertices = cugraph_k_core_result_get_src_vertices(k_core_result);
dst_vertices = cugraph_k_core_result_get_dst_vertices(k_core_result);
weights = cugraph_k_core_result_get_weights(k_core_result);
size_t number_of_result_edges = cugraph_type_erased_device_array_view_size(src_vertices);
vertex_t h_src_vertices[number_of_result_edges];
vertex_t h_dst_vertices[number_of_result_edges];
weight_t h_weights[number_of_result_edges];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_src_vertices, src_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_dst_vertices, dst_vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
resource_handle, (byte_t*)h_weights, weights, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
weight_t M[num_vertices][num_vertices];
for (int i = 0; i < num_vertices; ++i)
for (int j = 0; j < num_vertices; ++j)
M[i][j] = 0;
for (int i = 0; i < num_result_edges; ++i)
M[h_result_src[i]][h_result_dst[i]] = h_result_wgt[i];
for (int i = 0; (i < number_of_result_edges) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
M[h_src_vertices[i]][h_dst_vertices[i]] == h_weights[i],
"edge does not match");
}
cugraph_k_core_result_free(k_core_result);
cugraph_core_result_free(core_result);
cugraph_mg_graph_free(graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_k_core(const cugraph_resource_handle_t* resource_handle)
{
size_t num_edges = 22;
size_t num_vertices = 7;
size_t num_result_edges = 12;
size_t k = 3;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4, 1, 3, 4, 0, 1, 3, 5, 5, 3, 1, 4, 5, 5, 6};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5, 0, 1, 1, 2, 2, 2, 3, 4, 4, 5, 3, 1, 6, 5};
weight_t h_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
vertex_t h_result_src[] = {1, 1, 3, 4, 3, 4, 3, 4, 5, 5, 1, 5};
vertex_t h_result_dst[] = {3, 4, 5, 5, 1, 3, 4, 1, 3, 4, 5, 1};
weight_t h_result_wgt[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
return generic_k_core_test(resource_handle,
h_src,
h_dst,
h_wgt,
h_result_src,
h_result_dst,
h_result_wgt,
num_vertices,
num_edges,
num_result_edges,
k,
FALSE);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_k_core, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 6,226
| 37.202454
| 97
|
c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_katz_test.c
|
cugraph-branch-23.08/cpp/tests/c_api/mg_katz_test.c
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mg_test_utils.h" /* RUN_TEST */
#include <cugraph_c/algorithms.h>
#include <cugraph_c/graph.h>
#include <math.h>
typedef int32_t vertex_t;
typedef int32_t edge_t;
typedef float weight_t;
int generic_katz_test(const cugraph_resource_handle_t* handle,
vertex_t* h_src,
vertex_t* h_dst,
weight_t* h_wgt,
weight_t* h_result,
size_t num_vertices,
size_t num_edges,
bool_t store_transposed,
double alpha,
double beta,
double epsilon,
size_t max_iterations)
{
int test_ret_value = 0;
cugraph_error_code_t ret_code = CUGRAPH_SUCCESS;
cugraph_error_t* ret_error;
cugraph_graph_t* p_graph = NULL;
cugraph_centrality_result_t* p_result = NULL;
cugraph_type_erased_device_array_view_t* betas_view = NULL;
ret_code = create_mg_test_graph(
handle, h_src, h_dst, h_wgt, num_edges, store_transposed, FALSE, &p_graph, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "create_mg_test_graph failed.");
ret_code = cugraph_katz_centrality(handle,
p_graph,
betas_view,
alpha,
beta,
epsilon,
max_iterations,
FALSE,
&p_result,
&ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "cugraph_katz_centrality failed.");
// NOTE: Because we get back vertex ids and centralities, we can simply compare
// the returned values with the expected results for the entire
// graph. Each GPU will have a subset of the total vertices, so
// they will do a subset of the comparisons.
cugraph_type_erased_device_array_view_t* vertices;
cugraph_type_erased_device_array_view_t* centralities;
vertices = cugraph_centrality_result_get_vertices(p_result);
centralities = cugraph_centrality_result_get_values(p_result);
vertex_t h_vertices[num_vertices];
weight_t h_centralities[num_vertices];
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_vertices, vertices, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
ret_code = cugraph_type_erased_device_array_view_copy_to_host(
handle, (byte_t*)h_centralities, centralities, &ret_error);
TEST_ASSERT(test_ret_value, ret_code == CUGRAPH_SUCCESS, "copy_to_host failed.");
size_t num_local_vertices = cugraph_type_erased_device_array_view_size(vertices);
for (int i = 0; (i < num_local_vertices) && (test_ret_value == 0); ++i) {
TEST_ASSERT(test_ret_value,
nearlyEqual(h_result[h_vertices[i]], h_centralities[i], 0.001),
"katz centrality results don't match");
}
cugraph_centrality_result_free(p_result);
cugraph_mg_graph_free(p_graph);
cugraph_error_free(ret_error);
return test_ret_value;
}
int test_katz(const cugraph_resource_handle_t* handle)
{
size_t num_edges = 8;
size_t num_vertices = 6;
vertex_t h_src[] = {0, 1, 1, 2, 2, 2, 3, 4};
vertex_t h_dst[] = {1, 3, 4, 0, 1, 3, 5, 5};
weight_t h_wgt[] = {0.1f, 2.1f, 1.1f, 5.1f, 3.1f, 4.1f, 7.2f, 3.2f};
weight_t h_result[] = {0.410614, 0.403211, 0.390689, 0.415175, 0.395125, 0.433226};
double alpha = 0.01;
double beta = 1.0;
double epsilon = 0.000001;
size_t max_iterations = 1000;
// Katz wants store_transposed = TRUE
return generic_katz_test(handle,
h_src,
h_dst,
h_wgt,
h_result,
num_vertices,
num_edges,
TRUE,
alpha,
beta,
epsilon,
max_iterations);
}
/******************************************************************************/
int main(int argc, char** argv)
{
void* raft_handle = create_mg_raft_handle(argc, argv);
cugraph_resource_handle_t* handle = cugraph_create_resource_handle(raft_handle);
int result = 0;
result |= RUN_MG_TEST(test_katz, handle);
cugraph_free_resource_handle(handle);
free_mg_raft_handle(raft_handle);
return result;
}
| 5,309
| 34.878378
| 94
|
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.