template <class XPR> vtab_t eval(const XPR & xxi){ vtab_t xi = rowvect(xxi); itab_t index = nt2::bsearch (breaks, xi); vtab_t val = coefs(index, 1); for(size_t i=2; i <= order; ++i){ val = mul(colvect(xi-breaks(index)), val) + coefs(index,i); } val = nt2::reshape(val, size(xxi)); return val; }
static std::vector<float> evalSampling(int samplingRadius, float deviation) { std::vector<float> coefs(samplingRadius + 1, 0.0f); // corner case when radius is 0 or under if (samplingRadius <= 0) { coefs[0] = 1.0f; return coefs; } // Evaluate all the samples range integral of width 1 from center until the penultimate one float halfWidth = 0.5f; double sum = 0.0; for (int i = 0; i < samplingRadius; i++) { float x = (float) i; double sample = rangeIntegral(x - halfWidth, x + halfWidth, deviation); coefs[i] = sample; sum += sample; } // last sample goes to infinity float lastSampleX0 = (float) samplingRadius - halfWidth; float largeEnough = lastSampleX0 + 1000.0f * deviation; double sample = rangeIntegral(lastSampleX0, largeEnough, deviation); coefs[samplingRadius] = sample; sum += sample; return coefs; }
// Compute the mapping between linear array and a hypercube corresponding /// to a single generator tree void ComputeOneGenMapping(Permut& genMap, const OneGeneratorTree& T) { Vec<long> dims(INIT_SIZE, T.getNleaves()); Vec<long> coefs(INIT_SIZE,T.getNleaves()); for (long i=T.getNleaves()-1, leaf=T.lastLeaf(); i>=0; i--, leaf=T.prevLeaf(leaf)) { dims[i] = T[leaf].getData().size; coefs[i] = T[leaf].getData().e; } // A representation of an integer with digits from dims Vec<long> rep(INIT_SIZE, T.getNleaves()); for (long i=0; i<rep.length(); i++) rep[i]=0; // initialize to zero // initialize to all zero long sz = T[0].getData().size; genMap.SetLength(sz); for (long i=0; i<sz; i++) genMap[i]=0; // compute the permutation for (long i=1; i<sz; i++) { addOne(rep, dims); // representation of i in base dims for (long j=0; j<coefs.length(); j++) { long tmp = MulMod(rep[j], coefs[j], sz); genMap[i] = AddMod(genMap[i], tmp, sz); } } }
double compute_residual_norm2(fei::LinearSystem& fei_ls, fei::Vector& r) { fei::SharedPtr<fei::Matrix> A = fei_ls.getMatrix(); fei::SharedPtr<fei::Vector> x = fei_ls.getSolutionVector(); fei::SharedPtr<fei::Vector> b = fei_ls.getRHS(); //form r = A*x A->multiply(x.get(), &r); //form r = b - r (i.e., r = b - A*x) r.update(1, b.get(), -1); //!!!!!! fix this !!!!!!!!! //terrible data copy. fei::Vector should provide a norm operation instead //of making me roll my own here... std::vector<int> indices; r.getVectorSpace()->getIndices_Owned(indices); std::vector<double> coefs(indices.size()); r.copyOut(indices.size(), &indices[0], &coefs[0]); double local_sum = 0; for(size_t i=0; i<indices.size(); ++i) { local_sum += coefs[i]*coefs[i]; } #ifdef HAVE_MPI MPI_Comm comm = r.getVectorSpace()->getCommunicator(); double global_sum = 0; int num_doubles = 1; MPI_Allreduce(&local_sum, &global_sum, num_doubles, MPI_DOUBLE, MPI_SUM, comm); #else double global_sum = local_sum; #endif return std::sqrt(global_sum); }
void FnirtFileWriter::common_coef_construction(const string& fname, const basisfield& fieldx, const basisfield& fieldy, const basisfield& fieldz, const Matrix& aff) { volume4D<float> coefs(fieldx.CoefSz_x(),fieldx.CoefSz_y(),fieldx.CoefSz_z(),3); vector<float> ksp(3,1.0); try { const splinefield& f = dynamic_cast<const splinefield& >(fieldx); ksp[0] = float(f.Ksp_x()); ksp[1] = float(f.Ksp_y()); ksp[2] = float(f.Ksp_z()); if (f.Order() == 2) coefs.set_intent(FSL_QUADRATIC_SPLINE_COEFFICIENTS,f.Vxs_x(),f.Vxs_y(),f.Vxs_z()); else if (f.Order() == 3) coefs.set_intent(FSL_CUBIC_SPLINE_COEFFICIENTS,f.Vxs_x(),f.Vxs_y(),f.Vxs_z()); } catch (...) { try { const dctfield& f = dynamic_cast<const dctfield& >(fieldx); coefs.set_intent(FSL_DCT_COEFFICIENTS,f.Vxs_x(),f.Vxs_y(),f.Vxs_z()); throw FnirtFileWriterException("common_coef_construction: Saving of DCT coefficients not yet implemented"); } catch (...) { throw FnirtFileWriterException("common_coef_construction: Unknown field type"); } } coefs.setxdim(ksp[0]); coefs.setydim(ksp[1]); coefs.setzdim(ksp[2]); Matrix qform(4,4); qform = IdentityMatrix(4); qform(1,4) = fieldx.FieldSz_x(); qform(2,4) = fieldx.FieldSz_y(); qform(3,4) = fieldx.FieldSz_z(); coefs.set_qform(NIFTI_XFORM_SCANNER_ANAT,qform); coefs.set_sform(NIFTI_XFORM_SCANNER_ANAT,aff); vector<shared_ptr<ColumnVector> > coefp(3); coefp[0]=fieldx.GetCoef(); coefp[1]=fieldy.GetCoef(); coefp[2]=fieldz.GetCoef(); for (unsigned int v=0; v<3; v++) { ColumnVector c = *(coefp[v]); for (unsigned int k=0, vindx=0; k<fieldx.CoefSz_z(); k++) { for (unsigned int j=0; j<fieldx.CoefSz_y(); j++) { for (unsigned int i=0; i<fieldx.CoefSz_x(); i++) { coefs(i,j,k,v) = c.element(vindx++); } } } } save_orig_volume4D(coefs,fname); }
HiVector DriftCorrect::Solve(const HiVector &d) { ostringstream hist; _data = d; if ( _skipFit || (!gotGoodLines(d))) { _b2 = _data; _coefs = HiVector(4, 0.0); _uncert = _coefs; _cc = HiVector(2, 0.0); _chisq = 0.0; if ( !gotGoodLines(d) ) { hist << "NotEnoughLines(GoodLines[" << goodLines(d) << "],MinimumLines[" << _minLines << "]);"; } hist << "SkipFit(TRUE: Not using LMFit)"; _history.add(hist.str()); } else { hist << "Fit("; _b2 = HiVector(goodLines(_data)); if ( success(curvefit()) ) { _coefs = coefs(); _uncert = uncert(); hist << "Solved,#Iters[" << nIterations() << "],ChiSq[" << Chisq() << "],DoF[" << DoF() << "])"; _history.add(hist.str()); _history.add("a0("+ToString(_coefs[0])+"+-"+ToString(_uncert[0])+")"); _history.add("a1("+ToString(_coefs[1])+"+-"+ToString(_uncert[1])+")"); _history.add("a2("+ToString(_coefs[2])+"+-"+ToString(_uncert[2])+")"); _history.add("a3("+ToString(_coefs[3])+"+-"+ToString(_uncert[3])+")"); } else { // Punt, fit a straight line to the data _cc = poly_fit(d); HiVector a(4); a[0] = _cc[0]; a[1] = _cc[1]; a[2] = 0.0; a[3] = 0.0; _coefs = a; hist << "Failed::Reason("<< statusstr() << "),#Iters[" << nIterations() << "])"; _history.add(hist.str()); _history.add("a0("+ToString(_coefs[0])+")"); _history.add("a1("+ToString(_coefs[1])+")"); _history.add("a2("+ToString(_coefs[2])+")"); _history.add("a3("+ToString(_coefs[3])+")"); if ( _useLinFit ) { _history.add("OnFailureUse(LinearFit(Zf))"); } else { _skipFit = true; _history.add("OnFailureUse(ZfBuffer)"); } } } return (Yfit()); }
P rp(CGAL::Random &rand, int deg) { std::vector<typename P::NT> coefs(deg+1); for (int i=0; i< deg+1; ++i){ double mag= 10.0/(i+1); coefs[i]= rand.get_double(-mag, mag); } return P(coefs.begin(), coefs.end()); }
/// /// \brief UnivariateData::Calibrate /// \param values Intensity (or band ratio, or areas) of calibration curve) /// \param conentrations /// void UnivariateData::Calibrate(const vec &values, const vec &concentrations) { mat X = Vespucci::Math::LinLeastSq::Vandermonde(concentrations, 1); vec calibration_y; vec coefs = Vespucci::Math::LinLeastSq::OrdinaryLeastSquares(X, values, calibration_y, calibration_stats_); calibration_stats_["Calibrated"] = 1; vec residuals = values - calibration_y; calibration_curve_ = join_horiz(concentrations, join_horiz(calibration_y, residuals)); double b = coefs(0); double m = coefs(1); results_.transform([m, b](double val){return (val - b)/m;}); }
typename unicubicInterpolation<scalartype_>::matrixtype unicubicInterpolation<scalartype_>::makeAlpha(covafill<scalartype>* cf,vectortype minCoord,vectortype maxCoord) { matrixtype coords(2,minCoord.size()); for(int i = 0; i < minCoord.size(); ++i){ coords(0,i) = minCoord(i); coords(1,i) = maxCoord(i); } matrixtype Minv = getMinv(); int ncoef = 4; vectortype d = maxCoord - minCoord; vectortype mult(2); mult << 1, d(0); vectortype x(ncoef); x.setZero(); for(int i = 0; i < coords.rows(); ++i){ vectortype tmp(1); tmp(0) = coords(i,0); vectortype vals = cf->operator()(tmp); x.segment(2*i,2) = vals.head(2) * mult; } vectortype alphaCoef = Minv * x.matrix(); matrixtype coefs(4,ncoef/4); coefs.setZero(); int indx = 0; for(int j = 0; j < ncoef/4; ++j) for(int i = 0; i < 4; ++i) coefs(i,j) = alphaCoef(indx++); return coefs; };
void compute( const FUNC& f, const X & ranges, const o_t & o) { init(o); itab_t facts = ranges(nt2::_,begin_+1, nt2::_)-ranges(nt2::_,begin_, nt2::_); itab_t vols = nt2::prod(facts); input_t total_vol = globalasum1(vols); itab_t coefs = real_t(maxfunccnt_)*nt2::abs(vols)*nt2::rec(total_vol); BOOST_ASSERT_MSG(size(ranges, 2) == 2, "ranges must be a nx2xm expression"); size_t l = size(ranges, 3); res_ = nt2::Zero<value_t>(); for(size_t i=1; i <= l; ++i) { nbpts_ = coefs(i); res_ += compute(f, ranges(nt2::_,nt2::_,i), vols(i), facts(i)); fcnt_+= nbpts_; } }
bool confirm_vector_values(const fei::Vector& vec, double expected_value) { std::vector<int> indices; fei::SharedPtr<fei::VectorSpace> vspace = vec.getVectorSpace(); vspace->getIndices_Owned(indices); bool result = true; if (indices.size() > 0) { std::vector<double> coefs(indices.size()); vec.copyOut(indices.size(), &indices[0], &coefs[0]); for(size_t i=0; i<indices.size(); ++i) { if (std::abs(coefs[i] - expected_value) > 1.e-13) { result = false; break; } } } return result; }
void scale_vector(double scalar, fei::Vector& vec) { fei::SharedPtr<fei::VectorSpace> vspace = vec.getVectorSpace(); int numIndices = vspace->getNumIndices_Owned(); std::vector<int> indices(numIndices); vspace->getIndices_Owned(numIndices, &indices[0], numIndices); std::vector<double> coefs(numIndices); vec.copyOut(numIndices, &indices[0], &coefs[0]); for(size_t j=0; j<coefs.size(); ++j) { coefs[j] *= scalar; } vec.copyIn(numIndices, &indices[0], &coefs[0]); }
void add_vector_to_vector(double scalar, const fei::Vector& src_vector, fei::Vector& dest_vector) { fei::SharedPtr<fei::VectorSpace> vspace = src_vector.getVectorSpace(); int numIndices = vspace->getNumIndices_Owned(); std::vector<int> indices(numIndices); vspace->getIndices_Owned(numIndices, &indices[0], numIndices); std::vector<double> coefs(numIndices); src_vector.copyOut(numIndices, &indices[0], &coefs[0]); for(size_t j=0; j<coefs.size(); ++j) { coefs[j] *= scalar; } dest_vector.sumIn(numIndices, &indices[0], &coefs[0]); }
//---------------------------------------------------------------------------- int snl_fei::LinearSystem_General::loadPenaltyConstraint(int constraintID, const double *weights, double penaltyValue, double rhsValue) { if (output_level_ >= fei::BRIEF_LOGS && output_stream_ != NULL) { FEI_OSTREAM& os = *output_stream_; os << "loadPenaltyConstraint crID: "<<constraintID<<FEI_ENDL; } Constraint<fei::Record<int>*>* cr = matrixGraph_->getPenaltyConstraint(constraintID); if (cr == NULL) { return(-1); } CHK_ERR( matrixGraph_->getConstraintConnectivityIndices(cr, iwork_) ); fei::SharedPtr<fei::VectorSpace> vecSpace = matrixGraph_->getRowSpace(); int numIndices = iwork_.size(); int* indicesPtr = &(iwork_[0]); //now add the contributions to the matrix and rhs std::vector<double> coefs(numIndices); double* coefPtr = &coefs[0]; for(int i=0; i<numIndices; ++i) { for(int j=0; j<numIndices; ++j) { coefPtr[j] = weights[i]*weights[j]*penaltyValue; } CHK_ERR( matrix_->sumIn(1, &(indicesPtr[i]), numIndices, indicesPtr, &coefPtr) ); double rhsCoef = weights[i]*penaltyValue*rhsValue; CHK_ERR( rhs_->sumIn(1, &(indicesPtr[i]), &rhsCoef) ); } return(0); }
int main(int argc, char **argv){ if (argc < 2){ printf("Error: Debe especificar un archivo .pcd\n"); exit(1); } // Cargar nube de puntos PointCloud::Ptr cloud (new PointCloud); pcl::io::loadPCDFile(argv[1],*cloud); // Crear visualizador boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = simpleVis(cloud); // Segmentar segmentator.setOptimizeCoefficients(true); segmentator.setModelType(pcl::SACMODEL_PLANE); segmentator.setMethodType(pcl::SAC_RANSAC); segmentator.setDistanceThreshold(SEG_THRESHOLD); segmentator.setInputCloud(cloud); pcl::ModelCoefficients::Ptr coefs (new pcl::ModelCoefficients()); pcl::PointIndices::Ptr inliers (new pcl::PointIndices()); segmentator.segment(*inliers,*coefs); // Ver qué se obtuvo printf("Se obtienen %d puntos\n",(int)inliers->indices.size()); if (inliers->indices.size() == 0){ printf("Segmentación no sirvió de nada.\n"); exit(1); } viewer->addPlane(*coefs, "planito"); // Obtener centroide y dibujarlo Eigen::Vector4f centroid; compute3DCentroid(*cloud,centroid); viewer->addSphere(pcl::PointXYZ(centroid(0),centroid(1),centroid(2)), 0.2, "centroide"); // Dibujar un plano en el viewer para indicar más menos qué se obtuvo // http://docs.pointclouds.org/trunk/classpcl_1_1visualization_1_1_p_c_l_visualizer.html while (!viewer->wasStopped()){ viewer->spinOnce(100); boost::this_thread::sleep (boost::posix_time::microseconds (100000)); } }
int main(int argc, char** argv){ if(argc<3) { cout << "uso: ./set_params [input] [output]" << endl; return 0; } /* Abro los archivos */ ifstream in(argv[1]); if(!in.is_open()) cout << "No se pudo abrir el archivo: " << argv[1] << endl; ofstream out(argv[2]); if(!out.is_open()) cout << "No se pudo abrir el archivo: " << argv[2] << endl; uint amount_instance; in >> amount_instance; cout << "Son " << amount_instance << " instancias" << endl; uint order = 5; for(int j=0; j<amount_instance; j++){ cout << "Procesando instancia nro: " << j+1 << endl; /* Leo el orden del primer polinomio */ uint xj; in >> xj; /* Leo los coeficientes de X */ vector<double> coefs(order+1); for(int i=0; i<order+1; i++) in >> coefs[i]; for(ull iter=10; iter<=10000000; iter*=10){ cout << "Con iter = " << iter << endl; Setp_Polynomial pol(coefs,xj,order); vector<double> zeros(order); zeros = pol.zeros(0,1,0,iter); double min_zero = min(pol, zeros); out << iter << " " << abs(pol.evaluate(min_zero)) << endl; } /*double tolerance = TOLERANCE; //Parto de e-5 quiero llegar a e-25 for(int i=0; i<20; i++){ cout << "Con tolerance = " << tolerance << endl; Setp_Polynomial pol(coefs,xj,order); vector<double> zeros(order); zeros = pol.zeros(0,1,tolerance,ITER); double min_zero = min(pol, zeros); if(abs(pol.evaluate(min_zero)) < tolerance){ out << j << " " << tolerance << " " << pol.getAmountOp() << " " << abs(pol.evaluate(min_zero)) << endl; } else { cout << "No pasa la tolerancia" << endl; break; } tolerance/=10; }*/ } in.close(); out.close(); return 0; }
int main(int argc, char** argv) { #if defined(HAVE_MPI) && defined(HAVE_EPETRA) int numProcs = 1; int localProc = 0; //first, set up our MPI environment... MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &localProc); MPI_Comm_size(MPI_COMM_WORLD, &numProcs); // This program can only run on 3 processors, to make things // work out easy. // if (numProcs != 3) { std::cout << "num-procs="<<numProcs<<". This program can only " << "run on 3 procs. Exiting."<<std::endl; MPI_Finalize(); return(0); } //Consider the following mesh of 4 2-D quad elements: // // *-------*-------* // 8| 7| 6| // | E2 | E3 | // *-------*-------* // 3| 2| 5| // | E0 | E1 | // *-------*-------* // 0 1 4 // // Node-ids are to the lower-left of each node (*). // // Mimicing a finite-element application, we will say that // each node has 1 scalar degree-of-freedom, and assemble // a matrix which would have 9 global rows and columns. // // Each processor will have 3 rows. We'll set up a strange // initial map, where nodes are distributed as follows: // // proc 0: nodes 0,3,8, // proc 1: nodes 1,2,7 // proc 2: nodes 4,5,6. // // After we assemble our matrix, we'll create another matrix // and populate it with graph edge weights such that the // partitioner repartitions the problem so that nodes are // laid out as follows: // // proc 0: nodes 0, 1, 4 // proc 1: nodes 3, 2, 5 // proc 2: nodes 8, 7, 6 // int nodesPerElem = 4; int global_n = 9; //First, set up the initial map: std::vector<int> mynodes(3); if (localProc == 0) { mynodes[0] = 0; mynodes[1] = 3; mynodes[2] = 8; } if (localProc == 1) { mynodes[0] = 1; mynodes[1] = 2; mynodes[2] = 7; } if (localProc == 2) { mynodes[0] = 4; mynodes[1] = 5; mynodes[2] = 6; } Epetra_MpiComm comm(MPI_COMM_WORLD); Epetra_Map origmap(global_n, 3, &mynodes[0], 0, comm); Teuchos::RCP<Epetra_FECrsMatrix> matrix = Teuchos::rcp(new Epetra_FECrsMatrix(Copy, origmap, 0)); //We'll assemble elements E0 and E1 on proc 0, // element E2 or proc 1, // element E3 on proc 2. std::vector<int> indices(nodesPerElem); std::vector<double> coefs(nodesPerElem*nodesPerElem,2.0); if (localProc == 0) { //element E0: indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 3; matrix->InsertGlobalValues(nodesPerElem, &indices[0], &coefs[0]); //element E1: indices[0] = 1; indices[1] = 4; indices[2] = 5; indices[3] = 2; matrix->InsertGlobalValues(nodesPerElem, &indices[0], &coefs[0]); } else if (localProc == 1) { //element E2: indices[0] = 3; indices[1] = 2; indices[2] = 7; indices[3] = 8; matrix->InsertGlobalValues(nodesPerElem, &indices[0], &coefs[0]); } else { //localProc==2 //element E3: indices[0] = 2; indices[1] = 5; indices[2] = 6; indices[3] = 7; matrix->InsertGlobalValues(nodesPerElem, &indices[0], &coefs[0]); } int err = matrix->GlobalAssemble(); if (err != 0) { std::cout << "err="<<err<<" returned from matrix->GlobalAssemble()" << std::endl; } // std::cout << "matrix: " << std::endl; // std::cout << *matrix << std::endl; //We'll need a Teuchos::ParameterList object to pass to the //Isorropia::Epetra::Partitioner class. Teuchos::ParameterList paramlist; #ifdef HAVE_ISORROPIA_ZOLTAN // If Zoltan is available, we'll specify that the Zoltan package be // used for the partitioning operation, by creating a parameter // sublist named "Zoltan". // In the sublist, we'll set parameters that we want sent to Zoltan. paramlist.set("PARTITIONING METHOD", "GRAPH"); paramlist.set("PRINT ZOLTAN METRICS", "2"); Teuchos::ParameterList& sublist = paramlist.sublist("Zoltan"); sublist.set("GRAPH_PACKAGE", "PHG"); //sublist.set("DEBUG_LEVEL", "1"); // Zoltan will print out parameters //sublist.set("DEBUG_LEVEL", "5"); // proc 0 will trace Zoltan calls //sublist.set("DEBUG_MEMORY", "2"); // Zoltan will trace alloc & free #else // If Zoltan is not available, a simple linear partitioner will be // used to partition such that the number of nonzeros is equal (or // close to equal) on each processor. No parameter is necessary to // specify this. #endif Teuchos::RCP<Isorropia::Epetra::CostDescriber> costs = Teuchos::rcp(new Isorropia::Epetra::CostDescriber); //Next create a matrix which is a copy of the matrix we just //assembled, but we'll replace the values with graph edge weights. Teuchos::RCP<Epetra_FECrsMatrix> ge_weights = Teuchos::rcp(new Epetra_FECrsMatrix(*matrix)); Teuchos::RCP<Epetra_CrsMatrix> crs_ge_weights; crs_ge_weights = ge_weights; //Fill the matrix with a "default" weight of 1.0. crs_ge_weights->PutScalar(1.0); //Now we'll put a "large" weight on edges that connect nodes //0 and 1, 1 and 4, //3 and 2, 2 and 5, //8 and 7, 7 and 6. double weight = 500.0; if (localProc == 0) { //row 0, edge 1 indices[0] = 1; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(0, 1, &coefs[0], &indices[0]); //row 3, edge 2 indices[0] = 2; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(3, 1, &coefs[0], &indices[0]); //row 8, edge 7 indices[0] = 7; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(8, 1, &coefs[0], &indices[0]); } if (localProc == 1) { //row 1, edges 0 and 4 indices[0] = 0; indices[1] = 4; coefs[0] = weight; coefs[1] = weight; crs_ge_weights->ReplaceGlobalValues(1, 2, &coefs[0], &indices[0]); //row 2, edges 3 and 5 indices[0] = 3; indices[1] = 5; coefs[0] = weight; coefs[1] = weight; crs_ge_weights->ReplaceGlobalValues(2, 2, &coefs[0], &indices[0]); //row 7, edges 6 and 8 indices[0] = 6; indices[1] = 8; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(7, 2, &coefs[0], &indices[0]); } if (localProc == 2) { //row 4, edge 1 indices[0] = 1; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(4, 1, &coefs[0], &indices[0]); //row 5, edge 2 indices[0] = 2; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(5, 1, &coefs[0], &indices[0]); //row 6, edge 7 indices[0] = 7; coefs[0] = weight; crs_ge_weights->ReplaceGlobalValues(6, 1, &coefs[0], &indices[0]); } // std::cout << "crs_ge_weights: " << std::endl // << *crs_ge_weights << std::endl; //Now give the graph edge weights to the CostDescriber: costs->setGraphEdgeWeights(crs_ge_weights); Teuchos::RCP<const Epetra_RowMatrix> rowmatrix; rowmatrix = matrix; //Now create the partitioner object using an Isorropia factory-like //function... Teuchos::RCP<Isorropia::Epetra::Partitioner> partitioner = Teuchos::rcp(new Isorropia::Epetra::Partitioner(rowmatrix, costs, paramlist)); //Next create a Redistributor object and use it to create a //repartitioned copy of the matrix Isorropia::Epetra::Redistributor rd(partitioner); Teuchos::RCP<Epetra_CrsMatrix> bal_matrix; //Use a try-catch block because Isorropia will throw an exception //if it encounters an error. if (localProc == 0) { std::cout << " calling Isorropia::Epetra::Redistributor::redistribute..." << std::endl; } try { bal_matrix = rd.redistribute(*rowmatrix); } catch(std::exception& exc) { std::cout << "linsys example: Isorropia::Epetra::Redistributor threw " << "exception '" << exc.what() << "' on proc " << localProc << std::endl; MPI_Finalize(); return(-1); } // Results double bal0, bal1, cutn0, cutn1, cutl0, cutl1, cutWgt0, cutWgt1; int numCuts0, numCuts1; #if 1 // Balance and cut quality before partitioning double goalWeight = 1.0 / (double)numProcs; ispatest::compute_graph_metrics(*rowmatrix, *costs, goalWeight, bal0, numCuts0, cutWgt0, cutn0, cutl0); // Balance and cut quality after partitioning Teuchos::RCP<Epetra_CrsMatrix> new_weights = rd.redistribute(*crs_ge_weights); Isorropia::Epetra::CostDescriber new_costs; new_costs.setGraphEdgeWeights(new_weights); ispatest::compute_graph_metrics(*bal_matrix, new_costs, goalWeight, bal1, numCuts1, cutWgt1, cutn1, cutl1); #else std::vector<double> bal(2), cutwgt(2), cutn(2), cutl(2); std::vector<int >ncuts(2); Epetra_Import &importer = rd.get_importer(); costs->compareBeforeAndAfterGraph(*rowmatrix, *bal_matrix, importer, bal, ncuts, cutwgt, cutn, cutl); bal0 = bal[0]; cutn0 = cutn[0]; cutl0 = cutl[0]; cutWgt0 = cutwgt[0]; numCuts0 = ncuts[0]; bal1 = bal[1]; cutn1 = cutn[1]; cutl1 = cutl[1]; cutWgt1 = cutwgt[1]; numCuts1 = ncuts[1]; #endif bal_matrix.release(); if (localProc == 0){ std::cout << "Before partitioning: Number of cuts " << numCuts0 << " Cut weight " << cutWgt0 << std::endl; std::cout << " Balance " << bal0 << " cutN " << cutn0 << " cutL " << cutl0; std::cout << std::endl; std::cout << "After partitioning: Number of cuts " << numCuts1 << " Cut weight " << cutWgt1 << std::endl; std::cout << " Balance " << bal1 << " cutN " << cutn1 << " cutL " << cutl1; std::cout << std::endl; } MPI_Finalize(); #else std::cout << "part_redist: must have both MPI and EPETRA. Make sure Trilinos " << "is configured with --enable-mpi and --enable-epetra." << std::endl; #endif return(0); }
//============================================================================== vector<double> LRBSpline2D::unitIntervalBernsteinBasis(double start, double stop, Direction2D d) const //============================================================================== { // Get knot vector, where the knots are translated by start -> 0.0 and stop -> 1.0 vector<double> knots; vector<int> knots_int = kvec(d); double slope = 1.0/(stop - start); int deg = degree(d); for (int i = 0; i < deg + 2; ++i) knots.push_back(slope * (mesh_->kval(d,knots_int[i]) - start)); // Get the position of the interval containing [0,1]. We assume that for // some k, knots[k] <= 0.0 and knots[k+1] >= 1.0, and let interval_pos be this k. // We use 0.5 instead of 1.0 to break the loop, in order to avoid using tolerances. // Any number in the open interval (0,1) would work. int interval_pos; for (interval_pos = 0; interval_pos <= deg; ++interval_pos) if (knots[interval_pos + 1] >= 0.5) break; // Prepare array holding the Bernstein basis coefficients. // After each step for each polynomial degree (value of k in outermost loop below), // the polynomial part on the interval [ knots[interval_pos], knots[interval_pos+1] ]) // of the k-degree B-spline defined by knot vector knot[i],...,knot[i+k+1] is given // by coefficients coefs[i][0],...,coefs[i][k]. At the end, the coefficients to be // returned are in coefs[0] vector<vector<double> > coefs(deg+1); for (int i = 0; i <= deg; ++i) coefs[i].resize(deg + 1 - i); coefs[interval_pos][0] = 1.0; for (int k = 1; k <=deg; ++k) for (int i = 0; i <= deg - k; ++i) if (i >= interval_pos - k && i <= interval_pos) // Only look at B-splines with support in interval { double coefs_i_jmin1 = 0.0; // For caching coefs[i][j-1] in inner loop // Store 1/(k*(knots[i+k]-knots[i])) and same for next interval. The denominator should not be zero // (because knots[interval_pos] < knots[interval_pos +1]) but just in case we use the standard // assumption 1/0 = 0 from spline arithmetics double denom_0 = (double)k*(knots[i + k] - knots[i]); if (denom_0 != 0.0) denom_0 = 1.0/denom_0; double denom_1 = (double)k*(knots[i + k + 1] - knots[i + 1]); if (denom_1 != 0.0) denom_1 = 1.0/denom_1; // Some factors used several times double f0 = (1.0 - knots[i]) * denom_0; double f1 = (knots[i + k + 1] - 1.0) * denom_1; double f2 = f0 - denom_0; double f3 = f1 + denom_1; // Calculate the new coefficients for (int j = 0; j <= k; ++j) { double res = 0.0; if (j > 0) res += (f0 * coefs_i_jmin1 + f1 * coefs[i + 1][j - 1]) * (double)j; if (j < k) res += (f2 * coefs[i][j] + f3 * coefs[i + 1][j]) * (double)(k - j); coefs_i_jmin1 = coefs[i][j]; coefs[i][j] = res; } } return coefs[0]; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Updates sent planes using but environment model server // @param planes Vector of found planes // @param scene_cloud point cloud of the scene /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DynModelExporter2::update(std::vector<Plane<float> > & planes, Normals &normals) { if (m_keep_tracking == 0) displayed_planes.clear(); std::vector<PointCloud<pcl::PointXYZ>, Eigen::aligned_allocator<PointCloud<pcl::PointXYZ> > > planesInPCloud(planes.size()); for (int i = 0; i < normals.m_points.rows; ++i) for (int j = 0; j < normals.m_points.cols; ++j) { Vec3f point = normals.m_points.at<Vec3f>(i, j); cv::Vec4f localPlane = normals.m_planes.at<cv::Vec4f>(i, j); Plane<float> aaa(localPlane[0], localPlane[1], localPlane[2], localPlane[3]); double dist = DBL_MAX; int chosen = -1; // find the best plane for (unsigned int a = 0; a < planes.size(); ++a) { if (planes[a].distance(point) < dist && planes[a].distance(point) < m_max_distance && planes[a].isSimilar(aaa, m_max_plane_normal_dev, m_max_plane_shift_dev)) { dist = planes[a].distance(point); chosen = a; } } // if there is good plane, insert point into point cloud if (chosen > -1) { PointXYZ pclpoint(point[0], point[1], point[2]); planesInPCloud[chosen].push_back(pclpoint); } } // Indexed in point cloud //////////////////////////////////////////////////////////////////////////////////////////////// for (unsigned int j = 0; j < planesInPCloud.size(); ++j) { if (planesInPCloud[j].size() > 20) { double maxangle = DBL_MAX; double maxdist = DBL_MAX; int index = -1; for (unsigned int i = 0; i < displayed_planes.size(); ++i) { double angle = acos(((planes[j].a * displayed_planes[i].plane.a) + (planes[j].b * displayed_planes[i].plane.b) + (planes[j].c * displayed_planes[i].plane.c))); double xd = planes[j].d - displayed_planes[i].plane.d; xd = (xd > 0 ? xd : - xd); // Pretty nasty workaround... todo if (angle != angle) angle = 0.0; if (angle <= maxangle && xd <= maxdist && angle < 0.2 && xd < 0.2) { maxangle = angle; maxdist = xd; index = i; } } if (index >= 0) { for (unsigned int i = 0; i < displayed_planes[index].marker.points.size(); ++i) { geometry_msgs::Point p = displayed_planes[index].marker.points[i]; planesInPCloud[j].push_back(PointXYZ(p.x, p.y, p.z)); } pcl::ModelCoefficientsPtr coefs(new pcl::ModelCoefficients()); coefs->values.push_back(displayed_planes[index].plane.a); coefs->values.push_back(displayed_planes[index].plane.b); coefs->values.push_back(displayed_planes[index].plane.c); coefs->values.push_back(displayed_planes[index].plane.d); DynModelExporter2::createMarkerForConvexHull(planesInPCloud[j], coefs, displayed_planes[index].marker); } else { pcl::ModelCoefficientsPtr coefs(new pcl::ModelCoefficients()); coefs->values.push_back(planes[j].a); coefs->values.push_back(planes[j].b); coefs->values.push_back(planes[j].c); coefs->values.push_back(planes[j].d); // std::cerr << planes[j].a << " "; // std::cerr << planes[j].b << " "; // std::cerr << planes[j].c << " "; // std::cerr << planes[j].d << std::endl; visualization_msgs::Marker marker; DynModelExporter2::createMarkerForConvexHull(planesInPCloud[j], coefs, marker); marker.id = displayed_planes.size()+1; marker.ns = "Normals"; marker.pose.position.x = 0.0; marker.pose.position.y = 0.0; marker.pose.position.z = 0.0; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.x = 1; marker.scale.y = 1; marker.scale.z = 1; marker.color.r = 0.5; marker.color.g = 0.0; marker.color.b = 0.0; marker.color.a = 0.8; ExportedPlane newplane; newplane.id = index; newplane.marker = marker; newplane.plane = planes[j]; displayed_planes.push_back(newplane); } } } std::cerr << displayed_planes.size() << std::endl; }
//---------------------------------------------------------------------------- int snl_fei::LinearSystem_General::enforceEssentialBC_LinSysCore() { fei::Matrix* matptr = matrix_.get(); fei::MatrixReducer* matred = dynamic_cast<fei::MatrixReducer*>(matptr); if (matred != NULL) { matptr = matred->getTargetMatrix().get(); } fei::Matrix_Impl<LinearSystemCore>* lscmatrix = dynamic_cast<fei::Matrix_Impl<LinearSystemCore>*>(matptr); if (lscmatrix == 0) { return(-1); } int localsize = matrixGraph_->getRowSpace()->getNumIndices_Owned(); fei::SharedPtr<fei::Reducer> reducer = matrixGraph_->getReducer(); if (matrixGraph_->getGlobalNumSlaveConstraints() > 0) { localsize = reducer->getLocalReducedEqns().size(); } fei::SharedPtr<fei::FillableMat> inner(new fei::FillableMat); bool zeroSharedRows = false; fei::SharedPtr<fei::Matrix_Impl<fei::FillableMat> > matrix; matrix.reset(new fei::Matrix_Impl<fei::FillableMat>(inner, matrixGraph_, localsize, zeroSharedRows)); fei::SharedPtr<fei::SparseRowGraph> remoteGraph = matrixGraph_->getRemotelyOwnedGraphRows(); if (!BCenforcement_no_column_mod_) { CHK_ERR( snl_fei::gatherRemoteEssBCs(*essBCvalues_, remoteGraph.get(), *matrix) ); } unsigned numBCRows = inner->getNumRows(); if (output_stream_ != NULL && output_level_ >= fei::BRIEF_LOGS) { FEI_OSTREAM& os = *output_stream_; os << "#enforceEssentialBC_LinSysCore RemEssBCs to enforce: " << numBCRows << FEI_ENDL; } if (numBCRows > 0 && !BCenforcement_no_column_mod_) { std::vector<int*> colIndices(numBCRows); std::vector<double*> coefs(numBCRows); std::vector<int> colIndLengths(numBCRows); fei::CSRMat csrmat(*inner); fei::SparseRowGraph& srg = csrmat.getGraph(); int numEqns = csrmat.getNumRows(); int* eqns = &(srg.rowNumbers[0]); int* rowOffsets = &(srg.rowOffsets[0]); for(int i=0; i<numEqns; ++i) { colIndices[i] = &(srg.packedColumnIndices[rowOffsets[i]]); coefs[i] = &(csrmat.getPackedCoefs()[rowOffsets[i]]); colIndLengths[i] = rowOffsets[i+1] - rowOffsets[i]; } int** colInds = &colIndices[0]; int* colIndLens = &colIndLengths[0]; double** BCcoefs = &coefs[0]; if (output_stream_ != NULL && output_level_ > fei::BRIEF_LOGS) { FEI_OSTREAM& os = *output_stream_; for(int i=0; i<numEqns; ++i) { os << "remBCeqn: " << eqns[i] << ", inds/coefs: "; for(int j=0; j<colIndLens[i]; ++j) { os << "("<<colInds[i][j]<<","<<BCcoefs[i][j]<<") "; } os << FEI_ENDL; } } int errcode = lscmatrix->getMatrix()->enforceRemoteEssBCs(numEqns, eqns, colInds, colIndLens, BCcoefs); if (errcode != 0) { return(errcode); } } int numEqns = essBCvalues_->size(); if (numEqns > 0) { int* eqns = &(essBCvalues_->indices())[0]; double* bccoefs = &(essBCvalues_->coefs())[0]; std::vector<double> ones(numEqns, 1.0); return(lscmatrix->getMatrix()->enforceEssentialBC(eqns, &ones[0], bccoefs, numEqns)); } return(0); }
void test_Matrix_unit4(MPI_Comm comm, int numProcs, int localProc) { if (numProcs > 1) { return; } FEI_COUT << "testing fei::Matrix_Impl with FEI_BLOCK_DIAGONAL_ROW..."; fei::SharedPtr<fei::VectorSpace> rowspace(new fei::VectorSpace(comm)); fei::SharedPtr<fei::VectorSpace> colspace; int rowfield = 0, rowfieldsize = 2; int idType = 0; rowspace->defineFields(1, &rowfield, &rowfieldsize); rowspace->defineIDTypes(1, &idType); fei::SharedPtr<fei::MatrixGraph> mgraph(new fei::MatrixGraph_Impl2(rowspace, colspace)); int patternID1 = mgraph->definePattern(2, idType, rowfield); fei::Pattern* rowpattern = mgraph->getPattern(patternID1); bool diagonal = true; mgraph->initConnectivityBlock(0, 1, patternID1, diagonal); std::vector<int> ids(2); ids[0] = 0; ids[1] = 1; int err = mgraph->initConnectivity(0, 0, &ids[0]); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, initConnectivity returned err="<<err; throw std::runtime_error(osstr.str()); } err = mgraph->initComplete(); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, initComplete returned err="<<err; throw std::runtime_error(osstr.str()); } fei::SharedPtr<fei::Factory> factory; try { factory = fei::create_fei_Factory(comm, "Trilinos"); } catch(...) { FEI_COUT << "Trilinos not available."<<FEI_ENDL; return; } fei::Param blktrue("BLOCK_MATRIX", true); fei::Param blkfalse("BLOCK_MATRIX", false); fei::ParameterSet paramset; paramset.add(blktrue); factory->parameters(paramset); fei::SharedPtr<fei::Matrix> feiblkmat = factory->createMatrix(mgraph); paramset.add(blkfalse); factory->parameters(paramset); fei::SharedPtr<fei::Matrix> feimat = factory->createMatrix(mgraph); int numrowindices = rowpattern->getNumIndices(); std::vector<double> coefs(numrowindices*rowfieldsize*rowfieldsize, 1.0); std::vector<double*> coefs_2D(numrowindices*rowfieldsize); int offset = 0; for(int i=0; i<numrowindices*rowfieldsize; ++i) { coefs_2D[i] = &(coefs[offset]); offset += rowfieldsize; } err = feimat->sumIn(0, 0, &coefs_2D[0], FEI_BLOCK_DIAGONAL_ROW); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, feimat->sumIn returned err="<<err; throw std::runtime_error(osstr.str()); } err = feiblkmat->sumIn(0, 0, &coefs_2D[0], FEI_BLOCK_DIAGONAL_ROW); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, feiblkmat->sumIn returned err="<<err; throw std::runtime_error(osstr.str()); } err = feimat->globalAssemble(); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, feimat->globalAssemble returned err="<<err; throw std::runtime_error(osstr.str()); } err = feiblkmat->globalAssemble(); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit4, feimat->globalAssemble returned err="<<err; throw std::runtime_error(osstr.str()); } feimat->writeToFile("feimat_blkdiag.mtx"); feiblkmat->writeToFile("feiblkmat_blkdiag.mtx"); FEI_COUT << "ok"<<FEI_ENDL; }
bool FieldFuncBase::load (const std::vector<std::string>& fieldNames, const std::string& basisName, int level, size_t nPatches, bool isScalar) { size_t nOK = 0; if (nPatches == 0) nPatches = patch.size(); else if (patch.empty()) patch.resize(nPatches,nullptr); this->clearField(); #ifdef HAS_HDF5 size_t nFldCmp = fieldNames.size(); size_t nFldC2D = isScalar ? 1 : (nFldCmp < 2 ? 2 : nFldCmp); size_t nFldC3D = isScalar ? 1 : (nFldCmp < 3 ? 3 : nFldCmp); for (size_t ip = 0; ip < nPatches; ip++) { if (hdf5->hasGeometries(level,basisName)) { if (patch[ip]) { // We have an updated basis at this level, replace current one if (patch[ip]->getNoParamDim() == 2) nFldC2D = patch[ip]->getNoFields(); if (patch[ip]->getNoParamDim() == 3) nFldC3D = patch[ip]->getNoFields(); delete patch[ip]; } std::string g2; std::stringstream sbasis; sbasis << level <<"/basis/"<< basisName <<"/"<< ip+1; hdf5->readString(sbasis.str(),g2); if (g2.compare(0,9,"200 1 0 0") == 0) patch[ip] = ASM2D::create(ASM::Spline,nFldC2D); else if (g2.compare(0,9,"700 1 0 0") == 0) patch[ip] = ASM3D::create(ASM::Spline,nFldC3D); else if (g2.compare(0,18,"# LRSPLINE SURFACE") == 0) patch[ip] = ASM2D::create(ASM::LRSpline,nFldC2D); else if (g2.compare(0,17,"# LRSPLINE VOLUME") == 0) patch[ip] = ASM3D::create(ASM::LRSpline,nFldC3D); else patch[ip] = nullptr; if (patch[ip]) { std::stringstream strg2(g2); patch[ip]->read(strg2); } else std::cerr <<" *** FieldFuncBase::load: Undefined basis "<< sbasis.str() <<" ("<< g2.substr(0,9) <<")"<< std::endl; } if (patch[ip]) { RealArrays coefs(nFldCmp); for (size_t i = 0; i < nFldCmp; i++) { hdf5->readVector(level,fieldNames[i],ip+1,coefs[i]); #if SP_DEBUG > 1 std::cout <<"FieldFuncBase::load: Reading \""<< fieldNames[i] <<"\" ("<< coefs[i].size() <<") for patch "<< ip+1; for (size_t j = 0; j < coefs[i].size(); j++) std::cout << (j%10 ? ' ' : '\n') << coefs[i][j]; std::cout << std::endl; #endif } this->addPatchField(patch[ip],coefs); nOK++; } else std::cerr <<" *** FieldFuncBase::load: No field function created" <<" for patch "<< ip+1 << std::endl; } #endif return nOK == nPatches; }
SPOSetBase* PWOrbitalBuilder::createPW(xmlNodePtr cur, int spinIndex) { int nb=targetPtcl.last(spinIndex)-targetPtcl.first(spinIndex); vector<int> occBand(nb); for(int i=0;i<nb; i++) occBand[i]=i; typedef PWBasis::GIndex_t GIndex_t; GIndex_t nG(1); bool transform2grid=false; cur=cur->children; while(cur != NULL) { string cname((const char*)(cur->name)); if(cname == "transform") { putContent(nG,cur); transform2grid=true; } else if(cname == "occupation") { string occMode("ground"); int bandoffset(1); OhmmsAttributeSet aAttrib; aAttrib.add(spinIndex,"spindataset"); aAttrib.add(occMode,"mode"); aAttrib.add(bandoffset,"offset"); /* reserved for index offset */ aAttrib.put(cur); if(occMode == "excited") { vector<int> occ; vector<int> deleted, added; putContent(occ,cur); for(int i=0; i<occ.size(); i++) { if(occ[i]<0) deleted.push_back(-occ[i]); else added.push_back(occ[i]); } if(deleted.size() != added.size()) { app_error() << " Numbers of deleted and added bands are not identical." << endl; OHMMS::Controller->abort(); } for(int i=0; i<deleted.size(); i++) { occBand[deleted[i]-bandoffset]=added[i]-bandoffset; } app_log() << " mode=\"excited\" Occupied states: " << endl; std::copy(occBand.begin(),occBand.end(),ostream_iterator<int>(app_log()," ")); app_log() << endl; } } cur=cur->next; } string tname=myParam->getTwistName(); hid_t es_grp_id = H5Gopen(hfileID,myParam->eigTag.c_str()); hid_t twist_grp_id = H5Gopen(es_grp_id,tname.c_str()); //create a single-particle orbital set SPOSetType* psi=new SPOSetType; if(transform2grid) { nb=myParam->numBands; occBand.resize(nb); for(int i=0;i<nb; i++) occBand[i]=i; } //going to take care of occ psi->resize(myBasisSet,nb,true); if(myParam->hasComplexData(hfileID))//input is complex { app_log() << " PW coefficients are complex." << endl; typedef std::vector<complex<RealType> > TempVecType; TempVecType coefs(myBasisSet->inputmap.size()); HDFAttribIO<TempVecType> hdfobj_coefs(coefs); int ib=0; while(ib<nb) { string bname(myParam->getBandName(occBand[ib],spinIndex)); app_log() << " Reading " << myParam->eigTag << "/" << tname <<"/"<< bname << endl; hid_t band_grp_id = H5Gopen(twist_grp_id,bname.c_str()); hdfobj_coefs.read(band_grp_id,myParam->eigvecTag.c_str()); psi->addVector(coefs,ib); H5Gclose(band_grp_id); ++ib; } } else { app_log() << " PW coefficients are real." << endl; typedef std::vector<RealType> TempVecType; TempVecType coefs(myBasisSet->inputmap.size()); HDFAttribIO<TempVecType> hdfobj_coefs(coefs); int ib=0; while(ib<nb) { string bname(myParam->getBandName(occBand[ib],spinIndex)); app_log() << " Reading " << myParam->eigTag << "/" << tname <<"/"<< bname << endl; hid_t band_grp_id = H5Gopen(twist_grp_id,bname.c_str()); hdfobj_coefs.read(band_grp_id,myParam->eigvecTag.c_str()); psi->addVector(coefs,ib); H5Gclose(band_grp_id); ++ib; } } H5Gclose(twist_grp_id); H5Gclose(es_grp_id); #if defined(QMC_COMPLEX) if(transform2grid) { app_warning() << " Going to transform on grid " << endl; transform2GridData(nG,spinIndex,*psi); } #endif return psi; }
void test_Matrix_unit2(MPI_Comm comm, int numProcs, int localProc) { if (numProcs > 1) { return; } FEI_COUT << "testing fei::Matrix_Impl..."; fei::SharedPtr<fei::VectorSpace> rowspace(new fei::VectorSpace(comm)); fei::SharedPtr<fei::VectorSpace> colspace; int rowfield = 0, rowfieldsize = 1; int idType = 0; rowspace->defineFields(1, &rowfield, &rowfieldsize); rowspace->defineIDTypes(1, &idType); fei::SharedPtr<fei::MatrixGraph> mgraph(new fei::MatrixGraph_Impl2(rowspace, colspace)); int patternID1 = mgraph->definePattern(2, idType, rowfield); fei::Pattern* rowpattern = mgraph->getPattern(patternID1); mgraph->initConnectivityBlock(0, 1, patternID1); std::vector<int> ids(2); ids[0] = 0; ids[1] = 1; int err = mgraph->initConnectivity(0, 0, &ids[0]); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, initConnectivity returned err="<<err; throw std::runtime_error(osstr.str()); } err = mgraph->initComplete(); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, initComplete returned err="<<err; throw std::runtime_error(osstr.str()); } bool factory_created = false; fei::SharedPtr<fei::Factory> factory; try { factory = fei::create_fei_Factory(comm, "Trilinos"); factory_created = true; } catch(...) {} if (!factory_created) { FEI_COUT << "failed to create Trilinos factory."<<FEI_ENDL; return; } fei::SharedPtr<fei::Matrix> feimat = factory->createMatrix(mgraph); int numrowindices = rowpattern->getNumIndices(); std::vector<double> coefs(numrowindices*numrowindices, 1.0); std::vector<double*> coefs_2D(numrowindices); for(int i=0; i<numrowindices; ++i) { coefs_2D[i] = &(coefs[i*numrowindices]); } err = feimat->sumIn(0, 0, &coefs_2D[0]); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, feimat->sumIn returned err="<<err; throw std::runtime_error(osstr.str()); } err = feimat->globalAssemble(); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, feimat->globalAssemble returned err="<<err; throw std::runtime_error(osstr.str()); } err = feimat->writeToFile("feimat2.mtx", false); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, feimat->writeToFile returned err="<<err; throw std::runtime_error(osstr.str()); } fei::FillableMat feimat_ss; err = fei_test_utils::copy_feiMatrix_to_FillableMat(*feimat, feimat_ss); if (err) { FEI_OSTRINGSTREAM osstr; osstr << "test_Matrix_unit2, copy_feiMatrix_to_FillableMat returned err="<<err; throw std::runtime_error(osstr.str()); } fei_test_utils::writeMatrix("feimat_ss2.mtx", feimat_ss); FEI_COUT << "ok"<<FEI_ENDL; }
Teuchos::RCP<Epetra_CrsGraph> create_epetra_graph(int numProcs, int localProc) { if (localProc == 0) { std::cout << " creating Epetra_CrsGraph with un-even distribution..." << std::endl; } //create an Epetra_CrsGraph with rows spread un-evenly over //processors. Epetra_MpiComm comm(MPI_COMM_WORLD); int local_num_rows = 800; int nnz_per_row = local_num_rows/4+1; int global_num_rows = numProcs*local_num_rows; int mid_proc = numProcs/2; bool num_procs_even = numProcs%2==0 ? true : false; int adjustment = local_num_rows/2; //adjust local_num_rows so that it's not equal on all procs. if (localProc < mid_proc) { local_num_rows -= adjustment; } else { local_num_rows += adjustment; } //if numProcs is not an even number, undo the local_num_rows adjustment //on one proc so that the total will still be correct. if (localProc == numProcs-1) { if (num_procs_even == false) { local_num_rows -= adjustment; } } //now we're ready to create a row-map. Epetra_Map rowmap(global_num_rows, local_num_rows, 0, comm); //create a graph Teuchos::RCP<Epetra_CrsGraph> graph = Teuchos::rcp(new Epetra_CrsGraph(Copy, rowmap, nnz_per_row)); std::vector<int> indices(nnz_per_row); std::vector<double> coefs(nnz_per_row); int err = 0; for(int i=0; i<local_num_rows; ++i) { int global_row = rowmap.GID(i); int first_col = global_row - nnz_per_row/2; if (first_col < 0) { first_col = 0; } else if (first_col > (global_num_rows - nnz_per_row)) { first_col = global_num_rows - nnz_per_row; } for(int j=0; j<nnz_per_row; ++j) { indices[j] = first_col + j; coefs[j] = 1.0; } err = graph->InsertGlobalIndices(global_row, nnz_per_row, &indices[0]); if (err < 0) { throw Isorropia::Exception("create_epetra_graph: error inserting indices in graph"); } } err = graph->FillComplete(); if (err != 0) { throw Isorropia::Exception("create_epetra_graph: error in graph.FillComplete()"); } return(graph); }