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
abess
abess-master/python/include/unsupported/Eigen/src/IterativeSolvers/IncompleteLU.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Gael Guennebaud <[email protected]> // // 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_INCOMPLETE_LU_H #define EIGEN_INCOMPLETE_LU_H namespace Eigen { template <typename _Scalar> class IncompleteLU : public SparseSolverBase<IncompleteLU<_Scalar> > { protected: typedef SparseSolverBase<IncompleteLU<_Scalar> > Base; using Base::m_isInitialized; typedef _Scalar Scalar; typedef Matrix<Scalar,Dynamic,1> Vector; typedef typename Vector::Index Index; typedef SparseMatrix<Scalar,RowMajor> FactorType; public: typedef Matrix<Scalar,Dynamic,Dynamic> MatrixType; IncompleteLU() {} template<typename MatrixType> IncompleteLU(const MatrixType& mat) { compute(mat); } Index rows() const { return m_lu.rows(); } Index cols() const { return m_lu.cols(); } template<typename MatrixType> IncompleteLU& compute(const MatrixType& mat) { m_lu = mat; int size = mat.cols(); Vector diag(size); for(int i=0; i<size; ++i) { typename FactorType::InnerIterator k_it(m_lu,i); for(; k_it && k_it.index()<i; ++k_it) { int k = k_it.index(); k_it.valueRef() /= diag(k); typename FactorType::InnerIterator j_it(k_it); typename FactorType::InnerIterator kj_it(m_lu, k); while(kj_it && kj_it.index()<=k) ++kj_it; for(++j_it; j_it; ) { if(kj_it.index()==j_it.index()) { j_it.valueRef() -= k_it.value() * kj_it.value(); ++j_it; ++kj_it; } else if(kj_it.index()<j_it.index()) ++kj_it; else ++j_it; } } if(k_it && k_it.index()==i) diag(i) = k_it.value(); else diag(i) = 1; } m_isInitialized = true; return *this; } template<typename Rhs, typename Dest> void _solve_impl(const Rhs& b, Dest& x) const { x = m_lu.template triangularView<UnitLower>().solve(b); x = m_lu.template triangularView<Upper>().solve(x); } protected: FactorType m_lu; }; } // end namespace Eigen #endif // EIGEN_INCOMPLETE_LU_H
2,520
26.703297
69
h
abess
abess-master/python/include/unsupported/Eigen/src/IterativeSolvers/IterationController.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <[email protected]> /* NOTE The class IterationController has been adapted from the iteration * class of the GMM++ and ITL libraries. */ //======================================================================= // Copyright (C) 1997-2001 // Authors: Andrew Lumsdaine <[email protected]> // Lie-Quan Lee <[email protected]> // // This file is part of the Iterative Template Library // // You should have received a copy of the License Agreement for the // Iterative Template Library along with the software; see the // file LICENSE. // // Permission to modify the code and to distribute modified code is // granted, provided the text of this NOTICE is retained, a notice that // the code was modified is included with the above COPYRIGHT NOTICE and // with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE // file is distributed with the modified code. // // LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. // By way of example, but not limitation, Licensor MAKES NO // REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY // PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS // OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS // OR OTHER RIGHTS. //======================================================================= //======================================================================== // // Copyright (C) 2002-2007 Yves Renard // // This file is a part of GETFEM++ // // Getfem++ is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; version 2.1 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, // USA. // //======================================================================== #include "../../../../Eigen/src/Core/util/NonMPL2.h" #ifndef EIGEN_ITERATION_CONTROLLER_H #define EIGEN_ITERATION_CONTROLLER_H namespace Eigen { /** \ingroup IterativeSolvers_Module * \class IterationController * * \brief Controls the iterations of the iterative solvers * * This class has been adapted from the iteration class of GMM++ and ITL libraries. * */ class IterationController { protected : double m_rhsn; ///< Right hand side norm size_t m_maxiter; ///< Max. number of iterations int m_noise; ///< if noise > 0 iterations are printed double m_resmax; ///< maximum residual double m_resminreach, m_resadd; size_t m_nit; ///< iteration number double m_res; ///< last computed residual bool m_written; void (*m_callback)(const IterationController&); public : void init() { m_nit = 0; m_res = 0.0; m_written = false; m_resminreach = 1E50; m_resadd = 0.0; m_callback = 0; } IterationController(double r = 1.0E-8, int noi = 0, size_t mit = size_t(-1)) : m_rhsn(1.0), m_maxiter(mit), m_noise(noi), m_resmax(r) { init(); } void operator ++(int) { m_nit++; m_written = false; m_resadd += m_res; } void operator ++() { (*this)++; } bool first() { return m_nit == 0; } /* get/set the "noisyness" (verbosity) of the solvers */ int noiseLevel() const { return m_noise; } void setNoiseLevel(int n) { m_noise = n; } void reduceNoiseLevel() { if (m_noise > 0) m_noise--; } double maxResidual() const { return m_resmax; } void setMaxResidual(double r) { m_resmax = r; } double residual() const { return m_res; } /* change the user-definable callback, called after each iteration */ void setCallback(void (*t)(const IterationController&)) { m_callback = t; } size_t iteration() const { return m_nit; } void setIteration(size_t i) { m_nit = i; } size_t maxIterarions() const { return m_maxiter; } void setMaxIterations(size_t i) { m_maxiter = i; } double rhsNorm() const { return m_rhsn; } void setRhsNorm(double r) { m_rhsn = r; } bool converged() const { return m_res <= m_rhsn * m_resmax; } bool converged(double nr) { using std::abs; m_res = abs(nr); m_resminreach = (std::min)(m_resminreach, m_res); return converged(); } template<typename VectorType> bool converged(const VectorType &v) { return converged(v.squaredNorm()); } bool finished(double nr) { if (m_callback) m_callback(*this); if (m_noise > 0 && !m_written) { converged(nr); m_written = true; } return (m_nit >= m_maxiter || converged(nr)); } template <typename VectorType> bool finished(const MatrixBase<VectorType> &v) { return finished(double(v.squaredNorm())); } }; } // end namespace Eigen #endif // EIGEN_ITERATION_CONTROLLER_H
5,354
33.548387
84
h
abess
abess-master/python/include/unsupported/Eigen/src/IterativeSolvers/Scaling.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Desire NUENTSA WAKAM <[email protected] // // 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_ITERSCALING_H #define EIGEN_ITERSCALING_H namespace Eigen { /** * \ingroup IterativeSolvers_Module * \brief iterative scaling algorithm to equilibrate rows and column norms in matrices * * This class can be used as a preprocessing tool to accelerate the convergence of iterative methods * * This feature is useful to limit the pivoting amount during LU/ILU factorization * The scaling strategy as presented here preserves the symmetry of the problem * NOTE It is assumed that the matrix does not have empty row or column, * * Example with key steps * \code * VectorXd x(n), b(n); * SparseMatrix<double> A; * // fill A and b; * IterScaling<SparseMatrix<double> > scal; * // Compute the left and right scaling vectors. The matrix is equilibrated at output * scal.computeRef(A); * // Scale the right hand side * b = scal.LeftScaling().cwiseProduct(b); * // Now, solve the equilibrated linear system with any available solver * * // Scale back the computed solution * x = scal.RightScaling().cwiseProduct(x); * \endcode * * \tparam _MatrixType the type of the matrix. It should be a real square sparsematrix * * References : D. Ruiz and B. Ucar, A Symmetry Preserving Algorithm for Matrix Scaling, INRIA Research report RR-7552 * * \sa \ref IncompleteLUT */ template<typename _MatrixType> class IterScaling { public: typedef _MatrixType MatrixType; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::Index Index; public: IterScaling() { init(); } IterScaling(const MatrixType& matrix) { init(); compute(matrix); } ~IterScaling() { } /** * Compute the left and right diagonal matrices to scale the input matrix @p mat * * FIXME This algorithm will be modified such that the diagonal elements are permuted on the diagonal. * * \sa LeftScaling() RightScaling() */ void compute (const MatrixType& mat) { using std::abs; int m = mat.rows(); int n = mat.cols(); eigen_assert((m>0 && m == n) && "Please give a non - empty matrix"); m_left.resize(m); m_right.resize(n); m_left.setOnes(); m_right.setOnes(); m_matrix = mat; VectorXd Dr, Dc, DrRes, DcRes; // Temporary Left and right scaling vectors Dr.resize(m); Dc.resize(n); DrRes.resize(m); DcRes.resize(n); double EpsRow = 1.0, EpsCol = 1.0; int its = 0; do { // Iterate until the infinite norm of each row and column is approximately 1 // Get the maximum value in each row and column Dr.setZero(); Dc.setZero(); for (int k=0; k<m_matrix.outerSize(); ++k) { for (typename MatrixType::InnerIterator it(m_matrix, k); it; ++it) { if ( Dr(it.row()) < abs(it.value()) ) Dr(it.row()) = abs(it.value()); if ( Dc(it.col()) < abs(it.value()) ) Dc(it.col()) = abs(it.value()); } } for (int i = 0; i < m; ++i) { Dr(i) = std::sqrt(Dr(i)); Dc(i) = std::sqrt(Dc(i)); } // Save the scaling factors for (int i = 0; i < m; ++i) { m_left(i) /= Dr(i); m_right(i) /= Dc(i); } // Scale the rows and the columns of the matrix DrRes.setZero(); DcRes.setZero(); for (int k=0; k<m_matrix.outerSize(); ++k) { for (typename MatrixType::InnerIterator it(m_matrix, k); it; ++it) { it.valueRef() = it.value()/( Dr(it.row()) * Dc(it.col()) ); // Accumulate the norms of the row and column vectors if ( DrRes(it.row()) < abs(it.value()) ) DrRes(it.row()) = abs(it.value()); if ( DcRes(it.col()) < abs(it.value()) ) DcRes(it.col()) = abs(it.value()); } } DrRes.array() = (1-DrRes.array()).abs(); EpsRow = DrRes.maxCoeff(); DcRes.array() = (1-DcRes.array()).abs(); EpsCol = DcRes.maxCoeff(); its++; }while ( (EpsRow >m_tol || EpsCol > m_tol) && (its < m_maxits) ); m_isInitialized = true; } /** Compute the left and right vectors to scale the vectors * the input matrix is scaled with the computed vectors at output * * \sa compute() */ void computeRef (MatrixType& mat) { compute (mat); mat = m_matrix; } /** Get the vector to scale the rows of the matrix */ VectorXd& LeftScaling() { return m_left; } /** Get the vector to scale the columns of the matrix */ VectorXd& RightScaling() { return m_right; } /** Set the tolerance for the convergence of the iterative scaling algorithm */ void setTolerance(double tol) { m_tol = tol; } protected: void init() { m_tol = 1e-10; m_maxits = 5; m_isInitialized = false; } MatrixType m_matrix; mutable ComputationInfo m_info; bool m_isInitialized; VectorXd m_left; // Left scaling vector VectorXd m_right; // m_right scaling vector double m_tol; int m_maxits; // Maximum number of iterations allowed }; } #endif
5,739
29.531915
119
h
abess
abess-master/python/include/unsupported/Eigen/src/LevenbergMarquardt/LMcovar.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // This code initially comes from MINPACK whose original authors are: // Copyright Jorge More - Argonne National Laboratory // Copyright Burt Garbow - Argonne National Laboratory // Copyright Ken Hillstrom - Argonne National Laboratory // // This Source Code Form is subject to the terms of the Minpack license // (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. #ifndef EIGEN_LMCOVAR_H #define EIGEN_LMCOVAR_H namespace Eigen { namespace internal { template <typename Scalar> void covar( Matrix< Scalar, Dynamic, Dynamic > &r, const VectorXi& ipvt, Scalar tol = std::sqrt(NumTraits<Scalar>::epsilon()) ) { using std::abs; /* Local variables */ Index i, j, k, l, ii, jj; bool sing; Scalar temp; /* Function Body */ const Index n = r.cols(); const Scalar tolr = tol * abs(r(0,0)); Matrix< Scalar, Dynamic, 1 > wa(n); eigen_assert(ipvt.size()==n); /* form the inverse of r in the full upper triangle of r. */ l = -1; for (k = 0; k < n; ++k) if (abs(r(k,k)) > tolr) { r(k,k) = 1. / r(k,k); for (j = 0; j <= k-1; ++j) { temp = r(k,k) * r(j,k); r(j,k) = 0.; r.col(k).head(j+1) -= r.col(j).head(j+1) * temp; } l = k; } /* form the full upper triangle of the inverse of (r transpose)*r */ /* in the full upper triangle of r. */ for (k = 0; k <= l; ++k) { for (j = 0; j <= k-1; ++j) r.col(j).head(j+1) += r.col(k).head(j+1) * r(j,k); r.col(k).head(k+1) *= r(k,k); } /* form the full lower triangle of the covariance matrix */ /* in the strict lower triangle of r and in wa. */ for (j = 0; j < n; ++j) { jj = ipvt[j]; sing = j > l; for (i = 0; i <= j; ++i) { if (sing) r(i,j) = 0.; ii = ipvt[i]; if (ii > jj) r(ii,jj) = r(i,j); if (ii < jj) r(jj,ii) = r(i,j); } wa[jj] = r(j,j); } /* symmetrize the covariance matrix in r. */ r.topLeftCorner(n,n).template triangularView<StrictlyUpper>() = r.topLeftCorner(n,n).transpose(); r.diagonal() = wa; } } // end namespace internal } // end namespace Eigen #endif // EIGEN_LMCOVAR_H
2,443
27.752941
101
h
abess
abess-master/python/include/unsupported/Eigen/src/LevenbergMarquardt/LMpar.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // This code initially comes from MINPACK whose original authors are: // Copyright Jorge More - Argonne National Laboratory // Copyright Burt Garbow - Argonne National Laboratory // Copyright Ken Hillstrom - Argonne National Laboratory // // This Source Code Form is subject to the terms of the Minpack license // (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. #ifndef EIGEN_LMPAR_H #define EIGEN_LMPAR_H namespace Eigen { namespace internal { template <typename QRSolver, typename VectorType> void lmpar2( const QRSolver &qr, const VectorType &diag, const VectorType &qtb, typename VectorType::Scalar m_delta, typename VectorType::Scalar &par, VectorType &x) { using std::sqrt; using std::abs; typedef typename QRSolver::MatrixType MatrixType; typedef typename QRSolver::Scalar Scalar; // typedef typename QRSolver::StorageIndex StorageIndex; /* Local variables */ Index j; Scalar fp; Scalar parc, parl; Index iter; Scalar temp, paru; Scalar gnorm; Scalar dxnorm; // Make a copy of the triangular factor. // This copy is modified during call the qrsolv MatrixType s; s = qr.matrixR(); /* Function Body */ const Scalar dwarf = (std::numeric_limits<Scalar>::min)(); const Index n = qr.matrixR().cols(); eigen_assert(n==diag.size()); eigen_assert(n==qtb.size()); VectorType 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(); //FIXME There is no solve in place for sparse triangularView wa1.head(rank) = s.topLeftCorner(rank,rank).template triangularView<Upper>().solve(qtb.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 - m_delta; if (fp <= Scalar(0.1) * m_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; s.topLeftCorner(n,n).transpose().template triangularView<Lower>().solveInPlace(wa1); temp = wa1.blueNorm(); parl = fp / m_delta / temp / temp; } /* calculate an upper bound, paru, for the zero of the function. */ for (j = 0; j < n; ++j) wa1[j] = s.col(j).head(j+1).dot(qtb.head(j+1)) / diag[qr.colsPermutation().indices()(j)]; gnorm = wa1.stableNorm(); paru = gnorm / m_delta; if (paru == 0.) paru = dwarf / (std::min)(m_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; VectorType sdiag(n); lmqrsolv(s, qr.colsPermutation(), wa1, qtb, x, sdiag); wa2 = diag.cwiseProduct(x); dxnorm = wa2.blueNorm(); temp = fp; fp = dxnorm - m_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) * m_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[] for (j = 0; j < n; ++j) { wa1[j] /= sdiag[j]; temp = wa1[j]; for (Index i = j+1; i < n; ++i) wa1[i] -= s.coeff(i,j) * temp; } temp = wa1.blueNorm(); parc = fp / m_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 #endif // EIGEN_LMPAR_H
5,039
30.304348
103
h
abess
abess-master/python/include/unsupported/Eigen/src/LevenbergMarquardt/LMqrsolv.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Thomas Capricelli <[email protected]> // Copyright (C) 2012 Desire Nuentsa <[email protected]> // // This code initially comes from MINPACK whose original authors are: // Copyright Jorge More - Argonne National Laboratory // Copyright Burt Garbow - Argonne National Laboratory // Copyright Ken Hillstrom - Argonne National Laboratory // // This Source Code Form is subject to the terms of the Minpack license // (a BSD-like license) described in the campaigned CopyrightMINPACK.txt file. #ifndef EIGEN_LMQRSOLV_H #define EIGEN_LMQRSOLV_H namespace Eigen { namespace internal { template <typename Scalar,int Rows, int Cols, typename PermIndex> void lmqrsolv( Matrix<Scalar,Rows,Cols> &s, const PermutationMatrix<Dynamic,Dynamic,PermIndex> &iPerm, const Matrix<Scalar,Dynamic,1> &diag, const Matrix<Scalar,Dynamic,1> &qtb, Matrix<Scalar,Dynamic,1> &x, Matrix<Scalar,Dynamic,1> &sdiag) { /* Local variables */ Index i, j, k; 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. */ const PermIndex l = iPerm.indices()(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 tranformation 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. */ x = iPerm * wa; } template <typename Scalar, int _Options, typename Index> void lmqrsolv( SparseMatrix<Scalar,_Options,Index> &s, const PermutationMatrix<Dynamic,Dynamic> &iPerm, const Matrix<Scalar,Dynamic,1> &diag, const Matrix<Scalar,Dynamic,1> &qtb, Matrix<Scalar,Dynamic,1> &x, Matrix<Scalar,Dynamic,1> &sdiag) { /* Local variables */ typedef SparseMatrix<Scalar,RowMajor,Index> FactorType; 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 R. */ wa = qtb; FactorType R(s); // 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 = iPerm.indices()(j); if (diag(l) == Scalar(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; // Browse the nonzero elements of row j of the upper triangular s for (k = j; k < n; ++k) { typename FactorType::InnerIterator itk(R,k); for (; itk; ++itk){ if (itk.index() < k) continue; else break; } //At this point, we have the diagonal element R(k,k) // Determine a givens rotation which eliminates // the appropriate element in the current row of d givens.makeGivens(-itk.value(), sdiag(k)); // Compute the modified diagonal element of r and // the modified element of ((q transpose)*b,0). itk.valueRef() = givens.c() * itk.value() + 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 remaining k row/column of R for (++itk; itk; ++itk) { i = itk.index(); temp = givens.c() * itk.value() + givens.s() * sdiag(i); sdiag(i) = -givens.s() * itk.value() + givens.c() * sdiag(i); itk.valueRef() = 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(); // x = wa; wa.head(nsing) = R.topLeftCorner(nsing,nsing).template triangularView<Upper>().solve/*InPlace*/(wa.head(nsing)); sdiag = R.diagonal(); // Permute the components of z back to components of x x = iPerm * wa; } } // end namespace internal } // end namespace Eigen #endif // EIGEN_LMQRSOLV_H
6,804
35.005291
116
h
abess
abess-master/python/include/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009, 2010, 2013 Jitse Niesen <[email protected]> // Copyright (C) 2011, 2013 Chen-Pang He <[email protected]> // // 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_MATRIX_EXPONENTIAL #define EIGEN_MATRIX_EXPONENTIAL #include "StemFunction.h" namespace Eigen { namespace internal { /** \brief Scaling operator. * * This struct is used by CwiseUnaryOp to scale a matrix by \f$ 2^{-s} \f$. */ template <typename RealScalar> struct MatrixExponentialScalingOp { /** \brief Constructor. * * \param[in] squarings The integer \f$ s \f$ in this document. */ MatrixExponentialScalingOp(int squarings) : m_squarings(squarings) { } /** \brief Scale a matrix coefficient. * * \param[in,out] x The scalar to be scaled, becoming \f$ 2^{-s} x \f$. */ inline const RealScalar operator() (const RealScalar& x) const { using std::ldexp; return ldexp(x, -m_squarings); } typedef std::complex<RealScalar> ComplexScalar; /** \brief Scale a matrix coefficient. * * \param[in,out] x The scalar to be scaled, becoming \f$ 2^{-s} x \f$. */ inline const ComplexScalar operator() (const ComplexScalar& x) const { using std::ldexp; return ComplexScalar(ldexp(x.real(), -m_squarings), ldexp(x.imag(), -m_squarings)); } private: int m_squarings; }; /** \brief Compute the (3,3)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. */ template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade3(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatA>::Scalar>::Real RealScalar; const RealScalar b[] = {120.L, 60.L, 12.L, 1.L}; const MatrixType A2 = A * A; const MatrixType tmp = b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; V = b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } /** \brief Compute the (5,5)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. */ template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade5(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatrixType>::Scalar>::Real RealScalar; const RealScalar b[] = {30240.L, 15120.L, 3360.L, 420.L, 30.L, 1.L}; const MatrixType A2 = A * A; const MatrixType A4 = A2 * A2; const MatrixType tmp = b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; V = b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } /** \brief Compute the (7,7)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. */ template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade7(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatrixType>::Scalar>::Real RealScalar; const RealScalar b[] = {17297280.L, 8648640.L, 1995840.L, 277200.L, 25200.L, 1512.L, 56.L, 1.L}; const MatrixType A2 = A * A; const MatrixType A4 = A2 * A2; const MatrixType A6 = A4 * A2; const MatrixType tmp = b[7] * A6 + b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; V = b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } /** \brief Compute the (9,9)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. */ template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade9(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatrixType>::Scalar>::Real RealScalar; const RealScalar b[] = {17643225600.L, 8821612800.L, 2075673600.L, 302702400.L, 30270240.L, 2162160.L, 110880.L, 3960.L, 90.L, 1.L}; const MatrixType A2 = A * A; const MatrixType A4 = A2 * A2; const MatrixType A6 = A4 * A2; const MatrixType A8 = A6 * A2; const MatrixType tmp = b[9] * A8 + b[7] * A6 + b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; V = b[8] * A8 + b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } /** \brief Compute the (13,13)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. */ template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade13(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatrixType>::Scalar>::Real RealScalar; const RealScalar b[] = {64764752532480000.L, 32382376266240000.L, 7771770303897600.L, 1187353796428800.L, 129060195264000.L, 10559470521600.L, 670442572800.L, 33522128640.L, 1323241920.L, 40840800.L, 960960.L, 16380.L, 182.L, 1.L}; const MatrixType A2 = A * A; const MatrixType A4 = A2 * A2; const MatrixType A6 = A4 * A2; V = b[13] * A6 + b[11] * A4 + b[9] * A2; // used for temporary storage MatrixType tmp = A6 * V; tmp += b[7] * A6 + b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; tmp = b[12] * A6 + b[10] * A4 + b[8] * A2; V.noalias() = A6 * tmp; V += b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } /** \brief Compute the (17,17)-Pad&eacute; approximant to the exponential. * * After exit, \f$ (V+U)(V-U)^{-1} \f$ is the Pad&eacute; * approximant of \f$ \exp(A) \f$ around \f$ A = 0 \f$. * * This function activates only if your long double is double-double or quadruple. */ #if LDBL_MANT_DIG > 64 template <typename MatA, typename MatU, typename MatV> void matrix_exp_pade17(const MatA& A, MatU& U, MatV& V) { typedef typename MatA::PlainObject MatrixType; typedef typename NumTraits<typename traits<MatrixType>::Scalar>::Real RealScalar; const RealScalar b[] = {830034394580628357120000.L, 415017197290314178560000.L, 100610229646136770560000.L, 15720348382208870400000.L, 1774878043152614400000.L, 153822763739893248000.L, 10608466464820224000.L, 595373117923584000.L, 27563570274240000.L, 1060137318240000.L, 33924394183680.L, 899510451840.L, 19554575040.L, 341863200.L, 4651200.L, 46512.L, 306.L, 1.L}; const MatrixType A2 = A * A; const MatrixType A4 = A2 * A2; const MatrixType A6 = A4 * A2; const MatrixType A8 = A4 * A4; V = b[17] * A8 + b[15] * A6 + b[13] * A4 + b[11] * A2; // used for temporary storage MatrixType tmp = A8 * V; tmp += b[9] * A8 + b[7] * A6 + b[5] * A4 + b[3] * A2 + b[1] * MatrixType::Identity(A.rows(), A.cols()); U.noalias() = A * tmp; tmp = b[16] * A8 + b[14] * A6 + b[12] * A4 + b[10] * A2; V.noalias() = tmp * A8; V += b[8] * A8 + b[6] * A6 + b[4] * A4 + b[2] * A2 + b[0] * MatrixType::Identity(A.rows(), A.cols()); } #endif template <typename MatrixType, typename RealScalar = typename NumTraits<typename traits<MatrixType>::Scalar>::Real> struct matrix_exp_computeUV { /** \brief Compute Pad&eacute; approximant to the exponential. * * Computes \c U, \c V and \c squarings such that \f$ (V+U)(V-U)^{-1} \f$ is a Pad&eacute; * approximant of \f$ \exp(2^{-\mbox{squarings}}M) \f$ around \f$ M = 0 \f$, where \f$ M \f$ * denotes the matrix \c arg. The degree of the Pad&eacute; approximant and the value of squarings * are chosen such that the approximation error is no more than the round-off error. */ static void run(const MatrixType& arg, MatrixType& U, MatrixType& V, int& squarings); }; template <typename MatrixType> struct matrix_exp_computeUV<MatrixType, float> { template <typename ArgType> static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) { using std::frexp; using std::pow; const float l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); squarings = 0; if (l1norm < 4.258730016922831e-001f) { matrix_exp_pade3(arg, U, V); } else if (l1norm < 1.880152677804762e+000f) { matrix_exp_pade5(arg, U, V); } else { const float maxnorm = 3.925724783138660f; frexp(l1norm / maxnorm, &squarings); if (squarings < 0) squarings = 0; MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp<float>(squarings)); matrix_exp_pade7(A, U, V); } } }; template <typename MatrixType> struct matrix_exp_computeUV<MatrixType, double> { template <typename ArgType> static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) { using std::frexp; using std::pow; const double l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); squarings = 0; if (l1norm < 1.495585217958292e-002) { matrix_exp_pade3(arg, U, V); } else if (l1norm < 2.539398330063230e-001) { matrix_exp_pade5(arg, U, V); } else if (l1norm < 9.504178996162932e-001) { matrix_exp_pade7(arg, U, V); } else if (l1norm < 2.097847961257068e+000) { matrix_exp_pade9(arg, U, V); } else { const double maxnorm = 5.371920351148152; frexp(l1norm / maxnorm, &squarings); if (squarings < 0) squarings = 0; MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp<double>(squarings)); matrix_exp_pade13(A, U, V); } } }; template <typename MatrixType> struct matrix_exp_computeUV<MatrixType, long double> { template <typename ArgType> static void run(const ArgType& arg, MatrixType& U, MatrixType& V, int& squarings) { #if LDBL_MANT_DIG == 53 // double precision matrix_exp_computeUV<MatrixType, double>::run(arg, U, V, squarings); #else using std::frexp; using std::pow; const long double l1norm = arg.cwiseAbs().colwise().sum().maxCoeff(); squarings = 0; #if LDBL_MANT_DIG <= 64 // extended precision if (l1norm < 4.1968497232266989671e-003L) { matrix_exp_pade3(arg, U, V); } else if (l1norm < 1.1848116734693823091e-001L) { matrix_exp_pade5(arg, U, V); } else if (l1norm < 5.5170388480686700274e-001L) { matrix_exp_pade7(arg, U, V); } else if (l1norm < 1.3759868875587845383e+000L) { matrix_exp_pade9(arg, U, V); } else { const long double maxnorm = 4.0246098906697353063L; frexp(l1norm / maxnorm, &squarings); if (squarings < 0) squarings = 0; MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp<long double>(squarings)); matrix_exp_pade13(A, U, V); } #elif LDBL_MANT_DIG <= 106 // double-double if (l1norm < 3.2787892205607026992947488108213e-005L) { matrix_exp_pade3(arg, U, V); } else if (l1norm < 6.4467025060072760084130906076332e-003L) { matrix_exp_pade5(arg, U, V); } else if (l1norm < 6.8988028496595374751374122881143e-002L) { matrix_exp_pade7(arg, U, V); } else if (l1norm < 2.7339737518502231741495857201670e-001L) { matrix_exp_pade9(arg, U, V); } else if (l1norm < 1.3203382096514474905666448850278e+000L) { matrix_exp_pade13(arg, U, V); } else { const long double maxnorm = 3.2579440895405400856599663723517L; frexp(l1norm / maxnorm, &squarings); if (squarings < 0) squarings = 0; MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp<long double>(squarings)); matrix_exp_pade17(A, U, V); } #elif LDBL_MANT_DIG <= 112 // quadruple precison if (l1norm < 1.639394610288918690547467954466970e-005L) { matrix_exp_pade3(arg, U, V); } else if (l1norm < 4.253237712165275566025884344433009e-003L) { matrix_exp_pade5(arg, U, V); } else if (l1norm < 5.125804063165764409885122032933142e-002L) { matrix_exp_pade7(arg, U, V); } else if (l1norm < 2.170000765161155195453205651889853e-001L) { matrix_exp_pade9(arg, U, V); } else if (l1norm < 1.125358383453143065081397882891878e+000L) { matrix_exp_pade13(arg, U, V); } else { frexp(l1norm / maxnorm, &squarings); if (squarings < 0) squarings = 0; MatrixType A = arg.unaryExpr(MatrixExponentialScalingOp<long double>(squarings)); matrix_exp_pade17(A, U, V); } #else // this case should be handled in compute() eigen_assert(false && "Bug in MatrixExponential"); #endif #endif // LDBL_MANT_DIG } }; /* Computes the matrix exponential * * \param arg argument of matrix exponential (should be plain object) * \param result variable in which result will be stored */ template <typename ArgType, typename ResultType> void matrix_exp_compute(const ArgType& arg, ResultType &result) { typedef typename ArgType::PlainObject MatrixType; #if LDBL_MANT_DIG > 112 // rarely happens typedef typename traits<MatrixType>::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef typename std::complex<RealScalar> ComplexScalar; if (sizeof(RealScalar) > 14) { result = arg.matrixFunction(internal::stem_function_exp<ComplexScalar>); return; } #endif MatrixType U, V; int squarings; matrix_exp_computeUV<MatrixType>::run(arg, U, V, squarings); // Pade approximant is (U+V) / (-U+V) MatrixType numer = U + V; MatrixType denom = -U + V; result = denom.partialPivLu().solve(numer); for (int i=0; i<squarings; i++) result *= result; // undo scaling by repeated squaring } } // end namespace Eigen::internal /** \ingroup MatrixFunctions_Module * * \brief Proxy for the matrix exponential of some matrix (expression). * * \tparam Derived Type of the argument to the matrix exponential. * * This class holds the argument to the matrix exponential until it is assigned or evaluated for * some other reason (so the argument should not be changed in the meantime). It is the return type * of MatrixBase::exp() and most of the time this is the only way it is used. */ template<typename Derived> struct MatrixExponentialReturnValue : public ReturnByValue<MatrixExponentialReturnValue<Derived> > { typedef typename Derived::Index Index; public: /** \brief Constructor. * * \param src %Matrix (expression) forming the argument of the matrix exponential. */ MatrixExponentialReturnValue(const Derived& src) : m_src(src) { } /** \brief Compute the matrix exponential. * * \param result the matrix exponential of \p src in the constructor. */ template <typename ResultType> inline void evalTo(ResultType& result) const { const typename internal::nested_eval<Derived, 10>::type tmp(m_src); internal::matrix_exp_compute(tmp, result); } Index rows() const { return m_src.rows(); } Index cols() const { return m_src.cols(); } protected: const typename internal::ref_selector<Derived>::type m_src; }; namespace internal { template<typename Derived> struct traits<MatrixExponentialReturnValue<Derived> > { typedef typename Derived::PlainObject ReturnType; }; } template <typename Derived> const MatrixExponentialReturnValue<Derived> MatrixBase<Derived>::exp() const { eigen_assert(rows() == cols()); return MatrixExponentialReturnValue<Derived>(derived()); } } // end namespace Eigen #endif // EIGEN_MATRIX_EXPONENTIAL
16,020
36
115
h
abess
abess-master/python/include/unsupported/Eigen/src/MatrixFunctions/MatrixLogarithm.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011, 2013 Jitse Niesen <[email protected]> // Copyright (C) 2011 Chen-Pang He <[email protected]> // // 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_MATRIX_LOGARITHM #define EIGEN_MATRIX_LOGARITHM namespace Eigen { namespace internal { template <typename Scalar> struct matrix_log_min_pade_degree { static const int value = 3; }; template <typename Scalar> struct matrix_log_max_pade_degree { typedef typename NumTraits<Scalar>::Real RealScalar; static const int value = std::numeric_limits<RealScalar>::digits<= 24? 5: // single precision std::numeric_limits<RealScalar>::digits<= 53? 7: // double precision std::numeric_limits<RealScalar>::digits<= 64? 8: // extended precision std::numeric_limits<RealScalar>::digits<=106? 10: // double-double 11; // quadruple precision }; /** \brief Compute logarithm of 2x2 triangular matrix. */ template <typename MatrixType> void matrix_log_compute_2x2(const MatrixType& A, MatrixType& result) { typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; using std::abs; using std::ceil; using std::imag; using std::log; Scalar logA00 = log(A(0,0)); Scalar logA11 = log(A(1,1)); result(0,0) = logA00; result(1,0) = Scalar(0); result(1,1) = logA11; Scalar y = A(1,1) - A(0,0); if (y==Scalar(0)) { result(0,1) = A(0,1) / A(0,0); } else if ((abs(A(0,0)) < RealScalar(0.5)*abs(A(1,1))) || (abs(A(0,0)) > 2*abs(A(1,1)))) { result(0,1) = A(0,1) * (logA11 - logA00) / y; } else { // computation in previous branch is inaccurate if A(1,1) \approx A(0,0) int unwindingNumber = static_cast<int>(ceil((imag(logA11 - logA00) - RealScalar(EIGEN_PI)) / RealScalar(2*EIGEN_PI))); result(0,1) = A(0,1) * (numext::log1p(y/A(0,0)) + Scalar(0,2*EIGEN_PI*unwindingNumber)) / y; } } /* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = float) */ inline int matrix_log_get_pade_degree(float normTminusI) { const float maxNormForPade[] = { 2.5111573934555054e-1 /* degree = 3 */ , 4.0535837411880493e-1, 5.3149729967117310e-1 }; const int minPadeDegree = matrix_log_min_pade_degree<float>::value; const int maxPadeDegree = matrix_log_max_pade_degree<float>::value; int degree = minPadeDegree; for (; degree <= maxPadeDegree; ++degree) if (normTminusI <= maxNormForPade[degree - minPadeDegree]) break; return degree; } /* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = double) */ inline int matrix_log_get_pade_degree(double normTminusI) { const double maxNormForPade[] = { 1.6206284795015624e-2 /* degree = 3 */ , 5.3873532631381171e-2, 1.1352802267628681e-1, 1.8662860613541288e-1, 2.642960831111435e-1 }; const int minPadeDegree = matrix_log_min_pade_degree<double>::value; const int maxPadeDegree = matrix_log_max_pade_degree<double>::value; int degree = minPadeDegree; for (; degree <= maxPadeDegree; ++degree) if (normTminusI <= maxNormForPade[degree - minPadeDegree]) break; return degree; } /* \brief Get suitable degree for Pade approximation. (specialized for RealScalar = long double) */ inline int matrix_log_get_pade_degree(long double normTminusI) { #if LDBL_MANT_DIG == 53 // double precision const long double maxNormForPade[] = { 1.6206284795015624e-2L /* degree = 3 */ , 5.3873532631381171e-2L, 1.1352802267628681e-1L, 1.8662860613541288e-1L, 2.642960831111435e-1L }; #elif LDBL_MANT_DIG <= 64 // extended precision const long double maxNormForPade[] = { 5.48256690357782863103e-3L /* degree = 3 */, 2.34559162387971167321e-2L, 5.84603923897347449857e-2L, 1.08486423756725170223e-1L, 1.68385767881294446649e-1L, 2.32777776523703892094e-1L }; #elif LDBL_MANT_DIG <= 106 // double-double const long double maxNormForPade[] = { 8.58970550342939562202529664318890e-5L /* degree = 3 */, 9.34074328446359654039446552677759e-4L, 4.26117194647672175773064114582860e-3L, 1.21546224740281848743149666560464e-2L, 2.61100544998339436713088248557444e-2L, 4.66170074627052749243018566390567e-2L, 7.32585144444135027565872014932387e-2L, 1.05026503471351080481093652651105e-1L }; #else // quadruple precision const long double maxNormForPade[] = { 4.7419931187193005048501568167858103e-5L /* degree = 3 */, 5.8853168473544560470387769480192666e-4L, 2.9216120366601315391789493628113520e-3L, 8.8415758124319434347116734705174308e-3L, 1.9850836029449446668518049562565291e-2L, 3.6688019729653446926585242192447447e-2L, 5.9290962294020186998954055264528393e-2L, 8.6998436081634343903250580992127677e-2L, 1.1880960220216759245467951592883642e-1L }; #endif const int minPadeDegree = matrix_log_min_pade_degree<long double>::value; const int maxPadeDegree = matrix_log_max_pade_degree<long double>::value; int degree = minPadeDegree; for (; degree <= maxPadeDegree; ++degree) if (normTminusI <= maxNormForPade[degree - minPadeDegree]) break; return degree; } /* \brief Compute Pade approximation to matrix logarithm */ template <typename MatrixType> void matrix_log_compute_pade(MatrixType& result, const MatrixType& T, int degree) { typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; const int minPadeDegree = 3; const int maxPadeDegree = 11; assert(degree >= minPadeDegree && degree <= maxPadeDegree); const RealScalar nodes[][maxPadeDegree] = { { 0.1127016653792583114820734600217600L, 0.5000000000000000000000000000000000L, // degree 3 0.8872983346207416885179265399782400L }, { 0.0694318442029737123880267555535953L, 0.3300094782075718675986671204483777L, // degree 4 0.6699905217924281324013328795516223L, 0.9305681557970262876119732444464048L }, { 0.0469100770306680036011865608503035L, 0.2307653449471584544818427896498956L, // degree 5 0.5000000000000000000000000000000000L, 0.7692346550528415455181572103501044L, 0.9530899229693319963988134391496965L }, { 0.0337652428984239860938492227530027L, 0.1693953067668677431693002024900473L, // degree 6 0.3806904069584015456847491391596440L, 0.6193095930415984543152508608403560L, 0.8306046932331322568306997975099527L, 0.9662347571015760139061507772469973L }, { 0.0254460438286207377369051579760744L, 0.1292344072003027800680676133596058L, // degree 7 0.2970774243113014165466967939615193L, 0.5000000000000000000000000000000000L, 0.7029225756886985834533032060384807L, 0.8707655927996972199319323866403942L, 0.9745539561713792622630948420239256L }, { 0.0198550717512318841582195657152635L, 0.1016667612931866302042230317620848L, // degree 8 0.2372337950418355070911304754053768L, 0.4082826787521750975302619288199080L, 0.5917173212478249024697380711800920L, 0.7627662049581644929088695245946232L, 0.8983332387068133697957769682379152L, 0.9801449282487681158417804342847365L }, { 0.0159198802461869550822118985481636L, 0.0819844463366821028502851059651326L, // degree 9 0.1933142836497048013456489803292629L, 0.3378732882980955354807309926783317L, 0.5000000000000000000000000000000000L, 0.6621267117019044645192690073216683L, 0.8066857163502951986543510196707371L, 0.9180155536633178971497148940348674L, 0.9840801197538130449177881014518364L }, { 0.0130467357414141399610179939577740L, 0.0674683166555077446339516557882535L, // degree 10 0.1602952158504877968828363174425632L, 0.2833023029353764046003670284171079L, 0.4255628305091843945575869994351400L, 0.5744371694908156054424130005648600L, 0.7166976970646235953996329715828921L, 0.8397047841495122031171636825574368L, 0.9325316833444922553660483442117465L, 0.9869532642585858600389820060422260L }, { 0.0108856709269715035980309994385713L, 0.0564687001159523504624211153480364L, // degree 11 0.1349239972129753379532918739844233L, 0.2404519353965940920371371652706952L, 0.3652284220238275138342340072995692L, 0.5000000000000000000000000000000000L, 0.6347715779761724861657659927004308L, 0.7595480646034059079628628347293048L, 0.8650760027870246620467081260155767L, 0.9435312998840476495375788846519636L, 0.9891143290730284964019690005614287L } }; const RealScalar weights[][maxPadeDegree] = { { 0.2777777777777777777777777777777778L, 0.4444444444444444444444444444444444L, // degree 3 0.2777777777777777777777777777777778L }, { 0.1739274225687269286865319746109997L, 0.3260725774312730713134680253890003L, // degree 4 0.3260725774312730713134680253890003L, 0.1739274225687269286865319746109997L }, { 0.1184634425280945437571320203599587L, 0.2393143352496832340206457574178191L, // degree 5 0.2844444444444444444444444444444444L, 0.2393143352496832340206457574178191L, 0.1184634425280945437571320203599587L }, { 0.0856622461895851725201480710863665L, 0.1803807865240693037849167569188581L, // degree 6 0.2339569672863455236949351719947755L, 0.2339569672863455236949351719947755L, 0.1803807865240693037849167569188581L, 0.0856622461895851725201480710863665L }, { 0.0647424830844348466353057163395410L, 0.1398526957446383339507338857118898L, // degree 7 0.1909150252525594724751848877444876L, 0.2089795918367346938775510204081633L, 0.1909150252525594724751848877444876L, 0.1398526957446383339507338857118898L, 0.0647424830844348466353057163395410L }, { 0.0506142681451881295762656771549811L, 0.1111905172266872352721779972131204L, // degree 8 0.1568533229389436436689811009933007L, 0.1813418916891809914825752246385978L, 0.1813418916891809914825752246385978L, 0.1568533229389436436689811009933007L, 0.1111905172266872352721779972131204L, 0.0506142681451881295762656771549811L }, { 0.0406371941807872059859460790552618L, 0.0903240803474287020292360156214564L, // degree 9 0.1303053482014677311593714347093164L, 0.1561735385200014200343152032922218L, 0.1651196775006298815822625346434870L, 0.1561735385200014200343152032922218L, 0.1303053482014677311593714347093164L, 0.0903240803474287020292360156214564L, 0.0406371941807872059859460790552618L }, { 0.0333356721543440687967844049466659L, 0.0747256745752902965728881698288487L, // degree 10 0.1095431812579910219977674671140816L, 0.1346333596549981775456134607847347L, 0.1477621123573764350869464973256692L, 0.1477621123573764350869464973256692L, 0.1346333596549981775456134607847347L, 0.1095431812579910219977674671140816L, 0.0747256745752902965728881698288487L, 0.0333356721543440687967844049466659L }, { 0.0278342835580868332413768602212743L, 0.0627901847324523123173471496119701L, // degree 11 0.0931451054638671257130488207158280L, 0.1165968822959952399592618524215876L, 0.1314022722551233310903444349452546L, 0.1364625433889503153572417641681711L, 0.1314022722551233310903444349452546L, 0.1165968822959952399592618524215876L, 0.0931451054638671257130488207158280L, 0.0627901847324523123173471496119701L, 0.0278342835580868332413768602212743L } }; MatrixType TminusI = T - MatrixType::Identity(T.rows(), T.rows()); result.setZero(T.rows(), T.rows()); for (int k = 0; k < degree; ++k) { RealScalar weight = weights[degree-minPadeDegree][k]; RealScalar node = nodes[degree-minPadeDegree][k]; result += weight * (MatrixType::Identity(T.rows(), T.rows()) + node * TminusI) .template triangularView<Upper>().solve(TminusI); } } /** \brief Compute logarithm of triangular matrices with size > 2. * \details This uses a inverse scale-and-square algorithm. */ template <typename MatrixType> void matrix_log_compute_big(const MatrixType& A, MatrixType& result) { typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; using std::pow; int numberOfSquareRoots = 0; int numberOfExtraSquareRoots = 0; int degree; MatrixType T = A, sqrtT; int maxPadeDegree = matrix_log_max_pade_degree<Scalar>::value; const RealScalar maxNormForPade = maxPadeDegree<= 5? 5.3149729967117310e-1L: // single precision maxPadeDegree<= 7? 2.6429608311114350e-1L: // double precision maxPadeDegree<= 8? 2.32777776523703892094e-1L: // extended precision maxPadeDegree<=10? 1.05026503471351080481093652651105e-1L: // double-double 1.1880960220216759245467951592883642e-1L; // quadruple precision while (true) { RealScalar normTminusI = (T - MatrixType::Identity(T.rows(), T.rows())).cwiseAbs().colwise().sum().maxCoeff(); if (normTminusI < maxNormForPade) { degree = matrix_log_get_pade_degree(normTminusI); int degree2 = matrix_log_get_pade_degree(normTminusI / RealScalar(2)); if ((degree - degree2 <= 1) || (numberOfExtraSquareRoots == 1)) break; ++numberOfExtraSquareRoots; } matrix_sqrt_triangular(T, sqrtT); T = sqrtT.template triangularView<Upper>(); ++numberOfSquareRoots; } matrix_log_compute_pade(result, T, degree); result *= pow(RealScalar(2), numberOfSquareRoots); } /** \ingroup MatrixFunctions_Module * \class MatrixLogarithmAtomic * \brief Helper class for computing matrix logarithm of atomic matrices. * * Here, an atomic matrix is a triangular matrix whose diagonal entries are close to each other. * * \sa class MatrixFunctionAtomic, MatrixBase::log() */ template <typename MatrixType> class MatrixLogarithmAtomic { public: /** \brief Compute matrix logarithm of atomic matrix * \param[in] A argument of matrix logarithm, should be upper triangular and atomic * \returns The logarithm of \p A. */ MatrixType compute(const MatrixType& A); }; template <typename MatrixType> MatrixType MatrixLogarithmAtomic<MatrixType>::compute(const MatrixType& A) { using std::log; MatrixType result(A.rows(), A.rows()); if (A.rows() == 1) result(0,0) = log(A(0,0)); else if (A.rows() == 2) matrix_log_compute_2x2(A, result); else matrix_log_compute_big(A, result); return result; } } // end of namespace internal /** \ingroup MatrixFunctions_Module * * \brief Proxy for the matrix logarithm of some matrix (expression). * * \tparam Derived Type of the argument to the matrix function. * * This class holds the argument to the matrix function until it is * assigned or evaluated for some other reason (so the argument * should not be changed in the meantime). It is the return type of * MatrixBase::log() and most of the time this is the only way it * is used. */ template<typename Derived> class MatrixLogarithmReturnValue : public ReturnByValue<MatrixLogarithmReturnValue<Derived> > { public: typedef typename Derived::Scalar Scalar; typedef typename Derived::Index Index; protected: typedef typename internal::ref_selector<Derived>::type DerivedNested; public: /** \brief Constructor. * * \param[in] A %Matrix (expression) forming the argument of the matrix logarithm. */ explicit MatrixLogarithmReturnValue(const Derived& A) : m_A(A) { } /** \brief Compute the matrix logarithm. * * \param[out] result Logarithm of \p A, where \A is as specified in the constructor. */ template <typename ResultType> inline void evalTo(ResultType& result) const { typedef typename internal::nested_eval<Derived, 10>::type DerivedEvalType; typedef typename internal::remove_all<DerivedEvalType>::type DerivedEvalTypeClean; typedef internal::traits<DerivedEvalTypeClean> Traits; static const int RowsAtCompileTime = Traits::RowsAtCompileTime; static const int ColsAtCompileTime = Traits::ColsAtCompileTime; typedef std::complex<typename NumTraits<Scalar>::Real> ComplexScalar; typedef Matrix<ComplexScalar, Dynamic, Dynamic, 0, RowsAtCompileTime, ColsAtCompileTime> DynMatrixType; typedef internal::MatrixLogarithmAtomic<DynMatrixType> AtomicType; AtomicType atomic; internal::matrix_function_compute<typename DerivedEvalTypeClean::PlainObject>::run(m_A, atomic, result); } Index rows() const { return m_A.rows(); } Index cols() const { return m_A.cols(); } private: const DerivedNested m_A; }; namespace internal { template<typename Derived> struct traits<MatrixLogarithmReturnValue<Derived> > { typedef typename Derived::PlainObject ReturnType; }; } /********** MatrixBase method **********/ template <typename Derived> const MatrixLogarithmReturnValue<Derived> MatrixBase<Derived>::log() const { eigen_assert(rows() == cols()); return MatrixLogarithmReturnValue<Derived>(derived()); } } // end namespace Eigen #endif // EIGEN_MATRIX_LOGARITHM
17,425
45.593583
122
h
abess
abess-master/python/include/unsupported/Eigen/src/MatrixFunctions/MatrixPower.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012, 2013 Chen-Pang He <[email protected]> // // 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_MATRIX_POWER #define EIGEN_MATRIX_POWER namespace Eigen { template<typename MatrixType> class MatrixPower; /** * \ingroup MatrixFunctions_Module * * \brief Proxy for the matrix power of some matrix. * * \tparam MatrixType type of the base, a matrix. * * This class holds the arguments to the matrix power until it is * assigned or evaluated for some other reason (so the argument * should not be changed in the meantime). It is the return type of * MatrixPower::operator() and related functions and most of the * time this is the only way it is used. */ /* TODO This class is only used by MatrixPower, so it should be nested * into MatrixPower, like MatrixPower::ReturnValue. However, my * compiler complained about unused template parameter in the * following declaration in namespace internal. * * template<typename MatrixType> * struct traits<MatrixPower<MatrixType>::ReturnValue>; */ template<typename MatrixType> class MatrixPowerParenthesesReturnValue : public ReturnByValue< MatrixPowerParenthesesReturnValue<MatrixType> > { public: typedef typename MatrixType::RealScalar RealScalar; typedef typename MatrixType::Index Index; /** * \brief Constructor. * * \param[in] pow %MatrixPower storing the base. * \param[in] p scalar, the exponent of the matrix power. */ MatrixPowerParenthesesReturnValue(MatrixPower<MatrixType>& pow, RealScalar p) : m_pow(pow), m_p(p) { } /** * \brief Compute the matrix power. * * \param[out] result */ template<typename ResultType> inline void evalTo(ResultType& res) const { m_pow.compute(res, m_p); } Index rows() const { return m_pow.rows(); } Index cols() const { return m_pow.cols(); } private: MatrixPower<MatrixType>& m_pow; const RealScalar m_p; }; /** * \ingroup MatrixFunctions_Module * * \brief Class for computing matrix powers. * * \tparam MatrixType type of the base, expected to be an instantiation * of the Matrix class template. * * This class is capable of computing triangular real/complex matrices * raised to a power in the interval \f$ (-1, 1) \f$. * * \note Currently this class is only used by MatrixPower. One may * insist that this be nested into MatrixPower. This class is here to * faciliate future development of triangular matrix functions. */ template<typename MatrixType> class MatrixPowerAtomic : internal::noncopyable { private: enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime }; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef std::complex<RealScalar> ComplexScalar; typedef typename MatrixType::Index Index; typedef Block<MatrixType,Dynamic,Dynamic> ResultType; const MatrixType& m_A; RealScalar m_p; void computePade(int degree, const MatrixType& IminusT, ResultType& res) const; void compute2x2(ResultType& res, RealScalar p) const; void computeBig(ResultType& res) const; static int getPadeDegree(float normIminusT); static int getPadeDegree(double normIminusT); static int getPadeDegree(long double normIminusT); static ComplexScalar computeSuperDiag(const ComplexScalar&, const ComplexScalar&, RealScalar p); static RealScalar computeSuperDiag(RealScalar, RealScalar, RealScalar p); public: /** * \brief Constructor. * * \param[in] T the base of the matrix power. * \param[in] p the exponent of the matrix power, should be in * \f$ (-1, 1) \f$. * * The class stores a reference to T, so it should not be changed * (or destroyed) before evaluation. Only the upper triangular * part of T is read. */ MatrixPowerAtomic(const MatrixType& T, RealScalar p); /** * \brief Compute the matrix power. * * \param[out] res \f$ A^p \f$ where A and p are specified in the * constructor. */ void compute(ResultType& res) const; }; template<typename MatrixType> MatrixPowerAtomic<MatrixType>::MatrixPowerAtomic(const MatrixType& T, RealScalar p) : m_A(T), m_p(p) { eigen_assert(T.rows() == T.cols()); eigen_assert(p > -1 && p < 1); } template<typename MatrixType> void MatrixPowerAtomic<MatrixType>::compute(ResultType& res) const { using std::pow; switch (m_A.rows()) { case 0: break; case 1: res(0,0) = pow(m_A(0,0), m_p); break; case 2: compute2x2(res, m_p); break; default: computeBig(res); } } template<typename MatrixType> void MatrixPowerAtomic<MatrixType>::computePade(int degree, const MatrixType& IminusT, ResultType& res) const { int i = 2*degree; res = (m_p-degree) / (2*i-2) * IminusT; for (--i; i; --i) { res = (MatrixType::Identity(IminusT.rows(), IminusT.cols()) + res).template triangularView<Upper>() .solve((i==1 ? -m_p : i&1 ? (-m_p-i/2)/(2*i) : (m_p-i/2)/(2*i-2)) * IminusT).eval(); } res += MatrixType::Identity(IminusT.rows(), IminusT.cols()); } // This function assumes that res has the correct size (see bug 614) template<typename MatrixType> void MatrixPowerAtomic<MatrixType>::compute2x2(ResultType& res, RealScalar p) const { using std::abs; using std::pow; res.coeffRef(0,0) = pow(m_A.coeff(0,0), p); for (Index i=1; i < m_A.cols(); ++i) { res.coeffRef(i,i) = pow(m_A.coeff(i,i), p); if (m_A.coeff(i-1,i-1) == m_A.coeff(i,i)) res.coeffRef(i-1,i) = p * pow(m_A.coeff(i,i), p-1); else if (2*abs(m_A.coeff(i-1,i-1)) < abs(m_A.coeff(i,i)) || 2*abs(m_A.coeff(i,i)) < abs(m_A.coeff(i-1,i-1))) res.coeffRef(i-1,i) = (res.coeff(i,i)-res.coeff(i-1,i-1)) / (m_A.coeff(i,i)-m_A.coeff(i-1,i-1)); else res.coeffRef(i-1,i) = computeSuperDiag(m_A.coeff(i,i), m_A.coeff(i-1,i-1), p); res.coeffRef(i-1,i) *= m_A.coeff(i-1,i); } } template<typename MatrixType> void MatrixPowerAtomic<MatrixType>::computeBig(ResultType& res) const { using std::ldexp; const int digits = std::numeric_limits<RealScalar>::digits; const RealScalar maxNormForPade = digits <= 24? 4.3386528e-1L // single precision : digits <= 53? 2.789358995219730e-1L // double precision : digits <= 64? 2.4471944416607995472e-1L // extended precision : digits <= 106? 1.1016843812851143391275867258512e-1L // double-double : 9.134603732914548552537150753385375e-2L; // quadruple precision MatrixType IminusT, sqrtT, T = m_A.template triangularView<Upper>(); RealScalar normIminusT; int degree, degree2, numberOfSquareRoots = 0; bool hasExtraSquareRoot = false; for (Index i=0; i < m_A.cols(); ++i) eigen_assert(m_A(i,i) != RealScalar(0)); while (true) { IminusT = MatrixType::Identity(m_A.rows(), m_A.cols()) - T; normIminusT = IminusT.cwiseAbs().colwise().sum().maxCoeff(); if (normIminusT < maxNormForPade) { degree = getPadeDegree(normIminusT); degree2 = getPadeDegree(normIminusT/2); if (degree - degree2 <= 1 || hasExtraSquareRoot) break; hasExtraSquareRoot = true; } matrix_sqrt_triangular(T, sqrtT); T = sqrtT.template triangularView<Upper>(); ++numberOfSquareRoots; } computePade(degree, IminusT, res); for (; numberOfSquareRoots; --numberOfSquareRoots) { compute2x2(res, ldexp(m_p, -numberOfSquareRoots)); res = res.template triangularView<Upper>() * res; } compute2x2(res, m_p); } template<typename MatrixType> inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(float normIminusT) { const float maxNormForPade[] = { 2.8064004e-1f /* degree = 3 */ , 4.3386528e-1f }; int degree = 3; for (; degree <= 4; ++degree) if (normIminusT <= maxNormForPade[degree - 3]) break; return degree; } template<typename MatrixType> inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(double normIminusT) { const double maxNormForPade[] = { 1.884160592658218e-2 /* degree = 3 */ , 6.038881904059573e-2, 1.239917516308172e-1, 1.999045567181744e-1, 2.789358995219730e-1 }; int degree = 3; for (; degree <= 7; ++degree) if (normIminusT <= maxNormForPade[degree - 3]) break; return degree; } template<typename MatrixType> inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(long double normIminusT) { #if LDBL_MANT_DIG == 53 const int maxPadeDegree = 7; const double maxNormForPade[] = { 1.884160592658218e-2L /* degree = 3 */ , 6.038881904059573e-2L, 1.239917516308172e-1L, 1.999045567181744e-1L, 2.789358995219730e-1L }; #elif LDBL_MANT_DIG <= 64 const int maxPadeDegree = 8; const long double maxNormForPade[] = { 6.3854693117491799460e-3L /* degree = 3 */ , 2.6394893435456973676e-2L, 6.4216043030404063729e-2L, 1.1701165502926694307e-1L, 1.7904284231268670284e-1L, 2.4471944416607995472e-1L }; #elif LDBL_MANT_DIG <= 106 const int maxPadeDegree = 10; const double maxNormForPade[] = { 1.0007161601787493236741409687186e-4L /* degree = 3 */ , 1.0007161601787493236741409687186e-3L, 4.7069769360887572939882574746264e-3L, 1.3220386624169159689406653101695e-2L, 2.8063482381631737920612944054906e-2L, 4.9625993951953473052385361085058e-2L, 7.7367040706027886224557538328171e-2L, 1.1016843812851143391275867258512e-1L }; #else const int maxPadeDegree = 10; const double maxNormForPade[] = { 5.524506147036624377378713555116378e-5L /* degree = 3 */ , 6.640600568157479679823602193345995e-4L, 3.227716520106894279249709728084626e-3L, 9.619593944683432960546978734646284e-3L, 2.134595382433742403911124458161147e-2L, 3.908166513900489428442993794761185e-2L, 6.266780814639442865832535460550138e-2L, 9.134603732914548552537150753385375e-2L }; #endif int degree = 3; for (; degree <= maxPadeDegree; ++degree) if (normIminusT <= maxNormForPade[degree - 3]) break; return degree; } template<typename MatrixType> inline typename MatrixPowerAtomic<MatrixType>::ComplexScalar MatrixPowerAtomic<MatrixType>::computeSuperDiag(const ComplexScalar& curr, const ComplexScalar& prev, RealScalar p) { using std::ceil; using std::exp; using std::log; using std::sinh; ComplexScalar logCurr = log(curr); ComplexScalar logPrev = log(prev); int unwindingNumber = ceil((numext::imag(logCurr - logPrev) - RealScalar(EIGEN_PI)) / RealScalar(2*EIGEN_PI)); ComplexScalar w = numext::log1p((curr-prev)/prev)/RealScalar(2) + ComplexScalar(0, EIGEN_PI*unwindingNumber); return RealScalar(2) * exp(RealScalar(0.5) * p * (logCurr + logPrev)) * sinh(p * w) / (curr - prev); } template<typename MatrixType> inline typename MatrixPowerAtomic<MatrixType>::RealScalar MatrixPowerAtomic<MatrixType>::computeSuperDiag(RealScalar curr, RealScalar prev, RealScalar p) { using std::exp; using std::log; using std::sinh; RealScalar w = numext::log1p((curr-prev)/prev)/RealScalar(2); return 2 * exp(p * (log(curr) + log(prev)) / 2) * sinh(p * w) / (curr - prev); } /** * \ingroup MatrixFunctions_Module * * \brief Class for computing matrix powers. * * \tparam MatrixType type of the base, expected to be an instantiation * of the Matrix class template. * * This class is capable of computing real/complex matrices raised to * an arbitrary real power. Meanwhile, it saves the result of Schur * decomposition if an non-integral power has even been calculated. * Therefore, if you want to compute multiple (>= 2) matrix powers * for the same matrix, using the class directly is more efficient than * calling MatrixBase::pow(). * * Example: * \include MatrixPower_optimal.cpp * Output: \verbinclude MatrixPower_optimal.out */ template<typename MatrixType> class MatrixPower : internal::noncopyable { private: typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename MatrixType::Index Index; public: /** * \brief Constructor. * * \param[in] A the base of the matrix power. * * The class stores a reference to A, so it should not be changed * (or destroyed) before evaluation. */ explicit MatrixPower(const MatrixType& A) : m_A(A), m_conditionNumber(0), m_rank(A.cols()), m_nulls(0) { eigen_assert(A.rows() == A.cols()); } /** * \brief Returns the matrix power. * * \param[in] p exponent, a real scalar. * \return The expression \f$ A^p \f$, where A is specified in the * constructor. */ const MatrixPowerParenthesesReturnValue<MatrixType> operator()(RealScalar p) { return MatrixPowerParenthesesReturnValue<MatrixType>(*this, p); } /** * \brief Compute the matrix power. * * \param[in] p exponent, a real scalar. * \param[out] res \f$ A^p \f$ where A is specified in the * constructor. */ template<typename ResultType> void compute(ResultType& res, RealScalar p); Index rows() const { return m_A.rows(); } Index cols() const { return m_A.cols(); } private: typedef std::complex<RealScalar> ComplexScalar; typedef Matrix<ComplexScalar, Dynamic, Dynamic, 0, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> ComplexMatrix; /** \brief Reference to the base of matrix power. */ typename MatrixType::Nested m_A; /** \brief Temporary storage. */ MatrixType m_tmp; /** \brief Store the result of Schur decomposition. */ ComplexMatrix m_T, m_U; /** \brief Store fractional power of m_T. */ ComplexMatrix m_fT; /** * \brief Condition number of m_A. * * It is initialized as 0 to avoid performing unnecessary Schur * decomposition, which is the bottleneck. */ RealScalar m_conditionNumber; /** \brief Rank of m_A. */ Index m_rank; /** \brief Rank deficiency of m_A. */ Index m_nulls; /** * \brief Split p into integral part and fractional part. * * \param[in] p The exponent. * \param[out] p The fractional part ranging in \f$ (-1, 1) \f$. * \param[out] intpart The integral part. * * Only if the fractional part is nonzero, it calls initialize(). */ void split(RealScalar& p, RealScalar& intpart); /** \brief Perform Schur decomposition for fractional power. */ void initialize(); template<typename ResultType> void computeIntPower(ResultType& res, RealScalar p); template<typename ResultType> void computeFracPower(ResultType& res, RealScalar p); template<int Rows, int Cols, int Options, int MaxRows, int MaxCols> static void revertSchur( Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T, const ComplexMatrix& U); template<int Rows, int Cols, int Options, int MaxRows, int MaxCols> static void revertSchur( Matrix<RealScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T, const ComplexMatrix& U); }; template<typename MatrixType> template<typename ResultType> void MatrixPower<MatrixType>::compute(ResultType& res, RealScalar p) { using std::pow; switch (cols()) { case 0: break; case 1: res(0,0) = pow(m_A.coeff(0,0), p); break; default: RealScalar intpart; split(p, intpart); res = MatrixType::Identity(rows(), cols()); computeIntPower(res, intpart); if (p) computeFracPower(res, p); } } template<typename MatrixType> void MatrixPower<MatrixType>::split(RealScalar& p, RealScalar& intpart) { using std::floor; using std::pow; intpart = floor(p); p -= intpart; // Perform Schur decomposition if it is not yet performed and the power is // not an integer. if (!m_conditionNumber && p) initialize(); // Choose the more stable of intpart = floor(p) and intpart = ceil(p). if (p > RealScalar(0.5) && p > (1-p) * pow(m_conditionNumber, p)) { --p; ++intpart; } } template<typename MatrixType> void MatrixPower<MatrixType>::initialize() { const ComplexSchur<MatrixType> schurOfA(m_A); JacobiRotation<ComplexScalar> rot; ComplexScalar eigenvalue; m_fT.resizeLike(m_A); m_T = schurOfA.matrixT(); m_U = schurOfA.matrixU(); m_conditionNumber = m_T.diagonal().array().abs().maxCoeff() / m_T.diagonal().array().abs().minCoeff(); // Move zero eigenvalues to the bottom right corner. for (Index i = cols()-1; i>=0; --i) { if (m_rank <= 2) return; if (m_T.coeff(i,i) == RealScalar(0)) { for (Index j=i+1; j < m_rank; ++j) { eigenvalue = m_T.coeff(j,j); rot.makeGivens(m_T.coeff(j-1,j), eigenvalue); m_T.applyOnTheRight(j-1, j, rot); m_T.applyOnTheLeft(j-1, j, rot.adjoint()); m_T.coeffRef(j-1,j-1) = eigenvalue; m_T.coeffRef(j,j) = RealScalar(0); m_U.applyOnTheRight(j-1, j, rot); } --m_rank; } } m_nulls = rows() - m_rank; if (m_nulls) { eigen_assert(m_T.bottomRightCorner(m_nulls, m_nulls).isZero() && "Base of matrix power should be invertible or with a semisimple zero eigenvalue."); m_fT.bottomRows(m_nulls).fill(RealScalar(0)); } } template<typename MatrixType> template<typename ResultType> void MatrixPower<MatrixType>::computeIntPower(ResultType& res, RealScalar p) { using std::abs; using std::fmod; RealScalar pp = abs(p); if (p<0) m_tmp = m_A.inverse(); else m_tmp = m_A; while (true) { if (fmod(pp, 2) >= 1) res = m_tmp * res; pp /= 2; if (pp < 1) break; m_tmp *= m_tmp; } } template<typename MatrixType> template<typename ResultType> void MatrixPower<MatrixType>::computeFracPower(ResultType& res, RealScalar p) { Block<ComplexMatrix,Dynamic,Dynamic> blockTp(m_fT, 0, 0, m_rank, m_rank); eigen_assert(m_conditionNumber); eigen_assert(m_rank + m_nulls == rows()); MatrixPowerAtomic<ComplexMatrix>(m_T.topLeftCorner(m_rank, m_rank), p).compute(blockTp); if (m_nulls) { m_fT.topRightCorner(m_rank, m_nulls) = m_T.topLeftCorner(m_rank, m_rank).template triangularView<Upper>() .solve(blockTp * m_T.topRightCorner(m_rank, m_nulls)); } revertSchur(m_tmp, m_fT, m_U); res = m_tmp * res; } template<typename MatrixType> template<int Rows, int Cols, int Options, int MaxRows, int MaxCols> inline void MatrixPower<MatrixType>::revertSchur( Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T, const ComplexMatrix& U) { res.noalias() = U * (T.template triangularView<Upper>() * U.adjoint()); } template<typename MatrixType> template<int Rows, int Cols, int Options, int MaxRows, int MaxCols> inline void MatrixPower<MatrixType>::revertSchur( Matrix<RealScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T, const ComplexMatrix& U) { res.noalias() = (U * (T.template triangularView<Upper>() * U.adjoint())).real(); } /** * \ingroup MatrixFunctions_Module * * \brief Proxy for the matrix power of some matrix (expression). * * \tparam Derived type of the base, a matrix (expression). * * This class holds the arguments to the matrix power until it is * assigned or evaluated for some other reason (so the argument * should not be changed in the meantime). It is the return type of * MatrixBase::pow() and related functions and most of the * time this is the only way it is used. */ template<typename Derived> class MatrixPowerReturnValue : public ReturnByValue< MatrixPowerReturnValue<Derived> > { public: typedef typename Derived::PlainObject PlainObject; typedef typename Derived::RealScalar RealScalar; typedef typename Derived::Index Index; /** * \brief Constructor. * * \param[in] A %Matrix (expression), the base of the matrix power. * \param[in] p real scalar, the exponent of the matrix power. */ MatrixPowerReturnValue(const Derived& A, RealScalar p) : m_A(A), m_p(p) { } /** * \brief Compute the matrix power. * * \param[out] result \f$ A^p \f$ where \p A and \p p are as in the * constructor. */ template<typename ResultType> inline void evalTo(ResultType& res) const { MatrixPower<PlainObject>(m_A.eval()).compute(res, m_p); } Index rows() const { return m_A.rows(); } Index cols() const { return m_A.cols(); } private: const Derived& m_A; const RealScalar m_p; }; /** * \ingroup MatrixFunctions_Module * * \brief Proxy for the matrix power of some matrix (expression). * * \tparam Derived type of the base, a matrix (expression). * * This class holds the arguments to the matrix power until it is * assigned or evaluated for some other reason (so the argument * should not be changed in the meantime). It is the return type of * MatrixBase::pow() and related functions and most of the * time this is the only way it is used. */ template<typename Derived> class MatrixComplexPowerReturnValue : public ReturnByValue< MatrixComplexPowerReturnValue<Derived> > { public: typedef typename Derived::PlainObject PlainObject; typedef typename std::complex<typename Derived::RealScalar> ComplexScalar; typedef typename Derived::Index Index; /** * \brief Constructor. * * \param[in] A %Matrix (expression), the base of the matrix power. * \param[in] p complex scalar, the exponent of the matrix power. */ MatrixComplexPowerReturnValue(const Derived& A, const ComplexScalar& p) : m_A(A), m_p(p) { } /** * \brief Compute the matrix power. * * Because \p p is complex, \f$ A^p \f$ is simply evaluated as \f$ * \exp(p \log(A)) \f$. * * \param[out] result \f$ A^p \f$ where \p A and \p p are as in the * constructor. */ template<typename ResultType> inline void evalTo(ResultType& res) const { res = (m_p * m_A.log()).exp(); } Index rows() const { return m_A.rows(); } Index cols() const { return m_A.cols(); } private: const Derived& m_A; const ComplexScalar m_p; }; namespace internal { template<typename MatrixPowerType> struct traits< MatrixPowerParenthesesReturnValue<MatrixPowerType> > { typedef typename MatrixPowerType::PlainObject ReturnType; }; template<typename Derived> struct traits< MatrixPowerReturnValue<Derived> > { typedef typename Derived::PlainObject ReturnType; }; template<typename Derived> struct traits< MatrixComplexPowerReturnValue<Derived> > { typedef typename Derived::PlainObject ReturnType; }; } template<typename Derived> const MatrixPowerReturnValue<Derived> MatrixBase<Derived>::pow(const RealScalar& p) const { return MatrixPowerReturnValue<Derived>(derived(), p); } template<typename Derived> const MatrixComplexPowerReturnValue<Derived> MatrixBase<Derived>::pow(const std::complex<RealScalar>& p) const { return MatrixComplexPowerReturnValue<Derived>(derived(), p); } } // namespace Eigen #endif // EIGEN_MATRIX_POWER
23,493
32.090141
122
h
abess
abess-master/python/include/unsupported/Eigen/src/MoreVectorization/MathFunctions.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Rohit Garg <[email protected]> // Copyright (C) 2009 Benoit Jacob <[email protected]> // // 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_MOREVECTORIZATION_MATHFUNCTIONS_H #define EIGEN_MOREVECTORIZATION_MATHFUNCTIONS_H namespace Eigen { namespace internal { /** \internal \returns the arcsin of \a a (coeff-wise) */ template<typename Packet> inline static Packet pasin(Packet a) { return std::asin(a); } #ifdef EIGEN_VECTORIZE_SSE template<> EIGEN_DONT_INLINE Packet4f pasin(Packet4f x) { _EIGEN_DECLARE_CONST_Packet4f(half, 0.5); _EIGEN_DECLARE_CONST_Packet4f(minus_half, -0.5); _EIGEN_DECLARE_CONST_Packet4f(3half, 1.5); _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(sign_mask, 0x80000000); _EIGEN_DECLARE_CONST_Packet4f(pi, 3.141592654); _EIGEN_DECLARE_CONST_Packet4f(pi_over_2, 3.141592654*0.5); _EIGEN_DECLARE_CONST_Packet4f(asin1, 4.2163199048E-2); _EIGEN_DECLARE_CONST_Packet4f(asin2, 2.4181311049E-2); _EIGEN_DECLARE_CONST_Packet4f(asin3, 4.5470025998E-2); _EIGEN_DECLARE_CONST_Packet4f(asin4, 7.4953002686E-2); _EIGEN_DECLARE_CONST_Packet4f(asin5, 1.6666752422E-1); Packet4f a = pabs(x);//got the absolute value Packet4f sign_bit= _mm_and_ps(x, p4f_sign_mask);//extracted the sign bit Packet4f z1,z2;//will need them during computation //will compute the two branches for asin //so first compare with half Packet4f branch_mask= _mm_cmpgt_ps(a, p4f_half);//this is to select which branch to take //both will be taken, and finally results will be merged //the branch for values >0.5 { //the core series expansion z1=pmadd(p4f_minus_half,a,p4f_half); Packet4f x1=psqrt(z1); Packet4f s1=pmadd(p4f_asin1, z1, p4f_asin2); Packet4f s2=pmadd(s1, z1, p4f_asin3); Packet4f s3=pmadd(s2,z1, p4f_asin4); Packet4f s4=pmadd(s3,z1, p4f_asin5); Packet4f temp=pmul(s4,z1);//not really a madd but a mul by z so that the next term can be a madd z1=pmadd(temp,x1,x1); z1=padd(z1,z1); z1=psub(p4f_pi_over_2,z1); } { //the core series expansion Packet4f x2=a; z2=pmul(x2,x2); Packet4f s1=pmadd(p4f_asin1, z2, p4f_asin2); Packet4f s2=pmadd(s1, z2, p4f_asin3); Packet4f s3=pmadd(s2,z2, p4f_asin4); Packet4f s4=pmadd(s3,z2, p4f_asin5); Packet4f temp=pmul(s4,z2);//not really a madd but a mul by z so that the next term can be a madd z2=pmadd(temp,x2,x2); } /* select the correct result from the two branch evaluations */ z1 = _mm_and_ps(branch_mask, z1); z2 = _mm_andnot_ps(branch_mask, z2); Packet4f z = _mm_or_ps(z1,z2); /* update the sign */ return _mm_xor_ps(z, sign_bit); } #endif // EIGEN_VECTORIZE_SSE } // end namespace internal } // end namespace Eigen #endif // EIGEN_MOREVECTORIZATION_MATHFUNCTIONS_H
3,035
30.625
100
h
abess
abess-master/python/include/unsupported/Eigen/src/NonLinearOptimization/chkder.h
#define chkder_log10e 0.43429448190325182765 #define chkder_factor 100. namespace Eigen { namespace internal { template<typename Scalar> void chkder( const Matrix< Scalar, Dynamic, 1 > &x, const Matrix< Scalar, Dynamic, 1 > &fvec, const Matrix< Scalar, Dynamic, Dynamic > &fjac, Matrix< Scalar, Dynamic, 1 > &xp, const Matrix< Scalar, Dynamic, 1 > &fvecp, int mode, Matrix< Scalar, Dynamic, 1 > &err ) { using std::sqrt; using std::abs; using std::log; typedef DenseIndex Index; const Scalar eps = sqrt(NumTraits<Scalar>::epsilon()); const Scalar epsf = chkder_factor * NumTraits<Scalar>::epsilon(); const Scalar epslog = chkder_log10e * log(eps); Scalar temp; const Index m = fvec.size(), n = x.size(); if (mode != 2) { /* mode = 1. */ xp.resize(n); for (Index j = 0; j < n; ++j) { temp = eps * abs(x[j]); if (temp == 0.) temp = eps; xp[j] = x[j] + temp; } } else { /* mode = 2. */ err.setZero(m); for (Index j = 0; j < n; ++j) { temp = abs(x[j]); if (temp == 0.) temp = 1.; err += temp * fjac.col(j); } for (Index i = 0; i < m; ++i) { temp = 1.; if (fvec[i] != 0. && fvecp[i] != 0. && abs(fvecp[i] - fvec[i]) >= epsf * abs(fvec[i])) temp = eps * abs((fvecp[i] - fvec[i]) / eps - err[i]) / (abs(fvec[i]) + abs(fvecp[i])); err[i] = 1.; if (temp > NumTraits<Scalar>::epsilon() && temp < eps) err[i] = (chkder_log10e * log(temp) - epslog) / epslog; if (temp >= eps) err[i] = 0.; } } } } // end namespace internal } // end namespace Eigen
1,864
26.835821
103
h
abess
abess-master/python/include/unsupported/Eigen/src/NonLinearOptimization/covar.h
namespace Eigen { namespace internal { template <typename Scalar> void covar( Matrix< Scalar, Dynamic, Dynamic > &r, const VectorXi &ipvt, Scalar tol = std::sqrt(NumTraits<Scalar>::epsilon()) ) { using std::abs; typedef DenseIndex Index; /* Local variables */ Index i, j, k, l, ii, jj; bool sing; Scalar temp; /* Function Body */ const Index n = r.cols(); const Scalar tolr = tol * abs(r(0,0)); Matrix< Scalar, Dynamic, 1 > wa(n); eigen_assert(ipvt.size()==n); /* form the inverse of r in the full upper triangle of r. */ l = -1; for (k = 0; k < n; ++k) if (abs(r(k,k)) > tolr) { r(k,k) = 1. / r(k,k); for (j = 0; j <= k-1; ++j) { temp = r(k,k) * r(j,k); r(j,k) = 0.; r.col(k).head(j+1) -= r.col(j).head(j+1) * temp; } l = k; } /* form the full upper triangle of the inverse of (r transpose)*r */ /* in the full upper triangle of r. */ for (k = 0; k <= l; ++k) { for (j = 0; j <= k-1; ++j) r.col(j).head(j+1) += r.col(k).head(j+1) * r(j,k); r.col(k).head(k+1) *= r(k,k); } /* form the full lower triangle of the covariance matrix */ /* in the strict lower triangle of r and in wa. */ for (j = 0; j < n; ++j) { jj = ipvt[j]; sing = j > l; for (i = 0; i <= j; ++i) { if (sing) r(i,j) = 0.; ii = ipvt[i]; if (ii > jj) r(ii,jj) = r(i,j); if (ii < jj) r(jj,ii) = r(i,j); } wa[jj] = r(j,j); } /* symmetrize the covariance matrix in r. */ r.topLeftCorner(n,n).template triangularView<StrictlyUpper>() = r.topLeftCorner(n,n).transpose(); r.diagonal() = wa; } } // end namespace internal } // end namespace Eigen
1,915
25.985915
101
h
abess
abess-master/python/include/unsupported/Eigen/src/NonLinearOptimization/fdjac1.h
namespace Eigen { namespace internal { template<typename FunctorType, typename Scalar> DenseIndex fdjac1( const FunctorType &Functor, Matrix< Scalar, Dynamic, 1 > &x, Matrix< Scalar, Dynamic, 1 > &fvec, Matrix< Scalar, Dynamic, Dynamic > &fjac, DenseIndex ml, DenseIndex mu, Scalar epsfcn) { using std::sqrt; using std::abs; typedef DenseIndex Index; /* Local variables */ Scalar h; Index j, k; Scalar eps, temp; Index msum; int iflag; Index start, length; /* Function Body */ const Scalar epsmch = NumTraits<Scalar>::epsilon(); const Index n = x.size(); eigen_assert(fvec.size()==n); Matrix< Scalar, Dynamic, 1 > wa1(n); Matrix< Scalar, Dynamic, 1 > wa2(n); eps = sqrt((std::max)(epsfcn,epsmch)); msum = ml + mu + 1; if (msum >= n) { /* computation of dense approximate jacobian. */ for (j = 0; j < n; ++j) { temp = x[j]; h = eps * abs(temp); if (h == 0.) h = eps; x[j] = temp + h; iflag = Functor(x, wa1); if (iflag < 0) return iflag; x[j] = temp; fjac.col(j) = (wa1-fvec)/h; } }else { /* computation of banded approximate jacobian. */ for (k = 0; k < msum; ++k) { for (j = k; (msum<0) ? (j>n): (j<n); j += msum) { wa2[j] = x[j]; h = eps * abs(wa2[j]); if (h == 0.) h = eps; x[j] = wa2[j] + h; } iflag = Functor(x, wa1); if (iflag < 0) return iflag; for (j = k; (msum<0) ? (j>n): (j<n); j += msum) { x[j] = wa2[j]; h = eps * abs(wa2[j]); if (h == 0.) h = eps; fjac.col(j).setZero(); start = std::max<Index>(0,j-mu); length = (std::min)(n-1, j+ml) - start + 1; fjac.col(j).segment(start, length) = ( wa1.segment(start, length)-fvec.segment(start, length))/h; } } } return 0; } } // end namespace internal } // end namespace Eigen
2,225
26.825
113
h
abess
abess-master/python/include/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
abess
abess-master/python/include/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 tranformation 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,263
34.478261
108
h
abess
abess-master/python/include/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 dont 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,082
29.83
80
h
abess
abess-master/python/include/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
abess
abess-master/python/include/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 <[email protected]> // // 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
abess
abess-master/python/include/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 <[email protected]> // // 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 <typename T> T radix(){ return 2; } template <typename T> T radix2(){ return radix<T>()*radix<T>(); } 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 = -1/poly[deg] * poly.head(deg); //m_bl_diag.setIdentity( deg-1 ); 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 companion(deg,deg); companion << ( LeftBlock(deg,deg_1) << LeftBlockFirstRow::Zero(1,deg_1), BottomLeftBlock::Identity(deg-1,deg-1)*m_bl_diag.asDiagonal() ).finished() , m_monic; return companion; } 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 repectively the multipliers for * the column and the row in order to balance them. * */ bool balanced( Scalar colNorm, Scalar rowNorm, bool& isBalanced, Scalar& colB, Scalar& 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 repectively the multipliers for * the column and the row in order to balance them. * */ bool balancedR( Scalar colNorm, Scalar rowNorm, bool& isBalanced, Scalar& colB, Scalar& 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( Scalar colNorm, Scalar rowNorm, bool& isBalanced, Scalar& colB, Scalar& rowB ) { if( Scalar(0) == colNorm || Scalar(0) == 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$ rowB = rowNorm / radix<Scalar>(); colB = Scalar(1); const Scalar s = colNorm + rowNorm; while (colNorm < rowB) { colB *= radix<Scalar>(); colNorm *= radix2<Scalar>(); } rowB = rowNorm * radix<Scalar>(); while (colNorm >= rowB) { colB /= radix<Scalar>(); colNorm /= radix2<Scalar>(); } //This line is used to avoid insubstantial balancing if ((rowNorm + colNorm) < Scalar(0.95) * s * colB) { isBalanced = false; rowB = Scalar(1) / colB; return false; } else{ return true; } } } template< typename _Scalar, int _Deg > inline bool companion<_Scalar,_Deg>::balancedR( Scalar colNorm, Scalar rowNorm, bool& isBalanced, Scalar& colB, Scalar& rowB ) { if( Scalar(0) == colNorm || Scalar(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 _Scalar q = colNorm/rowNorm; if( !isApprox( q, _Scalar(1) ) ) { rowB = sqrt( colNorm/rowNorm ); colB = Scalar(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; Scalar colNorm,rowNorm; Scalar 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
7,745
26.963899
102
h
abess
abess-master/python/include/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 <[email protected]> // // 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<Scalar> greater; return selectComplexRoot_withRespectToNorm( greater ); } /** * \returns the complex root with smallest norm. */ inline const RootType& smallestRoot() const { std::less<Scalar> 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( 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<Scalar> 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<Scalar> 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<Scalar> 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<Scalar> 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 EigenSolver<CompanionMatrixType> EigenSolverType; 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(); } 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
14,376
34.324324
104
h
abess
abess-master/python/include/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 <[email protected]> // // 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. * * <i><b>Note for stability:</b></i> * <dd> \f$ |x| \le 1 \f$ </dd> */ 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$. * * <i><b>Precondition:</b></i> * <dd> the leading coefficient of the input polynomial poly must be non zero </dd> */ 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,862
32.770833
96
h
abess
abess-master/python/include/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 <[email protected]> // // 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 imcomplete * 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_SKYLINELU_H
11,358
31.17847
126
h
abess
abess-master/python/include/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 <[email protected]> // // 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 Index rows() const { return derived().rows(); } /** \returns the number of columns. \sa rows(), ColsAtCompileTime*/ inline Index cols() const { return derived().cols(); } /** \returns the number of coefficients, which is \a rows()*cols(). * \sa rows(), cols(), SizeAtCompileTime. */ inline Index size() const { 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,745
35.366197
107
h
abess
abess-master/python/include/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 <[email protected]> // // 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
abess
abess-master/python/include/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 <[email protected]> // // 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
abess
abess-master/python/include/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 <[email protected]> // // 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
abess
abess-master/python/include/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 <[email protected]> // Copyright (C) 2012 Desire NUENTSA WAKAM <[email protected]> // // 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> namespace Eigen { namespace internal { template <typename Scalar> inline bool GetMarketLine (std::stringstream& line, Index& M, Index& N, Index& i, Index& j, Scalar& value) { line >> i >> j >> value; i--; j--; if(i>=0 && j>=0 && i<M && j<N) { return true; } else return false; } template <typename Scalar> inline bool GetMarketLine (std::stringstream& line, Index& M, Index& N, Index& i, Index& j, std::complex<Scalar>& value) { Scalar valR, valI; line >> i >> j >> valR >> valI; i--; j--; if(i>=0 && j>=0 && i<M && j<N) { value = std::complex<Scalar>(valR, valI); return true; } else return false; } 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> inline void PutMatrixElt(Scalar value, int row, int col, std::ofstream& out) { out << row << " "<< col << " " << value << "\n"; } template<typename Scalar> inline void PutMatrixElt(std::complex<Scalar> value, int row, int 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 namepsace internal inline bool getMarketHeader(const std::string& filename, int& sym, bool& iscomplex, bool& isvector) { sym = 0; 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::Index Index; std::ifstream input(filename.c_str(),std::ios::in); if(!input) return false; const int maxBuffersize = 2048; char buffer[maxBuffersize]; bool readsizes = false; typedef Triplet<Scalar,Index> 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; std::stringstream line(buffer); if(!readsizes) { line >> M >> N >> NNZ; if(M > 0 && N > 0 && NNZ > 0) { readsizes = true; //std::cout << "sizes: " << M << "," << N << "," << NNZ << "\n"; mat.resize(M,N); mat.reserve(NNZ); } } else { Index i(-1), j(-1); Scalar value; if( internal::GetMarketLine(line, M, N, i, j, value) ) { ++ 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; std::ofstream out(filename.c_str(),std::ios::out); if(!out) return false; out.flags(std::ios_base::scientific); out.precision(64); 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 << it.row()+1 << " " << it.col()+1 << " " << it.value() << "\n"; } out.close(); return true; } template<typename VectorType> bool saveMarketVector (const VectorType& vec, const std::string& filename) { typedef typename VectorType::Scalar Scalar; std::ofstream out(filename.c_str(),std::ios::out); if(!out) return false; out.flags(std::ios_base::scientific); out.precision(64); 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
7,563
26.505455
122
h
abess
abess-master/python/include/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 <[email protected]> // // 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
abess
abess-master/python/include/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 <[email protected]> // // 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 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 #ifdef _DENSE_HASH_MAP_H_ /** Represents a google::dense_hash_map * * \see RandomSetter */ template<typename Scalar> struct GoogleDenseHashMapTraits { typedef int KeyType; typedef google::dense_hash_map<KeyType,Scalar> Type; enum { IsSorted = 0 }; static void setInvalidKey(Type& map, const KeyType& k) { map.set_empty_key(k); } }; #endif #ifdef _SPARSE_HASH_MAP_H_ /** Represents a google::sparse_hash_map * * \see RandomSetter */ template<typename Scalar> struct GoogleSparseHashMapTraits { typedef int KeyType; typedef google::sparse_hash_map<KeyType,Scalar> 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 * the Google's hash_map implementation. To enable the support for them, you have two options: * - \#include <google/dense_hash_map> yourself \b before Eigen/Sparse header * - define EIGEN_GOOGLEHASH_SUPPORT * In the later case the inclusion of <google/dense_hash_map> is made for you. * * \see http://code.google.com/p/google-sparsehash/ */ template<typename SparseMatrixType, template <typename T> class MapTraits = #if defined _DENSE_HASH_MAP_H_ 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 Index count = 0; for (Index j=0; j<mp_target->outerSize(); ++j) { Index 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] = 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
11,788
34.942073
130
h
abess
abess-master/python/include/unsupported/Eigen/src/SpecialFunctions/SpecialFunctionsFunctors.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2016 Eugene Brevdo <[email protected]> // Copyright (C) 2016 Gael Guennebaud <[email protected]> // // 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_FUNCTORS_H #define EIGEN_SPECIALFUNCTIONS_FUNCTORS_H namespace Eigen { namespace internal { /** \internal * \brief Template functor to compute the incomplete gamma function igamma(a, x) * * \sa class CwiseBinaryOp, Cwise::igamma */ template<typename Scalar> struct scalar_igamma_op : binary_op_base<Scalar,Scalar> { EIGEN_EMPTY_STRUCT_CTOR(scalar_igamma_op) EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const { using numext::igamma; return igamma(a, x); } template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const { return internal::pigamma(a, x); } }; template<typename Scalar> struct functor_traits<scalar_igamma_op<Scalar> > { enum { // Guesstimate Cost = 20 * NumTraits<Scalar>::MulCost + 10 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasIGamma }; }; /** \internal * \brief Template functor to compute the complementary incomplete gamma function igammac(a, x) * * \sa class CwiseBinaryOp, Cwise::igammac */ template<typename Scalar> struct scalar_igammac_op : binary_op_base<Scalar,Scalar> { EIGEN_EMPTY_STRUCT_CTOR(scalar_igammac_op) EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a, const Scalar& x) const { using numext::igammac; return igammac(a, x); } template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a, const Packet& x) const { return internal::pigammac(a, x); } }; template<typename Scalar> struct functor_traits<scalar_igammac_op<Scalar> > { enum { // Guesstimate Cost = 20 * NumTraits<Scalar>::MulCost + 10 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasIGammac }; }; /** \internal * \brief Template functor to compute the incomplete beta integral betainc(a, b, x) * */ template<typename Scalar> struct scalar_betainc_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_betainc_op) EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& x, const Scalar& a, const Scalar& b) const { using numext::betainc; return betainc(x, a, b); } template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& x, const Packet& a, const Packet& b) const { return internal::pbetainc(x, a, b); } }; template<typename Scalar> struct functor_traits<scalar_betainc_op<Scalar> > { enum { // Guesstimate Cost = 400 * NumTraits<Scalar>::MulCost + 400 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasBetaInc }; }; /** \internal * \brief Template functor to compute the natural log of the absolute * value of Gamma of a scalar * \sa class CwiseUnaryOp, Cwise::lgamma() */ template<typename Scalar> struct scalar_lgamma_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_lgamma_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& a) const { using numext::lgamma; return lgamma(a); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& a) const { return internal::plgamma(a); } }; template<typename Scalar> struct functor_traits<scalar_lgamma_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasLGamma }; }; /** \internal * \brief Template functor to compute psi, the derivative of lgamma of a scalar. * \sa class CwiseUnaryOp, Cwise::digamma() */ template<typename Scalar> struct scalar_digamma_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_digamma_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& a) const { using numext::digamma; return digamma(a); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& a) const { return internal::pdigamma(a); } }; template<typename Scalar> struct functor_traits<scalar_digamma_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasDiGamma }; }; /** \internal * \brief Template functor to compute the Riemann Zeta function of two arguments. * \sa class CwiseUnaryOp, Cwise::zeta() */ template<typename Scalar> struct scalar_zeta_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_zeta_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& x, const Scalar& q) const { using numext::zeta; return zeta(x, q); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& x, const Packet& q) const { return internal::pzeta(x, q); } }; template<typename Scalar> struct functor_traits<scalar_zeta_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasZeta }; }; /** \internal * \brief Template functor to compute the polygamma function. * \sa class CwiseUnaryOp, Cwise::polygamma() */ template<typename Scalar> struct scalar_polygamma_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_polygamma_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& n, const Scalar& x) const { using numext::polygamma; return polygamma(n, x); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& n, const Packet& x) const { return internal::ppolygamma(n, x); } }; template<typename Scalar> struct functor_traits<scalar_polygamma_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasPolygamma }; }; /** \internal * \brief Template functor to compute the Gauss error function of a * scalar * \sa class CwiseUnaryOp, Cwise::erf() */ template<typename Scalar> struct scalar_erf_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_erf_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& a) const { using numext::erf; return erf(a); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& a) const { return internal::perf(a); } }; template<typename Scalar> struct functor_traits<scalar_erf_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasErf }; }; /** \internal * \brief Template functor to compute the Complementary Error Function * of a scalar * \sa class CwiseUnaryOp, Cwise::erfc() */ template<typename Scalar> struct scalar_erfc_op { EIGEN_EMPTY_STRUCT_CTOR(scalar_erfc_op) EIGEN_DEVICE_FUNC inline const Scalar operator() (const Scalar& a) const { using numext::erfc; return erfc(a); } typedef typename packet_traits<Scalar>::type Packet; EIGEN_DEVICE_FUNC inline Packet packetOp(const Packet& a) const { return internal::perfc(a); } }; template<typename Scalar> struct functor_traits<scalar_erfc_op<Scalar> > { enum { // Guesstimate Cost = 10 * NumTraits<Scalar>::MulCost + 5 * NumTraits<Scalar>::AddCost, PacketAccess = packet_traits<Scalar>::HasErfc }; }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_SPECIALFUNCTIONS_FUNCTORS_H
7,907
32.367089
123
h
abess
abess-master/python/include/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 <[email protected]> // // 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 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 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
2,709
44.932203
117
h
abess
abess-master/python/include/unsupported/Eigen/src/SpecialFunctions/arch/CUDA/CudaSpecialFunctions.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2014 Benoit Steiner <[email protected]> // // 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_CUDA_SPECIALFUNCTIONS_H #define EIGEN_CUDA_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(__CUDACC__) && 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 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 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)); } #endif } // end namespace internal } // end namespace Eigen #endif // EIGEN_CUDA_SPECIALFUNCTIONS_H
4,528
26.283133
107
h
abess
abess-master/python/include/unsupported/test/matrix_functions.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2011 Jitse Niesen <[email protected]> // // 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/. #include "main.h" #include <unsupported/Eigen/MatrixFunctions> // For complex matrices, any matrix is fine. template<typename MatrixType, int IsComplex = NumTraits<typename internal::traits<MatrixType>::Scalar>::IsComplex> struct processTriangularMatrix { static void run(MatrixType&, MatrixType&, const MatrixType&) { } }; // For real matrices, make sure none of the eigenvalues are negative. template<typename MatrixType> struct processTriangularMatrix<MatrixType,0> { static void run(MatrixType& m, MatrixType& T, const MatrixType& U) { const Index size = m.cols(); for (Index i=0; i < size; ++i) { if (i == size - 1 || T.coeff(i+1,i) == 0) T.coeffRef(i,i) = std::abs(T.coeff(i,i)); else ++i; } m = U * T * U.transpose(); } }; template <typename MatrixType, int IsComplex = NumTraits<typename internal::traits<MatrixType>::Scalar>::IsComplex> struct generateTestMatrix; template <typename MatrixType> struct generateTestMatrix<MatrixType,0> { static void run(MatrixType& result, typename MatrixType::Index size) { result = MatrixType::Random(size, size); RealSchur<MatrixType> schur(result); MatrixType T = schur.matrixT(); processTriangularMatrix<MatrixType>::run(result, T, schur.matrixU()); } }; template <typename MatrixType> struct generateTestMatrix<MatrixType,1> { static void run(MatrixType& result, typename MatrixType::Index size) { result = MatrixType::Random(size, size); } }; template <typename Derived, typename OtherDerived> typename Derived::RealScalar relerr(const MatrixBase<Derived>& A, const MatrixBase<OtherDerived>& B) { return std::sqrt((A - B).cwiseAbs2().sum() / (std::min)(A.cwiseAbs2().sum(), B.cwiseAbs2().sum())); }
2,106
29.985294
115
h
abess
abess-master/python/src/List.h
#ifndef SRC_LIST_H #define SRC_LIST_H #include <Eigen/Eigen> #include <iostream> #include <vector> using namespace std; using namespace Eigen; class List { public: List(){}; ~List(){}; // void add(string name, int value); // void get_value_by_name(string name, int &value); void add(string name, double value); void get_value_by_name(string name, double &value); void add(string name, MatrixXd &value); void get_value_by_name(string name, MatrixXd &value); void add(string name, VectorXd &value); void get_value_by_name(string name, VectorXd &value); void add(string name, VectorXi &value); void combine_beta(VectorXd &value); // void get_value_by_name(string name, VectorXi &value); // void add(string name, Eigen::Matrix<VectorXd, Dynamic, Dynamic> &value); // void get_value_by_name(string name, Eigen::Matrix<VectorXd, Dynamic, Dynamic> &value); // void add(string name, Eigen::Matrix<VectorXi, Dynamic, Dynamic> &value); // void get_value_by_name(string name, Eigen::Matrix<VectorXi, Dynamic, Dynamic> &value); private: vector<int> vector_int; vector<string> vector_int_name; vector<double> vector_double; vector<string> vector_double_name; vector<Eigen::MatrixXd> vector_MatrixXd; vector<string> vector_MatrixXd_name; vector<Eigen::VectorXd> vector_VectorXd; vector<string> vector_VectorXd_name; vector<Eigen::VectorXi> vector_VectorXi; vector<string> vector_VectorXi_name; vector<Eigen::Matrix<VectorXi, Dynamic, Dynamic>> vector_Matrix_VectorXi; vector<string> vector_Matrix_VectorXi_name; vector<Eigen::Matrix<VectorXd, Dynamic, Dynamic>> vector_Matrix_VectorXd; vector<string> vector_Matrix_VectorXd_name; }; #endif // SRC_LIST_H
1,775
36
93
h
abess
abess-master/src/AlgorithmPCA.h
#ifndef SRC_ALGORITHMPCA_H #define SRC_ALGORITHMPCA_H #include <Spectra/SymEigsSolver.h> #include "Algorithm.h" using namespace Spectra; template <class T4> class abessPCA : public Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, T4> { public: int pca_n = -1; bool is_cv = false; MatrixXd sigma; abessPCA(int algorithm_type, int model_type, int max_iter = 30, int primary_model_fit_max_iter = 10, double primary_model_fit_epsilon = 1e-8, bool warm_start = true, int exchange_num = 5, Eigen::VectorXi always_select = Eigen::VectorXi::Zero(0), int splicing_type = 1, int sub_search = 0) : Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, T4>::Algorithm( algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon, warm_start, exchange_num, always_select, splicing_type, sub_search){}; ~abessPCA(){}; void inital_setting(T4 &X, VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, int &N) { if (this->is_cv) { this->sigma = compute_Sigma(X); } } void updata_tau(int train_n, int N) { if (this->pca_n > 0) train_n = this->pca_n; if (train_n == 1) { this->tau = 0.0; } else { this->tau = 0.01 * (double)this->sparsity_level * log((double)N) * log(log((double)train_n)) / (double)train_n; } } bool primary_model_fit(T4 &x, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &beta, double &coef0, double loss0, Eigen::VectorXi &A, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size) { if (beta.size() == 0) return true; if (beta.size() == 1) { beta(0) = 1; return true; } MatrixXd Y = SigmaA(this->sigma, A, g_index, g_size); DenseSymMatProd<double> op(Y); SymEigsSolver<DenseSymMatProd<double>> eig(op, 1, 2); eig.init(); eig.compute(); MatrixXd temp; if (eig.info() == CompInfo::Successful) { temp = eig.eigenvectors(1); } else { return false; } beta = temp.col(0); return true; }; double loss_function(T4 &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &beta, double &coef0, Eigen::VectorXi &A, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, double lambda) { MatrixXd Y; if (this->is_cv) { MatrixXd sigma_test = compute_Sigma(X); Y = SigmaA(sigma_test, A, g_index, g_size); } else { Y = SigmaA(this->sigma, A, g_index, g_size); } return -beta.transpose() * Y * beta; }; void sacrifice(T4 &X, T4 &XA, Eigen::VectorXd &y, Eigen::VectorXd &beta, Eigen::VectorXd &beta_A, double &coef0, Eigen::VectorXi &A, Eigen::VectorXi &I, Eigen::VectorXd &weights, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, int N, Eigen::VectorXi &A_ind, Eigen::VectorXd &bd, Eigen::VectorXi &U, Eigen::VectorXi &U_ind, int num) { VectorXd D = -this->sigma * beta + beta.transpose() * this->sigma * beta * beta; for (int i = 0; i < A.size(); i++) { VectorXd temp = beta.segment(g_index(A(i)), g_size(A(i))); bd(A(i)) = temp.squaredNorm(); } for (int i = 0; i < I.size(); i++) { VectorXd temp = D.segment(g_index(I(i)), g_size(I(i))); bd(I(i)) = temp.squaredNorm(); } }; MatrixXd SigmaA(Eigen::MatrixXd &Sigma, Eigen::VectorXi &A, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size) { int len = 0; for (int i = 0; i < A.size(); i++) { len += g_size(A(i)); } int k = 0; VectorXd ind(len); for (int i = 0; i < A.size(); i++) for (int j = 0; j < g_size(A(i)); j++) ind(k++) = g_index(A(i)) + j; MatrixXd SA(len, len); for (int i = 0; i < len; i++) for (int j = 0; j < i + 1; j++) { int di = ind(i), dj = ind(j); SA(i, j) = Sigma(di, dj); SA(j, i) = Sigma(dj, di); } return SA; } MatrixXd compute_Sigma(T4 &X) { MatrixXd X1 = MatrixXd(X); MatrixXd centered = X1.rowwise() - X1.colwise().mean(); return centered.adjoint() * centered / (X1.rows() - 1); } }; template <class T4> class abessRPCA : public Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, T4> { public: MatrixXd L; int r = 10; abessRPCA(int algorithm_type, int model_type, int max_iter = 30, int primary_model_fit_max_iter = 10, double primary_model_fit_epsilon = 1e-8, bool warm_start = true, int exchange_num = 5, Eigen::VectorXi always_select = Eigen::VectorXi::Zero(0), int splicing_type = 1, int sub_search = 0) : Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, T4>::Algorithm( algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon, warm_start, exchange_num, always_select, splicing_type, sub_search){}; ~abessRPCA(){}; int get_beta_size(int n, int p) { return n * p; } void update_tau(int train_n, int N) { this->tau = 0.0; } Eigen::VectorXi inital_screening(T4 &X, Eigen::VectorXd &y, Eigen::VectorXd &beta, double &coef0, Eigen::VectorXi &A, Eigen::VectorXi &I, Eigen::VectorXd &bd, Eigen::VectorXd &weights, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, int &N) { MatrixXd S; if (bd.size() == 0) { // variable initialization bd = VectorXd::Zero(N); this->L = this->trun_svd(X); S = X - this->L; S.resize(N, 1); for (int i = 0; i < N; i++) bd(i) = abs(S(i, 0)); // A_init for (int i = 0; i < A.size(); i++) { bd(A(i)) = DBL_MAX / 2; } // alway_select for (int i = 0; i < (this->always_select).size(); i++) { bd(this->always_select(i)) = DBL_MAX; } this->r = (int)this->lambda_level; } // get Active-set A according to max_k bd VectorXi A_new = max_k(bd, this->sparsity_level); return A_new; } bool primary_model_fit(T4 &x, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &beta, double &coef0, double loss0, Eigen::VectorXi &A, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size) { int n = x.rows(); MatrixXd L_old = this->L; this->L = this->HardImpute(x, A, 1000, 1e-5); for (int i = 0; i < A.size(); i++) { int mi = A(i) % n; int mj = int(A(i) / n); beta(i) = x.coeff(mi, mj) - this->L(mi, mj); } double loss1 = this->loss_function(x, y, weights, beta, coef0, A, g_index, g_size, 0); if (loss0 - loss1 <= this->tau) { this->L = L_old; } return true; }; double loss_function(T4 &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &beta, double &coef0, Eigen::VectorXi &A, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, double lambda) { int n = X.rows(); int p = X.cols(); // MatrixXd L = this->HardImpute(X, A, 1000, 1e-5); MatrixXd S = compute_S(beta, A, n, p); MatrixXd W = X - this->L - S; return W.squaredNorm() / n / p; }; void sacrifice(T4 &X, T4 &XA, Eigen::VectorXd &y, Eigen::VectorXd &beta, Eigen::VectorXd &beta_A, double &coef0, Eigen::VectorXi &A, Eigen::VectorXi &I, Eigen::VectorXd &weights, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, int N, Eigen::VectorXi &A_ind, Eigen::VectorXd &bd, Eigen::VectorXi &U, Eigen::VectorXi &U_ind, int num) { int n = X.rows(); int p = X.cols(); // MatrixXd L = this->HardImpute(X, A, 1000, 1e-5); MatrixXd S = compute_S(beta_A, A, n, p); MatrixXd W = X - this->L - S; for (int i = 0; i < A.size(); i++) { int mi = A(i) % n; int mj = int(A(i) / n); bd(A(i)) = S(mi, mj) * S(mi, mj) + 2 * S(mi, mj) * W(mi, mj); } for (int i = 0; i < I.size(); i++) { int mi = I(i) % n; int mj = int(I(i) / n); bd(I(i)) = W(mi, mj) * W(mi, mj); } return; }; MatrixXd trun_svd(MatrixXd X) { int m = X.rows(), n = X.cols(), K = this->r; MatrixXd Y(m, n); if (m > n) { MatrixXd R = X.transpose() * X; DenseSymMatProd<double> op_r(R); SymEigsSolver<DenseSymMatProd<double>> eig_r(op_r, K, 2 * K > n ? n : 2 * K); eig_r.init(); eig_r.compute(SortRule::LargestAlge); VectorXd evalues; if (eig_r.info() == CompInfo::Successful) { evalues = eig_r.eigenvalues(); int num = 0; for (int s = 0; s < K; s++) { if (evalues(s) > 0) { num++; } } if (num < K) { K = num; } MatrixXd vec_r = eig_r.eigenvectors(K); Y = X * vec_r * vec_r.transpose(); } } else { MatrixXd L = X * X.transpose(); DenseSymMatProd<double> op_l(L); SymEigsSolver<DenseSymMatProd<double>> eig_l(op_l, K, 2 * K > m ? m : 2 * K); eig_l.init(); eig_l.compute(SortRule::LargestAlge); VectorXd evalues; if (eig_l.info() == CompInfo::Successful) { evalues = eig_l.eigenvalues(); int num = 0; for (int s = 0; s < K; s++) { if (evalues(s) > 0) { num++; } } if (num < K) { K = num; } MatrixXd vec_l = eig_l.eigenvectors(K); Y = vec_l * vec_l.transpose() * X; } } return Y; }; MatrixXd HardImpute(T4 &X, VectorXi &A, int max_it, double tol) { int m = X.rows(), n = X.cols(); MatrixXd Z_old = MatrixXd::Zero(m, n); MatrixXd Z_new(m, n); MatrixXd lambda = MatrixXd::Zero(m, n); double eps = 1; int count = 0; while (eps > tol && count < max_it) { lambda = X - Z_old; for (int i = 0; i < A.size(); i++) { int r = A(i) % m; int c = int(A(i) / m); lambda(r, c) = 0; } Z_new = trun_svd(Z_old + lambda); eps = (Z_new - Z_old).squaredNorm() / Z_old.squaredNorm(); Z_old = Z_new; count++; } return Z_new; } MatrixXd compute_S(VectorXd &beta, VectorXi &A, int n, int p) { MatrixXd S = MatrixXd::Zero(n, p); for (int i = 0; i < A.size(); i++) { int mi = A(i) % n; int mj = int(A(i) / n); S(mi, mj) = beta(i); } return S; }; }; #endif // SRC_ALGORITHMPCA_H
11,557
36.044872
120
h
abess
abess-master/src/Data.h
// // Created by Jin Zhu on 2020/2/18. // // #define R_BUILD #ifndef SRC_DATA_H #define SRC_DATA_H #ifdef R_BUILD #include <RcppEigen.h> // [[Rcpp::depends(RcppEigen)]] #else #include <Eigen/Eigen> #endif #include <iostream> #include <vector> #include "normalize.h" #include "utilities.h" using namespace std; using namespace Eigen; template <class T1, class T2, class T3, class T4> class Data { public: T4 x; T1 y; Eigen::VectorXd weight; Eigen::VectorXd x_mean; Eigen::VectorXd x_norm; T3 y_mean; int n; int p; int M; int normalize_type; int g_num; Eigen::VectorXi g_index; Eigen::VectorXi g_size; Data() = default; Data(T4 &x, T1 &y, int normalize_type, Eigen::VectorXd &weight, Eigen::VectorXi &g_index, bool sparse_matrix, int beta_size) { this->x = x; this->y = y; this->normalize_type = normalize_type; this->n = x.rows(); this->p = x.cols(); this->M = y.cols(); this->weight = weight; this->x_mean = Eigen::VectorXd::Zero(this->p); this->x_norm = Eigen::VectorXd::Zero(this->p); if (normalize_type > 0 && !sparse_matrix) { this->normalize(); } this->g_index = g_index; this->g_num = g_index.size(); Eigen::VectorXi temp = Eigen::VectorXi::Zero(this->g_num); for (int i = 0; i < g_num - 1; i++) temp(i) = g_index(i + 1); temp(g_num - 1) = beta_size; this->g_size = temp - g_index; }; void normalize() { if (this->normalize_type == 1) { Normalize(this->x, this->y, this->weight, this->x_mean, this->y_mean, this->x_norm); } else if (this->normalize_type == 2) { Normalize3(this->x, this->weight, this->x_mean, this->x_norm); } else { Normalize4(this->x, this->weight, this->x_norm); } }; // Eigen::VectorXi get_g_index() // { // return this->g_index; // }; // int get_g_num() // { // return this->g_num; // }; // Eigen::VectorXi get_g_size() // { // return this->g_size; // }; // int get_n() // { // return this->n; // }; // int get_p() // { // return this->p; // }; }; #endif // SRC_DATA_H
2,313
21.686275
113
h
abess
abess-master/src/Metric.h
// // Created by Jin Zhu on 2020/2/18. // // #define R_BUILD #ifndef SRC_METRICS_H #define SRC_METRICS_H #ifdef R_BUILD #include <Rcpp.h> using namespace Rcpp; #endif #include <algorithm> #include <random> #include <vector> #include "Algorithm.h" #include "Data.h" #include "utilities.h" template <class T1, class T2, class T3, class T4> // To do: calculate loss && all to one && lm poisson cox class Metric { public: bool is_cv; int Kfold; int eval_type; double ic_coef; bool raise_warning = true; // Eigen::Matrix<T2, Dynamic, 1> cv_initial_model_param; // Eigen::Matrix<T3, Dynamic, 1> cv_initial_coef0; // std::vector<Eigen::VectorXi> cv_initial_A; // std::vector<Eigen::VectorXi> cv_initial_I; std::vector<Eigen::VectorXi> train_mask_list; std::vector<Eigen::VectorXi> test_mask_list; std::vector<T4> train_X_list; std::vector<T4> test_X_list; std::vector<T1> train_y_list; std::vector<T1> test_y_list; std::vector<Eigen::VectorXd> train_weight_list; std::vector<Eigen::VectorXd> test_weight_list; std::vector<FIT_ARG<T2, T3>> cv_init_fit_arg; // std::vector<std::vector<T4>> group_XTX_list; Metric() = default; Metric(int eval_type, double ic_coef = 1.0, int Kfold = 5) { this->is_cv = Kfold > 1; this->eval_type = eval_type; this->Kfold = Kfold; this->ic_coef = ic_coef; if (is_cv) { cv_init_fit_arg.resize(Kfold); train_X_list.resize(Kfold); test_X_list.resize(Kfold); train_y_list.resize(Kfold); test_y_list.resize(Kfold); test_weight_list.resize(Kfold); train_weight_list.resize(Kfold); } }; void set_cv_init_fit_arg(int beta_size, int M) { for (int i = 0; i < this->Kfold; i++) { T2 beta_init; T3 coef0_init; coef_set_zero(beta_size, M, beta_init, coef0_init); Eigen::VectorXi A_init; Eigen::VectorXd bd_init; FIT_ARG<T2, T3> fit_arg(0, 0., beta_init, coef0_init, bd_init, A_init); cv_init_fit_arg[i] = fit_arg; } } // void set_cv_initial_model_param(int Kfold, int p) // { // this->cv_initial_model_param = Eigen::MatrixXd::Zero(p, Kfold); // }; // void set_cv_initial_A(int Kfold, int p) // { // vector<Eigen::VectorXi> tmp(Kfold); // this->cv_initial_A = tmp; // }; // void set_cv_initial_coef0(int Kfold, int p) // { // vector<double> tmp(Kfold); // for (int i = 0; i < Kfold; i++) // tmp[i] = 0; // this->cv_initial_coef0 = tmp; // }; // void update_cv_initial_model_param(Eigen::VectorXd model_param, int k) // { // this->cv_initial_model_param.col(k) = model_param; // } // void update_cv_initial_A(Eigen::VectorXi A, int k) // { // this->cv_initial_A[k] = A; // } // void update_cv_initial_coef0(double coef0, int k) // { // this->cv_initial_coef0[k] = coef0; // } void set_cv_train_test_mask(Data<T1, T2, T3, T4> &data, int n, Eigen::VectorXi &cv_fold_id) { Eigen::VectorXi index_list(n); std::vector<int> index_vec((unsigned int)n); std::vector<Eigen::VectorXi> group_list((unsigned int)this->Kfold); for (int i = 0; i < n; i++) { index_vec[i] = i; } if (cv_fold_id.size() == 0) { // std::random_device rd; std::mt19937 g(123); std::shuffle(index_vec.begin(), index_vec.end(), g); for (int i = 0; i < n; i++) { index_list(i) = index_vec[i]; } Eigen::VectorXd loss_list(this->Kfold); int group_size = int(n / this->Kfold); for (int k = 0; k < (this->Kfold - 1); k++) { group_list[k] = index_list.segment(int(k * group_size), group_size); } group_list[this->Kfold - 1] = index_list.segment(int((this->Kfold - 1) * group_size), n - int(int(this->Kfold - 1) * group_size)); } else { // given cv_fold_id auto rule = [cv_fold_id](int i, int j) -> bool { return cv_fold_id(i) < cv_fold_id(j); }; std::sort(index_vec.begin(), index_vec.end(), rule); for (int i = 0; i < n; i++) { index_list(i) = index_vec[i]; } int k = 0, st = 0, ed = 1; while (k < this->Kfold && ed < n) { int mask = cv_fold_id(index_list(st)); while (ed < n && mask == cv_fold_id(index_list(ed))) ed++; group_list[k] = index_list.segment(st, ed - st); st = ed; ed++; k++; } } for (int k = 0; k < this->Kfold; k++) { std::sort(group_list[k].data(), group_list[k].data() + group_list[k].size()); } // cv train-test partition: std::vector<Eigen::VectorXi> train_mask_list_tmp((unsigned int)this->Kfold); std::vector<Eigen::VectorXi> test_mask_list_tmp((unsigned int)this->Kfold); for (int k = 0; k < this->Kfold; k++) { int train_x_size = n - group_list[k].size(); // get train_mask Eigen::VectorXi train_mask(train_x_size); int i = 0; for (int j = 0; j < this->Kfold; j++) { if (j != k) { for (int s = 0; s < group_list[j].size(); s++) { train_mask(i) = group_list[j](s); i++; } } } std::sort(train_mask.data(), train_mask.data() + train_mask.size()); train_mask_list_tmp[k] = train_mask; test_mask_list_tmp[k] = group_list[k]; slice(data.x, train_mask, this->train_X_list[k]); slice(data.x, group_list[k], this->test_X_list[k]); slice(data.y, train_mask, this->train_y_list[k]); slice(data.y, group_list[k], this->test_y_list[k]); slice(data.weight, train_mask, this->train_weight_list[k]); slice(data.weight, group_list[k], this->test_weight_list[k]); } this->train_mask_list = train_mask_list_tmp; this->test_mask_list = test_mask_list_tmp; }; // void cal_cv_group_XTX(Data<T1, T2, T3> &data) // { // int p = data.p; // Eigen::VectorXi index = data.g_index; // Eigen::VectorXi gsize = data.g_size; // int N = data.g_num; // std::vector<std::vector<Eigen::MatrixXd>> group_XTX_list_tmp(this->Kfold); // for (int k = 0; k < this->Kfold; k++) // { // int train_size = this->train_mask_list[k].size(); // Eigen::MatrixXd train_x(train_size, p); // for (int i = 0; i < train_size; i++) // { // train_x.row(i) = data.x.row(this->train_mask_list[k](i)); // }; // group_XTX_list_tmp[k] = group_XTX(train_x, index, gsize, train_size, p, N, 1); // } // this->group_XTX_list = group_XTX_list_tmp; // } double ic(int train_n, int M, int N, Algorithm<T1, T2, T3, T4> *algorithm) { // information criterioin: for non-CV double loss; if (algorithm->model_type == 1 || algorithm->model_type == 5) { loss = train_n * log(algorithm->get_train_loss() - algorithm->lambda_level * algorithm->beta.cwiseAbs2().sum()); } else { loss = 2 * (algorithm->get_train_loss() - algorithm->lambda_level * algorithm->beta.cwiseAbs2().sum()); } // 0. only loss if (this->eval_type == 0) { return loss; } // 1. AIC if (this->eval_type == 1) { return loss + 2.0 * algorithm->get_effective_number(); } // 2. BIC if (this->eval_type == 2) { return loss + this->ic_coef * log(double(train_n)) * algorithm->get_effective_number(); } // 3. GIC if (this->eval_type == 3) { return loss + this->ic_coef * log(double(N)) * log(log(double(train_n))) * algorithm->get_effective_number(); } // 4. EBIC if (this->eval_type == 4) { return loss + this->ic_coef * (log(double(train_n)) + 2 * log(double(N))) * algorithm->get_effective_number(); } // 5. HIC if (this->eval_type == 5) { return train_n * (algorithm->get_train_loss() - algorithm->lambda_level * algorithm->beta.cwiseAbs2().sum()) + this->ic_coef * log(double(N)) * log(log(double(train_n))) * algorithm->get_effective_number(); } if (this->raise_warning) { #ifdef R_BUILD Rcout << "[warning] No available IC type for training. Use loss instead. " << "(E" << this->eval_type << "M" << algorithm->model_type << ")" << endl; #else cout << "[warning] No available IC type for training. Use loss instead. " << "(E" << this->eval_type << "M" << algorithm->model_type << ")" << endl; #endif this->raise_warning = false; } // return 0; return loss; }; double test_loss(T4 &test_x, T1 &test_y, Eigen::VectorXd &test_weight, Eigen::VectorXi &g_index, Eigen::VectorXi &g_size, int test_n, int p, int N, Algorithm<T1, T2, T3, T4> *algorithm) { // test loss: for CV Eigen::VectorXi A = algorithm->get_A_out(); T2 beta = algorithm->get_beta(); T3 coef0 = algorithm->get_coef0(); Eigen::VectorXi A_ind = find_ind(A, g_index, g_size, beta.rows(), N); T4 test_X_A = X_seg(test_x, test_n, A_ind, algorithm->model_type); T2 beta_A; slice(beta, A_ind, beta_A); // 0. only test loss if (this->eval_type == 0) { return algorithm->loss_function(test_X_A, test_y, test_weight, beta_A, coef0, A, g_index, g_size, algorithm->lambda_level); } // 1. negative AUC (for logistic) if (this->eval_type == 1 && algorithm->model_type == 2) { // compute probability Eigen::VectorXd test_y_temp = test_y; Eigen::VectorXd proba = test_X_A * beta_A + coef0 * Eigen::VectorXd::Ones(test_n); proba = proba.array().exp(); proba = proba.cwiseQuotient(Eigen::VectorXd::Ones(test_n) + proba); return -this->binary_auc_score(test_y_temp, proba); } // 2. 3. negative AUC, One vs One/Rest (for multinomial) if (algorithm->model_type == 6) { int M = test_y.cols(); // compute probability Eigen::MatrixXd proba = test_X_A * beta_A; proba = rowwise_add(proba, coef0); proba = proba.array().exp(); Eigen::VectorXd proba_rowsum = proba.rowwise().sum(); proba = proba.cwiseQuotient(proba_rowsum.replicate(1, p)); // compute AUC if (this->eval_type == 2) { // (One vs One) the AUC of all possible pairwise combinations of classes double auc = 0; for (int i = 0; i < M - 1; i++) { for (int j = i + 1; j < M; j++) { int nij = 0; Eigen::VectorXd test_y_i(test_n), test_y_j(test_n), proba_i(test_n), proba_j(test_n); // extract samples who belongs to class i or j for (int k = 0; k < test_n; k++) { if (test_y(k, i) + test_y(k, j) > 0) { test_y_i(nij) = test_y(k, i); test_y_j(nij) = test_y(k, j); proba_i(nij) = proba(k, i); proba_j(nij) = proba(k, j); nij++; } } test_y_i = test_y_i.head(nij).eval(); test_y_j = test_y_j.head(nij).eval(); proba_i = proba_i.head(nij).eval(); proba_j = proba_j.head(nij).eval(); // get AUC auc += this->binary_auc_score(test_y_i, proba_i); auc += this->binary_auc_score(test_y_j, proba_j); } } return -auc / (p * (p - 1)); } if (this->eval_type == 3) { // (One vs Rest) the AUC of each class against the rest double auc = 0; for (int i = 0; i < M; i++) { Eigen::VectorXd test_y_single = test_y.col(i); Eigen::VectorXd proba_single = proba.col(i); auc += this->binary_auc_score(test_y_single, proba_single); } return -auc / p; } } if (this->raise_warning) { #ifdef R_BUILD Rcout << "[warning] No available CV score for training. Use test_loss instead. " << "(E" << this->eval_type << "M" << algorithm->model_type << ")" << endl; #else cout << "[warning] No available CV score for training. Use test_loss instead. " << "(E" << this->eval_type << "M" << algorithm->model_type << ")" << endl; #endif this->raise_warning = false; } // return 0; return algorithm->loss_function(test_X_A, test_y, test_weight, beta_A, coef0, A, g_index, g_size, algorithm->lambda_level); }; double binary_auc_score(Eigen::VectorXd &true_label, Eigen::VectorXd &pred_proba) { // sort proba from large to small int n = true_label.rows(); Eigen::VectorXi sort_ind = max_k(pred_proba, n, true); // use each value as threshold to get TPR, FPR double tp = 0, fp = 0, positive = true_label.sum(); double last_tpr = 0, last_fpr = 0, auc = 0; if (positive == 0 || positive == n) { #ifdef R_BUILD Rcout << "[Warning] There is only one class in the test data, " << "the result may be meaningless. Please use another type of loss, " << "or try to specify cv_fold_id." << endl; #else cout << "[Warning] There is only one class in the test data, " << "the result may be meaningless. Please use another type of loss, " << "or try to specify cv_fold_id." << endl; #endif } for (int i = 0; i < n; i++) { // current threshold: pred_proba(sort_ind(i)) int k = sort_ind(i); tp += true_label(k); fp += 1 - true_label(k); // skip same threshold if (i < n - 1) { int kk = sort_ind(i + 1); if (pred_proba(k) == pred_proba(kk)) continue; } // compute tpr, fpr double tpr = tp / positive; double fpr = fp / (n - positive); if (fpr > last_fpr) { auc += (tpr + last_tpr) / 2 * (fpr - last_fpr); } last_tpr = tpr; last_fpr = fpr; } return auc; }; // to do Eigen::VectorXd fit_and_evaluate_in_metric(std::vector<Algorithm<T1, T2, T3, T4> *> algorithm_list, Data<T1, T2, T3, T4> &data, FIT_ARG<T2, T3> &fit_arg) { Eigen::VectorXd loss_list(this->Kfold); if (!is_cv) { algorithm_list[0]->update_sparsity_level(fit_arg.support_size); algorithm_list[0]->update_lambda_level(fit_arg.lambda); algorithm_list[0]->update_beta_init(fit_arg.beta_init); algorithm_list[0]->update_bd_init(fit_arg.bd_init); algorithm_list[0]->update_coef0_init(fit_arg.coef0_init); algorithm_list[0]->update_A_init(fit_arg.A_init, data.g_num); algorithm_list[0]->fit(data.x, data.y, data.weight, data.g_index, data.g_size, data.n, data.p, data.g_num); if (algorithm_list[0]->get_warm_start()) { fit_arg.beta_init = algorithm_list[0]->get_beta(); fit_arg.coef0_init = algorithm_list[0]->get_coef0(); fit_arg.bd_init = algorithm_list[0]->get_bd(); } loss_list(0) = this->ic(data.n, data.M, data.g_num, algorithm_list[0]); } else { Eigen::VectorXi g_index = data.g_index; Eigen::VectorXi g_size = data.g_size; int p = data.p; int N = data.g_num; #pragma omp parallel for // parallel for (int k = 0; k < this->Kfold; k++) { // get test_x, test_y int test_n = this->test_mask_list[k].size(); int train_n = this->train_mask_list[k].size(); // train & test data // Eigen::MatrixXd train_x = matrix_slice(data.x, this->train_mask_list[k], 0); // Eigen::MatrixXd test_x = matrix_slice(data.x, this->test_mask_list[k], 0); // Eigen::VectorXd train_y = vector_slice(data.y, this->train_mask_list[k]); // Eigen::VectorXd test_y = vector_slice(data.y, this->test_mask_list[k]); // Eigen::VectorXd train_weight = vector_slice(data.weight, this->train_mask_list[k]); // Eigen::VectorXd test_weight = vector_slice(data.weight, this->test_mask_list[k]); // Eigen::VectorXd beta_init; algorithm_list[k]->update_sparsity_level(fit_arg.support_size); algorithm_list[k]->update_lambda_level(fit_arg.lambda); algorithm_list[k]->update_beta_init(this->cv_init_fit_arg[k].beta_init); algorithm_list[k]->update_bd_init(this->cv_init_fit_arg[k].bd_init); algorithm_list[k]->update_coef0_init(this->cv_init_fit_arg[k].coef0_init); algorithm_list[k]->update_A_init(this->cv_init_fit_arg[k].A_init, N); // beta_init = this->cv_initial_model_param.col(k).eval(); // algorithm->update_beta_init(beta_init); // algorithm->update_coef0_init(this->cv_initial_coef0[k]); // algorithm->update_A_init(this->cv_initial_A[k], N); // algorithm->update_train_mask(this->train_mask_list[k]); // ?????????????????????????????????????????????????????????????? algorithm_list[k]->fit(this->train_X_list[k], this->train_y_list[k], this->train_weight_list[k], g_index, g_size, train_n, p, N); if (algorithm_list[k]->get_warm_start()) { this->cv_init_fit_arg[k].beta_init = algorithm_list[k]->get_beta(); this->cv_init_fit_arg[k].coef0_init = algorithm_list[k]->get_coef0(); this->cv_init_fit_arg[k].bd_init = algorithm_list[k]->get_bd(); // this->update_cv_initial_model_param(algorithm->get_beta(), k); // this->update_cv_initial_A(algorithm->get_A_out(), k); // this->update_cv_initial_coef0(algorithm->get_coef0(), k); } loss_list(k) = this->test_loss(this->test_X_list[k], this->test_y_list[k], this->test_weight_list[k], g_index, g_size, test_n, p, N, algorithm_list[k]); } } return loss_list; }; }; #endif // SRC_METRICS_H
19,691
39.68595
119
h
abess
abess-master/src/abessOpenMP.h
#ifndef SRC_ABESSOPENMP_H #define SRC_ABESSOPENMP_H #ifdef _OPENMP #include <omp.h> // [[Rcpp::plugins(openmp)]] #else #ifndef DISABLE_OPENMP #ifndef R_BUILD // use pragma message instead of warning #pragma message( \ "Warning: OpenMP is not available, " \ "project will be compiled into single-thread code. " \ "Use OpenMP-enabled compiler to get benefit of multi-threading.") #endif #endif inline int omp_get_thread_num() { return 0; } inline int omp_get_num_threads() { return 1; } inline int omp_get_num_procs() { return 1; } inline void omp_set_num_threads(int nthread) {} inline void omp_set_dynamic(int flag) {} #endif #endif // SRC_ABESSOPENMP_H
725
28.04
69
h
abess
abess-master/src/api.h
/***************************************************************************** * OpenST Basic tool library * * Copyright (C) 2021 Kangkang Jiang [email protected] * * * * This file is part of OST. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 3 as * * published by the Free Software Foundation. * * * * You should have received a copy of the GNU General Public License * * along with OST. If not, see <http://www.gnu.org/licenses/>. * * * * 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. * * * * @file abess.h * * @brief The main function of abess fremework * * * * * * @author Kangkang Jiang * * @email [email protected] * * @version 0.0.1 * * @date 2021-07-31 * * @license GNU General Public License (GPL) * * * *----------------------------------------------------------------------------* * Remark : Description * *----------------------------------------------------------------------------* * Change History : * * <Date> | <Version> | <Author> | <Description> * *----------------------------------------------------------------------------* * 2021/07/31 | 0.0.1 | Kangkang Jiang | First version * *----------------------------------------------------------------------------* * * *****************************************************************************/ #ifndef SRC_API_H #define SRC_API_H #ifdef R_BUILD #include <Rcpp.h> #include <RcppEigen.h> // [[Rcpp::depends(RcppEigen)]] using namespace Rcpp; #else #include <Eigen/Eigen> #include "List.h" #endif #include <iostream> /** * @brief The main function of abess fremework * @param X Training data. * @param y Target values. Will be cast to X's dtype if necessary. * For linear regression problem, y should be a $n \time 1$ numpy array with type * \code{double}. For classification problem, \code{y} should be a $n \time 1$ numpy array with values \code{0} or * \code{1}. For count data, \code{y} should be a $n \time 1$ numpy array of non-negative integer. Note that, for * multivariate problem, \code{y} can also be a matrix shaped $n \time M$, where $M > 1$. * @param n Sample size. * @param p Variable dimension. * @param weight Individual weights for each sample. * @param sigma Sample covariance matrix. For PCA problem under Kfold=1, it should be given as * input, instead of X. * @param normalize_type Type of normalization on X before fitting the algorithm. If normalize_type=0, * normalization will not be used. * @param algorithm_type Algorithm type. * @param model_type Model type. * @param max_iter Maximum number of iterations taken for the splicing algorithm to converge. * Due to the limitation of loss reduction, the splicing algorithm must be able to * converge. The number of iterations is only to simplify the implementation. * @param exchange_num Max exchange variable num for the splicing algorithm. * @param path_type The method to be used to select the optimal support size. * For path_type = 1, we solve the best subset selection problem for each size in * support_size. For path_type = 2, we solve the best subset selection problem with support size ranged in (s_min, * s_max), where the specific support size to be considered is determined by golden section. * @param is_warm_start When tuning the optimal parameter combination, whether to use the last solution * as a warm start to accelerate the iterative convergence of the splicing algorithm. * @param ic_type The type of criterion for choosing the support size. * @param Kfold The folds number to use the Cross-validation method. If Kfold=1, * Cross-validation will not be used. * @param sequence An integer vector representing the alternative support sizes. Only used for * path_type = 1. * @param s_min The lower bound of golden-section-search for sparsity searching. Only used for * path_type = 2. * @param s_max The higher bound of golden-section-search for sparsity searching. Only used for * path_type = 2. * @param thread Max number of multithreads. If thread = 0, the program will use the maximum * number supported by the device. * @param screening_size Screen the variables first and use the chosen variables in abess process. * The number of variables remaining after screening. It should be an integer * smaller than p. If screen_size = -1, screening will not be used. * @param g_index The group index for each variable. * @param always_select An array contains the indexes of variables we want to consider in the model. * @param primary_model_fit_max_iter The maximal number of iteration in `primary_model_fit()` (in Algorithm.h). * @param primary_model_fit_epsilon The epsilon (threshold) of iteration in `primary_model_fit()` (in Algorithm.h). * @param splicing_type The type of splicing in `fit()` (in Algorithm.h). * "0" for decreasing by half, "1" for decresing by one. * @param sub_search The number of inactive sets that are split when splicing. It should be a * positive integer. * @return result list. */ List abessGLM_API(Eigen::MatrixXd x, Eigen::MatrixXd y, int n, int p, int normalize_type, Eigen::VectorXd weight, int algorithm_type, int model_type, int max_iter, int exchange_num, int path_type, bool is_warm_start, int ic_type, double ic_coef, int Kfold, Eigen::VectorXi sequence, Eigen::VectorXd lambda_seq, int s_min, int s_max, double lambda_min, double lambda_max, int nlambda, int screening_size, Eigen::VectorXi g_index, Eigen::VectorXi always_select, int primary_model_fit_max_iter, double primary_model_fit_epsilon, bool early_stop, bool approximate_Newton, int thread, bool covariance_update, bool sparse_matrix, int splicing_type, int sub_search, Eigen::VectorXi cv_fold_id, Eigen::VectorXi A_init, bool fit_intercept); List abessPCA_API(Eigen::MatrixXd x, int n, int p, int normalize_type, Eigen::VectorXd weight, Eigen::MatrixXd sigma, int max_iter, int exchange_num, int path_type, bool is_warm_start, int ic_type, double ic_coef, int Kfold, Eigen::MatrixXi sequence, int s_min, int s_max, int screening_size, Eigen::VectorXi g_index, Eigen::VectorXi always_select, bool early_stop, int thread, bool sparse_matrix, int splicing_type, int sub_search, Eigen::VectorXi cv_fold_id, int pca_num, Eigen::VectorXi A_init); List abessRPCA_API(Eigen::MatrixXd x, int n, int p, int max_iter, int exchange_num, int path_type, bool is_warm_start, int ic_type, double ic_coef, Eigen::VectorXi sequence, Eigen::VectorXd lambda_seq, // rank of L int s_min, int s_max, double lambda_min, double lambda_max, int nlambda, int screening_size, int primary_model_fit_max_iter, double primary_model_fit_epsilon, Eigen::VectorXi g_index, Eigen::VectorXi always_select, bool early_stop, int thread, bool sparse_matrix, int splicing_type, int sub_search, Eigen::VectorXi A_init); #endif // SRC_API_H
9,617
71.315789
120
h
abess
abess-master/src/normalize.h
// // Created by Jin Zhu on 2020/3/8. // // #define R_BUILD #ifndef SRC_NORMALIZE_H #define SRC_NORMALIZE_H #ifdef R_BUILD #include <RcppEigen.h> #else #include <Eigen/Eigen> #endif void constant_warning_ith_variable(int i); void Normalize(Eigen::MatrixXd &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, double &meany, Eigen::VectorXd &normx); void Normalize(Eigen::MatrixXd &X, Eigen::MatrixXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &meany, Eigen::VectorXd &normx); void Normalize3(Eigen::MatrixXd &X, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &normx); void Normalize4(Eigen::MatrixXd &X, Eigen::VectorXd &weights, Eigen::VectorXd &normx); void Normalize(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, double &meany, Eigen::VectorXd &normx); void Normalize(Eigen::SparseMatrix<double> &X, Eigen::MatrixXd &y, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &meany, Eigen::VectorXd &normx); void Normalize3(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &weights, Eigen::VectorXd &meanx, Eigen::VectorXd &normx); void Normalize4(Eigen::SparseMatrix<double> &X, Eigen::VectorXd &weights, Eigen::VectorXd &normx); #endif // SRC_NORMALIZE_H
1,375
42
119
h
abess
abess-master/src/path.h
// // Created by Jin Zhu on 2020/3/8. // #ifndef SRC_PATH_H #define SRC_PATH_H #ifdef R_BUILD #include <RcppEigen.h> // [[Rcpp::depends(RcppEigen)]s] using namespace Eigen; #else #include <Eigen/Eigen> #include "List.h" #endif #include <vector> #include "Algorithm.h" #include "Data.h" #include "Metric.h" #include "utilities.h" template <class T1, class T2, class T3, class T4> void sequential_path_cv(Data<T1, T2, T3, T4> &data, Algorithm<T1, T2, T3, T4> *algorithm, Metric<T1, T2, T3, T4> *metric, Parameters &parameters, bool early_stop, int k, Eigen::VectorXi &A_init, Result<T2, T3> &result) { int beta_size = algorithm->get_beta_size(data.n, data.p); int p = data.p; int N = data.g_num; int M = data.M; Eigen::VectorXi g_index = data.g_index; Eigen::VectorXi g_size = data.g_size; int sequence_size = (parameters.sequence).size(); // int early_stop_s = sequence_size; Eigen::VectorXi train_mask, test_mask; T1 train_y, test_y; Eigen::VectorXd train_weight, test_weight; T4 train_x, test_x; int train_n = 0, test_n = 0; // train & test data if (!metric->is_cv) { train_x = data.x; train_y = data.y; train_weight = data.weight; train_n = data.n; } else { train_mask = metric->train_mask_list[k]; test_mask = metric->test_mask_list[k]; slice(data.x, train_mask, train_x); slice(data.x, test_mask, test_x); slice(data.y, train_mask, train_y); slice(data.y, test_mask, test_y); slice(data.weight, train_mask, train_weight); slice(data.weight, test_mask, test_weight); train_n = train_mask.size(); test_n = test_mask.size(); } Eigen::Matrix<T2, Dynamic, 1> beta_matrix(sequence_size, 1); Eigen::Matrix<T3, Dynamic, 1> coef0_matrix(sequence_size, 1); Eigen::MatrixXd train_loss_matrix(sequence_size, 1); Eigen::MatrixXd ic_matrix(sequence_size, 1); Eigen::MatrixXd test_loss_matrix(sequence_size, 1); Eigen::Matrix<VectorXd, Dynamic, 1> bd_matrix(sequence_size, 1); Eigen::MatrixXd effective_number_matrix(sequence_size, 1); T2 beta_init; T3 coef0_init; coef_set_zero(beta_size, M, beta_init, coef0_init); Eigen::VectorXd bd_init; for (int ind = 0; ind < sequence_size; ind++) { algorithm->update_sparsity_level(parameters.sequence(ind).support_size); algorithm->update_lambda_level(parameters.sequence(ind).lambda); algorithm->update_beta_init(beta_init); algorithm->update_bd_init(bd_init); algorithm->update_coef0_init(coef0_init); algorithm->update_A_init(A_init, N); algorithm->fit(train_x, train_y, train_weight, g_index, g_size, train_n, p, N); if (algorithm->warm_start) { beta_init = algorithm->get_beta(); coef0_init = algorithm->get_coef0(); bd_init = algorithm->get_bd(); } // evaluate the beta if (metric->is_cv) { test_loss_matrix(ind) = metric->test_loss(test_x, test_y, test_weight, g_index, g_size, test_n, p, N, algorithm); } else { ic_matrix(ind) = metric->ic(train_n, M, N, algorithm); } // save for best_model fit beta_matrix(ind) = algorithm->get_beta(); coef0_matrix(ind) = algorithm->get_coef0(); train_loss_matrix(ind) = algorithm->get_train_loss(); bd_matrix(ind) = algorithm->get_bd(); effective_number_matrix(ind) = algorithm->get_effective_number(); } // To be ensured // if (early_stop && lambda_size <= 1 && i >= 3) // { // bool condition1 = ic_sequence(i, 0) > ic_sequence(i - 1, 0); // bool condition2 = ic_sequence(i - 1, 0) > ic_sequence(i - 2, 0); // bool condition3 = ic_sequence(i - 2, 0) > ic_sequence(i - 3, 0); // if (condition1 && condition2 && condition3) // { // early_stop_s = i + 1; // break; // } // } // if (early_stop) // { // ic_sequence = ic_sequence.block(0, 0, early_stop_s, lambda_size).eval(); // } result.beta_matrix = beta_matrix; result.coef0_matrix = coef0_matrix; result.train_loss_matrix = train_loss_matrix; result.bd_matrix = bd_matrix; result.ic_matrix = ic_matrix; result.test_loss_matrix = test_loss_matrix; result.effective_number_matrix = effective_number_matrix; } template <class T1, class T2, class T3, class T4> void gs_path(Data<T1, T2, T3, T4> &data, vector<Algorithm<T1, T2, T3, T4> *> algorithm_list, Metric<T1, T2, T3, T4> *metric, Parameters &parameters, Eigen::VectorXi &A_init, vector<Result<T2, T3>> &result_list) { int s_min = parameters.s_min; int s_max = parameters.s_max; int sequence_size = s_max - s_min + 5; Eigen::VectorXi support_size_list = Eigen::VectorXi::Zero(sequence_size); // init: store for each fold int Kfold = metric->Kfold; vector<Eigen::Matrix<T2, -1, -1>> beta_matrix(Kfold); vector<Eigen::Matrix<T3, -1, -1>> coef0_matrix(Kfold); vector<Eigen::MatrixXd> train_loss_matrix(Kfold); vector<Eigen::MatrixXd> ic_matrix(Kfold); vector<Eigen::MatrixXd> test_loss_matrix(Kfold); vector<Eigen::Matrix<VectorXd, -1, -1>> bd_matrix(Kfold); vector<Eigen::MatrixXd> effective_number_matrix(Kfold); for (int k = 0; k < Kfold; k++) { beta_matrix[k].resize(sequence_size, 1); coef0_matrix[k].resize(sequence_size, 1); train_loss_matrix[k].resize(sequence_size, 1); ic_matrix[k].resize(sequence_size, 1); test_loss_matrix[k].resize(sequence_size, 1); bd_matrix[k].resize(sequence_size, 1); effective_number_matrix[k].resize(sequence_size, 1); } T2 beta_init; T3 coef0_init; int beta_size = algorithm_list[0]->get_beta_size(data.n, data.p); coef_set_zero(beta_size, data.M, beta_init, coef0_init); Eigen::VectorXd bd_init; // gs only support the first lambda FIT_ARG<T2, T3> fit_arg(0, parameters.lambda_list(0), beta_init, coef0_init, bd_init, A_init); int ind = -1; int left = round(0.618 * s_min + 0.382 * s_max); int right = round(0.382 * s_min + 0.618 * s_max); bool fit_l = true, fit_r = (left != right); double loss_l = 0, loss_r = 0; while (true) { // cout<<" ==> gs: "<<s_min<<" - "<<s_max<<endl; if (fit_l) { fit_l = false; fit_arg.support_size = left; Eigen::VectorXd loss_list = metric->fit_and_evaluate_in_metric(algorithm_list, data, fit_arg); loss_l = loss_list.mean(); // record: left support_size_list(++ind) = left; for (int k = 0; k < Kfold; k++) { beta_matrix[k](ind) = algorithm_list[k]->beta; coef0_matrix[k](ind) = algorithm_list[k]->coef0; train_loss_matrix[k](ind) = algorithm_list[k]->get_train_loss(); bd_matrix[k](ind) = algorithm_list[k]->bd; effective_number_matrix[k](ind) = algorithm_list[k]->get_effective_number(); if (metric->is_cv) test_loss_matrix[k](ind) = loss_list(k); else ic_matrix[k](ind) = loss_list(k); } } if (fit_r) { fit_r = false; fit_arg.support_size = right; Eigen::VectorXd loss_list = metric->fit_and_evaluate_in_metric(algorithm_list, data, fit_arg); loss_r = loss_list.mean(); // record: pos 2 support_size_list(++ind) = right; for (int k = 0; k < Kfold; k++) { beta_matrix[k](ind) = algorithm_list[k]->beta; coef0_matrix[k](ind) = algorithm_list[k]->coef0; train_loss_matrix[k](ind) = algorithm_list[k]->get_train_loss(); bd_matrix[k](ind) = algorithm_list[k]->bd; effective_number_matrix[k](ind) = algorithm_list[k]->get_effective_number(); if (metric->is_cv) test_loss_matrix[k](ind) = loss_list(k); else ic_matrix[k](ind) = loss_list(k); } } // update split point if (loss_l < loss_r) { s_max = right; right = left; loss_r = loss_l; left = round(0.618 * s_min + 0.382 * s_max); fit_l = true; } else { s_min = left; left = right; loss_l = loss_r; right = round(0.382 * s_min + 0.618 * s_max); fit_r = true; } if (left == right) break; } // cout<<"left==right | s_min = "<<s_min<<" | s_max = "<<s_max<<endl; T2 best_beta; // T3 best_coef0; // double best_train_loss = 0; double best_loss = DBL_MAX; for (int s = s_min; s <= s_max; s++) { fit_arg.support_size = s; fit_arg.beta_init = beta_init; fit_arg.coef0_init = coef0_init; fit_arg.bd_init = bd_init; Eigen::VectorXd loss_list = metric->fit_and_evaluate_in_metric(algorithm_list, data, fit_arg); double loss = loss_list.mean(); if (loss < best_loss) { // record support_size_list(++ind) = s; best_loss = loss; for (int k = 0; k < Kfold; k++) { beta_matrix[k](ind) = algorithm_list[k]->beta; coef0_matrix[k](ind) = algorithm_list[k]->coef0; train_loss_matrix[k](ind) = algorithm_list[k]->get_train_loss(); bd_matrix[k](ind) = algorithm_list[k]->bd; effective_number_matrix[k](ind) = algorithm_list[k]->get_effective_number(); if (metric->is_cv) test_loss_matrix[k](ind) = loss_list(k); else ic_matrix[k](ind) = loss_list(k); } } } ind++; for (int k = 0; k < Kfold; k++) { result_list[k].beta_matrix = beta_matrix[k].block(0, 0, ind, 1); result_list[k].coef0_matrix = coef0_matrix[k].block(0, 0, ind, 1); result_list[k].train_loss_matrix = train_loss_matrix[k].block(0, 0, ind, 1); result_list[k].bd_matrix = bd_matrix[k].block(0, 0, ind, 1); result_list[k].ic_matrix = ic_matrix[k].block(0, 0, ind, 1); result_list[k].test_loss_matrix = test_loss_matrix[k].block(0, 0, ind, 1); result_list[k].effective_number_matrix = effective_number_matrix[k].block(0, 0, ind, 1); } // build sequence for gs parameters.support_size_list = support_size_list.head(ind).eval(); parameters.lambda_list = parameters.lambda_list.head(1).eval(); parameters.build_sequence(); } // double det(double a[], double b[]); // calculate the intersection of two lines // if parallal, need_flag = false. // void line_intersection(double line1[2][2], double line2[2][2], double intersection[], bool &need_flag); // boundary: s=smin, s=max, lambda=lambda_min, lambda_max // line: crosses p and is parallal to u // calculate the intersections between boundary and line // void cal_intersections(double p[], double u[], int s_min, int s_max, double lambda_min, double lambda_max, int a[], // int b[]); // template <class T1, class T2, class T3> // void golden_section_search(Data<T1, T2, T3> &data, Algorithm<T1, T2, T3> *algorithm, Metric<T1, T2, T3> *metric, // double p[], double u[], int s_min, int s_max, double log_lambda_min, double log_lambda_max, double best_arg[], // T2 &beta1, T3 &coef01, double &train_loss1, double &ic1, Eigen::MatrixXd &ic_sequence); // template <class T1, class T2, class T3> // void seq_search(Data<T1, T2, T3> &data, Algorithm<T1, T2, T3> *algorithm, Metric<T1, T2, T3> *metric, double p[], // double u[], int s_min, int s_max, double log_lambda_min, double log_lambda_max, double best_arg[], // T2 &beta1, T3 &coef01, double &train_loss1, double &ic1, int nlambda, Eigen::MatrixXd &ic_sequence); // List pgs_path(Data &data, Algorithm *algorithm, Metric *metric, int s_min, int s_max, double log_lambda_min, double // log_lambda_max, int powell_path, int nlambda); #endif // SRC_PATH_H
12,293
38.277955
119
h
abess
abess-master/src/screening.h
#ifndef SRC_SCREENING_H #define SRC_SCREENING_H // #define R_BUILD #ifdef R_BUILD #include <Rcpp.h> #include <RcppEigen.h> using namespace Rcpp; // [[Rcpp::depends(RcppEigen)]] #else #include <Eigen/Eigen> #endif #include <algorithm> #include <cfloat> #include <iostream> #include "Data.h" #include "utilities.h" using namespace std; using namespace Eigen; template <class T1, class T2, class T3, class T4> Eigen::VectorXi screening(Data<T1, T2, T3, T4> &data, std::vector<Algorithm<T1, T2, T3, T4> *> algorithm_list, int screening_size, int &beta_size, double lambda, Eigen::VectorXi &A_init) { int n = data.n; int M = data.M; int g_num = data.g_num; Eigen::VectorXi g_size = data.g_size; Eigen::VectorXi g_index = data.g_index; Eigen::VectorXi always_select = algorithm_list[0]->always_select; Eigen::VectorXi screening_A(screening_size); Eigen::VectorXd coef_norm = Eigen::VectorXd::Zero(g_num); T2 beta_init; T3 coef0_init; Eigen::VectorXd bd_init; for (int i = 0; i < g_num; i++) { int p_tmp = g_size(i); T4 x_tmp = data.x.middleCols(g_index(i), p_tmp); Eigen::VectorXi g_index_tmp = Eigen::VectorXi::LinSpaced(p_tmp, 0, p_tmp - 1); Eigen::VectorXi g_size_tmp = Eigen::VectorXi::Ones(p_tmp); coef_set_zero(p_tmp, M, beta_init, coef0_init); algorithm_list[0]->update_sparsity_level(p_tmp); algorithm_list[0]->update_lambda_level(lambda); algorithm_list[0]->update_beta_init(beta_init); algorithm_list[0]->update_bd_init(bd_init); algorithm_list[0]->update_coef0_init(coef0_init); algorithm_list[0]->update_A_init(A_init, p_tmp); algorithm_list[0]->fit(x_tmp, data.y, data.weight, g_index_tmp, g_size_tmp, n, p_tmp, p_tmp); T2 beta = algorithm_list[0]->beta; coef_norm(i) = beta.squaredNorm() / p_tmp; } // keep always_select in active_set slice_assignment(coef_norm, always_select, DBL_MAX); screening_A = max_k(coef_norm, screening_size); // data after screening Eigen::VectorXi new_g_index(screening_size); Eigen::VectorXi new_g_size(screening_size); int new_p = 0; for (int i = 0; i < screening_size; i++) { new_p += g_size(screening_A(i)); new_g_size(i) = g_size(screening_A(i)); } new_g_index(0) = 0; for (int i = 0; i < screening_size - 1; i++) { new_g_index(i + 1) = new_g_index(i) + g_size(screening_A(i)); } Eigen::VectorXi screening_A_ind = find_ind(screening_A, g_index, g_size, beta_size, g_num); T4 x_A; slice(data.x, screening_A_ind, x_A, 1); Eigen::VectorXd new_x_mean, new_x_norm; slice(data.x_mean, screening_A_ind, new_x_mean); slice(data.x_norm, screening_A_ind, new_x_norm); data.x = x_A; data.x_mean = new_x_mean; data.x_norm = new_x_norm; data.p = new_p; data.g_num = screening_size; data.g_index = new_g_index; data.g_size = new_g_size; beta_size = algorithm_list[0]->get_beta_size(n, new_p); if (always_select.size() != 0) { Eigen::VectorXi new_always_select(always_select.size()); int j = 0; for (int i = 0; i < always_select.size(); i++) { while (always_select(i) != screening_A(j)) j++; new_always_select(i) = j; } int algorithm_list_size = algorithm_list.size(); for (int i = 0; i < algorithm_list_size; i++) { algorithm_list[i]->always_select = new_always_select; } } algorithm_list[0]->clear_setting(); return screening_A_ind; } #endif // SRC_SCREENING_H
3,639
30.37931
110
h
abess
abess-master/src/utilities.h
// // Created by jiangkangkang on 2020/3/9. // /** * @file utilities.h * @brief some utilities for abess package. */ #ifndef SRC_UTILITIES_H #define SRC_UTILITIES_H #ifndef R_BUILD #include <Eigen/Eigen> #include <unsupported/Eigen/MatrixFunctions> #else #include <Rcpp.h> #include <RcppEigen.h> #endif #include <cfloat> #include <iostream> using namespace std; using namespace Eigen; /** * @brief Save the sequential fitting result along the parameter searching. * @details All matrix stored here have only one column, and each row correspond to a * parameter combination in class Parameters. * @tparam T2 for beta * @tparam T3 for coef0 */ template <class T2, class T3> struct Result { Eigen::Matrix<T2, Eigen::Dynamic, Eigen::Dynamic> beta_matrix; /*!< Each value is the beta corrsponding a parameter combination */ Eigen::Matrix<T3, Eigen::Dynamic, Eigen::Dynamic> coef0_matrix; /*!< Each value is the coef0 corrsponding a parameter combination */ Eigen::MatrixXd ic_matrix; /*!< Each value is the information criterion value corrsponding a parameter combination */ Eigen::MatrixXd test_loss_matrix; /*!< Each value is the test loss corrsponding a parameter combination */ Eigen::MatrixXd train_loss_matrix; /*!< Each value is the train loss corrsponding a parameter combination */ Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, Eigen::Dynamic> bd_matrix; /*!< Each value is the sacrfice corrsponding a parameter combination */ Eigen::MatrixXd effective_number_matrix; /*!< Each value is the effective number corrsponding a parameter combination */ }; template <class T2, class T3> struct FIT_ARG { int support_size; double lambda; T2 beta_init; T3 coef0_init; Eigen::VectorXd bd_init; Eigen::VectorXi A_init; FIT_ARG(int _support_size, double _lambda, T2 _beta_init, T3 _coef0_init, VectorXd _bd_init, VectorXi _A_init) { support_size = _support_size; lambda = _lambda; beta_init = _beta_init; coef0_init = _coef0_init; bd_init = _bd_init; A_init = _A_init; }; FIT_ARG(){}; }; struct single_parameter { int support_size; double lambda; single_parameter(){}; single_parameter(int support_size, double lambda) { this->support_size = support_size; this->lambda = lambda; }; }; /** * @brief Parameter list * @details Store all parameters (e.g. `support_size`, `lambda`), and make a list of their combination. * So that the algorithm can extract them one by one. */ class Parameters { public: Eigen::VectorXi support_size_list; Eigen::VectorXd lambda_list; int s_min = 0; int s_max = 0; Eigen::Matrix<single_parameter, -1, 1> sequence; Parameters() {} Parameters(Eigen::VectorXi &support_size_list, Eigen::VectorXd &lambda_list, int s_min, int s_max) { this->support_size_list = support_size_list; this->lambda_list = lambda_list; this->s_min = s_min; this->s_max = s_max; if (support_size_list.size() > 0) { // path = "seq" this->build_sequence(); } } /** * @brief build sequence with all combinations of parameters. */ void build_sequence() { // suppose each input vector has size >= 1 int ind = 0; int size1 = (this->support_size_list).size(); int size2 = (this->lambda_list).size(); (this->sequence).resize(size1 * size2, 1); for (int i1 = 0; i1 < size1; i1++) { // other order? for (int i2 = (1 - pow(-1, i1)) * (size2 - 1) / 2; i2 < size2 && i2 >= 0; i2 = i2 + pow(-1, i1)) { int support_size = this->support_size_list(i1); double lambda = this->lambda_list(i2); single_parameter temp(support_size, lambda); this->sequence(ind++) = temp; } } } void print_sequence() { // for debug #ifdef R_BUILD Rcout << "==> Parameter List:" << endl; #else std::cout << "==> Parameter List:" << endl; #endif for (int i = 0; i < (this->sequence).size(); i++) { int support_size = (this->sequence(i)).support_size; double lambda = (this->sequence(i)).lambda; #ifdef R_BUILD Rcout << " support_size = " << support_size << ", lambda = " << lambda << endl; #else std::cout << " support_size = " << support_size << ", lambda = " << lambda << endl; #endif } } }; /** * @brief return the indexes of all variables in groups in `L`. */ Eigen::VectorXi find_ind(Eigen::VectorXi &L, Eigen::VectorXi &index, Eigen::VectorXi &gsize, int beta_size, int N); /** * @brief return part of X, which only contains columns in `ind`. */ template <class T4> T4 X_seg(T4 &X, int n, Eigen::VectorXi &ind, int model_type) { if (ind.size() == X.cols() || model_type == 10 || model_type == 7) { return X; } else { T4 X_new(n, ind.size()); for (int k = 0; k < ind.size(); k++) { X_new.col(k) = X.col(ind(k)); } return X_new; } }; // template <class T4> // void X_seg(T4 &X, int n, Eigen::VectorXi &ind, T4 &X_seg) // { // if (ind.size() == X.cols()) // { // X_seg = X; // } // else // { // X_seg.resize(n, ind.size()); // for (int k = 0; k < ind.size(); k++) // { // X_seg.col(k) = X.col(ind(k)); // } // } // }; template <class T4> Eigen::Matrix<T4, -1, -1> compute_group_XTX(T4 &X, Eigen::VectorXi index, Eigen::VectorXi gsize, int n, int p, int N) { Eigen::Matrix<T4, -1, -1> XTX(N, 1); for (int i = 0; i < N; i++) { T4 X_ind = X.block(0, index(i), n, gsize(i)); XTX(i, 0) = X_ind.transpose() * X_ind; } return XTX; } template <class T4> Eigen::Matrix<Eigen::MatrixXd, -1, -1> Phi(T4 &X, Eigen::VectorXi index, Eigen::VectorXi gsize, int n, int p, int N, double lambda, Eigen::Matrix<T4, -1, -1> group_XTX) { Eigen::Matrix<Eigen::MatrixXd, -1, -1> phi(N, 1); for (int i = 0; i < N; i++) { Eigen::MatrixXd lambda_XtX = 2 * lambda * Eigen::MatrixXd::Identity(gsize(i), gsize(i)) + group_XTX(i, 0) / double(n); lambda_XtX.sqrt().evalTo(phi(i, 0)); } return phi; } Eigen::Matrix<Eigen::MatrixXd, -1, -1> invPhi(Eigen::Matrix<Eigen::MatrixXd, -1, -1> &Phi, int N); // void max_k(Eigen::VectorXd &vec, int k, Eigen::VectorXi &result); void slice_assignment(Eigen::VectorXd &nums, Eigen::VectorXi &ind, double value); // Eigen::VectorXi get_value_index(Eigen::VectorXd &nums, double value); // Eigen::VectorXd vector_slice(Eigen::VectorXd &nums, Eigen::VectorXi &ind); Eigen::VectorXi vector_slice(Eigen::VectorXi &nums, Eigen::VectorXi &ind); // Eigen::MatrixXd row_slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind); // Eigen::MatrixXd matrix_slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind, int axis); // Eigen::MatrixXd X_seg(Eigen::MatrixXd &X, int n, Eigen::VectorXi &ind); /** * @brief complement of A, the whole set is {0..N-1} */ Eigen::VectorXi complement(Eigen::VectorXi &A, int N); // Eigen::VectorXi Ac(Eigen::VectorXi &A, Eigen::VectorXi &U); /** * @brief replace `B` by `C` in `A` */ Eigen::VectorXi diff_union(Eigen::VectorXi A, Eigen::VectorXi &B, Eigen::VectorXi &C); /** * @brief return the indexes of min `k` values in `nums`. */ Eigen::VectorXi min_k(Eigen::VectorXd &nums, int k, bool sort_by_value = false); /** * @brief return the indexes of max `k` values in `nums`. */ Eigen::VectorXi max_k(Eigen::VectorXd &nums, int k, bool sort_by_value = false); // Eigen::VectorXi max_k_2(Eigen::VectorXd &vec, int k); /** * @brief Extract `nums` at `ind` position, and store in `A`. */ void slice(Eigen::VectorXd &nums, Eigen::VectorXi &ind, Eigen::VectorXd &A, int axis = 0); void slice(Eigen::MatrixXd &nums, Eigen::VectorXi &ind, Eigen::MatrixXd &A, int axis = 0); void slice(Eigen::SparseMatrix<double> &nums, Eigen::VectorXi &ind, Eigen::SparseMatrix<double> &A, int axis = 0); /** * @brief The inverse action of function slice. */ void slice_restore(Eigen::VectorXd &A, Eigen::VectorXi &ind, Eigen::VectorXd &nums, int axis = 0); void slice_restore(Eigen::MatrixXd &A, Eigen::VectorXi &ind, Eigen::MatrixXd &nums, int axis = 0); void coef_set_zero(int p, int M, Eigen::VectorXd &beta, double &coef0); void coef_set_zero(int p, int M, Eigen::MatrixXd &beta, Eigen::VectorXd &coef0); /** * @brief element-wise product: A.array() * B.array(). */ Eigen::VectorXd array_product(Eigen::VectorXd &A, Eigen::VectorXd &B, int axis = 0); /** * @brief product by specific axis. */ Eigen::MatrixXd array_product(Eigen::MatrixXd &A, Eigen::VectorXd &B, int axis = 0); // Eigen::SparseMatrix<double> array_product(Eigen::SparseMatrix<double> &A, Eigen::VectorXd &B, int axis = 0); /** * @brief element-wise division: A.array() / B.array(). */ void array_quotient(Eigen::VectorXd &A, Eigen::VectorXd &B, int axis = 0); /** * @brief division by specific axis. */ void array_quotient(Eigen::MatrixXd &A, Eigen::VectorXd &B, int axis = 0); /** * @brief A.dot(B) */ double matrix_dot(Eigen::VectorXd &A, Eigen::VectorXd &B); /** * @brief A.transpose() * B */ Eigen::VectorXd matrix_dot(Eigen::MatrixXd &A, Eigen::VectorXd &B); // void matrix_sqrt(Eigen::MatrixXd &A, Eigen::MatrixXd &B); // void matrix_sqrt(Eigen::SparseMatrix<double> &A, Eigen::MatrixXd &B); /** * @brief Add an all-ones column as the first column in X. */ void add_constant_column(Eigen::MatrixXd &X); /** * @brief Add an all-ones column as the first column in X. */ void add_constant_column(Eigen::SparseMatrix<double> &X); // void set_nonzeros(Eigen::MatrixXd &X, Eigen::MatrixXd &x); // void set_nonzeros(Eigen::SparseMatrix<double> &X, Eigen::SparseMatrix<double> &x); // void overload_ldlt(Eigen::SparseMatrix<double> &X_new, Eigen::SparseMatrix<double> &X, Eigen::VectorXd &Z, // Eigen::VectorXd &beta); void overload_ldlt(Eigen::MatrixXd &X_new, Eigen::MatrixXd &X, Eigen::VectorXd &Z, // Eigen::VectorXd &beta); // void overload_ldlt(Eigen::SparseMatrix<double> &X_new, Eigen::SparseMatrix<double> &X, Eigen::MatrixXd &Z, // Eigen::MatrixXd &beta); void overload_ldlt(Eigen::MatrixXd &X_new, Eigen::MatrixXd &X, Eigen::MatrixXd &Z, // Eigen::MatrixXd &beta); // bool check_ill_condition(Eigen::MatrixXd &M); /** * @brief If enable normalization, restore coefficients after fitting. */ template <class T2, class T3> void restore_for_normal(T2 &beta, T3 &coef0, Eigen::Matrix<T2, Dynamic, 1> &beta_matrix, Eigen::Matrix<T3, Dynamic, 1> &coef0_matrix, bool sparse_matrix, int normalize_type, int n, Eigen::VectorXd x_mean, T3 y_mean, Eigen::VectorXd x_norm) { if (normalize_type == 0 || sparse_matrix) { // no need to restore return; } int sequence_size = beta_matrix.rows(); if (normalize_type == 1) { array_quotient(beta, x_norm, 1); beta = beta * sqrt(double(n)); coef0 = y_mean - matrix_dot(beta, x_mean); for (int ind = 0; ind < sequence_size; ind++) { array_quotient(beta_matrix(ind), x_norm, 1); beta_matrix(ind) = beta_matrix(ind) * sqrt(double(n)); coef0_matrix(ind) = y_mean - matrix_dot(beta_matrix(ind), x_mean); } } else if (normalize_type == 2) { array_quotient(beta, x_norm, 1); beta = beta * sqrt(double(n)); coef0 = coef0 - matrix_dot(beta, x_mean); for (int ind = 0; ind < sequence_size; ind++) { array_quotient(beta_matrix(ind), x_norm, 1); beta_matrix(ind) = beta_matrix(ind) * sqrt(double(n)); coef0_matrix(ind) = coef0_matrix(ind) - matrix_dot(beta_matrix(ind), x_mean); } } else { array_quotient(beta, x_norm, 1); beta = beta * sqrt(double(n)); for (int ind = 0; ind < sequence_size; ind++) { array_quotient(beta_matrix(ind), x_norm, 1); beta_matrix(ind) = beta_matrix(ind) * sqrt(double(n)); } } return; } template <class T4> Eigen::VectorXd pi(T4 &X, Eigen::VectorXd &y, Eigen::VectorXd &coef) { int p = coef.size(); int n = X.rows(); Eigen::VectorXd Pi = Eigen::VectorXd::Zero(n); if (X.cols() == p - 1) { Eigen::VectorXd intercept = Eigen::VectorXd::Ones(n) * coef(0); Eigen::VectorXd one = Eigen::VectorXd::Ones(n); Eigen::VectorXd eta = X * (coef.tail(p - 1).eval()) + intercept; for (int i = 0; i < n; i++) { if (eta(i) > 30) { eta(i) = 30; } else if (eta(i) < -30) { eta(i) = -30; } } Eigen::VectorXd expeta = eta.array().exp(); Pi = expeta.array() / (one + expeta).array(); return Pi; } else { Eigen::VectorXd eta = X * coef; Eigen::VectorXd one = Eigen::VectorXd::Ones(n); for (int i = 0; i < n; i++) { if (eta(i) > 30) { eta(i) = 30; } else if (eta(i) < -30) { eta(i) = -30; } } Eigen::VectorXd expeta = eta.array().exp(); Pi = expeta.array() / (one + expeta).array(); return Pi; } } template <class T4> void pi(T4 &X, Eigen::MatrixXd &y, Eigen::MatrixXd &beta, Eigen::VectorXd &coef0, Eigen::MatrixXd &pr) { int n = X.rows(); Eigen::MatrixXd one = Eigen::MatrixXd::Ones(n, 1); Eigen::MatrixXd Xbeta = X * beta + one * coef0.transpose(); pr = Xbeta.array().exp(); Eigen::VectorXd sumpi = pr.rowwise().sum(); for (int i = 0; i < n; i++) { pr.row(i) = pr.row(i) / sumpi(i); } // return pi; }; template <class T4> void pi(T4 &X, Eigen::MatrixXd &y, Eigen::MatrixXd &coef, Eigen::MatrixXd &pr) { int n = X.rows(); // Eigen::MatrixXd one = Eigen::MatrixXd::Ones(n, 1); Eigen::MatrixXd Xbeta = X * coef; pr = Xbeta.array().exp(); Eigen::VectorXd sumpi = pr.rowwise().sum(); for (int i = 0; i < n; i++) { pr.row(i) = pr.row(i) / sumpi(i); } // return pi; }; /** * @brief Add weights information into data. */ void add_weight(Eigen::MatrixXd &x, Eigen::VectorXd &y, Eigen::VectorXd weights); /** * @brief Add weights information into data. */ void add_weight(Eigen::MatrixXd &x, Eigen::MatrixXd &y, Eigen::VectorXd weights); /** * @brief Add weights information into data. */ void add_weight(Eigen::SparseMatrix<double> &x, Eigen::VectorXd &y, Eigen::VectorXd weights); /** * @brief Add weights information into data. */ void add_weight(Eigen::SparseMatrix<double> &x, Eigen::MatrixXd &y, Eigen::VectorXd weights); void add_constant_column(Eigen::MatrixXd &X_full, Eigen::MatrixXd &X, bool add_constant) { if (!add_constant) { X_full = X.eval(); return; } X_full.resize(X.rows(), X.cols() + 1); X_full.rightCols(X.cols()) = X.eval(); X_full.col(0) = Eigen::MatrixXd::Ones(X.rows(), 1); return; } void add_constant_column(Eigen::SparseMatrix<double> &X_full, Eigen::SparseMatrix<double> &X, bool add_constant) { if (!add_constant) { X_full = X.eval(); return; } X_full.resize(X.rows(), X.cols() + 1); X_full.rightCols(X.cols()) = X.eval(); for (int i = 0; i < X.rows(); i++) { X_full.insert(i, 0) = 1.0; } return; } void combine_beta_coef0(Eigen::VectorXd &beta_full, Eigen::VectorXd &beta, double &coef0, bool add_constant) { if (!add_constant) { beta_full = beta.eval(); return; } int p = beta.rows(); beta_full.resize(p + 1); beta_full(0) = coef0; beta_full.tail(p) = beta.eval(); return; } void combine_beta_coef0(Eigen::MatrixXd &beta_full, Eigen::MatrixXd &beta, Eigen::VectorXd &coef0, bool add_constant) { if (!add_constant) { beta_full = beta.eval(); return; } int p = beta.rows(); int M = beta.cols(); beta_full.resize(p + 1, M); beta_full.row(0) = coef0.transpose().eval(); beta_full.bottomRows(p) = beta.eval(); return; } void extract_beta_coef0(Eigen::VectorXd &beta_full, Eigen::VectorXd &beta, double &coef0, bool add_constant) { if (!add_constant) { beta = beta_full.eval(); coef0 = 0; return; } int p = beta_full.rows() - 1; coef0 = beta_full(0); beta = beta_full.tail(p).eval(); return; } void extract_beta_coef0(Eigen::MatrixXd &beta_full, Eigen::MatrixXd &beta, Eigen::VectorXd &coef0, bool add_constant) { if (!add_constant) { beta = beta_full.eval(); coef0 = Eigen::VectorXd::Zero(beta_full.cols()); return; } int p = beta_full.rows() - 1; coef0 = beta_full.row(0).transpose().eval(); beta = beta_full.bottomRows(p).eval(); return; } void trunc(double &value, double *trunc_range) { if (value < trunc_range[0]) value = trunc_range[0]; if (value > trunc_range[1]) value = trunc_range[1]; } void trunc(Eigen::VectorXd &vec, double *trunc_range) { for (int i = 0; i < vec.size(); i++) { trunc(vec(i), trunc_range); } } Eigen::MatrixXd rowwise_add(Eigen::MatrixXd &m, Eigen::VectorXd &v) { return m.rowwise() + v.transpose(); } Eigen::MatrixXd rowwise_add(Eigen::MatrixXd &m, double &v) { Eigen::VectorXd ones = Eigen::VectorXd::Ones(m.cols()); return m.rowwise() + ones.transpose() * v; } #endif // SRC_UTILITIES_H
17,518
32.755299
119
h
abess
abess-master/src/workflow.h
/** * @file workflow.h * @brief The main workflow for abess. * @details It receives all inputs from API, runs the whole abess process * and then return the results as a list. */ #ifndef SRC_WORKFLOW_H #define SRC_WORKFLOW_H // #define R_BUILD #ifdef R_BUILD #include <Rcpp.h> #include <RcppEigen.h> // [[Rcpp::depends(RcppEigen)]] using namespace Rcpp; #else #include <Eigen/Eigen> #include "List.h" #endif #include <iostream> #include <vector> #include "Algorithm.h" #include "Data.h" #include "Metric.h" #include "abessOpenMP.h" #include "path.h" #include "screening.h" #include "utilities.h" typedef Eigen::Triplet<double> triplet; using namespace Eigen; using namespace std; // <Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd> for Univariate Dense // <Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double> > for Univariate Sparse // <Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::MatrixXd> for Multivariable Dense // <Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::SparseMatrix<double> > for Multivariable Sparse /** * @brief The main workflow for abess. * @tparam T1 for y, XTy, XTone * @tparam T2 for beta * @tparam T3 for coef0 * @tparam T4 for X * @param x sample matrix * @param y response matrix * @param n sample size * @param p number of variables * @param normalize_type type of normalize * @param weight weight of each sample * @param algorithm_type type of algorithm * @param path_type type of path: 1 for sequencial search and 2 for golden section search * @param is_warm_start whether enable warm-start * @param eval_type type of information criterion, or test loss in CV * @param Kfold number of folds, used for CV * @param parameters parameters to be selected, including `support_size`, `lambda` * @param screening_size size of screening * @param g_index the first position of each group * @param early_stop whether enable early-stop * @param thread number of threads used for parallel computing * @param sparse_matrix whether sample matrix `x` is sparse matrix * @param cv_fold_id user-specified cross validation division * @param A_init initial active set * @param algorithm_list the algorithm pointer * @return the result of abess, including the best model parameters */ template <class T1, class T2, class T3, class T4> List abessWorkflow(T4 &x, T1 &y, int n, int p, int normalize_type, Eigen::VectorXd weight, int algorithm_type, int path_type, bool is_warm_start, int eval_type, double ic_coef, int Kfold, Parameters parameters, int screening_size, Eigen::VectorXi g_index, bool early_stop, int thread, bool sparse_matrix, Eigen::VectorXi &cv_fold_id, Eigen::VectorXi &A_init, vector<Algorithm<T1, T2, T3, T4> *> algorithm_list) { #ifndef R_BUILD std::srand(123); #endif int algorithm_list_size = algorithm_list.size(); // Size of the candidate set: // usually it is equal to `p`, the number of variable, // but it could be different in e.g. RPCA. int beta_size = algorithm_list[0]->get_beta_size(n, p); // Data packing & normalize: // pack & initial all information of data, // including normalize. Data<T1, T2, T3, T4> data(x, y, normalize_type, weight, g_index, sparse_matrix, beta_size); if (algorithm_list[0]->model_type == 1 || algorithm_list[0]->model_type == 5) { add_weight(data.x, data.y, data.weight); } // Screening: // if there are too many noise variables, // screening can choose the `screening_size` most important variables // and then focus on them later. Eigen::VectorXi screening_A; if (screening_size >= 0) { screening_A = screening<T1, T2, T3, T4>(data, algorithm_list, screening_size, beta_size, parameters.lambda_list(0), A_init); } // Prepare for CV: // if CV is enable, // specify train and test data, // and initialize the fitting argument inside each fold. Metric<T1, T2, T3, T4> *metric = new Metric<T1, T2, T3, T4>(eval_type, ic_coef, Kfold); if (Kfold > 1) { metric->set_cv_train_test_mask(data, data.n, cv_fold_id); metric->set_cv_init_fit_arg(beta_size, data.M); // metric->set_cv_initial_model_param(Kfold, data.p); // metric->set_cv_initial_A(Kfold, data.p); // metric->set_cv_initial_coef0(Kfold, data.p); // if (model_type == 1) // metric->cal_cv_group_XTX(data); } // Fitting and loss: // follow the search path, // fit on each parameter combination, // and calculate ic/loss. vector<Result<T2, T3>> result_list(Kfold); if (path_type == 1) { // sequentical search #pragma omp parallel for for (int i = 0; i < Kfold; i++) { sequential_path_cv<T1, T2, T3, T4>(data, algorithm_list[i], metric, parameters, early_stop, i, A_init, result_list[i]); } } else { // if (algorithm_type == 5 || algorithm_type == 3) // { // double log_lambda_min = log(max(lambda_min, 1e-5)); // double log_lambda_max = log(max(lambda_max, 1e-5)); // result = pgs_path(data, algorithm, metric, s_min, s_max, log_lambda_min, log_lambda_max, powell_path, // nlambda); // } // golden section search gs_path<T1, T2, T3, T4>(data, algorithm_list, metric, parameters, A_init, result_list); } for (int k = 0; k < Kfold; k++) { algorithm_list[k]->clear_setting(); } // Get bestmodel && fit bestmodel: // choose the best model with lowest ic/loss // and if CV, refit on full data. int min_loss_index = 0; int sequence_size = (parameters.sequence).size(); Eigen::Matrix<T2, Dynamic, 1> beta_matrix(sequence_size, 1); Eigen::Matrix<T3, Dynamic, 1> coef0_matrix(sequence_size, 1); Eigen::Matrix<VectorXd, Dynamic, 1> bd_matrix(sequence_size, 1); Eigen::MatrixXd ic_matrix(sequence_size, 1); Eigen::MatrixXd test_loss_sum = Eigen::MatrixXd::Zero(sequence_size, 1); Eigen::MatrixXd train_loss_matrix(sequence_size, 1); Eigen::MatrixXd effective_number_matrix(sequence_size, 1); if (Kfold == 1) { // not CV: choose lowest ic beta_matrix = result_list[0].beta_matrix; coef0_matrix = result_list[0].coef0_matrix; ic_matrix = result_list[0].ic_matrix; train_loss_matrix = result_list[0].train_loss_matrix; effective_number_matrix = result_list[0].effective_number_matrix; ic_matrix.col(0).minCoeff(&min_loss_index); } else { // CV: choose lowest test loss for (int i = 0; i < Kfold; i++) { test_loss_sum += result_list[i].test_loss_matrix; } test_loss_sum /= ((double)Kfold); test_loss_sum.col(0).minCoeff(&min_loss_index); Eigen::VectorXi used_algorithm_index = Eigen::VectorXi::Zero(algorithm_list_size); // refit on full data #pragma omp parallel for for (int ind = 0; ind < sequence_size; ind++) { int support_size = parameters.sequence(ind).support_size; double lambda = parameters.sequence(ind).lambda; int algorithm_index = omp_get_thread_num(); used_algorithm_index(algorithm_index) = 1; T2 beta_init; T3 coef0_init; Eigen::VectorXi A_init; // start from a clear A_init (not from the given one) coef_set_zero(beta_size, data.M, beta_init, coef0_init); Eigen::VectorXd bd_init = Eigen::VectorXd::Zero(data.g_num); // warmstart from CV's result for (int j = 0; j < Kfold; j++) { beta_init = beta_init + result_list[j].beta_matrix(ind) / Kfold; coef0_init = coef0_init + result_list[j].coef0_matrix(ind) / Kfold; bd_init = bd_init + result_list[j].bd_matrix(ind) / Kfold; } // fitting algorithm_list[algorithm_index]->update_sparsity_level(support_size); algorithm_list[algorithm_index]->update_lambda_level(lambda); algorithm_list[algorithm_index]->update_beta_init(beta_init); algorithm_list[algorithm_index]->update_coef0_init(coef0_init); algorithm_list[algorithm_index]->update_bd_init(bd_init); algorithm_list[algorithm_index]->update_A_init(A_init, data.g_num); algorithm_list[algorithm_index]->fit(data.x, data.y, data.weight, data.g_index, data.g_size, data.n, data.p, data.g_num); // update results beta_matrix(ind) = algorithm_list[algorithm_index]->get_beta(); coef0_matrix(ind) = algorithm_list[algorithm_index]->get_coef0(); train_loss_matrix(ind) = algorithm_list[algorithm_index]->get_train_loss(); ic_matrix(ind) = metric->ic(data.n, data.M, data.g_num, algorithm_list[algorithm_index]); effective_number_matrix(ind) = algorithm_list[algorithm_index]->get_effective_number(); } for (int i = 0; i < algorithm_list_size; i++) { if (used_algorithm_index(i) == 1) { algorithm_list[i]->clear_setting(); } } } // Best result double best_support_size = parameters.sequence(min_loss_index).support_size; double best_lambda = parameters.sequence(min_loss_index).lambda; T2 best_beta; T3 best_coef0; double best_train_loss, best_ic, best_test_loss; best_beta = beta_matrix(min_loss_index); best_coef0 = coef0_matrix(min_loss_index); best_train_loss = train_loss_matrix(min_loss_index); best_ic = ic_matrix(min_loss_index); best_test_loss = test_loss_sum(min_loss_index); // Restore for normal: // restore the changes if normalization is used. restore_for_normal<T2, T3>(best_beta, best_coef0, beta_matrix, coef0_matrix, sparse_matrix, data.normalize_type, data.n, data.x_mean, data.y_mean, data.x_norm); // Store in a list for output List out_result; #ifdef R_BUILD out_result = List::create( Named("beta") = best_beta, Named("coef0") = best_coef0, Named("train_loss") = best_train_loss, Named("ic") = best_ic, Named("lambda") = best_lambda, Named("beta_all") = beta_matrix, Named("coef0_all") = coef0_matrix, Named("train_loss_all") = train_loss_matrix, Named("ic_all") = ic_matrix, Named("effective_number_all") = effective_number_matrix, Named("test_loss_all") = test_loss_sum); if (path_type == 2) { out_result.push_back(parameters.support_size_list, "sequence"); } #else out_result.add("beta", best_beta); out_result.add("coef0", best_coef0); out_result.add("train_loss", best_train_loss); out_result.add("test_loss", best_test_loss); out_result.add("ic", best_ic); out_result.add("lambda", best_lambda); // out_result.add("beta_all", beta_matrix); // out_result.add("coef0_all", coef0_matrix); // out_result.add("train_loss_all", train_loss_matrix); // out_result.add("ic_all", ic_matrix); // out_result.add("test_loss_all", test_loss_sum); #endif // Restore for screening // restore the changes if screening is used. if (screening_size >= 0) { T2 beta_screening_A; T2 beta; T3 coef0; beta_size = algorithm_list[0]->get_beta_size(n, p); coef_set_zero(beta_size, data.M, beta, coef0); #ifndef R_BUILD out_result.get_value_by_name("beta", beta_screening_A); slice_restore(beta_screening_A, screening_A, beta); out_result.add("beta", beta); out_result.add("screening_A", screening_A); #else beta_screening_A = out_result["beta"]; slice_restore(beta_screening_A, screening_A, beta); out_result["beta"] = beta; out_result.push_back(screening_A, "screening_A"); #endif } delete metric; // Return the results return out_result; } #endif // SRC_WORKFLOW_H
12,239
39
120
h
null
DA-Transformer-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
null
ParMETIS-main/libparmetis/initbalance.c
/* * Copyright 1997, Regents of the University of Minnesota * * initbalance.c * * This file contains code that computes an initial partitioning * * Started 3/4/96 * George * * $Id: initbalance.c 10592 2011-07-16 21:17:53Z karypis $ */ #include <parmetislib.h> /************************************************************************* * This function is the entry point of the initial balancing algorithm. * This algorithm assembles the graph to all the processors and preceeds * with the balancing step. **************************************************************************/ void Balance_Partition(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nvtxs, nedges, ncon; idx_t mype, npes, srnpes, srmype; idx_t *vtxdist, *xadj, *adjncy, *adjwgt, *vwgt, *vsize; idx_t *part, *lwhere, *home; idx_t lnparts, fpart, fpe, lnpes, ngroups; idx_t *rcounts, *rdispls; idx_t twoparts=2, moptions[METIS_NOPTIONS], edgecut, max_cut; idx_t sr_pe, gd_pe, sr, gd, who_wins; real_t my_cut, my_totalv, my_cost = -1.0, my_balance = -1.0, wsum; real_t rating, max_rating, your_cost = -1.0, your_balance = -1.0; real_t lbsum, min_lbsum, *lbvec, *tpwgts, *tpwgts2, buffer[2]; graph_t *agraph, cgraph; ctrl_t *myctrl; MPI_Status status; MPI_Comm ipcomm, srcomm; struct { double cost; int rank; } lpecost, gpecost; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->InitPartTmr)); WCOREPUSH; vtxdist = graph->vtxdist; agraph = AssembleAdaptiveGraph(ctrl, graph); nvtxs = cgraph.nvtxs = agraph->nvtxs; nedges = cgraph.nedges = agraph->nedges; ncon = cgraph.ncon = agraph->ncon; xadj = cgraph.xadj = icopy(nvtxs+1, agraph->xadj, iwspacemalloc(ctrl, nvtxs+1)); vwgt = cgraph.vwgt = icopy(nvtxs*ncon, agraph->vwgt, iwspacemalloc(ctrl, nvtxs*ncon)); vsize = cgraph.vsize = icopy(nvtxs, agraph->vsize, iwspacemalloc(ctrl, nvtxs)); adjncy = cgraph.adjncy = icopy(nedges, agraph->adjncy, iwspacemalloc(ctrl, nedges)); adjwgt = cgraph.adjwgt = icopy(nedges, agraph->adjwgt, iwspacemalloc(ctrl, nedges)); part = cgraph.where = agraph->where = iwspacemalloc(ctrl, nvtxs); lwhere = iwspacemalloc(ctrl, nvtxs); home = iwspacemalloc(ctrl, nvtxs); lbvec = rwspacemalloc(ctrl, graph->ncon); /****************************************/ /****************************************/ if (ctrl->ps_relation == PARMETIS_PSR_UNCOUPLED) { WCOREPUSH; rcounts = iwspacemalloc(ctrl, ctrl->npes); rdispls = iwspacemalloc(ctrl, ctrl->npes+1); for (i=0; i<ctrl->npes; i++) rdispls[i] = rcounts[i] = vtxdist[i+1]-vtxdist[i]; MAKECSR(i, ctrl->npes, rdispls); gkMPI_Allgatherv((void *)graph->home, graph->nvtxs, IDX_T, (void *)part, rcounts, rdispls, IDX_T, ctrl->comm); for (i=0; i<agraph->nvtxs; i++) home[i] = part[i]; WCOREPOP; /* local frees */ } else { for (i=0; i<ctrl->npes; i++) { for (j=vtxdist[i]; j<vtxdist[i+1]; j++) part[j] = home[j] = i; } } /* Ensure that the initial partitioning is legal */ for (i=0; i<agraph->nvtxs; i++) { if (part[i] >= ctrl->nparts) part[i] = home[i] = part[i] % ctrl->nparts; if (part[i] < 0) part[i] = home[i] = (-1*part[i]) % ctrl->nparts; } /****************************************/ /****************************************/ IFSET(ctrl->dbglvl, DBG_REFINEINFO, ComputeSerialBalance(ctrl, agraph, agraph->where, lbvec)); IFSET(ctrl->dbglvl, DBG_REFINEINFO, rprintf(ctrl, "input cut: %"PRIDX", balance: ", ComputeSerialEdgeCut(agraph))); for (i=0; i<agraph->ncon; i++) IFSET(ctrl->dbglvl, DBG_REFINEINFO, rprintf(ctrl, "%.3"PRREAL" ", lbvec[i])); IFSET(ctrl->dbglvl, DBG_REFINEINFO, rprintf(ctrl, "\n")); /****************************************/ /* Split the processors into two groups */ /****************************************/ sr = (ctrl->mype % 2 == 0) ? 1 : 0; gd = (ctrl->mype % 2 == 1) ? 1 : 0; if (graph->ncon > MAX_NCON_FOR_DIFFUSION || ctrl->npes == 1) { sr = 1; gd = 0; } sr_pe = 0; gd_pe = 1; gkMPI_Comm_split(ctrl->gcomm, sr, 0, &ipcomm); gkMPI_Comm_rank(ipcomm, &mype); gkMPI_Comm_size(ipcomm, &npes); if (sr == 1) { /* Half of the processors do scratch-remap */ ngroups = gk_max(gk_min(RIP_SPLIT_FACTOR, npes), 1); gkMPI_Comm_split(ipcomm, mype % ngroups, 0, &srcomm); gkMPI_Comm_rank(srcomm, &srmype); gkMPI_Comm_size(srcomm, &srnpes); METIS_SetDefaultOptions(moptions); moptions[METIS_OPTION_SEED] = ctrl->sync + (mype % ngroups) + 1; tpwgts = ctrl->tpwgts; tpwgts2 = rwspacemalloc(ctrl, 2*ncon); iset(nvtxs, 0, lwhere); lnparts = ctrl->nparts; fpart = fpe = 0; lnpes = srnpes; while (lnpes > 1 && lnparts > 1) { PASSERT(ctrl, agraph->nvtxs > 1); /* determine the weights of the two partitions as a function of the weight of the target partition weights */ for (j=(lnparts>>1), i=0; i<ncon; i++) { tpwgts2[i] = rsum(j, tpwgts+fpart*ncon+i, ncon); tpwgts2[ncon+i] = rsum(lnparts-j, tpwgts+(fpart+j)*ncon+i, ncon); wsum = 1.0/(tpwgts2[i] + tpwgts2[ncon+i]); tpwgts2[i] *= wsum; tpwgts2[ncon+i] *= wsum; } METIS_PartGraphRecursive(&agraph->nvtxs, &ncon, agraph->xadj, agraph->adjncy, agraph->vwgt, NULL, agraph->adjwgt, &twoparts, tpwgts2, NULL, moptions, &edgecut, part); /* pick one of the branches */ if (srmype < fpe+lnpes/2) { KeepPart(ctrl, agraph, part, 0); lnpes = lnpes/2; lnparts = lnparts/2; } else { KeepPart(ctrl, agraph, part, 1); fpart = fpart + lnparts/2; fpe = fpe + lnpes/2; lnpes = lnpes - lnpes/2; lnparts = lnparts - lnparts/2; } } if (lnparts == 1) { /* Case in which srnpes is greater or equal to nparts */ /* Only the first process will assign labels (for the reduction to work) */ if (srmype == fpe) { for (i=0; i<agraph->nvtxs; i++) lwhere[agraph->label[i]] = fpart; } } else { /* Case in which srnpes is smaller than nparts */ /* create the normalized tpwgts for the lnparts from ctrl->tpwgts */ tpwgts = rwspacemalloc(ctrl, lnparts*ncon); for (j=0; j<ncon; j++) { for (wsum=0.0, i=0; i<lnparts; i++) { tpwgts[i*ncon+j] = ctrl->tpwgts[(fpart+i)*ncon+j]; wsum += tpwgts[i*ncon+j]; } for (wsum=1.0/wsum, i=0; i<lnparts; i++) tpwgts[i*ncon+j] *= wsum; } METIS_PartGraphKway(&agraph->nvtxs, &ncon, agraph->xadj, agraph->adjncy, agraph->vwgt, NULL, agraph->adjwgt, &lnparts, tpwgts, NULL, moptions, &edgecut, part); for (i=0; i<agraph->nvtxs; i++) lwhere[agraph->label[i]] = fpart + part[i]; } gkMPI_Allreduce((void *)lwhere, (void *)part, nvtxs, IDX_T, MPI_SUM, srcomm); edgecut = ComputeSerialEdgeCut(&cgraph); ComputeSerialBalance(ctrl, &cgraph, part, lbvec); lbsum = rsum(ncon, lbvec, 1); gkMPI_Allreduce((void *)&edgecut, (void *)&max_cut, 1, IDX_T, MPI_MAX, ipcomm); gkMPI_Allreduce((void *)&lbsum, (void *)&min_lbsum, 1, REAL_T, MPI_MIN, ipcomm); lpecost.rank = ctrl->mype; lpecost.cost = lbsum; if (min_lbsum < UNBALANCE_FRACTION * (real_t)(ncon)) { if (lbsum < UNBALANCE_FRACTION * (real_t)(ncon)) lpecost.cost = (double)edgecut; else lpecost.cost = (double)max_cut + lbsum; } gkMPI_Allreduce((void *)&lpecost, (void *)&gpecost, 1, MPI_DOUBLE_INT, MPI_MINLOC, ipcomm); if (ctrl->mype == gpecost.rank && ctrl->mype != sr_pe) gkMPI_Send((void *)part, nvtxs, IDX_T, sr_pe, 1, ctrl->comm); if (ctrl->mype != gpecost.rank && ctrl->mype == sr_pe) gkMPI_Recv((void *)part, nvtxs, IDX_T, gpecost.rank, 1, ctrl->comm, &status); if (ctrl->mype == sr_pe) { icopy(nvtxs, part, lwhere); SerialRemap(ctrl, &cgraph, ctrl->nparts, home, lwhere, part, ctrl->tpwgts); } gkMPI_Comm_free(&srcomm); } else { /* The other half do global diffusion */ /* setup a ctrl for the diffusion */ myctrl = (ctrl_t *)gk_malloc(sizeof(ctrl_t), "myctrl"); memset(myctrl, 0, sizeof(ctrl_t)); myctrl->mype = mype; myctrl->npes = npes; myctrl->comm = ipcomm; myctrl->sync = ctrl->sync; myctrl->seed = ctrl->seed; myctrl->nparts = ctrl->nparts; myctrl->ncon = ctrl->ncon; myctrl->ipc_factor = ctrl->ipc_factor; myctrl->redist_factor = ctrl->redist_base; myctrl->partType = ADAPTIVE_PARTITION; myctrl->ps_relation = PARMETIS_PSR_UNCOUPLED; myctrl->tpwgts = rmalloc(myctrl->nparts*myctrl->ncon, "myctrl->tpwgts"); myctrl->ubvec = rmalloc(myctrl->ncon, "myctrl->ubvec"); myctrl->invtvwgts = rmalloc(myctrl->ncon, "myctrl->invtvwgts"); rcopy(myctrl->nparts*myctrl->ncon, ctrl->tpwgts, myctrl->tpwgts); rcopy(myctrl->ncon, ctrl->ubvec, myctrl->ubvec); rcopy(myctrl->ncon, ctrl->invtvwgts, myctrl->invtvwgts); AllocateWSpace(myctrl, 10*agraph->nvtxs); AllocateRefinementWorkSpace(myctrl, agraph->nvtxs); /* This stmt is required to balance out the sr gkMPI_Comm_split */ gkMPI_Comm_split(ipcomm, MPI_UNDEFINED, 0, &srcomm); if (ncon == 1) { rating = WavefrontDiffusion(myctrl, agraph, home); ComputeSerialBalance(ctrl, &cgraph, part, lbvec); lbsum = rsum(ncon, lbvec, 1); /* Determine which PE computed the best partitioning */ gkMPI_Allreduce((void *)&rating, (void *)&max_rating, 1, REAL_T, MPI_MAX, ipcomm); gkMPI_Allreduce((void *)&lbsum, (void *)&min_lbsum, 1, REAL_T, MPI_MIN, ipcomm); lpecost.rank = ctrl->mype; lpecost.cost = lbsum; if (min_lbsum < UNBALANCE_FRACTION * (real_t)(ncon)) { if (lbsum < UNBALANCE_FRACTION * (real_t)(ncon)) lpecost.cost = rating; else lpecost.cost = max_rating + lbsum; } gkMPI_Allreduce((void *)&lpecost, (void *)&gpecost, 1, MPI_DOUBLE_INT, MPI_MINLOC, ipcomm); /* Now send this to the coordinating processor */ if (ctrl->mype == gpecost.rank && ctrl->mype != gd_pe) gkMPI_Send((void *)part, nvtxs, IDX_T, gd_pe, 1, ctrl->comm); if (ctrl->mype != gpecost.rank && ctrl->mype == gd_pe) gkMPI_Recv((void *)part, nvtxs, IDX_T, gpecost.rank, 1, ctrl->comm, &status); if (ctrl->mype == gd_pe) { icopy(nvtxs, part, lwhere); SerialRemap(ctrl, &cgraph, ctrl->nparts, home, lwhere, part, ctrl->tpwgts); } } else { Mc_Diffusion(myctrl, agraph, graph->vtxdist, agraph->where, home, N_MOC_GD_PASSES); } FreeCtrl(&myctrl); } if (graph->ncon <= MAX_NCON_FOR_DIFFUSION) { if (ctrl->mype == sr_pe || ctrl->mype == gd_pe) { /********************************************************************/ /* The coordinators from each group decide on the best partitioning */ /********************************************************************/ my_cut = (real_t) ComputeSerialEdgeCut(&cgraph); my_totalv = (real_t) Mc_ComputeSerialTotalV(&cgraph, home); ComputeSerialBalance(ctrl, &cgraph, part, lbvec); my_balance = rsum(cgraph.ncon, lbvec, 1); my_balance /= (real_t) cgraph.ncon; my_cost = ctrl->ipc_factor * my_cut + REDIST_WGT * ctrl->redist_base * my_totalv; IFSET(ctrl->dbglvl, DBG_REFINEINFO, printf("%s initial cut: %.1"PRREAL", totalv: %.1"PRREAL", balance: %.3"PRREAL"\n", (ctrl->mype == sr_pe ? "scratch-remap" : "diffusion"), my_cut, my_totalv, my_balance)); if (ctrl->mype == gd_pe) { buffer[0] = my_cost; buffer[1] = my_balance; gkMPI_Send((void *)buffer, 2, REAL_T, sr_pe, 1, ctrl->comm); } else { gkMPI_Recv((void *)buffer, 2, REAL_T, gd_pe, 1, ctrl->comm, &status); your_cost = buffer[0]; your_balance = buffer[1]; } } if (ctrl->mype == sr_pe) { who_wins = gd_pe; if ((my_balance < 1.1 && your_balance > 1.1) || (my_balance < 1.1 && your_balance < 1.1 && my_cost < your_cost) || (my_balance > 1.1 && your_balance > 1.1 && my_balance < your_balance)) { who_wins = sr_pe; } } gkMPI_Bcast((void *)&who_wins, 1, IDX_T, sr_pe, ctrl->comm); } else { who_wins = sr_pe; } gkMPI_Bcast((void *)part, nvtxs, IDX_T, who_wins, ctrl->comm); icopy(graph->nvtxs, part+vtxdist[ctrl->mype], graph->where); gkMPI_Comm_free(&ipcomm); agraph->where = NULL; FreeGraph(agraph); WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->InitPartTmr)); } /*************************************************************************/ /*! This function assembles the graph into a single processor. It should work for static, adaptive, single-, and multi-contraint */ /*************************************************************************/ graph_t *AssembleAdaptiveGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, k, l, gnvtxs, nvtxs, ncon, gnedges, nedges, gsize; idx_t *xadj, *vwgt, *vsize, *adjncy, *adjwgt, *vtxdist, *imap; idx_t *axadj, *aadjncy, *aadjwgt, *avwgt, *avsize = NULL, *alabel; idx_t *mygraph, *ggraph; idx_t *rcounts, *rdispls, mysize; real_t *anvwgt; graph_t *agraph; WCOREPUSH; gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; ncon = graph->ncon; nedges = graph->xadj[nvtxs]; xadj = graph->xadj; vwgt = graph->vwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vtxdist = graph->vtxdist; imap = graph->imap; /*************************************************************/ /* Determine the # of idx_t to receive from each processor */ /*************************************************************/ rcounts = iwspacemalloc(ctrl, ctrl->npes); switch (ctrl->partType) { case STATIC_PARTITION: mysize = (1+ncon)*nvtxs + 2*nedges; break; case ADAPTIVE_PARTITION: case REFINE_PARTITION: mysize = (2+ncon)*nvtxs + 2*nedges; break; default: printf("WARNING: bad value for ctrl->partType %"PRIDX"\n", ctrl->partType); break; } gkMPI_Allgather((void *)(&mysize), 1, IDX_T, (void *)rcounts, 1, IDX_T, ctrl->comm); rdispls = iwspacemalloc(ctrl, ctrl->npes+1); for (rdispls[0]=0, i=1; i<ctrl->npes+1; i++) rdispls[i] = rdispls[i-1] + rcounts[i-1]; /* allocate memory for the recv buffer of the assembled graph */ gsize = rdispls[ctrl->npes]; ggraph = iwspacemalloc(ctrl, gsize); /* Construct the one-array storage format of the assembled graph */ WCOREPUSH; /* for freeing mygraph */ mygraph = iwspacemalloc(ctrl, mysize); for (k=i=0; i<nvtxs; i++) { mygraph[k++] = xadj[i+1]-xadj[i]; for (j=0; j<ncon; j++) mygraph[k++] = vwgt[i*ncon+j]; if (ctrl->partType == ADAPTIVE_PARTITION || ctrl->partType == REFINE_PARTITION) mygraph[k++] = vsize[i]; for (j=xadj[i]; j<xadj[i+1]; j++) { mygraph[k++] = imap[adjncy[j]]; mygraph[k++] = adjwgt[j]; } } PASSERT(ctrl, mysize == k); /**************************************/ /* Assemble and send the entire graph */ /**************************************/ gkMPI_Allgatherv((void *)mygraph, mysize, IDX_T, (void *)ggraph, rcounts, rdispls, IDX_T, ctrl->comm); WCOREPOP; /* free mygraph */ agraph = CreateGraph(); agraph->nvtxs = gnvtxs; agraph->ncon = ncon; switch (ctrl->partType) { case STATIC_PARTITION: agraph->nedges = gnedges = (gsize-(1+ncon)*gnvtxs)/2; break; case ADAPTIVE_PARTITION: case REFINE_PARTITION: agraph->nedges = gnedges = (gsize-(2+ncon)*gnvtxs)/2; break; default: printf("WARNING: bad value for ctrl->partType %"PRIDX"\n", ctrl->partType); agraph->nedges = gnedges = -1; break; } /*******************************************/ /* Allocate memory for the assembled graph */ /*******************************************/ axadj = agraph->xadj = imalloc(gnvtxs+1, "AssembleGraph: axadj"); avwgt = agraph->vwgt = imalloc(gnvtxs*ncon, "AssembleGraph: avwgt"); anvwgt = agraph->nvwgt = rmalloc(gnvtxs*ncon, "AssembleGraph: anvwgt"); aadjncy = agraph->adjncy = imalloc(gnedges, "AssembleGraph: adjncy"); aadjwgt = agraph->adjwgt = imalloc(gnedges, "AssembleGraph: adjwgt"); alabel = agraph->label = imalloc(gnvtxs, "AssembleGraph: alabel"); if (ctrl->partType == ADAPTIVE_PARTITION || ctrl->partType == REFINE_PARTITION) avsize = agraph->vsize = imalloc(gnvtxs, "AssembleGraph: avsize"); for (k=j=i=0; i<gnvtxs; i++) { axadj[i] = ggraph[k++]; for (l=0; l<ncon; l++) avwgt[i*ncon+l] = ggraph[k++]; if (ctrl->partType == ADAPTIVE_PARTITION || ctrl->partType == REFINE_PARTITION) avsize[i] = ggraph[k++]; for (l=0; l<axadj[i]; l++) { aadjncy[j] = ggraph[k++]; aadjwgt[j] = ggraph[k++]; j++; } } /*********************************/ /* Now fix up the received graph */ /*********************************/ MAKECSR(i, gnvtxs, axadj); for (i=0; i<gnvtxs; i++) { for (j=0; j<ncon; j++) anvwgt[i*ncon+j] = ctrl->invtvwgts[j]*agraph->vwgt[i*ncon+j]; } iincset(gnvtxs, 0, alabel); WCOREPOP; return agraph; }
17,514
33.890438
93
c
null
ParMETIS-main/libparmetis/ctrl.c
/*! * Copyright 1997, Regents of the University of Minnesota * * \file * \brief Functions dealing with manipulating the ctrl_t structure * * * \date Started 10/19/1996 * \author George Karypis * \version\verbatim $Id: ctrl.c 10592 2011-07-16 21:17:53Z karypis $ \endverbatime */ #include <parmetislib.h> /*************************************************************************/ /*! This function sets the ctrl_t structure */ /*************************************************************************/ ctrl_t *SetupCtrl(pmoptype_et optype, idx_t *options, idx_t ncon, idx_t nparts, real_t *tpwgts, real_t *ubvec, MPI_Comm comm) { idx_t i, j, defopts; ctrl_t *ctrl; ctrl = (ctrl_t *)gk_malloc(sizeof(ctrl_t), "SetupCtrl: ctrl"); memset((void *)ctrl, 0, sizeof(ctrl_t)); /* communicator-related info */ MPI_Comm_dup(comm, &(ctrl->gcomm)); ctrl->comm = ctrl->gcomm; ctrl->free_comm = 1; gkMPI_Comm_rank(ctrl->gcomm, &ctrl->mype); gkMPI_Comm_size(ctrl->gcomm, &ctrl->npes); /* options[]-related info */ defopts = (options == NULL ? 1 : options[0] == 0); switch (optype) { case PARMETIS_OP_KMETIS: case PARMETIS_OP_GKMETIS: ctrl->partType = STATIC_PARTITION; ctrl->ps_relation = -1; break; case PARMETIS_OP_GMETIS: break; case PARMETIS_OP_RMETIS: ctrl->partType = REFINE_PARTITION; ctrl->ipc_factor = 1000.0; ctrl->ps_relation = (defopts ? (ctrl->npes == nparts ? PARMETIS_PSR_COUPLED : PARMETIS_PSR_UNCOUPLED) : (ctrl->npes == nparts ? options[PMV3_OPTION_PSR] : PARMETIS_PSR_UNCOUPLED)); break; case PARMETIS_OP_AMETIS: ctrl->partType = ADAPTIVE_PARTITION; ctrl->ps_relation = (defopts ? (ctrl->npes == nparts ? PARMETIS_PSR_COUPLED : PARMETIS_PSR_UNCOUPLED) : (ctrl->npes == nparts ? options[PMV3_OPTION_PSR] : PARMETIS_PSR_UNCOUPLED)); break; case PARMETIS_OP_OMETIS: /* This is handled directly by the code as its parameter passing does not conform to the options[] style. This will probably be changed once the changed have been debugged. */ break; case PARMETIS_OP_M2DUAL: break; case PARMETIS_OP_MKMETIS: break; } ctrl->dbglvl = (defopts ? GLOBAL_DBGLVL : options[PMV3_OPTION_DBGLVL]); ctrl->seed = (defopts ? GLOBAL_SEED : options[PMV3_OPTION_SEED]); ctrl->sync = GlobalSEMax(ctrl, ctrl->seed); ctrl->seed = (ctrl->seed == 0 ? ctrl->mype : ctrl->seed*ctrl->mype); /* options passed via dbglvl */ ctrl->dropedges = ctrl->dbglvl&PARMETIS_DBGLVL_DROPEDGES; ctrl->twohop = ctrl->dbglvl&PARMETIS_DBGLVL_TWOHOP; ctrl->fast = ctrl->dbglvl&PARMETIS_DBGLVL_FAST; ctrl->ondisk = ctrl->dbglvl&PARMETIS_DBGLVL_ONDISK; ctrl->pid = getpid(); /* common info */ ctrl->optype = optype; ctrl->ncon = ncon; ctrl->nparts = nparts; ctrl->redist_factor = 1.0; ctrl->redist_base = 1.0; /* setup tpwgts */ ctrl->tpwgts = rmalloc(nparts*ncon, "SetupCtrl: tpwgts"); if (tpwgts) { rcopy(nparts*ncon, tpwgts, ctrl->tpwgts); } else { for (i=0; i<nparts; i++) { for (j=0; j<ncon; j++) ctrl->tpwgts[i*ncon+j] = 1.0/nparts; } } /* setup ubvec */ ctrl->ubvec = rsmalloc(ncon, UNBALANCE_FRACTION, "SetupCtrl: ubvec"); if (ubvec) rcopy(ncon, ubvec, ctrl->ubvec); /* initialize the various timers */ InitTimers(ctrl); /* initialize the random number generator */ srand(ctrl->seed); return ctrl; } /*************************************************************************/ /*! This function computes the invtvwgts of a graph and stores them in ctrl */ /*************************************************************************/ void SetupCtrl_invtvwgts(ctrl_t *ctrl, graph_t *graph) { idx_t j, ncon; ncon = graph->ncon; ctrl->invtvwgts = rmalloc(ncon, "SetupCtrl_tvwgts: invtvwgts"); for (j=0; j<ncon; j++) ctrl->invtvwgts[j] = 1.0/GlobalSESum(ctrl, isum(graph->nvtxs, graph->vwgt+j, ncon)); } /*************************************************************************/ /*! This function de-allocates memory allocated for the control structures */ /*************************************************************************/ void FreeCtrl(ctrl_t **r_ctrl) { ctrl_t *ctrl = *r_ctrl; FreeWSpace(ctrl); if (ctrl->free_comm) gkMPI_Comm_free(&(ctrl->gcomm)); gk_free((void **)&ctrl->invtvwgts, &ctrl->ubvec, &ctrl->tpwgts, &ctrl->sreq, &ctrl->rreq, &ctrl->statuses, &ctrl, LTERM); *r_ctrl = NULL; }
4,919
28.638554
88
c
null
ParMETIS-main/libparmetis/defs.h
/* * Copyright 1997, Regents of the University of Minnesota * * defs.h * * This file contains constant definitions * * Started 8/27/94 * George * * $Id: defs.h 10543 2011-07-11 19:32:24Z karypis $ * */ #define GLOBAL_DBGLVL 0 #define GLOBAL_SEED 15 #define NUM_INIT_MSECTIONS 5 #define MC_FLOW_BALANCE_THRESHOLD 0.2 #define MOC_GD_GRANULARITY_FACTOR 1.0 #define RIP_SPLIT_FACTOR 8 #define MAX_NPARTS_MULTIPLIER 20 #define STATIC_PARTITION 1 #define ORDER_PARTITION 2 #define ADAPTIVE_PARTITION 3 #define REFINE_PARTITION 4 #define REDIST_WGT 2.0 #define MAXNVWGT_FACTOR 2.0 #define N_MOC_REDO_PASSES 10 #define N_MOC_GR_PASSES 8 #define NREMAP_PASSES 8 #define N_MOC_GD_PASSES 6 #define N_MOC_BAL_PASSES 4 #define NMATCH_PASSES 4 #define MAX_NCON_FOR_DIFFUSION 2 #define SMALLGRAPH 10000 #define LTERM (void **) 0 /* List terminator for GKfree() */ #define NGD_PASSES 20 #define PMV3_OPTION_DBGLVL 1 #define PMV3_OPTION_SEED 2 #define PMV3_OPTION_IPART 3 #define PMV3_OPTION_PSR 3 #define XYZ_XCOORD 1 #define XYZ_SPFILL 2 /* Type of initial vertex separator algorithms */ #define ISEP_EDGE 1 #define ISEP_NODE 2 #define UNMATCHED -1 #define MAYBE_MATCHED -2 #define TOO_HEAVY -3 #define HTABLE_EMPTY -1 #define NGR_PASSES 4 /* Number of greedy refinement passes */ #define NIPARTS 8 /* Number of random initial partitions */ #define NLGR_PASSES 5 /* Number of GR refinement during IPartition */ #define SMALLFLOAT 0.000001 #define COARSEN_FRACTION 0.75 /* Node reduction between succesive coarsening levels */ #define COARSEN_FRACTION2 0.55 /* Node reduction between succesive coarsening levels */ #define UNBALANCE_FRACTION 1.05 #define ORDER_UNBALANCE_FRACTION 1.10 #define MAXVWGT_FACTOR 1.4 /* Debug Levels */ #define DBG_TIME PARMETIS_DBGLVL_TIME #define DBG_INFO PARMETIS_DBGLVL_INFO #define DBG_PROGRESS PARMETIS_DBGLVL_PROGRESS #define DBG_REFINEINFO PARMETIS_DBGLVL_REFINEINFO #define DBG_MATCHINFO PARMETIS_DBGLVL_MATCHINFO #define DBG_RMOVEINFO PARMETIS_DBGLVL_RMOVEINFO #define DBG_REMAP PARMETIS_DBGLVL_REMAP
2,253
24.044444
87
h
null
ParMETIS-main/libparmetis/ometis.c
/*! * Copyright 1997, Regents of the University of Minnesota * * \file * \brief This is the entry point of parallel ordering routines * * \date Started 8/1/2008 * \author George Karypis * \version\verbatim $Id: ometis.c 10666 2011-08-04 05:22:36Z karypis $ \endverbatime * */ #include <parmetislib.h> /***********************************************************************************/ /*! This function is the entry point of the parallel ordering algorithm. It simply translates the arguments to the tunable version. */ /***********************************************************************************/ int ParMETIS_V3_NodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm) { idx_t status; idx_t seed = (options != NULL && options[0] != 0 ? options[PMV3_OPTION_SEED] : -1); idx_t dbglvl = (options != NULL && options[0] != 0 ? options[PMV3_OPTION_DBGLVL] : -1); /* Check the input parameters and return if an error */ status = CheckInputsNodeND(vtxdist, xadj, adjncy, numflag, options, order, sizes, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; ParMETIS_V32_NodeND(vtxdist, xadj, adjncy, /*vwgt=*/NULL, numflag, /*mtype=*/NULL, /*rtype=*/NULL, /*p_nseps=*/NULL, /*s_nseps=*/NULL, /*ubfrac=*/NULL, /*seed=*/(options==NULL || options[0] == 0 ? NULL : &seed), /*dbglvl=*/(options==NULL || options[0] == 0 ? NULL : &dbglvl), order, sizes, comm); return METIS_OK; } /***********************************************************************************/ /*! This function is the entry point of the tunable parallel ordering algorithm. This is the main ordering algorithm and implements a multilevel nested dissection ordering approach. */ /***********************************************************************************/ int ParMETIS_V32_NodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *numflag, idx_t *mtype, idx_t *rtype, idx_t *p_nseps, idx_t *s_nseps, real_t *ubfrac, idx_t *seed, idx_t *idbglvl, idx_t *order, idx_t *sizes, MPI_Comm *comm) { idx_t i, npes, mype, dbglvl, status, wgtflag=0; ctrl_t *ctrl; graph_t *graph, *mgraph; idx_t *morder; size_t curmem; gkMPI_Comm_size(*comm, &npes); gkMPI_Comm_rank(*comm, &mype); /* Deal with poor vertex distributions */ if (GlobalSEMinComm(*comm, vtxdist[mype+1]-vtxdist[mype]) < 1) { printf("Error: Poor vertex distribution (processor with no vertices).\n"); return METIS_ERROR; } status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, 5*npes, NULL, NULL, *comm); dbglvl = (idbglvl == NULL ? 0 : *idbglvl); ctrl->dbglvl = dbglvl; STARTTIMER(ctrl, ctrl->TotalTmr); ctrl->dbglvl = 0; /*=======================================================================*/ /*! Compute the initial k-way partitioning */ /*=======================================================================*/ /* Setup the graph */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 1); graph = SetupGraph(ctrl, 1, vtxdist, xadj, NULL, NULL, adjncy, NULL, 0); /* Allocate workspace */ AllocateWSpace(ctrl, 10*graph->nvtxs); /* Compute the partitioning */ ctrl->CoarsenTo = gk_min(vtxdist[npes]+1, 200*gk_max(npes, ctrl->nparts)); if (seed != NULL) ctrl->seed = (*seed == 0 ? mype : (*seed)*mype); Global_Partition(ctrl, graph); /* Collapse the number of partitions to be from 0..npes-1 */ for (i=0; i<graph->nvtxs; i++) graph->where[i] = graph->where[i]%npes; ctrl->nparts = npes; /* Put back the real vertex weights */ if (vwgt) { gk_free((void **)&graph->vwgt, LTERM); graph->vwgt = vwgt; graph->free_vwgt = 0; wgtflag = 2; } /*=======================================================================*/ /*! Move the graph according to the partitioning */ /*=======================================================================*/ STARTTIMER(ctrl, ctrl->MoveTmr); mgraph = MoveGraph(ctrl, graph); /* compute nvwgts for the moved graph */ SetupGraph_nvwgts(ctrl, mgraph); STOPTIMER(ctrl, ctrl->MoveTmr); /*=======================================================================*/ /*! Now compute an ordering of the moved graph */ /*=======================================================================*/ ctrl->optype = PARMETIS_OP_OMETIS; ctrl->partType = ORDER_PARTITION; ctrl->mtype = (mtype == NULL ? PARMETIS_MTYPE_GLOBAL : *mtype); ctrl->rtype = (rtype == NULL ? PARMETIS_SRTYPE_2PHASE : *rtype); ctrl->p_nseps = (p_nseps == NULL ? 1 : *p_nseps); ctrl->s_nseps = (s_nseps == NULL ? 1 : *s_nseps); ctrl->ubfrac = (ubfrac == NULL ? ORDER_UNBALANCE_FRACTION : *ubfrac); ctrl->dbglvl = dbglvl; ctrl->ipart = ISEP_NODE; ctrl->CoarsenTo = gk_min(graph->gnvtxs-1, gk_max(1500*npes, graph->gnvtxs/(5*NUM_INIT_MSECTIONS*npes))); morder = imalloc(mgraph->nvtxs, "ParMETIS_NodeND: morder"); MultilevelOrder(ctrl, mgraph, morder, sizes); /* Invert the ordering back to the original graph */ ProjectInfoBack(ctrl, graph, order, morder); STOPTIMER(ctrl, ctrl->TotalTmr); IFSET(dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); gk_free((void **)&morder, LTERM); FreeGraph(mgraph); FreeInitialGraphAndRemap(graph); /* If required, restore the graph numbering */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 0); goto DONE; /* Remove the warning for now */ DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; } /*********************************************************************************/ /*! This is the top level ordering routine. \param order is the computed ordering. \param sizes is the 2*nparts array that will store the sizes of each subdomains and the sizes of the separators at each level. Note that the top-level separator is stores at \c sizes[2*nparts-2]. */ /*********************************************************************************/ void MultilevelOrder(ctrl_t *ctrl, graph_t *graph, idx_t *order, idx_t *sizes) { idx_t i, nparts, nvtxs, npes; idx_t *perm, *lastnode, *morder, *porder; graph_t *mgraph; nvtxs = graph->nvtxs; npes = 1<<log2Int(ctrl->npes); /* # of nested dissection levels = floor(log_2(npes)) */ perm = imalloc(nvtxs, "MultilevelOrder: perm"); lastnode = ismalloc(4*npes, -1, "MultilevelOrder: lastnode"); for (i=0; i<nvtxs; i++) perm[i] = i; lastnode[2] = graph->gnvtxs; iset(nvtxs, -1, order); /* This is used as a pointer to the end of the sizes[] array (i.e., >=nparts) that has not yet been filled in so that the separator sizes of the succesive levels will be stored correctly. It is used in LabelSeparatos() */ sizes[0] = 2*npes-1; graph->where = ismalloc(nvtxs, 0, "MultilevelOrder: graph->where"); for (nparts=2; nparts<=npes; nparts*=2) { ctrl->nparts = nparts; Order_Partition_Multiple(ctrl, graph); LabelSeparators(ctrl, graph, lastnode, perm, order, sizes); CompactGraph(ctrl, graph, perm); if (ctrl->CoarsenTo < 100*nparts) { ctrl->CoarsenTo = 1.5*ctrl->CoarsenTo; } ctrl->CoarsenTo = gk_min(ctrl->CoarsenTo, graph->gnvtxs-1); } /*----------------------------------------------------------------- / Move the graph so that each processor gets its partition -----------------------------------------------------------------*/ IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->MoveTmr)); CommSetup(ctrl, graph); graph->ncon = 1; /* needed for MoveGraph */ mgraph = MoveGraph(ctrl, graph); /* Fill in the sizes[] array for the local part. Just the vtxdist of the mgraph */ for (i=0; i<npes; i++) sizes[i] = mgraph->vtxdist[i+1]-mgraph->vtxdist[i]; porder = imalloc(graph->nvtxs, "MultilevelOrder: porder"); morder = imalloc(mgraph->nvtxs, "MultilevelOrder: morder"); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->MoveTmr)); /* Find the local ordering */ if (ctrl->mype < npes) LocalNDOrder(ctrl, mgraph, morder, lastnode[2*(npes+ctrl->mype)]-mgraph->nvtxs); /* Project the ordering back to the before-move graph */ ProjectInfoBack(ctrl, graph, porder, morder); /* Copy the ordering from porder to order using perm */ for (i=0; i<graph->nvtxs; i++) { PASSERT(ctrl, order[perm[i]] == -1); order[perm[i]] = porder[i]; } FreeGraph(mgraph); gk_free((void **)&perm, (void **)&lastnode, (void **)&porder, (void **)&morder, LTERM); /* PrintVector(ctrl, 2*npes-1, 0, sizes, "SIZES"); */ } /**************************************************************************/ /*! This is the top-level driver of the multiple multisection ordering code. */ /***************************************************************************/ void Order_Partition_Multiple(ctrl_t *ctrl, graph_t *graph) { idx_t i, sid, iter, nvtxs, nparts, nlevels; idx_t *xadj, *adjncy, *where, *gpwgts, *imap; idx_t *bestseps, *bestwhere, *origwhere; CommSetup(ctrl, graph); nparts = ctrl->nparts; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; bestseps = ismalloc(2*nparts, -1, "Order_Partition_Multiple: bestseps"); bestwhere = imalloc(nvtxs+graph->nrecv, "Order_Partition_Multiple: bestwhere"); origwhere = graph->where; for (nlevels=-1, iter=0; iter<ctrl->p_nseps; iter++) { graph->where = imalloc(nvtxs, "Order_Partition_Multiple: where"); icopy(nvtxs, origwhere, graph->where); Order_Partition(ctrl, graph, &nlevels, 0); where = graph->where; gpwgts = graph->gpwgts; /* Update the where[] vectors of the subdomains that improved */ for (i=0; i<nvtxs; i++) { sid = (where[i] < nparts ? nparts + where[i] - (where[i]%2) : where[i]); if (iter == 0 || bestseps[sid] > gpwgts[sid]) bestwhere[i] = where[i]; } /* Update the size of the separators for those improved subdomains */ for (i=0; i<nparts; i+=2) { sid = nparts+i; if (iter == 0 || bestseps[sid] > gpwgts[sid]) bestseps[sid] = gpwgts[sid]; } /* free all the memory allocated for coarsening/refinement, but keep the setup fields so that they will not be re-computed */ FreeNonGraphNonSetupFields(graph); } graph->where = bestwhere; AllocateNodePartitionParams(ctrl, graph); ComputeNodePartitionParams(ctrl, graph); for (i=0; i<nparts; i+=2) PASSERT(ctrl, bestseps[nparts+i] == graph->gpwgts[nparts+i]); gk_free((void **)&bestseps, &origwhere, LTERM); /* PrintVector(ctrl, 2*nparts-1, 0, bestseps, "bestseps"); */ } /**************************************************************************/ /*! The driver of the multilvelel separator finding algorithm */ /**************************************************************************/ void Order_Partition(ctrl_t *ctrl, graph_t *graph, idx_t *nlevels, idx_t clevel) { CommSetup(ctrl, graph); graph->ncon = 1; IFSET(ctrl->dbglvl, DBG_PROGRESS, rprintf(ctrl, "[%6"PRIDX" %8"PRIDX" %5"PRIDX" %5"PRIDX"][%"PRIDX"][%"PRIDX"]\n", graph->gnvtxs, GlobalSESum(ctrl, graph->nedges), GlobalSEMin(ctrl, graph->nvtxs), GlobalSEMax(ctrl, graph->nvtxs), ctrl->CoarsenTo, GlobalSEMax(ctrl, imax(graph->nvtxs, graph->vwgt, 1)))); if ((*nlevels != -1 && *nlevels == clevel) || (*nlevels == -1 && ((graph->gnvtxs < 1.66*ctrl->CoarsenTo) || (graph->finer != NULL && graph->gnvtxs > graph->finer->gnvtxs*COARSEN_FRACTION)))) { /* set the nlevels to where coarsening stopped */ *nlevels = clevel; /* Compute the initial npart-way multisection */ InitMultisection(ctrl, graph); if (graph->finer == NULL) { /* Do that only if no-coarsening took place */ AllocateNodePartitionParams(ctrl, graph); ComputeNodePartitionParams(ctrl, graph); switch (ctrl->rtype) { case PARMETIS_SRTYPE_GREEDY: KWayNodeRefine_Greedy(ctrl, graph, NGR_PASSES, ctrl->ubfrac); break; case PARMETIS_SRTYPE_2PHASE: KWayNodeRefine2Phase(ctrl, graph, NGR_PASSES, ctrl->ubfrac); break; default: errexit("Unknown rtype of %"PRIDX"\n", ctrl->rtype); } } } else { /* Coarsen it and then partition it */ switch (ctrl->mtype) { case PARMETIS_MTYPE_LOCAL: Match_Local(ctrl, graph); break; case PARMETIS_MTYPE_GLOBAL: Match_Global(ctrl, graph); break; default: errexit("Unknown mtype of %"PRIDX"\n", ctrl->mtype); } graph_WriteToDisk(ctrl, graph); Order_Partition(ctrl, graph->coarser, nlevels, clevel+1); graph_ReadFromDisk(ctrl, graph); ProjectPartition(ctrl, graph); AllocateNodePartitionParams(ctrl, graph); ComputeNodePartitionParams(ctrl, graph); switch (ctrl->rtype) { case PARMETIS_SRTYPE_GREEDY: KWayNodeRefine_Greedy(ctrl, graph, NGR_PASSES, ctrl->ubfrac); break; case PARMETIS_SRTYPE_2PHASE: KWayNodeRefine2Phase(ctrl, graph, NGR_PASSES, ctrl->ubfrac); break; default: errexit("Unknown rtype of %"PRIDX"\n", ctrl->rtype); } } } /*********************************************************************************/ /*! This function is used to assign labels to the nodes in the separators. It uses the appropriate entry in the lastnode array to select label boundaries and adjusts it for the next level. */ /*********************************************************************************/ void LabelSeparators(ctrl_t *ctrl, graph_t *graph, idx_t *lastnode, idx_t *perm, idx_t *order, idx_t *sizes) { idx_t i, nvtxs, nparts, sid; idx_t *where, *lpwgts, *gpwgts, *sizescan; nparts = ctrl->nparts; nvtxs = graph->nvtxs; where = graph->where; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; if (ctrl->dbglvl&DBG_INFO) { if (ctrl->mype == 0) { printf("SepWgts: "); for (i=0; i<nparts; i+=2) printf(" %"PRIDX" [%"PRIDX" %"PRIDX"]", gpwgts[nparts+i], gpwgts[i], gpwgts[i+1]); printf("\n"); } gkMPI_Barrier(ctrl->comm); } /* Compute the local size of the separator. This is required in case the graph has vertex weights */ iset(2*nparts, 0, lpwgts); for (i=0; i<nvtxs; i++) lpwgts[where[i]]++; sizescan = imalloc(2*nparts, "LabelSeparators: sizescan"); /* Perform a Prefix scan of the separator sizes to determine the boundaries */ gkMPI_Scan((void *)lpwgts, (void *)sizescan, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); #ifdef DEBUG_ORDER PrintVector(ctrl, 2*nparts, 0, lpwgts, "Lpwgts"); PrintVector(ctrl, 2*nparts, 0, sizescan, "SizeScan"); PrintVector(ctrl, 2*nparts, 0, lastnode, "LastNode"); #endif /* Fillin the sizes[] array. See the comment on MultilevelOrder() on the purpose of the sizes[0] value. */ for (i=nparts-2; i>=0; i-=2) sizes[--sizes[0]] = gpwgts[nparts+i]; if (ctrl->dbglvl&DBG_INFO) { if (ctrl->mype == 0) { printf("SepSizes: "); for (i=0; i<nparts; i+=2) printf(" %"PRIDX" [%"PRIDX" %"PRIDX"]", gpwgts[nparts+i], gpwgts[i], gpwgts[i+1]); printf("\n"); } gkMPI_Barrier(ctrl->comm); } for (i=0; i<2*nparts; i++) sizescan[i] -= lpwgts[i]; /* Assign the order[] values to the separator nodes */ for (i=0; i<nvtxs; i++) { if (where[i] >= nparts) { sid = where[i]; sizescan[sid]++; PASSERT(ctrl, order[perm[i]] == -1); order[perm[i]] = lastnode[sid] - sizescan[sid]; /*myprintf(ctrl, "order[%"PRIDX"] = %"PRIDX", %"PRIDX"\n", perm[i], order[perm[i]], sid); */ } } /* Update lastnode array */ icopy(2*nparts, lastnode, sizescan); for (i=0; i<nparts; i+=2) { lastnode[2*nparts+2*i] = sizescan[nparts+i]-gpwgts[nparts+i]-gpwgts[i+1]; lastnode[2*nparts+2*(i+1)] = sizescan[nparts+i]-gpwgts[nparts+i]; /*myprintf(ctrl, "lastnode: %"PRIDX" %"PRIDX"\n", lastnode[2*nparts+2*i], * lastnode[2*nparts+2*(i+1)]);*/ } gk_free((void **)&sizescan, LTERM); } /************************************************************************* * This function compacts a graph by removing the vertex separator **************************************************************************/ void CompactGraph(ctrl_t *ctrl, graph_t *graph, idx_t *perm) { idx_t i, j, l, nvtxs, cnvtxs, cfirstvtx, nparts, npes; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *where; idx_t *cmap, *cvtxdist, *newwhere; WCOREPUSH; nparts = ctrl->nparts; npes = ctrl->npes; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; if (graph->cmap == NULL) graph->cmap = imalloc(nvtxs+graph->nrecv, "CompactGraph: cmap"); cmap = graph->cmap; vtxdist = graph->vtxdist; /************************************************************* * Construct the cvtxdist of the contracted graph. Uses the fact * that lpwgts stores the local non separator vertices. **************************************************************/ cnvtxs = isum(nparts, graph->lpwgts, 1); cvtxdist = iwspacemalloc(ctrl, npes+1); gkMPI_Allgather((void *)&cnvtxs, 1, IDX_T, (void *)cvtxdist, 1, IDX_T, ctrl->comm); MAKECSR(i, npes, cvtxdist); #ifdef DEBUG_ORDER PrintVector(ctrl, npes+1, 0, cvtxdist, "cvtxdist"); #endif /************************************************************* * Construct the cmap vector **************************************************************/ cfirstvtx = cvtxdist[ctrl->mype]; /* Create the cmap of what you know so far locally */ for (cnvtxs=0, i=0; i<nvtxs; i++) { if (where[i] < nparts) { perm[cnvtxs] = perm[i]; cmap[i] = cfirstvtx + cnvtxs++; } } CommInterfaceData(ctrl, graph, cmap, cmap+nvtxs); /************************************************************* * Finally, compact the graph **************************************************************/ newwhere = imalloc(cnvtxs, "CompactGraph: newwhere"); cnvtxs = l = 0; for (i=0; i<nvtxs; i++) { if (where[i] < nparts) { for (j=xadj[i]; j<xadj[i+1]; j++) { PASSERT(ctrl, where[i] == where[adjncy[j]] || where[adjncy[j]] >= nparts); if (where[i] == where[adjncy[j]]) { adjncy[l] = cmap[adjncy[j]]; adjwgt[l++] = adjwgt[j]; } } xadj[cnvtxs] = l; graph->vwgt[cnvtxs] = graph->vwgt[i]; newwhere[cnvtxs] = where[i]; cnvtxs++; } } SHIFTCSR(i, cnvtxs, xadj); gk_free((void **)&graph->match, (void **)&graph->cmap, (void **)&graph->lperm, (void **)&graph->where, (void **)&graph->label, (void **)&graph->ckrinfo, (void **)&graph->nrinfo, (void **)&graph->lpwgts, (void **)&graph->gpwgts, (void **)&graph->sepind, (void **)&graph->peind, (void **)&graph->sendptr, (void **)&graph->sendind, (void **)&graph->recvptr, (void **)&graph->recvind, (void **)&graph->imap, (void **)&graph->rlens, (void **)&graph->slens, (void **)&graph->rcand, (void **)&graph->pexadj, (void **)&graph->peadjncy, (void **)&graph->peadjloc, LTERM); graph->nvtxs = cnvtxs; graph->nedges = l; graph->gnvtxs = cvtxdist[npes]; graph->where = newwhere; icopy(npes+1, cvtxdist, graph->vtxdist); WCOREPOP; } /*************************************************************************/ /*! This function orders the locally stored graph using MMD. The vertices will be ordered from firstnode onwards. */ /*************************************************************************/ void LocalNDOrder(ctrl_t *ctrl, graph_t *graph, idx_t *order, idx_t firstnode) { idx_t i, j, nvtxs, firstvtx, lastvtx; idx_t *xadj, *adjncy; idx_t *perm, *iperm; idx_t numflag=0, options[METIS_NOPTIONS]; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->SerialTmr)); WCOREPUSH; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; firstvtx = graph->vtxdist[ctrl->mype]; lastvtx = graph->vtxdist[ctrl->mype+1]; /* Relabel the vertices so that they are in local index space */ for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { PASSERT(ctrl, adjncy[j]>=firstvtx && adjncy[j]<lastvtx); adjncy[j] -= firstvtx; } } perm = iwspacemalloc(ctrl, nvtxs+5); iperm = iwspacemalloc(ctrl, nvtxs+5); METIS_SetDefaultOptions(options); options[METIS_OPTION_NSEPS] = ctrl->s_nseps; METIS_NodeND(&nvtxs, xadj, adjncy, graph->vwgt, options, perm, iperm); for (i=0; i<nvtxs; i++) { PASSERT(ctrl, iperm[i]>=0 && iperm[i]<nvtxs); order[i] = firstnode+iperm[i]; } WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->SerialTmr)); }
21,503
32.032258
116
c
null
ParMETIS-main/libparmetis/macros.h
/* * Copyright 1997, Regents of the University of Minnesota * * macros.h * * This file contains macros used in multilevel * * Started 9/25/94 * George * * $Id: macros.h 10578 2011-07-14 18:10:15Z karypis $ * */ /* The following macro returns a random number in the specified range */ #define AND(a, b) ((a) < 0 ? ((-(a))&(b)) : ((a)&(b))) #define OR(a, b) ((a) < 0 ? -((-(a))|(b)) : ((a)|(b))) #define XOR(a, b) ((a) < 0 ? -((-(a))^(b)) : ((a)^(b))) #define HASHFCT(key, size) ((key)%(size)) /* set/reset the current workspace core */ #define WCOREPUSH do {PASSERT(ctrl,ctrl->mcore!=NULL); gk_mcorePush(ctrl->mcore);}while(0) #define WCOREPOP do {PASSERT(ctrl,ctrl->mcore!=NULL); gk_mcorePop(ctrl->mcore);}while(0) /* Timer macros */ #define cleartimer(tmr) (tmr = 0.0) #define starttimer(tmr) (tmr -= MPI_Wtime()) #define stoptimer(tmr) (tmr += MPI_Wtime()) #define gettimer(tmr) (tmr) #define STARTTIMER(ctrl, tmr) \ do { \ IFSET((ctrl)->dbglvl, DBG_TIME, gkMPI_Barrier((ctrl)->gcomm));\ IFSET((ctrl)->dbglvl, DBG_TIME, starttimer((tmr))); \ } while (0) #define STOPTIMER(ctrl, tmr) \ do { \ IFSET((ctrl)->dbglvl, DBG_TIME, gkMPI_Barrier((ctrl)->gcomm));\ IFSET((ctrl)->dbglvl, DBG_TIME, stoptimer((tmr))); \ } while (0) /* Debugging macros */ #ifndef NDEBUG # define PASSERT(ctrl, expr) \ if (!(expr)) { \ myprintf(ctrl, "***ASSERTION failed on line %d of file %s: " #expr "\n", \ __LINE__, __FILE__); \ assert(expr); \ } # define PASSERTP(ctrl, expr, msg) \ if (!(expr)) { \ myprintf(ctrl, "***ASSERTION failed on line %d of file %s:" #expr "\n", \ __LINE__, __FILE__); \ myprintf msg ; \ assert(expr); \ } #else # define PASSERT(ctrl, expr) ; # define PASSERTP(ctrl, expr,msg) ; #endif /************************************************************************* * * These macros insert and remove nodes from the boundary list * **************************************************************************/ #define BNDInsert(nbnd, bndind, bndptr, vtx) \ do { \ bndind[nbnd] = vtx; \ bndptr[vtx] = nbnd++;\ } while(0) #define BNDDelete(nbnd, bndind, bndptr, vtx) \ do { \ bndind[bndptr[vtx]] = bndind[--nbnd]; \ bndptr[bndind[nbnd]] = bndptr[vtx]; \ bndptr[vtx] = -1; \ } while(0)
2,645
29.767442
93
h
null
ParMETIS-main/libparmetis/gklib.c
/*! \file gklib.c \brief Various helper routines generated using GKlib's templates \date Started 4/12/2007 \author George \author Copyright 1997-2009, Regents of the University of Minnesota \version\verbatim $Id: gklib.c 10395 2011-06-23 23:28:06Z karypis $ \endverbatim */ #include "parmetislib.h" /*************************************************************************/ /*! BLAS routines */ /*************************************************************************/ GK_MKBLAS(i, idx_t, idx_t) GK_MKBLAS(r, real_t, real_t) /*************************************************************************/ /*! Memory allocation routines */ /*************************************************************************/ GK_MKALLOC(i, idx_t) GK_MKALLOC(r, real_t) GK_MKALLOC(ikv, ikv_t) GK_MKALLOC(rkv, rkv_t) /*************************************************************************/ /*! Priority queues routines */ /*************************************************************************/ #define key_gt(a, b) ((a) > (b)) GK_MKPQUEUE(ipq, ipq_t, ikv_t, idx_t, idx_t, ikvmalloc, IDX_MAX, key_gt) GK_MKPQUEUE(rpq, rpq_t, rkv_t, real_t, idx_t, rkvmalloc, REAL_MAX, key_gt) #undef key_gt /*************************************************************************/ /*! Random number generation routines */ /*************************************************************************/ GK_MKRANDOM(i, idx_t, idx_t) /*************************************************************************/ /*! Utility routines */ /*************************************************************************/ GK_MKARRAY2CSR(i, idx_t) /*************************************************************************/ /*! Sorting routines */ /*************************************************************************/ void isorti(size_t n, idx_t *base) { #define i_lt(a, b) ((*a) < (*b)) GK_MKQSORT(idx_t, base, n, i_lt); #undef i_lt } void isortd(size_t n, idx_t *base) { #define i_gt(a, b) ((*a) > (*b)) GK_MKQSORT(idx_t, base, n, i_gt); #undef i_gt } void rsorti(size_t n, real_t *base) { #define r_lt(a, b) ((*a) < (*b)) GK_MKQSORT(real_t, base, n, r_lt); #undef r_lt } void rsortd(size_t n, real_t *base) { #define r_gt(a, b) ((*a) > (*b)) GK_MKQSORT(real_t, base, n, r_gt); #undef r_gt } void ikvsorti(size_t n, ikv_t *base) { #define ikey_lt(a, b) ((a)->key < (b)->key) GK_MKQSORT(ikv_t, base, n, ikey_lt); #undef ikey_lt } /* Sorts based both on key and val */ void ikvsortii(size_t n, ikv_t *base) { #define ikeyval_lt(a, b) ((a)->key < (b)->key || ((a)->key == (b)->key && (a)->val < (b)->val)) GK_MKQSORT(ikv_t, base, n, ikeyval_lt); #undef ikeyval_lt } void ikvsortd(size_t n, ikv_t *base) { #define ikey_gt(a, b) ((a)->key > (b)->key) GK_MKQSORT(ikv_t, base, n, ikey_gt); #undef ikey_gt } void rkvsorti(size_t n, rkv_t *base) { #define rkey_lt(a, b) ((a)->key < (b)->key) GK_MKQSORT(rkv_t, base, n, rkey_lt); #undef rkey_lt } void rkvsortd(size_t n, rkv_t *base) { #define rkey_gt(a, b) ((a)->key > (b)->key) GK_MKQSORT(rkv_t, base, n, rkey_gt); #undef rkey_gt } void uvwsorti(size_t n, uvw_t *base) { #define uvwkey_lt(a, b) ((a)->u < (b)->u || ((a)->u == (b)->u && (a)->v < (b)->v)) GK_MKQSORT(uvw_t, base, n, uvwkey_lt); #undef uvwkey_lt }
3,276
26.082645
95
c
null
ParMETIS-main/libparmetis/msetup.c
/* * Copyright 1997, Regents of the University of Minnesota * * msetup.c * * This file contain various routines for setting up a mesh * * Started 10/19/96 * George * * $Id: msetup.c 10057 2011-06-02 13:44:44Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function setsup the ctrl_t structure **************************************************************************/ mesh_t *SetUpMesh(idx_t *etype, idx_t *ncon, idx_t *elmdist, idx_t *elements, idx_t *elmwgt, idx_t *wgtflag, MPI_Comm *comm) { mesh_t *mesh; idx_t i, npes, mype; idx_t esizes[5] = {-1, 3, 4, 8, 4}; idx_t maxnode, gmaxnode, minnode, gminnode; gkMPI_Comm_size(*comm, &npes); gkMPI_Comm_rank(*comm, &mype); mesh = CreateMesh(); mesh->elmdist = elmdist; mesh->gnelms = elmdist[npes]; mesh->nelms = elmdist[mype+1]-elmdist[mype]; mesh->elements = elements; mesh->elmwgt = elmwgt; mesh->etype = *etype; mesh->ncon = *ncon; mesh->esize = esizes[*etype]; if (((*wgtflag)&1) == 0) { mesh->elmwgt = ismalloc(mesh->nelms*mesh->ncon, 1, "SetUpMesh: elmwgt"); } minnode = imin(mesh->nelms*mesh->esize, elements, 1); gkMPI_Allreduce((void *)&minnode, (void *)&gminnode, 1, IDX_T, MPI_MIN, *comm); for (i=0; i<mesh->nelms*mesh->esize; i++) elements[i] -= gminnode; mesh->gminnode = gminnode; maxnode = imax(mesh->nelms*mesh->esize, elements, 1); gkMPI_Allreduce((void *)&maxnode, (void *)&gmaxnode, 1, IDX_T, MPI_MAX, *comm); mesh->gnns = gmaxnode+1; return mesh; } /************************************************************************* * This function creates a mesh_t data structure and initializes * the various fields **************************************************************************/ mesh_t *CreateMesh(void) { mesh_t *mesh; mesh = (mesh_t *)gk_malloc(sizeof(mesh_t), "CreateMesh: mesh"); InitMesh(mesh); return mesh; } /************************************************************************* * This function initializes the various fields of a mesh_t. **************************************************************************/ void InitMesh(mesh_t *mesh) { mesh->etype = -1; mesh->gnelms = -1; mesh->gnns = -1; mesh->nelms = -1; mesh->nns = -1; mesh->ncon = -1; mesh->esize = -1; mesh->gminnode = 0; mesh->elmdist = NULL; mesh->elements = NULL; mesh->elmwgt = NULL; return; }
2,449
24.520833
81
c
null
ParMETIS-main/libparmetis/kmetis.c
/* * Copyright 1997, Regents of the University of Minnesota * * kmetis.c * * This is the entry point of ParMETIS_PartKway * * Started 10/19/96 * George * * $Id: kmetis.c 10757 2011-09-15 22:07:47Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the parallel k-way multilevel partitionioner. * This function assumes nothing about the graph distribution. * It is the general case. ************************************************************************************/ int ParMETIS_V3_PartKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t h, i, status, nvtxs, npes, mype, seed, dbglvl; ctrl_t *ctrl; graph_t *graph; idx_t moptions[METIS_NOPTIONS]; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsPartKway(vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Set up the control */ ctrl = SetupCtrl(PARMETIS_OP_KMETIS, options, *ncon, *nparts, tpwgts, ubvec, *comm); npes = ctrl->npes; mype = ctrl->mype; /* Take care the nparts == 1 case */ if (*nparts == 1) { iset(vtxdist[mype+1]-vtxdist[mype], (*numflag == 0 ? 0 : 1), part); *edgecut = 0; goto DONE; } /* Take care of npes == 1 case */ if (npes == 1) { nvtxs = vtxdist[1] - vtxdist[0]; METIS_SetDefaultOptions(moptions); moptions[METIS_OPTION_NUMBERING] = *numflag; status = METIS_PartGraphKway(&nvtxs, ncon, xadj, adjncy, vwgt, NULL, adjwgt, nparts, tpwgts, ubvec, moptions, edgecut, part); goto DONE; } /* Setup the graph */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 1); graph = SetupGraph(ctrl, *ncon, vtxdist, xadj, vwgt, NULL, adjncy, adjwgt, *wgtflag); /* Setup the workspace */ AllocateWSpace(ctrl, 10*graph->nvtxs); /* Partition the graph */ STARTTIMER(ctrl, ctrl->TotalTmr); ctrl->CoarsenTo = gk_min(vtxdist[npes]+1, 25*(*ncon)*gk_max(npes, *nparts)); if (vtxdist[npes] < SMALLGRAPH || vtxdist[npes] < npes*20 || GlobalSESum(ctrl, graph->nedges) == 0) { /* serially */ IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Partitioning a graph of size %"PRIDX" serially\n", vtxdist[npes])); PartitionSmallGraph(ctrl, graph); } else { /* in parallel */ Global_Partition(ctrl, graph); } ParallelReMapGraph(ctrl, graph); icopy(graph->nvtxs, graph->where, part); *edgecut = graph->mincut; STOPTIMER(ctrl, ctrl->TotalTmr); /* Print out stats */ IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); IFSET(ctrl->dbglvl, DBG_INFO, PrintPostPartInfo(ctrl, graph, 0)); FreeInitialGraphAndRemap(graph); if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 0); DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; } /*************************************************************************/ /*! This function is the driver to the multi-constraint partitioning algorithm. */ /*************************************************************************/ void Global_Partition(ctrl_t *ctrl, graph_t *graph) { idx_t i, ncon, nparts; real_t ftmp, ubavg, lbavg, *lbvec; WCOREPUSH; ncon = graph->ncon; nparts = ctrl->nparts; ubavg = ravg(graph->ncon, ctrl->ubvec); CommSetup(ctrl, graph); lbvec = rwspacemalloc(ctrl, ncon); if (ctrl->dbglvl&DBG_PROGRESS) { rprintf(ctrl, "[%6"PRIDX" %8"PRIDX" %5"PRIDX" %5"PRIDX"] [%"PRIDX"] [", graph->gnvtxs, GlobalSESum(ctrl, graph->nedges), GlobalSEMin(ctrl, graph->nvtxs), GlobalSEMax(ctrl, graph->nvtxs), ctrl->CoarsenTo); for (i=0; i<ncon; i++) rprintf(ctrl, " %.3"PRREAL"", GlobalSEMinFloat(ctrl,graph->nvwgt[rargmin_strd(graph->nvtxs, graph->nvwgt+i, ncon)*ncon+i])); rprintf(ctrl, "] ["); for (i=0; i<ncon; i++) rprintf(ctrl, " %.3"PRREAL"", GlobalSEMaxFloat(ctrl, graph->nvwgt[rargmax_strd(graph->nvtxs, graph->nvwgt+i, ncon)*ncon+i])); rprintf(ctrl, "]\n"); } if (graph->gnvtxs < 1.3*ctrl->CoarsenTo || (graph->finer != NULL && graph->gnvtxs > graph->finer->gnvtxs*COARSEN_FRACTION)) { /* Done with coarsening. Find a partition */ AllocateRefinementWorkSpace(ctrl, 2*graph->nedges); graph->where = imalloc(graph->nvtxs+graph->nrecv, "graph->where"); InitPartition(ctrl, graph); if (ctrl->dbglvl&DBG_PROGRESS) { ComputePartitionParams(ctrl, graph); ComputeParallelBalance(ctrl, graph, graph->where, lbvec); rprintf(ctrl, "nvtxs: %10"PRIDX", cut: %8"PRIDX", balance: ", graph->gnvtxs, graph->mincut); for (i=0; i<graph->ncon; i++) rprintf(ctrl, "%.3"PRREAL" ", lbvec[i]); rprintf(ctrl, "\n"); /* free memory allocated by ComputePartitionParams */ gk_free((void **)&graph->ckrinfo, &graph->lnpwgts, &graph->gnpwgts, LTERM); } /* In case no coarsening took place */ if (graph->finer == NULL) { ComputePartitionParams(ctrl, graph); KWayFM(ctrl, graph, NGR_PASSES); } } else { Match_Global(ctrl, graph); graph_WriteToDisk(ctrl, graph); Global_Partition(ctrl, graph->coarser); graph_ReadFromDisk(ctrl, graph); ProjectPartition(ctrl, graph); ComputePartitionParams(ctrl, graph); if (graph->ncon > 1 && graph->level < 3) { for (i=0; i<ncon; i++) { ftmp = rsum(nparts, graph->gnpwgts+i, ncon); if (ftmp != 0.0) lbvec[i] = (real_t)(nparts) * graph->gnpwgts[rargmax_strd(nparts, graph->gnpwgts+i, ncon)*ncon+i]/ftmp; else lbvec[i] = 1.0; } lbavg = ravg(graph->ncon, lbvec); if (lbavg > ubavg + 0.035) { if (ctrl->dbglvl&DBG_PROGRESS) { ComputeParallelBalance(ctrl, graph, graph->where, lbvec); rprintf(ctrl, "nvtxs: %10"PRIDX", cut: %8"PRIDX", balance: ", graph->gnvtxs, graph->mincut); for (i=0; i<graph->ncon; i++) rprintf(ctrl, "%.3"PRREAL" ", lbvec[i]); rprintf(ctrl, " [b]\n"); } KWayBalance(ctrl, graph, graph->ncon); } } KWayFM(ctrl, graph, NGR_PASSES); if (ctrl->dbglvl&DBG_PROGRESS) { ComputeParallelBalance(ctrl, graph, graph->where, lbvec); rprintf(ctrl, "nvtxs: %10"PRIDX", cut: %8"PRIDX", balance: ", graph->gnvtxs, graph->mincut); for (i=0; i<graph->ncon; i++) rprintf(ctrl, "%.3"PRREAL" ", lbvec[i]); rprintf(ctrl, "\n"); } if (graph->level != 0) gk_free((void **)&graph->lnpwgts, (void **)&graph->gnpwgts, LTERM); } WCOREPOP; }
7,322
28.768293
133
c
null
ParMETIS-main/libparmetis/proto.h
/* * Copyright 1997, Regents of the University of Minnesota * * proto.h * * This file contains header files * * Started 10/19/95 * George * * $Id: proto.h 10592 2011-07-16 21:17:53Z karypis $ * */ /* ctrl.c */ ctrl_t *SetupCtrl(pmoptype_et optype, idx_t *options, idx_t ncon, idx_t nparts, real_t *tpwgts, real_t *ubvec, MPI_Comm comm); void SetupCtrl_invtvwgts(ctrl_t *ctrl, graph_t *graph); void FreeCtrl(ctrl_t **r_ctrl); /* kmetis.c */ void Global_Partition(ctrl_t *, graph_t *); /* mmetis.c */ /* gkmetis.c */ /* match.c */ void Match_Global(ctrl_t *, graph_t *); void Match_Local(ctrl_t *, graph_t *); void CreateCoarseGraph_Global(ctrl_t *, graph_t *, idx_t); void CreateCoarseGraph_Local(ctrl_t *, graph_t *, idx_t); void DropEdges(ctrl_t *ctrl, graph_t *graph); /* initpart.c */ void InitPartition(ctrl_t *, graph_t *); void KeepPart(ctrl_t *, graph_t *, idx_t *, idx_t); /* kwayrefine.c */ void ProjectPartition(ctrl_t *, graph_t *); void ComputePartitionParams(ctrl_t *, graph_t *); void KWayFM(ctrl_t *, graph_t *, idx_t); void KWayBalance(ctrl_t *, graph_t *, idx_t); /* remap.c */ void ParallelReMapGraph(ctrl_t *, graph_t *); void ParallelTotalVReMap(ctrl_t *, idx_t *, idx_t *, idx_t, idx_t); idx_t SimilarTpwgts(real_t *, idx_t, idx_t, idx_t); /* move.c */ graph_t *MoveGraph(ctrl_t *, graph_t *); void CheckMGraph(ctrl_t *, graph_t *); void ProjectInfoBack(ctrl_t *, graph_t *, idx_t *, idx_t *); void FindVtxPerm(ctrl_t *, graph_t *, idx_t *); /* wspace.c */ void AllocateWSpace(ctrl_t *ctrl, size_t nwords); void AllocateRefinementWorkSpace(ctrl_t *ctrl, idx_t nbrpoolsize); void FreeWSpace(ctrl_t *); void *wspacemalloc(ctrl_t *ctrl, size_t nbytes); idx_t *iwspacemalloc(ctrl_t *ctrl, size_t n); real_t *rwspacemalloc(ctrl_t *ctrl, size_t n); ikv_t *ikvwspacemalloc(ctrl_t *ctrl, size_t n); rkv_t *rkvwspacemalloc(ctrl_t *ctrl, size_t n); void cnbrpoolReset(ctrl_t *ctrl); idx_t cnbrpoolGetNext(ctrl_t *ctrl, idx_t nnbrs); /* ametis.c */ void Adaptive_Partition(ctrl_t *, graph_t *); /* rmetis.c */ /* wave.c */ real_t WavefrontDiffusion(ctrl_t *, graph_t *, idx_t *); /* balancemylink.c */ idx_t BalanceMyLink(ctrl_t *, graph_t *, idx_t *, idx_t, idx_t, real_t *, real_t, real_t *, real_t *, real_t); /* redomylink.c */ void RedoMyLink(ctrl_t *, graph_t *, idx_t *, idx_t, idx_t, real_t *, real_t *, real_t *); /* initbalance.c */ void Balance_Partition(ctrl_t *, graph_t *); graph_t *AssembleAdaptiveGraph(ctrl_t *, graph_t *); /* mdiffusion.c */ idx_t Mc_Diffusion(ctrl_t *, graph_t *, idx_t *, idx_t *, idx_t *, idx_t); graph_t *ExtractGraph(ctrl_t *, graph_t *, idx_t *, idx_t *, idx_t *); /* diffutil.c */ void SetUpConnectGraph(graph_t *, matrix_t *, idx_t *); void Mc_ComputeMoveStatistics(ctrl_t *, graph_t *, idx_t *, idx_t *, idx_t *); idx_t Mc_ComputeSerialTotalV(graph_t *, idx_t *); void ComputeLoad(graph_t *, idx_t, real_t *, real_t *, idx_t); void ConjGrad2(matrix_t *, real_t *, real_t *, real_t, real_t *); void mvMult2(matrix_t *, real_t *, real_t *); void ComputeTransferVector(idx_t, matrix_t *, real_t *, real_t *, idx_t); idx_t ComputeSerialEdgeCut(graph_t *); idx_t ComputeSerialTotalV(graph_t *, idx_t *); /* akwayfm.c */ void KWayAdaptiveRefine(ctrl_t *, graph_t *, idx_t); /* selectq.c */ void Mc_DynamicSelectQueue(ctrl_t *ctrl, idx_t nqueues, idx_t ncon, idx_t subdomain1, idx_t subdomain2, idx_t *currentq, real_t *flows, idx_t *from, idx_t *qnum, idx_t minval, real_t avgvwgt, real_t maxdiff); idx_t Mc_HashVwgts(ctrl_t *ctrl, idx_t ncon, real_t *nvwgt); idx_t Mc_HashVRank(idx_t ncon, idx_t *vwgt); /* csrmatch.c */ void CSR_Match_SHEM(matrix_t *, idx_t *, idx_t *, idx_t *, idx_t); /* serial.c */ void Mc_ComputeSerialPartitionParams(ctrl_t *ctrl, graph_t *, idx_t); void Mc_SerialKWayAdaptRefine(ctrl_t *ctrl, graph_t *, idx_t, idx_t *, real_t *, idx_t); idx_t AreAllHVwgtsBelow(idx_t, real_t, real_t *, real_t, real_t *, real_t *); void ComputeHKWayLoadImbalance(idx_t, idx_t, real_t *, real_t *); void SerialRemap(ctrl_t *ctrl, graph_t *, idx_t, idx_t *, idx_t *, idx_t *, real_t *); int SSMIncKeyCmp(const void *, const void *); void Mc_Serial_FM_2WayRefine(ctrl_t *ctrl, graph_t *, real_t *, idx_t); void Serial_SelectQueue(idx_t, real_t *, real_t *, idx_t *, idx_t *, rpq_t **[2]); idx_t Serial_BetterBalance(idx_t, real_t *, real_t *, real_t *, real_t *); real_t Serial_Compute2WayHLoadImbalance(idx_t, real_t *, real_t *); void Mc_Serial_Balance2Way(ctrl_t *ctrl, graph_t *, real_t *, real_t); void Mc_Serial_Init2WayBalance(ctrl_t *ctrl, graph_t *, real_t *); idx_t Serial_SelectQueueOneWay(idx_t, real_t *, real_t *, idx_t, rpq_t **[2]); void Mc_Serial_Compute2WayPartitionParams(ctrl_t *ctrl, graph_t *); idx_t Serial_AreAnyVwgtsBelow(idx_t, real_t, real_t *, real_t, real_t *, real_t *); /* weird.c */ int CheckInputsPartKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int CheckInputsPartGeomKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int CheckInputsPartGeom(idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Comm *comm); int CheckInputsAdaptiveRepart(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int CheckInputsNodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm); int CheckInputsPartMeshKway(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); void PartitionSmallGraph(ctrl_t *, graph_t *); /* mesh.c */ /* pspases.c */ graph_t *AssembleEntireGraph(ctrl_t *, idx_t *, idx_t *, idx_t *); /* node_refine.c */ void AllocateNodePartitionParams(ctrl_t *, graph_t *); void ComputeNodePartitionParams(ctrl_t *, graph_t *); void UpdateNodePartitionParams(ctrl_t *, graph_t *); void KWayNodeRefine_Greedy(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac); void KWayNodeRefine2Phase(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac); void KWayNodeRefineInterior(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac); void PrintNodeBalanceInfo(ctrl_t *, idx_t, idx_t *, idx_t *, char *); /* initmsection.c */ void InitMultisection(ctrl_t *, graph_t *); graph_t *AssembleMultisectedGraph(ctrl_t *, graph_t *); /* ometis.c */ void MultilevelOrder(ctrl_t *ctrl, graph_t *graph, idx_t *order, idx_t *sizes); void Order_Partition_Multiple(ctrl_t *ctrl, graph_t *graph); void Order_Partition(ctrl_t *ctrl, graph_t *graph, idx_t *nlevels, idx_t clevel); void LabelSeparators(ctrl_t *, graph_t *, idx_t *, idx_t *, idx_t *, idx_t *); void CompactGraph(ctrl_t *, graph_t *, idx_t *); void LocalNDOrder(ctrl_t *, graph_t *, idx_t *, idx_t); /* xyzpart.c */ void Coordinate_Partition(ctrl_t *, graph_t *, idx_t, real_t *, idx_t); void IRBinCoordinates(ctrl_t *ctrl, graph_t *graph, idx_t ndims, real_t *xyz, idx_t nbins, idx_t *bxyz); void RBBinCoordinates(ctrl_t *ctrl, graph_t *graph, idx_t ndims, real_t *xyz, idx_t nbins, idx_t *bxyz); void SampleSort(ctrl_t *, graph_t *, ikv_t *); void PseudoSampleSort(ctrl_t *, graph_t *, ikv_t *); /* stat.c */ void ComputeSerialBalance(ctrl_t *, graph_t *, idx_t *, real_t *); void ComputeParallelBalance(ctrl_t *, graph_t *, idx_t *, real_t *); void Mc_PrintThrottleMatrix(ctrl_t *, graph_t *, real_t *); void PrintPostPartInfo(ctrl_t *ctrl, graph_t *graph, idx_t movestats); void ComputeMoveStatistics(ctrl_t *, graph_t *, idx_t *, idx_t *, idx_t *); /* debug.c */ void PrintVector(ctrl_t *, idx_t, idx_t, idx_t *, char *); void PrintVector2(ctrl_t *, idx_t, idx_t, idx_t *, char *); void PrintPairs(ctrl_t *, idx_t, ikv_t *, char *); void PrintGraph(ctrl_t *, graph_t *); void PrintGraph2(ctrl_t *, graph_t *); void PrintSetUpInfo(ctrl_t *ctrl, graph_t *graph); void PrintTransferedGraphs(ctrl_t *, idx_t, idx_t *, idx_t *, idx_t *, idx_t *, idx_t *); void WriteMetisGraph(idx_t, idx_t *, idx_t *, idx_t *, idx_t *); /* comm.c */ void CommSetup(ctrl_t *, graph_t *); void CommUpdateNnbrs(ctrl_t *ctrl, idx_t nnbrs); void CommInterfaceData(ctrl_t *ctrl, graph_t *graph, idx_t *data, idx_t *recvvector); void CommChangedInterfaceData(ctrl_t *ctrl, graph_t *graph, idx_t nchanged, idx_t *changed, idx_t *data, ikv_t *sendpairs, ikv_t *recvpairs); idx_t GlobalSEMax(ctrl_t *, idx_t); idx_t GlobalSEMaxComm(MPI_Comm comm, idx_t value); idx_t GlobalSEMin(ctrl_t *, idx_t); idx_t GlobalSEMinComm(MPI_Comm comm, idx_t value); idx_t GlobalSESum(ctrl_t *, idx_t); idx_t GlobalSESumComm(MPI_Comm comm, idx_t value); real_t GlobalSEMaxFloat(ctrl_t *, real_t); real_t GlobalSEMinFloat(ctrl_t *, real_t); real_t GlobalSESumFloat(ctrl_t *, real_t); /* util.c */ void myprintf(ctrl_t *ctrl, char *f_str,...); void rprintf(ctrl_t *ctrl, char *f_str,...); void mypridx_tf(ctrl_t *, char *f_str,...); void rpridx_tf(ctrl_t *, char *f_str,...); idx_t BSearch(idx_t, idx_t *, idx_t); void RandomPermute(idx_t, idx_t *, idx_t); void FastRandomPermute(idx_t, idx_t *, idx_t); idx_t ispow2(idx_t); idx_t log2Int(idx_t); void BucketSortKeysDec(idx_t, idx_t, idx_t *, idx_t *); real_t BetterVBalance(idx_t, real_t *, real_t *, real_t *); idx_t IsHBalanceBetterTT(idx_t, real_t *, real_t *, real_t *, real_t *); idx_t IsHBalanceBetterFT(idx_t, real_t *, real_t *, real_t *, real_t *); void GetThreeMax(idx_t, real_t *, idx_t *, idx_t *, idx_t *); size_t rargmax_strd(size_t n, real_t *x, size_t incx); size_t rargmin_strd(size_t n, real_t *x, size_t incx); size_t rargmax2(size_t n, real_t *x); real_t ravg(size_t n, real_t *x); real_t rfavg(size_t n, real_t *x); /* graph.c */ graph_t *SetupGraph(ctrl_t *ctrl, idx_t ncon, idx_t *vtxdist, idx_t *xadj, idx_t *vwgt, idx_t *vsize, idx_t *adjncy, idx_t *adjwgt, idx_t wgtflag); void SetupGraph_nvwgts(ctrl_t *ctrl, graph_t *graph); graph_t *CreateGraph(void); void InitGraph(graph_t *); void FreeGraph(graph_t *graph); void FreeNonGraphFields(graph_t *graph); void FreeNonGraphNonSetupFields(graph_t *graph); void FreeCommSetupFields(graph_t *graph); void FreeInitialGraphAndRemap(graph_t *graph); void graph_WriteToDisk(ctrl_t *ctrl, graph_t *graph); void graph_ReadFromDisk(ctrl_t *ctrl, graph_t *graph); /* renumber.c */ void ChangeNumbering(idx_t *, idx_t *, idx_t *, idx_t *, idx_t, idx_t, idx_t); void ChangeNumberingMesh(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *xadj, idx_t *adjncy, idx_t *part, idx_t npes, idx_t mype, idx_t from); /* timer.c */ void InitTimers(ctrl_t *); void PrintTimingInfo(ctrl_t *); void PrintTimer(ctrl_t *, timer, char *); /* parmetis.c */ void ChangeToFortranNumbering(idx_t *, idx_t *, idx_t *, idx_t, idx_t); /* msetup.c */ mesh_t *SetUpMesh(idx_t *etype, idx_t *ncon, idx_t *elmdist, idx_t *elements, idx_t *elmwgt, idx_t *wgtflag, MPI_Comm *comm); mesh_t *CreateMesh(void); void InitMesh(mesh_t *mesh); /* gkmpi.c */ int gkMPI_Comm_size(MPI_Comm comm, idx_t *size); int gkMPI_Comm_rank(MPI_Comm comm, idx_t *rank); int gkMPI_Get_count(MPI_Status *status, MPI_Datatype datatype, idx_t *count); int gkMPI_Send(void *buf, idx_t count, MPI_Datatype datatype, idx_t dest, idx_t tag, MPI_Comm comm); int gkMPI_Recv(void *buf, idx_t count, MPI_Datatype datatype, idx_t source, idx_t tag, MPI_Comm comm, MPI_Status *status); int gkMPI_Isend(void *buf, idx_t count, MPI_Datatype datatype, idx_t dest, idx_t tag, MPI_Comm comm, MPI_Request *request); int gkMPI_Irecv(void *buf, idx_t count, MPI_Datatype datatype, idx_t source, idx_t tag, MPI_Comm comm, MPI_Request *request); int gkMPI_Wait(MPI_Request *request, MPI_Status *status); int gkMPI_Waitall(idx_t count, MPI_Request *array_of_requests, MPI_Status *array_of_statuses); int gkMPI_Barrier(MPI_Comm comm); int gkMPI_Bcast(void *buffer, idx_t count, MPI_Datatype datatype, idx_t root, MPI_Comm comm); int gkMPI_Reduce(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, idx_t root, MPI_Comm comm); int gkMPI_Allreduce(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); int gkMPI_Scan(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm); int gkMPI_Allgather(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, MPI_Comm comm); int gkMPI_Alltoall(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, MPI_Comm comm); int gkMPI_Alltoallv(void *sendbuf, idx_t *sendcounts, idx_t *sdispls, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *rdispls, MPI_Datatype recvtype, MPI_Comm comm); int gkMPI_Allgatherv(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *rdispls, MPI_Datatype recvtype, MPI_Comm comm); int gkMPI_Scatterv(void *sendbuf, idx_t *sendcounts, idx_t *sdispls, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, idx_t root, MPI_Comm comm); int gkMPI_Gatherv(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *displs, MPI_Datatype recvtype, idx_t root, MPI_Comm comm); int gkMPI_Comm_split(MPI_Comm comm, idx_t color, idx_t key, MPI_Comm *newcomm); int gkMPI_Comm_free(MPI_Comm *comm); int gkMPI_Finalize();
14,305
40.109195
90
h
null
ParMETIS-main/libparmetis/mdiffusion.c
/* * Copyright 1997, Regents of the University of Minnesota * * mdiffusion.c * * This file contains code that performs mc-diffusion * * Started 9/16/99 * George * * $Id: mdiffusion.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define PE -1 /************************************************************************* * This function is the entry point of the initial partitioning algorithm. * This algorithm assembles the graph to all the processors and preceed * serially. **************************************************************************/ idx_t Mc_Diffusion(ctrl_t *ctrl, graph_t *graph, idx_t *vtxdist, idx_t *where, idx_t *home, idx_t npasses) { idx_t h, i, j; idx_t nvtxs, nedges, ncon, pass, iter, domain, processor; idx_t nparts, mype, npes, nlinks, me, you, wsize; idx_t nvisited, nswaps = -1, tnswaps, done, alldone = -1; idx_t *rowptr, *colind, *diff_where, *sr_where, *ehome, *map, *rmap; idx_t *pack, *unpack, *match, *proc2sub, *sub2proc; idx_t *visited, *gvisited; real_t *transfer, *npwgts, maxdiff, minflow, maxflow; real_t lbavg, oldlbavg, ubavg, *lbvec; real_t *diff_flows, *sr_flows; real_t diff_lbavg, sr_lbavg, diff_cost, sr_cost; idx_t *rbuffer, *sbuffer; idx_t *rcount, *rdispl; real_t *solution, *load, *workspace; matrix_t matrix; graph_t *egraph; if (graph->ncon > 3) return 0; WCOREPUSH; nvtxs = graph->nvtxs; nedges = graph->nedges; ncon = graph->ncon; nparts = ctrl->nparts; mype = ctrl->mype; npes = ctrl->npes; ubavg = ravg(ncon, ctrl->ubvec); /* initialize variables and allocate memory */ lbvec = rwspacemalloc(ctrl, ncon); diff_flows = rwspacemalloc(ctrl, ncon); sr_flows = rwspacemalloc(ctrl, ncon); load = rwspacemalloc(ctrl, nparts); solution = rwspacemalloc(ctrl, nparts); npwgts = graph->gnpwgts = rwspacemalloc(ctrl, ncon*nparts); matrix.values = rwspacemalloc(ctrl, nedges); transfer = matrix.transfer = rwspacemalloc(ctrl, ncon*nedges); proc2sub = iwspacemalloc(ctrl, gk_max(nparts, npes*2)); sub2proc = iwspacemalloc(ctrl, nparts); match = iwspacemalloc(ctrl, nparts); rowptr = matrix.rowptr = iwspacemalloc(ctrl, nparts+1); colind = matrix.colind = iwspacemalloc(ctrl, nedges); rcount = iwspacemalloc(ctrl, npes); rdispl = iwspacemalloc(ctrl, npes+1); pack = iwspacemalloc(ctrl, nvtxs); unpack = iwspacemalloc(ctrl, nvtxs); rbuffer = iwspacemalloc(ctrl, nvtxs); sbuffer = iwspacemalloc(ctrl, nvtxs); map = iwspacemalloc(ctrl, nvtxs); rmap = iwspacemalloc(ctrl, nvtxs); diff_where = iwspacemalloc(ctrl, nvtxs); ehome = iwspacemalloc(ctrl, nvtxs); wsize = gk_max(sizeof(real_t)*nparts*6, sizeof(idx_t)*(nvtxs+nparts*2+1)); workspace = (real_t *)gk_malloc(wsize, "Mc_Diffusion: workspace"); graph->ckrinfo = (ckrinfo_t *)gk_malloc(nvtxs*sizeof(ckrinfo_t), "Mc_Diffusion: rinfo"); /* construct subdomain connectivity graph */ matrix.nrows = nparts; SetUpConnectGraph(graph, &matrix, (idx_t *)workspace); nlinks = (matrix.nnzs-nparts) / 2; visited = iwspacemalloc(ctrl, matrix.nnzs); gvisited = iwspacemalloc(ctrl, matrix.nnzs); for (pass=0; pass<npasses; pass++) { rset(matrix.nnzs*ncon, 0.0, transfer); iset(matrix.nnzs, 0, gvisited); iset(matrix.nnzs, 0, visited); iter = nvisited = 0; /* compute ncon flow solutions */ for (h=0; h<ncon; h++) { rset(nparts, 0.0, solution); ComputeLoad(graph, nparts, load, ctrl->tpwgts, h); lbvec[h] = (rmax(nparts, load, 1)+1.0/nparts) * (real_t)nparts; ConjGrad2(&matrix, load, solution, 0.001, workspace); ComputeTransferVector(ncon, &matrix, solution, transfer, h); } oldlbavg = ravg(ncon, lbvec); tnswaps = 0; maxdiff = 0.0; for (i=0; i<nparts; i++) { for (j=rowptr[i]; j<rowptr[i+1]; j++) { maxflow = rmax(ncon, transfer+j*ncon, 1); minflow = rmin(ncon, transfer+j*ncon, 1); maxdiff = (maxflow - minflow > maxdiff) ? maxflow - minflow : maxdiff; } } while (nvisited < nlinks) { /* compute independent sets of subdomains */ iset(gk_max(nparts, npes*2), UNMATCHED, proc2sub); CSR_Match_SHEM(&matrix, match, proc2sub, gvisited, ncon); /* set up the packing arrays */ iset(nparts, UNMATCHED, sub2proc); for (i=0; i<npes*2; i++) { if (proc2sub[i] == UNMATCHED) break; sub2proc[proc2sub[i]] = i/2; } iset(npes, 0, rcount); for (i=0; i<nvtxs; i++) { domain = where[i]; processor = sub2proc[domain]; if (processor != UNMATCHED) rcount[processor]++; } rdispl[0] = 0; for (i=1; i<npes+1; i++) rdispl[i] = rdispl[i-1] + rcount[i-1]; iset(nvtxs, UNMATCHED, unpack); for (i=0; i<nvtxs; i++) { domain = where[i]; processor = sub2proc[domain]; if (processor != UNMATCHED) unpack[rdispl[processor]++] = i; } SHIFTCSR(i, npes, rdispl); iset(nvtxs, UNMATCHED, pack); for (i=0; i<rdispl[npes]; i++) { ASSERT(unpack[i] != UNMATCHED); domain = where[unpack[i]]; processor = sub2proc[domain]; if (processor != UNMATCHED) pack[unpack[i]] = i; } /* Compute the flows */ if (proc2sub[mype*2] != UNMATCHED) { me = proc2sub[2*mype]; you = proc2sub[2*mype+1]; ASSERT(me != you); for (j=rowptr[me]; j<rowptr[me+1]; j++) { if (colind[j] == you) { visited[j] = 1; rcopy(ncon, transfer+j*ncon, diff_flows); break; } } for (j=rowptr[you]; j<rowptr[you+1]; j++) { if (colind[j] == me) { visited[j] = 1; for (h=0; h<ncon; h++) { if (transfer[j*ncon+h] > 0.0) diff_flows[h] = -1.0 * transfer[j*ncon+h]; } break; } } nswaps = 1; rcopy(ncon, diff_flows, sr_flows); iset(nvtxs, 0, sbuffer); for (i=0; i<nvtxs; i++) { if (where[i] == me || where[i] == you) sbuffer[i] = 1; } egraph = ExtractGraph(ctrl, graph, sbuffer, map, rmap); if (egraph != NULL) { icopy(egraph->nvtxs, egraph->where, diff_where); for (j=0; j<egraph->nvtxs; j++) ehome[j] = home[map[j]]; RedoMyLink(ctrl, egraph, ehome, me, you, sr_flows, &sr_cost, &sr_lbavg); if (ncon <= 4) { sr_where = egraph->where; egraph->where = diff_where; nswaps = BalanceMyLink(ctrl, egraph, ehome, me, you, diff_flows, maxdiff, &diff_cost, &diff_lbavg, 1.0/(real_t)nvtxs); if ((sr_lbavg < diff_lbavg && (diff_lbavg >= ubavg-1.0 || sr_cost == diff_cost)) || (sr_lbavg < ubavg-1.0 && sr_cost < diff_cost)) { for (i=0; i<egraph->nvtxs; i++) where[map[i]] = sr_where[i]; } else { for (i=0; i<egraph->nvtxs; i++) where[map[i]] = diff_where[i]; } } else { for (i=0; i<egraph->nvtxs; i++) where[map[i]] = egraph->where[i]; } gk_free((void **)&egraph->xadj, &egraph->nvwgt, &egraph->adjncy, &egraph, LTERM); } /* Pack the flow data */ iset(nvtxs, UNMATCHED, sbuffer); for (i=0; i<nvtxs; i++) { domain = where[i]; if (domain == you || domain == me) sbuffer[pack[i]] = where[i]; } } /* Broadcast the flow data */ gkMPI_Allgatherv((void *)&sbuffer[rdispl[mype]], rcount[mype], IDX_T, (void *)rbuffer, rcount, rdispl, IDX_T, ctrl->comm); /* Unpack the flow data */ for (i=0; i<rdispl[npes]; i++) { if (rbuffer[i] != UNMATCHED) where[unpack[i]] = rbuffer[i]; } /* Do other stuff */ gkMPI_Allreduce((void *)visited, (void *)gvisited, matrix.nnzs, IDX_T, MPI_MAX, ctrl->comm); nvisited = isum(matrix.nnzs, gvisited, 1)/2; tnswaps += GlobalSESum(ctrl, nswaps); if (iter++ == NGD_PASSES) break; } /* perform serial refinement */ Mc_ComputeSerialPartitionParams(ctrl, graph, nparts); Mc_SerialKWayAdaptRefine(ctrl, graph, nparts, home, ctrl->ubvec, 10); /* check for early breakout */ for (h=0; h<ncon; h++) { lbvec[h] = (real_t)(nparts) * npwgts[rargmax_strd(nparts,npwgts+h,ncon)*ncon+h]; } lbavg = ravg(ncon, lbvec); done = 0; if (tnswaps == 0 || lbavg >= oldlbavg || lbavg <= ubavg + 0.035) done = 1; alldone = GlobalSEMax(ctrl, done); if (alldone == 1) break; } /* ensure that all subdomains have at least one vertex */ /* iset(nparts, 0, match); for (i=0; i<nvtxs; i++) match[where[i]]++; done = 0; while (done == 0) { done = 1; me = iargmin(nparts, match); if (match[me] == 0) { if (ctrl->mype == PE) printf("WARNING: empty subdomain %"PRIDX" in Mc_Diffusion\n", me); you = iargmax(nparts, match); for (i=0; i<nvtxs; i++) { if (where[i] == you) { where[i] = me; match[you]--; match[me]++; done = 0; break; } } } } */ /* now free memory and return */ gk_free((void **)&workspace, (void **)&graph->ckrinfo, LTERM); graph->gnpwgts = NULL; graph->ckrinfo = NULL; WCOREPOP; return 0; } /************************************************************************* * This function extracts a subgraph from a graph given an indicator array. **************************************************************************/ graph_t *ExtractGraph(ctrl_t *ctrl, graph_t *graph, idx_t *indicator, idx_t *map, idx_t *rmap) { idx_t h, i, j; idx_t nvtxs, envtxs, enedges, ncon; idx_t vtx, count; idx_t *xadj, *vsize, *adjncy, *adjwgt, *where; idx_t *exadj, *evsize, *eadjncy, *eadjwgt, *ewhere; real_t *nvwgt, *envwgt; graph_t *egraph; nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; nvwgt = graph->nvwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; count = 0; for (i=0; i<nvtxs; i++) { if (indicator[i] == 1) { map[count] = i; rmap[i] = count; count++; } } if (count == 0) return NULL; /*******************/ /* allocate memory */ /*******************/ egraph = CreateGraph(); envtxs = egraph->nvtxs = count; egraph->ncon = graph->ncon; exadj = egraph->xadj = imalloc(envtxs*3+1, "exadj"); ewhere = egraph->where = exadj + envtxs + 1; evsize = egraph->vsize = exadj + 2*envtxs + 1; envwgt = egraph->nvwgt = rmalloc(envtxs*ncon, "envwgt"); /************************************************/ /* compute xadj, where, nvwgt, and vsize arrays */ /************************************************/ iset(envtxs+1, 0, exadj); for (i=0; i<envtxs; i++) { vtx = map[i]; ewhere[i] = where[vtx]; for (h=0; h<ncon; h++) envwgt[i*ncon+h] = nvwgt[vtx*ncon+h]; if (ctrl->partType == ADAPTIVE_PARTITION || ctrl->partType == REFINE_PARTITION) evsize[i] = vsize[vtx]; for (j=xadj[vtx]; j<xadj[vtx+1]; j++) if (indicator[adjncy[j]] == 1) exadj[i]++; } MAKECSR(i, envtxs, exadj); /************************************/ /* compute adjncy and adjwgt arrays */ /************************************/ enedges = egraph->nedges = exadj[envtxs]; eadjncy = egraph->adjncy = imalloc(enedges*2, "eadjncy"); eadjwgt = egraph->adjwgt = eadjncy + enedges; for (i=0; i<envtxs; i++) { vtx = map[i]; for (j=xadj[vtx]; j<xadj[vtx+1]; j++) { if (indicator[adjncy[j]] == 1) { eadjncy[exadj[i]] = rmap[adjncy[j]]; eadjwgt[exadj[i]++] = adjwgt[j]; } } } for (i=envtxs; i>0; i--) exadj[i] = exadj[i-1]; exadj[0] = 0; return egraph; }
12,256
28.045024
94
c
null
ParMETIS-main/libparmetis/util.c
/* * Copyright 1997, Regents of the University of Minnesota * * util.c * * This function contains various utility routines * * Started 9/28/95 * George * * $Id: util.c 10057 2011-06-02 13:44:44Z karypis $ */ #include <parmetislib.h> /************************************************************************* * This function prints an error message and exits **************************************************************************/ void myprintf(ctrl_t *ctrl, char *f_str,...) { va_list argp; fprintf(stdout, "[%2"PRIDX"] ", ctrl->mype); va_start(argp, f_str); vfprintf(stdout, f_str, argp); va_end(argp); if (strlen(f_str) == 0 || f_str[strlen(f_str)-1] != '\n') fprintf(stdout,"\n"); fflush(stdout); } /************************************************************************* * This function prints an error message and exits **************************************************************************/ void rprintf(ctrl_t *ctrl, char *f_str,...) { va_list argp; if (ctrl->mype == 0) { va_start(argp, f_str); vfprintf(stdout, f_str, argp); va_end(argp); } fflush(stdout); gkMPI_Barrier(ctrl->comm); } /************************************************************************* * This function does a binary search on an array for a key and returns * the index **************************************************************************/ idx_t BSearch(idx_t n, idx_t *array, idx_t key) { idx_t a=0, b=n, c; while (b-a > 8) { c = (a+b)>>1; if (array[c] > key) b = c; else a = c; } for (c=a; c<b; c++) { if (array[c] == key) return c; } errexit("Key %"PRIDX" not found!\n", key); return 0; } /************************************************************************* * This file randomly permutes the contents of an array. * flag == 0, don't initialize perm * flag == 1, set p[i] = i **************************************************************************/ void RandomPermute(idx_t n, idx_t *p, idx_t flag) { idx_t i, u, v; idx_t tmp; if (flag == 1) { for (i=0; i<n; i++) p[i] = i; } for (i=0; i<n; i++) { v = RandomInRange(n); u = RandomInRange(n); gk_SWAP(p[v], p[u], tmp); } } /************************************************************************* * This file randomly permutes the contents of an array. * flag == 0, don't initialize perm * flag == 1, set p[i] = i **************************************************************************/ void FastRandomPermute(idx_t n, idx_t *p, idx_t flag) { idx_t i, u, v; idx_t tmp; /* this is for very small arrays */ if (n < 25) { RandomPermute(n, p, flag); return; } if (flag == 1) { for (i=0; i<n; i++) p[i] = i; } for (i=0; i<n; i+=8) { v = RandomInRange(n-4); u = RandomInRange(n-4); gk_SWAP(p[v], p[u], tmp); gk_SWAP(p[v+1], p[u+1], tmp); gk_SWAP(p[v+2], p[u+2], tmp); gk_SWAP(p[v+3], p[u+3], tmp); } } /************************************************************************* * This function returns true if the a is a power of 2 **************************************************************************/ idx_t ispow2(idx_t a) { for (; a%2 != 1; a = a>>1); return (a > 1 ? 0 : 1); } /************************************************************************* * This function returns the log2(x) **************************************************************************/ idx_t log2Int(idx_t a) { idx_t i; for (i=1; a > 1; i++, a = a>>1); return i-1; } /************************************************************************* * These functions return the index of the maximum element in a vector **************************************************************************/ size_t rargmax_strd(size_t n, real_t *x, size_t incx) { size_t i, max=0; n *= incx; for (i=incx; i<n; i+=incx) max = (x[i] > x[max] ? i : max); return max/incx; } /************************************************************************* * These functions return the index of the maximum element in a vector **************************************************************************/ size_t rargmin_strd(size_t n, real_t *x, size_t incx) { size_t i, min=0; n *= incx; for (i=incx; i<n; i+=incx) min = (x[i] < x[min] ? i : min); return min/incx; } /************************************************************************* * These functions return the index of the almost maximum element in a vector **************************************************************************/ size_t rargmax2(size_t n, real_t *x) { size_t i, max1, max2; if (x[0] > x[1]) { max1 = 0; max2 = 1; } else { max1 = 1; max2 = 0; } for (i=2; i<n; i++) { if (x[i] > x[max1]) { max2 = max1; max1 = i; } else if (x[i] > x[max2]) max2 = i; } return max2; } /************************************************************************* * This function returns the average value of an array **************************************************************************/ real_t ravg(size_t n, real_t *x) { size_t i; real_t retval = 0.0; for (i=0; i<n; i++) retval += x[i]; return retval/n; } /************************************************************************* * These functions return the index of the maximum element in a vector **************************************************************************/ real_t rfavg(size_t n, real_t *x) { size_t i; real_t total = 0.0; if (n == 0) return 0.0; for (i=0; i<n; i++) total += fabs(x[i]); return total/n; } /************************************************************************* * This function checks if v+u2 provides a better balance in the weight * vector that v+u1 **************************************************************************/ real_t BetterVBalance(idx_t ncon, real_t *vwgt, real_t *u1wgt, real_t *u2wgt) { idx_t i; real_t sum1, sum2, diff1, diff2; if (ncon == 1) return u1wgt[0] - u1wgt[0]; sum1 = sum2 = 0.0; for (i=0; i<ncon; i++) { sum1 += vwgt[i]+u1wgt[i]; sum2 += vwgt[i]+u2wgt[i]; } sum1 = sum1/(1.0*ncon); sum2 = sum2/(1.0*ncon); diff1 = diff2 = 0.0; for (i=0; i<ncon; i++) { diff1 += fabs(sum1 - (vwgt[i]+u1wgt[i])); diff2 += fabs(sum2 - (vwgt[i]+u2wgt[i])); } return diff1 - diff2; } /************************************************************************* * This function checks if the pairwise balance of the between the two * partitions will improve by moving the vertex v from pfrom to pto, * subject to the target partition weights of tfrom, and tto respectively **************************************************************************/ idx_t IsHBalanceBetterFT(idx_t ncon, real_t *pfrom, real_t *pto, real_t *nvwgt, real_t *ubvec) { idx_t i; real_t blb1=0.0, alb1=0.0, sblb=0.0, salb=0.0; real_t blb2=0.0, alb2=0.0; real_t temp; for (i=0; i<ncon; i++) { temp =gk_max(pfrom[i], pto[i])/ubvec[i]; if (blb1 < temp) { blb2 = blb1; blb1 = temp; } else if (blb2 < temp) blb2 = temp; sblb += temp; temp =gk_max(pfrom[i]-nvwgt[i], pto[i]+nvwgt[i])/ubvec[i]; if (alb1 < temp) { alb2 = alb1; alb1 = temp; } else if (alb2 < temp) alb2 = temp; salb += temp; } if (alb1 < blb1) return 1; if (blb1 < alb1) return 0; if (alb2 < blb2) return 1; if (blb2 < alb2) return 0; return salb < sblb; } /************************************************************************* * This function checks if it will be better to move a vertex to pt2 than * to pt1 subject to their target weights of tt1 and tt2, respectively * This routine takes into account the weight of the vertex in question **************************************************************************/ idx_t IsHBalanceBetterTT(idx_t ncon, real_t *pt1, real_t *pt2, real_t *nvwgt, real_t *ubvec) { idx_t i; real_t m11=0.0, m12=0.0, m21=0.0, m22=0.0, sm1=0.0, sm2=0.0, temp; for (i=0; i<ncon; i++) { temp = (pt1[i]+nvwgt[i])/ubvec[i]; if (m11 < temp) { m12 = m11; m11 = temp; } else if (m12 < temp) m12 = temp; sm1 += temp; temp = (pt2[i]+nvwgt[i])/ubvec[i]; if (m21 < temp) { m22 = m21; m21 = temp; } else if (m22 < temp) m22 = temp; sm2 += temp; } if (m21 < m11) return 1; if (m21 > m11) return 0; if (m22 < m12) return 1; if (m22 > m12) return 0; return sm2 < sm1; } /************************************************************************* * This function computes the top three values of a real_t array **************************************************************************/ void GetThreeMax(idx_t n, real_t *x, idx_t *first, idx_t *second, idx_t *third) { idx_t i; if (n <= 0) { *first = *second = *third = -1; return; } *second = *third = -1; *first = 0; for (i=1; i<n; i++) { if (x[i] > x[*first]) { *third = *second; *second = *first; *first = i; continue; } if (*second == -1 || x[i] > x[*second]) { *third = *second; *second = i; continue; } if (*third == -1 || x[i] > x[*third]) *third = i; } return; }
9,302
22.027228
94
c
null
ParMETIS-main/libparmetis/gkmpi.c
/* * Copyright 1997, Regents of the University of Minnesota * * gkmpi.c * * This function contains wrappers around MPI calls to allow * future de-coupling of sizes from 'int' datatypes. * * Started 5/30/11 * George * * $Id: gkmpi.c 10022 2011-05-30 20:18:42Z karypis $ */ #include <parmetislib.h> int gkMPI_Comm_size(MPI_Comm comm, idx_t *size) { int status, lsize; status = MPI_Comm_size(comm, &lsize); *size = lsize; return status; } int gkMPI_Comm_rank(MPI_Comm comm, idx_t *rank) { int status, lrank; status = MPI_Comm_rank(comm, &lrank); *rank = lrank; return status; } int gkMPI_Get_count(MPI_Status *status, MPI_Datatype datatype, idx_t *count) { int rstatus; #if MPI_VERSION < 4 int lcount; rstatus = MPI_Get_count(status, datatype, &lcount); #else MPI_Count lcount; rstatus = MPI_Get_count_c(status, datatype, &lcount); #endif *count = lcount; return rstatus; } int gkMPI_Send(void *buf, idx_t count, MPI_Datatype datatype, idx_t dest, idx_t tag, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Send(buf, count, datatype, dest, tag, comm); #else return MPI_Send_c(buf, count, datatype, dest, tag, comm); #endif } int gkMPI_Recv(void *buf, idx_t count, MPI_Datatype datatype, idx_t source, idx_t tag, MPI_Comm comm, MPI_Status *status) { #if MPI_VERSION < 4 return MPI_Recv(buf, count, datatype, source, tag, comm, status); #else return MPI_Recv_c(buf, count, datatype, source, tag, comm, status); #endif } int gkMPI_Isend(void *buf, idx_t count, MPI_Datatype datatype, idx_t dest, idx_t tag, MPI_Comm comm, MPI_Request *request) { #if MPI_VERSION < 4 return MPI_Isend(buf, count, datatype, dest, tag, comm, request); #else return MPI_Isend_c(buf, count, datatype, dest, tag, comm, request); #endif } int gkMPI_Irecv(void *buf, idx_t count, MPI_Datatype datatype, idx_t source, idx_t tag, MPI_Comm comm, MPI_Request *request) { #if MPI_VERSION < 4 return MPI_Irecv(buf, count, datatype, source, tag, comm, request); #else return MPI_Irecv_c(buf, count, datatype, source, tag, comm, request); #endif } int gkMPI_Wait(MPI_Request *request, MPI_Status *status) { return MPI_Wait(request, status); } int gkMPI_Waitall(idx_t count, MPI_Request *array_of_requests, MPI_Status *array_of_statuses) { return MPI_Waitall(count, array_of_requests, array_of_statuses); } int gkMPI_Barrier(MPI_Comm comm) { return MPI_Barrier(comm); } int gkMPI_Bcast(void *buffer, idx_t count, MPI_Datatype datatype, idx_t root, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Bcast(buffer, count, datatype, root, comm); #else return MPI_Bcast_c(buffer, count, datatype, root, comm); #endif } int gkMPI_Reduce(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, idx_t root, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Reduce(sendbuf, recvbuf, count, datatype, op, root, comm); #else return MPI_Reduce_c(sendbuf, recvbuf, count, datatype, op, root, comm); #endif } int gkMPI_Allreduce(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, comm); #else return MPI_Allreduce_c(sendbuf, recvbuf, count, datatype, op, comm); #endif } int gkMPI_Scan(void *sendbuf, void *recvbuf, idx_t count, MPI_Datatype datatype, MPI_Op op, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Scan(sendbuf, recvbuf, count, datatype, op, comm); #else return MPI_Scan_c(sendbuf, recvbuf, count, datatype, op, comm); #endif } int gkMPI_Allgather(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Allgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); #else return MPI_Allgather_c(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); #endif } int gkMPI_Alltoall(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, MPI_Comm comm) { #if MPI_VERSION < 4 return MPI_Alltoall(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); #else return MPI_Alltoall_c(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm); #endif } int gkMPI_Alltoallv(void *sendbuf, idx_t *sendcounts, idx_t *sdispls, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *rdispls, MPI_Datatype recvtype, MPI_Comm comm) { #if MPI_VERSION < 4 #if IDXTYPEWIDTH == 32 return MPI_Alltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #else idx_t i; int status, npes, *lsendcounts, *lsdispls, *lrecvcounts, *lrdispls; MPI_Comm_size(comm, &npes); /* bail-out if MPI 3.x cannot handle such large counts */ for (i=0; i<npes; i++) { if (sendcounts[i] >= INT_MAX || sdispls[i] >= INT_MAX || recvcounts[i] >= INT_MAX || rdispls[i] >= INT_MAX) errexit("MPI_Gatherv message sizes goes over INT_MAX. Use MPI 4.x\n"); } lsendcounts = gk_imalloc(npes, "lsendcounts"); lsdispls = gk_imalloc(npes, "lsdispls"); lrecvcounts = gk_imalloc(npes, "lrecvcounts"); lrdispls = gk_imalloc(npes, "lrdispls"); for (i=0; i<npes; i++) { lsendcounts[i] = sendcounts[i]; lsdispls[i] = sdispls[i]; lrecvcounts[i] = recvcounts[i]; lrdispls[i] = rdispls[i]; } status = MPI_Alltoallv(sendbuf, lsendcounts, lsdispls, sendtype, recvbuf, lrecvcounts, lrdispls, recvtype, comm); for (i=0; i<npes; i++) { sendcounts[i] = lsendcounts[i]; sdispls[i] = lsdispls[i]; recvcounts[i] = lrecvcounts[i]; rdispls[i] = lrdispls[i]; } gk_free((void **)&lsendcounts, &lrecvcounts, &lsdispls, &lrdispls, LTERM); return status; #endif #else #if IDXTYPEWIDTH == 32 return MPI_Alltoallv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #else return MPI_Alltoallv_c(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #endif #endif } int gkMPI_Allgatherv(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *rdispls, MPI_Datatype recvtype, MPI_Comm comm) { #if MPI_VERSION < 4 #if IDXTYPEWIDTH == 32 return MPI_Allgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #else idx_t i; int status, npes, *lrecvcounts, *lrdispls; MPI_Comm_size(comm, &npes); /* bail-out if MPI 3.x cannot handle such large counts */ for (i=0; i<npes; i++) { if (sendcount >= INT_MAX || recvcounts[i] >= INT_MAX || rdispls[i] >= INT_MAX) errexit("MPI_Allgatherv message sizes goes over INT_MAX. Use MPI 4.x\n"); } lrecvcounts = gk_imalloc(npes, "lrecvcounts"); lrdispls = gk_imalloc(npes, "lrdispls"); for (i=0; i<npes; i++) { lrecvcounts[i] = recvcounts[i]; lrdispls[i] = rdispls[i]; } status = MPI_Allgatherv(sendbuf, sendcount, sendtype, recvbuf, lrecvcounts, lrdispls, recvtype, comm); for (i=0; i<npes; i++) { recvcounts[i] = lrecvcounts[i]; rdispls[i] = lrdispls[i]; } gk_free((void **)&lrecvcounts, &lrdispls, LTERM); return status; #endif #else #if IDXTYPEWIDTH == 32 return MPI_Allgatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #else return MPI_Allgatherv_c(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, comm); #endif #endif } int gkMPI_Scatterv(void *sendbuf, idx_t *sendcounts, idx_t *sdispls, MPI_Datatype sendtype, void *recvbuf, idx_t recvcount, MPI_Datatype recvtype, idx_t root, MPI_Comm comm) { #if MPI_VERSION < 4 #if IDXTYPEWIDTH == 32 return MPI_Scatterv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcount, recvtype, root, comm); #else idx_t i; int status, npes, *lsendcounts, *lsdispls; MPI_Comm_size(comm, &npes); /* bail-out if MPI 3.x cannot handle such large counts */ for (i=0; i<npes; i++) { if (sendcounts[i] >= INT_MAX || recvcount >= INT_MAX || sdispls[i] >= INT_MAX) errexit("MPI_Scatterv message sizes goes over INT_MAX. Use MPI 4.x\n"); } lsendcounts = gk_imalloc(npes, "lsendcounts"); lsdispls = gk_imalloc(npes, "lsdispls"); for (i=0; i<npes; i++) { lsendcounts[i] = sendcounts[i]; lsdispls[i] = sdispls[i]; } status = MPI_Scatterv(sendbuf, lsendcounts, lsdispls, sendtype, recvbuf, recvcount, recvtype, root, comm); for (i=0; i<npes; i++) { sendcounts[i] = lsendcounts[i]; sdispls[i] = lsdispls[i]; } gk_free((void **)&lsendcounts, &lsdispls, LTERM); return status; #endif #else #if IDXTYPEWIDTH == 32 return MPI_Scatterv(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcount, recvtype, root, comm); #else return MPI_Scatterv_c(sendbuf, sendcounts, sdispls, sendtype, recvbuf, recvcount, recvtype, root, comm); #endif #endif } int gkMPI_Gatherv(void *sendbuf, idx_t sendcount, MPI_Datatype sendtype, void *recvbuf, idx_t *recvcounts, idx_t *rdispls, MPI_Datatype recvtype, idx_t root, MPI_Comm comm) { #if MPI_VERSION < 4 #if IDXTYPEWIDTH == 32 return MPI_Gatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, root, comm); #else idx_t i; int status, npes, *lrecvcounts, *lrdispls; MPI_Comm_size(comm, &npes); /* bail-out if MPI 3.x cannot handle such large counts */ for (i=0; i<npes; i++) { if (sendcount >= INT_MAX || recvcounts[i] >= INT_MAX || rdispls[i] >= INT_MAX) errexit("MPI_Gatherv message sizes goes over INT_MAX. Use MPI 4.x\n"); } lrecvcounts = gk_imalloc(npes, "lrecvcounts"); lrdispls = gk_imalloc(npes, "lrdispls"); for (i=0; i<npes; i++) { lrecvcounts[i] = recvcounts[i]; lrdispls[i] = rdispls[i]; } status = MPI_Gatherv(sendbuf, sendcount, sendtype, recvbuf, lrecvcounts, lrdispls, recvtype, root, comm); for (i=0; i<npes; i++) { recvcounts[i] = lrecvcounts[i]; rdispls[i] = lrdispls[i]; } gk_free((void **)&lrecvcounts, &lrdispls, LTERM); return status; #endif #else #if IDXTYPEWIDTH == 32 return MPI_Gatherv(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, root, comm); #else return MPI_Gatherv_c(sendbuf, sendcount, sendtype, recvbuf, recvcounts, rdispls, recvtype, root, comm); #endif #endif } int gkMPI_Comm_split(MPI_Comm comm, idx_t color, idx_t key, MPI_Comm *newcomm) { return MPI_Comm_split(comm, color, key, newcomm); } int gkMPI_Comm_free(MPI_Comm *comm) { return MPI_Comm_free(comm); } int gkMPI_Finalize() { return MPI_Finalize(); }
11,037
26.254321
82
c
null
ParMETIS-main/libparmetis/pspases.c
/* * pspases.c * * This file contains ordering routines that are to be used with the * parallel Cholesky factorization code PSPASES * * Started 10/14/97 * George * * $Id: pspases.c 10535 2011-07-11 04:29:44Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the serial ordering algorithm. ************************************************************************************/ int ParMETIS_SerialNodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm) { idx_t i, npes, mype; ctrl_t *ctrl=NULL; graph_t *agraph=NULL; idx_t *perm=NULL, *iperm=NULL; idx_t *sendcount, *displs; /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_OMETIS, options, 1, 1, NULL, NULL, *comm); npes = ctrl->npes; mype = ctrl->mype; if (!ispow2(npes)) { if (mype == 0) printf("Error: The number of processors must be a power of 2!\n"); FreeCtrl(&ctrl); return METIS_ERROR; } if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 1); STARTTIMER(ctrl, ctrl->TotalTmr); STARTTIMER(ctrl, ctrl->MoveTmr); agraph = AssembleEntireGraph(ctrl, vtxdist, xadj, adjncy); STOPTIMER(ctrl, ctrl->MoveTmr); if (mype == 0) { perm = imalloc(agraph->nvtxs, "PAROMETISS: perm"); iperm = imalloc(agraph->nvtxs, "PAROMETISS: iperm"); METIS_NodeNDP(agraph->nvtxs, agraph->xadj, agraph->adjncy, agraph->vwgt, npes, NULL, perm, iperm, sizes); } STARTTIMER(ctrl, ctrl->MoveTmr); /* Broadcast the sizes array */ gkMPI_Bcast((void *)sizes, 2*npes, IDX_T, 0, ctrl->gcomm); /* Scatter the iperm */ sendcount = imalloc(npes, "PAROMETISS: sendcount"); displs = imalloc(npes, "PAROMETISS: displs"); for (i=0; i<npes; i++) { sendcount[i] = vtxdist[i+1]-vtxdist[i]; displs[i] = vtxdist[i]; } gkMPI_Scatterv((void *)iperm, sendcount, displs, IDX_T, (void *)order, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, ctrl->gcomm); STOPTIMER(ctrl, ctrl->MoveTmr); STOPTIMER(ctrl, ctrl->TotalTmr); IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); gk_free((void **)&agraph->xadj, &agraph->adjncy, &perm, &iperm, &sendcount, &displs, &agraph, LTERM); if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, order, npes, mype, 0); goto DONE; DONE: FreeCtrl(&ctrl); return METIS_OK; } /************************************************************************* * This function assembles the graph into a single processor **************************************************************************/ graph_t *AssembleEntireGraph(ctrl_t *ctrl, idx_t *vtxdist, idx_t *xadj, idx_t *adjncy) { idx_t i, gnvtxs, nvtxs, gnedges, nedges; idx_t npes = ctrl->npes, mype = ctrl->mype; idx_t *axadj, *aadjncy; idx_t *recvcounts, *displs; graph_t *agraph; gnvtxs = vtxdist[npes]; nvtxs = vtxdist[mype+1]-vtxdist[mype]; nedges = xadj[nvtxs]; recvcounts = imalloc(npes, "AssembleGraph: recvcounts"); displs = imalloc(npes+1, "AssembleGraph: displs"); /* Gather all the xadj arrays first */ for (i=0; i<nvtxs; i++) xadj[i] = xadj[i+1]-xadj[i]; axadj = imalloc(gnvtxs+1, "AssembleEntireGraph: axadj"); for (i=0; i<npes; i++) { recvcounts[i] = vtxdist[i+1]-vtxdist[i]; displs[i] = vtxdist[i]; } /* Assemble the xadj and then the adjncy */ gkMPI_Gatherv((void *)xadj, nvtxs, IDX_T, axadj, recvcounts, displs, IDX_T, 0, ctrl->comm); MAKECSR(i, nvtxs, xadj); MAKECSR(i, gnvtxs, axadj); /* Gather all the adjncy arrays next */ /* Determine the # of edges stored at each processor */ gkMPI_Allgather((void *)(&nedges), 1, IDX_T, (void *)recvcounts, 1, IDX_T, ctrl->comm); displs[0] = 0; for (i=1; i<npes+1; i++) displs[i] = displs[i-1] + recvcounts[i-1]; gnedges = displs[npes]; aadjncy = imalloc(gnedges, "AssembleEntireGraph: aadjncy"); /* Assemble the xadj and then the adjncy */ gkMPI_Gatherv((void *)adjncy, nedges, IDX_T, aadjncy, recvcounts, displs, IDX_T, 0, ctrl->comm); /* myprintf(ctrl, "Gnvtxs: %"PRIDX", Gnedges: %"PRIDX"\n", gnvtxs, gnedges); */ agraph = CreateGraph(); agraph->nvtxs = gnvtxs; agraph->nedges = gnedges; agraph->xadj = axadj; agraph->adjncy = aadjncy; return agraph; }
4,467
27.458599
98
c
null
ParMETIS-main/libparmetis/rename.h
#ifndef _LIBPARMETIS_RENAME_H_ #define _LIBPARMETIS_RENAME_H_ #define KWayAdaptiveRefine libparmetis__KWayAdaptiveRefine #define Adaptive_Partition libparmetis__Adaptive_Partition #define BalanceMyLink libparmetis__BalanceMyLink #define CommChangedInterfaceData libparmetis__CommChangedInterfaceData #define CommInterfaceData libparmetis__CommInterfaceData #define CommSetup libparmetis__CommSetup #define CommUpdateNnbrs libparmetis__CommUpdateNnbrs #define GlobalSEMax libparmetis__GlobalSEMax #define GlobalSEMaxComm libparmetis__GlobalSEMaxComm #define GlobalSEMaxFloat libparmetis__GlobalSEMaxFloat #define GlobalSEMin libparmetis__GlobalSEMin #define GlobalSEMinComm libparmetis__GlobalSEMinComm #define GlobalSEMinFloat libparmetis__GlobalSEMinFloat #define GlobalSESum libparmetis__GlobalSESum #define GlobalSESumComm libparmetis__GlobalSESumComm #define GlobalSESumFloat libparmetis__GlobalSESumFloat #define CSR_Match_SHEM libparmetis__CSR_Match_SHEM #define FreeCtrl libparmetis__FreeCtrl #define SetupCtrl libparmetis__SetupCtrl #define SetupCtrl_invtvwgts libparmetis__SetupCtrl_invtvwgts #define PrintGraph libparmetis__PrintGraph #define PrintGraph2 libparmetis__PrintGraph2 #define PrintPairs libparmetis__PrintPairs #define PrintSetUpInfo libparmetis__PrintSetUpInfo #define PrintTransferedGraphs libparmetis__PrintTransferedGraphs #define PrintVector libparmetis__PrintVector #define PrintVector2 libparmetis__PrintVector2 #define WriteMetisGraph libparmetis__WriteMetisGraph #define ComputeLoad libparmetis__ComputeLoad #define ComputeTransferVector libparmetis__ComputeTransferVector #define ConjGrad2 libparmetis__ConjGrad2 #define Mc_ComputeMoveStatistics libparmetis__Mc_ComputeMoveStatistics #define Mc_ComputeSerialTotalV libparmetis__Mc_ComputeSerialTotalV #define SetUpConnectGraph libparmetis__SetUpConnectGraph #define mvMult2 libparmetis__mvMult2 #define gkMPI_Allgather libparmetis__gkMPI_Allgather #define gkMPI_Allgatherv libparmetis__gkMPI_Allgatherv #define gkMPI_Allreduce libparmetis__gkMPI_Allreduce #define gkMPI_Alltoall libparmetis__gkMPI_Alltoall #define gkMPI_Alltoallv libparmetis__gkMPI_Alltoallv #define gkMPI_Barrier libparmetis__gkMPI_Barrier #define gkMPI_Bcast libparmetis__gkMPI_Bcast #define gkMPI_Comm_free libparmetis__gkMPI_Comm_free #define gkMPI_Comm_rank libparmetis__gkMPI_Comm_rank #define gkMPI_Comm_size libparmetis__gkMPI_Comm_size #define gkMPI_Comm_split libparmetis__gkMPI_Comm_split #define gkMPI_Finalize libparmetis__gkMPI_Finalize #define gkMPI_Gatherv libparmetis__gkMPI_Gatherv #define gkMPI_Get_count libparmetis__gkMPI_Get_count #define gkMPI_Irecv libparmetis__gkMPI_Irecv #define gkMPI_Isend libparmetis__gkMPI_Isend #define gkMPI_Recv libparmetis__gkMPI_Recv #define gkMPI_Reduce libparmetis__gkMPI_Reduce #define gkMPI_Scan libparmetis__gkMPI_Scan #define gkMPI_Scatterv libparmetis__gkMPI_Scatterv #define gkMPI_Send libparmetis__gkMPI_Send #define gkMPI_Wait libparmetis__gkMPI_Wait #define gkMPI_Waitall libparmetis__gkMPI_Waitall #define CreateGraph libparmetis__CreateGraph #define FreeGraph libparmetis__FreeGraph #define FreeInitialGraphAndRemap libparmetis__FreeInitialGraphAndRemap #define FreeNonGraphFields libparmetis__FreeNonGraphFields #define FreeNonGraphNonSetupFields libparmetis__FreeNonGraphNonSetupFields #define InitGraph libparmetis__InitGraph #define SetupGraph libparmetis__SetupGraph #define SetupGraph_nvwgts libparmetis__SetupGraph_nvwgts #define AssembleAdaptiveGraph libparmetis__AssembleAdaptiveGraph #define Balance_Partition libparmetis__Balance_Partition #define AssembleMultisectedGraph libparmetis__AssembleMultisectedGraph #define InitMultisection libparmetis__InitMultisection #define InitPartition libparmetis__InitPartition #define KeepPart libparmetis__KeepPart #define Global_Partition libparmetis__Global_Partition #define ComputePartitionParams libparmetis__ComputePartitionParams #define KWayBalance libparmetis__KWayBalance #define KWayFM libparmetis__KWayFM #define ProjectPartition libparmetis__ProjectPartition #define CreateCoarseGraph_Global libparmetis__CreateCoarseGraph_Global #define CreateCoarseGraph_Local libparmetis__CreateCoarseGraph_Local #define Match_Global libparmetis__Match_Global #define Match_Local libparmetis__Match_Local #define ExtractGraph libparmetis__ExtractGraph #define Mc_Diffusion libparmetis__Mc_Diffusion #define CheckMGraph libparmetis__CheckMGraph #define FindVtxPerm libparmetis__FindVtxPerm #define MoveGraph libparmetis__MoveGraph #define ProjectInfoBack libparmetis__ProjectInfoBack #define CreateMesh libparmetis__CreateMesh #define InitMesh libparmetis__InitMesh #define SetUpMesh libparmetis__SetUpMesh #define AllocateNodePartitionParams libparmetis__AllocateNodePartitionParams #define ComputeNodePartitionParams libparmetis__ComputeNodePartitionParams #define KWayNodeRefine2Phase libparmetis__KWayNodeRefine2Phase #define KWayNodeRefineInterior libparmetis__KWayNodeRefineInterior #define KWayNodeRefine_Greedy libparmetis__KWayNodeRefine_Greedy #define PrintNodeBalanceInfo libparmetis__PrintNodeBalanceInfo #define UpdateNodePartitionParams libparmetis__UpdateNodePartitionParams #define CompactGraph libparmetis__CompactGraph #define LabelSeparators libparmetis__LabelSeparators #define LocalNDOrder libparmetis__LocalNDOrder #define MultilevelOrder libparmetis__MultilevelOrder #define Order_Partition libparmetis__Order_Partition #define Order_Partition_Multiple libparmetis__Order_Partition_Multiple #define AssembleEntireGraph libparmetis__AssembleEntireGraph #define RedoMyLink libparmetis__RedoMyLink #define ParallelReMapGraph libparmetis__ParallelReMapGraph #define ParallelTotalVReMap libparmetis__ParallelTotalVReMap #define SimilarTpwgts libparmetis__SimilarTpwgts #define ChangeNumbering libparmetis__ChangeNumbering #define ChangeNumberingMesh libparmetis__ChangeNumberingMesh #define Mc_DynamicSelectQueue libparmetis__Mc_DynamicSelectQueue #define Mc_HashVRank libparmetis__Mc_HashVRank #define Mc_HashVwgts libparmetis__Mc_HashVwgts #define AreAllHVwgtsBelow libparmetis__AreAllHVwgtsBelow #define ComputeHKWayLoadImbalance libparmetis__ComputeHKWayLoadImbalance #define ComputeSerialEdgeCut libparmetis__ComputeSerialEdgeCut #define ComputeSerialTotalV libparmetis__ComputeSerialTotalV #define Mc_ComputeSerialPartitionParams libparmetis__Mc_ComputeSerialPartitionParams #define Mc_SerialKWayAdaptRefine libparmetis__Mc_SerialKWayAdaptRefine #define Mc_Serial_Balance2Way libparmetis__Mc_Serial_Balance2Way #define Mc_Serial_Compute2WayPartitionParams libparmetis__Mc_Serial_Compute2WayPartitionParams #define Mc_Serial_FM_2WayRefine libparmetis__Mc_Serial_FM_2WayRefine #define Mc_Serial_Init2WayBalance libparmetis__Mc_Serial_Init2WayBalance #define SSMIncKeyCmp libparmetis__SSMIncKeyCmp #define SerialRemap libparmetis__SerialRemap #define Serial_AreAnyVwgtsBelow libparmetis__Serial_AreAnyVwgtsBelow #define Serial_BetterBalance libparmetis__Serial_BetterBalance #define Serial_Compute2WayHLoadImbalance libparmetis__Serial_Compute2WayHLoadImbalance #define Serial_SelectQueue libparmetis__Serial_SelectQueue #define Serial_SelectQueueOneWay libparmetis__Serial_SelectQueueOneWay #define ComputeMoveStatistics libparmetis__ComputeMoveStatistics #define ComputeParallelBalance libparmetis__ComputeParallelBalance #define ComputeSerialBalance libparmetis__ComputeSerialBalance #define Mc_PrintThrottleMatrix libparmetis__Mc_PrintThrottleMatrix #define PrintPostPartInfo libparmetis__PrintPostPartInfo #define InitTimers libparmetis__InitTimers #define PrintTimer libparmetis__PrintTimer #define PrintTimingInfo libparmetis__PrintTimingInfo #define BSearch libparmetis__BSearch #define BetterVBalance libparmetis__BetterVBalance #define FastRandomPermute libparmetis__FastRandomPermute #define GetThreeMax libparmetis__GetThreeMax #define IsHBalanceBetterFT libparmetis__IsHBalanceBetterFT #define IsHBalanceBetterTT libparmetis__IsHBalanceBetterTT #define RandomPermute libparmetis__RandomPermute #define ispow2 libparmetis__ispow2 #define log2Int libparmetis__log2Int #define myprintf libparmetis__myprintf #define rargmax2 libparmetis__rargmax2 #define rargmax_strd libparmetis__rargmax_strd #define rargmin_strd libparmetis__rargmin_strd #define ravg libparmetis__ravg #define rfavg libparmetis__rfavg #define rprintf libparmetis__rprintf #define WavefrontDiffusion libparmetis__WavefrontDiffusion #define CheckInputsAdaptiveRepart libparmetis__CheckInputsAdaptiveRepart #define CheckInputsNodeND libparmetis__CheckInputsNodeND #define CheckInputsPartGeom libparmetis__CheckInputsPartGeom #define CheckInputsPartGeomKway libparmetis__CheckInputsPartGeomKway #define CheckInputsPartKway libparmetis__CheckInputsPartKway #define CheckInputsPartMeshKway libparmetis__CheckInputsPartMeshKway #define PartitionSmallGraph libparmetis__PartitionSmallGraph #define AllocateRefinementWorkSpace libparmetis__AllocateRefinementWorkSpace #define AllocateWSpace libparmetis__AllocateWSpace #define FreeWSpace libparmetis__FreeWSpace #define cnbrpoolGetNext libparmetis__cnbrpoolGetNext #define cnbrpoolReset libparmetis__cnbrpoolReset #define ikvwspacemalloc libparmetis__ikvwspacemalloc #define iwspacemalloc libparmetis__iwspacemalloc #define rkvwspacemalloc libparmetis__rkvwspacemalloc #define rwspacemalloc libparmetis__rwspacemalloc #define wspacemalloc libparmetis__wspacemalloc #define Coordinate_Partition libparmetis__Coordinate_Partition #define IRBinCoordinates libparmetis__IRBinCoordinates #define PseudoSampleSort libparmetis__PseudoSampleSort #define RBBinCoordinates libparmetis__RBBinCoordinates #define SampleSort libparmetis__SampleSort #endif
9,650
51.737705
94
h
null
ParMETIS-main/libparmetis/gklib_defs.h
/*! \file \brief Data structures and prototypes for GKlib integration \date Started 12/23/2008 \author George \version\verbatim $Id: gklib_defs.h 10395 2011-06-23 23:28:06Z karypis $ \endverbatim */ #ifndef _LIBPARMETIS_GKLIB_H_ #define _LIBPARMETIS_GKLIB_H_ #include "gklib_rename.h" /*************************************************************************/ /*! Stores a weighted edge */ /*************************************************************************/ typedef struct { idx_t u, v, w; /*!< Edge (u,v) with weight w */ } uvw_t; /************************************************************************* * Define various data structure using GKlib's templates. **************************************************************************/ GK_MKKEYVALUE_T(ikv_t, idx_t, idx_t) GK_MKKEYVALUE_T(rkv_t, real_t, idx_t) GK_MKPQUEUE_T(ipq_t, ikv_t) GK_MKPQUEUE_T(rpq_t, rkv_t) /* gklib.c */ GK_MKBLAS_PROTO(i, idx_t, idx_t) GK_MKBLAS_PROTO(r, real_t, real_t) GK_MKALLOC_PROTO(i, idx_t) GK_MKALLOC_PROTO(r, real_t) GK_MKALLOC_PROTO(ikv, ikv_t) GK_MKALLOC_PROTO(rkv, rkv_t) GK_MKPQUEUE_PROTO(ipq, ipq_t, idx_t, idx_t) GK_MKPQUEUE_PROTO(rpq, rpq_t, real_t, idx_t) GK_MKRANDOM_PROTO(i, idx_t, idx_t) GK_MKARRAY2CSR_PROTO(i, idx_t) void isorti(size_t n, idx_t *base); void isortd(size_t n, idx_t *base); void rsorti(size_t n, real_t *base); void rsortd(size_t n, real_t *base); void ikvsorti(size_t n, ikv_t *base); void ikvsortii(size_t n, ikv_t *base); void ikvsortd(size_t n, ikv_t *base); void rkvsorti(size_t n, rkv_t *base); void rkvsortd(size_t n, rkv_t *base); void uvwsorti(size_t n, uvw_t *base); #endif
1,637
29.333333
85
h
null
ParMETIS-main/libparmetis/comm.c
/* * Copyright 1997, Regents of the University of Minnesota * * comm.c * * This function provides various high level communication functions * * $Id: comm.c 10592 2011-07-16 21:17:53Z karypis $ */ #include <parmetislib.h> /*************************************************************************/ /*! This function performs the following functions: - determines the processors that contain adjacent vertices and setup the infrastructure for efficient communication. - localizes the numbering of the adjancency lists. */ /**************************************************************************/ void CommSetup(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, k, islocal, penum, gnvtxs, nvtxs, nlocal, firstvtx, lastvtx, nsend, nrecv, nnbrs, nadj; idx_t npes=ctrl->npes, mype=ctrl->mype; idx_t *vtxdist, *xadj, *adjncy; idx_t *peind, *recvptr, *recvind, *sendptr, *sendind; idx_t *imap, *lperm; idx_t *pexadj, *peadjncy, *peadjloc, *startsind; ikv_t *recvrequests, *sendrequests, *adjpairs; if (graph->lperm != NULL) return; /* The communication structure has already been setup */ STARTTIMER(ctrl, ctrl->SetupTmr); gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; lperm = graph->lperm = iincset(nvtxs, 0, imalloc(nvtxs, "CommSetup: graph->lperm")); vtxdist = graph->vtxdist; firstvtx = vtxdist[mype]; lastvtx = vtxdist[mype+1]; WCOREPUSH; /************************************************************* * Determine what you need to receive *************************************************************/ /* first pass: determine nadj and interior/interface vertices */ for (nlocal=0, nadj=0, i=0; i<nvtxs; i++) { islocal = 1; for (j=xadj[i]; j<xadj[i+1]; j++) { k = adjncy[j]; if (k < firstvtx || k >= lastvtx) { /* remote vertex */ nadj++; islocal = 0; } } if (islocal) { lperm[i] = lperm[nlocal]; lperm[nlocal++] = i; } } graph->nlocal = nlocal; adjpairs = ikvwspacemalloc(ctrl, nadj+1); /* second pass: rewrite locale entries and populate remote edges */ for (nadj=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { k = adjncy[j]; if (k >= firstvtx && k < lastvtx) { /* local vertex */ adjncy[j] = k-firstvtx; } else { /* remote vertex */ adjpairs[nadj].key = k; adjpairs[nadj++].val = j; } } } STARTTIMER(ctrl, ctrl->AuxTmr1); /* use a sort-based "unique" approach */ ikvsorti(nadj, adjpairs); adjpairs[nadj].key = gnvtxs+1; /* boundary condition */ STOPTIMER(ctrl, ctrl->AuxTmr1); /* determine how many distinct vertices you need to receive */ for (nrecv=0, i=0; i<nadj; i++) { if (adjpairs[i].key != adjpairs[i+1].key) nrecv++; } graph->nrecv = nrecv; /* allocate space for the to be received vertices part of the recvinfo */ recvind = graph->recvind = imalloc(nrecv, "CommSetup: recvind"); /* store distinct vertices into recvind array and re-write adjncy */ for (nrecv=0, i=0; i<nadj; i++) { adjncy[adjpairs[i].val] = nvtxs+nrecv; if (adjpairs[i].key != adjpairs[i+1].key) recvind[nrecv++] = adjpairs[i].key; } PASSERT(ctrl, nrecv == graph->nrecv); /* determine the number of neighboring processors */ for (i=0, nnbrs=0, penum=0; penum<npes; penum++) { for (j=i; j<nrecv; j++) { if (recvind[j] >= vtxdist[penum+1]) break; } if (j > i) { nnbrs++; i = j; } } graph->nnbrs = nnbrs; /* Update the ctrl arrays that have to do with p2p communication */ CommUpdateNnbrs(ctrl, nnbrs); /* allocate space for peind/recvptr part of the recvinfo */ peind = graph->peind = imalloc(nnbrs, "CommSetup: peind"); recvptr = graph->recvptr = imalloc(nnbrs+1, "CommSetup: recvptr"); /* populate the peind/recvptr arrays */ for (i=0, nnbrs=0, recvptr[0]=0, penum=0; penum<npes; penum++) { for (j=i; j<nrecv; j++) { if (recvind[j] >= vtxdist[penum+1]) break; } if (j > i) { peind[nnbrs++] = penum; recvptr[nnbrs] = j; i = j; } } PASSERT(ctrl, nnbrs == graph->nnbrs); WCOREPOP; /* PrintVector(ctrl, nnbrs+1, 0, recvptr, "recvptr"); */ WCOREPUSH; /************************************************************* * Determine what you need to send *************************************************************/ /* GKTODO - This can be replaced via a sparse communication */ /* Tell the other processors what they need to send you */ recvrequests = ikvwspacemalloc(ctrl, npes); sendrequests = ikvwspacemalloc(ctrl, npes); memset(recvrequests, 0, sizeof(ikv_t)*npes); for (i=0; i<nnbrs; i++) { recvrequests[peind[i]].key = recvptr[i+1]-recvptr[i]; recvrequests[peind[i]].val = nvtxs+recvptr[i]; } gkMPI_Alltoall((void *)recvrequests, 2, IDX_T, (void *)sendrequests, 2, IDX_T, ctrl->comm); /* PrintPairs(ctrl, npes, recvrequests, "recvrequests"); */ /* PrintPairs(ctrl, npes, sendrequests, "sendrequests"); */ startsind = iwspacemalloc(ctrl, nnbrs); sendptr = graph->sendptr = imalloc(nnbrs+1, "CommSetup: sendptr"); for (j=0, i=0; i<npes; i++) { if (sendrequests[i].key > 0) { sendptr[j] = sendrequests[i].key; startsind[j] = sendrequests[i].val; j++; } } PASSERT(ctrl, j == nnbrs); MAKECSR(i, nnbrs, sendptr); nsend = graph->nsend = sendptr[nnbrs]; sendind = graph->sendind = imalloc(nsend, "CommSetup: sendind"); /* Issue the receives for sendind */ for (i=0; i<nnbrs; i++) { gkMPI_Irecv((void *)(sendind+sendptr[i]), sendptr[i+1]-sendptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); } /* Issue the sends. My recvind[penum] becomes penum's sendind[mype] */ for (i=0; i<nnbrs; i++) { gkMPI_Isend((void *)(recvind+recvptr[i]), recvptr[i+1]-recvptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); } gkMPI_Waitall(nnbrs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); /* Create the peadjncy data structure for sparse boundary exchanges */ pexadj = graph->pexadj = ismalloc(nvtxs+1, 0, "CommSetup: pexadj"); peadjncy = graph->peadjncy = imalloc(nsend, "CommSetup: peadjncy"); peadjloc = graph->peadjloc = imalloc(nsend, "CommSetup: peadjloc"); for (i=0; i<nsend; i++) { PASSERTP(ctrl, sendind[i] >= firstvtx && sendind[i] < lastvtx, (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX"\n", sendind[i], firstvtx, lastvtx)); pexadj[sendind[i]-firstvtx]++; } MAKECSR(i, nvtxs, pexadj); for (i=0; i<nnbrs; i++) { for (j=sendptr[i]; j<sendptr[i+1]; j++) { k = pexadj[sendind[j]-firstvtx]++; peadjncy[k] = i; /* peind[i] is the actual PE number */ peadjloc[k] = startsind[i]++; } } PASSERT(ctrl, pexadj[nvtxs] == nsend); SHIFTCSR(i, nvtxs, pexadj); WCOREPOP; /* Create the inverse map from ladjncy to adjncy */ imap = graph->imap = imalloc(nvtxs+nrecv, "CommSetup: imap"); for (i=0; i<nvtxs; i++) imap[i] = firstvtx+i; for (i=0; i<nrecv; i++) imap[nvtxs+i] = recvind[i]; STOPTIMER(ctrl, ctrl->SetupTmr); #ifdef DEBUG_SETUPINFO rprintf(ctrl, "[%5"PRIDX" %5"PRIDX"] \tl:[%5"PRIDX" %5"PRIDX"] \ts:[%5"PRIDX", %5"PRIDX"] \tr:[%5"PRIDX", %5"PRIDX"]\n", GlobalSEMin(ctrl, nvtxs), GlobalSEMax(ctrl, nvtxs), GlobalSEMin(ctrl, nlocal), GlobalSEMax(ctrl, nlocal), GlobalSEMin(ctrl, nsend), GlobalSEMax(ctrl, nsend), GlobalSEMin(ctrl, nrecv), GlobalSEMax(ctrl, nrecv)); PrintSetUpInfo(ctrl, graph); #endif } /*************************************************************************/ /*! This function updates the sreq/rreq/statuses arrays in ctrl based on the new number of neighbors. */ /*************************************************************************/ void CommUpdateNnbrs(ctrl_t *ctrl, idx_t nnbrs) { if (ctrl->ncommpes >= nnbrs) return; ctrl->ncommpes = nnbrs; ctrl->sreq = (MPI_Request *)gk_realloc(ctrl->sreq, sizeof(MPI_Request)*nnbrs, "sreq"); ctrl->rreq = (MPI_Request *)gk_realloc(ctrl->rreq, sizeof(MPI_Request)*nnbrs, "rreq"); ctrl->statuses = (MPI_Status *)gk_realloc(ctrl->statuses, sizeof(MPI_Status)*nnbrs, "statuses"); } /*************************************************************************/ /*! This function performs the gather/scatter for the boundary vertices */ /*************************************************************************/ void CommInterfaceData(ctrl_t *ctrl, graph_t *graph, idx_t *data, idx_t *recvvector) { idx_t i, k, nnbrs, firstvtx; idx_t *peind, *sendptr, *sendind, *sendvector, *recvptr, *recvind; WCOREPUSH; firstvtx = graph->vtxdist[ctrl->mype]; nnbrs = graph->nnbrs; peind = graph->peind; sendptr = graph->sendptr; sendind = graph->sendind; recvptr = graph->recvptr; recvind = graph->recvind; /* Issue the receives first */ for (i=0; i<nnbrs; i++) { gkMPI_Irecv((void *)(recvvector+recvptr[i]), recvptr[i+1]-recvptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); } /* Issue the sends next */ k = sendptr[nnbrs]; sendvector = iwspacemalloc(ctrl, k); for (i=0; i<k; i++) sendvector[i] = data[sendind[i]-firstvtx]; for (i=0; i<nnbrs; i++) { gkMPI_Isend((void *)(sendvector+sendptr[i]), sendptr[i+1]-sendptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); } /* OK, now get into the loop waiting for the operations to finish */ gkMPI_Waitall(nnbrs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); WCOREPOP; } /************************************************************************* * This function performs the gather/scatter for the boundary vertices **************************************************************************/ void CommChangedInterfaceData(ctrl_t *ctrl, graph_t *graph, idx_t nchanged, idx_t *changed, idx_t *data, ikv_t *sendpairs, ikv_t *recvpairs) { idx_t i, j, k, nnbrs, firstvtx, nrecv, penum, nreceived; idx_t *peind, *sendptr, *recvptr, *recvind, *pexadj, *peadjncy, *peadjloc, *psendptr; ikv_t *pairs; firstvtx = graph->vtxdist[ctrl->mype]; nnbrs = graph->nnbrs; nrecv = graph->nrecv; peind = graph->peind; sendptr = graph->sendptr; recvptr = graph->recvptr; recvind = graph->recvind; pexadj = graph->pexadj; peadjncy = graph->peadjncy; peadjloc = graph->peadjloc; /* Issue the receives first */ for (i=0; i<nnbrs; i++) { gkMPI_Irecv((void *)(recvpairs+recvptr[i]), 2*(recvptr[i+1]-recvptr[i]), IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); } if (nchanged != 0) { WCOREPUSH; psendptr = icopy(nnbrs, sendptr, iwspacemalloc(ctrl, nnbrs)); /* Copy the changed values into the sendvector */ for (i=0; i<nchanged; i++) { j = changed[i]; for (k=pexadj[j]; k<pexadj[j+1]; k++) { penum = peadjncy[k]; sendpairs[psendptr[penum]].key = peadjloc[k]; sendpairs[psendptr[penum]].val = data[j]; psendptr[penum]++; } } for (i=0; i<nnbrs; i++) { gkMPI_Isend((void *)(sendpairs+sendptr[i]), 2*(psendptr[i]-sendptr[i]), IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); } WCOREPOP; } else { for (i=0; i<nnbrs; i++) gkMPI_Isend((void *)(sendpairs), 0, IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); } /* OK, now get into the loop waiting for the operations to finish */ for (i=0; i<nnbrs; i++) { gkMPI_Wait(ctrl->rreq+i, &(ctrl->status)); gkMPI_Get_count(&ctrl->status, IDX_T, &nreceived); if (nreceived != 0) { nreceived = nreceived/2; pairs = recvpairs+graph->recvptr[i]; for (k=0; k<nreceived; k++) data[pairs[k].key] = pairs[k].val; } } gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSEMax(ctrl_t *ctrl, idx_t value) { idx_t max; gkMPI_Allreduce((void *)&value, (void *)&max, 1, IDX_T, MPI_MAX, ctrl->comm); return max; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSEMaxComm(MPI_Comm comm, idx_t value) { idx_t max; gkMPI_Allreduce((void *)&value, (void *)&max, 1, IDX_T, MPI_MAX, comm); return max; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSEMin(ctrl_t *ctrl, idx_t value) { idx_t min; gkMPI_Allreduce((void *)&value, (void *)&min, 1, IDX_T, MPI_MIN, ctrl->comm); return min; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSEMinComm(MPI_Comm comm, idx_t value) { idx_t min; gkMPI_Allreduce((void *)&value, (void *)&min, 1, IDX_T, MPI_MIN, comm); return min; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSESum(ctrl_t *ctrl, idx_t value) { idx_t sum; gkMPI_Allreduce((void *)&value, (void *)&sum, 1, IDX_T, MPI_SUM, ctrl->comm); return sum; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ idx_t GlobalSESumComm(MPI_Comm comm, idx_t value) { idx_t min; gkMPI_Allreduce((void *)&value, (void *)&min, 1, IDX_T, MPI_SUM, comm); return min; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ real_t GlobalSEMaxFloat(ctrl_t *ctrl, real_t value) { real_t max; gkMPI_Allreduce((void *)&value, (void *)&max, 1, REAL_T, MPI_MAX, ctrl->comm); return max; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ real_t GlobalSEMinFloat(ctrl_t *ctrl, real_t value) { real_t min; gkMPI_Allreduce((void *)&value, (void *)&min, 1, REAL_T, MPI_MIN, ctrl->comm); return min; } /************************************************************************* * This function computes the max of a single element **************************************************************************/ real_t GlobalSESumFloat(ctrl_t *ctrl, real_t value) { real_t sum; gkMPI_Allreduce((void *)&value, (void *)&sum, 1, REAL_T, MPI_SUM, ctrl->comm); return sum; }
15,306
29.860887
123
c
null
ParMETIS-main/libparmetis/diffutil.c
/* * Copyright 1997, Regents of the University of Minnesota * * wavefrontK.c * * This file contains code for the initial directed diffusion at the coarsest * graph * * Started 5/19/97, Kirk, George * * $Id: diffutil.c 13946 2013-03-30 15:51:45Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function computes the load for each subdomain **************************************************************************/ void SetUpConnectGraph(graph_t *graph, matrix_t *matrix, idx_t *workspace) { idx_t i, ii, j, jj, k, l; idx_t nvtxs, nrows; idx_t *xadj, *adjncy, *where; idx_t *rowptr, *colind; idx_t *pcounts, *perm, *marker; real_t *values; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; where = graph->where; nrows = matrix->nrows; rowptr = matrix->rowptr; colind = matrix->colind; values = matrix->values; perm = workspace; marker = iset(nrows, -1, workspace+nvtxs); pcounts = iset(nrows+1, 0, workspace+nvtxs+nrows); for (i=0; i<nvtxs; i++) pcounts[where[i]]++; MAKECSR(i, nrows, pcounts); for (i=0; i<nvtxs; i++) perm[pcounts[where[i]]++] = i; for (i=nrows; i>0; i--) pcounts[i] = pcounts[i-1]; pcounts[0] = 0; /************************/ /* Construct the matrix */ /************************/ rowptr[0] = k = 0; for (ii=0; ii<nrows; ii++) { colind[k++] = ii; marker[ii] = ii; for (jj=pcounts[ii]; jj<pcounts[ii+1]; jj++) { i = perm[jj]; for (j=xadj[i]; j<xadj[i+1]; j++) { l = where[adjncy[j]]; if (marker[l] != ii) { colind[k] = l; values[k++] = -1.0; marker[l] = ii; } } } values[rowptr[ii]] = (real_t)(k-rowptr[ii]-1); rowptr[ii+1] = k; } matrix->nnzs = rowptr[nrows]; return; } /************************************************************************* * This function computes movement statistics for adaptive refinement * schemes **************************************************************************/ void Mc_ComputeMoveStatistics(ctrl_t *ctrl, graph_t *graph, idx_t *nmoved, idx_t *maxin, idx_t *maxout) { idx_t i, nvtxs, nparts, myhome; idx_t *vwgt, *where; idx_t *lend, *gend, *lleft, *gleft, *lstart, *gstart; nvtxs = graph->nvtxs; vwgt = graph->vwgt; where = graph->where; nparts = ctrl->nparts; lstart = ismalloc(nparts, 0, "ComputeMoveStatistics: lstart"); gstart = ismalloc(nparts, 0, "ComputeMoveStatistics: gstart"); lleft = ismalloc(nparts, 0, "ComputeMoveStatistics: lleft"); gleft = ismalloc(nparts, 0, "ComputeMoveStatistics: gleft"); lend = ismalloc(nparts, 0, "ComputeMoveStatistics: lend"); gend = ismalloc(nparts, 0, "ComputeMoveStatistics: gend"); for (i=0; i<nvtxs; i++) { myhome = (ctrl->ps_relation == PARMETIS_PSR_COUPLED) ? ctrl->mype : graph->home[i]; lstart[myhome] += (graph->vsize == NULL) ? 1 : graph->vsize[i]; lend[where[i]] += (graph->vsize == NULL) ? 1 : graph->vsize[i]; if (where[i] != myhome) lleft[myhome] += (graph->vsize == NULL) ? 1 : graph->vsize[i]; } /* PrintVector(ctrl, ctrl->npes, 0, lend, "Lend: "); */ gkMPI_Allreduce((void *)lstart, (void *)gstart, nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lleft, (void *)gleft, nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lend, (void *)gend, nparts, IDX_T, MPI_SUM, ctrl->comm); *nmoved = isum(nparts, gleft, 1); *maxout = imax(nparts, gleft, 1); for (i=0; i<nparts; i++) lstart[i] = gend[i]+gleft[i]-gstart[i]; *maxin = imax(nparts, lstart, 1); gk_free((void **)&lstart, (void **)&gstart, (void **)&lleft, (void **)&gleft, (void **)&lend, (void **)&gend, LTERM); } /************************************************************************* * This function computes the TotalV of a serial graph. **************************************************************************/ idx_t Mc_ComputeSerialTotalV(graph_t *graph, idx_t *home) { idx_t i; idx_t totalv = 0; for (i=0; i<graph->nvtxs; i++) { if (graph->where[i] != home[i]) totalv += (graph->vsize == NULL) ? graph->vwgt[i*graph->ncon] : graph->vsize[i]; } return totalv; } /************************************************************************* * This function computes the load for each subdomain **************************************************************************/ void ComputeLoad(graph_t *graph, idx_t nparts, real_t *load, real_t *tpwgts, idx_t index) { idx_t i; idx_t nvtxs, ncon; idx_t *where; real_t *nvwgt; nvtxs = graph->nvtxs; ncon = graph->ncon; where = graph->where; nvwgt = graph->nvwgt; rset(nparts, 0.0, load); for (i=0; i<nvtxs; i++) load[where[i]] += nvwgt[i*ncon+index]; ASSERT(fabs(rsum(nparts, load, 1)-1.0) < 0.001); for (i=0; i<nparts; i++) { load[i] -= tpwgts[i*ncon+index]; } return; } /************************************************************************* * This function implements the CG solver used during the directed diffusion **************************************************************************/ void ConjGrad2(matrix_t *A, real_t *b, real_t *x, real_t tol, real_t *workspace) { idx_t i, k, n; real_t *p, *r, *q, *z, *M; real_t alpha, beta, rho, rho_1 = -1.0, error, bnrm2, tmp; idx_t *rowptr, *colind; real_t *values; n = A->nrows; rowptr = A->rowptr; colind = A->colind; values = A->values; /* Initial Setup */ p = workspace; r = workspace + n; q = workspace + 2*n; z = workspace + 3*n; M = workspace + 4*n; for (i=0; i<n; i++) { x[i] = 0.0; if (values[rowptr[i]] != 0.0) M[i] = 1.0/values[rowptr[i]]; else M[i] = 0.0; } /* r = b - Ax */ mvMult2(A, x, r); for (i=0; i<n; i++) r[i] = b[i]-r[i]; bnrm2 = rnorm2(n, b, 1); if (bnrm2 > 0.0) { error = rnorm2(n, r, 1) / bnrm2; if (error > tol) { /* Begin Iterations */ for (k=0; k<n; k++) { for (i=0; i<n; i++) z[i] = r[i]*M[i]; rho = rdot(n, r, 1, z, 1); if (k == 0) rcopy(n, z, p); else { if (rho_1 != 0.0) beta = rho/rho_1; else beta = 0.0; for (i=0; i<n; i++) p[i] = z[i] + beta*p[i]; } mvMult2(A, p, q); /* q = A*p */ tmp = rdot(n, p, 1, q, 1); if (tmp != 0.0) alpha = rho/tmp; else alpha = 0.0; raxpy(n, alpha, p, 1, x, 1); /* x = x + alpha*p */ raxpy(n, -alpha, q, 1, r, 1); /* r = r - alpha*q */ error = rnorm2(n, r, 1) / bnrm2; if (error < tol) break; rho_1 = rho; } } } } /************************************************************************* * This function performs Matrix-Vector multiplication **************************************************************************/ void mvMult2(matrix_t *A, real_t *v, real_t *w) { idx_t i, j; for (i = 0; i < A->nrows; i++) w[i] = 0.0; for (i = 0; i < A->nrows; i++) for (j = A->rowptr[i]; j < A->rowptr[i+1]; j++) w[i] += A->values[j] * v[A->colind[j]]; return; } /************************************************************************* * This function sets up the transfer vectors **************************************************************************/ void ComputeTransferVector(idx_t ncon, matrix_t *matrix, real_t *solution, real_t *transfer, idx_t index) { idx_t j, k; idx_t nrows; idx_t *rowptr, *colind; nrows = matrix->nrows; rowptr = matrix->rowptr; colind = matrix->colind; for (j=0; j<nrows; j++) { for (k=rowptr[j]+1; k<rowptr[j+1]; k++) { if (solution[j] > solution[colind[k]]) { transfer[k*ncon+index] = solution[j] - solution[colind[k]]; } else { transfer[k*ncon+index] = 0.0; } } } }
7,949
25.588629
119
c
null
ParMETIS-main/libparmetis/xyzpart.c
/* * Copyright 1997, Regents of the University of Minnesota * * xyzpart.c * * This file contains code that implements a coordinate based partitioning * * Started 7/11/97 * George * * $Id: xyzpart.c 10755 2011-09-15 12:28:34Z karypis $ * */ #include <parmetislib.h> /*************************************************************************/ /*! This function implements a simple coordinate based partitioning */ /*************************************************************************/ void Coordinate_Partition(ctrl_t *ctrl, graph_t *graph, idx_t ndims, real_t *xyz, idx_t setup) { idx_t i, j, k, nvtxs, firstvtx, icoord, nbits; idx_t *vtxdist, *bxyz; ikv_t *cand; WCOREPUSH; if (setup) CommSetup(ctrl, graph); else graph->nrecv = 0; nvtxs = graph->nvtxs; vtxdist = graph->vtxdist; firstvtx = vtxdist[ctrl->mype]; cand = ikvwspacemalloc(ctrl, nvtxs); bxyz = iwspacemalloc(ctrl, nvtxs*ndims); /* Assign the coordinates into bins */ nbits = 9; /* 2^nbits # of bins */ IRBinCoordinates(ctrl, graph, ndims, xyz, 1<<nbits, bxyz); /* Z-ordering */ for (i=0; i<nvtxs; i++) { for (icoord=0, j=nbits-1; j>=0; j--) { for (k=0; k<ndims; k++) icoord = (icoord<<1) + (bxyz[i*ndims+k]&(1<<j) ? 1 : 0); } cand[i].key = icoord; cand[i].val = firstvtx+i; } /* Partition using sorting */ PseudoSampleSort(ctrl, graph, cand); WCOREPOP; } /*************************************************************************/ /*! This function maps the coordinates into bin numbers. It starts with a uniform distribution of the max-min range and then performs a number of iterations that adjust the bucket boundaries based on the actual bucket counts. */ /*************************************************************************/ void IRBinCoordinates(ctrl_t *ctrl, graph_t *graph, idx_t ndims, real_t *xyz, idx_t nbins, idx_t *bxyz) { idx_t npes=ctrl->npes, mype=ctrl->mype; idx_t i, j, k, l, gnvtxs, nvtxs; idx_t csize, psize; idx_t *vtxdist, *lcounts, *gcounts; real_t gmin, gmax, *emarkers, *nemarkers; rkv_t *cand; WCOREPUSH; gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; cand = rkvwspacemalloc(ctrl, nvtxs); lcounts = iwspacemalloc(ctrl, nbins); gcounts = iwspacemalloc(ctrl, nbins); emarkers = rwspacemalloc(ctrl, nbins+1); nemarkers = rwspacemalloc(ctrl, nbins+1); /* Go over each dimension */ for (k=0; k<ndims; k++) { for (i=0; i<nvtxs; i++) { cand[i].key = xyz[i*ndims+k]; cand[i].val = i; } rkvsorti(nvtxs, cand); /* determine initial range */ gkMPI_Allreduce((void *)&cand[0].key, (void *)&gmin, 1, REAL_T, MPI_MIN, ctrl->comm); gkMPI_Allreduce((void *)&cand[nvtxs-1].key, (void *)&gmax, 1, REAL_T, MPI_MAX, ctrl->comm); for (i=0; i<nbins; i++) emarkers[i] = gmin + (gmax-gmin)*i/nbins; emarkers[nbins] = gmax*(1.0+2.0*REAL_EPSILON); /* get into a iterative backet boundary refinement */ for (l=0; l<5; l++) { /* determine bucket counts */ iset(nbins, 0, lcounts); for (j=0, i=0; i<nvtxs;) { if (cand[i].key < emarkers[j+1]) { lcounts[j]++; i++; } else { j++; } } gkMPI_Allreduce((void *)lcounts, (void *)gcounts, nbins, IDX_T, MPI_SUM, ctrl->comm); /* if (mype == 0) { printf("Distribution [%"PRIDX"]...\n", l); for (i=0; i<nbins; i++) printf("\t%"PRREAL" - %"PRREAL" => %"PRIDX"\n", emarkers[i], emarkers[i+1], gcounts[i]); } */ /* break-out if things look reasonably balanced */ if (imax(nbins, gcounts, 1) < 4*gnvtxs/nbins) break; /* refine buckets */ rset(nbins, -1, nemarkers); for (j=0, i=0; i<nbins; i++) { for (csize=0; ; j++) { if (csize+gcounts[j] < gnvtxs/nbins) { csize += gcounts[j]; } else { psize = gnvtxs/nbins-csize; emarkers[j] += (emarkers[j+1]-emarkers[j])*psize/gcounts[j]; gcounts[j] -= psize; nemarkers[i+1] = emarkers[j]; break; } } } nemarkers[0] = gmin; nemarkers[nbins] = gmax*(1.0+2.0*REAL_EPSILON); rcopy(nbins+1, nemarkers, emarkers); } /* assign the coordinate to the appropriate bin */ for (j=0, i=0; i<nvtxs;) { if (cand[i].key < emarkers[j+1]) { bxyz[cand[i].val*ndims+k] = j; i++; } else { j++; } } } WCOREPOP; } /*************************************************************************/ /*! This function maps the coordinates into bin numbers. It uses a per dimension recursive center-of mass bisection approach. */ /*************************************************************************/ void RBBinCoordinates(ctrl_t *ctrl, graph_t *graph, idx_t ndims, real_t *xyz, idx_t nbins, idx_t *bxyz) { idx_t npes=ctrl->npes, mype=ctrl->mype; idx_t i, j, k, l, gnvtxs, nvtxs, cnbins; idx_t *vtxdist, *lcounts, *gcounts; real_t sum, gmin, gmax, gsum, *emarkers, *nemarkers, *lsums, *gsums; rkv_t *cand; ikv_t *buckets; WCOREPUSH; gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; buckets = ikvwspacemalloc(ctrl, nbins); cand = rkvwspacemalloc(ctrl, nvtxs); lcounts = iwspacemalloc(ctrl, nbins); gcounts = iwspacemalloc(ctrl, nbins); lsums = rwspacemalloc(ctrl, nbins); gsums = rwspacemalloc(ctrl, nbins); emarkers = rwspacemalloc(ctrl, nbins+1); nemarkers = rwspacemalloc(ctrl, nbins+1); /* Go over each dimension */ for (k=0; k<ndims; k++) { for (sum=0.0, i=0; i<nvtxs; i++) { cand[i].key = xyz[i*ndims+k]; cand[i].val = i; sum += cand[i].key; } rkvsorti(nvtxs, cand); /* determine initial stats */ gkMPI_Allreduce((void *)&cand[0].key, (void *)&gmin, 1, REAL_T, MPI_MIN, ctrl->comm); gkMPI_Allreduce((void *)&cand[nvtxs-1].key, (void *)&gmax, 1, REAL_T, MPI_MAX, ctrl->comm); gkMPI_Allreduce((void *)&sum, (void *)&gsum, 1, REAL_T, MPI_MAX, ctrl->comm); emarkers[0] = gmin; emarkers[1] = gsum/gnvtxs; emarkers[2] = gmax*(1.0+2.0*REAL_EPSILON); cnbins = 2; /* get into a iterative backet boundary refinement */ while (cnbins < nbins) { /* determine bucket counts */ iset(cnbins, 0, lcounts); rset(cnbins, 0, lsums); for (j=0, i=0; i<nvtxs;) { if (cand[i].key < emarkers[j+1]) { lcounts[j]++; lsums[j] += cand[i].key; i++; } else { j++; } } gkMPI_Allreduce((void *)lcounts, (void *)gcounts, cnbins, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lsums, (void *)gsums, cnbins, REAL_T, MPI_SUM, ctrl->comm); /* if (mype == 0) { printf("Distribution [%"PRIDX"]...\n", cnbins); for (i=0; i<cnbins; i++) printf("\t%"PRREAL" - %"PRREAL" => %"PRIDX"\n", emarkers[i], emarkers[i+1], gcounts[i]); } */ /* split over-weight buckets */ for (i=0; i<cnbins; i++) { buckets[i].key = gcounts[i]; buckets[i].val = i; } ikvsorti(cnbins, buckets); for (j=0, i=cnbins-1; i>=0; i--, j++) { l = buckets[i].val; if (buckets[i].key > gnvtxs/nbins && cnbins < nbins) { /* if (mype == 0) printf("\t\t %f %f\n", (float)emarkers[l], (float)emarkers[l+1]); */ nemarkers[j++] = (emarkers[l]+emarkers[l+1])/2; cnbins++; } nemarkers[j] = emarkers[l]; } PASSERT(ctrl, cnbins == j); rsorti(cnbins, nemarkers); rcopy(cnbins, nemarkers, emarkers); emarkers[cnbins] = gmax*(1.0+2.0*REAL_EPSILON); } /* assign the coordinate to the appropriate bin */ for (j=0, i=0; i<nvtxs;) { if (cand[i].key < emarkers[j+1]) { bxyz[cand[i].val*ndims+k] = j; i++; } else { j++; } } } WCOREPOP; } /**************************************************************************/ /*! This function sorts a distributed list of ikv_t in increasing order, and uses it to compute a partition. It uses samplesort. This function is poorly implemented and makes the assumption that the number of vertices in each processor is greater than npes. This constraint is currently enforced by the calling functions. \todo fix it in 4.0. */ /**************************************************************************/ void SampleSort(ctrl_t *ctrl, graph_t *graph, ikv_t *elmnts) { idx_t i, j, k, nvtxs, nrecv, npes=ctrl->npes, mype=ctrl->mype, firstvtx, lastvtx; idx_t *scounts, *rcounts, *vtxdist, *perm; ikv_t *relmnts, *mypicks, *allpicks; WCOREPUSH; CommUpdateNnbrs(ctrl, npes); nvtxs = graph->nvtxs; vtxdist = graph->vtxdist; /* get memory for the counts */ scounts = iwspacemalloc(ctrl, npes+1); rcounts = iwspacemalloc(ctrl, npes+1); /* get memory for the splitters */ mypicks = ikvwspacemalloc(ctrl, npes+1); WCOREPUSH; /* for freeing allpicks */ allpicks = ikvwspacemalloc(ctrl, npes*npes); /* Sort the local elements */ ikvsorti(nvtxs, elmnts); /* Select the local npes-1 equally spaced elements */ for (i=1; i<npes; i++) { mypicks[i-1].key = elmnts[i*(nvtxs/npes)].key; mypicks[i-1].val = elmnts[i*(nvtxs/npes)].val; } /* PrintPairs(ctrl, npes-1, mypicks, "Mypicks"); */ /* Gather the picks to all the processors */ gkMPI_Allgather((void *)mypicks, 2*(npes-1), IDX_T, (void *)allpicks, 2*(npes-1), IDX_T, ctrl->comm); /* PrintPairs(ctrl, npes*(npes-1), allpicks, "Allpicks"); */ /* Sort all the picks */ ikvsortii(npes*(npes-1), allpicks); /* PrintPairs(ctrl, npes*(npes-1), allpicks, "Allpicks"); */ /* Select the final splitters. Set the boundaries to simplify coding */ for (i=1; i<npes; i++) mypicks[i] = allpicks[i*(npes-1)]; mypicks[0].key = IDX_MIN; mypicks[npes].key = IDX_MAX; /* PrintPairs(ctrl, npes+1, mypicks, "Mypicks"); */ WCOREPOP; /* free allpicks */ /* Compute the number of elements that belong to each bucket */ iset(npes, 0, scounts); for (j=i=0; i<nvtxs; i++) { if (elmnts[i].key < mypicks[j+1].key || (elmnts[i].key == mypicks[j+1].key && elmnts[i].val < mypicks[j+1].val)) scounts[j]++; else scounts[++j]++; } gkMPI_Alltoall(scounts, 1, IDX_T, rcounts, 1, IDX_T, ctrl->comm); MAKECSR(i, npes, scounts); MAKECSR(i, npes, rcounts); /* PrintVector(ctrl, npes+1, 0, scounts, "Scounts"); PrintVector(ctrl, npes+1, 0, rcounts, "Rcounts"); */ /* Allocate memory for sorted elements and receive them */ nrecv = rcounts[npes]; relmnts = ikvwspacemalloc(ctrl, nrecv); /* Issue the receives first */ for (i=0; i<npes; i++) gkMPI_Irecv((void *)(relmnts+rcounts[i]), 2*(rcounts[i+1]-rcounts[i]), IDX_T, i, 1, ctrl->comm, ctrl->rreq+i); /* Issue the sends next */ for (i=0; i<npes; i++) gkMPI_Isend((void *)(elmnts+scounts[i]), 2*(scounts[i+1]-scounts[i]), IDX_T, i, 1, ctrl->comm, ctrl->sreq+i); gkMPI_Waitall(npes, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(npes, ctrl->sreq, ctrl->statuses); /* OK, now do the local sort of the relmnts. Use perm to keep track original order */ perm = iwspacemalloc(ctrl, nrecv); for (i=0; i<nrecv; i++) { perm[i] = relmnts[i].val; relmnts[i].val = i; } ikvsorti(nrecv, relmnts); /* Compute what needs to be shifted */ gkMPI_Scan((void *)(&nrecv), (void *)(&lastvtx), 1, IDX_T, MPI_SUM, ctrl->comm); firstvtx = lastvtx-nrecv; /*myprintf(ctrl, "first, last: %"PRIDX" %"PRIDX"\n", firstvtx, lastvtx); */ for (j=0, i=0; i<npes; i++) { if (vtxdist[i+1] > firstvtx) { /* Found the first PE that is passed me */ if (vtxdist[i+1] >= lastvtx) { /* myprintf(ctrl, "Shifting %"PRIDX" elements to processor %"PRIDX"\n", lastvtx-firstvtx, i); */ for (k=0; k<lastvtx-firstvtx; k++, j++) relmnts[relmnts[j].val].key = i; } else { /* myprintf(ctrl, "Shifting %"PRIDX" elements to processor %"PRIDX"\n", vtxdist[i+1]-firstvtx, i); */ for (k=0; k<vtxdist[i+1]-firstvtx; k++, j++) relmnts[relmnts[j].val].key = i; firstvtx = vtxdist[i+1]; } } if (vtxdist[i+1] >= lastvtx) break; } /* Reverse the ordering on the relmnts[].val */ for (i=0; i<nrecv; i++) { PASSERTP(ctrl, relmnts[i].key>=0 && relmnts[i].key<npes, (ctrl, "%"PRIDX" %"PRIDX"\n", i, relmnts[i].key)); relmnts[i].val = perm[i]; } /* OK, now sent it back */ /* Issue the receives first */ for (i=0; i<npes; i++) gkMPI_Irecv((void *)(elmnts+scounts[i]), 2*(scounts[i+1]-scounts[i]), IDX_T, i, 1, ctrl->comm, ctrl->rreq+i); /* Issue the sends next */ for (i=0; i<npes; i++) gkMPI_Isend((void *)(relmnts+rcounts[i]), 2*(rcounts[i+1]-rcounts[i]), IDX_T, i, 1, ctrl->comm, ctrl->sreq+i); gkMPI_Waitall(npes, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(npes, ctrl->sreq, ctrl->statuses); /* Construct a partition for the graph */ graph->where = imalloc(graph->nvtxs+graph->nrecv, "PartSort: graph->where"); firstvtx = vtxdist[mype]; for (i=0; i<nvtxs; i++) { PASSERTP(ctrl, elmnts[i].key>=0 && elmnts[i].key<npes, (ctrl, "%"PRIDX" %"PRIDX"\n", i, elmnts[i].key)); PASSERTP(ctrl, elmnts[i].val>=vtxdist[mype] && elmnts[i].val<vtxdist[mype+1], (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", i, vtxdist[mype], vtxdist[mype+1], elmnts[i].val)); graph->where[elmnts[i].val-firstvtx] = elmnts[i].key; } WCOREPOP; } /**************************************************************************/ /*! This function sorts a distributed list of ikv_t in increasing order, and uses it to compute a partition. It uses a samplesort variant whose number of local samples can potentially be smaller than npes. */ /**************************************************************************/ void PseudoSampleSort(ctrl_t *ctrl, graph_t *graph, ikv_t *elmnts) { idx_t npes=ctrl->npes, mype=ctrl->mype; idx_t i, j, k, nlsamples, ntsamples, nvtxs, nrecv, firstvtx, lastvtx; idx_t *scounts, *rcounts, *sdispls, *rdispls, *vtxdist, *perm; ikv_t *relmnts, *mypicks, *allpicks; STARTTIMER(ctrl, ctrl->AuxTmr1); WCOREPUSH; nvtxs = graph->nvtxs; vtxdist = graph->vtxdist; /* determine the number of local samples */ //nlsamples = (GlobalSESum(ctrl, graph->nedges) + graph->gnvtxs)/(npes*npes); nlsamples = graph->gnvtxs/(npes*npes); if (nlsamples > npes) nlsamples = npes; else if (nlsamples < 75) nlsamples = gk_min(75, npes); /* the 'npes' in the min is to account for small graphs */ IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "PseudoSampleSort: nlsamples=%"PRIDX" of %"PRIDX"\n", nlsamples, npes)); /* get memory for the counts and displacements */ scounts = iwspacemalloc(ctrl, npes+1); rcounts = iwspacemalloc(ctrl, npes+1); sdispls = iwspacemalloc(ctrl, npes+1); rdispls = iwspacemalloc(ctrl, npes+1); /* get memory for the splitters */ mypicks = ikvwspacemalloc(ctrl, npes+1); WCOREPUSH; /* for freeing allpicks */ allpicks = ikvwspacemalloc(ctrl, npes*nlsamples); /* Sort the local elements */ ikvsorti(nvtxs, elmnts); /* Select the local nlsamples-1 equally spaced elements */ for (i=0; i<nlsamples-1; i++) { if (nvtxs > 0) { k = (nvtxs/(3*nlsamples) /* initial offset */ + i*nvtxs/nlsamples /* increament */ + mype*nvtxs/(npes*nlsamples) /* per-pe shift for nlsamples<npes */ )%nvtxs; mypicks[i].key = elmnts[k].key; mypicks[i].val = elmnts[k].val; } else { /* Take care the case in which a processor has no elements, at which point we still select nlsamples-1, but we set their .val to -1 to be removed later prior to sorting */ mypicks[i].val = -1; } } /* PrintPairs(ctrl, nlsamples-1, mypicks, "Mypicks"); */ STOPTIMER(ctrl, ctrl->AuxTmr1); STARTTIMER(ctrl, ctrl->AuxTmr2); /* Gather the picks to all the processors */ gkMPI_Allgather((void *)mypicks, 2*(nlsamples-1), IDX_T, (void *)allpicks, 2*(nlsamples-1), IDX_T, ctrl->comm); /* PrintPairs(ctrl, npes*(nlsamples-1), allpicks, "Allpicks"); */ /* Remove any samples that have .val == -1 */ for (ntsamples=0, i=0; i<npes*(nlsamples-1); i++) { if (allpicks[i].val != -1) allpicks[ntsamples++] = allpicks[i]; } /* Sort all the picks */ ikvsortii(ntsamples, allpicks); /* Select the final splitters. Set the boundaries to simplify coding */ for (i=1; i<npes; i++) mypicks[i] = allpicks[i*ntsamples/npes]; mypicks[0].key = IDX_MIN; mypicks[npes].key = IDX_MAX; WCOREPOP; /* free allpicks */ STOPTIMER(ctrl, ctrl->AuxTmr2); STARTTIMER(ctrl, ctrl->AuxTmr3); /* Compute the number of elements that belong to each bucket */ iset(npes, 0, scounts); for (j=i=0; i<nvtxs; i++) { if (elmnts[i].key < mypicks[j+1].key || (elmnts[i].key == mypicks[j+1].key && elmnts[i].val < mypicks[j+1].val)) scounts[j]++; else scounts[++j]++; } PASSERT(ctrl, j < npes); gkMPI_Alltoall(scounts, 1, IDX_T, rcounts, 1, IDX_T, ctrl->comm); /* multiply raw counts by 2 to account for the ikv_t type */ sdispls[0] = rdispls[0] = 0; for (i=0; i<npes; i++) { scounts[i] *= 2; rcounts[i] *= 2; sdispls[i+1] = sdispls[i] + scounts[i]; rdispls[i+1] = rdispls[i] + rcounts[i]; } STOPTIMER(ctrl, ctrl->AuxTmr3); STARTTIMER(ctrl, ctrl->AuxTmr4); /* PrintVector(ctrl, npes+1, 0, scounts, "Scounts"); PrintVector(ctrl, npes+1, 0, rcounts, "Rcounts"); */ /* Allocate memory for sorted elements and receive them */ nrecv = rdispls[npes]/2; /* The divide by 2 is to get the # of ikv_t elements */ relmnts = ikvwspacemalloc(ctrl, nrecv); IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "PseudoSampleSort: max_nrecv: %"PRIDX" of %"PRIDX"\n", GlobalSEMax(ctrl, nrecv), graph->gnvtxs/npes)); if (mype == 0 || mype == npes-1) IFSET(ctrl->dbglvl, DBG_INFO, myprintf(ctrl, "PseudoSampleSort: nrecv: %"PRIDX" of %"PRIDX"\n", nrecv, graph->gnvtxs/npes)); gkMPI_Alltoallv((void *)elmnts, scounts, sdispls, IDX_T, (void *)relmnts, rcounts, rdispls, IDX_T, ctrl->comm); STOPTIMER(ctrl, ctrl->AuxTmr4); STARTTIMER(ctrl, ctrl->AuxTmr5); /* OK, now do the local sort of the relmnts. Use perm to keep track original order */ perm = iwspacemalloc(ctrl, nrecv); for (i=0; i<nrecv; i++) { perm[i] = relmnts[i].val; relmnts[i].val = i; } ikvsorti(nrecv, relmnts); /* Compute what needs to be shifted */ gkMPI_Scan((void *)(&nrecv), (void *)(&lastvtx), 1, IDX_T, MPI_SUM, ctrl->comm); firstvtx = lastvtx-nrecv; for (j=0, i=0; i<npes; i++) { if (vtxdist[i+1] > firstvtx) { /* Found the first PE that is passed me */ if (vtxdist[i+1] >= lastvtx) { /* myprintf(ctrl, "Shifting %"PRIDX" elements to processor %"PRIDX"\n", lastvtx-firstvtx, i); */ for (k=0; k<lastvtx-firstvtx; k++, j++) relmnts[relmnts[j].val].key = i; } else { /* myprintf(ctrl, "Shifting %"PRIDX" elements to processor %"PRIDX"\n", vtxdist[i+1]-firstvtx, i); */ for (k=0; k<vtxdist[i+1]-firstvtx; k++, j++) relmnts[relmnts[j].val].key = i; firstvtx = vtxdist[i+1]; } } if (vtxdist[i+1] >= lastvtx) break; } /* Reverse the ordering on the relmnts[].val */ for (i=0; i<nrecv; i++) { PASSERTP(ctrl, relmnts[i].key>=0 && relmnts[i].key<npes, (ctrl, "%"PRIDX" %"PRIDX"\n", i, relmnts[i].key)); relmnts[i].val = perm[i]; } STOPTIMER(ctrl, ctrl->AuxTmr5); STARTTIMER(ctrl, ctrl->AuxTmr6); /* OK, now sent it back. The role of send/recv arrays is now reversed. */ gkMPI_Alltoallv((void *)relmnts, rcounts, rdispls, IDX_T, (void *)elmnts, scounts, sdispls, IDX_T, ctrl->comm); /* Construct a partition for the graph */ graph->where = imalloc(graph->nvtxs+graph->nrecv, "PartSort: graph->where"); firstvtx = vtxdist[mype]; for (i=0; i<nvtxs; i++) { PASSERTP(ctrl, elmnts[i].key>=0 && elmnts[i].key<npes, (ctrl, "%"PRIDX" %"PRIDX"\n", i, elmnts[i].key)); PASSERTP(ctrl, elmnts[i].val>=vtxdist[mype] && elmnts[i].val<vtxdist[mype+1], (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", i, vtxdist[mype], vtxdist[mype+1], elmnts[i].val)); graph->where[elmnts[i].val-firstvtx] = elmnts[i].key; } WCOREPOP; STOPTIMER(ctrl, ctrl->AuxTmr6); }
20,877
29.748159
109
c
null
ParMETIS-main/libparmetis/wspace.c
/* * Copyright 1997, Regents of the University of Minnesota * * memory.c * * This file contains routines that deal with memory allocation * * Started 2/24/96 * George * * $Id: wspace.c 10540 2011-07-11 15:42:13Z karypis $ * */ #include <parmetislib.h> /*************************************************************************/ /*! This function allocate various pools of memory */ /*************************************************************************/ void AllocateWSpace(ctrl_t *ctrl, size_t nwords) { ctrl->mcore = gk_mcoreCreate(nwords*sizeof(idx_t)); } /*************************************************************************/ /*! This function allocates refinement-specific memory for the workspace */ /*************************************************************************/ void AllocateRefinementWorkSpace(ctrl_t *ctrl, idx_t nbrpoolsize) { ctrl->nbrpoolsize = nbrpoolsize; ctrl->nbrpoolcpos = 0; ctrl->nbrpoolreallocs = 0; ctrl->cnbrpool = (cnbr_t *)gk_malloc(ctrl->nbrpoolsize*sizeof(cnbr_t), "AllocateRefinementWorkSpace: cnbrpool"); } /*************************************************************************/ /*! This function de-allocate various pools of memory */ /**************************************************************************/ void FreeWSpace(ctrl_t *ctrl) { ctrl->dbglvl = 0; gk_mcoreDestroy(&ctrl->mcore, (ctrl->dbglvl&DBG_INFO)); if (ctrl->dbglvl&DBG_INFO) { printf(" nbrpool statistics [pe:%"PRIDX"]\n" " nbrpoolsize: %12zu nbrpoolcpos: %12zu\n" " nbrpoolreallocs: %12zu\n\n", ctrl->mype, ctrl->nbrpoolsize, ctrl->nbrpoolcpos, ctrl->nbrpoolreallocs); } gk_free((void **)&ctrl->cnbrpool, LTERM); ctrl->nbrpoolsize = 0; ctrl->nbrpoolcpos = 0; } /*************************************************************************/ /*! This function allocate space from the workspace/heap */ /*************************************************************************/ void *wspacemalloc(ctrl_t *ctrl, size_t nbytes) { return gk_mcoreMalloc(ctrl->mcore, nbytes); } /*************************************************************************/ /*! This function allocate space from the core */ /*************************************************************************/ idx_t *iwspacemalloc(ctrl_t *ctrl, size_t n) { return (idx_t *)wspacemalloc(ctrl, n*sizeof(idx_t)); } /*************************************************************************/ /*! This function resets the cnbrpool */ /*************************************************************************/ void cnbrpoolReset(ctrl_t *ctrl) { ctrl->nbrpoolcpos = 0; } /*************************************************************************/ /*! This function gets the next free index from cnbrpool */ /*************************************************************************/ idx_t cnbrpoolGetNext(ctrl_t *ctrl, idx_t nnbrs) { nnbrs = gk_min(ctrl->nparts, nnbrs); ctrl->nbrpoolcpos += nnbrs; if (ctrl->nbrpoolcpos > ctrl->nbrpoolsize) { ctrl->nbrpoolsize += gk_max(10*nnbrs, ctrl->nbrpoolsize/2); ctrl->cnbrpool = (cnbr_t *)gk_realloc(ctrl->cnbrpool, ctrl->nbrpoolsize*sizeof(cnbr_t), "cnbrpoolGet: cnbrpool"); ctrl->nbrpoolreallocs++; } return ctrl->nbrpoolcpos - nnbrs; } /*************************************************************************/ /*! This function allocate space from the core */ /*************************************************************************/ real_t *rwspacemalloc(ctrl_t *ctrl, size_t n) { return (real_t *)wspacemalloc(ctrl, n*sizeof(real_t)); } /*************************************************************************/ /*! This function allocate space from the core */ /*************************************************************************/ ikv_t *ikvwspacemalloc(ctrl_t *ctrl, size_t n) { return (ikv_t *)wspacemalloc(ctrl, n*sizeof(ikv_t)); } /*************************************************************************/ /*! This function allocate space from the core */ /*************************************************************************/ rkv_t *rkvwspacemalloc(ctrl_t *ctrl, size_t n) { return (rkv_t *)wspacemalloc(ctrl, n*sizeof(rkv_t)); }
4,315
30.05036
85
c
null
ParMETIS-main/libparmetis/timer.c
/* * Copyright 1997, Regents of the University of Minnesota * * timer.c * * This file contain various timing routines * * Started 10/19/96 * George * * $Id: timer.c 10052 2011-06-01 22:29:57Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function initializes the various timers **************************************************************************/ void InitTimers(ctrl_t *ctrl) { cleartimer(ctrl->TotalTmr); cleartimer(ctrl->InitPartTmr); cleartimer(ctrl->MatchTmr); cleartimer(ctrl->ContractTmr); cleartimer(ctrl->CoarsenTmr); cleartimer(ctrl->RefTmr); cleartimer(ctrl->SetupTmr); cleartimer(ctrl->ProjectTmr); cleartimer(ctrl->KWayInitTmr); cleartimer(ctrl->KWayTmr); cleartimer(ctrl->MoveTmr); cleartimer(ctrl->RemapTmr); cleartimer(ctrl->SerialTmr); cleartimer(ctrl->AuxTmr1); cleartimer(ctrl->AuxTmr2); cleartimer(ctrl->AuxTmr3); cleartimer(ctrl->AuxTmr4); cleartimer(ctrl->AuxTmr5); cleartimer(ctrl->AuxTmr6); } /************************************************************************* * This function prints timing information about KMETIS **************************************************************************/ void PrintTimingInfo(ctrl_t *ctrl) { /* PrintTimer(ctrl, ctrl->CoarsenTmr, " Coarsening"); */ PrintTimer(ctrl, ctrl->SetupTmr, " Setup"); PrintTimer(ctrl, ctrl->MatchTmr, " Matching"); PrintTimer(ctrl, ctrl->ContractTmr, "Contraction"); PrintTimer(ctrl, ctrl->InitPartTmr, " InitPart"); /* PrintTimer(ctrl, ctrl->RefTmr, " Refinement"); */ PrintTimer(ctrl, ctrl->ProjectTmr, " Project"); PrintTimer(ctrl, ctrl->KWayInitTmr, " Initialize"); PrintTimer(ctrl, ctrl->KWayTmr, " K-way"); PrintTimer(ctrl, ctrl->SerialTmr, " Serial"); PrintTimer(ctrl, ctrl->MoveTmr, " Move"); PrintTimer(ctrl, ctrl->RemapTmr, " Remap"); PrintTimer(ctrl, ctrl->TotalTmr, " Total"); PrintTimer(ctrl, ctrl->AuxTmr1, " Aux1"); PrintTimer(ctrl, ctrl->AuxTmr2, " Aux2"); PrintTimer(ctrl, ctrl->AuxTmr3, " Aux3"); PrintTimer(ctrl, ctrl->AuxTmr4, " Aux4"); PrintTimer(ctrl, ctrl->AuxTmr5, " Aux5"); PrintTimer(ctrl, ctrl->AuxTmr6, " Aux6"); } /************************************************************************* * This function prints timer stat **************************************************************************/ void PrintTimer(ctrl_t *ctrl, timer tmr, char *msg) { double sum, max, tsec; tsec = gettimer(tmr); gkMPI_Reduce((void *)&tsec, (void *)&sum, 1, MPI_DOUBLE, MPI_SUM, 0, ctrl->comm); tsec = gettimer(tmr); gkMPI_Reduce((void *)&tsec, (void *)&max, 1, MPI_DOUBLE, MPI_MAX, 0, ctrl->comm); if (ctrl->mype == 0 && sum != 0.0) printf("%s: Max: %7.3"PRREAL", Sum: %7.3"PRREAL", Balance: %7.3"PRREAL"\n", msg, (real_t)max, (real_t)sum, (real_t)(max*ctrl->npes/sum)); }
3,030
31.591398
83
c
null
ParMETIS-main/libparmetis/gklib_rename.h
/*! \file * Copyright 1997, Regents of the University of Minnesota * * This file contains header files * * Started 10/2/97 * George * * $Id: gklib_rename.h 10395 2011-06-23 23:28:06Z karypis $ * */ #ifndef _LIBPARMETIS_GKLIB_RENAME_H_ #define _LIBPARMETIS_GKLIB_RENAME_H_ /* gklib.c - generated from the .o files using the ./utils/listundescapedsumbols.csh */ #define iAllocMatrix libparmetis__iAllocMatrix #define iFreeMatrix libparmetis__iFreeMatrix #define iSetMatrix libparmetis__iSetMatrix #define iargmax libparmetis__iargmax #define iargmax_n libparmetis__iargmax_n #define iargmin libparmetis__iargmin #define iarray2csr libparmetis__iarray2csr #define iaxpy libparmetis__iaxpy #define icopy libparmetis__icopy #define idot libparmetis__idot #define iincset libparmetis__iincset #define ikvAllocMatrix libparmetis__ikvAllocMatrix #define ikvFreeMatrix libparmetis__ikvFreeMatrix #define ikvSetMatrix libparmetis__ikvSetMatrix #define ikvcopy libparmetis__ikvcopy #define ikvmalloc libparmetis__ikvmalloc #define ikvrealloc libparmetis__ikvrealloc #define ikvset libparmetis__ikvset #define ikvsmalloc libparmetis__ikvsmalloc #define ikvsortd libparmetis__ikvsortd #define ikvsorti libparmetis__ikvsorti #define ikvsortii libparmetis__ikvsortii #define imalloc libparmetis__imalloc #define imax libparmetis__imax #define imin libparmetis__imin #define inorm2 libparmetis__inorm2 #define ipqCheckHeap libparmetis__ipqCheckHeap #define ipqCreate libparmetis__ipqCreate #define ipqDelete libparmetis__ipqDelete #define ipqDestroy libparmetis__ipqDestroy #define ipqFree libparmetis__ipqFree #define ipqGetTop libparmetis__ipqGetTop #define ipqInit libparmetis__ipqInit #define ipqInsert libparmetis__ipqInsert #define ipqLength libparmetis__ipqLength #define ipqReset libparmetis__ipqReset #define ipqSeeKey libparmetis__ipqSeeKey #define ipqSeeTopKey libparmetis__ipqSeeTopKey #define ipqSeeTopVal libparmetis__ipqSeeTopVal #define ipqUpdate libparmetis__ipqUpdate #define isrand libparmetis__isrand #define irand libparmetis__irand #define irandArrayPermute libparmetis__irandArrayPermute #define irandArrayPermuteFine libparmetis__irandArrayPermuteFine #define irandInRange libparmetis__irandInRange #define irealloc libparmetis__irealloc #define iscale libparmetis__iscale #define iset libparmetis__iset #define ismalloc libparmetis__ismalloc #define isortd libparmetis__isortd #define isorti libparmetis__isorti #define isrand libparmetis__isrand #define isum libparmetis__isum #define rAllocMatrix libparmetis__rAllocMatrix #define rFreeMatrix libparmetis__rFreeMatrix #define rSetMatrix libparmetis__rSetMatrix #define rargmax libparmetis__rargmax #define rargmax_n libparmetis__rargmax_n #define rargmin libparmetis__rargmin #define raxpy libparmetis__raxpy #define rcopy libparmetis__rcopy #define rdot libparmetis__rdot #define rincset libparmetis__rincset #define rkvAllocMatrix libparmetis__rkvAllocMatrix #define rkvFreeMatrix libparmetis__rkvFreeMatrix #define rkvSetMatrix libparmetis__rkvSetMatrix #define rkvcopy libparmetis__rkvcopy #define rkvmalloc libparmetis__rkvmalloc #define rkvrealloc libparmetis__rkvrealloc #define rkvset libparmetis__rkvset #define rkvsmalloc libparmetis__rkvsmalloc #define rkvsortd libparmetis__rkvsortd #define rkvsorti libparmetis__rkvsorti #define rmalloc libparmetis__rmalloc #define rmax libparmetis__rmax #define rmin libparmetis__rmin #define rnorm2 libparmetis__rnorm2 #define rpqCheckHeap libparmetis__rpqCheckHeap #define rpqCreate libparmetis__rpqCreate #define rpqDelete libparmetis__rpqDelete #define rpqDestroy libparmetis__rpqDestroy #define rpqFree libparmetis__rpqFree #define rpqGetTop libparmetis__rpqGetTop #define rpqInit libparmetis__rpqInit #define rpqInsert libparmetis__rpqInsert #define rpqLength libparmetis__rpqLength #define rpqReset libparmetis__rpqReset #define rpqSeeKey libparmetis__rpqSeeKey #define rpqSeeTopKey libparmetis__rpqSeeTopKey #define rpqSeeTopVal libparmetis__rpqSeeTopVal #define rpqUpdate libparmetis__rpqUpdate #define rrealloc libparmetis__rrealloc #define rscale libparmetis__rscale #define rset libparmetis__rset #define rsmalloc libparmetis__rsmalloc #define rsortd libparmetis__rsortd #define rsorti libparmetis__rsorti #define rsum libparmetis__rsum #define uvwsorti libparmetis__uvwsorti #endif
4,321
34.138211
87
h
null
ParMETIS-main/libparmetis/renumber.c
/* * Copyright 1997, Regents of the University of Minnesota * * mgrsetup.c * * This file contain various graph setting up routines * * Started 10/19/96 * George * * $Id: renumber.c 10531 2011-07-09 21:58:13Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function changes the numbering from 1 to 0 or 0 to 1 **************************************************************************/ void ChangeNumbering(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *part, idx_t npes, idx_t mype, idx_t from) { idx_t i, nvtxs; nvtxs = vtxdist[mype+1]-vtxdist[mype]; if (from == 1) { /* Change it from 1 to 0 */ for (i=0; i<npes+1; i++) vtxdist[i]--; for (i=0; i<nvtxs+1; i++) xadj[i]--; for (i=0; i<xadj[nvtxs]; i++) adjncy[i]--; } else { /* Change it from 0 to 1 */ for (i=0; i<npes+1; i++) vtxdist[i]++; for (i=0; i<xadj[nvtxs]; i++) adjncy[i]++; for (i=0; i<nvtxs+1; i++) xadj[i]++; for (i=0; i<nvtxs; i++) part[i]++; } } /************************************************************************* * This function changes the numbering from 1 to 0 or 0 to 1 **************************************************************************/ void ChangeNumberingMesh(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *xadj, idx_t *adjncy, idx_t *part, idx_t npes, idx_t mype, idx_t from) { idx_t i, nelms; nelms = elmdist[mype+1]-elmdist[mype]; if (from == 1) { /* Change it from 1 to 0 */ for (i=0; i<npes+1; i++) elmdist[i]--; for (i=0; i<nelms+1; i++) eptr[i]--; for (i=0; i<eptr[nelms]; i++) eind[i]--; } else { /* Change it from 0 to 1 */ for (i=0; i<npes+1; i++) elmdist[i]++; for (i=0; i<eptr[nelms]; i++) eind[i]++; for (i=0; i<nelms+1; i++) eptr[i]++; for (i=0; i<xadj[nelms]; i++) adjncy[i]++; for (i=0; i<nelms+1; i++) xadj[i]++; if (part != NULL) for (i=0; i<nelms; i++) part[i]++; } }
2,130
21.431579
113
c
null
ParMETIS-main/libparmetis/mmetis.c
/* * Copyright 1997, Regents of the University of Minnesota * * mmetis.c * * This is the entry point of ParMETIS_V3_PartMeshKway * * Started 10/19/96 * George * * $Id: mmetis.c 10573 2011-07-14 13:31:54Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the parallel k-way multilevel mesh partitionioner. * This function assumes nothing about the mesh distribution. * It is the general case. ************************************************************************************/ int ParMETIS_V3_PartMeshKway(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, status, nvtxs, nedges, gnedges, npes, mype; idx_t *xadj, *adjncy; ctrl_t *ctrl; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsPartMeshKway(elmdist, eptr, eind, elmwgt, wgtflag, numflag, ncon, ncommon, nparts, tpwgts, ubvec, options, edgecut, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_MKMETIS, NULL, 1, 1, NULL, NULL, *comm); npes = ctrl->npes; mype = ctrl->mype; /* Create the dual graph */ STARTTIMER(ctrl, ctrl->MoveTmr); ParMETIS_V3_Mesh2Dual(elmdist, eptr, eind, numflag, ncommon, &xadj, &adjncy, &(ctrl->comm)); if (ctrl->dbglvl&DBG_INFO) { nvtxs = elmdist[mype+1]-elmdist[mype]; nedges = xadj[nvtxs] + (*numflag == 0 ? 0 : -1); rprintf(ctrl, "Completed Dual Graph -- Nvtxs: %"PRIDX", Nedges: %"PRIDX" \n", elmdist[npes], GlobalSESum(ctrl, nedges)); } STOPTIMER(ctrl, ctrl->MoveTmr); /* Partition the dual graph */ STARTTIMER(ctrl, ctrl->TotalTmr); status = ParMETIS_V3_PartKway(elmdist, xadj, adjncy, elmwgt, NULL, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &(ctrl->comm)); STOPTIMER(ctrl, ctrl->TotalTmr); IFSET(ctrl->dbglvl, DBG_TIME, PrintTimer(ctrl, ctrl->MoveTmr, " Mesh2Dual")); IFSET(ctrl->dbglvl, DBG_TIME, PrintTimer(ctrl, ctrl->TotalTmr, " ParMETIS")); METIS_Free(xadj); METIS_Free(adjncy); FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; }
2,725
29.629213
89
c
null
ParMETIS-main/libparmetis/akwayfm.c
/* * Copyright 1997, Regents of the University of Minnesota * * makwayfm.c * * This file contains code that performs the k-way refinement * * Started 3/1/96 * George * * $Id: akwayfm.c 10528 2011-07-09 19:47:30Z karypis $ */ #include <parmetislib.h> #define ProperSide(c, from, other) \ (((c) == 0 && (from)-(other) < 0) || ((c) == 1 && (from)-(other) > 0)) /************************************************************************* * This function performs k-way refinement **************************************************************************/ void KWayAdaptiveRefine(ctrl_t *ctrl, graph_t *graph, idx_t npasses) { idx_t npes = ctrl->npes, mype = ctrl->mype, nparts = ctrl->nparts; idx_t h, i, ii, iii, j, k, c; idx_t pass, nvtxs, nedges, ncon; idx_t nmoves, nmoved; idx_t me, firstvtx, lastvtx, yourlastvtx; idx_t from, to = -1, oldto, oldcut, mydomain, yourdomain, imbalanced, overweight; idx_t nlupd, nsupd, nnbrs, nchanged, *nupds_pe; idx_t *xadj, *ladjncy, *adjwgt, *vtxdist; idx_t *where, *tmp_where, *moved, *oldEDs; real_t *lnpwgts, *gnpwgts, *ognpwgts, *pgnpwgts, *movewgts, *overfill; idx_t *update, *supdate, *rupdate, *pe_updates; idx_t *changed, *perm, *pperm, *htable; idx_t *peind, *recvptr, *sendptr; ikv_t *swchanges, *rwchanges; real_t *lbvec, *nvwgt, *badmaxpwgt, *ubvec, *tpwgts, lbavg, ubavg; real_t oldgain, gain; real_t ipc_factor, redist_factor, vsize; idx_t ndirty, nclean, dptr; idx_t better, worse; ckrinfo_t *myrinfo; cnbr_t *mynbrs; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayTmr)); WCOREPUSH; /*************************/ /* set up common aliases */ /*************************/ nvtxs = graph->nvtxs; nedges = graph->nedges; ncon = graph->ncon; vtxdist = graph->vtxdist; xadj = graph->xadj; ladjncy = graph->adjncy; adjwgt = graph->adjwgt; firstvtx = vtxdist[mype]; lastvtx = vtxdist[mype+1]; where = graph->where; lnpwgts = graph->lnpwgts; gnpwgts = graph->gnpwgts; ubvec = ctrl->ubvec; tpwgts = ctrl->tpwgts; ipc_factor = ctrl->ipc_factor; redist_factor = ctrl->redist_factor; nnbrs = graph->nnbrs; peind = graph->peind; recvptr = graph->recvptr; sendptr = graph->sendptr; /************************************/ /* set up important data structures */ /************************************/ lbvec = rwspacemalloc(ctrl, ncon); badmaxpwgt = rwspacemalloc(ctrl, nparts*ncon); movewgts = rwspacemalloc(ctrl, nparts*ncon); ognpwgts = rwspacemalloc(ctrl, nparts*ncon); pgnpwgts = rwspacemalloc(ctrl, nparts*ncon); overfill = rwspacemalloc(ctrl, nparts*ncon); pperm = iwspacemalloc(ctrl, nparts); nupds_pe = iwspacemalloc(ctrl, npes); oldEDs = iwspacemalloc(ctrl, nvtxs); changed = iwspacemalloc(ctrl, nvtxs); perm = iwspacemalloc(ctrl, nvtxs); update = iwspacemalloc(ctrl, nvtxs); moved = iwspacemalloc(ctrl, nvtxs); htable = iset(nvtxs+graph->nrecv, 0, iwspacemalloc(ctrl, nvtxs+graph->nrecv)); rwchanges = ikvwspacemalloc(ctrl, graph->nrecv); swchanges = ikvwspacemalloc(ctrl, graph->nsend); supdate = iwspacemalloc(ctrl, graph->nrecv); rupdate = iwspacemalloc(ctrl, graph->nsend); tmp_where = iwspacemalloc(ctrl, nvtxs+graph->nrecv); for (i=0; i<nparts; i++) { for (h=0; h<ncon; h++) badmaxpwgt[i*ncon+h] = ubvec[h]*tpwgts[i*ncon+h]; } icopy(nvtxs+graph->nrecv, where, tmp_where); /* this will record the overall external degrees of the vertices prior to a inner refinement iteration in order to allow for the proper updating of the lmincut */ for (i=0; i<nvtxs; i++) oldEDs[i] = graph->ckrinfo[i].ed; /*********************************************************/ /* perform a small number of passes through the vertices */ /*********************************************************/ for (pass=0; pass<npasses; pass++) { if (mype == 0) RandomPermute(nparts, pperm, 1); gkMPI_Bcast((void *)pperm, nparts, IDX_T, 0, ctrl->comm); oldcut = graph->mincut; /* FastRandomPermute(nvtxs, perm, 1); */ /*****************************/ /* move dirty vertices first */ /*****************************/ ndirty = 0; for (i=0; i<nvtxs; i++) if (where[i] != mype) ndirty++; dptr = 0; for (i=0; i<nvtxs; i++) if (where[i] != mype) perm[dptr++] = i; else perm[ndirty++] = i; PASSERT(ctrl, ndirty == nvtxs); ndirty = dptr; nclean = nvtxs-dptr; FastRandomPermute(ndirty, perm, 0); FastRandomPermute(nclean, perm+ndirty, 0); /* check to see if the partitioning is imbalanced */ ComputeParallelBalance(ctrl, graph, graph->where, lbvec); ubavg = ravg(ncon, ubvec); lbavg = ravg(ncon, lbvec); imbalanced = (lbavg > ubavg) ? 1 : 0; for (c=0; c<2; c++) { rcopy(ncon*nparts, gnpwgts, ognpwgts); rset(ncon*nparts, 0.0, movewgts); nmoved = 0; /**********************************************/ /* PASS ONE -- record stats for desired moves */ /**********************************************/ for (iii=0; iii<nvtxs; iii++) { i = perm[iii]; from = tmp_where[i]; nvwgt = graph->nvwgt+i*ncon; vsize = (real_t)(graph->vsize[i]); for (h=0; h<ncon; h++) { if (rabs(nvwgt[h]-gnpwgts[from*ncon+h]) < SMALLFLOAT) break; } if (h < ncon) continue; /* only check border vertices */ myrinfo = graph->ckrinfo + i; if (myrinfo->ed <= 0) continue; PASSERT(ctrl, myrinfo->inbr != -1); mynbrs = ctrl->cnbrpool + myrinfo->inbr; for (k=myrinfo->nnbrs-1; k>=0; k--) { to = mynbrs[k].pid; if (ProperSide(c, pperm[from], pperm[to])) { for (h=0; h<ncon; h++) { if (gnpwgts[to*ncon+h]+nvwgt[h] > badmaxpwgt[to*ncon+h] && nvwgt[h] > 0.0) break; } if (h == ncon) break; } } /* break out if you did not find a candidate */ if (k < 0) continue; oldto = to; /**************************/ /**************************/ switch (ctrl->ps_relation) { case PARMETIS_PSR_COUPLED: better = (oldto == mype) ? 1 : 0; worse = (from == mype) ? 1 : 0; break; case PARMETIS_PSR_UNCOUPLED: default: better = (oldto == graph->home[i]) ? 1 : 0; worse = (from == graph->home[i]) ? 1 : 0; break; } /**************************/ /**************************/ oldgain = ipc_factor * (real_t)(mynbrs[k].ed-myrinfo->id); if (better) oldgain += redist_factor * vsize; if (worse) oldgain -= redist_factor * vsize; for (j=k-1; j>=0; j--) { to = mynbrs[j].pid; if (ProperSide(c, pperm[from], pperm[to])) { /**************************/ /**************************/ switch (ctrl->ps_relation) { case PARMETIS_PSR_COUPLED: better = (to == mype) ? 1 : 0; break; case PARMETIS_PSR_UNCOUPLED: default: better = (to == graph->home[i]) ? 1 : 0; break; } /**************************/ /**************************/ gain = ipc_factor * (real_t)(mynbrs[j].ed-myrinfo->id); if (better) gain += redist_factor * vsize; if (worse) gain -= redist_factor * vsize; for (h=0; h<ncon; h++) { if (gnpwgts[to*ncon+h]+nvwgt[h] > badmaxpwgt[to*ncon+h] && nvwgt[h] > 0.0) break; } if (h == ncon) { if (gain > oldgain || (rabs(gain-oldgain) < SMALLFLOAT && IsHBalanceBetterTT(ncon,gnpwgts+oldto*ncon,gnpwgts+to*ncon,nvwgt,ubvec))){ oldgain = gain; oldto = to; k = j; } } } } to = oldto; gain = oldgain; if (gain > 0.0 || (gain > -1.0*SMALLFLOAT && (imbalanced || graph->level > 3 || iii % 8 == 0) && IsHBalanceBetterFT(ncon,gnpwgts+from*ncon,gnpwgts+to*ncon,nvwgt,ubvec))) { /****************************************/ /* Update tmp arrays of the moved vertex */ /****************************************/ tmp_where[i] = to; moved[nmoved++] = i; for (h=0; h<ncon; h++) { INC_DEC(lnpwgts[to*ncon+h], lnpwgts[from*ncon+h], nvwgt[h]); INC_DEC(gnpwgts[to*ncon+h], gnpwgts[from*ncon+h], nvwgt[h]); INC_DEC(movewgts[to*ncon+h], movewgts[from*ncon+h], nvwgt[h]); } myrinfo->ed += myrinfo->id-mynbrs[k].ed; gk_SWAP(myrinfo->id, mynbrs[k].ed, j); if (mynbrs[k].ed == 0) mynbrs[k] = mynbrs[--myrinfo->nnbrs]; else mynbrs[k].pid = from; /* Update the degrees of adjacent vertices */ for (j=xadj[i]; j<xadj[i+1]; j++) { /* no need to bother about vertices on different pe's */ if (ladjncy[j] >= nvtxs) continue; me = ladjncy[j]; mydomain = tmp_where[me]; myrinfo = graph->ckrinfo+me; if (myrinfo->inbr == -1) { myrinfo->inbr = cnbrpoolGetNext(ctrl, xadj[me+1]-xadj[me]); myrinfo->nnbrs = 0; } mynbrs = ctrl->cnbrpool + myrinfo->inbr; if (mydomain == from) { INC_DEC(myrinfo->ed, myrinfo->id, adjwgt[j]); } else { if (mydomain == to) { INC_DEC(myrinfo->id, myrinfo->ed, adjwgt[j]); } } /* Remove contribution from the .ed of 'from' */ if (mydomain != from) { for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == from) { if (mynbrs[k].ed == adjwgt[j]) mynbrs[k] = mynbrs[--myrinfo->nnbrs]; else mynbrs[k].ed -= adjwgt[j]; break; } } } /* Add contribution to the .ed of 'to' */ if (mydomain != to) { for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == to) { mynbrs[k].ed += adjwgt[j]; break; } } if (k == myrinfo->nnbrs) { mynbrs[k].pid = to; mynbrs[k].ed = adjwgt[j]; myrinfo->nnbrs++; } } } } } /******************************************/ /* Let processors know the subdomain wgts */ /* if all proposed moves commit. */ /******************************************/ gkMPI_Allreduce((void *)lnpwgts, (void *)pgnpwgts, nparts*ncon, REAL_T, MPI_SUM, ctrl->comm); /**************************/ /* compute overfill array */ /**************************/ overweight = 0; for (j=0; j<nparts; j++) { for (h=0; h<ncon; h++) { if (pgnpwgts[j*ncon+h] > ognpwgts[j*ncon+h]) overfill[j*ncon+h] = (pgnpwgts[j*ncon+h]-badmaxpwgt[j*ncon+h]) / (pgnpwgts[j*ncon+h]-ognpwgts[j*ncon+h]); else overfill[j*ncon+h] = 0.0; overfill[j*ncon+h] =gk_max(overfill[j*ncon+h], 0.0); overfill[j*ncon+h] *= movewgts[j*ncon+h]; if (overfill[j*ncon+h] > 0.0) overweight = 1; PASSERTP(ctrl, ognpwgts[j*ncon+h] <= badmaxpwgt[j*ncon+h] || pgnpwgts[j*ncon+h] <= ognpwgts[j*ncon+h], (ctrl, "%.4"PRREAL" %.4"PRREAL" %.4"PRREAL"\n", ognpwgts[j*ncon+h], badmaxpwgt[j*ncon+h], pgnpwgts[j*ncon+h])); } } /****************************************************/ /* select moves to undo according to overfill array */ /****************************************************/ if (overweight == 1) { for (iii=0; iii<nmoved; iii++) { i = moved[iii]; oldto = tmp_where[i]; nvwgt = graph->nvwgt+i*ncon; myrinfo = graph->ckrinfo + i; mynbrs = ctrl->cnbrpool + myrinfo->inbr; PASSERT(ctrl, myrinfo->nnbrs == 0 || myrinfo->inbr != -1); for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == where[i]) break; } for (h=0; h<ncon; h++) { if (nvwgt[h] > 0.0 && overfill[oldto*ncon+h] > nvwgt[h]/4.0) break; } /**********************************/ /* nullify this move if necessary */ /**********************************/ if (k != myrinfo->nnbrs && h != ncon) { moved[iii] = -1; from = oldto; to = where[i]; for (h=0; h<ncon; h++) overfill[oldto*ncon+h] =gk_max(overfill[oldto*ncon+h]-nvwgt[h], 0.0); tmp_where[i] = to; myrinfo->ed += myrinfo->id-mynbrs[k].ed; gk_SWAP(myrinfo->id, mynbrs[k].ed, j); if (mynbrs[k].ed == 0) mynbrs[k] = mynbrs[--myrinfo->nnbrs]; else mynbrs[k].pid = from; for (h=0; h<ncon; h++) INC_DEC(lnpwgts[to*ncon+h], lnpwgts[from*ncon+h], nvwgt[h]); /* Update the degrees of adjacent vertices */ for (j=xadj[i]; j<xadj[i+1]; j++) { /* no need to bother about vertices on different pe's */ if (ladjncy[j] >= nvtxs) continue; me = ladjncy[j]; mydomain = tmp_where[me]; myrinfo = graph->ckrinfo+me; if (myrinfo->inbr == -1) { myrinfo->inbr = cnbrpoolGetNext(ctrl, xadj[me+1]-xadj[me]); myrinfo->nnbrs = 0; } mynbrs = ctrl->cnbrpool + myrinfo->inbr; if (mydomain == from) { INC_DEC(myrinfo->ed, myrinfo->id, adjwgt[j]); } else { if (mydomain == to) { INC_DEC(myrinfo->id, myrinfo->ed, adjwgt[j]); } } /* Remove contribution from the .ed of 'from' */ if (mydomain != from) { for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == from) { if (mynbrs[k].ed == adjwgt[j]) mynbrs[k] = mynbrs[--myrinfo->nnbrs]; else mynbrs[k].ed -= adjwgt[j]; break; } } } /* Add contribution to the .ed of 'to' */ if (mydomain != to) { for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == to) { mynbrs[k].ed += adjwgt[j]; break; } } if (k == myrinfo->nnbrs) { mynbrs[k].pid = to; mynbrs[k].ed = adjwgt[j]; myrinfo->nnbrs++; } } } } } } /*************************************************/ /* PASS TWO -- commit the remainder of the moves */ /*************************************************/ nlupd = nsupd = nmoves = nchanged = 0; for (iii=0; iii<nmoved; iii++) { i = moved[iii]; if (i == -1) continue; where[i] = tmp_where[i]; /* Make sure to update the vertex information */ if (htable[i] == 0) { /* make sure you do the update */ htable[i] = 1; update[nlupd++] = i; } /* Put the vertices adjacent to i into the update array */ for (j=xadj[i]; j<xadj[i+1]; j++) { k = ladjncy[j]; if (htable[k] == 0) { htable[k] = 1; if (k<nvtxs) update[nlupd++] = k; else supdate[nsupd++] = k; } } nmoves++; if (graph->pexadj[i+1]-graph->pexadj[i] > 0) changed[nchanged++] = i; } /* Tell interested pe's the new where[] info for the interface vertices */ CommChangedInterfaceData(ctrl, graph, nchanged, changed, where, swchanges, rwchanges); IFSET(ctrl->dbglvl, DBG_RMOVEINFO, rprintf(ctrl, "\t[%"PRIDX" %"PRIDX"], [%.4"PRREAL"], [%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"]\n", pass, c, badmaxpwgt[0], GlobalSESum(ctrl, nmoved), GlobalSESum(ctrl, nmoves), GlobalSESum(ctrl, nsupd), GlobalSESum(ctrl, nlupd))); /*------------------------------------------------------------- / Time to communicate with processors to send the vertices / whose degrees need to be update. /-------------------------------------------------------------*/ /* Issue the receives first */ for (i=0; i<nnbrs; i++) gkMPI_Irecv((void *)(rupdate+sendptr[i]), sendptr[i+1]-sendptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); /* Issue the sends next. This needs some preporcessing */ for (i=0; i<nsupd; i++) { htable[supdate[i]] = 0; supdate[i] = graph->imap[supdate[i]]; } isorti(nsupd, supdate); for (j=i=0; i<nnbrs; i++) { yourlastvtx = vtxdist[peind[i]+1]; for (k=j; k<nsupd && supdate[k] < yourlastvtx; k++); gkMPI_Isend((void *)(supdate+j), k-j, IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); j = k; } /* OK, now get into the loop waiting for the send/recv operations to finish */ gkMPI_Waitall(nnbrs, ctrl->rreq, ctrl->statuses); for (i=0; i<nnbrs; i++) gkMPI_Get_count(ctrl->statuses+i, IDX_T, nupds_pe+i); gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); /*------------------------------------------------------------- / Place the received to-be updated vertices into update[] /-------------------------------------------------------------*/ for (i=0; i<nnbrs; i++) { pe_updates = rupdate+sendptr[i]; for (j=0; j<nupds_pe[i]; j++) { k = pe_updates[j]; if (htable[k-firstvtx] == 0) { htable[k-firstvtx] = 1; update[nlupd++] = k-firstvtx; } } } /*------------------------------------------------------------- / Update the rinfo of the vertices in the update[] array /-------------------------------------------------------------*/ for (ii=0; ii<nlupd; ii++) { i = update[ii]; PASSERT(ctrl, htable[i] == 1); htable[i] = 0; mydomain = where[i]; myrinfo = graph->ckrinfo+i; if (myrinfo->inbr == -1) myrinfo->inbr = cnbrpoolGetNext(ctrl, xadj[i+1]-xadj[i]); mynbrs = ctrl->cnbrpool + myrinfo->inbr; graph->lmincut -= oldEDs[i]; myrinfo->nnbrs = 0; myrinfo->id = 0; myrinfo->ed = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { yourdomain = where[ladjncy[j]]; if (mydomain != yourdomain) { myrinfo->ed += adjwgt[j]; for (k=0; k<myrinfo->nnbrs; k++) { if (mynbrs[k].pid == yourdomain) { mynbrs[k].ed += adjwgt[j]; break; } } if (k == myrinfo->nnbrs) { mynbrs[k].pid = yourdomain; mynbrs[k].ed = adjwgt[j]; myrinfo->nnbrs++; } PASSERT(ctrl, myrinfo->nnbrs <= xadj[i+1]-xadj[i]); } else { myrinfo->id += adjwgt[j]; } } graph->lmincut += myrinfo->ed; oldEDs[i] = myrinfo->ed; /* for the next iteration */ } /* finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lnpwgts, (void *)gnpwgts, nparts*ncon, REAL_T, MPI_SUM, ctrl->comm); } graph->mincut = GlobalSESum(ctrl, graph->lmincut)/2; IFSET(ctrl->dbglvl, DBG_RMOVEINFO, rprintf(ctrl, "\t\tcut: %"PRIDX"\n", graph->mincut)); if (graph->mincut == oldcut) break; } WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayTmr)); }
20,868
31.916404
97
c
null
ParMETIS-main/libparmetis/gkmetis.c
/* * Copyright 1997, Regents of the University of Minnesota * * gkmetis.c * * This is the entry point of parallel geometry based partitioning * routines * * Started 10/19/96 * George * * $Id: gkmetis.c 10663 2011-08-04 03:54:49Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the parallel kmetis algorithm that uses * coordinates to compute an initial graph distribution. ************************************************************************************/ int ParMETIS_V3_PartGeomKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t h, i, j, npes, mype, status, nvtxs, seed, dbglvl; idx_t cut, gcut, maxnvtxs; idx_t moptions[METIS_NOPTIONS]; ctrl_t *ctrl; graph_t *graph, *mgraph; real_t balance; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsPartGeomKway(vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ndims, xyz, ncon, nparts, tpwgts, ubvec, options, edgecut, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_GKMETIS, options, *ncon, *nparts, tpwgts, ubvec, *comm); npes = ctrl->npes; mype = ctrl->mype; /* Take care the nparts == 1 case */ if (*nparts == 1) { iset(vtxdist[mype+1]-vtxdist[mype], (*numflag == 0 ? 0 : 1), part); *edgecut = 0; goto DONE; } /* Take care of npes == 1 case */ if (npes == 1) { nvtxs = vtxdist[1] - vtxdist[0]; /* subtraction is required when numflag==1 */ METIS_SetDefaultOptions(moptions); moptions[METIS_OPTION_NUMBERING] = *numflag; status = METIS_PartGraphKway(&nvtxs, ncon, xadj, adjncy, vwgt, NULL, adjwgt, nparts, tpwgts, ubvec, moptions, edgecut, part); goto DONE; } /* Setup the graph */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 1); graph = SetupGraph(ctrl, *ncon, vtxdist, xadj, vwgt, NULL, adjncy, adjwgt, *wgtflag); gk_free((void **)&graph->nvwgt, LTERM); /* Allocate the workspace */ AllocateWSpace(ctrl, 10*graph->nvtxs); /* Compute the initial npes-way partitioning geometric partitioning */ STARTTIMER(ctrl, ctrl->TotalTmr); Coordinate_Partition(ctrl, graph, *ndims, xyz, 1); STOPTIMER(ctrl, ctrl->TotalTmr); /* Move the graph according to the partitioning */ STARTTIMER(ctrl, ctrl->MoveTmr); ctrl->nparts = npes; mgraph = MoveGraph(ctrl, graph); ctrl->nparts = *nparts; SetupGraph_nvwgts(ctrl, mgraph); /* compute nvwgts for the moved graph */ if (ctrl->dbglvl&DBG_INFO) { CommInterfaceData(ctrl, graph, graph->where, graph->where+graph->nvtxs); for (cut=0, i=0; i<graph->nvtxs; i++) { for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++) { if (graph->where[i] != graph->where[graph->adjncy[j]]) cut += graph->adjwgt[j]; } } gcut = GlobalSESum(ctrl, cut)/2; maxnvtxs = GlobalSEMax(ctrl, mgraph->nvtxs); balance = (real_t)(maxnvtxs)/((real_t)(graph->gnvtxs)/(real_t)(npes)); rprintf(ctrl, "XYZ Cut: %6"PRIDX" \tBalance: %6.3"PRREAL" [%"PRIDX" %"PRIDX" %"PRIDX"]\n", gcut, balance, maxnvtxs, graph->gnvtxs, npes); } STOPTIMER(ctrl, ctrl->MoveTmr); /* Compute the partition of the moved graph */ STARTTIMER(ctrl, ctrl->TotalTmr); ctrl->CoarsenTo = gk_min(vtxdist[npes]+1, 25*(*ncon)*gk_max(npes, *nparts)); if (vtxdist[npes] < SMALLGRAPH || vtxdist[npes] < npes*20 || GlobalSESum(ctrl, mgraph->nedges) == 0) { /* serially */ IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Partitioning a graph of size %"PRIDX" serially\n", vtxdist[npes])); PartitionSmallGraph(ctrl, mgraph); } else { /* in parallel */ Global_Partition(ctrl, mgraph); } ParallelReMapGraph(ctrl, mgraph); /* Invert the ordering back to the original graph */ ctrl->nparts = npes; ProjectInfoBack(ctrl, graph, part, mgraph->where); ctrl->nparts = *nparts; *edgecut = mgraph->mincut; STOPTIMER(ctrl, ctrl->TotalTmr); /* Print some stats */ IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); IFSET(ctrl->dbglvl, DBG_INFO, PrintPostPartInfo(ctrl, mgraph, 0)); FreeGraph(mgraph); FreeInitialGraphAndRemap(graph); if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 0); DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; } /*********************************************************************************** * This function is the entry point of the parallel ordering algorithm. * This function assumes that the graph is already nice partitioned among the * processors and then proceeds to perform recursive bisection. ************************************************************************************/ int ParMETIS_V3_PartGeom(idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Comm *comm) { idx_t i, nvtxs, firstvtx, npes, mype, status; idx_t *xadj, *adjncy; ctrl_t *ctrl=NULL; graph_t *graph=NULL; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsPartGeom(vtxdist, ndims, xyz, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_GMETIS, NULL, 1, 1, NULL, NULL, *comm); /*ctrl->dbglvl=15;*/ npes = ctrl->npes; mype = ctrl->mype; /* Trivial case when npes == 1 */ if (npes == 1) { iset(vtxdist[mype+1]-vtxdist[mype], 0, part); goto DONE; } /* Setup a fake graph to allow the rest of the code to work unchanged */ nvtxs = vtxdist[mype+1]-vtxdist[mype]; firstvtx = vtxdist[mype]; xadj = imalloc(nvtxs+1, "ParMETIS_PartGeom: xadj"); adjncy = imalloc(nvtxs, "ParMETIS_PartGeom: adjncy"); for (i=0; i<nvtxs; i++) { xadj[i] = i; adjncy[i] = firstvtx + (i+1)%nvtxs; } xadj[nvtxs] = nvtxs; graph = SetupGraph(ctrl, 1, vtxdist, xadj, NULL, NULL, adjncy, NULL, 0); /* Allocate workspace memory */ AllocateWSpace(ctrl, 5*graph->nvtxs); /* Compute the initial geometric partitioning */ STARTTIMER(ctrl, ctrl->TotalTmr); Coordinate_Partition(ctrl, graph, *ndims, xyz, 0); icopy(graph->nvtxs, graph->where, part); STOPTIMER(ctrl, ctrl->TotalTmr); IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); gk_free((void **)&xadj, (void **)&adjncy, LTERM); FreeInitialGraphAndRemap(graph); DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; }
7,399
27.682171
94
c
null
ParMETIS-main/libparmetis/initpart.c
/* * Copyright 1997, Regents of the University of Minnesota * * initpart.c * * This file contains code that performs log(p) parallel multilevel * recursive bissection * * Started 3/4/96 * George * * $Id: initpart.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define DEBUG_IPART_ /************************************************************************* * This function is the entry point of the initial partition algorithm * that does recursive bissection. * This algorithm assembles the graph to all the processors and preceeds * by parallelizing the recursive bisection step. **************************************************************************/ void InitPartition(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, ncon, mype, npes, gnvtxs, ngroups; idx_t *xadj, *adjncy, *adjwgt, *vwgt; idx_t *part, *gwhere0, *gwhere1; idx_t *tmpwhere, *tmpvwgt, *tmpxadj, *tmpadjncy, *tmpadjwgt; graph_t *agraph; idx_t lnparts, fpart, fpe, lnpes; idx_t twoparts=2, moptions[METIS_NOPTIONS], edgecut, max_cut; real_t *tpwgts, *tpwgts2, *lbvec, lbsum, min_lbsum, wsum; MPI_Comm ipcomm; struct { double sum; int rank; } lpesum, gpesum; WCOREPUSH; ncon = graph->ncon; ngroups = gk_max(gk_min(RIP_SPLIT_FACTOR, ctrl->npes), 1); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->InitPartTmr)); lbvec = rwspacemalloc(ctrl, ncon); /* assemble the graph to all the processors */ agraph = AssembleAdaptiveGraph(ctrl, graph); gnvtxs = agraph->nvtxs; /* make a copy of the graph's structure for later */ xadj = icopy(gnvtxs+1, agraph->xadj, iwspacemalloc(ctrl, gnvtxs+1)); vwgt = icopy(gnvtxs*ncon, agraph->vwgt, iwspacemalloc(ctrl, gnvtxs*ncon)); adjncy = icopy(agraph->nedges, agraph->adjncy, iwspacemalloc(ctrl, agraph->nedges)); adjwgt = icopy(agraph->nedges, agraph->adjwgt, iwspacemalloc(ctrl, agraph->nedges)); part = iwspacemalloc(ctrl, gnvtxs); /* create different processor groups */ gkMPI_Comm_split(ctrl->gcomm, ctrl->mype % ngroups, 0, &ipcomm); gkMPI_Comm_rank(ipcomm, &mype); gkMPI_Comm_size(ipcomm, &npes); /* Go into the recursive bisection */ METIS_SetDefaultOptions(moptions); moptions[METIS_OPTION_SEED] = ctrl->sync + (ctrl->mype % ngroups) + 1; if (ctrl->fast) { moptions[METIS_OPTION_NITER] = 1; moptions[METIS_OPTION_NIPARTS] = 1; moptions[METIS_OPTION_DROPEDGES] = 1; moptions[METIS_OPTION_ONDISK] = 1; //moptions[METIS_OPTION_NO2HOP] = 0; } tpwgts = ctrl->tpwgts; tpwgts2 = rwspacemalloc(ctrl, 2*ncon); lnparts = ctrl->nparts; fpart = fpe = 0; lnpes = npes; while (lnpes > 1 && lnparts > 1) { /* determine the weights of the two partitions as a function of the weight of the target partition weights */ for (j=(lnparts>>1), i=0; i<ncon; i++) { tpwgts2[i] = rsum(j, tpwgts+fpart*ncon+i, ncon); tpwgts2[ncon+i] = rsum(lnparts-j, tpwgts+(fpart+j)*ncon+i, ncon); wsum = 1.0/(tpwgts2[i] + tpwgts2[ncon+i]); tpwgts2[i] *= wsum; tpwgts2[ncon+i] *= wsum; } METIS_PartGraphRecursive(&agraph->nvtxs, &ncon, agraph->xadj, agraph->adjncy, agraph->vwgt, NULL, agraph->adjwgt, &twoparts, tpwgts2, NULL, moptions, &edgecut, part); /* pick one of the branches */ if (mype < fpe+lnpes/2) { KeepPart(ctrl, agraph, part, 0); lnpes = lnpes/2; lnparts = lnparts/2; } else { KeepPart(ctrl, agraph, part, 1); fpart = fpart + lnparts/2; fpe = fpe + lnpes/2; lnpes = lnpes - lnpes/2; lnparts = lnparts - lnparts/2; } } gwhere0 = iset(gnvtxs, 0, iwspacemalloc(ctrl, gnvtxs)); gwhere1 = iwspacemalloc(ctrl, gnvtxs); if (lnparts == 1) { /* Case npes is greater than or equal to nparts */ /* Only the first process will assign labels (for the reduction to work) */ if (mype == fpe) { for (i=0; i<agraph->nvtxs; i++) gwhere0[agraph->label[i]] = fpart; } } else { /* Case in which npes is smaller than nparts */ /* create the normalized tpwgts for the lnparts from ctrl->tpwgts */ tpwgts = rwspacemalloc(ctrl, lnparts*ncon); for (j=0; j<ncon; j++) { for (wsum=0.0, i=0; i<lnparts; i++) { tpwgts[i*ncon+j] = ctrl->tpwgts[(fpart+i)*ncon+j]; wsum += tpwgts[i*ncon+j]; } for (wsum=1.0/wsum, i=0; i<lnparts; i++) tpwgts[i*ncon+j] *= wsum; } METIS_PartGraphKway(&agraph->nvtxs, &ncon, agraph->xadj, agraph->adjncy, agraph->vwgt, NULL, agraph->adjwgt, &lnparts, tpwgts, NULL, moptions, &edgecut, part); for (i=0; i<agraph->nvtxs; i++) gwhere0[agraph->label[i]] = fpart + part[i]; } gkMPI_Allreduce((void *)gwhere0, (void *)gwhere1, gnvtxs, IDX_T, MPI_SUM, ipcomm); if (ngroups > 1) { tmpxadj = agraph->xadj; tmpadjncy = agraph->adjncy; tmpadjwgt = agraph->adjwgt; tmpvwgt = agraph->vwgt; tmpwhere = agraph->where; agraph->xadj = xadj; agraph->adjncy = adjncy; agraph->adjwgt = adjwgt; agraph->vwgt = vwgt; agraph->where = gwhere1; agraph->vwgt = vwgt; agraph->nvtxs = gnvtxs; edgecut = ComputeSerialEdgeCut(agraph); ComputeSerialBalance(ctrl, agraph, gwhere1, lbvec); lbsum = rsum(ncon, lbvec, 1); gkMPI_Allreduce((void *)&edgecut, (void *)&max_cut, 1, IDX_T, MPI_MAX, ctrl->gcomm); gkMPI_Allreduce((void *)&lbsum, (void *)&min_lbsum, 1, REAL_T, MPI_MIN, ctrl->gcomm); lpesum.sum = lbsum; if (min_lbsum < UNBALANCE_FRACTION*ncon) { if (lbsum < UNBALANCE_FRACTION*ncon) lpesum.sum = edgecut; else lpesum.sum = max_cut; } lpesum.rank = ctrl->mype; gkMPI_Allreduce((void *)&lpesum, (void *)&gpesum, 1, MPI_DOUBLE_INT, MPI_MINLOC, ctrl->gcomm); gkMPI_Bcast((void *)gwhere1, gnvtxs, IDX_T, gpesum.rank, ctrl->gcomm); agraph->xadj = tmpxadj; agraph->adjncy = tmpadjncy; agraph->adjwgt = tmpadjwgt; agraph->vwgt = tmpvwgt; agraph->where = tmpwhere; } icopy(graph->nvtxs, gwhere1+graph->vtxdist[ctrl->mype], graph->where); FreeGraph(agraph); gkMPI_Comm_free(&ipcomm); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->InitPartTmr)); WCOREPOP; } /************************************************************************* * This function keeps one parts **************************************************************************/ void KeepPart(ctrl_t *ctrl, graph_t *graph, idx_t *part, idx_t mypart) { idx_t h, i, j, k; idx_t nvtxs, ncon, mynvtxs, mynedges; idx_t *xadj, *vwgt, *adjncy, *adjwgt, *label; idx_t *rename; WCOREPUSH; nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; vwgt = graph->vwgt; adjncy = graph->adjncy; adjwgt = graph->adjwgt; label = graph->label; rename = iwspacemalloc(ctrl, nvtxs); for (mynvtxs=0, i=0; i<nvtxs; i++) { if (part[i] == mypart) rename[i] = mynvtxs++; } for (mynvtxs=0, mynedges=0, j=xadj[0], i=0; i<nvtxs; i++) { if (part[i] == mypart) { for (; j<xadj[i+1]; j++) { k = adjncy[j]; if (part[k] == mypart) { adjncy[mynedges] = rename[k]; adjwgt[mynedges++] = adjwgt[j]; } } j = xadj[i+1]; /* Save xadj[i+1] for later use */ for (h=0; h<ncon; h++) vwgt[mynvtxs*ncon+h] = vwgt[i*ncon+h]; label[mynvtxs] = label[i]; xadj[++mynvtxs] = mynedges; } else { j = xadj[i+1]; /* Save xadj[i+1] for later use */ } } graph->nvtxs = mynvtxs; graph->nedges = mynedges; WCOREPOP; }
7,758
28.727969
91
c
null
ParMETIS-main/libparmetis/rmetis.c
/* * Copyright 1997, Regents of the University of Minnesota * * rmetis.c * * This is the entry point of the partitioning refinement routine * * Started 10/19/96 * George * * $Id: rmetis.c 10612 2011-07-21 20:09:05Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the parallel multilevel local diffusion * algorithm. It uses parallel undirected diffusion followed by adaptive k-way * refinement. This function utilizes local coarsening. ************************************************************************************/ int ParMETIS_V3_RefineKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t npes, mype, status; ctrl_t *ctrl=NULL; graph_t *graph=NULL; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsPartKway(vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup ctrl */ ctrl = SetupCtrl(PARMETIS_OP_RMETIS, options, *ncon, *nparts, tpwgts, ubvec, *comm); npes = ctrl->npes; mype = ctrl->mype; /* Take care the nparts == 1 case */ if (*nparts == 1) { iset(vtxdist[mype+1]-vtxdist[mype], (*numflag == 0 ? 0 : 1), part); *edgecut = 0; goto DONE; } /* setup the graph */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 1); graph = SetupGraph(ctrl, *ncon, vtxdist, xadj, vwgt, NULL, adjncy, adjwgt, *wgtflag); if (ctrl->ps_relation == PARMETIS_PSR_COUPLED) iset(graph->nvtxs, mype, graph->home); else icopy(graph->nvtxs, part, graph->home); /* Allocate workspace */ AllocateWSpace(ctrl, 10*graph->nvtxs); /* Partition and Remap */ STARTTIMER(ctrl, ctrl->TotalTmr); ctrl->CoarsenTo = gk_min(vtxdist[npes]+1, 50*(*ncon)*gk_max(npes, *nparts)); Adaptive_Partition(ctrl, graph); ParallelReMapGraph(ctrl, graph); icopy(graph->nvtxs, graph->where, part); *edgecut = graph->mincut; STOPTIMER(ctrl, ctrl->TotalTmr); /* Take care of output */ IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); IFSET(ctrl->dbglvl, DBG_INFO, PrintPostPartInfo(ctrl, graph, 1)); FreeInitialGraphAndRemap(graph); if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 0); DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; }
3,045
26.690909
87
c
null
ParMETIS-main/libparmetis/graph.c
/* * Copyright 1997, Regents of the University of Minnesota * * graph.c * * This file contains routines that deal with setting up and freeing the * graph structure. * * Started 2/24/96 * George * * $Id: memory.c 10412 2011-06-25 23:12:57Z karypis $ * */ #include <parmetislib.h> /*************************************************************************/ /*! This function creates the graph from the user's inputs */ /*************************************************************************/ graph_t *SetupGraph(ctrl_t *ctrl, idx_t ncon, idx_t *vtxdist, idx_t *xadj, idx_t *vwgt, idx_t *vsize, idx_t *adjncy, idx_t *adjwgt, idx_t wgtflag) { idx_t i, j; graph_t *graph; graph = CreateGraph(); graph->level = 0; graph->gnvtxs = vtxdist[ctrl->npes]; graph->nvtxs = vtxdist[ctrl->mype+1]-vtxdist[ctrl->mype]; graph->ncon = ncon; graph->nedges = xadj[graph->nvtxs]; graph->xadj = xadj; graph->vwgt = vwgt; graph->vsize = vsize; graph->adjncy = adjncy; graph->adjwgt = adjwgt; graph->vtxdist = vtxdist; graph->free_xadj = 0; graph->free_adjncy = 0; /* allocate memory for weight arrays if not provided */ if ((wgtflag&2) == 0 || vwgt == NULL) graph->vwgt = ismalloc(graph->nvtxs*ncon, 1, "SetupGraph: vwgt"); else graph->free_vwgt = 0; if ((wgtflag&1) == 0 || adjwgt == NULL) graph->adjwgt = ismalloc(graph->nedges, 1, "SetupGraph: adjwgt"); else graph->free_adjwgt = 0; /* allocate memory for special arrays that apply only to some optypes */ if (ctrl->optype == PARMETIS_OP_AMETIS || ctrl->optype == PARMETIS_OP_RMETIS) { if (vsize == NULL) graph->vsize = ismalloc(graph->nvtxs, 1, "vsize"); else graph->free_vsize = 0; graph->home = ismalloc(graph->nvtxs, 1, "home"); /* determine edge_size_ratio */ ctrl->edge_size_ratio = (.1+(real_t)GlobalSESum(ctrl, isum(graph->nedges, graph->adjwgt, 1))) / (.1+(real_t)GlobalSESum(ctrl, isum(graph->nvtxs, graph->vsize, 1))); } /* compute invtvwgts */ SetupCtrl_invtvwgts(ctrl, graph); /* compute nvwgts */ SetupGraph_nvwgts(ctrl, graph); return graph; } /*************************************************************************/ /*! This function creates the nvwgt of the graph */ /*************************************************************************/ void SetupGraph_nvwgts(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nvtxs, ncon; idx_t *vwgt; real_t *nvwgt, *invtvwgts; nvtxs = graph->nvtxs; ncon = graph->ncon; vwgt = graph->vwgt; invtvwgts = ctrl->invtvwgts; /* compute nvwgts */ nvwgt = graph->nvwgt = rmalloc(nvtxs*ncon, "SetupGraph_nvwgts: graph->nvwgt"); for (i=0; i<nvtxs; i++) { for (j=0; j<ncon; j++) nvwgt[i*ncon+j] = invtvwgts[j]*vwgt[i*ncon+j]; } } /*************************************************************************/ /*! This function creates a Coarsegraph_t data structure and initializes the various fields. */ /*************************************************************************/ graph_t *CreateGraph(void) { graph_t *graph; graph = (graph_t *)gk_malloc(sizeof(graph_t), "CreateGraph: graph"); InitGraph(graph); return graph; } /*************************************************************************/ /*! This function creates a Coarsegraph_t data structure and initializes the various fields */ /*************************************************************************/ void InitGraph(graph_t *graph) { memset(graph, 0, sizeof(graph_t)); graph->gnvtxs = graph->nvtxs = graph->nedges = graph->nsep = -1; graph->nnbrs = graph->nrecv = graph->nsend = graph->nlocal = -1; graph->xadj = graph->vwgt = graph->vsize = graph->adjncy = graph->adjwgt = NULL; graph->nvwgt = NULL; graph->vtxdist = NULL; graph->match = graph->cmap = NULL; graph->label = NULL; graph->peind = NULL; graph->sendptr = graph->sendind = graph->recvptr = graph->recvind = NULL; graph->imap = NULL; graph->pexadj = graph->peadjncy = graph->peadjloc = NULL; graph->lperm = NULL; graph->slens = graph->rlens = NULL; graph->rcand = NULL; graph->where = graph->home = graph->lpwgts = graph->gpwgts = NULL; graph->lnpwgts = graph->gnpwgts = NULL; graph->ckrinfo = NULL; graph->nrinfo = NULL; graph->sepind = NULL; graph->coarser = graph->finer = NULL; graph->free_xadj = graph->free_adjncy = graph->free_vwgt = graph->free_adjwgt = graph->free_vsize = 1; } /*************************************************************************/ /*! This function deallocates any memory stored in a graph */ /*************************************************************************/ void FreeGraph(graph_t *graph) { /* Graph structure fields */ gk_free((void **)&graph->xadj, (void **)&graph->vwgt, (void **)&graph->nvwgt, (void **)&graph->vsize, (void **)&graph->adjncy, (void **)&graph->adjwgt, (void **)&graph->vtxdist, (void **)&graph->home, LTERM); FreeNonGraphFields(graph); gk_free((void **)&graph, LTERM); } /*************************************************************************/ /*! This function deallocates the non-graph structure fields of a graph data structure */ /*************************************************************************/ void FreeNonGraphFields(graph_t *graph) { gk_free( /* Coarsening fields */ (void **)&graph->match, (void **)&graph->cmap, /* Initial partitioning fields */ (void **)&graph->label, /* Communication/Setup fields */ (void **)&graph->peind, (void **)&graph->sendptr, (void **)&graph->sendind, (void **)&graph->recvptr, (void **)&graph->recvind, (void **)&graph->imap, (void **)&graph->pexadj, (void **)&graph->peadjncy, (void **)&graph->peadjloc, (void **)&graph->lperm, /* Projection fields */ (void **)&graph->rlens, (void **)&graph->slens, (void **)&graph->rcand, /* Refinement fields */ (void **)&graph->where, (void **)&graph->lpwgts, (void **)&graph->gpwgts, (void **)&graph->lnpwgts, (void **)&graph->gnpwgts, (void **)&graph->ckrinfo, (void **)&graph->nrinfo, (void **)&graph->sepind, LTERM); } /*************************************************************************/ /*! This function deallocates the non-graph and non-setup structure fields of a graph data structure */ /*************************************************************************/ void FreeNonGraphNonSetupFields(graph_t *graph) { gk_free( /* Coarsening fields */ (void **)&graph->match, (void **)&graph->cmap, /* Initial partitioning fields */ (void **)&graph->label, /* Projection fields */ (void **)&graph->rlens, (void **)&graph->slens, (void **)&graph->rcand, /* Refinement fields */ (void **)&graph->where, (void **)&graph->lpwgts, (void **)&graph->gpwgts, (void **)&graph->lnpwgts, (void **)&graph->gnpwgts, (void **)&graph->ckrinfo, (void **)&graph->nrinfo, (void **)&graph->sepind, LTERM); } /*************************************************************************/ /*! This function deallocates the fields created by the CommSetup() */ /*************************************************************************/ void FreeCommSetupFields(graph_t *graph) { gk_free( /* Communication/Setup fields */ (void **)&graph->lperm, (void **)&graph->peind, (void **)&graph->sendptr, (void **)&graph->sendind, (void **)&graph->recvptr, (void **)&graph->recvind, (void **)&graph->imap, (void **)&graph->pexadj, (void **)&graph->peadjncy, (void **)&graph->peadjloc, LTERM); } /*************************************************************************/ /*! This function frees any memory allocated for storing the initial graph and performs the local to global (i.e., original numbering of the adjacency list) */ /*************************************************************************/ void FreeInitialGraphAndRemap(graph_t *graph) { idx_t i, nedges; idx_t *adjncy, *imap; nedges = graph->nedges; adjncy = graph->adjncy; imap = graph->imap; if (imap != NULL) { for (i=0; i<nedges; i++) adjncy[i] = imap[adjncy[i]]; /* Apply local to global transformation */ } /* Free fields that are not related to the structure of the graph */ FreeNonGraphFields(graph); /* Free some derived graph-structure fields */ gk_free((void **)&graph->nvwgt, &graph->home, &graph->lnpwgts, &graph->gnpwgts, LTERM); if (graph->free_vwgt) gk_free((void **)&graph->vwgt, LTERM); if (graph->free_adjwgt) gk_free((void **)&graph->adjwgt, LTERM); if (graph->free_vsize) gk_free((void **)&graph->vsize, LTERM); gk_free((void **)&graph, LTERM); } /*************************************************************************/ /*! This function writes the key contents of the graph on disk and frees the associated memory */ /*************************************************************************/ void graph_WriteToDisk(ctrl_t *ctrl, graph_t *graph) { idx_t nvtxs, ncon, *xadj; static int gID = 1; char outfile[1024]; FILE *fpout; if (ctrl->ondisk == 0) return; if (sizeof(idx_t)*(graph->nvtxs*(graph->ncon+1)+2*graph->xadj[graph->nvtxs]) < 128*1024*1024) return; if (graph->gID > 0) { sprintf(outfile, "parmetis%d.%d.%d", (int)ctrl->mype, (int)ctrl->pid, graph->gID); gk_rmpath(outfile); } graph->gID = gID++; sprintf(outfile, "parmetis%d.%d.%d", (int)ctrl->mype, (int)ctrl->pid, graph->gID); if ((fpout = fopen(outfile, "wb")) == NULL) return; nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; if (graph->free_xadj) { if (fwrite(graph->xadj, sizeof(idx_t), nvtxs+1, fpout) != nvtxs+1) goto error; } if (graph->free_vwgt) { if (fwrite(graph->vwgt, sizeof(idx_t), nvtxs*ncon, fpout) != nvtxs*ncon) goto error; } if (fwrite(graph->nvwgt, sizeof(real_t), nvtxs*ncon, fpout) != nvtxs*ncon) goto error; if (graph->free_adjncy) { if (fwrite(graph->adjncy, sizeof(idx_t), xadj[nvtxs], fpout) != xadj[nvtxs]) goto error; } if (graph->free_adjwgt) { if (fwrite(graph->adjwgt, sizeof(idx_t), xadj[nvtxs], fpout) != xadj[nvtxs]) goto error; } if (ctrl->optype == PARMETIS_OP_AMETIS || ctrl->optype == PARMETIS_OP_RMETIS) { if (graph->free_vsize) { if (fwrite(graph->vsize, sizeof(idx_t), nvtxs, fpout) != nvtxs) goto error; } if (fwrite(graph->home, sizeof(idx_t), nvtxs, fpout) != nvtxs) goto error; } fclose(fpout); if (graph->free_xadj) gk_free((void **)&graph->xadj, LTERM); if (graph->free_vwgt) gk_free((void **)&graph->vwgt, LTERM); gk_free((void **)&graph->nvwgt, LTERM); if (graph->free_vsize) gk_free((void **)&graph->vsize, LTERM); if (graph->free_adjncy) gk_free((void **)&graph->adjncy, LTERM); if (graph->free_adjwgt) gk_free((void **)&graph->adjwgt, LTERM); gk_free((void **)&graph->home, LTERM); graph->ondisk = 1; return; error: printf("Failed on writing %s\n", outfile); fclose(fpout); gk_rmpath(outfile); graph->ondisk = 0; } /*************************************************************************/ /*! This function reads the key contents of a graph from the disk */ /*************************************************************************/ void graph_ReadFromDisk(ctrl_t *ctrl, graph_t *graph) { idx_t nvtxs, ncon, *xadj; char infile[1024]; FILE *fpin; if (graph->ondisk == 0) return; /* this graph is not on the disk */ sprintf(infile, "parmetis%d.%d.%d", (int)ctrl->mype, (int)ctrl->pid, graph->gID); if ((fpin = fopen(infile, "rb")) == NULL) return; nvtxs = graph->nvtxs; ncon = graph->ncon; if (graph->free_xadj) { graph->xadj = imalloc(nvtxs+1, "graph_ReadFromDisk: xadj"); if (fread(graph->xadj, sizeof(idx_t), nvtxs+1, fpin) != nvtxs+1) goto error; } xadj = graph->xadj; if (graph->free_vwgt) { graph->vwgt = imalloc(nvtxs*ncon, "graph_ReadFromDisk: vwgt"); if (fread(graph->vwgt, sizeof(idx_t), nvtxs*ncon, fpin) != nvtxs*ncon) goto error; } graph->nvwgt = rmalloc(nvtxs*ncon, "graph_ReadFromDisk: nvwgt"); if (fread(graph->nvwgt, sizeof(real_t), nvtxs*ncon, fpin) != nvtxs*ncon) goto error; if (graph->free_adjncy) { graph->adjncy = imalloc(xadj[nvtxs], "graph_ReadFromDisk: adjncy"); if (fread(graph->adjncy, sizeof(idx_t), xadj[nvtxs], fpin) != xadj[nvtxs]) goto error; } if (graph->free_adjwgt) { graph->adjwgt = imalloc(xadj[nvtxs], "graph_ReadFromDisk: adjwgt"); if (fread(graph->adjwgt, sizeof(idx_t), xadj[nvtxs], fpin) != xadj[nvtxs]) goto error; } if (ctrl->optype == PARMETIS_OP_AMETIS || ctrl->optype == PARMETIS_OP_RMETIS) { if (graph->free_vsize) { graph->vsize = imalloc(nvtxs, "graph_ReadFromDisk: vsize"); if (fread(graph->vsize, sizeof(idx_t), nvtxs, fpin) != nvtxs) goto error; } graph->home = imalloc(nvtxs, "graph_ReadFromDisk: vsize"); if (fread(graph->home, sizeof(idx_t), nvtxs, fpin) != nvtxs) goto error; } fclose(fpin); //printf("ondisk: deleting %s\n", infile); gk_rmpath(infile); graph->gID = 0; graph->ondisk = 0; return; error: fclose(fpin); gk_rmpath(infile); graph->ondisk = 0; gk_errexit(SIGERR, "Failed to restore graph %s from the disk.\n", infile); }
13,813
26.794769
104
c
null
ParMETIS-main/libparmetis/weird.c
/* * Copyright 1997, Regents of the University of Minnesota * * weird.c * * This file contain various graph setting up routines * * Started 10/19/96 * George * * $Id: weird.c 10592 2011-07-16 21:17:53Z karypis $ * */ #include <parmetislib.h> #define RIFN(x) \ if ((x) == NULL) {\ printf("PARMETIS ERROR " #x " is NULL.\n");\ return 0;\ } #define RIFNP(x) \ if ((*x) <= 0) {\ printf("PARMETIS ERROR " #x " is <= 0.\n");\ return 0;\ } /*************************************************************************/ /*! This function checks the validity of the inputs for PartKway */ /*************************************************************************/ int CheckInputsPartKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, j, mype; real_t sum; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } gkMPI_Comm_rank(*comm, &mype); RIFN(vtxdist); RIFN(xadj); RIFN(adjncy); RIFN(wgtflag); RIFN(numflag); RIFN(ncon); RIFN(nparts); RIFN(tpwgts); RIFN(ubvec); RIFN(options); RIFN(edgecut); RIFN(part); if (*wgtflag == 2 || *wgtflag == 3) { RIFN(vwgt); for (j=0; j<*ncon; j++) { if (GlobalSESumComm(*comm, isum(vtxdist[mype+1]-vtxdist[mype], vwgt+j, *ncon)) == 0) { printf("PARMETIS ERROR: sum weight for constraint %"PRIDX" is zero.\n", j); return 0; } } } if (*wgtflag == 1 || *wgtflag == 3) RIFN(adjwgt); /* Check that the supplied information is actually valid/reasonable */ if (vtxdist[mype+1]-vtxdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial vertex distribution. " "Processor %"PRIDX" has no vertices assigned to it!\n", mype); return 0; } RIFNP(ncon); RIFNP(nparts); for (j=0; j<*ncon; j++) { sum = rsum(*nparts, tpwgts+j, *ncon); if (sum < 0.999 || sum > 1.001) { printf("PARMETIS ERROR: The sum of tpwgts for constraint #%"PRIDX" is not 1.0\n", j); return 0; } } for (j=0; j<*ncon; j++) { for (i=0; i<*nparts; i++) { if (tpwgts[i*(*ncon)+j] < 0.0 || tpwgts[i] > 1.001) { printf("PARMETIS ERROR: The tpwgts for constraint #%"PRIDX" and partition #%"PRIDX" is out of bounds.\n", j, i); return 0; } } } for (j=0; j<*ncon; j++) { if (ubvec[j] <= 1.0) { printf("PARMETIS ERROR: The ubvec for constraint #%"PRIDX" must be > 1.0\n", j); return 0; } } return 1; } /*************************************************************************/ /*! This function checks the validity of the inputs for PartGeomKway */ /*************************************************************************/ int CheckInputsPartGeomKway(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, j, mype; real_t sum; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } gkMPI_Comm_rank(*comm, &mype); RIFN(vtxdist); RIFN(xadj); RIFN(adjncy); RIFN(xyz); RIFN(ndims); RIFN(wgtflag); RIFN(numflag); RIFN(ncon); RIFN(nparts); RIFN(tpwgts); RIFN(ubvec); RIFN(options); RIFN(edgecut); RIFN(part); if (*wgtflag == 2 || *wgtflag == 3) { RIFN(vwgt); for (j=0; j<*ncon; j++) { if (GlobalSESumComm(*comm, isum(vtxdist[mype+1]-vtxdist[mype], vwgt+j, *ncon)) == 0) { printf("PARMETIS ERROR: sum weight for constraint %"PRIDX" is zero.\n", j); return 0; } } } if (*wgtflag == 1 || *wgtflag == 3) RIFN(adjwgt); /* Check that the supplied information is actually valid/reasonable */ if (vtxdist[mype+1]-vtxdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial vertex distribution. " "Processor %"PRIDX" has no vertices assigned to it!\n", mype); return 0; } RIFNP(ncon); RIFNP(nparts); RIFNP(ndims); if (*ndims > 3) { printf("PARMETIS ERROR: The ndims should be <= 3.\n"); return 0; } for (j=0; j<*ncon; j++) { sum = rsum(*nparts, tpwgts+j, *ncon); if (sum < 0.999 || sum > 1.001) { printf("PARMETIS ERROR: The sum of tpwgts for constraint #%"PRIDX" is not 1.0\n", j); return 0; } } for (j=0; j<*ncon; j++) { for (i=0; i<*nparts; i++) { if (tpwgts[i*(*ncon)+j] < 0.0 || tpwgts[i] > 1.001) { printf("PARMETIS ERROR: The tpwgts for constraint #%"PRIDX" and partition #%"PRIDX" is out of bounds.\n", j, i); return 0; } } } for (j=0; j<*ncon; j++) { if (ubvec[j] <= 1.0) { printf("PARMETIS ERROR: The ubvec for constraint #%"PRIDX" must be > 1.0\n", j); return 0; } } return 1; } /*************************************************************************/ /*! This function checks the validity of the inputs for PartGeom */ /*************************************************************************/ int CheckInputsPartGeom(idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Comm *comm) { idx_t mype; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } RIFN(vtxdist); RIFN(xyz); RIFN(ndims); RIFN(part); /* Check that the supplied information is actually valid/reasonable */ gkMPI_Comm_rank(*comm, &mype); if (vtxdist[mype+1]-vtxdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial vertex distribution. " "Processor %"PRIDX" has no vertices assigned to it!\n", mype); return 0; } RIFNP(ndims); if (*ndims > 3) { printf("PARMETIS ERROR: The ndims should be <= 3.\n"); return 0; } return 1; } /*************************************************************************/ /*! This function checks the validity of the inputs for AdaptiveRepart */ /*************************************************************************/ int CheckInputsAdaptiveRepart(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, j, mype; real_t sum; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } gkMPI_Comm_rank(*comm, &mype); RIFN(vtxdist); RIFN(xadj); RIFN(adjncy); /*RIFN(vsize);*/ RIFN(wgtflag); RIFN(numflag); RIFN(ncon); RIFN(nparts); RIFN(tpwgts); RIFN(ubvec); RIFN(options); RIFN(edgecut); RIFN(part); if (*wgtflag == 2 || *wgtflag == 3) { RIFN(vwgt); for (j=0; j<*ncon; j++) { if (GlobalSESumComm(*comm, isum(vtxdist[mype+1]-vtxdist[mype], vwgt+j, *ncon)) == 0) { printf("PARMETIS ERROR: sum weight for constraint %"PRIDX" is zero.\n", j); return 0; } } } if (*wgtflag == 1 || *wgtflag == 3) RIFN(adjwgt); /* Check that the supplied information is actually valid/reasonable */ if (vtxdist[mype+1]-vtxdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial vertex distribution. " "Processor %"PRIDX" has no vertices assigned to it!\n", mype); return 0; } RIFNP(ncon); RIFNP(nparts); for (j=0; j<*ncon; j++) { sum = rsum(*nparts, tpwgts+j, *ncon); if (sum < 0.999 || sum > 1.001) { printf("PARMETIS ERROR: The sum of tpwgts for constraint #%"PRIDX" is not 1.0\n", j); return 0; } } for (j=0; j<*ncon; j++) { for (i=0; i<*nparts; i++) { if (tpwgts[i*(*ncon)+j] < 0.0 || tpwgts[i] > 1.001) { printf("PARMETIS ERROR: The tpwgts for constraint #%"PRIDX" and partition #%"PRIDX" is out of bounds.\n", j, i); return 0; } } } for (j=0; j<*ncon; j++) { if (ubvec[j] <= 1.0) { printf("PARMETIS ERROR: The ubvec for constraint #%"PRIDX" must be > 1.0\n", j); return 0; } } if (*ipc2redist < 0.0001 || *ipc2redist > 1000000.0) { printf("PARMETIS ERROR: The ipc2redist value should be between [0.0001, 1000000.0]\n"); return 0; } return 1; } /*************************************************************************/ /*! This function checks the validity of the inputs for NodeND */ /*************************************************************************/ int CheckInputsNodeND(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm) { idx_t mype; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } RIFN(vtxdist); RIFN(xadj); RIFN(adjncy); RIFN(numflag); RIFN(options); RIFN(order); RIFN(sizes); /* Check that the supplied information is actually valid/reasonable */ gkMPI_Comm_rank(*comm, &mype); if (vtxdist[mype+1]-vtxdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial vertex distribution. " "Processor %"PRIDX" has no vertices assigned to it!\n", mype); return 0; } return 1; } /*************************************************************************/ /*! This function checks the validity of the inputs for PartMeshKway */ /*************************************************************************/ int CheckInputsPartMeshKway(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, j, mype; real_t sum; /* Check that the supplied information is actually non-NULL */ if (comm == NULL) { printf("PARMETIS ERROR: comm is NULL. Aborting\n"); abort(); } RIFN(elmdist); RIFN(eptr); RIFN(eind); RIFN(wgtflag); RIFN(numflag); RIFN(ncon); RIFN(nparts); RIFN(tpwgts); RIFN(ubvec); RIFN(options); RIFN(edgecut); RIFN(part); if (*wgtflag == 2 || *wgtflag == 3) RIFN(elmwgt); /* Check that the supplied information is actually valid/reasonable */ gkMPI_Comm_rank(*comm, &mype); if (elmdist[mype+1]-elmdist[mype] < 1) { printf("PARMETIS ERROR: Poor initial element distribution. " "Processor %"PRIDX" has no elements assigned to it!\n", mype); return 0; } RIFNP(ncon); RIFNP(nparts); for (j=0; j<*ncon; j++) { sum = rsum(*nparts, tpwgts+j, *ncon); if (sum < 0.999 || sum > 1.001) { printf("PARMETIS ERROR: The sum of tpwgts for constraint #%"PRIDX" is not 1.0\n", j); return 0; } } for (j=0; j<*ncon; j++) { for (i=0; i<*nparts; i++) { if (tpwgts[i*(*ncon)+j] < 0.0 || tpwgts[i] > 1.001) { printf("PARMETIS ERROR: The tpwgts for constraint #%"PRIDX" and partition #%"PRIDX" is out of bounds.\n", j, i); return 0; } } } for (j=0; j<*ncon; j++) { if (ubvec[j] <= 1.0) { printf("PARMETIS ERROR: The ubvec for constraint #%"PRIDX" must be > 1.0\n", j); return 0; } } return 1; } /*************************************************************************/ /*! This function computes a partitioning of a small graph */ /*************************************************************************/ void PartitionSmallGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, h, ncon, nparts, npes, mype; idx_t moptions[METIS_NOPTIONS]; idx_t me; idx_t *mypart; int lpecut[2], gpecut[2]; graph_t *agraph; idx_t *sendcounts, *displs; real_t *gnpwgts, *lnpwgts; ncon = graph->ncon; nparts = ctrl->nparts; npes = ctrl->npes; mype = ctrl->mype; WCOREPUSH; CommSetup(ctrl, graph); graph->where = imalloc(graph->nvtxs+graph->nrecv, "PartitionSmallGraph: where"); agraph = AssembleAdaptiveGraph(ctrl, graph); mypart = iwspacemalloc(ctrl, agraph->nvtxs); METIS_SetDefaultOptions(moptions); moptions[METIS_OPTION_SEED] = ctrl->sync + mype; METIS_PartGraphKway(&agraph->nvtxs, &ncon, agraph->xadj, agraph->adjncy, agraph->vwgt, NULL, agraph->adjwgt, &nparts, ctrl->tpwgts, NULL, moptions, &graph->mincut, mypart); lpecut[0] = graph->mincut; lpecut[1] = mype; gkMPI_Allreduce(lpecut, gpecut, 1, MPI_2INT, MPI_MINLOC, ctrl->comm); graph->mincut = gpecut[0]; if (lpecut[1] == gpecut[1] && gpecut[1] != 0) gkMPI_Send((void *)mypart, agraph->nvtxs, IDX_T, 0, 1, ctrl->comm); if (lpecut[1] == 0 && gpecut[1] != 0) gkMPI_Recv((void *)mypart, agraph->nvtxs, IDX_T, gpecut[1], 1, ctrl->comm, &ctrl->status); sendcounts = iwspacemalloc(ctrl, npes); displs = iwspacemalloc(ctrl, npes); for (i=0; i<npes; i++) { sendcounts[i] = graph->vtxdist[i+1]-graph->vtxdist[i]; displs[i] = graph->vtxdist[i]; } gkMPI_Scatterv((void *)mypart, sendcounts, displs, IDX_T, (void *)graph->where, graph->nvtxs, IDX_T, 0, ctrl->comm); lnpwgts = graph->lnpwgts = rmalloc(nparts*ncon, "lnpwgts"); gnpwgts = graph->gnpwgts = rmalloc(nparts*ncon, "gnpwgts"); rset(nparts*ncon, 0, lnpwgts); for (i=0; i<graph->nvtxs; i++) { me = graph->where[i]; for (h=0; h<ncon; h++) lnpwgts[me*ncon+h] += graph->nvwgt[i*ncon+h]; } gkMPI_Allreduce((void *)lnpwgts, (void *)gnpwgts, nparts*ncon, REAL_T, MPI_SUM, ctrl->comm); FreeGraph(agraph); WCOREPOP; return; }
13,955
25.838462
120
c
null
ParMETIS-main/libparmetis/csrmatch.c
/* * Copyright 1997, Regents of the University of Minnesota * * csrmatch.c * * This file contains the code that computes matchings * * Started 7/23/97 * George * * $Id: csrmatch.c 10057 2011-06-02 13:44:44Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function finds a matching using the HEM heuristic **************************************************************************/ void CSR_Match_SHEM(matrix_t *matrix, idx_t *match, idx_t *mlist, idx_t *skip, idx_t ncon) { idx_t h, i, ii, j; idx_t nrows, edge, maxidx, count; real_t maxwgt; idx_t *rowptr, *colind; real_t *transfer; rkv_t *links; nrows = matrix->nrows; rowptr = matrix->rowptr; colind = matrix->colind; transfer = matrix->transfer; iset(nrows, UNMATCHED, match); links = rkvmalloc(nrows, "links"); for (i=0; i<nrows; i++) { links[i].key = 0.0; links[i].val = i; for (j=rowptr[i]; j<rowptr[i+1]; j++) { for (h=0; h<ncon; h++) { if (links[i].key < fabs(transfer[j*ncon+h])) links[i].key = fabs(transfer[j*ncon+h]); } } } rkvsortd(nrows, links); for (count=0, ii=0; ii<nrows; ii++) { i = links[ii].val; if (match[i] == UNMATCHED) { maxidx = i; maxwgt = 0.0; /* Find a heavy-edge matching */ for (j=rowptr[i]; j<rowptr[i+1]; j++) { edge = colind[j]; if (match[edge] == UNMATCHED && edge != i && skip[j] == 0) { for (h=0; h<ncon; h++) if (maxwgt < fabs(transfer[j*ncon+h])) break; if (h != ncon) { maxwgt = fabs(transfer[j*ncon+h]); maxidx = edge; } } } if (maxidx != i) { match[i] = maxidx; match[maxidx] = i; mlist[count++] = gk_max(i, maxidx); mlist[count++] = gk_min(i, maxidx); } } } gk_free((void **)&links, LTERM); }
1,976
21.988372
75
c
null
ParMETIS-main/libparmetis/wave.c
/* * Copyright 1997, Regents of the University of Minnesota * * wave.c * * This file contains code for directed diffusion at the coarsest graph * * Started 5/19/97, Kirk, George * * $Id: wave.c 13946 2013-03-30 15:51:45Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function performs a k-way directed diffusion **************************************************************************/ real_t WavefrontDiffusion(ctrl_t *ctrl, graph_t *graph, idx_t *home) { idx_t ii, i, j, k, l, nvtxs, nedges, nparts; idx_t from, to, edge, done, nswaps, noswaps, totalv, wsize; idx_t npasses, first, second, third, mind, maxd; idx_t *xadj, *adjncy, *adjwgt, *where, *perm; idx_t *rowptr, *colind, *ed, *psize; real_t *transfer, *tmpvec; real_t balance = -1.0, *load, *solution, *workspace; real_t *nvwgt, *npwgts, flowFactor, cost, ubfactor; matrix_t matrix; ikv_t *cand; idx_t ndirty, nclean, dptr, clean; nvtxs = graph->nvtxs; nedges = graph->nedges; xadj = graph->xadj; nvwgt = graph->nvwgt; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; nparts = ctrl->nparts; ubfactor = ctrl->ubvec[0]; matrix.nrows = nparts; flowFactor = 0.35; flowFactor = (ctrl->mype == 2) ? 0.50 : flowFactor; flowFactor = (ctrl->mype == 3) ? 0.75 : flowFactor; flowFactor = (ctrl->mype == 4) ? 1.00 : flowFactor; /* allocate memory */ solution = rmalloc(6*nparts+2*nedges, "WavefrontDiffusion: solution"); tmpvec = solution + nparts; /* nparts */ npwgts = solution + 2*nparts; /* nparts */ load = solution + 3*nparts; /* nparts */ matrix.values = solution + 4*nparts; /* nparts+nedges */ transfer = matrix.transfer = solution + 5*nparts + nedges /* nparts+nedges */; perm = imalloc(2*nvtxs+3*nparts+nedges+1, "WavefrontDiffusion: perm"); ed = perm + nvtxs; /* nvtxs */ psize = perm + 2*nvtxs; /* nparts */ rowptr = matrix.rowptr = perm + 2*nvtxs + nparts; /* nparts+1 */ colind = matrix.colind = perm + 2*nvtxs + 2*nparts + 1; /* nparts+nedges */ /*GKTODO - Potential problem with this malloc */ wsize = gk_max(sizeof(real_t)*6*nparts, sizeof(idx_t)*(nvtxs+2*nparts+1)); workspace = (real_t *)gk_malloc(wsize, "WavefrontDiffusion: workspace"); cand = ikvmalloc(nvtxs, "WavefrontDiffusion: cand"); /* Populate empty subdomains */ iset(nparts, 0, psize); for (i=0; i<nvtxs; i++) psize[where[i]]++; for (l=0; l<nparts; l++) { if (psize[l] == 0) break; } if (l < nparts) { /* there is at least an empty subdomain */ FastRandomPermute(nvtxs, perm, 1); for (mind=0; mind<nparts; mind++) { if (psize[mind] > 0) continue; maxd = iargmax(nparts, psize, 1); if (psize[maxd] == 1) break; /* we cannot do anything if the heaviest subdomain contains one vertex! */ for (i=0; i<nvtxs; i++) { k = perm[i]; if (where[k] == maxd) { where[k] = mind; psize[mind]++; psize[maxd]--; break; } } } } /* compute the external degrees of the vertices */ iset(nvtxs, 0, ed); rset(nparts, 0.0, npwgts); for (i=0; i<nvtxs; i++) { npwgts[where[i]] += nvwgt[i]; for (j=xadj[i]; j<xadj[i+1]; j++) ed[i] += (where[i] != where[adjncy[j]] ? adjwgt[j] : 0); } ComputeLoad(graph, nparts, load, ctrl->tpwgts, 0); /* zero out the tmpvec array */ rset(nparts, 0.0, tmpvec); npasses = gk_min(nparts/2, NGD_PASSES); for (done=0, l=0; l<npasses; l++) { /* Set-up and solve the diffusion equation */ nswaps = 0; /* Solve flow equations */ SetUpConnectGraph(graph, &matrix, (idx_t *)workspace); /* check for disconnected subdomains */ for(i=0; i<matrix.nrows; i++) { if (matrix.rowptr[i]+1 == matrix.rowptr[i+1]) { cost = (real_t)(ctrl->mype); break; } } if (i == matrix.nrows) { /* if connected, proceed */ ConjGrad2(&matrix, load, solution, 0.001, workspace); ComputeTransferVector(1, &matrix, solution, transfer, 0); GetThreeMax(nparts, load, &first, &second, &third); if (l%3 == 0) { FastRandomPermute(nvtxs, perm, 1); } else { /*****************************/ /* move dirty vertices first */ /*****************************/ ndirty = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) ndirty++; } dptr = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) perm[dptr++] = i; else perm[ndirty++] = i; } PASSERT(ctrl, ndirty == nvtxs); ndirty = dptr; nclean = nvtxs-dptr; FastRandomPermute(ndirty, perm, 0); FastRandomPermute(nclean, perm+ndirty, 0); } if (ctrl->mype == 0) { for (j=nvtxs, k=0, ii=0; ii<nvtxs; ii++) { i = perm[ii]; if (ed[i] != 0) { cand[k].key = -ed[i]; cand[k++].val = i; } else { cand[--j].key = 0; cand[j].val = i; } } ikvsorti(k, cand); } for (ii=0; ii<nvtxs/3; ii++) { i = (ctrl->mype == 0) ? cand[ii].val : perm[ii]; from = where[i]; /* don't move out the last vertex in a subdomain */ if (psize[from] == 1) continue; clean = (from == home[i]) ? 1 : 0; /* only move from top three or dirty vertices */ if (from != first && from != second && from != third && clean) continue; /* Scatter the sparse transfer row into the dense tmpvec row */ for (j=rowptr[from]+1; j<rowptr[from+1]; j++) tmpvec[colind[j]] = transfer[j]; for (j=xadj[i]; j<xadj[i+1]; j++) { to = where[adjncy[j]]; if (from != to) { if (tmpvec[to] > (flowFactor * nvwgt[i])) { tmpvec[to] -= nvwgt[i]; INC_DEC(psize[to], psize[from], 1); INC_DEC(npwgts[to], npwgts[from], nvwgt[i]); INC_DEC(load[to], load[from], nvwgt[i]); where[i] = to; nswaps++; /* Update external degrees */ ed[i] = 0; for (k=xadj[i]; k<xadj[i+1]; k++) { edge = adjncy[k]; ed[i] += (to != where[edge] ? adjwgt[k] : 0); if (where[edge] == from) ed[edge] += adjwgt[k]; if (where[edge] == to) ed[edge] -= adjwgt[k]; } break; } } } /* Gather the dense tmpvec row into the sparse transfer row */ for (j=rowptr[from]+1; j<rowptr[from+1]; j++) { transfer[j] = tmpvec[colind[j]]; tmpvec[colind[j]] = 0.0; } } } if (l % 2 == 1) { balance = rmax(nparts, npwgts, 1)*nparts; if (balance < ubfactor + 0.035) done = 1; if (GlobalSESum(ctrl, done) > 0) break; noswaps = (nswaps > 0 ? 0 : 1); if (GlobalSESum(ctrl, noswaps) > ctrl->npes/2) break; } } graph->mincut = ComputeSerialEdgeCut(graph); totalv = Mc_ComputeSerialTotalV(graph, home); cost = ctrl->ipc_factor * (real_t)graph->mincut + ctrl->redist_factor * (real_t)totalv; CleanUpAndExit: gk_free((void **)&solution, (void **)&perm, (void **)&workspace, (void **)&cand, LTERM); return cost; }
7,851
29.316602
98
c
null
ParMETIS-main/libparmetis/redomylink.c
/* * Copyright 1997, Regents of the University of Minnesota * * redomylink.c * * This file contains code that implements the edge-based FM refinement * * Started 7/23/97 * George * * $Id: redomylink.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define PE 0 /************************************************************************* * This function performs an edge-based FM refinement **************************************************************************/ void RedoMyLink(ctrl_t *ctrl, graph_t *graph, idx_t *home, idx_t me, idx_t you, real_t *flows, real_t *sr_cost, real_t *sr_lbavg) { idx_t h, i, r; idx_t nvtxs, nedges, ncon; idx_t pass, lastseed, totalv; idx_t *xadj, *adjncy, *adjwgt, *where, *vsize; idx_t *costwhere, *lbwhere, *selectwhere; idx_t *ed, *id, *bndptr, *bndind, *perm; real_t *nvwgt, mycost; real_t lbavg, *lbvec; real_t best_lbavg, other_lbavg = -1.0, bestcost, othercost = -1.0; real_t *npwgts, *pwgts, *tpwgts; real_t ipc_factor, redist_factor, ftmp; idx_t mype; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); WCOREPUSH; nvtxs = graph->nvtxs; nedges = graph->nedges; ncon = graph->ncon; xadj = graph->xadj; nvwgt = graph->nvwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; ipc_factor = ctrl->ipc_factor; redist_factor = ctrl->redist_factor; /* set up data structures */ id = graph->sendind = iwspacemalloc(ctrl, nvtxs); ed = graph->recvind = iwspacemalloc(ctrl, nvtxs); bndptr = graph->sendptr = iwspacemalloc(ctrl, nvtxs); bndind = graph->recvptr = iwspacemalloc(ctrl, nvtxs); costwhere = iwspacemalloc(ctrl, nvtxs); lbwhere = iwspacemalloc(ctrl, nvtxs); perm = iwspacemalloc(ctrl, nvtxs); lbvec = rwspacemalloc(ctrl, ncon); pwgts = rset(2*ncon, 0.0, rwspacemalloc(ctrl, 2*ncon)); npwgts = rwspacemalloc(ctrl, 2*ncon); tpwgts = rwspacemalloc(ctrl, 2*ncon); graph->gnpwgts = npwgts; RandomPermute(nvtxs, perm, 1); icopy(nvtxs, where, costwhere); icopy(nvtxs, where, lbwhere); /* compute target pwgts */ for (h=0; h<ncon; h++) { tpwgts[h] = -1.0*flows[h]; tpwgts[ncon+h] = flows[h]; } for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) { tpwgts[h] += nvwgt[i*ncon+h]; pwgts[h] += nvwgt[i*ncon+h]; } } else { ASSERT(where[i] == you); for (h=0; h<ncon; h++) { tpwgts[ncon+h] += nvwgt[i*ncon+h]; pwgts[ncon+h] += nvwgt[i*ncon+h]; } } } /* we don't want any weights to be less than zero */ for (h=0; h<ncon; h++) { if (tpwgts[h] < 0.0) { tpwgts[ncon+h] += tpwgts[h]; tpwgts[h] = 0.0; } if (tpwgts[ncon+h] < 0.0) { tpwgts[h] += tpwgts[ncon+h]; tpwgts[ncon+h] = 0.0; } } /* now compute new bisection */ bestcost = (real_t)isum(nedges, adjwgt, 1)*ipc_factor + (real_t)isum(nvtxs, vsize, 1)*redist_factor; best_lbavg = 10.0; lastseed = 0; for (pass=N_MOC_REDO_PASSES; pass>0; pass--) { iset(nvtxs, 1, where); /* find seed vertices */ r = perm[lastseed] % nvtxs; lastseed = (lastseed+1) % nvtxs; where[r] = 0; Mc_Serial_Compute2WayPartitionParams(ctrl, graph); Mc_Serial_Init2WayBalance(ctrl, graph, tpwgts); Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4); Mc_Serial_Balance2Way(ctrl, graph, tpwgts, 1.02); Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4); for (i=0; i<nvtxs; i++) where[i] = (where[i] == 0) ? me : you; for (i=0; i<ncon; i++) { ftmp = (pwgts[i]+pwgts[ncon+i])/2.0; if (ftmp != 0.0) lbvec[i] = fabs(npwgts[i]-tpwgts[i])/ftmp; else lbvec[i] = 0.0; } lbavg = ravg(ncon, lbvec); totalv = 0; for (i=0; i<nvtxs; i++) if (where[i] != home[i]) totalv += vsize[i]; mycost = (real_t)(graph->mincut)*ipc_factor + (real_t)totalv*redist_factor; if (bestcost >= mycost) { bestcost = mycost; other_lbavg = lbavg; icopy(nvtxs, where, costwhere); } if (best_lbavg >= lbavg) { best_lbavg = lbavg; othercost = mycost; icopy(nvtxs, where, lbwhere); } } if (other_lbavg <= .05) { selectwhere = costwhere; *sr_cost = bestcost; *sr_lbavg = other_lbavg; } else { selectwhere = lbwhere; *sr_cost = othercost; *sr_lbavg = best_lbavg; } icopy(nvtxs, selectwhere, where); WCOREPOP; }
4,522
24.410112
79
c
null
ParMETIS-main/libparmetis/frename.c
/* * frename.c * * This file contains some renaming routines to deal with different * Fortran compilers. * * Started 6/1/98 * George * * $Id: frename.c 13945 2013-03-30 14:38:24Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * Renaming macro (at least to save some typing :)) **************************************************************************/ #define FRENAME(name0, name1, name2, name3, name4, dargs, cargs) \ int name1 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name2 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name3 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name4 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; } /************************************************************************* * Renames for Release 3.0 API **************************************************************************/ FRENAME(ParMETIS_V3_AdaptiveRepart, PARMETIS_V3_ADAPTIVEREPART, parmetis_v3_adaptiverepart, parmetis_v3_adaptiverepart_, parmetis_v3_adaptiverepart__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, vsize, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, ipc2redist, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_PartGeomKway, PARMETIS_V3_PARTGEOMKWAY, parmetis_v3_partgeomkway, parmetis_v3_partgeomkway_, parmetis_v3_partgeomkway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ndims, xyz, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_PartGeom, PARMETIS_V3_PARTGEOM, parmetis_v3_partgeom, parmetis_v3_partgeom_, parmetis_v3_partgeom__, (idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Fint *icomm), (vtxdist, ndims, xyz, part, &comm) ) FRENAME(ParMETIS_V3_PartKway, PARMETIS_V3_PARTKWAY, parmetis_v3_partkway, parmetis_v3_partkway_, parmetis_v3_partkway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_Mesh2Dual, PARMETIS_V3_MESH2DUAL, parmetis_v3_mesh2dual, parmetis_v3_mesh2dual_, parmetis_v3_mesh2dual__, (idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommonnodes, idx_t **xadj, idx_t **adjncy, MPI_Fint *icomm), (elmdist, eptr, eind, numflag, ncommonnodes, xadj, adjncy, &comm) ) FRENAME(ParMETIS_V3_PartMeshKway, PARMETIS_V3_PARTMESHKWAY, parmetis_v3_partmeshkway, parmetis_v3_partmeshkway_, parmetis_v3_partmeshkway__, (idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommonnodes, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (elmdist, eptr, eind, elmwgt, wgtflag, numflag, ncon, ncommonnodes, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_NodeND, PARMETIS_V3_NODEND, parmetis_v3_nodend, parmetis_v3_nodend_, parmetis_v3_nodend__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Fint *icomm), (vtxdist, xadj, adjncy, numflag, options, order, sizes, &comm) ) FRENAME(ParMETIS_V3_RefineKway, PARMETIS_V3_REFINEKWAY, parmetis_v3_refinekway, parmetis_v3_refinekway_, parmetis_v3_refinekway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) )
4,633
36.674797
93
c
null
ParMETIS-main/libparmetis/selectq.c
/* * Copyright 1997, Regents of the University of Minnesota * * selectq.c * * This file contains the driving routines for multilevel k-way refinement * * Started 7/28/97 * George * * $Id: selectq.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> /*************************************************************************/ /*! This stuff is hardcoded for up to four constraints */ /*************************************************************************/ void Mc_DynamicSelectQueue(ctrl_t *ctrl, idx_t nqueues, idx_t ncon, idx_t subdomain1, idx_t subdomain2, idx_t *currentq, real_t *flows, idx_t *from, idx_t *qnum, idx_t minval, real_t avgvwgt, real_t maxdiff) { idx_t i, j; idx_t hash, index = -1, current; idx_t *cand, *rank, *dont_cares; idx_t nperms, perm[24][5]; real_t sign = 0.0; rkv_t *array; idx_t mype; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); WCOREPUSH; *qnum = -1; /* allocate memory */ cand = iwspacemalloc(ctrl, ncon); rank = iwspacemalloc(ctrl, ncon); dont_cares = iwspacemalloc(ctrl, ncon); array = rkvwspacemalloc(ctrl, ncon); if (*from == -1) { for (i=0; i<ncon; i++) { array[i].key = fabs(flows[i]); array[i].val = i; } /* GKTODO - Need to check the correct direction of the sort */ rkvsorti(ncon, array); /* GKTODO - The following assert was disabled as it was failing. Need to check if it is a valid assert */ /*ASSERT(array[ncon-1].key - array[0].key <= maxdiff) */ if (flows[array[ncon-1].val] > avgvwgt*MOC_GD_GRANULARITY_FACTOR) { *from = subdomain1; sign = 1.0; index = 0; } if (flows[array[ncon-1].val] < -1.0*avgvwgt*MOC_GD_GRANULARITY_FACTOR) { *from = subdomain2; sign = -1.0; index = nqueues; } if (*from == -1) goto DONE; } else { ASSERT(*from == subdomain1 || *from == subdomain2); if (*from == subdomain1) { sign = 1.0; index = 0; } else { sign = -1.0; index = nqueues; } } for (i=0; i<ncon; i++) { array[i].key = flows[i] * sign; array[i].val = i; } /* GKTODO Need to check the direction of those sorts */ rkvsorti(ncon, array); iset(ncon, 1, dont_cares); for (current=0, i=0; i<ncon-1; i++) { if (array[i+1].key - array[i].key < maxdiff * MC_FLOW_BALANCE_THRESHOLD && dont_cares[current] < ncon-1) { dont_cares[current]++; dont_cares[i+1] = 0; } else current = i+1; } switch (ncon) { /***********************/ case 2: nperms = 1; perm[0][0] = 0; perm[0][1] = 1; break; /***********************/ case 3: /* if the first and second flows are close */ if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 1) { nperms = 4; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[3][0] = 1; perm[3][1] = 2; perm[3][2] = 0; break; } /* if the second and third flows are close */ if (dont_cares[0] == 1 && dont_cares[1] == 2 && dont_cares[2] == 0) { nperms = 4; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[2][0] = 1; perm[2][1] = 0; perm[2][2] = 2; perm[3][0] = 2; perm[3][1] = 0; perm[3][2] = 1; break; } /* all or none of the flows are close */ nperms = 3; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; break; /***********************/ case 4: if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 1 && dont_cares[3] == 1) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 1; perm[3][1] = 2; perm[3][2] = 0; perm[3][3] = 3; perm[4][0] = 0; perm[4][1] = 1; perm[4][2] = 3; perm[4][3] = 2; perm[5][0] = 1; perm[5][1] = 0; perm[5][2] = 3; perm[5][3] = 2; perm[6][0] = 0; perm[6][1] = 3; perm[6][2] = 1; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 0; perm[8][1] = 2; perm[8][2] = 3; perm[8][3] = 1; perm[9][0] = 1; perm[9][1] = 2; perm[9][2] = 3; perm[9][3] = 0; perm[10][0] = 2; perm[10][1] = 0; perm[10][2] = 1; perm[10][3] = 3; perm[11][0] = 2; perm[11][1] = 1; perm[11][2] = 0; perm[11][3] = 3; perm[12][0] = 0; perm[12][1] = 3; perm[12][2] = 2; perm[12][3] = 1; perm[13][0] = 1; perm[13][1] = 3; perm[13][2] = 2; perm[13][3] = 0; break; } if (dont_cares[0] == 1 && dont_cares[1] == 1 && dont_cares[2] == 2 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 1; perm[1][2] = 3; perm[1][3] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 0; perm[3][1] = 3; perm[3][2] = 1; perm[3][3] = 2; perm[4][0] = 1; perm[4][1] = 0; perm[4][2] = 2; perm[4][3] = 3; perm[5][0] = 1; perm[5][1] = 0; perm[5][2] = 3; perm[5][3] = 2; perm[6][0] = 1; perm[6][1] = 2; perm[6][2] = 0; perm[6][3] = 3; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 3; perm[9][1] = 0; perm[9][2] = 1; perm[9][3] = 2; perm[10][0] = 0; perm[10][1] = 2; perm[10][2] = 3; perm[10][3] = 1; perm[11][0] = 0; perm[11][1] = 3; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 2; perm[12][1] = 1; perm[12][2] = 0; perm[12][3] = 3; perm[13][0] = 3; perm[13][1] = 1; perm[13][2] = 0; perm[13][3] = 2; break; } if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 2 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 1; perm[2][2] = 3; perm[2][3] = 2; perm[3][0] = 1; perm[3][1] = 0; perm[3][2] = 3; perm[3][3] = 2; perm[4][0] = 0; perm[4][1] = 2; perm[4][2] = 1; perm[4][3] = 3; perm[5][0] = 1; perm[5][1] = 2; perm[5][2] = 0; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 3; perm[6][2] = 1; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 0; perm[9][1] = 2; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 2; perm[10][1] = 1; perm[10][2] = 0; perm[10][3] = 3; perm[11][0] = 0; perm[11][1] = 3; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 3; perm[12][1] = 0; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 1; perm[13][1] = 2; perm[13][2] = 3; perm[13][3] = 0; break; } if (dont_cares[0] == 3 && dont_cares[1] == 0 && dont_cares[2] == 0 && dont_cares[3] == 1) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[1][3] = 3; perm[2][0] = 1; perm[2][1] = 0; perm[2][2] = 2; perm[2][3] = 3; perm[3][0] = 2; perm[3][1] = 0; perm[3][2] = 1; perm[3][3] = 3; perm[4][0] = 1; perm[4][1] = 2; perm[4][2] = 0; perm[4][3] = 3; perm[5][0] = 2; perm[5][1] = 1; perm[5][2] = 0; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 1; perm[6][2] = 3; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 0; perm[7][2] = 3; perm[7][3] = 2; perm[8][0] = 0; perm[8][1] = 2; perm[8][2] = 3; perm[8][3] = 1; perm[9][0] = 2; perm[9][1] = 0; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 1; perm[10][1] = 2; perm[10][2] = 3; perm[10][3] = 0; perm[11][0] = 2; perm[11][1] = 1; perm[11][2] = 3; perm[11][3] = 0; perm[12][0] = 0; perm[12][1] = 3; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 0; perm[13][1] = 3; perm[13][2] = 2; perm[13][3] = 1; break; } if (dont_cares[0] == 1 && dont_cares[1] == 3 && dont_cares[2] == 0 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 1; perm[2][2] = 3; perm[2][3] = 2; perm[3][0] = 0; perm[3][1] = 2; perm[3][2] = 3; perm[3][3] = 1; perm[4][0] = 0; perm[4][1] = 3; perm[4][2] = 1; perm[4][3] = 2; perm[5][0] = 0; perm[5][1] = 3; perm[5][2] = 2; perm[5][3] = 1; perm[6][0] = 1; perm[6][1] = 0; perm[6][2] = 2; perm[6][3] = 3; perm[7][0] = 1; perm[7][1] = 0; perm[7][2] = 3; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 2; perm[9][1] = 0; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 3; perm[10][1] = 0; perm[10][2] = 1; perm[10][3] = 2; perm[11][0] = 3; perm[11][1] = 0; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 1; perm[12][1] = 2; perm[12][2] = 0; perm[12][3] = 3; perm[13][0] = 2; perm[13][1] = 1; perm[13][2] = 0; perm[13][3] = 3; break; } nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 0; perm[3][1] = 1; perm[3][2] = 3; perm[3][3] = 2; perm[4][0] = 1; perm[4][1] = 0; perm[4][2] = 3; perm[4][3] = 2; perm[5][0] = 2; perm[5][1] = 0; perm[5][2] = 1; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 2; perm[6][2] = 3; perm[6][3] = 1; perm[7][0] = 1; perm[7][1] = 2; perm[7][2] = 0; perm[7][3] = 3; perm[8][0] = 0; perm[8][1] = 3; perm[8][2] = 1; perm[8][3] = 2; perm[9][0] = 2; perm[9][1] = 1; perm[9][2] = 0; perm[9][3] = 3; perm[10][0] = 0; perm[10][1] = 3; perm[10][2] = 2; perm[10][3] = 1; perm[11][0] = 2; perm[11][1] = 0; perm[11][2] = 3; perm[11][3] = 1; perm[12][0] = 3; perm[12][1] = 0; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 1; perm[13][1] = 2; perm[13][2] = 3; perm[13][3] = 0; break; /***********************/ default: goto DONE; } for (i=0; i<nperms; i++) { for (j=0; j<ncon; j++) cand[j] = array[perm[i][j]].val; for (j=0; j<ncon; j++) rank[cand[j]] = j; hash = Mc_HashVRank(ncon, rank) - minval; if (currentq[hash+index] > 0) { *qnum = hash; goto DONE; } } DONE: WCOREPOP; } /*************************************************************************/ /*! This function sorts the nvwgts of a vertex and returns a hashed value */ /*************************************************************************/ idx_t Mc_HashVwgts(ctrl_t *ctrl, idx_t ncon, real_t *nvwgt) { idx_t i; idx_t multiplier, retval; idx_t *rank; rkv_t *array; WCOREPUSH; rank = iwspacemalloc(ctrl, ncon); array = rkvwspacemalloc(ctrl, ncon); for (i=0; i<ncon; i++) { array[i].key = nvwgt[i]; array[i].val = i; } rkvsorti(ncon, array); for (i=0; i<ncon; i++) rank[array[i].val] = i; multiplier = 1; retval = 0; for (i=0; i<ncon; i++) { multiplier *= (i+1); retval += rank[ncon-i-1] * multiplier; } WCOREPOP; return retval; } /*************************************************************************/ /*! This function sorts the vwgts of a vertex and returns a hashed value */ /*************************************************************************/ idx_t Mc_HashVRank(idx_t ncon, idx_t *vwgt) { idx_t i, multiplier, retval; multiplier = 1; retval = 0; for (i=0; i<ncon; i++) { multiplier *= (i+1); retval += vwgt[ncon-1-i] * multiplier; } return retval; }
13,136
35.491667
110
c
null
ParMETIS-main/libparmetis/struct.h
/* * Copyright 1997, Regents of the University of Minnesota * * struct.h * * This file contains data structures for ILU routines. * * Started 9/26/95 * George * * $Id: struct.h 10592 2011-07-16 21:17:53Z karypis $ */ /*************************************************************************/ /*! This data structure stores cut-based k-way refinement info about an * adjacent subdomain for a given vertex. */ /*************************************************************************/ typedef struct cnbr_t { idx_t pid; /*!< The partition ID */ idx_t ed; /*!< The sum of the weights of the adjacent edges that are incident on pid */ } cnbr_t; /************************************************************************* * The following data structure stores key-key-value triplets **************************************************************************/ typedef struct i2kv_t { idx_t key1, key2; idx_t val; } i2kv_t; /************************************************************************* * The following data structure holds information on degrees for k-way * partition **************************************************************************/ typedef struct ckrinfo_t { idx_t id; /*!< The internal degree of a vertex (sum of weights) */ idx_t ed; /*!< The total external degree of a vertex */ idx_t nnbrs; /*!< The number of neighboring subdomains */ idx_t inbr; /*!< The index in the cnbr_t array where the nnbrs list of neighbors is stored */ } ckrinfo_t; /************************************************************************* * The following data structure holds information on degrees for k-way * partition **************************************************************************/ struct nrinfodef { idx_t edegrees[2]; }; typedef struct nrinfodef NRInfoType; /************************************************************************* * The following data structure stores a sparse matrix in CSR format * The diagonal entry is in the first position of each row. **************************************************************************/ typedef struct matrix_t { idx_t nrows, nnzs; /* Number of rows and nonzeros in the matrix */ idx_t *rowptr; idx_t *colind; real_t *values; real_t *transfer; } matrix_t; /************************************************************************* * This data structure holds the input graph **************************************************************************/ typedef struct graph_t { idx_t gnvtxs, nvtxs, nedges, ncon, nobj; idx_t *xadj; /* Pointers to the locally stored vertices */ idx_t *vwgt; /* Vertex weights */ real_t *nvwgt; /* Vertex weights */ idx_t *vsize; /* Vertex size */ idx_t *adjncy; /* Array that stores the adjacency lists of nvtxs */ idx_t *adjwgt; /* Array that stores the weights of the adjacency lists */ idx_t *vtxdist; /* Distribution of vertices */ idx_t *home; /* The initial partition of the vertex */ /* used for not freeing application supplied arrays */ idx_t free_xadj; idx_t free_adjncy; idx_t free_vwgt; idx_t free_adjwgt; idx_t free_vsize; /* Coarsening structures */ idx_t *match; idx_t *cmap; /* Dropedges */ idx_t *unmatched; /* used to mark the coarse vertices that resulted from match[u]=u */ /* Used during initial partitioning */ idx_t *label; /* Communication/Setup parameters */ idx_t nnbrs; /*!< The number of neighboring processors */ idx_t nrecv; /*!< The total number of remote vertices that need to be received. nrecv == recvptr[nnbrs] */ idx_t nsend; /*!< The total number of local vertices that need to be sent. This corresponds to the communication volume of each pe, in the sense that if a vertex needs to be sent multiple times, it is accounted in nsend. nsend == sendptr[nnbrs] */ idx_t *peind; /*!< Array of size nnbrs storing the neighboring PEs */ idx_t *sendptr, *sendind; /*!< CSR format of the vertices that are sent to each of the neighboring processors */ idx_t *recvptr, *recvind; /*!< CSR format of the vertices that are received from each of the neighboring PEs. */ idx_t *imap; /*!< The inverse map of local to global indices */ idx_t *pexadj, *peadjncy, *peadjloc; /*!< CSR format of the PEs each vertex is adjancent to along with the location in the sendind of the non-local adjancent vertices */ idx_t nlocal; /*!< Number of interior vertices */ idx_t *lperm; /*!< lperm[0:nlocal] points to interior vertices, the rest are interface */ /* Communication parameters for projecting the partition. * These are computed during CreateCoarseGraph and used during projection * Note that during projection, the meaning of received and sent is reversed! */ idx_t *rlens, *slens; /* Arrays of size nnbrs of how many vertices you are sending and receiving */ ikv_t *rcand; /* Partition parameters */ idx_t *where; idx_t *lpwgts, *gpwgts; real_t *lnpwgts, *gnpwgts; ckrinfo_t *ckrinfo; /* Node refinement information */ idx_t nsep; /* The number of vertices in the separator */ NRInfoType *nrinfo; idx_t *sepind; /* The indices of the vertices in the separator */ /* Vertex/edge metadata information use by DistDGL */ size_t emdata_size, vmdata_size; idx_t *vmptr, *emptr; char *vmdata, *emdata; idx_t *vtype; /* Various fields for out-of-core processing */ int gID; int ondisk; idx_t lmincut, mincut; idx_t level; idx_t match_type; idx_t edgewgt_type; struct graph_t *coarser, *finer; } graph_t; /************************************************************************* * The following data type implements a timer **************************************************************************/ typedef double timer; /************************************************************************* * The following structure stores information used by parallel kmetis **************************************************************************/ typedef struct ctrl_t { pmoptype_et optype; /*!< The operation being performed */ idx_t mype, npes; /*!< Info about the parallel system */ idx_t ncon; /*!< The number of balancing constraints */ idx_t CoarsenTo; /*!< The # of vertices in the coarsest graph */ idx_t dbglvl; /*!< Controls the debuging output of the program */ idx_t nparts; /*!< The number of partitions */ idx_t foldf; /*!< What is the folding factor */ idx_t mtype; /*!< The matching type */ idx_t ipart; /*!< The initial partitioning type */ idx_t rtype; /*!< The refinement type */ idx_t p_nseps; /*!< The number of separators to compute at each parallel bisection */ idx_t s_nseps; /* The number of separators to compute at each serial bisection */ real_t ubfrac; /* The max/avg fraction for separator bisections */ idx_t seed; /* Random number seed */ idx_t sync; /* Random number seed */ real_t *tpwgts; /* Target subdomain weights */ real_t *invtvwgts; /* Per-constraint 1/total vertex weight */ real_t *ubvec; /* Per-constraint unbalance factor */ idx_t dropedges; idx_t twohop; idx_t fast; idx_t partType; idx_t ps_relation; real_t redist_factor; real_t redist_base; real_t ipc_factor; real_t edge_size_ratio; matrix_t *matrix; idx_t free_comm; /*!< Used to indicate if gcomm needs to be freed */ MPI_Comm gcomm; /*!< A copy of the application supplied communicator */ MPI_Comm comm; /*!< The current communicator */ idx_t ncommpes; /*!< The maximum number of processors that a processor may need to communicate with. This determines the size of the sreq/rreq/statuses arrays and is updated after every call to CommSetup() */ MPI_Request *sreq; /*!< MPI send requests */ MPI_Request *rreq; /*!< MPI receive requests */ MPI_Status *statuses; /*!< MPI status for p2p i-messages */ MPI_Status status; /* workspace variables */ gk_mcore_t *mcore; /* GKlib's mcore */ /* These are for use by the k-way refinement routines */ size_t nbrpoolsize; /*!< The number of cnbr_t entries that have been allocated */ size_t nbrpoolcpos; /*!< The position of the first free entry in the array */ size_t nbrpoolreallocs; /*!< The number of times the pool was resized */ cnbr_t *cnbrpool; /*!< The pool of cnbr_t entries to be used during refinement. The size and current position of the pool is controlled by nnbrs & cnbrs */ /* ondisk-related info */ idx_t ondisk; pid_t pid; /*!< The pid of the running process */ /* Various Timers */ timer TotalTmr, InitPartTmr, MatchTmr, ContractTmr, CoarsenTmr, RefTmr, SetupTmr, ProjectTmr, KWayInitTmr, KWayTmr, MoveTmr, RemapTmr, SerialTmr, AuxTmr1, AuxTmr2, AuxTmr3, AuxTmr4, AuxTmr5, AuxTmr6; } ctrl_t; /************************************************************************* * The following data structure stores a mesh. **************************************************************************/ typedef struct mesh_t { idx_t etype; idx_t gnelms, gnns; idx_t nelms, nns; idx_t ncon; idx_t esize, gminnode; idx_t *elmdist; idx_t *elements; idx_t *elmwgt; } mesh_t;
10,131
37.378788
101
h
null
ParMETIS-main/libparmetis/stat.c
/* * Copyright 1997, Regents of the University of Minnesota * * stat.c * * This file computes various statistics * * Started 7/25/97 * George * * $Id: stat.c 10578 2011-07-14 18:10:15Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function computes the balance of the partitioning **************************************************************************/ void ComputeSerialBalance(ctrl_t *ctrl, graph_t *graph, idx_t *where, real_t *ubvec) { idx_t i, j, nvtxs, ncon, nparts; idx_t *pwgts, *tvwgts, *vwgt; real_t *tpwgts, maximb; nvtxs = graph->nvtxs; ncon = graph->ncon; vwgt = graph->vwgt; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; pwgts = ismalloc(nparts*ncon, 0, "pwgts"); tvwgts = ismalloc(ncon, 0, "tvwgts"); for (i=0; i<graph->nvtxs; i++) { for (j=0; j<ncon; j++) { pwgts[where[i]*ncon+j] += vwgt[i*ncon+j]; tvwgts[j] += vwgt[i*ncon+j]; } } /* The +1 in the following code is to deal with bad cases of tpwgts[i*ncon+j] == 0 */ for (j=0; j<ncon; j++) { maximb = 0.0; for (i=0; i<nparts; i++) maximb =gk_max(maximb, (1.0+(real_t)pwgts[i*ncon+j])/(1.0+(tpwgts[i*ncon+j]*(real_t)tvwgts[j]))); ubvec[j] = maximb; } gk_free((void **)&pwgts, (void **)&tvwgts, LTERM); } /************************************************************************* * This function computes the balance of the partitioning **************************************************************************/ void ComputeParallelBalance(ctrl_t *ctrl, graph_t *graph, idx_t *where, real_t *ubvec) { idx_t i, j, nvtxs, ncon, nparts; real_t *nvwgt, *lnpwgts, *gnpwgts, *lminvwgts, *gminvwgts; real_t *tpwgts, maximb; WCOREPUSH; ncon = graph->ncon; nvtxs = graph->nvtxs; nvwgt = graph->nvwgt; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; lminvwgts = rset(ncon, 1.0, rwspacemalloc(ctrl, ncon)); gminvwgts = rwspacemalloc(ctrl, ncon); lnpwgts = rset(nparts*ncon, 0.0, rwspacemalloc(ctrl, nparts*ncon)); gnpwgts = rwspacemalloc(ctrl, nparts*ncon); for (i=0; i<nvtxs; i++) { for (j=0; j<ncon; j++) { lnpwgts[where[i]*ncon+j] += nvwgt[i*ncon+j]; /* The following is to deal with tpwgts[] that are 0.0 for certain partitions/constraints */ lminvwgts[j] = (nvwgt[i*ncon+j] > 0.0 && lminvwgts[j] > nvwgt[i*ncon+j] ? nvwgt[i*ncon+j] : lminvwgts[j]); } } gkMPI_Allreduce((void *)(lnpwgts), (void *)(gnpwgts), nparts*ncon, REAL_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)(lminvwgts), (void *)(gminvwgts), ncon, REAL_T, MPI_MIN, ctrl->comm); /* The +gminvwgts[j] in the following code is to deal with bad cases of tpwgts[i*ncon+j] == 0 */ for (j=0; j<ncon; j++) { maximb = 0.0; for (i=0; i<nparts; i++) maximb =gk_max(maximb, (gminvwgts[j]+gnpwgts[i*ncon+j])/(gminvwgts[j]+tpwgts[i*ncon+j])); ubvec[j] = maximb; } WCOREPOP; } /************************************************************************* * This function prints a matrix **************************************************************************/ void Mc_PrintThrottleMatrix(ctrl_t *ctrl, graph_t *graph, real_t *matrix) { idx_t i, j; for (i=0; i<ctrl->npes; i++) { if (i == ctrl->mype) { for (j=0; j<ctrl->npes; j++) printf("%.3"PRREAL" ", matrix[j]); printf("\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); } if (ctrl->mype == 0) { printf("****************************\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); return; } /***********************************************************************************/ /*! This function prints post-partitioning information */ /***********************************************************************************/ void PrintPostPartInfo(ctrl_t *ctrl, graph_t *graph, idx_t movestats) { idx_t i, j, ncon, nmoved, maxin, maxout, nparts; real_t maximb, *tpwgts; ncon = graph->ncon; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; rprintf(ctrl, "Final %3"PRIDX"-way Cut: %6"PRIDX" \tBalance: ", nparts, graph->mincut); for (j=0; j<ncon; j++) { for (maximb=0.0, i=0; i<nparts; i++) maximb = gk_max(maximb, graph->gnpwgts[i*ncon+j]/tpwgts[i*ncon+j]); rprintf(ctrl, "%.3"PRREAL" ", maximb); } if (movestats) { Mc_ComputeMoveStatistics(ctrl, graph, &nmoved, &maxin, &maxout); rprintf(ctrl, "\nNMoved: %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", nmoved, maxin, maxout, maxin+maxout); } else { rprintf(ctrl, "\n"); } } /************************************************************************* * This function computes movement statistics for adaptive refinement * schemes **************************************************************************/ void ComputeMoveStatistics(ctrl_t *ctrl, graph_t *graph, idx_t *nmoved, idx_t *maxin, idx_t *maxout) { idx_t i, j, nvtxs; idx_t *vwgt, *where; idx_t *lpvtxs, *gpvtxs; nvtxs = graph->nvtxs; vwgt = graph->vwgt; where = graph->where; lpvtxs = ismalloc(ctrl->nparts, 0, "ComputeMoveStatistics: lpvtxs"); gpvtxs = ismalloc(ctrl->nparts, 0, "ComputeMoveStatistics: gpvtxs"); for (j=i=0; i<nvtxs; i++) { lpvtxs[where[i]]++; if (where[i] != ctrl->mype) j++; } /* PrintVector(ctrl, ctrl->npes, 0, lpvtxs, "Lpvtxs: "); */ gkMPI_Allreduce((void *)lpvtxs, (void *)gpvtxs, ctrl->nparts, IDX_T, MPI_SUM, ctrl->comm); *nmoved = GlobalSESum(ctrl, j); *maxout = GlobalSEMax(ctrl, j); *maxin = GlobalSEMax(ctrl, gpvtxs[ctrl->mype]-(nvtxs-j)); gk_free((void **)&lpvtxs, (void **)&gpvtxs, LTERM); }
5,661
27.59596
112
c
null
ParMETIS-main/libparmetis/remap.c
/* * premap.c * * This file contains code that computes the assignment of processors to * partition numbers so that it will minimize the redistribution cost * * Started 4/16/98 * George * * $Id: remap.c 10361 2011-06-21 19:16:22Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function remaps that graph so that it will minimize the * redistribution cost **************************************************************************/ void ParallelReMapGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, nvtxs, nparts; idx_t *where, *vsize, *map, *lpwgts; IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->RemapTmr)); if (ctrl->npes != ctrl->nparts) { IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->RemapTmr)); return; } WCOREPUSH; nvtxs = graph->nvtxs; where = graph->where; vsize = graph->vsize; nparts = ctrl->nparts; map = iwspacemalloc(ctrl, nparts); lpwgts = iset(nparts, 0, iwspacemalloc(ctrl, nparts)); for (i=0; i<nvtxs; i++) lpwgts[where[i]] += (vsize == NULL) ? 1 : vsize[i]; ParallelTotalVReMap(ctrl, lpwgts, map, NREMAP_PASSES, graph->ncon); for (i=0; i<nvtxs; i++) where[i] = map[where[i]]; WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->RemapTmr)); } /************************************************************************* * This function computes the assignment using the the objective the * minimization of the total volume of data that needs to move **************************************************************************/ void ParallelTotalVReMap(ctrl_t *ctrl, idx_t *lpwgts, idx_t *map, idx_t npasses, idx_t ncon) { idx_t i, ii, j, k, nparts, mype; idx_t pass, maxipwgt, nmapped, oldwgt, newwgt, done; idx_t *rowmap, *mylpwgts; ikv_t *recv, send; idx_t nsaved, gnsaved; WCOREPUSH; mype = ctrl->mype; nparts = ctrl->nparts; rowmap = iset(nparts, -1, iwspacemalloc(ctrl, nparts)); mylpwgts = icopy(nparts, lpwgts, iwspacemalloc(ctrl, nparts)); recv = ikvwspacemalloc(ctrl, nparts); iset(nparts, -1, map); done = nmapped = 0; for (pass=0; pass<npasses; pass++) { maxipwgt = iargmax(nparts, mylpwgts, 1); if (mylpwgts[maxipwgt] > 0 && !done) { send.key = -mylpwgts[maxipwgt]; send.val = mype*nparts+maxipwgt; } else { send.key = 0; send.val = -1; } /* each processor sends its selection */ gkMPI_Allgather((void *)&send, 2, IDX_T, (void *)recv, 2, IDX_T, ctrl->comm); ikvsorti(nparts, recv); if (recv[0].key == 0) break; /* now make as many assignments as possible */ for (ii=0; ii<nparts; ii++) { i = recv[ii].val; if (i == -1) continue; j = i%nparts; k = i/nparts; if (map[j] == -1 && rowmap[k] == -1 && SimilarTpwgts(ctrl->tpwgts, ncon, j, k)) { map[j] = k; rowmap[k] = j; nmapped++; mylpwgts[j] = 0; if (mype == k) done = 1; } if (nmapped == nparts) break; } if (nmapped == nparts) break; } /* Map unmapped partitions */ if (nmapped < nparts) { for (i=j=0; j<nparts && nmapped<nparts; j++) { if (map[j] == -1) { for (; i<nparts; i++) { if (rowmap[i] == -1 && SimilarTpwgts(ctrl->tpwgts, ncon, i, j)) { map[j] = i; rowmap[i] = j; nmapped++; break; } } } } } /* check to see if remapping fails (due to dis-similar tpwgts) */ /* if remapping fails, revert to original mapping */ if (nmapped < nparts) { for (i=0; i<nparts; i++) map[i] = i; IFSET(ctrl->dbglvl, DBG_REMAP, rprintf(ctrl, "Savings from parallel remapping: %0\n")); } else { /* check for a savings */ oldwgt = lpwgts[mype]; newwgt = lpwgts[rowmap[mype]]; nsaved = newwgt - oldwgt; gnsaved = GlobalSESum(ctrl, nsaved); /* undo everything if we don't see a savings */ if (gnsaved <= 0) { for (i=0; i<nparts; i++) map[i] = i; } IFSET(ctrl->dbglvl, DBG_REMAP, rprintf(ctrl, "Savings from parallel remapping: %"PRIDX"\n",gk_max(0,gnsaved))); } WCOREPOP; } /************************************************************************* * This function computes the assignment using the the objective the * minimization of the total volume of data that needs to move **************************************************************************/ idx_t SimilarTpwgts(real_t *tpwgts, idx_t ncon, idx_t s1, idx_t s2) { idx_t i; for (i=0; i<ncon; i++) if (fabs(tpwgts[s1*ncon+i]-tpwgts[s2*ncon+i]) > SMALLFLOAT) break; if (i == ncon) return 1; return 0; }
4,883
24.978723
92
c
null
ParMETIS-main/libparmetis/balancemylink.c
/* * Copyright 1997, Regents of the University of Minnesota * * balancemylink.c * * This file contains code that implements the edge-based FM refinement * * Started 7/23/97 * George * * $Id: balancemylink.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define PE 0 /************************************************************************* * This function performs an edge-based FM refinement **************************************************************************/ idx_t BalanceMyLink(ctrl_t *ctrl, graph_t *graph, idx_t *home, idx_t me, idx_t you, real_t *flows, real_t maxdiff, real_t *diff_cost, real_t *diff_lbavg, real_t avgvwgt) { idx_t h, i, ii, j, k, mype; idx_t nvtxs, ncon; idx_t nqueues, minval, maxval, higain, vtx, edge, totalv; idx_t from, to, qnum, index, nchanges, cut, tmp; idx_t pass, nswaps, nmoves, multiplier; idx_t *xadj, *vsize, *adjncy, *adjwgt, *where, *ed, *id; idx_t *hval, *nvpq, *inq, *map, *rmap, *ptr, *myqueue, *changes; real_t *nvwgt, *lbvec, *pwgts, *tpwgts, *my_wgt; real_t newgain; real_t lbavg, bestflow, mycost; real_t ipc_factor, redist_factor, ftmp; rpq_t **queues; WCOREPUSH; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; nvwgt = graph->nvwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; ipc_factor = ctrl->ipc_factor; redist_factor = ctrl->redist_factor; hval = iwspacemalloc(ctrl, nvtxs); id = iwspacemalloc(ctrl, nvtxs); ed = iwspacemalloc(ctrl, nvtxs); map = iwspacemalloc(ctrl, nvtxs); rmap = iwspacemalloc(ctrl, nvtxs); myqueue = iwspacemalloc(ctrl, nvtxs); changes = iwspacemalloc(ctrl, nvtxs); lbvec = rwspacemalloc(ctrl, ncon); pwgts = rset(2*ncon, 0.0, rwspacemalloc(ctrl, 2*ncon)); tpwgts = rwspacemalloc(ctrl, 2*ncon); my_wgt = rset(ncon, 0.0, rwspacemalloc(ctrl, ncon)); for (h=0; h<ncon; h++) { tpwgts[h] = -1.0*flows[h]; tpwgts[ncon+h] = flows[h]; } for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) { tpwgts[h] += nvwgt[i*ncon+h]; pwgts[h] += nvwgt[i*ncon+h]; } } else { ASSERT(where[i] == you); for (h=0; h<ncon; h++) { tpwgts[ncon+h] += nvwgt[i*ncon+h]; pwgts[ncon+h] += nvwgt[i*ncon+h]; } } } /* we don't want any tpwgts to be less than zero */ for (h=0; h<ncon; h++) { if (tpwgts[h] < 0.0) { tpwgts[ncon+h] += tpwgts[h]; tpwgts[h] = 0.0; } if (tpwgts[ncon+h] < 0.0) { tpwgts[h] += tpwgts[ncon+h]; tpwgts[ncon+h] = 0.0; } } /*******************************/ /* insert vertices into queues */ /*******************************/ minval = maxval = 0; multiplier = 1; for (i=0; i<ncon; i++) { multiplier *= (i+1); maxval += i*multiplier; minval += (ncon-1-i)*multiplier; } nqueues = maxval-minval+1; nvpq = iset(nqueues, 0, iwspacemalloc(ctrl, nqueues)); ptr = iwspacemalloc(ctrl, nqueues+1); inq = iwspacemalloc(ctrl, 2*nqueues); queues = (rpq_t **)(wspacemalloc(ctrl, sizeof(rpq_t *)*2*nqueues)); for (i=0; i<nvtxs; i++) hval[i] = Mc_HashVwgts(ctrl, ncon, nvwgt+i*ncon) - minval; for (i=0; i<nvtxs; i++) nvpq[hval[i]]++; for (ptr[0]=0, i=0; i<nqueues; i++) ptr[i+1] = ptr[i] + nvpq[i]; for (i=0; i<nvtxs; i++) { map[i] = ptr[hval[i]]; rmap[ptr[hval[i]]++] = i; } SHIFTCSR(i, nqueues, ptr); /* initialize queues */ for (i=0; i<nqueues; i++) if (nvpq[i] > 0) { queues[i] = rpqCreate(nvpq[i]); queues[nqueues+i] = rpqCreate(nvpq[i]); } /* compute internal/external degrees */ iset(nvtxs, 0, id); iset(nvtxs, 0, ed); for (j=0; j<nvtxs; j++) { for (k=xadj[j]; k<xadj[j+1]; k++) { if (where[adjncy[k]] == where[j]) id[j] += adjwgt[k]; else ed[j] += adjwgt[k]; } } nswaps = 0; for (pass=0; pass<N_MOC_BAL_PASSES; pass++) { iset(nvtxs, -1, myqueue); iset(nqueues*2, 0, inq); /* insert vertices into correct queues */ for (j=0; j<nvtxs; j++) { index = (where[j] == me) ? 0 : nqueues; newgain = ipc_factor*(real_t)(ed[j]-id[j]); if (home[j] == me || home[j] == you) { if (where[j] == home[j]) newgain -= redist_factor*(real_t)vsize[j]; else newgain += redist_factor*(real_t)vsize[j]; } rpqInsert(queues[hval[j]+index], map[j]-ptr[hval[j]], newgain); myqueue[j] = (where[j] == me) ? 0 : 1; inq[hval[j]+index]++; } /* bestflow = rfavg(ncon, flows); */ for (j=0, h=0; h<ncon; h++) { if (fabs(flows[h]) > fabs(flows[j])) j = h; } bestflow = fabs(flows[j]); nchanges = nmoves = 0; for (ii=0; ii<nvtxs/2; ii++) { from = -1; Mc_DynamicSelectQueue(ctrl, nqueues, ncon, me, you, inq, flows, &from, &qnum, minval, avgvwgt, maxdiff); /* can't find a vertex in one subdomain, try the other */ if (from != -1 && qnum == -1) { from = (from == me) ? you : me; if (from == me) { for (j=0; j<ncon; j++) { if (flows[j] > avgvwgt) break; } } else { for (j=0; j<ncon; j++) { if (flows[j] < -1.0*avgvwgt) break; } } if (j != ncon) Mc_DynamicSelectQueue(ctrl, nqueues, ncon, me, you, inq, flows, &from, &qnum, minval, avgvwgt, maxdiff); } if (qnum == -1) break; to = (from == me) ? you : me; index = (from == me) ? 0 : nqueues; higain = rpqGetTop(queues[qnum+index]); inq[qnum+index]--; ASSERT(higain != -1); /*****************/ /* make the swap */ /*****************/ vtx = rmap[higain+ptr[qnum]]; myqueue[vtx] = -1; where[vtx] = to; nswaps++; nmoves++; /* update the flows */ for (j=0; j<ncon; j++) flows[j] += (to == me) ? nvwgt[vtx*ncon+j] : -1.0*nvwgt[vtx*ncon+j]; /* ftmp = rfavg(ncon, flows); */ for (j=0, h=0; h<ncon; h++) { if (fabs(flows[h]) > fabs(flows[j])) j = h; } ftmp = fabs(flows[j]); if (ftmp < bestflow) { bestflow = ftmp; nchanges = 0; } else { changes[nchanges++] = vtx; } gk_SWAP(id[vtx], ed[vtx], tmp); for (j=xadj[vtx]; j<xadj[vtx+1]; j++) { edge = adjncy[j]; tmp = (to == where[edge] ? adjwgt[j] : -adjwgt[j]); INC_DEC(id[edge], ed[edge], tmp); if (myqueue[edge] != -1) { newgain = ipc_factor*(real_t)(ed[edge]-id[edge]); if (home[edge] == me || home[edge] == you) { if (where[edge] == home[edge]) newgain -= redist_factor*(real_t)vsize[edge]; else newgain += redist_factor*(real_t)vsize[edge]; } rpqUpdate(queues[hval[edge]+(nqueues*myqueue[edge])], map[edge]-ptr[hval[edge]], newgain); } } } /****************************/ /* now go back to best flow */ /****************************/ nswaps -= nchanges; nmoves -= nchanges; for (i=0; i<nchanges; i++) { vtx = changes[i]; from = where[vtx]; where[vtx] = to = (from == me) ? you : me; gk_SWAP(id[vtx], ed[vtx], tmp); for (j=xadj[vtx]; j<xadj[vtx+1]; j++) { edge = adjncy[j]; tmp = (to == where[edge] ? adjwgt[j] : -adjwgt[j]); INC_DEC(id[edge], ed[edge], tmp); } } for (i=0; i<nqueues; i++) { if (nvpq[i] > 0) { rpqReset(queues[i]); rpqReset(queues[i+nqueues]); } } if (nmoves == 0) break; } /***************************/ /* compute 2-way imbalance */ /***************************/ for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) my_wgt[h] += nvwgt[i*ncon+h]; } } for (i=0; i<ncon; i++) { ftmp = (pwgts[i]+pwgts[ncon+i])/2.0; if (ftmp != 0.0) lbvec[i] = fabs(my_wgt[i]-tpwgts[i]) / ftmp; else lbvec[i] = 0.0; } lbavg = ravg(ncon, lbvec); *diff_lbavg = lbavg; /****************/ /* compute cost */ /****************/ cut = totalv = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) totalv += vsize[i]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (where[adjncy[j]] != where[i]) cut += adjwgt[j]; } } cut /= 2; mycost = cut*ipc_factor + totalv*redist_factor; *diff_cost = mycost; /* free memory */ for (i=0; i<nqueues; i++) { if (nvpq[i] > 0) { rpqDestroy(queues[i]); rpqDestroy(queues[i+nqueues]); } } WCOREPOP; return nswaps; }
8,895
24.489971
76
c
null
ParMETIS-main/libparmetis/move.c
/* * Copyright 1997, Regents of the University of Minnesota * * mmove.c * * This file contains functions that move the graph given a partition * * Started 11/22/96 * George * * $Id: move.c 10657 2011-08-03 14:34:35Z karypis $ * */ #include <parmetislib.h> /*************************************************************************/ /*! This function moves the graph, and returns a new graph. This routine can be called with or without performing refinement. In the latter case it allocates and computes lpwgts itself. */ /*************************************************************************/ graph_t *MoveGraph(ctrl_t *ctrl, graph_t *graph) { idx_t h, i, ii, j, jj, nvtxs, ncon, npes, nsnbrs, nrnbrs; idx_t *xadj, *vwgt, *adjncy, *adjwgt, *mvtxdist; idx_t *where, *newlabel, *lpwgts, *gpwgts; idx_t *sgraph, *rgraph; ikv_t *sinfo, *rinfo; graph_t *mgraph; WCOREPUSH; /* this routine only works when nparts <= npes */ PASSERT(ctrl, ctrl->nparts <= ctrl->npes); npes = ctrl->npes; nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; vwgt = graph->vwgt; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; mvtxdist = imalloc(npes+1, "MoveGraph: mvtxdist"); /* Let's do a prefix scan to determine the labeling of the nodes given */ lpwgts = iwspacemalloc(ctrl, npes+1); gpwgts = iwspacemalloc(ctrl, npes+1); sinfo = ikvwspacemalloc(ctrl, npes); rinfo = ikvwspacemalloc(ctrl, npes); for (i=0; i<npes; i++) sinfo[i].key = sinfo[i].val = 0; for (i=0; i<nvtxs; i++) { sinfo[where[i]].key++; sinfo[where[i]].val += xadj[i+1]-xadj[i]; } for (i=0; i<npes; i++) lpwgts[i] = sinfo[i].key; gkMPI_Scan((void *)lpwgts, (void *)gpwgts, npes, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)mvtxdist, npes, IDX_T, MPI_SUM, ctrl->comm); MAKECSR(i, npes, mvtxdist); /* gpwgts[i] will store the label of the first vertex for each domain in each processor */ for (i=0; i<npes; i++) /* We were interested in an exclusive scan */ gpwgts[i] = mvtxdist[i] + gpwgts[i] - lpwgts[i]; newlabel = iwspacemalloc(ctrl, nvtxs+graph->nrecv); for (i=0; i<nvtxs; i++) newlabel[i] = gpwgts[where[i]]++; /* OK, now send the newlabel info to processors storing adjacent interface nodes */ CommInterfaceData(ctrl, graph, newlabel, newlabel+nvtxs); /* Now lets tell everybody what and from where he will get it. */ gkMPI_Alltoall((void *)sinfo, 2, IDX_T, (void *)rinfo, 2, IDX_T, ctrl->comm); /* Use lpwgts and gpwgts as pointers to where data will be received and send */ lpwgts[0] = 0; /* Send part */ gpwgts[0] = 0; /* Received part */ for (nsnbrs=nrnbrs=0, i=0; i<npes; i++) { lpwgts[i+1] = lpwgts[i] + (1+ncon)*sinfo[i].key + 2*sinfo[i].val; gpwgts[i+1] = gpwgts[i] + (1+ncon)*rinfo[i].key + 2*rinfo[i].val; if (rinfo[i].key > 0) nrnbrs++; if (sinfo[i].key > 0) nsnbrs++; } /* Update the max # of sreq/rreq/statuses */ CommUpdateNnbrs(ctrl, gk_max(nsnbrs, nrnbrs)); rgraph = iwspacemalloc(ctrl, gpwgts[npes]); WCOREPUSH; /* for freeing the send part early */ sgraph = iwspacemalloc(ctrl, lpwgts[npes]); /* Issue the receives first */ for (j=0, i=0; i<npes; i++) { if (rinfo[i].key > 0) gkMPI_Irecv((void *)(rgraph+gpwgts[i]), gpwgts[i+1]-gpwgts[i], IDX_T, i, 1, ctrl->comm, ctrl->rreq+j++); else PASSERT(ctrl, gpwgts[i+1]-gpwgts[i] == 0); } /* Assemble the graph to be sent and send it */ for (i=0; i<nvtxs; i++) { PASSERT(ctrl, where[i] >= 0 && where[i] < npes); ii = lpwgts[where[i]]; sgraph[ii++] = xadj[i+1]-xadj[i]; for (h=0; h<ncon; h++) sgraph[ii++] = vwgt[i*ncon+h]; for (j=xadj[i]; j<xadj[i+1]; j++) { sgraph[ii++] = newlabel[adjncy[j]]; sgraph[ii++] = adjwgt[j]; } lpwgts[where[i]] = ii; } SHIFTCSR(i, npes, lpwgts); for (j=0, i=0; i<npes; i++) { if (sinfo[i].key > 0) gkMPI_Isend((void *)(sgraph+lpwgts[i]), lpwgts[i+1]-lpwgts[i], IDX_T, i, 1, ctrl->comm, ctrl->sreq+j++); else PASSERT(ctrl, lpwgts[i+1]-lpwgts[i] == 0); } /* Wait for the send/recv to finish */ gkMPI_Waitall(nrnbrs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nsnbrs, ctrl->sreq, ctrl->statuses); WCOREPOP; /* frees sgraph */ /* OK, now go and put the graph into graph_t Format */ mgraph = CreateGraph(); mgraph->vtxdist = mvtxdist; mgraph->gnvtxs = graph->gnvtxs; mgraph->ncon = ncon; mgraph->level = 0; mgraph->nvtxs = mgraph->nedges = 0; for (i=0; i<npes; i++) { mgraph->nvtxs += rinfo[i].key; mgraph->nedges += rinfo[i].val; } nvtxs = mgraph->nvtxs; xadj = mgraph->xadj = imalloc(nvtxs+1, "MMG: mgraph->xadj"); vwgt = mgraph->vwgt = imalloc(nvtxs*ncon, "MMG: mgraph->vwgt"); adjncy = mgraph->adjncy = imalloc(mgraph->nedges, "MMG: mgraph->adjncy"); adjwgt = mgraph->adjwgt = imalloc(mgraph->nedges, "MMG: mgraph->adjwgt"); for (jj=ii=i=0; i<nvtxs; i++) { xadj[i] = rgraph[ii++]; for (h=0; h<ncon; h++) vwgt[i*ncon+h] = rgraph[ii++]; for (j=0; j<xadj[i]; j++, jj++) { adjncy[jj] = rgraph[ii++]; adjwgt[jj] = rgraph[ii++]; } } MAKECSR(i, nvtxs, xadj); PASSERT(ctrl, jj == mgraph->nedges); PASSERT(ctrl, ii == gpwgts[npes]); PASSERTP(ctrl, jj == mgraph->nedges, (ctrl, "%"PRIDX" %"PRIDX"\n", jj, mgraph->nedges)); PASSERTP(ctrl, ii == gpwgts[npes], (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", ii, gpwgts[npes], jj, mgraph->nedges, nvtxs)); #ifdef DEBUG IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Checking moved graph...\n")); CheckMGraph(ctrl, mgraph); IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Moved graph is consistent.\n")); #endif WCOREPOP; return mgraph; } /************************************************************************* * This function is used to transfer information from the moved graph * back to the original graph. The information is transfered from array * minfo to array info. The routine assumes that graph->where is left intact * and it is used to get the inverse mapping information. * The routine assumes that graph->where corresponds to a npes-way partition. **************************************************************************/ void ProjectInfoBack(ctrl_t *ctrl, graph_t *graph, idx_t *info, idx_t *minfo) { idx_t i, nvtxs, nparts, nrecvs, nsends; idx_t *where, *auxinfo, *sinfo, *rinfo; WCOREPUSH; nparts = ctrl->npes; nvtxs = graph->nvtxs; where = graph->where; sinfo = iwspacemalloc(ctrl, nparts+1); rinfo = iwspacemalloc(ctrl, nparts+1); /* Find out in rinfo how many entries are received per partition */ iset(nparts, 0, rinfo); for (i=0; i<nvtxs; i++) rinfo[where[i]]++; /* The rinfo are transposed and become the sinfo for the back-projection */ gkMPI_Alltoall((void *)rinfo, 1, IDX_T, (void *)sinfo, 1, IDX_T, ctrl->comm); MAKECSR(i, nparts, sinfo); MAKECSR(i, nparts, rinfo); /* allocate memory for auxinfo */ auxinfo = iwspacemalloc(ctrl, rinfo[nparts]); /*----------------------------------------------------------------- * Now, go and send back the minfo -----------------------------------------------------------------*/ for (nrecvs=0, i=0; i<nparts; i++) { if (rinfo[i+1]-rinfo[i] > 0) gkMPI_Irecv((void *)(auxinfo+rinfo[i]), rinfo[i+1]-rinfo[i], IDX_T, i, 1, ctrl->comm, ctrl->rreq+nrecvs++); } for (nsends=0, i=0; i<nparts; i++) { if (sinfo[i+1]-sinfo[i] > 0) gkMPI_Isend((void *)(minfo+sinfo[i]), sinfo[i+1]-sinfo[i], IDX_T, i, 1, ctrl->comm, ctrl->sreq+nsends++); } PASSERT(ctrl, nrecvs <= ctrl->ncommpes); PASSERT(ctrl, nsends <= ctrl->ncommpes); /* Wait for the send/recv to finish */ gkMPI_Waitall(nrecvs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nsends, ctrl->sreq, ctrl->statuses); /* Scatter the info received in auxinfo back to info. */ for (i=0; i<nvtxs; i++) info[i] = auxinfo[rinfo[where[i]]++]; WCOREPOP; } /************************************************************************* * This function is used to convert a partition vector to a permutation * vector. **************************************************************************/ void FindVtxPerm(ctrl_t *ctrl, graph_t *graph, idx_t *perm) { idx_t i, nvtxs, nparts; idx_t *xadj, *adjncy, *adjwgt, *mvtxdist; idx_t *where, *lpwgts, *gpwgts; WCOREPUSH; nparts = ctrl->nparts; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; mvtxdist = iwspacemalloc(ctrl, nparts+1); lpwgts = iwspacemalloc(ctrl, nparts+1); gpwgts = iwspacemalloc(ctrl, nparts+1); /* Here we care about the count and not total weight (diff since graph may be weighted */ iset(nparts, 0, lpwgts); for (i=0; i<nvtxs; i++) lpwgts[where[i]]++; /* Let's do a prefix scan to determine the labeling of the nodes given */ gkMPI_Scan((void *)lpwgts, (void *)gpwgts, nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)mvtxdist, nparts, IDX_T, MPI_SUM, ctrl->comm); MAKECSR(i, nparts, mvtxdist); for (i=0; i<nparts; i++) gpwgts[i] = mvtxdist[i] + gpwgts[i] - lpwgts[i]; /* We were interested in an exclusive Scan */ for (i=0; i<nvtxs; i++) perm[i] = gpwgts[where[i]]++; WCOREPOP; } /************************************************************************* * This function quickly performs a check on the consistency of moved graph. **************************************************************************/ void CheckMGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, jj, k, nvtxs, firstvtx, lastvtx; idx_t *xadj, *adjncy, *vtxdist; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vtxdist = graph->vtxdist; firstvtx = vtxdist[ctrl->mype]; lastvtx = vtxdist[ctrl->mype+1]; for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (firstvtx+i == adjncy[j]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") diagonal entry\n", i, i); if (adjncy[j] >= firstvtx && adjncy[j] < lastvtx) { k = adjncy[j]-firstvtx; for (jj=xadj[k]; jj<xadj[k+1]; jj++) { if (adjncy[jj] == firstvtx+i) break; } if (jj == xadj[k+1]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") but not (%"PRIDX" %"PRIDX") [%"PRIDX" %"PRIDX"] [%"PRIDX" %"PRIDX"]\n", i, k, k, i, firstvtx+i, firstvtx+k, xadj[i+1]-xadj[i], xadj[k+1]-xadj[k]); } } } }
10,661
30.175439
118
c
null
ParMETIS-main/libparmetis/node_refine.c
/* * Copyright 1997, Regents of the University of Minnesota * * node_refine.c * * This file contains code that performs the k-way refinement * * Started 3/1/96 * George * * $Id: node_refine.c 10391 2011-06-23 19:00:08Z karypis $ */ #include <parmetislib.h> /************************************************************************************/ /*! This function allocates the memory required for the nodeND refinement code. The only refinement-related information that is has is the \c graph->where vector and allocates the memory for the remaining of the refinement-related data-structures. */ /************************************************************************************/ void AllocateNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t nparts, nvtxs; idx_t *vwgt; NRInfoType *rinfo, *myrinfo; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; graph->nrinfo = (NRInfoType *)gk_malloc(sizeof(NRInfoType)*nvtxs, "AllocateNodePartitionParams: rinfo"); graph->lpwgts = imalloc(2*nparts, "AllocateNodePartitionParams: lpwgts"); graph->gpwgts = imalloc(2*nparts, "AllocateNodePartitionParams: gpwgts"); graph->sepind = imalloc(nvtxs, "AllocateNodePartitionParams: sepind"); /* Allocate additional memory for graph->vwgt in order to store the weights of the remote vertices */ vwgt = graph->vwgt; graph->vwgt = imalloc(nvtxs+graph->nrecv, "AllocateNodePartitionParams: graph->vwgt"); icopy(nvtxs, vwgt, graph->vwgt); gk_free((void **)&vwgt, LTERM); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function computes the initial node refinment information for the parallel nodeND code. It requires that the required data-structures have already been allocated via a call to AllocateNodePartitionParams. */ /************************************************************************************/ void ComputeNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nparts, nvtxs, nsep; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt, *lpwgts, *gpwgts, *sepind; idx_t *where; NRInfoType *rinfo, *myrinfo; idx_t me, other, otherwgt; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; sepind = graph->sepind; /* Reset refinement data structures */ iset(2*nparts, 0, lpwgts); /* Send/Receive the where and vwgt information of interface vertices. */ CommInterfaceData(ctrl, graph, where, where+nvtxs); CommInterfaceData(ctrl, graph, vwgt, vwgt+nvtxs); /*------------------------------------------------------------ / Compute now the degrees /------------------------------------------------------------*/ for (nsep=i=0; i<nvtxs; i++) { me = where[i]; PASSERT(ctrl, me >= 0 && me < 2*nparts); lpwgts[me] += vwgt[i]; if (me >= nparts) { /* If it is a separator vertex */ sepind[nsep++] = i; lpwgts[2*nparts-1] += vwgt[i]; /* Keep track of total separator weight */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } graph->nsep = nsep; /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function updates the node refinment information after a where[] change */ /************************************************************************************/ void UpdateNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nparts, nvtxs, nsep; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt, *lpwgts, *gpwgts, *sepind; idx_t *where; NRInfoType *rinfo, *myrinfo; idx_t me, other, otherwgt; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; sepind = graph->sepind; /* Reset refinement data structures */ iset(2*nparts, 0, lpwgts); /* Send/Receive the where and vwgt information of interface vertices. */ CommInterfaceData(ctrl, graph, where, where+nvtxs); /*------------------------------------------------------------ / Compute now the degrees /------------------------------------------------------------*/ for (nsep=i=0; i<nvtxs; i++) { me = where[i]; PASSERT(ctrl, me >= 0 && me < 2*nparts); lpwgts[me] += vwgt[i]; if (me >= nparts) { /* If it is a separator vertex */ sepind[nsep++] = i; lpwgts[2*nparts-1] += vwgt[i]; /* Keep track of total separator weight */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } graph->nsep = nsep; /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function performs k-way node-based refinement. The refinement is done concurrently for all the different partitions. It works because each of the partitions is disconnected from each other due to the removal of the previous level separators. This version uses a priority queue to order the nodes and incorporates gain updates from the local information within each inner iteration. The refinement exits when there is no improvement in two successive itereations in order to account for the fact that a 0 => 1 iteration may have no gain but a 1 => 0 iteration may have a gain. */ /************************************************************************************/ void KWayNodeRefine_Greedy(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, ii, iii, j, jj, k, pass, nvtxs, nrecv, firstvtx, lastvtx, otherlastvtx, side, c, cc, nmoves, nlupd, nsupd, nnbrs, nchanged, nsep, nzerogainiterations; idx_t npes = ctrl->npes, mype = ctrl->mype, nparts = ctrl->nparts; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt; idx_t *where, *lpwgts, *gpwgts, *sepind; idx_t *peind, *recvptr, *sendptr; idx_t *update, *supdate, *rupdate, *pe_updates, *marker, *changed; idx_t *badmaxpwgt; ikv_t *swchanges, *rwchanges; idx_t *nupds_pe; NRInfoType *rinfo, *myrinfo; idx_t from, to, me, other, oldcut; rpq_t *queue; idx_t *inqueue; idx_t *rxadj, *radjncy; char title[1024]; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayTmr)); WCOREPUSH; nvtxs = graph->nvtxs; nrecv = graph->nrecv; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; firstvtx = vtxdist[mype]; lastvtx = vtxdist[mype+1]; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; nsep = graph->nsep; sepind = graph->sepind; nnbrs = graph->nnbrs; peind = graph->peind; recvptr = graph->recvptr; sendptr = graph->sendptr; badmaxpwgt = iwspacemalloc(ctrl, nparts); nupds_pe = iwspacemalloc(ctrl, npes); changed = iwspacemalloc(ctrl, nvtxs); update = iwspacemalloc(ctrl, nvtxs); marker = iset(nvtxs+nrecv, 0, iwspacemalloc(ctrl, nvtxs+nrecv)); inqueue = iwspacemalloc(ctrl, nvtxs+nrecv); rwchanges = ikvwspacemalloc(ctrl, graph->nrecv); swchanges = ikvwspacemalloc(ctrl, graph->nsend); supdate = iwspacemalloc(ctrl, graph->nrecv); rupdate = iwspacemalloc(ctrl, graph->nsend); queue = rpqCreate(nvtxs); for (i=0; i<nparts; i+=2) { //badmaxpwgt[i] = badmaxpwgt[i+1] = ubfrac*(gpwgts[i]+gpwgts[i+1]+gpwgts[nparts+i])/2; badmaxpwgt[i] = badmaxpwgt[i+1] = ubfrac*(gpwgts[i]+gpwgts[i+1])/2; } /* construct the local adjacency list of the interface nodes */ rxadj = iset(nrecv+1, 0, iwspacemalloc(ctrl, nrecv+1)); for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if ((k = adjncy[j]-nvtxs) >= 0) rxadj[k]++; } } MAKECSR(i, nrecv, rxadj); radjncy = iwspacemalloc(ctrl, rxadj[nrecv]); for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if ((k = adjncy[j]-nvtxs) >= 0) radjncy[rxadj[k]++] = i; } } SHIFTCSR(i, nrecv, rxadj); IFSET(ctrl->dbglvl, DBG_REFINEINFO, PrintNodeBalanceInfo(ctrl, nparts, gpwgts, badmaxpwgt, "K-way sep-refinement")); c = GlobalSESum(ctrl, RandomInRange(2))%2; nzerogainiterations = 0; for (pass=0; pass<npasses; pass++) { oldcut = graph->mincut; for (side=0; side<2; side++) { cc = (c+1)%2; #ifndef NDEBUG /* This is for debugging purposes */ for (ii=0, i=0; i<nvtxs; i++) { if (where[i] >= nparts) ii++; } PASSERT(ctrl, ii == nsep); #endif /* Put the separator nodes in queue */ rpqReset(queue); iset(nvtxs+nrecv, 0, inqueue); for (ii=0; ii<nsep; ii++) { i = sepind[ii]; PASSERT(ctrl, inqueue[i] == 0); PASSERT(ctrl, where[i] >= nparts); rpqInsert(queue, i, vwgt[i] - rinfo[i].edegrees[cc]); inqueue[i] = 1; } nlupd = nsupd = nmoves = nchanged = nsep = 0; while ((i = rpqGetTop(queue)) != -1) { inqueue[i] = 0; from = where[i]; PASSERT(ctrl, from >= nparts); /* It is a one-sided move so it will go to the other partition. Look at the comments in InitMultisection to understand the meaning of from%nparts */ to = from%nparts+c; /* where to move the separator node */ other = from%nparts+cc; /* the other partition involved in the 3-way view */ /* Go through the loop to see if gain is possible for the separator vertex */ if (gpwgts[to]+vwgt[i] <= badmaxpwgt[to] && vwgt[i] - rinfo[i].edegrees[cc] >= 0) { /* Update the where information of the vertex you moved */ where[i] = to; lpwgts[from] -= vwgt[i]; lpwgts[2*nparts-1] -= vwgt[i]; lpwgts[to] += vwgt[i]; gpwgts[to] += vwgt[i]; /* Update and record future updates */ for (j=xadj[i]; j<xadj[i+1]; j++) { ii = adjncy[j]; /* If vertex ii is being pulled into the separator for the first time, then update the edegrees[] of the nodes currently in the queue that vertex ii is connected to */ if (marker[ii] == 0 && where[ii] == other) { if (ii < nvtxs) { /* local vertices */ for (jj=xadj[ii]; jj<xadj[ii+1]; jj++) { iii = adjncy[jj]; if (inqueue[iii] == 1) { PASSERT(ctrl, rinfo[iii].edegrees[cc] >= vwgt[ii]); rinfo[iii].edegrees[cc] -= vwgt[ii]; rpqUpdate(queue, iii, vwgt[iii]-rinfo[iii].edegrees[cc]); } } } else { /* remote vertices */ for (jj=rxadj[ii-nvtxs]; jj<rxadj[ii-nvtxs+1]; jj++) { iii = radjncy[jj]; if (inqueue[iii] == 1) { PASSERT(ctrl, rinfo[iii].edegrees[cc] >= vwgt[ii]); rinfo[iii].edegrees[cc] -= vwgt[ii]; rpqUpdate(queue, iii, vwgt[iii]-rinfo[iii].edegrees[cc]); } } } } /* Put the vertices adjacent to i that belong to either the separator or the cc partition into the update array */ if (marker[ii] == 0 && where[ii] != to) { marker[ii] = 1; if (ii<nvtxs) update[nlupd++] = ii; else supdate[nsupd++] = ii; } } nmoves++; if (graph->pexadj[i+1]-graph->pexadj[i] > 0) changed[nchanged++] = i; } else { /* This node will remain in the separator for the next iteration */ sepind[nsep++] = i; } } /* myprintf(ctrl, "nmoves: %"PRIDX", nlupd: %"PRIDX", nsupd: %"PRIDX"\n", nmoves, nlupd, nsupd); */ IFSET(ctrl->dbglvl, DBG_RMOVEINFO, rprintf(ctrl, "\t[%"PRIDX" %"PRIDX"], [%"PRIDX" %"PRIDX" %"PRIDX"]\n", pass, c, GlobalSESum(ctrl, nmoves), GlobalSESum(ctrl, nsupd), GlobalSESum(ctrl, nlupd))); /*----------------------------------------------------------------------- / Time to communicate with processors to send the vertices whose degrees / need to be updated. /-----------------------------------------------------------------------*/ /* Issue the receives first */ for (i=0; i<nnbrs; i++) { gkMPI_Irecv((void *)(rupdate+sendptr[i]), sendptr[i+1]-sendptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); } /* Issue the sends next. This needs some preporcessing */ for (i=0; i<nsupd; i++) { marker[supdate[i]] = 0; supdate[i] = graph->imap[supdate[i]]; } isorti(nsupd, supdate); for (j=i=0; i<nnbrs; i++) { otherlastvtx = vtxdist[peind[i]+1]; for (k=j; k<nsupd && supdate[k] < otherlastvtx; k++); gkMPI_Isend((void *)(supdate+j), k-j, IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); j = k; } /* OK, now get into the loop waiting for the send/recv operations to finish */ gkMPI_Waitall(nnbrs, ctrl->rreq, ctrl->statuses); for (i=0; i<nnbrs; i++) gkMPI_Get_count(ctrl->statuses+i, IDX_T, nupds_pe+i); gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); /*------------------------------------------------------------- / Place the received to-be updated vertices into update[] /-------------------------------------------------------------*/ for (i=0; i<nnbrs; i++) { pe_updates = rupdate+sendptr[i]; for (j=0; j<nupds_pe[i]; j++) { k = pe_updates[j]; if (marker[k-firstvtx] == 0) { marker[k-firstvtx] = 1; update[nlupd++] = k-firstvtx; } } } /*------------------------------------------------------------- / Update the where information of the vertices that are pulled / into the separator. /-------------------------------------------------------------*/ for (ii=0; ii<nlupd; ii++) { i = update[ii]; me = where[i]; if (me < nparts && me%2 == cc) { /* This vertex is pulled into the separator */ lpwgts[me] -= vwgt[i]; where[i] = nparts+me-(me%2); sepind[nsep++] = i; /* Put the vertex into the sepind array */ if (graph->pexadj[i+1]-graph->pexadj[i] > 0) changed[nchanged++] = i; lpwgts[where[i]] += vwgt[i]; lpwgts[2*nparts-1] += vwgt[i]; /* myprintf(ctrl, "Vertex %"PRIDX" moves into the separator from %"PRIDX" to %"PRIDX"\n", i+firstvtx, me, where[i]); */ } } /* Tell everybody interested what the new where[] info is for the interface vertices */ CommChangedInterfaceData(ctrl, graph, nchanged, changed, where, swchanges, rwchanges); /*------------------------------------------------------------- / Update the rinfo of the vertices in the update[] array /-------------------------------------------------------------*/ for (ii=0; ii<nlupd; ii++) { i = update[ii]; PASSERT(ctrl, marker[i] == 1); marker[i] = 0; me = where[i]; if (me >= nparts) { /* If it is a separator vertex */ /* myprintf(ctrl, "Updating %"PRIDX" %"PRIDX"\n", i+firstvtx, me); */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; sprintf(title, "\tTotalSep [%"PRIDX"]", c); IFSET(ctrl->dbglvl, DBG_REFINEINFO, PrintNodeBalanceInfo(ctrl, nparts, gpwgts, badmaxpwgt, title)); /* break out if there is no improvement in two successive inner iterations that can span successive outer iterations */ if (graph->mincut == oldcut) { if (++nzerogainiterations == 2) break; } else { nzerogainiterations = 0; } c = cc; } /* break out if there is no improvement in two successive inner iterations that can span successive outer iterations */ if (graph->mincut == oldcut && nzerogainiterations == 2) break; } rpqDestroy(queue); WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayTmr)); } /************************************************************************************/ /*! This function performs k-way node-based refinement. The key difference between this and the previous routine is that the well-interior nodes are refined using a serial node-based refinement algortihm. */ /************************************************************************************/ void KWayNodeRefine2Phase(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, oldcut; oldcut = graph->mincut+1; for (i=0; i<npasses; i++) { KWayNodeRefine_Greedy(ctrl, graph, npasses, ubfrac); if (graph->mincut == oldcut) break; oldcut = graph->mincut; KWayNodeRefineInterior(ctrl, graph, 2, ubfrac); UpdateNodePartitionParams(ctrl, graph); if (graph->mincut == oldcut) break; oldcut = graph->mincut; } } /************************************************************************************/ /*! This function performs k-way node-based refinement of the interior nodes of the graph assigned to each processor using a serial node-refinement algorithm. */ /************************************************************************************/ void KWayNodeRefineInterior(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, j, k, ii, gnnz, gid, qsize; idx_t npes = ctrl->npes, mype = ctrl->mype, nparts = ctrl->nparts; idx_t nvtxs, *xadj, *adjncy, *vwgt, *where, *pexadj; idx_t gnvtxs, *gxadj, *gadjncy, *gvwgt, *gwhere, *ghmarker; idx_t *gmap, *gimap; idx_t *pptr, *pind; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->AuxTmr1)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayTmr)); WCOREPUSH; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vwgt = graph->vwgt; where = graph->where; pexadj = graph->pexadj; gxadj = iwspacemalloc(ctrl, nvtxs+1); gvwgt = iwspacemalloc(ctrl, nvtxs); gadjncy = iwspacemalloc(ctrl, xadj[nvtxs]); gwhere = iwspacemalloc(ctrl, nvtxs); ghmarker = iwspacemalloc(ctrl, nvtxs); gmap = iset(nvtxs, -1, iwspacemalloc(ctrl, nvtxs)); gimap = iwspacemalloc(ctrl, nvtxs); pptr = iset(2*nparts+1, 0, iwspacemalloc(ctrl, 2*nparts+1)); pind = iwspacemalloc(ctrl, nvtxs); /* Set pptr/pind to contain the vertices in each one of the partitions */ for (i=0; i<nvtxs; i++) pptr[where[i]]++; MAKECSR(i, 2*nparts, pptr); for (i=0; i<nvtxs; i++) pind[pptr[where[i]]++] = i; SHIFTCSR(i, 2*nparts, pptr); /* Extract each individual graph and refine it */ for (gid=0; gid<nparts; gid+=2) { if (graph->lpwgts[nparts+gid] == 0) continue; /* a quick test to determine if there are sufficient non-interface separator nodes */ for (qsize=0, ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++) { if (pexadj[pind[ii]] == pexadj[pind[ii]+1]) { if (++qsize >= 2) break; } } if (ii == pptr[nparts+gid+1]) break; /* no need to proceed. not enough non-interface separator nodes */ /* compute the gmap/gimap and other node info for the extracted graph */ for (gnvtxs=0, ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++, gnvtxs++) { i = pind[ii]; gmap[i] = gnvtxs; gimap[gnvtxs] = i; gvwgt[gnvtxs] = vwgt[i]; gwhere[gnvtxs] = 2; ghmarker[gnvtxs] = (pexadj[i+1]-pexadj[i] > 0 ? gwhere[gnvtxs] : -1); } for (ii=pptr[gid]; ii<pptr[gid+2]; ii++, gnvtxs++) { i = pind[ii]; gmap[i] = gnvtxs; gimap[gnvtxs] = i; gvwgt[gnvtxs] = vwgt[i]; gwhere[gnvtxs] = where[i] - gid; ghmarker[gnvtxs] = (pexadj[i+1]-pexadj[i] > 0 ? gwhere[gnvtxs] : -1); PASSERT(ctrl, gwhere[gnvtxs] >= 0 && gwhere[gnvtxs] <= 1); } gxadj[0]=0; gnvtxs=0; gnnz=0; /* go over the separator nodes */ for (ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++) { i = pind[ii]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (adjncy[j] < nvtxs) gadjncy[gnnz++] = gmap[adjncy[j]]; } gxadj[++gnvtxs] = gnnz; } /* go over the interior nodes */ for (ii=pptr[gid]; ii<pptr[gid+2]; ii++) { i = pind[ii]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (adjncy[j] < nvtxs) gadjncy[gnnz++] = gmap[adjncy[j]]; } gxadj[++gnvtxs] = gnnz; } if (gnnz == 0) continue; /* The 1.03 is here by choice as it is better to refine using tight constraints */ METIS_NodeRefine(gnvtxs, gxadj, gvwgt, gadjncy, gwhere, ghmarker, 1.03); for (i=0; i<gnvtxs; i++) { if (gwhere[i] == 2) where[gimap[i]] = nparts + gid; else where[gimap[i]] = gwhere[i] + gid; } } WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayTmr)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->AuxTmr1)); } /************************************************************************************/ /*! This function prints balance information for the parallel k-section refinement algorithm. */ /************************************************************************************/ void PrintNodeBalanceInfo(ctrl_t *ctrl, idx_t nparts, idx_t *gpwgts, idx_t *badmaxpwgt, char *title) { idx_t i; if (ctrl->mype == 0) { printf("%s: %"PRIDX", ", title, gpwgts[2*nparts-1]); for (i=0; i<nparts; i+=2) printf(" [%5"PRIDX" %5"PRIDX" %5"PRIDX" %5"PRIDX"]", gpwgts[i], gpwgts[i+1], gpwgts[nparts+i], badmaxpwgt[i]); printf("\n"); } gkMPI_Barrier(ctrl->comm); }
23,763
32.236364
117
c
null
ParMETIS-main/libparmetis/mesh.c
/* * Copyright 1997, Regents of the University of Minnesota * * mesh.c * * This file contains routines for constructing the dual graph of a mesh. * Assumes that each processor has at least one mesh element. * * Started 10/19/94 * George * * $Id: mesh.c 10575 2011-07-14 14:46:42Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function converts a mesh into a dual graph **************************************************************************/ int ParMETIS_V3_Mesh2Dual(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommon, idx_t **r_xadj, idx_t **r_adjncy, MPI_Comm *comm) { idx_t i, j, jj, k, kk, m; idx_t npes, mype, pe, count, mask, pass; idx_t nelms, lnns, my_nns, node; idx_t firstelm, firstnode, lnode, nrecv, nsend; idx_t *scounts, *rcounts, *sdispl, *rdispl; idx_t *nodedist, *nmap, *auxarray; idx_t *gnptr, *gnind, *nptr, *nind, *myxadj=NULL, *myadjncy = NULL; idx_t *sbuffer, *rbuffer, *htable; ikv_t *nodelist, *recvbuffer; idx_t maxcount, *ind, *wgt; idx_t gmaxnode, gminnode; size_t curmem; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Get basic comm info */ gkMPI_Comm_size(*comm, &npes); gkMPI_Comm_rank(*comm, &mype); nelms = elmdist[mype+1]-elmdist[mype]; if (*numflag > 0) ChangeNumberingMesh(elmdist, eptr, eind, NULL, NULL, NULL, npes, mype, 1); mask = (1<<11)-1; /*****************************/ /* Determine number of nodes */ /*****************************/ gminnode = GlobalSEMinComm(*comm, imin(eptr[nelms], eind, 1)); for (i=0; i<eptr[nelms]; i++) eind[i] -= gminnode; gmaxnode = GlobalSEMaxComm(*comm, imax(eptr[nelms], eind, 1)); /**************************/ /* Check for input errors */ /**************************/ ASSERT(nelms > 0); /* construct node distribution array */ nodedist = ismalloc(npes+1, 0, "nodedist"); for (nodedist[0]=0, i=0,j=gmaxnode+1; i<npes; i++) { k = j/(npes-i); nodedist[i+1] = nodedist[i]+k; j -= k; } my_nns = nodedist[mype+1]-nodedist[mype]; firstnode = nodedist[mype]; nodelist = ikvmalloc(eptr[nelms], "nodelist"); auxarray = imalloc(eptr[nelms], "auxarray"); htable = ismalloc(gk_max(my_nns, mask+1), -1, "htable"); scounts = imalloc(npes, "scounts"); rcounts = imalloc(npes, "rcounts"); sdispl = imalloc(npes+1, "sdispl"); rdispl = imalloc(npes+1, "rdispl"); /*********************************************/ /* first find a local numbering of the nodes */ /*********************************************/ for (i=0; i<nelms; i++) { for (j=eptr[i]; j<eptr[i+1]; j++) { nodelist[j].key = eind[j]; nodelist[j].val = j; auxarray[j] = i; /* remember the local element ID that uses this node */ } } ikvsorti(eptr[nelms], nodelist); for (count=1, i=1; i<eptr[nelms]; i++) { if (nodelist[i].key > nodelist[i-1].key) count++; } lnns = count; nmap = imalloc(lnns, "nmap"); /* renumber the nodes of the elements array */ count = 1; nmap[0] = nodelist[0].key; eind[nodelist[0].val] = 0; nodelist[0].val = auxarray[nodelist[0].val]; /* Store the local element ID */ for (i=1; i<eptr[nelms]; i++) { if (nodelist[i].key > nodelist[i-1].key) { nmap[count] = nodelist[i].key; count++; } eind[nodelist[i].val] = count-1; nodelist[i].val = auxarray[nodelist[i].val]; /* Store the local element ID */ } gkMPI_Barrier(*comm); /**********************************************************/ /* perform comms necessary to construct node-element list */ /**********************************************************/ iset(npes, 0, scounts); for (pe=i=0; i<eptr[nelms]; i++) { while (nodelist[i].key >= nodedist[pe+1]) pe++; scounts[pe] += 2; } ASSERT(pe < npes); gkMPI_Alltoall((void *)scounts, 1, IDX_T, (void *)rcounts, 1, IDX_T, *comm); icopy(npes, scounts, sdispl); MAKECSR(i, npes, sdispl); icopy(npes, rcounts, rdispl); MAKECSR(i, npes, rdispl); ASSERT(sdispl[npes] == eptr[nelms]*2); nrecv = rdispl[npes]/2; recvbuffer = ikvmalloc(gk_max(1, nrecv), "recvbuffer"); gkMPI_Alltoallv((void *)nodelist, scounts, sdispl, IDX_T, (void *)recvbuffer, rcounts, rdispl, IDX_T, *comm); /**************************************/ /* construct global node-element list */ /**************************************/ gnptr = ismalloc(my_nns+1, 0, "gnptr"); for (i=0; i<npes; i++) { for (j=rdispl[i]/2; j<rdispl[i+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; ASSERT(lnode >= 0 && lnode < my_nns) gnptr[lnode]++; } } MAKECSR(i, my_nns, gnptr); gnind = imalloc(gk_max(1, gnptr[my_nns]), "gnind"); for (pe=0; pe<npes; pe++) { firstelm = elmdist[pe]; for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; gnind[gnptr[lnode]++] = recvbuffer[j].val+firstelm; } } SHIFTCSR(i, my_nns, gnptr); /*********************************************************/ /* send the node-element info to the relevant processors */ /*********************************************************/ iset(npes, 0, scounts); /* use a hash table to ensure that each node is sent to a proc only once */ for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; if (htable[lnode] == -1) { scounts[pe] += gnptr[lnode+1]-gnptr[lnode]; htable[lnode] = 1; } } /* now reset the hash table */ for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; htable[lnode] = -1; } } gkMPI_Alltoall((void *)scounts, 1, IDX_T, (void *)rcounts, 1, IDX_T, *comm); icopy(npes, scounts, sdispl); MAKECSR(i, npes, sdispl); /* create the send buffer */ nsend = sdispl[npes]; sbuffer = imalloc(gk_max(1, nsend), "sbuffer"); count = 0; for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; if (htable[lnode] == -1) { for (k=gnptr[lnode]; k<gnptr[lnode+1]; k++) { if (k == gnptr[lnode]) sbuffer[count++] = -1*(gnind[k]+1); else sbuffer[count++] = gnind[k]; } htable[lnode] = 1; } } ASSERT(count == sdispl[pe+1]); /* now reset the hash table */ for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; htable[lnode] = -1; } } icopy(npes, rcounts, rdispl); MAKECSR(i, npes, rdispl); nrecv = rdispl[npes]; rbuffer = imalloc(gk_max(1, nrecv), "rbuffer"); gkMPI_Alltoallv((void *)sbuffer, scounts, sdispl, IDX_T, (void *)rbuffer, rcounts, rdispl, IDX_T, *comm); k = -1; nptr = ismalloc(lnns+1, 0, "nptr"); nind = rbuffer; for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]; j<rdispl[pe+1]; j++) { if (nind[j] < 0) { k++; nind[j] = (-1*nind[j])-1; } nptr[k]++; } } MAKECSR(i, lnns, nptr); ASSERT(k+1 == lnns); ASSERT(nptr[lnns] == nrecv) myxadj = *r_xadj = (idx_t *)malloc(sizeof(idx_t)*(nelms+1)); if (myxadj == NULL) gk_errexit(SIGMEM, "Failed to allocate memory for the dual graph's xadj array.\n"); iset(nelms+1, 0, myxadj); iset(mask+1, -1, htable); firstelm = elmdist[mype]; /* Two passes -- in first pass, simply find out the memory requirements */ maxcount = 200; ind = imalloc(maxcount, "ParMETIS_V3_Mesh2Dual: ind"); wgt = imalloc(maxcount, "ParMETIS_V3_Mesh2Dual: wgt"); for (pass=0; pass<2; pass++) { for (i=0; i<nelms; i++) { for (count=0, j=eptr[i]; j<eptr[i+1]; j++) { node = eind[j]; for (k=nptr[node]; k<nptr[node+1]; k++) { if ((kk=nind[k]) == firstelm+i) continue; m = htable[(kk&mask)]; if (m == -1) { ind[count] = kk; wgt[count] = 1; htable[(kk&mask)] = count++; } else { if (ind[m] == kk) { wgt[m]++; } else { for (jj=0; jj<count; jj++) { if (ind[jj] == kk) { wgt[jj]++; break; } } if (jj == count) { ind[count] = kk; wgt[count++] = 1; } } } /* Adjust the memory. This will be replaced by a idxrealloc() when GKlib will be incorporated */ if (count == maxcount-1) { maxcount *= 2; ind = irealloc(ind, maxcount, "ParMETIS_V3_Mesh2Dual: ind"); wgt = irealloc(wgt, maxcount, "ParMETIS_V3_Mesh2Dual: wgt"); } } } for (j=0; j<count; j++) { htable[(ind[j]&mask)] = -1; if (wgt[j] >= *ncommon) { if (pass == 0) myxadj[i]++; else myadjncy[myxadj[i]++] = ind[j]; } } } if (pass == 0) { MAKECSR(i, nelms, myxadj); myadjncy = *r_adjncy = (idx_t *)malloc(sizeof(idx_t)*myxadj[nelms]); if (myadjncy == NULL) gk_errexit(SIGMEM, "Failed to allocate memory for dual graph's adjncy array.\n"); } else { SHIFTCSR(i, nelms, myxadj); } } /*****************************************/ /* correctly renumber the elements array */ /*****************************************/ for (i=0; i<eptr[nelms]; i++) eind[i] = nmap[eind[i]] + gminnode; if (*numflag == 1) ChangeNumberingMesh(elmdist, eptr, eind, myxadj, myadjncy, NULL, npes, mype, 0); /* do not free nodelist, recvbuffer, rbuffer */ gk_free((void **)&nodedist, &nodelist, &auxarray, &htable, &scounts, &rcounts, &sdispl, &rdispl, &nmap, &recvbuffer, &gnptr, &gnind, &sbuffer, &rbuffer, &nptr, &ind, &wgt, LTERM); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return METIS_OK; }
10,199
27.333333
89
c
null
ParMETIS-main/libparmetis/initmsection.c
/* * Copyright 1997, Regents of the University of Minnesota * * initmsection.c * * This file contains code that performs the k-way multisection * * Started 6/3/97 * George * * $Id: initmsection.c 10361 2011-06-21 19:16:22Z karypis $ */ #include <parmetislib.h> #define DEBUG_IPART_ /************************************************************************************/ /*! The entry point of the algorithm that finds the separators of the coarsest graph. This algorithm first assembles the graph to all the processors, it then splits the processors into groups depending on the number of partitions for which we want to compute the separator. The processors of each group compute the separator of their corresponding graph and the smallest separator is selected. The parameter nparts on calling this routine indicates the number of desired partitions after the multisection (excluding the nodes that end up on the separator). The initial bisection is achieved when nparts==2 and upon entry graph->where[] = 0 for all vertices. Similarly, if nparts==4, it indicates that we have a graph that is already partitioned into two parts (as specified in graph->where) and we need to find the separator of each one of these parts. The final partitioning is encoded in the graph->where vector as follows. If nparts is the number of partitions, the left, right, and separator subpartitions of the original partition i will be labeled 2*i, 2*i+1, and nparts+2*i, respectively. Note that in the above expressions, i goes from [0...nparts/2]. As a result of this encoding, the left (i.e., 0th) partition of a node \c i on the separator will be given by where[i]%nparts. */ /************************************************************************************/ void InitMultisection(ctrl_t *ctrl, graph_t *graph) { idx_t i, myrank, mypart, options[METIS_NOPTIONS]; idx_t *vtxdist, *gwhere = NULL, *part, *label; graph_t *agraph; idx_t *sendcounts, *displs; MPI_Comm newcomm, labelcomm; struct { double cut; int rank; } lpecut, gpecut; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->InitPartTmr)); WCOREPUSH; /* Assemble the graph and do the necessary pre-processing */ agraph = AssembleMultisectedGraph(ctrl, graph); part = agraph->where; agraph->where = NULL; /* Split the processors into groups so that each one can do a bisection */ mypart = ctrl->mype%(ctrl->nparts/2); gkMPI_Comm_split(ctrl->comm, mypart, 0, &newcomm); gkMPI_Comm_rank(newcomm, &myrank); /* Each processor keeps the graph that it only needs and bisects it */ KeepPart(ctrl, agraph, part, mypart); label = agraph->label; /* Save this because ipart may need it */ agraph->label = NULL; /* Bisect the graph and construct the separator */ METIS_SetDefaultOptions(options); options[METIS_OPTION_SEED] = (ctrl->mype+8)*101; options[METIS_OPTION_NSEPS] = 5; options[METIS_OPTION_UFACTOR] = (idx_t)(1000.0*(ctrl->ubfrac - 1.0)); WCOREPUSH; /* for freeing agraph->where and gwhere */ agraph->where = iwspacemalloc(ctrl, agraph->nvtxs); METIS_ComputeVertexSeparator(&agraph->nvtxs, agraph->xadj, agraph->adjncy, agraph->vwgt, options, &agraph->mincut, agraph->where); for (i=0; i<agraph->nvtxs; i++) { PASSERT(ctrl, agraph->where[i]>=0 && agraph->where[i]<=2); if (agraph->where[i] == 2) agraph->where[i] = ctrl->nparts+2*mypart; else agraph->where[i] += 2*mypart; } /* Determine which PE got the minimum cut */ lpecut.cut = agraph->mincut; lpecut.rank = myrank; gkMPI_Allreduce(&lpecut, &gpecut, 1, MPI_DOUBLE_INT, MPI_MINLOC, newcomm); /* myprintf(ctrl, "Nvtxs: %"PRIDX", Mincut: %"PRIDX", GMincut: %"PRIDX", %"PRIDX"\n", agraph->nvtxs, agraph->mincut, (idx_t)gpecut.cut, (idx_t)gpecut.rank); */ /* Send the best where to the root processor of this partition */ if (myrank != 0 && myrank == gpecut.rank) gkMPI_Send((void *)agraph->where, agraph->nvtxs, IDX_T, 0, 1, newcomm); if (myrank == 0 && myrank != gpecut.rank) gkMPI_Recv((void *)agraph->where, agraph->nvtxs, IDX_T, gpecut.rank, 1, newcomm, &ctrl->status); /* Create a communicator that stores all the i-th processors of the newcomm */ gkMPI_Comm_split(ctrl->comm, myrank, 0, &labelcomm); /* Map the separator back to agraph. This is inefficient! */ if (myrank == 0) { gwhere = iset(graph->gnvtxs, 0, iwspacemalloc(ctrl, graph->gnvtxs)); for (i=0; i<agraph->nvtxs; i++) gwhere[label[i]] = agraph->where[i]; gkMPI_Reduce((void *)gwhere, (void *)part, graph->gnvtxs, IDX_T, MPI_SUM, 0, labelcomm); } WCOREPOP; /* free agraph->where & gwhere */ agraph->where = part; /* The minimum PE performs the Scatter */ vtxdist = graph->vtxdist; PASSERT(ctrl, graph->where != NULL); gk_free((void **)&graph->where, LTERM); /* Remove the propagated down where info */ graph->where = imalloc(graph->nvtxs+graph->nrecv, "InitPartition: where"); sendcounts = iwspacemalloc(ctrl, ctrl->npes); displs = iwspacemalloc(ctrl, ctrl->npes); for (i=0; i<ctrl->npes; i++) { sendcounts[i] = vtxdist[i+1]-vtxdist[i]; displs[i] = vtxdist[i]; } gkMPI_Scatterv((void *)agraph->where, sendcounts, displs, IDX_T, (void *)graph->where, graph->nvtxs, IDX_T, 0, ctrl->comm); agraph->label = label; FreeGraph(agraph); gkMPI_Comm_free(&newcomm); gkMPI_Comm_free(&labelcomm); WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->InitPartTmr)); } /*************************************************************************/ /*! This function assembles the graph into a single processor */ /*************************************************************************/ graph_t *AssembleMultisectedGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, k, l, gnvtxs, nvtxs, gnedges, nedges, gsize; idx_t *xadj, *vwgt, *where, *adjncy, *adjwgt, *vtxdist, *imap; idx_t *axadj, *aadjncy, *aadjwgt, *avwgt, *awhere, *alabel; idx_t *mygraph, *ggraph; idx_t *recvcounts, *displs, mysize; graph_t *agraph; WCOREPUSH; gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; nedges = graph->xadj[nvtxs]; xadj = graph->xadj; vwgt = graph->vwgt; where = graph->where; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vtxdist = graph->vtxdist; imap = graph->imap; /* Determine the # of idx_t to receive from each processor */ recvcounts = iwspacemalloc(ctrl, ctrl->npes); mysize = 3*nvtxs + 2*nedges; gkMPI_Allgather((void *)(&mysize), 1, IDX_T, (void *)recvcounts, 1, IDX_T, ctrl->comm); displs = iwspacemalloc(ctrl, ctrl->npes+1); for (displs[0]=0, i=1; i<ctrl->npes+1; i++) displs[i] = displs[i-1] + recvcounts[i-1]; /* allocate memory for the recv buffer of the assembled graph */ gsize = displs[ctrl->npes]; ggraph = iwspacemalloc(ctrl, gsize); /* Construct the one-array storage format of the assembled graph */ WCOREPUSH; /* for freeing mygraph */ mygraph = iwspacemalloc(ctrl, mysize); for (k=i=0; i<nvtxs; i++) { mygraph[k++] = xadj[i+1]-xadj[i]; mygraph[k++] = vwgt[i]; mygraph[k++] = where[i]; for (j=xadj[i]; j<xadj[i+1]; j++) { mygraph[k++] = imap[adjncy[j]]; mygraph[k++] = adjwgt[j]; } } PASSERT(ctrl, mysize == k); /* Assemble the entire graph */ gkMPI_Allgatherv((void *)mygraph, mysize, IDX_T, (void *)ggraph, recvcounts, displs, IDX_T, ctrl->comm); WCOREPOP; /* free mygraph */ agraph = CreateGraph(); agraph->nvtxs = gnvtxs; agraph->ncon = 1; agraph->nedges = gnedges = (gsize-3*gnvtxs)/2; /* Allocate memory for the assembled graph */ axadj = agraph->xadj = imalloc(gnvtxs+1, "AssembleGraph: axadj"); avwgt = agraph->vwgt = imalloc(gnvtxs, "AssembleGraph: avwgt"); awhere = agraph->where = imalloc(gnvtxs, "AssembleGraph: awhere"); aadjncy = agraph->adjncy = imalloc(gnedges, "AssembleGraph: adjncy"); aadjwgt = agraph->adjwgt = imalloc(gnedges, "AssembleGraph: adjwgt"); alabel = agraph->label = imalloc(gnvtxs, "AssembleGraph: alabel"); for (k=j=i=0; i<gnvtxs; i++) { axadj[i] = ggraph[k++]; avwgt[i] = ggraph[k++]; awhere[i] = ggraph[k++]; for (l=0; l<axadj[i]; l++) { aadjncy[j] = ggraph[k++]; aadjwgt[j] = ggraph[k++]; j++; } } /* Now fix up the received graph */ MAKECSR(i, gnvtxs, axadj); iincset(gnvtxs, 0, alabel); WCOREPOP; return agraph; }
8,484
33.076305
103
c
null
ParMETIS-main/programs/ptest.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: ptest.c,v 1.3 2003/07/22 21:47:20 karypis Exp $ * */ #include <parmetisbin.h> #define NCON 5 /*************************************************************************/ /*! Entry point of the testing routine */ /*************************************************************************/ int main(int argc, char *argv[]) { idx_t mype, npes; MPI_Comm comm; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 2 && argc != 3) { if (mype == 0) printf("Usage: %s <graph-file> [coord-file]\n", argv[0]); MPI_Finalize(); exit(0); } TestParMetis_GPart(argv[1], (argc == 3 ? argv[2] : NULL), comm); gkMPI_Comm_free(&comm); MPI_Finalize(); return 0; } /***********************************************************************************/ /*! This function tests the various graph partitioning and ordering routines */ /***********************************************************************************/ void TestParMetis_GPart(char *filename, char *xyzfile, MPI_Comm comm) { idx_t ncon, nparts, npes, mype, opt2, realcut; graph_t graph, mgraph; idx_t *part, *mpart, *savepart, *order, *sizes; idx_t numflag=0, wgtflag=0, options[10], edgecut, ndims; real_t ipc2redist, *xyz=NULL, *tpwgts = NULL, ubvec[MAXNCON]; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); ParallelReadGraph(&graph, filename, comm); if (xyzfile) xyz = ReadTestCoordinates(&graph, xyzfile, &ndims, comm); gkMPI_Barrier(comm); part = imalloc(graph.nvtxs, "TestParMetis_V3: part"); tpwgts = rmalloc(MAXNCON*npes*2, "TestParMetis_V3: tpwgts"); rset(MAXNCON, 1.05, ubvec); graph.vwgt = ismalloc(graph.nvtxs*5, 1, "TestParMetis_GPart: vwgt"); /*====================================================================== / ParMETIS_V3_PartKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; wgtflag = 2; numflag = 0; edgecut = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=NCON; ncon++) { if (ncon > 1 && nparts > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); if (mype == 0) printf("\nTesting ParMETIS_V3_PartKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) { printf("ParMETIS_V3_PartKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } if (mype == 0) printf("\nTesting ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); options[3] = PARMETIS_PSR_UNCOUPLED; ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) { printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } /*====================================================================== / ParMETIS_V3_PartGeomKway /=======================================================================*/ if (xyzfile != NULL) { options[0] = 1; options[1] = 3; options[2] = 1; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=NCON; ncon++) { if (ncon > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeomKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ndims, xyz, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) printf("ParMETIS_V3_PartGeomKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } /*====================================================================== / ParMETIS_V3_PartGeom /=======================================================================*/ if (xyz != NULL) { wgtflag = 0; numflag = 0; if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeom\n"); ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) printf("ParMETIS_V3_PartGeom reported a cut of %"PRIDX"\n", realcut); } /*====================================================================== / Coupled ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting coupled ParMETIS_V3_RefineKway with default options (before move)\n"); ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); /* Compute a good partition and move the graph. Do so quietly! */ options[0] = 0; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &npes, tpwgts, ubvec, options, &edgecut, part, &comm); TestMoveGraph(&graph, &mgraph, part, comm); gk_free((void **)&(graph.vwgt), LTERM); mpart = ismalloc(mgraph.nvtxs, mype, "TestParMetis_V3: mpart"); savepart = imalloc(mgraph.nvtxs, "TestParMetis_V3: savepart"); /*====================================================================== / Coupled ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; nparts = npes; wgtflag = 0; numflag = 0; for (ncon=1; ncon<=NCON; ncon++) { if (mype == 0) printf("\nTesting coupled ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_RefineKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, mpart, &comm); realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, filename, comm); if (mype == 0) printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } /*ADAPTIVE:*/ /*====================================================================== / ParMETIS_V3_AdaptiveRepart /=======================================================================*/ mgraph.vwgt = ismalloc(mgraph.nvtxs*NCON, 1, "TestParMetis_V3: mgraph.vwgt"); mgraph.vsize = ismalloc(mgraph.nvtxs, 1, "TestParMetis_V3: mgraph.vsize"); AdaptGraph(&mgraph, 4, comm); options[0] = 1; options[1] = 7; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2; nparts = nparts/2) { options[0] = 0; ncon = 1; wgtflag = 0; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, savepart, &comm); options[0] = 1; wgtflag = 2; for (ncon=1; ncon<=NCON; ncon++) { rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (ncon > 1) Mc_AdaptGraph(&mgraph, savepart, ncon, nparts, comm); else AdaptGraph(&mgraph, 4, comm); for (ipc2redist=1000.0; ipc2redist>=0.001; ipc2redist/=1000.0) { icopy(mgraph.nvtxs, savepart, mpart); if (mype == 0) printf("\nTesting ParMETIS_V3_AdaptiveRepart with ipc2redist: %.3"PRREAL", ncon: %"PRIDX", nparts: %"PRIDX"\n", ipc2redist, ncon, nparts); ParMETIS_V3_AdaptiveRepart(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, mgraph.vwgt, mgraph.vsize, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, &ipc2redist, options, &edgecut, mpart, &comm); realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, filename, comm); if (mype == 0) printf("ParMETIS_V3_AdaptiveRepart reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } gk_free((void **)&tpwgts, &part, &mpart, &savepart, &xyz, &mgraph.vwgt, &mgraph.vsize, LTERM); } /******************************************************************************/ /*! This function takes a partition vector that is distributed and reads in the original graph and computes the edgecut */ /******************************************************************************/ idx_t ComputeRealCut(idx_t *vtxdist, idx_t *part, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype != 0) { gkMPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); for (i=1; i<npes; i++) gkMPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gpart[i] != gpart[adjncy[j]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &xadj, &adjncy, LTERM); return cut; } return 0; } /******************************************************************************/ /*! This function takes a partition vector of the original graph and that of the moved graph and computes the cut of the original graph based on the moved graph */ /*******************************************************************************/ idx_t ComputeRealCutFromMoved(idx_t *vtxdist, idx_t *mvtxdist, idx_t *part, idx_t *mpart, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart, *gmpart, *perm, *sizes; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype != 0) { gkMPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); gkMPI_Send((void *)mpart, mvtxdist[mype+1]-mvtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); gmpart = imalloc(mvtxdist[npes], "ComputeRealCut: gmpart"); icopy(mvtxdist[1], mpart, gmpart); for (i=1; i<npes; i++) { gkMPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); gkMPI_Recv((void *)(gmpart+mvtxdist[i]), mvtxdist[i+1]-mvtxdist[i], IDX_T, i, 1, comm, &status); } /* OK, now go and reconstruct the permutation to go from the graph to mgraph */ perm = imalloc(vtxdist[npes], "ComputeRealCut: perm"); sizes = ismalloc(npes+1, 0, "ComputeRealCut: sizes"); for (i=0; i<vtxdist[npes]; i++) sizes[gpart[i]]++; MAKECSR(i, npes, sizes); for (i=0; i<vtxdist[npes]; i++) perm[i] = sizes[gpart[i]]++; /* Ok, now read the graph from the file */ ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gmpart[perm[i]] != gmpart[perm[adjncy[j]]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &gmpart, &perm, &sizes, &xadj, &adjncy, LTERM); return cut; } return 0; } /****************************************************************************** * This function takes a graph and its partition vector and creates a new * graph corresponding to the one after the movement *******************************************************************************/ void TestMoveGraph(graph_t *ograph, graph_t *omgraph, idx_t *part, MPI_Comm comm) { idx_t npes, mype; ctrl_t *ctrl; graph_t *graph, *mgraph; idx_t options[5] = {0, 0, 1, 0, 0}; gkMPI_Comm_size(comm, &npes); ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, npes, NULL, NULL, comm); mype = ctrl->mype; ctrl->CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ graph = TestSetUpGraph(ctrl, ograph->vtxdist, ograph->xadj, NULL, ograph->adjncy, NULL, 0); AllocateWSpace(ctrl, 0); CommSetup(ctrl, graph); graph->where = part; graph->ncon = 1; mgraph = MoveGraph(ctrl, graph); omgraph->gnvtxs = mgraph->gnvtxs; omgraph->nvtxs = mgraph->nvtxs; omgraph->nedges = mgraph->nedges; omgraph->vtxdist = mgraph->vtxdist; omgraph->xadj = mgraph->xadj; omgraph->adjncy = mgraph->adjncy; mgraph->vtxdist = NULL; mgraph->xadj = NULL; mgraph->adjncy = NULL; FreeGraph(mgraph); graph->where = NULL; FreeInitialGraphAndRemap(graph); FreeCtrl(&ctrl); } /***************************************************************************** * This function sets up a graph data structure for partitioning *****************************************************************************/ graph_t *TestSetUpGraph(ctrl_t *ctrl, idx_t *vtxdist, idx_t *xadj, idx_t *vwgt, idx_t *adjncy, idx_t *adjwgt, idx_t wgtflag) { return SetupGraph(ctrl, 1, vtxdist, xadj, vwgt, NULL, adjncy, adjwgt, wgtflag); }
15,095
31.746204
122
c
null
ParMETIS-main/programs/proto.h
/* * Copyright 1997, Regents of the University of Minnesota * * proto.h * * This file contains header files * * Started 10/19/95 * George * * $Id: proto.h 10076 2011-06-03 15:36:39Z karypis $ * */ /* pio.c */ void ParallelReadGraph(graph_t *, char *, MPI_Comm); void Mc_ParallelWriteGraph(ctrl_t *, graph_t *, char *, idx_t, idx_t); void ReadTestGraph(graph_t *, char *, MPI_Comm); real_t *ReadTestCoordinates(graph_t *, char *, idx_t *, MPI_Comm); void ReadMetisGraph(char *, idx_t *, idx_t **, idx_t **); void Mc_SerialReadGraph(graph_t *, char *, idx_t *, MPI_Comm); void Mc_SerialReadMetisGraph(char *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t **, idx_t **, idx_t **, idx_t **, idx_t *); void WritePVector(char *gname, idx_t *vtxdist, idx_t *part, MPI_Comm comm); void WriteOVector(char *gname, idx_t *vtxdist, idx_t *order, MPI_Comm comm); /* adaptgraph */ void AdaptGraph(graph_t *, idx_t, MPI_Comm); void AdaptGraph2(graph_t *, idx_t, MPI_Comm); void Mc_AdaptGraph(graph_t *, idx_t *, idx_t, idx_t, MPI_Comm); /* ptest.c */ void TestParMetis_GPart(char *filename, char *xyzfile, MPI_Comm comm); idx_t ComputeRealCut(idx_t *, idx_t *, char *, MPI_Comm); idx_t ComputeRealCutFromMoved(idx_t *, idx_t *, idx_t *, idx_t *, char *, MPI_Comm); void TestMoveGraph(graph_t *, graph_t *, idx_t *, MPI_Comm); graph_t *TestSetUpGraph(ctrl_t *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t); /* mienio.c */ void mienIO(mesh_t *, char *, idx_t, idx_t, MPI_Comm); /* meshio.c */ void ParallelReadMesh(mesh_t *, char *, MPI_Comm);
1,553
30.714286
122
h
null
ParMETIS-main/programs/pometis.c
/* * Copyright 1997, Regents of the University of Minnesota * * pometis.c * * This is the entry point of the ILUT * * Started 10/19/95 * George * * $Id: parmetis.c,v 1.5 2003/07/30 21:18:54 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * Let the game begin **************************************************************************/ int main(int argc, char *argv[]) { idx_t i, j, npes, mype, optype, nparts, adptf, options[10]; idx_t *order, *sizes; graph_t graph; MPI_Comm comm; idx_t numflag=0, wgtflag=0, ndims=3, edgecut; idx_t mtype, rtype, p_nseps, s_nseps, seed, dbglvl; real_t ubfrac; size_t opc; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 10) { if (mype == 0) { printf("Usage: %s <graph-file> <op-type> <seed> <dbglvl> <mtype> <rtype> <p_nseps> <s_nseps> <ubfrac>\n", argv[0]); printf(" op-type: 1=ParNodeND_V3, 2=ParNodeND_V32, 3=SerNodeND\n"); printf(" mtype: %"PRIDX"=LOCAL, %"PRIDX"=GLOBAL\n", (idx_t)PARMETIS_MTYPE_LOCAL, (idx_t)PARMETIS_MTYPE_GLOBAL); printf(" rtype: %"PRIDX"=GREEDY, %"PRIDX"=2PHASE\n", (idx_t)PARMETIS_SRTYPE_GREEDY, (idx_t)PARMETIS_SRTYPE_2PHASE); } MPI_Finalize(); exit(0); } optype = atoi(argv[2]); if (mype == 0) printf("reading file: %s\n", argv[1]); ParallelReadGraph(&graph, argv[1], comm); if (mype == 0) printf("done\n"); order = ismalloc(graph.nvtxs, mype, "main: order"); sizes = imalloc(2*npes, "main: sizes"); switch (optype) { case 1: options[0] = 1; options[PMV3_OPTION_SEED] = atoi(argv[3]); options[PMV3_OPTION_DBGLVL] = atoi(argv[4]); ParMETIS_V3_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, order, sizes, &comm); break; case 2: seed = atoi(argv[3]); dbglvl = atoi(argv[4]); mtype = atoi(argv[5]); rtype = atoi(argv[6]); p_nseps = atoi(argv[7]); s_nseps = atoi(argv[8]); ubfrac = atof(argv[9]); ParMETIS_V32_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, &numflag, &mtype, &rtype, &p_nseps, &s_nseps, &ubfrac, &seed, &dbglvl, order, sizes, &comm); break; case 3: options[0] = 0; ParMETIS_SerialNodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, order, sizes, &comm); break; default: if (mype == 0) printf("Uknown optype of %"PRIDX"\n", optype); MPI_Finalize(); exit(0); } WriteOVector(argv[1], graph.vtxdist, order, comm); /* print the partition sizes and the separators */ if (mype == 0) { opc = 0; nparts = 1<<log2Int(npes); for (i=0; i<2*nparts-1; i++) { printf(" %6"PRIDX"", sizes[i]); if (i >= nparts) opc += sizes[i]*(sizes[i]+1)/2; } printf("\nTopSep OPC: %zu\n", opc); } gk_free((void **)&order, &sizes, &graph.vtxdist, &graph.xadj, &graph.adjncy, &graph.vwgt, &graph.adjwgt, LTERM); MPI_Comm_free(&comm); MPI_Finalize(); return 0; }
3,225
26.338983
121
c
null
ParMETIS-main/programs/mtest.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: mtest.c,v 1.3 2003/07/25 14:31:47 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * Let the game begin **************************************************************************/ int main(int argc, char *argv[]) { idx_t i, mype, npes, nelms; idx_t *part, *eptr; mesh_t mesh; MPI_Comm comm; idx_t wgtflag, numflag, edgecut, nparts, options[10]; idx_t mgcnum = -1, mgcnums[5] = {-1, 2, 3, 4, 2}, esizes[5] = {-1, 3, 4, 8, 4}; real_t *tpwgts, ubvec[MAXNCON]; gk_malloc_init(); MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc < 2) { if (mype == 0) printf("Usage: %s <mesh-file> [NCommonNodes]\n", argv[0]); MPI_Finalize(); exit(0); } ParallelReadMesh(&mesh, argv[1], comm); mgcnum = mgcnums[mesh.etype]; mesh.ncon = 1; if (argc > 2) mgcnum = atoi(argv[2]); if (mype == 0) printf("MGCNUM: %"PRIDX"\n", mgcnum); nparts = npes; tpwgts = rmalloc(nparts*mesh.ncon, "tpwgts"); for (i=0; i<nparts*mesh.ncon; i++) tpwgts[i] = 1.0/(real_t)(nparts); for (i=0; i<mesh.ncon; i++) ubvec[i] = UNBALANCE_FRACTION; part = imalloc(mesh.nelms, "part"); numflag = wgtflag = 0; options[0] = 1; options[PMV3_OPTION_DBGLVL] = 7; options[PMV3_OPTION_SEED] = 0; nelms = mesh.elmdist[mype+1]-mesh.elmdist[mype]; eptr = ismalloc(nelms+1, esizes[mesh.etype], "main; eptr"); MAKECSR(i, nelms, eptr); eptr[nelms]--; /* make the last element different */ ParMETIS_V3_PartMeshKway(mesh.elmdist, eptr, mesh.elements, NULL, &wgtflag, &numflag, &(mesh.ncon), &mgcnum, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); /* graph = ParallelMesh2Dual(&mesh, mgcnum, comm); MPI_Barrier(comm); MPI_Allreduce((void *)&(graph->nedges), (void *)&gnedges, 1, IDX_T, MPI_SUM, comm); if (mype == 0) printf("Completed Dual Graph -- Nvtxs: %"PRIDX", Nedges: %"PRIDX"\n", graph->gnvtxs, gnedges/2); numflag = wgtflag = 0; ParMETIS_V3_PartKway(graph->vtxdist, graph->xadj, graph->adjncy, NULL, NULL, &wgtflag, &numflag, &(graph->ncon), &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); gk_free((void **)&(graph.vtxdist), &(graph.xadj), &(graph.vwgt), &(graph.adjncy), &(graph.adjwgt), LTERM); */ gk_free((void **)&part, &tpwgts, &eptr, LTERM); MPI_Comm_free(&comm); MPI_Finalize(); gk_malloc_cleanup(0); return 0; }
2,701
25.752475
108
c
null
ParMETIS-main/include/parmetis.h
/* * Copyright 1997-2003, Regents of the University of Minnesota * * parmetis.h * * This file contains function prototypes and constrant definitions for * ParMETIS * * Started 7/21/03 * George * */ #ifndef __parmetis_h__ #define __parmetis_h__ #include <mpi.h> #include <metis.h> #ifndef _MSC_VER #define __cdecl #endif #if IDXTYPEWIDTH == 32 /*#define IDX_T MPI_INT32_T */ #define IDX_T MPI_INT #define KEEP_BIT 0x40000000L #elif IDXTYPEWIDTH == 64 /*#define IDX_T MPI_INT64_T */ #define IDX_T MPI_LONG_LONG_INT #define KEEP_BIT 0x4000000000000000LL #else #error "Incorrect user-supplied value fo IDXTYPEWIDTH" #endif #if REALTYPEWIDTH == 32 #define REAL_T MPI_FLOAT #elif REALTYPEWIDTH == 64 #define REAL_T MPI_DOUBLE #else #error "Incorrect user-supplied value fo REALTYPEWIDTH" #endif /************************************************************************* * Constants **************************************************************************/ #define PARMETIS_MAJOR_VERSION 4 #define PARMETIS_MINOR_VERSION 0 #define PARMETIS_SUBMINOR_VERSION 3 /************************************************************************* * Function prototypes **************************************************************************/ #ifdef __cplusplus extern "C" { #endif /*------------------------------------------------------------------- * API Introduced with Release 3.0 (current API) *--------------------------------------------------------------------*/ int __cdecl ParMETIS_V3_PartKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartGeomKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartGeom( idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_RefineKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_AdaptiveRepart( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_Mesh2Dual( idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommonnodes, idx_t **xadj, idx_t **adjncy, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartMeshKway( idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommonnodes, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_NodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm); int __cdecl ParMETIS_V32_NodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *numflag, idx_t *mtype, idx_t *rtype, idx_t *p_nseps, idx_t *s_nseps, real_t *ubfrac, idx_t *seed, idx_t *dbglvl, idx_t *order, idx_t *sizes, MPI_Comm *comm); int __cdecl ParMETIS_SerialNodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm); #ifdef __cplusplus } #endif /*------------------------------------------------------------------------ * Enum type definitions *-------------------------------------------------------------------------*/ /*! Operation type codes */ typedef enum { PARMETIS_OP_KMETIS, PARMETIS_OP_GKMETIS, PARMETIS_OP_GMETIS, PARMETIS_OP_RMETIS, PARMETIS_OP_AMETIS, PARMETIS_OP_OMETIS, PARMETIS_OP_M2DUAL, PARMETIS_OP_MKMETIS } pmoptype_et; /************************************************************************* * Various constants used for the different parameters **************************************************************************/ /* Matching types */ #define PARMETIS_MTYPE_LOCAL 1 /* Restrict matching to within processor vertices */ #define PARMETIS_MTYPE_GLOBAL 2 /* Remote vertices can be matched */ /* Separator refinement types */ #define PARMETIS_SRTYPE_GREEDY 1 /* Vertices are visted from highest to lowest gain */ #define PARMETIS_SRTYPE_2PHASE 2 /* Separators are refined in a two-phase fashion using PARMETIS_SRTYPE_GREEDY for the 2nd phase */ /* Coupling types for ParMETIS_V3_RefineKway & ParMETIS_V3_AdaptiveRepart */ #define PARMETIS_PSR_COUPLED 1 /* # of partitions == # of processors */ #define PARMETIS_PSR_UNCOUPLED 2 /* # of partitions != # of processors */ /* Debug levels (fields should be ORed) */ #define PARMETIS_DBGLVL_TIME 1 /* Perform timing analysis */ #define PARMETIS_DBGLVL_INFO 2 /* Perform timing analysis */ #define PARMETIS_DBGLVL_PROGRESS 4 /* Show the coarsening progress */ #define PARMETIS_DBGLVL_REFINEINFO 8 /* Show info on communication during folding */ #define PARMETIS_DBGLVL_MATCHINFO 16 /* Show info on matching */ #define PARMETIS_DBGLVL_RMOVEINFO 32 /* Show info on communication during folding */ #define PARMETIS_DBGLVL_REMAP 64 /* Determines if remapping will take place */ #define PARMETIS_DBGLVL_TWOHOP 128 /* Performs a 2-hop matching */ #define PARMETIS_DBGLVL_DROPEDGES 256 /* Drop edges during coarsening */ #define PARMETIS_DBGLVL_FAST 512 /* Reduces #trials for various steps */ #define PARMETIS_DBGLVL_ONDISK 1024 /* Saves non-active graphs to disk */ #endif
6,414
36.95858
93
h
filebench
filebench-master/aslr.c
/* * mmap() call with MAP_FIXED flag does not guarantee that the allocated memory * region is not overlapped with the previously existant mappings. According to * POSIX, old mappings are silently discarded. There is no generic way to * detect overlap. If a silent overlap occurs, strange runtime errors might * happen, because we might overlap stack, libraries, anything else. * * Since we always fork+exec same binary (filebench), theoretically all the * mappings should be the same, so no overlap should happen. However, if * virtual Address Space Layout Randomization (ASLR) is enabled on the target * machine - overlap is very likely (especially if workload defines a lot of * processes). We observed numerous segmentation faults on CentOS because of * that. * * The function below disables ASLR in Linux. In future, more platform-specific * functions should be added. */ #include "config.h" #if defined(HAVE_SYS_PERSONALITY_H) #include <sys/personality.h> #endif #include "filebench.h" #include "aslr.h" #if defined(HAVE_SYS_PERSONALITY_H) && defined(HAVE_ADDR_NO_RANDOMIZE) void linux_disable_aslr() { int r; (void) personality(0xffffffff); r = personality(0xffffffff | ADDR_NO_RANDOMIZE); if (r == -1) filebench_log(LOG_ERROR, "Could not disable ASLR"); } #else /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */ void other_disable_aslr() { filebench_log(LOG_INFO, "Per-process disabling of ASLR is not " "supported on this system. " "For Filebench to work properly, " "disable ASLR manually for the whole system. " "On Linux it can be achieved by " "\"sysctl kernel.randomize_va_space=0\" command. " "(the change does not persist across reboots)"); } #endif /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */
1,777
33.862745
79
c
filebench
filebench-master/eventgen.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ /* * The event generator in this module is the producer half of a metering system * which blocks flowops using consumer routines in the flowop_library.c module. * Four routines in that module can limit rates by event rate * (flowoplib_eventlimit), by I/O operations rate (flowoplib_iopslimit()), by * operations rate (flowoplib_opslimit), or by I/O bandwidth limit * (flowoplib_bwlimit). By setting appropriate event generation rates, required * calls per second, I/O ops per second, file system ops per second, or I/O * bandwidth per second limits can be set. Note, the generated events are * shared with all consumer flowops, of which their will be one for each * process / thread instance which has a consumer flowop defined in it. */ #include <sys/time.h> #include "filebench.h" #include "vars.h" #include "eventgen.h" #include "flowop.h" #include "ipc.h" #define FB_SEC2NSEC 1000000000UL /* * The producer side of the event system. Once eventgen_hz has been set by * eventgen_setrate(), the routine sends eventgen_hz events per second until * the program terminates. Events are posted by incrementing * filebench_shm->shm_eventgen_q by the number of generated events then * signalling the condition variable filebench_shm->shm_eventgen_cv to indicate * to event consumers that more events are available. * * Eventgen_thread attempts to sleep for 10 event periods, then, once awakened, * determines how many periods actually passed since sleeping, and issues a set * of events equal to the number of periods that it slept, thus keeping the * average rate at the requested rate. */ static void eventgen_thread(void) { hrtime_t last; last = gethrtime(); filebench_shm->shm_eventgen_enabled = FALSE; while (1) { struct timespec sleeptime; hrtime_t delta; int count, rate; if (filebench_shm->shm_eventgen_hz == NULL) { (void) sleep(1); continue; } else { rate = avd_get_int(filebench_shm->shm_eventgen_hz); if (rate > 0) filebench_shm->shm_eventgen_enabled = TRUE; else continue; } /* Sleep for [10 x period] */ sleeptime.tv_sec = 0; sleeptime.tv_nsec = FB_SEC2NSEC / rate; sleeptime.tv_nsec *= 10; if (sleeptime.tv_nsec < 1000UL) sleeptime.tv_nsec = 1000UL; sleeptime.tv_sec = sleeptime.tv_nsec / FB_SEC2NSEC; if (sleeptime.tv_sec > 0) sleeptime.tv_nsec -= (sleeptime.tv_sec * FB_SEC2NSEC); (void)nanosleep(&sleeptime, NULL); delta = gethrtime() - last; last = gethrtime(); count = (rate * delta) / FB_SEC2NSEC; filebench_log(LOG_DEBUG_SCRIPT, "delta %lluns count %d", (u_longlong_t)delta, count); /* Send 'count' events */ (void)ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); /* * Keep the producer with a max of 5 second depth. * Events accumulate in shm_eventgen_cv even before * worker threads are created. But eventgen_reset() * drops shm_eventgen_q to zero after the worker threads * are created. */ if (filebench_shm->shm_eventgen_q < (5 * rate)) filebench_shm->shm_eventgen_q += count; (void)pthread_cond_signal(&filebench_shm->shm_eventgen_cv); (void)ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } } /* * Creates a thread to run the event generator eventgen_thread routine. */ void eventgen_init(void) { pthread_t tid; if (pthread_create(&tid, NULL, (void *(*)(void *))eventgen_thread, 0) != 0) { filebench_log(LOG_ERROR, "create timer thread failed: %s", strerror(errno)); exit(1); } } /* * Sets the event generator rate to that supplied by * var_t *rate. */ void eventgen_setrate(avd_t rate) { filebench_shm->shm_eventgen_hz = rate; if (rate == NULL) { filebench_log(LOG_ERROR, "eventgen_setrate() called without a rate"); return; } } /* * Clears the event queue so we have a clean start */ void eventgen_reset(void) { filebench_shm->shm_eventgen_q = 0; }
4,841
27.650888
79
c
filebench
filebench-master/eventgen.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_EVENTGEN_H #define _FB_EVENTGEN_H #include "filebench.h" void eventgen_init(void); void eventgen_setrate(avd_t rate); void eventgen_reset(void); #endif /* _FB_EVENTGEN_H */
1,115
30
70
h
filebench
filebench-master/fb_avl.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_AVL_H #define _FB_AVL_H #include "filebench.h" /* * Derived from Solaris' sys/avl.h and sys/avl_impl.h files. */ /* * Generic AVL tree implementation for Filebench use. * * The interfaces provide an efficient way of implementing an ordered set of * data structures. * * AVL trees provide an alternative to using an ordered linked list. Using AVL * trees will usually be faster, however they requires more storage. An ordered * linked list in general requires 2 pointers in each data structure. The * AVL tree implementation uses 3 pointers. The following chart gives the * approximate performance of operations with the different approaches: * * Operation Link List AVL tree * --------- -------- -------- * lookup O(n) O(log(n)) * * insert 1 node constant constant * * delete 1 node constant between constant and O(log(n)) * * delete all nodes O(n) O(n) * * visit the next * or prev node constant between constant and O(log(n)) * * * There are 5 pieces of information stored for each node in an AVL tree * * pointer to less than child * pointer to greater than child * a pointer to the parent of this node * which child [left(0) or right(1)] this node is for its parent * a "balance" (-1, 0, +1) indicating which child tree is taller * * Since they only need 3 bits, the last two fields are packed into the * bottom bits of the parent pointer on 64 bit machines to save on space. */ #if !defined(_LP64) && !(__WORDSIZE == 64) struct avl_node { struct avl_node *avl_child[2]; /* left/right children */ struct avl_node *avl_parent; /* this node's parent */ unsigned short avl_child_index; /* my index in parent's avl_child[] */ short avl_balance; /* balance value: -1, 0, +1 */ }; #define AVL_XPARENT(n) ((n)->avl_parent) #define AVL_SETPARENT(n, p) ((n)->avl_parent = (p)) #define AVL_XCHILD(n) ((n)->avl_child_index) #define AVL_SETCHILD(n, c) ((n)->avl_child_index = (unsigned short)(c)) #define AVL_XBALANCE(n) ((n)->avl_balance) #define AVL_SETBALANCE(n, b) ((n)->avl_balance = (short)(b)) #else /* !defined(_LP64) && !(__WORDSIZE == 64) */ /* * for 64 bit machines, avl_pcb contains parent pointer, balance and child_index * values packed in the following manner: * * |63 3| 2 |1 0 | * |-------------------------------------|-----------------|-------------| * | avl_parent hi order bits | avl_child_index | avl_balance | * | | | + 1 | * |-------------------------------------|-----------------|-------------| * */ struct avl_node { struct avl_node *avl_child[2]; /* left/right children nodes */ uintptr_t avl_pcb; /* parent, child_index, balance */ }; /* * macros to extract/set fields in avl_pcb * * pointer to the parent of the current node is the high order bits */ #define AVL_XPARENT(n) ((struct avl_node *)((n)->avl_pcb & ~7)) #define AVL_SETPARENT(n, p) \ ((n)->avl_pcb = (((n)->avl_pcb & 7) | (uintptr_t)(p))) /* * index of this node in its parent's avl_child[]: bit #2 */ #define AVL_XCHILD(n) (((n)->avl_pcb >> 2) & 1) #define AVL_SETCHILD(n, c) \ ((n)->avl_pcb = (uintptr_t)(((n)->avl_pcb & ~4) | ((c) << 2))) /* * balance indication for a node, lowest 2 bits. A valid balance is * -1, 0, or +1, and is encoded by adding 1 to the value to get the * unsigned values of 0, 1, 2. */ #define AVL_XBALANCE(n) ((int)(((n)->avl_pcb & 3) - 1)) #define AVL_SETBALANCE(n, b) \ ((n)->avl_pcb = (uintptr_t)((((n)->avl_pcb & ~3) | ((b) + 1)))) #endif /* !defined(_LP64) && !(__WORDSIZE == 64) */ /* * switch between a node and data pointer for a given tree * the value of "o" is tree->avl_offset */ #define AVL_NODE2DATA(n, o) ((void *)((uintptr_t)(n) - (o))) #define AVL_DATA2NODE(d, o) ((struct avl_node *)((uintptr_t)(d) + (o))) /* * macros used to create/access an avl_index_t */ #define AVL_INDEX2NODE(x) ((avl_node_t *)((x) & ~1)) #define AVL_INDEX2CHILD(x) ((x) & 1) #define AVL_MKINDEX(n, c) ((avl_index_t)(n) | (c)) /* * The tree structure. The fields avl_root, avl_compar, and avl_offset come * first since they are needed for avl_find(). We want them to fit into * a single 64 byte cache line to make avl_find() as fast as possible. */ struct avl_tree { struct avl_node *avl_root; /* root node in tree */ int (*avl_compar)(const void *, const void *); size_t avl_offset; /* offsetof(type, avl_link_t field) */ unsigned long avl_numnodes; /* number of nodes in the tree */ size_t avl_size; /* sizeof user type struct */ }; /* * This will only by used via AVL_NEXT() or AVL_PREV() */ extern void *avl_walk(struct avl_tree *, void *, int); /* * The data structure nodes are anchored at an "avl_tree_t" (the equivalent * of a list header) and the individual nodes will have a field of * type "avl_node_t" (corresponding to list pointers). * * The type "avl_index_t" is used to indicate a position in the list for * certain calls. * * The usage scenario is generally: * * 1. Create the list/tree with: avl_create() * * followed by any mixture of: * * 2a. Insert nodes with: avl_add(), or avl_find() and avl_insert() * * 2b. Visited elements with: * avl_first() - returns the lowest valued node * avl_last() - returns the highest valued node * AVL_NEXT() - given a node go to next higher one * AVL_PREV() - given a node go to previous lower one * * 2c. Find the node with the closest value either less than or greater * than a given value with avl_nearest(). * * 2d. Remove individual nodes from the list/tree with avl_remove(). * * and finally when the list is being destroyed * * 3. Use avl_destroy_nodes() to quickly process/free up any remaining nodes. * Note that once you use avl_destroy_nodes(), you can no longer * use any routine except avl_destroy_nodes() and avl_destoy(). * * 4. Use avl_destroy() to destroy the AVL tree itself. * * Any locking for multiple thread access is up to the user to provide, just * as is needed for any linked list implementation. */ /* * Type used for the root of the AVL tree. */ typedef struct avl_tree avl_tree_t; /* * The data nodes in the AVL tree must have a field of this type. */ typedef struct avl_node avl_node_t; /* * An opaque type used to locate a position in the tree where a node * would be inserted. */ typedef uintptr_t avl_index_t; /* * Direction constants used for avl_nearest(). */ #define AVL_BEFORE (0) #define AVL_AFTER (1) /* * Prototypes * * Where not otherwise mentioned, "void *" arguments are a pointer to the * user data structure which must contain a field of type avl_node_t. * * Also assume the user data structures looks like: * stuct my_type { * ... * avl_node_t my_link; * ... * }; */ /* * Initialize an AVL tree. Arguments are: * * tree - the tree to be initialized * compar - function to compare two nodes, it must return exactly: -1, 0, or +1 * -1 for <, 0 for ==, and +1 for > * size - the value of sizeof(struct my_type) * offset - the value of OFFSETOF(struct my_type, my_link) */ extern void avl_create(avl_tree_t *tree, int (*compar) (const void *, const void *), size_t size, size_t offset); /* * Find a node with a matching value in the tree. Returns the matching node * found. If not found, it returns NULL and then if "where" is not NULL it sets * "where" for use with avl_insert() or avl_nearest(). * * node - node that has the value being looked for * where - position for use with avl_nearest() or avl_insert(), may be NULL */ extern void *avl_find(avl_tree_t *tree, void *node, avl_index_t *where); /* * Insert a node into the tree. * * node - the node to insert * where - position as returned from avl_find() */ extern void avl_insert(avl_tree_t *tree, void *node, avl_index_t where); /* * Insert "new_data" in "tree" in the given "direction" either after * or before the data "here". * * This might be usefull for avl clients caching recently accessed * data to avoid doing avl_find() again for insertion. * * new_data - new data to insert * here - existing node in "tree" * direction - either AVL_AFTER or AVL_BEFORE the data "here". */ extern void avl_insert_here(avl_tree_t *tree, void *new_data, void *here, int direction); /* * Return the first or last valued node in the tree. Will return NULL * if the tree is empty. * */ extern void *avl_first(avl_tree_t *tree); extern void *avl_last(avl_tree_t *tree); /* * Return the next or previous valued node in the tree. * AVL_NEXT() will return NULL if at the last node. * AVL_PREV() will return NULL if at the first node. * * node - the node from which the next or previous node is found */ #define AVL_NEXT(tree, node) avl_walk(tree, node, AVL_AFTER) #define AVL_PREV(tree, node) avl_walk(tree, node, AVL_BEFORE) /* * Find the node with the nearest value either greater or less than * the value from a previous avl_find(). Returns the node or NULL if * there isn't a matching one. * * where - position as returned from avl_find() * direction - either AVL_BEFORE or AVL_AFTER * * EXAMPLE get the greatest node that is less than a given value: * * avl_tree_t *tree; * struct my_data look_for_value = {....}; * struct my_data *node; * struct my_data *less; * avl_index_t where; * * node = avl_find(tree, &look_for_value, &where); * if (node != NULL) * less = AVL_PREV(tree, node); * else * less = avl_nearest(tree, where, AVL_BEFORE); */ extern void *avl_nearest(avl_tree_t *tree, avl_index_t where, int direction); /* * Add a single node to the tree. * The node must not be in the tree, and it must not * compare equal to any other node already in the tree. * * node - the node to add */ extern void avl_add(avl_tree_t *tree, void *node); /* * Remove a single node from the tree. The node must be in the tree. * * node - the node to remove */ extern void avl_remove(avl_tree_t *tree, void *node); /* * Reinsert a node only if its order has changed relative to its nearest * neighbors. To optimize performance avl_update_lt() checks only the previous * node and avl_update_gt() checks only the next node. Use avl_update_lt() and * avl_update_gt() only if you know the direction in which the order of the * node may change. */ extern boolean_t avl_update(avl_tree_t *, void *); extern boolean_t avl_update_lt(avl_tree_t *, void *); extern boolean_t avl_update_gt(avl_tree_t *, void *); /* * Return the number of nodes in the tree */ extern unsigned long avl_numnodes(avl_tree_t *tree); /* * Return B_TRUE if there are zero nodes in the tree, B_FALSE otherwise. */ extern boolean_t avl_is_empty(avl_tree_t *tree); /* * Used to destroy any remaining nodes in a tree. The cookie argument should * be initialized to NULL before the first call. Returns a node that has been * removed from the tree and may be free()'d. Returns NULL when the tree is * empty. * * Once you call avl_destroy_nodes(), you can only continuing calling it and * finally avl_destroy(). No other AVL routines will be valid. * * cookie - a "void *" used to save state between calls to avl_destroy_nodes() * * EXAMPLE: * avl_tree_t *tree; * struct my_data *node; * void *cookie; * * cookie = NULL; * while ((node = avl_destroy_nodes(tree, &cookie)) != NULL) * free(node); * avl_destroy(tree); */ extern void *avl_destroy_nodes(avl_tree_t *tree, void **cookie); /* * Final destroy of an AVL tree. Arguments are: * * tree - the empty tree to destroy */ extern void avl_destroy(avl_tree_t *tree); #endif /* _FB_AVL_H */
12,596
29.575243
80
h
filebench
filebench-master/fb_cvar.h
/* * fb_cvar.h * * Include file for code using custom variables. * * @Author Santhosh Kumar Koundinya ([email protected]) */ #ifndef _FB_CVAR_H #define _FB_CVAR_H #include <stdint.h> #include <sys/types.h> /* Function (symbol) names within custom variable libraries. */ #define FB_CVAR_MODULE_INIT "cvar_module_init" #define FB_CVAR_ALLOC_HANDLE "cvar_alloc_handle" #define FB_CVAR_REVALIDATE_HANDLE "cvar_revalidate_handle" #define FB_CVAR_NEXT_VALUE "cvar_next_value" #define FB_CVAR_FREE_HANDLE "cvar_free_handle" #define FB_CVAR_MODULE_EXIT "cvar_module_exit" #define FB_CVAR_USAGE "cvar_usage" #define FB_CVAR_VERSION "cvar_version" /* Information about each library supporting a custom variable. This structure * is rooted in the shared memory segment. */ typedef struct cvar_library_info { char *filename; /* The fully qualified path to the library. */ /* The type name of the library is the soname without the "lib" prefix and * the ".so.XXX.XXX" suffix. */ char *type; /* The index is a sequentially increasing count. It helps seek within global * variable cvar_library_array. */ int index; struct cvar_library_info *next; } cvar_library_info_t; /* Structure that encapsulates access to a custom variable. A var_t points to a * cvar_t (and not vice versa). */ typedef struct cvar { /* Used to provide exclusive access to this custom variable across threads * and processes. */ pthread_mutex_t cvar_lock; /* The custom variable handle returned by cvar_alloc() */ void *cvar_handle; double min; double max; uint64_t round; cvar_library_info_t *cvar_lib_info; struct cvar *next; } cvar_t; /* The operations vector for a library. Each member is populated by a call to * dlsym(). */ typedef struct cvar_operations { int (*cvar_module_init)(void); void *(*cvar_alloc_handle)(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *ptr)); int (*cvar_revalidate_handle)(void *cvar_handle); int (*cvar_next_value)(void *cvar_handle, double *value); void (*cvar_free_handle)(void *cvar_handle, void (*cvar_free)(void *ptr)); void (*cvar_module_exit)(); const char *(*cvar_usage)(void); const char *(*cvar_version)(void); } cvar_operations_t; /* Structure that represents a library. This structure is "per-process" and * "per-library" (and not in the shared memory). There is a one to one mapping * between cvar_library_t and cvar_library_info_t. */ typedef struct cvar_library { cvar_library_info_t *cvar_lib_info; void *lib_handle; /* The handle returned by dlopen(). */ cvar_operations_t cvar_op; /* The operations vector of the library. */ } cvar_library_t; /* Points to the head of an array of pointers to cvar_library_t. */ extern cvar_library_t **cvar_libraries; cvar_t * cvar_alloc(void); int init_cvar_library_info(const char *dirpath); int init_cvar_libraries(); int init_cvar_handle(cvar_t *cvar, const char *type, const char *parameters); double get_cvar_value(cvar_t *cvar); int revalidate_cvar_handles(); #endif /* _FB_CVAR_H */
3,054
34.114943
79
h
filebench
filebench-master/fb_localfs.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include "config.h" #include "filebench.h" #include "flowop.h" #include "threadflow.h" /* For aiolist definition */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/param.h> #include <sys/resource.h> #include <strings.h> #include "filebench.h" #include "fsplug.h" #ifdef HAVE_AIO #include <aio.h> #endif /* HAVE_AIO */ /* * These routines implement local file access. They are placed into a * vector of functions that are called by all I/O operations in fileset.c * and flowop_library.c. This represents the default file system plug-in, * and may be replaced by vectors for other file system plug-ins. */ static int fb_lfs_freemem(fb_fdesc_t *fd, off64_t size); static int fb_lfs_open(fb_fdesc_t *, char *, int, int); static int fb_lfs_pread(fb_fdesc_t *, caddr_t, fbint_t, off64_t); static int fb_lfs_read(fb_fdesc_t *, caddr_t, fbint_t); static int fb_lfs_pwrite(fb_fdesc_t *, caddr_t, fbint_t, off64_t); static int fb_lfs_write(fb_fdesc_t *, caddr_t, fbint_t); static int fb_lfs_lseek(fb_fdesc_t *, off64_t, int); static int fb_lfs_truncate(fb_fdesc_t *, off64_t); static int fb_lfs_rename(const char *, const char *); static int fb_lfs_close(fb_fdesc_t *); static int fb_lfs_link(const char *, const char *); static int fb_lfs_symlink(const char *, const char *); static int fb_lfs_unlink(char *); static ssize_t fb_lfs_readlink(const char *, char *, size_t); static int fb_lfs_mkdir(char *, int); static int fb_lfs_rmdir(char *); static DIR *fb_lfs_opendir(char *); static struct dirent *fb_lfs_readdir(DIR *); static int fb_lfs_closedir(DIR *); static int fb_lfs_fsync(fb_fdesc_t *); static int fb_lfs_stat(char *, struct stat64 *); static int fb_lfs_fstat(fb_fdesc_t *, struct stat64 *); static int fb_lfs_access(const char *, int); static void fb_lfs_recur_rm(char *); static fsplug_func_t fb_lfs_funcs = { "locfs", fb_lfs_freemem, /* flush page cache */ fb_lfs_open, /* open */ fb_lfs_pread, /* pread */ fb_lfs_read, /* read */ fb_lfs_pwrite, /* pwrite */ fb_lfs_write, /* write */ fb_lfs_lseek, /* lseek */ fb_lfs_truncate, /* ftruncate */ fb_lfs_rename, /* rename */ fb_lfs_close, /* close */ fb_lfs_link, /* link */ fb_lfs_symlink, /* symlink */ fb_lfs_unlink, /* unlink */ fb_lfs_readlink, /* readlink */ fb_lfs_mkdir, /* mkdir */ fb_lfs_rmdir, /* rmdir */ fb_lfs_opendir, /* opendir */ fb_lfs_readdir, /* readdir */ fb_lfs_closedir, /* closedir */ fb_lfs_fsync, /* fsync */ fb_lfs_stat, /* stat */ fb_lfs_fstat, /* fstat */ fb_lfs_access, /* access */ fb_lfs_recur_rm /* recursive rm */ }; #ifdef HAVE_AIO /* * Local file system asynchronous IO flowops are in this module, as * they have a number of local file system specific features. */ static int fb_lfsflow_aiowrite(threadflow_t *threadflow, flowop_t *flowop); static int fb_lfsflow_aiowait(threadflow_t *threadflow, flowop_t *flowop); static flowop_proto_t fb_lfsflow_funcs[] = { {FLOW_TYPE_AIO, FLOW_ATTR_WRITE, "aiowrite", flowop_init_generic, fb_lfsflow_aiowrite, flowop_destruct_generic}, {FLOW_TYPE_AIO, 0, "aiowait", flowop_init_generic, fb_lfsflow_aiowait, flowop_destruct_generic} }; #endif /* HAVE_AIO */ /* * Initialize file system functions vector to point to the vector of local file * system functions. This function will be called for the master process and * every created worker process. */ void fb_lfs_funcvecinit(void) { fs_functions_vec = &fb_lfs_funcs; } /* * Initialize those flowops which implementation is file system specific. It is * called only once in the master process. */ void fb_lfs_newflowops(void) { #ifdef HAVE_AIO int nops; nops = sizeof (fb_lfsflow_funcs) / sizeof (flowop_proto_t); flowop_add_from_proto(fb_lfsflow_funcs, nops); #endif /* HAVE_AIO */ } /* * Frees up memory mapped file region of supplied size. The * file descriptor "fd" indicates which memory mapped file. * If successful, returns 0. Otherwise returns -1 if "size" * is zero, or -1 times the number of times msync() failed. */ static int fb_lfs_freemem(fb_fdesc_t *fd, off64_t size) { off64_t left; int ret = 0; for (left = size; left > 0; left -= MMAP_SIZE) { off64_t thismapsize; caddr_t addr; thismapsize = MIN(MMAP_SIZE, left); addr = mmap64(0, thismapsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd->fd_num, size - left); ret += msync(addr, thismapsize, MS_INVALIDATE); (void) munmap(addr, thismapsize); } return (ret); } /* * Does a posix pread. Returns what the pread() returns. */ static int fb_lfs_pread(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize, off64_t fileoffset) { return (pread64(fd->fd_num, iobuf, iosize, fileoffset)); } /* * Does a posix read. Returns what the read() returns. */ static int fb_lfs_read(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize) { return (read(fd->fd_num, iobuf, iosize)); } #ifdef HAVE_AIO /* * Asynchronous write section. An Asynchronous IO element * (aiolist_t) is used to associate the asynchronous write request with * its subsequent completion. This element includes a aiocb64 struct * that is used by posix aio_xxx calls to track the asynchronous writes. * The flowops aiowrite and aiowait result in calls to these posix * aio_xxx system routines to do the actual asynchronous write IO * operations. */ /* * Allocates an asynchronous I/O list (aio, of type * aiolist_t) element. Adds it to the flowop thread's * threadflow aio list. Returns a pointer to the element. */ static aiolist_t * aio_allocate(flowop_t *flowop) { aiolist_t *aiolist; if ((aiolist = malloc(sizeof (aiolist_t))) == NULL) { filebench_log(LOG_ERROR, "malloc aiolist failed"); filebench_shutdown(1); } bzero(aiolist, sizeof(*aiolist)); /* Add to list */ if (flowop->fo_thread->tf_aiolist == NULL) { flowop->fo_thread->tf_aiolist = aiolist; aiolist->al_next = NULL; } else { aiolist->al_next = flowop->fo_thread->tf_aiolist; flowop->fo_thread->tf_aiolist = aiolist; } return (aiolist); } /* * Searches for the aiolist element that has a matching * completion block, aiocb. If none found returns FILEBENCH_ERROR. If * found, removes the aiolist element from flowop thread's * list and returns FILEBENCH_OK. */ static int aio_deallocate(flowop_t *flowop, struct aiocb64 *aiocb) { aiolist_t *aiolist = flowop->fo_thread->tf_aiolist; aiolist_t *previous = NULL; aiolist_t *match = NULL; if (aiocb == NULL) { filebench_log(LOG_ERROR, "null aiocb deallocate"); return (FILEBENCH_OK); } while (aiolist) { if (aiocb == &(aiolist->al_aiocb)) { match = aiolist; break; } previous = aiolist; aiolist = aiolist->al_next; } if (match == NULL) return (FILEBENCH_ERROR); /* Remove from the list */ if (previous) previous->al_next = match->al_next; else flowop->fo_thread->tf_aiolist = match->al_next; return (FILEBENCH_OK); } /* * Emulate posix aiowrite(). Determines which file to use, * either one file of a fileset, or the file associated * with a fileobj, allocates and fills an aiolist_t element * for the write, and issues the asynchronous write. This * operation is only valid for random IO, and returns an * error if the flowop is set for sequential IO. Returns * FILEBENCH_OK on success, FILEBENCH_NORSC if iosetup can't * obtain a file to open, and FILEBENCH_ERROR on any * encountered error. */ static int fb_lfsflow_aiowrite(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; fbint_t wss; fbint_t iosize; fb_fdesc_t *fdesc; int ret; iosize = avd_get_int(flowop->fo_iosize); if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, iosize)) != FILEBENCH_OK) return (ret); if (avd_get_bool(flowop->fo_random)) { uint64_t fileoffset; struct aiocb64 *aiocb; aiolist_t *aiolist; if (wss < iosize) { filebench_log(LOG_ERROR, "file size smaller than IO size for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } fb_random64(&fileoffset, wss, iosize, NULL); aiolist = aio_allocate(flowop); aiolist->al_type = AL_WRITE; aiocb = &aiolist->al_aiocb; aiocb->aio_fildes = fdesc->fd_num; aiocb->aio_buf = iobuf; aiocb->aio_nbytes = (size_t)iosize; aiocb->aio_offset = (off64_t)fileoffset; aiocb->aio_reqprio = 0; filebench_log(LOG_DEBUG_IMPL, "aio fd=%d, bytes=%llu, offset=%llu", fdesc->fd_num, (u_longlong_t)iosize, (u_longlong_t)fileoffset); flowop_beginop(threadflow, flowop); if (aio_write64(aiocb) < 0) { filebench_log(LOG_ERROR, "aiowrite failed: %s", strerror(errno)); filebench_shutdown(1); } flowop_endop(threadflow, flowop, iosize); } else { return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } #define MAXREAP 4096 /* * Emulate posix aiowait(). Waits for the completion of half the * outstanding asynchronous IOs, or a single IO, which ever is * larger. The routine will return after a sufficient number of * completed calls issued by any thread in the procflow have * completed, or a 1 second timout elapses. All completed * IO operations are deleted from the thread's aiolist. */ static int fb_lfsflow_aiowait(threadflow_t *threadflow, flowop_t *flowop) { struct aiocb64 **worklist; aiolist_t *aio = flowop->fo_thread->tf_aiolist; int uncompleted = 0; #ifdef HAVE_AIOWAITN int i; #endif worklist = calloc(MAXREAP, sizeof (struct aiocb64 *)); /* Count the list of pending aios */ while (aio) { uncompleted++; aio = aio->al_next; } do { uint_t ncompleted = 0; uint_t todo; int inprogress; #ifdef HAVE_AIOWAITN struct timespec timeout; /* Wait for half of the outstanding requests */ timeout.tv_sec = 1; timeout.tv_nsec = 0; #endif if (uncompleted > MAXREAP) todo = MAXREAP; else todo = uncompleted / 2; if (todo == 0) todo = 1; flowop_beginop(threadflow, flowop); #ifdef HAVE_AIOWAITN if (((aio_waitn64((struct aiocb64 **)worklist, MAXREAP, &todo, &timeout)) == -1) && errno && (errno != ETIME)) { filebench_log(LOG_ERROR, "aiowait failed: %s, outstanding = %d, " "ncompleted = %d ", strerror(errno), uncompleted, todo); } ncompleted = todo; /* Take the completed I/Os from the list */ inprogress = 0; for (i = 0; i < ncompleted; i++) { if ((aio_return64(worklist[i]) == -1) && (errno == EINPROGRESS)) { inprogress++; continue; } if (aio_deallocate(flowop, worklist[i]) == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "Could not remove " "aio from list "); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } } uncompleted -= ncompleted; uncompleted += inprogress; #else for (ncompleted = 0, inprogress = 0, aio = flowop->fo_thread->tf_aiolist; ncompleted < todo && aio != NULL; aio = aio->al_next) { int result = aio_error64(&aio->al_aiocb); if (result == EINPROGRESS) { inprogress++; continue; } if ((aio_return64(&aio->al_aiocb) == -1) || result) { filebench_log(LOG_ERROR, "aio failed: %s", strerror(result)); continue; } ncompleted++; if (aio_deallocate(flowop, &aio->al_aiocb) < 0) { filebench_log(LOG_ERROR, "Could not remove " "aio from list "); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } } uncompleted -= ncompleted; #endif filebench_log(LOG_DEBUG_SCRIPT, "aio2 completed %d ios, uncompleted = %d, inprogress = %d", ncompleted, uncompleted, inprogress); } while (uncompleted > MAXREAP); flowop_endop(threadflow, flowop, 0); free(worklist); return (FILEBENCH_OK); } #endif /* HAVE_AIO */ /* * Does an open64 of a file. Inserts the file descriptor number returned * by open() into the supplied filebench fd. Returns FILEBENCH_OK on * successs, and FILEBENCH_ERROR on failure. */ static int fb_lfs_open(fb_fdesc_t *fd, char *path, int flags, int perms) { if ((fd->fd_num = open64(path, flags, perms)) < 0) return (FILEBENCH_ERROR); else return (FILEBENCH_OK); } /* * Does an unlink (delete) of a file. */ static int fb_lfs_unlink(char *path) { return (unlink(path)); } /* * Does a readlink of a symbolic link. */ static ssize_t fb_lfs_readlink(const char *path, char *buf, size_t buf_size) { return (readlink(path, buf, buf_size)); } /* * Does fsync of a file. Returns with fsync return info. */ static int fb_lfs_fsync(fb_fdesc_t *fd) { return (fsync(fd->fd_num)); } /* * Do a posix lseek of a file. Return what lseek() returns. */ static int fb_lfs_lseek(fb_fdesc_t *fd, off64_t offset, int whence) { return (lseek64(fd->fd_num, offset, whence)); } /* * Do a posix rename of a file. Return what rename() returns. */ static int fb_lfs_rename(const char *old, const char *new) { return (rename(old, new)); } /* * Do a posix close of a file. Return what close() returns. */ static int fb_lfs_close(fb_fdesc_t *fd) { return (close(fd->fd_num)); } /* * Use mkdir to create a directory. */ static int fb_lfs_mkdir(char *path, int perm) { return (mkdir(path, perm)); } /* * Use rmdir to delete a directory. Returns what rmdir() returns. */ static int fb_lfs_rmdir(char *path) { return (rmdir(path)); } /* * does a recursive rm to remove an entire directory tree (i.e. a fileset). * Supplied with the path to the root of the tree. */ static void fb_lfs_recur_rm(char *path) { char cmd[MAXPATHLEN]; (void) snprintf(cmd, sizeof (cmd), "rm -rf %s", path); /* We ignore system()'s return value */ if (system(cmd)); return; } /* * Does a posix opendir(), Returns a directory handle on success, * NULL on failure. */ static DIR * fb_lfs_opendir(char *path) { return (opendir(path)); } /* * Does a readdir() call. Returns a pointer to a table of directory * information on success, NULL on failure. */ static struct dirent * fb_lfs_readdir(DIR *dirp) { return (readdir(dirp)); } /* * Does a closedir() call. */ static int fb_lfs_closedir(DIR *dirp) { return (closedir(dirp)); } /* * Does an fstat of a file. */ static int fb_lfs_fstat(fb_fdesc_t *fd, struct stat64 *statbufp) { return (fstat64(fd->fd_num, statbufp)); } /* * Does a stat of a file. */ static int fb_lfs_stat(char *path, struct stat64 *statbufp) { return (stat64(path, statbufp)); } /* * Do a pwrite64 to a file. */ static int fb_lfs_pwrite(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize, off64_t offset) { return (pwrite64(fd->fd_num, iobuf, iosize, offset)); } /* * Do a write to a file. */ static int fb_lfs_write(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize) { return (write(fd->fd_num, iobuf, iosize)); } /* * Does a truncate operation and returns the result */ static int fb_lfs_truncate(fb_fdesc_t *fd, off64_t fse_size) { #ifdef HAVE_FTRUNCATE64 return (ftruncate64(fd->fd_num, fse_size)); #else filebench_log(LOG_ERROR, "Converting off64_t to off_t in ftruncate," " might be a possible problem"); return (ftruncate(fd->fd_num, (off_t)fse_size)); #endif } /* * Does a link operation and returns the result */ static int fb_lfs_link(const char *existing, const char *new) { return (link(existing, new)); } /* * Does a symlink operation and returns the result */ static int fb_lfs_symlink(const char *existing, const char *new) { return (symlink(existing, new)); } /* * Does an access() check on a file. */ static int fb_lfs_access(const char *path, int amode) { return (access(path, amode)); }
16,441
22.96793
79
c
filebench
filebench-master/fb_random.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> /* this definition prevents warning about using undefined round() function */ #include <math.h> #include "filebench.h" #include "ipc.h" #include "gamma_dist.h" #include "cvars/mtwist/mtwist.h" /* * Generates a 64-bit random number using mtwist or from a provided random * variable "avd". * * Returned random number "randp" is clipped by the "max" value and rounded off * by the "round" value. Returns 0 on success, shuts down Filebench on * failure. */ void fb_random64(uint64_t *randp, uint64_t max, uint64_t round, avd_t avd) { double random_normalized; uint64_t random = 0; if (avd) { /* get it from the random variable */ if (!AVD_IS_RANDOM(avd)) { /* trying to get random value not from random variable. That's a clear error. */ filebench_log(LOG_ERROR, "filebench_randomno64: trying" " to get a random value from not a random variable"); filebench_shutdown(1); /* NOT REACHABLE */ } else { random = avd_get_int(avd); } } else { random = mt_llrand(); } /* * If round is not zero, then caller will get a random number in the * range [0; max - round]. This allows the caller to use this * function, for example, to obtain a pointer in an allocated memory * region of [0; max] and read/write round bytes safely starting * at this pointer. */ max = max - round; random_normalized = (double)random / UINT64_MAX; random = random_normalized * max; if (round) { random = random / round; random = random * round; } *randp = random; } /* * Same as filebench_randomno64, but for 32 bit integers. */ void fb_random32(uint32_t *randp, uint32_t max, uint32_t round, avd_t avd) { uint64_t rand64; fb_random64(&rand64, max, round, avd); /* rand64 always fits uint32, since "max" above was 32 bit */ *randp = (uint32_t)rand64; } /* * Same as filebench_randomno64, but for probability [0-1]. */ static double fb_random_probability() { uint64_t randnum; fb_random64(&randnum, UINT64_MAX, 0, NULL); /* convert to 0-1 probability */ return (double)randnum / (double)(UINT64_MAX); } /**************************************** * * * randist related functions * * * ****************************************/ static double fb_rand_src_rand48(unsigned short *xi) { return (erand48(xi)); } static double fb_rand_src_random(unsigned short *xi) { return fb_random_probability(); } /* * fetch a uniformly distributed random number from the supplied * random object. */ static double rand_uniform_get(randdist_t *rndp) { double dprob, dmin, dres, dround; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dprob = (*rndp->rnd_src)(rndp->rnd_xi); dres = (dprob * (2.0 * (rndp->rnd_dbl_mean - dmin))) + dmin; if (dround == 0.0) return (dres); else return (round(dres / dround) * dround); } /* * fetch a gamma distributed random number from the supplied * random object. */ static double rand_gamma_get(randdist_t *rndp) { double dmult, dres, dmin, dround; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dmult = (rndp->rnd_dbl_mean - dmin) / rndp->rnd_dbl_gamma; dres = gamma_dist_knuth_src(rndp->rnd_dbl_gamma, dmult, rndp->rnd_src, rndp->rnd_xi) + dmin; if (dround == 0.0) return (dres); else return (round(dres / dround) * dround); } /* * fetch a table driven random number from the supplied * random object. */ static double rand_table_get(randdist_t *rndp) { double dprob, dprcnt, dtabres, dsclres, dmin, dround; int idx; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dprob = (*rndp->rnd_src)(rndp->rnd_xi); dprcnt = (dprob * (double)(PF_TAB_SIZE)); idx = (int)dprcnt; dtabres = (rndp->rnd_rft[idx].rf_base + (rndp->rnd_rft[idx].rf_range * (dprcnt - (double)idx))); dsclres = (dtabres * (rndp->rnd_dbl_mean - dmin)) + dmin; if (dround == 0.0) return (dsclres); else return (round(dsclres / dround) * dround); } /* * Set the random seed in the supplied random object. */ static void rand_seed_set(randdist_t *rndp) { union { uint64_t ll; uint16_t w[4]; } temp1; int idx; temp1.ll = (uint64_t)avd_get_int(rndp->rnd_seed); for (idx = 0; idx < 3; idx++) { #ifdef _BIG_ENDIAN rndp->rnd_xi[idx] = temp1.w[3-idx]; #else rndp->rnd_xi[idx] = temp1.w[idx]; #endif } } /* * Define a random entity which will contain the parameters of a random * distribution. */ randdist_t * randdist_alloc(void) { randdist_t *rndp; if ((rndp = (randdist_t *)ipc_malloc(FILEBENCH_RANDDIST)) == NULL) { filebench_log(LOG_ERROR, "Out of memory for random dist"); return (NULL); } /* place on global list */ rndp->rnd_next = filebench_shm->shm_rand_list; filebench_shm->shm_rand_list = rndp; return (rndp); } /* * Initializes a random distribution entity, converting avd_t parameters to * doubles, and converting the list of probability density function table * entries, if supplied, into a probablilty function table. */ void randdist_init(randdist_t *rndp) { probtabent_t *rdte_hdp, *ptep; double tablemean, tablemin = 0; int pteidx; /* convert parameters to doubles */ rndp->rnd_dbl_gamma = (double)avd_get_int(rndp->rnd_gamma) / 1000.0; if (rndp->rnd_mean != NULL) rndp->rnd_dbl_mean = (double)avd_get_int(rndp->rnd_mean); else rndp->rnd_dbl_mean = rndp->rnd_dbl_gamma; /* de-reference min and round amounts for later use */ rndp->rnd_vint_min = avd_get_int(rndp->rnd_min); rndp->rnd_vint_round = avd_get_int(rndp->rnd_round); filebench_log(LOG_DEBUG_IMPL, "init random var: Mean = %6.0llf, Gamma = %6.3llf, Min = %llu", rndp->rnd_dbl_mean, rndp->rnd_dbl_gamma, (u_longlong_t)rndp->rnd_vint_min); /* initialize distribution to apply */ switch (rndp->rnd_type & RAND_TYPE_MASK) { case RAND_TYPE_UNIFORM: rndp->rnd_get = rand_uniform_get; break; case RAND_TYPE_GAMMA: rndp->rnd_get = rand_gamma_get; break; case RAND_TYPE_TABLE: rndp->rnd_get = rand_table_get; break; default: filebench_log(LOG_DEBUG_IMPL, "Random Type not Specified"); filebench_shutdown(1); return; } /* initialize source of random numbers */ if (rndp->rnd_type & RAND_SRC_GENERATOR) { rndp->rnd_src = fb_rand_src_rand48; rand_seed_set(rndp); } else { rndp->rnd_src = fb_rand_src_random; } /* any random distribution table to convert? */ if ((rdte_hdp = rndp->rnd_probtabs) == NULL) return; /* determine random distribution max and mins and initialize table */ pteidx = 0; tablemean = 0.0; for (ptep = rdte_hdp; ptep; ptep = ptep->pte_next) { double dmin, dmax; int entcnt; dmax = (double)avd_get_int(ptep->pte_segmax); dmin = (double)avd_get_int(ptep->pte_segmin); /* initialize table minimum on first pass */ if (pteidx == 0) tablemin = dmin; /* update table minimum */ if (tablemin > dmin) tablemin = dmin; entcnt = (int)avd_get_int(ptep->pte_percent); tablemean += (((dmin + dmax)/2.0) * (double)entcnt); /* populate the lookup table */ for (; entcnt > 0; entcnt--) { rndp->rnd_rft[pteidx].rf_base = dmin; rndp->rnd_rft[pteidx].rf_range = dmax - dmin; pteidx++; } } /* check to see if probability equals 100% */ if (pteidx != PF_TAB_SIZE) filebench_log(LOG_ERROR, "Prob table only totals %d%%", pteidx); /* If table is not supplied with a mean value, set it to table mean */ if (rndp->rnd_dbl_mean == 0.0) rndp->rnd_dbl_mean = (double)tablemean / (double)PF_TAB_SIZE; /* now normalize the entries for a min value of 0, mean of 1 */ tablemean = (tablemean / 100.0) - tablemin; /* special case if really a constant value */ if (tablemean == 0.0) { for (pteidx = 0; pteidx < PF_TAB_SIZE; pteidx++) { rndp->rnd_rft[pteidx].rf_base = 0.0; rndp->rnd_rft[pteidx].rf_range = 0.0; } return; } for (pteidx = 0; pteidx < PF_TAB_SIZE; pteidx++) { rndp->rnd_rft[pteidx].rf_base = ((rndp->rnd_rft[pteidx].rf_base - tablemin) / tablemean); rndp->rnd_rft[pteidx].rf_range = (rndp->rnd_rft[pteidx].rf_range / tablemean); } }
9,001
23.198925
79
c
filebench
filebench-master/fb_random.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_RANDOM_H #define _FB_RANDOM_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" /* * probability table entry, used while parsing the supplied * probability table */ typedef struct probtabent { struct probtabent *pte_next; avd_t pte_percent; avd_t pte_segmin; avd_t pte_segmax; } probtabent_t; /* * The supplied probability table is converted into a probability funtion * lookup table at initialization time. This is the definition for each * entry in the table. */ typedef struct randfunc { double rf_base; double rf_range; } randfunc_t; /* Number of entries in the probability function table */ #define PF_TAB_SIZE 100 /* * Random Distribution definition object. Includes a pointer to the * appropriate function to access the distribution defined by the object, * as well as a function pointer to the specified source of random * numbers. */ typedef struct randdist { double (*rnd_get)(struct randdist *); double (*rnd_src)(unsigned short *); struct randdist *rnd_next; avd_t rnd_seed; avd_t rnd_mean; avd_t rnd_gamma; avd_t rnd_min; avd_t rnd_round; double rnd_dbl_mean; double rnd_dbl_gamma; fbint_t rnd_vint_min; fbint_t rnd_vint_round; probtabent_t *rnd_probtabs; randfunc_t rnd_rft[PF_TAB_SIZE]; uint16_t rnd_xi[3]; uint16_t rnd_type; } randdist_t; #define RAND_TYPE_UNIFORM 0x1 #define RAND_TYPE_GAMMA 0x2 #define RAND_TYPE_TABLE 0x3 #define RAND_TYPE_MASK 0x0fff #define RAND_SRC_URANDOM 0x0000 #define RAND_SRC_GENERATOR 0x1000 #define RAND_PARAM_TYPE 1 #define RAND_PARAM_SRC 2 #define RAND_PARAM_SEED 3 #define RAND_PARAM_MIN 4 #define RAND_PARAM_MEAN 5 #define RAND_PARAM_GAMMA 6 #define RAND_PARAM_ROUND 7 /* Function declarations */ extern void fb_random64(uint64_t *, uint64_t, uint64_t, avd_t); extern void fb_random32(uint32_t *, uint32_t, uint32_t, avd_t); extern randdist_t *randdist_alloc(void); extern void randdist_init(randdist_t *rndp); #endif /* _FB_RANDOM_H */
2,906
26.685714
73
h