Пример #1
0
  void DGFiniteElement<D>:: 
  CalcGradientMatrix (FlatMatrix<> gmat) const
  {
    IntegrationRule ir (this->ElementType(), 2*order);

    Vector<> shape(ndof);
    MatrixFixWidth<D> dshape(ndof);
    Vector<> norms(ndof);
    
    gmat = 0.0;
    norms = 0.0;
    for (int i = 0; i < ir.Size(); i++)
      {
	this -> CalcShape (ir[i], shape);
	this -> CalcDShape (ir[i], dshape);
        
        for (int j = 0; j < ndof; j++)
          for (int k = 0; k < ndof; k++)
            for (int l = 0; l < D; l++)
              gmat(k*D+l, j) += ir[i].Weight() * dshape(j,l) * shape(k);

	for (int j = 0; j < norms.Size(); j++)
	  norms(j) += ir[i].Weight() * sqr (shape(j));
      }
    for (int j = 0; j < ndof; j++)
      gmat.Rows(D*j, D*(j+1)) /= norms(j);
  }
Пример #2
0
  void DGFiniteElement<D>:: 
  CalcTraceMatrix (int facet, FlatMatrix<> trace) const
  {
    ELEMENT_TYPE ftype = ElementTopology::GetFacetType (this->ElementType(), facet);
    Facet2ElementTrafo f2el(this->ElementType(), FlatArray<int> (8, const_cast<int*> (vnums)) );
    const IntegrationRule & ir = SelectIntegrationRule (ftype, 2*order);

    ScalarFiniteElement<0> * facetfe0 = NULL;
    ScalarFiniteElement<1> * facetfe1 = NULL;
    ScalarFiniteElement<2> * facetfe2 = NULL;
    switch (ftype)
      {
      case ET_POINT : facetfe0 = new FE_Point; break;
      case ET_SEGM : facetfe1 = new L2HighOrderFE<ET_SEGM> (order); break;
      case ET_TRIG : facetfe2 = new L2HighOrderFE<ET_TRIG> (order); break;
      case ET_QUAD : facetfe2 = new L2HighOrderFE<ET_QUAD> (order); break;
      default:
	;
      }

    int ndof_facet = trace.Height();
    Vector<> shape(ndof);
    Vector<> fshape(ndof_facet);
    Vector<> norms(ndof_facet);

    trace = 0.0;
    norms = 0.0;
    for (int i = 0; i < ir.Size(); i++)
      {
	if (D == 1) 
          facetfe0 -> CalcShape (ir[i], fshape);
	else if (D == 2) 
          facetfe1 -> CalcShape (ir[i], fshape);
	else            
          facetfe2 -> CalcShape (ir[i], fshape);

	this -> CalcShape (f2el (facet, ir[i]), shape);

	trace += ir[i].Weight() * fshape * Trans (shape);
	for (int j = 0; j < norms.Size(); j++)
	  norms(j) += ir[i].Weight() * sqr (fshape(j));
      }

    for (int j = 0; j < fshape.Size(); j++)
      trace.Row(j) /= norms(j);

    delete facetfe0;
    delete facetfe1;
    delete facetfe2;
  }
Пример #3
0
Wavefront::Wavefront(const LLVolumeFace* face, const LLXform* transform, const LLXform* transform_normals)
:	name("")
{
	class v4adapt
	{
		private:
			LLStrider<LLVector4a> mV4aStrider;
		public:
			v4adapt(LLVector4a* vp){ mV4aStrider = vp; }
			inline LLVector3 operator[] (const unsigned int i)
			{
				return LLVector3((F32*)&mV4aStrider[i]);
			}
	};
	v4adapt verts(face->mPositions);
	for (S32 i = 0; i < face->mNumVertices; ++i)
	{
		LLVector3 v = verts[i];
		vertices.push_back(std::pair<LLVector3, LLVector2>(v, face->mTexCoords[i]));
	}

	if (transform) Transform(vertices, transform);

	v4adapt norms(face->mNormals);
	for (S32 i = 0; i < face->mNumVertices; ++i)
		normals.push_back(norms[i]);

	if (transform_normals) Transform(normals, transform_normals);

	for (S32 i = 0; i < face->mNumIndices/3; ++i)
	{
		triangles.push_back(tri(face->mIndices[i*3+0], face->mIndices[i*3+1], face->mIndices[i*3+2]));
	}
}
Пример #4
0
void
AdaptivityAction::act()
{
  NonlinearSystemBase & system = _problem->getNonlinearSystemBase();

  Adaptivity & adapt = _problem->adaptivity();

  // we don't need to run mesh modifiers *again* after they ran already during the mesh
  // splitting process. Adaptivity::init must be called for any adaptivity to work, however, so we
  // can't just skip it for the useSplit case.
  if (_app.isUseSplit())
    adapt.init(0, 0);
  else
    adapt.init(getParam<unsigned int>("steps"), getParam<unsigned int>("initial_adaptivity"));

  adapt.setErrorEstimator(getParam<MooseEnum>("error_estimator"));

  adapt.setParam("cycles_per_step", getParam<unsigned int>("cycles_per_step"));
  adapt.setParam("refine fraction", getParam<Real>("refine_fraction"));
  adapt.setParam("coarsen fraction", getParam<Real>("coarsen_fraction"));
  adapt.setParam("max h-level", getParam<unsigned int>("max_h_level"));
  adapt.setParam("recompute_markers_during_cycles",
                 getParam<bool>("recompute_markers_during_cycles"));

  adapt.setPrintMeshChanged(getParam<bool>("print_changed_info"));

  const std::vector<std::string> & weight_names =
      getParam<std::vector<std::string>>("weight_names");
  const std::vector<Real> & weight_values = getParam<std::vector<Real>>("weight_values");

  int num_weight_names = weight_names.size();
  int num_weight_values = weight_values.size();

  if (num_weight_names)
  {
    if (num_weight_names != num_weight_values)
      mooseError("Number of weight_names must be equal to number of weight_values in "
                 "Execution/Adaptivity");

    // If weights have been specified then set the default weight to zero
    std::vector<Real> weights(system.nVariables(), 0);

    for (int i = 0; i < num_weight_names; i++)
    {
      std::string name = weight_names[i];
      double value = weight_values[i];

      weights[system.getVariable(0, name).number()] = value;
    }

    std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);

    SystemNorm sys_norm(norms, weights);

    adapt.setErrorNorm(sys_norm);
  }

  adapt.setTimeActive(getParam<Real>("start_time"), getParam<Real>("stop_time"));
  adapt.setInterval(getParam<unsigned int>("interval"));
}
Пример #5
0
	QModelIndex cast( NifModel * nif, const QModelIndex & index )
	{
		QModelIndex iData = getShapeData( nif, index );
		
		QVector<Vector3> verts = nif->getArray<Vector3>( iData, "Vertices" );
		QVector<Triangle> triangles;
		QModelIndex iPoints = nif->getIndex( iData, "Points" );
		if ( iPoints.isValid() )
		{
			QList< QVector< quint16 > > strips;
			for ( int r = 0; r < nif->rowCount( iPoints ); r++ )
				strips.append( nif->getArray<quint16>( iPoints.child( r, 0 ) ) );
			triangles = triangulate( strips );
		}
		else
		{
			triangles = nif->getArray<Triangle>( iData, "Triangles" );
		}
		
		
		QVector<Vector3> norms( verts.count() );
		foreach ( Triangle tri, triangles )
		{
			Vector3 a = verts[ tri[0] ];
			Vector3 b = verts[ tri[1] ];
			Vector3 c = verts[ tri[2] ];
			
			Vector3 fn = Vector3::crossproduct( b - a, c - a );
			norms[ tri[0] ] += fn;
			norms[ tri[1] ] += fn;
			norms[ tri[2] ] += fn;
		}
Пример #6
0
//! Sets an integer indicating the current number of iterations, {\em
//! currentNumIter} to \f$1\f$. Returns \f$0\f$ if successfull, an error message
//! and \f$-1\f$ are returned if no LinearSOE object has been set. 
int XC::CTestRelativeNormUnbalance::start(void)
  {
    int retval= ConvergenceTestNorm::start();
    
    // determine the initial norm .. the the norm of the initial unbalance
    calculatedNormB= getNormB();
    if(currentIter <= maxNumIter) 
      norms(0)= calculatedNormB;
    norm0= calculatedNormB;
    return retval;
  }
Пример #7
0
CompressedFormat Dataset::compute_sim() const
{
    stack::fe_asserter dummy{};
    index_t nnz_sim = 0;
    index_t *starts_sim = nullptr, *index_sim = nullptr;
    double *values_sim = nullptr;
    
    spmm(TRANS::N, TRANS::T,
        n_users, n_items, n_users,
        ratings.nnz(),ratings.values(),ratings.starts(),ratings.index(),
        ratings.nnz(),ratings.values(),ratings.starts(),ratings.index(),
        nnz_sim, values_sim, starts_sim, index_sim);

    #ifndef NDEBUG
    std::cerr << (nnz_sim * 100.0) / n_users / n_users << "% sparsity of sim" << std::endl;
    #endif
    std::function<double(index_t)> norm = [=](index_t row)->double {
        /* for normal cosine similarity */
        // const double *begin = ratings.values() + ratings.starts()[row];
        // const double *end = ratings.values() + ratings.starts()[row + 1];
        // double x = 0; // must be executed serially !
        // double x_c = 0;
        // std::for_each(begin, end, [&](double v){ kahan_accumulate(x, x_c, v * v); });
        // return std::sqrt(x);
        /* for squared cosine similarity */
        return nnz_row(row, ratings.starts());
    };
    // cache the norms
    std::vector<double> norms(n_users);
    for(int user = 0; user < n_users; user ++)
        norms[user] = norm(user);
    // divide
    for(int user = 0; user < n_users; user ++)
    {
        double *ptr = values_sim + starts_sim[user];
        const double *end = values_sim + starts_sim[user + 1];
        const index_t *index = index_sim + starts_sim[user];

        while(ptr != end)
        {
            double divisor = norms[user] * norms[*index];
            if(std::fpclassify(divisor) != FP_ZERO)
                *ptr = *ptr * *ptr / divisor;
                // *ptr /= divisor; // for normal cosine similarity
            index++;
            ptr++;
        }
    }

    return CompressedFormat(n_users, n_users, std::move(values_sim), nnz_sim,
        std::move(starts_sim), ratings.starts_len(), std::move(index_sim));

}
Пример #8
0
Base<F> Coherence( const ElementalMatrix<F>& A )
{
    DEBUG_ONLY(CSE cse("Coherence"))
    DistMatrix<F> B( A );
    DistMatrix<Base<F>,MR,STAR> norms(B.Grid());
    ColumnTwoNorms( B, norms );

    DiagonalSolve( RIGHT, NORMAL, norms, B, true );
    DistMatrix<F> C(B.Grid());
    Identity( C, A.Width(), A.Width() );
    Herk( UPPER, ADJOINT, Base<F>(-1), B, Base<F>(1), C );

    return HermitianMaxNorm( UPPER, C );
}
Пример #9
0
void
AdaptivityAction::act()
{
  NonlinearSystem & system = _problem->getNonlinearSystem();

  Adaptivity & adapt = _problem->adaptivity();

  adapt.init(getParam<unsigned int>("steps"), getParam<unsigned int>("initial_adaptivity"));

  adapt.setErrorEstimator(getParam<MooseEnum>("error_estimator"));

  adapt.setParam("cycles_per_step", getParam<unsigned int>("cycles_per_step"));
  adapt.setParam("refine fraction", getParam<Real>("refine_fraction"));
  adapt.setParam("coarsen fraction", getParam<Real>("coarsen_fraction"));
  adapt.setParam("max h-level", getParam<unsigned int>("max_h_level"));

  adapt.setPrintMeshChanged(getParam<bool>("print_changed_info"));

  const std::vector<std::string> & weight_names = getParam<std::vector<std::string> >("weight_names");
  const std::vector<Real> & weight_values = getParam<std::vector<Real> >("weight_values");

  int num_weight_names  = weight_names.size();
  int num_weight_values = weight_values.size();

  if (num_weight_names)
  {
    if (num_weight_names != num_weight_values)
      mooseError("Number of weight_names must be equal to number of weight_values in Execution/Adaptivity");

    // If weights have been specified then set the default weight to zero
    std::vector<Real> weights(system.nVariables(),0);

    for(int i=0;i<num_weight_names;i++)
    {
      std::string name = weight_names[i];
      double value = weight_values[i];

      weights[system.getVariable(0, name).number()] = value;
    }

    std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);

    SystemNorm sys_norm(norms, weights);

    adapt.setErrorNorm(sys_norm);
  }

  adapt.setTimeActive(getParam<Real>("start_time"), getParam<Real>("stop_time"));
}
Пример #10
0
    StatusType checkStatus(Iteration<SC,MV,OP>* iSolver) {
      // Get residual
      std::vector<MagnitudeType> norms(1);
      Teuchos::RCP<const MV> res = iSolver->getNativeResiduals(&norms);
      MagnitudeType resNorm = norms[0];

      if (curNorm_ == -STS::one()) {
        prevNorm_ = curNorm_ = resNorm;
      } else {
        prevNorm_ = curNorm_;
        curNorm_  = resNorm;
      }

      return Base::checkStatus(iSolver);
    }
Пример #11
0
void Mesh::computeNormals(void) {

  if (normals.size() == vertices.size()) {
    std::cout << "Normals already exist! : " << normals.size() << "\n";
    return;
  }

  clock_t begin, end;
  double elapsed_secs;
  begin = clock();
  std::cout << "Calculating normals begin\n";

  std::vector<Vertex> norms(vertices.size());

  for (auto &t : triangles) {
    Vertex pa, pb, pc;
    Vertex diff1, diff2;
    Vertex trinorm;

    pa = vertices[t.v1];
    pb = vertices[t.v2];
    pc = vertices[t.v3];

    diff1 = pb - pa;
    diff2 = pc - pa;
    trinorm = diff1.Cross(diff2);
    trinorm = trinorm.Normalize();
    trinormals.push_back(trinorm);

    float theta1 = (pb - pa).Angle(pc - pa);
    float theta2 = (pa - pb).Angle(pc - pb);
    float theta3 = (pb - pc).Angle(pa - pc);

    norms[t.v1] = norms[t.v1] + trinorm * t.Area(vertices) * theta1;
    norms[t.v2] = norms[t.v2] + trinorm * t.Area(vertices) * theta2;
    norms[t.v3] = norms[t.v3] + trinorm * t.Area(vertices) * theta3;
  }

  for (auto &n : norms) {
    Vertex v = n.Normalize();
    normals.push_back(v);
  }

  end = clock();
  elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
  std::cout << "Calculating normals end : elapsed time: " << elapsed_secs
            << "\n";
}
    // SmootherBase test
    ST::magnitudeType testApply(const Matrix& A, const SmootherBase & smoother, MultiVector & X, const MultiVector & RHS, Teuchos::FancyOStream & out, bool & success) {
      Array<ST::magnitudeType> norms(1);

      RHS.norm2(norms);
      out << "||RHS|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;

      Teuchos::Array<ST::magnitudeType> initialNorms(1); X.norm2(initialNorms);
      out << "||X_initial|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << initialNorms[0] << std::endl;

      smoother.Apply(X, RHS); // TODO: bool const &InitialGuessIsZero=false

      Teuchos::Array<ST::magnitudeType> finalNorms(1); X.norm2(finalNorms);
      out << "||X_final|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(25) << norms[0] << std::endl;

      Teuchos::Array<ST::magnitudeType> residualNorms = Utils::ResidualNorm(A, X, RHS);
      out << "||Residual|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(20) << residualNorms[0] << std::endl;

      return residualNorms[0];
    }
Пример #13
0
void CModelSurface::UpdateNormals(){
	vector<CVec3> norms( _vertices.size() );
	for( vector<CTriangle>::iterator it=_triangles.begin();it!=_triangles.end();++it ){
		const CTriangle &tri=*it;
		int i0=tri.vertices[0];
		int i1=tri.vertices[1];
		int i2=tri.vertices[2];
		const CVec3 &v0=_vertices[i0].position;
		const CVec3 &v1=_vertices[i1].position;
		const CVec3 &v2=_vertices[i2].position;
		CVec3 normal=CPlane::TrianglePlane( v0,v1,v2 ).n;
		norms[i0]+=normal;
		norms[i1]+=normal;
		norms[i2]+=normal;
	}
	for( int i=0;i<_vertices.size();++i ){
		_vertices[i].normal=norms[i].Normalize();
	}
}
Пример #14
0
    bool BelosAdaptersTestResults(int numIters, RCP<MV> & X, Teuchos::FancyOStream & out, bool & success) {

      // Check numIters
      switch (TestHelpers::Parameters::getDefaultComm()->getSize()) {
        case 0: TEST_EQUALITY(numIters, 5); break;
        case 4:
                // Epetra TEST_EQUALITY(numIters, 6);
                // Tpetra TEST_EQUALITY(numIters, 7);
                break;
        default:;
      }

      // Compute norm of X (using MV traits)
      typedef Belos::MultiVecTraits<Scalar, MV> MVT;
      std::vector<Scalar> norms(1);
      MVT::MvNorm(*X, norms);

      // Test norm equality across the unit tests
      return MueLuTests::BelosAdaptersTestResultsNorm<Scalar>(norms[0]);
    }
    // SmootherBase test
    ST::magnitudeType testApply_X0_RandomRHS(const Matrix& A, const SmootherBase & smoother, Teuchos::FancyOStream & out, bool & success) {
      RCP<MultiVector> X   = MultiVectorFactory::Build(A.getDomainMap(),1);
      RCP<MultiVector> RHS = MultiVectorFactory::Build(A.getRangeMap(),1);

      // Random X
      X->setSeed(846930886);
      X->randomize();

      // Normalize X
      Array<ST::magnitudeType> norms(1); X->norm2(norms);
      X->scale(1/norms[0]);

      // Compute RHS corresponding to X
      A.apply(*X,*RHS, Teuchos::NO_TRANS,(SC)1.0,(SC)0.0);

      // Reset X to 0
      X->putScalar((SC) 0.0);

      return testApply(A, smoother, *X, *RHS, out, success);
    }
int CTestRelativeNormUnbalance::start(void)
{
    if (theSOE == 0) {
        opserr << "WARNING: CTestRelativeNormUnbalance::test() - no SOE returning true\n";
        return -1;
    }
    
    // set iteration count = 1
    norms.Zero();
    currentIter = 1;    
    norm0 = 0.0;
    
    // determine the initial norm .. the the norm of the initial unbalance
    const Vector &x = theSOE->getB();
    double norm = x.pNorm(nType);
    if (currentIter <= maxNumIter) 
        norms(0) = norm;
    norm0 = norm;
    
    return 0;
}
Пример #17
0
// The main program
int main(int argc, char** argv)
{
    // Initialize libMesh
    LibMeshInit init(argc, argv);

    // Parameters
    GetPot infile("fem_system_params.in");
    const Real global_tolerance          = infile("global_tolerance", 0.);
    const unsigned int nelem_target      = infile("n_elements", 400);
    const bool transient                 = infile("transient", true);
    const Real deltat                    = infile("deltat", 0.005);
    unsigned int n_timesteps             = infile("n_timesteps", 1);
    //const unsigned int coarsegridsize    = infile("coarsegridsize", 1);
    const unsigned int coarserefinements = infile("coarserefinements", 0);
    const unsigned int max_adaptivesteps = infile("max_adaptivesteps", 10);
    //const unsigned int dim               = 2;

#ifdef LIBMESH_HAVE_EXODUS_API
    const unsigned int write_interval    = infile("write_interval", 5);
#endif

    // Create a mesh, with dimension to be overridden later, distributed
    // across the default MPI communicator.
    Mesh mesh(init.comm());
    GetPot infileForMesh("convdiff_mprime.in");
    std::string find_mesh_here = infileForMesh("mesh","psiLF_mesh.xda");
    mesh.read(find_mesh_here);

    std::cout << "Read in mesh from: " << find_mesh_here << "\n\n";

    // And an object to refine it
    MeshRefinement mesh_refinement(mesh);
    mesh_refinement.coarsen_by_parents() = true;
    mesh_refinement.absolute_global_tolerance() = global_tolerance;
    mesh_refinement.nelem_target() = nelem_target;
    mesh_refinement.refine_fraction() = 0.3;
    mesh_refinement.coarsen_fraction() = 0.3;
    mesh_refinement.coarsen_threshold() = 0.1;

    //mesh_refinement.uniformly_refine(coarserefinements);

    // Print information about the mesh to the screen.
    mesh.print_info();

    // Create an equation systems object.
    EquationSystems equation_systems (mesh);

    // Name system
    ConvDiff_MprimeSys & system =
        equation_systems.add_system<ConvDiff_MprimeSys>("Diff_ConvDiff_MprimeSys");

    // Steady-state problem
    system.time_solver =
        AutoPtr<TimeSolver>(new SteadySolver(system));

    // Sanity check that we are indeed solving a steady problem
    libmesh_assert_equal_to (n_timesteps, 1);

    // Read in all the equation systems data from the LF solve (system, solutions, rhs, etc)
    std::string find_psiLF_here = infileForMesh("psiLF_file","psiLF.xda");
    std::cout << "Looking for psiLF at: " << find_psiLF_here << "\n\n";

    equation_systems.read(find_psiLF_here, READ,
                          EquationSystems::READ_HEADER |
                          EquationSystems::READ_DATA |
                          EquationSystems::READ_ADDITIONAL_DATA);

    // Check that the norm of the solution read in is what we expect it to be
    Real readin_L2 = system.calculate_norm(*system.solution, 0, L2);
    std::cout << "Read in solution norm: "<< readin_L2 << std::endl << std::endl;

    //DEBUG
    //equation_systems.write("right_back_out.xda", WRITE, EquationSystems::WRITE_DATA |
    //		 EquationSystems::WRITE_ADDITIONAL_DATA);
#ifdef LIBMESH_HAVE_GMV
    //GMVIO(equation_systems.get_mesh()).write_equation_systems(std::string("right_back_out.gmv"), equation_systems);
#endif

    // Initialize the system
    //equation_systems.init ();  //already initialized by read-in

    // And the nonlinear solver options
    NewtonSolver *solver = new NewtonSolver(system);
    system.time_solver->diff_solver() = AutoPtr<DiffSolver>(solver);
    solver->quiet = infile("solver_quiet", true);
    solver->verbose = !solver->quiet;
    solver->max_nonlinear_iterations =
        infile("max_nonlinear_iterations", 15);
    solver->relative_step_tolerance =
        infile("relative_step_tolerance", 1.e-3);
    solver->relative_residual_tolerance =
        infile("relative_residual_tolerance", 0.0);
    solver->absolute_residual_tolerance =
        infile("absolute_residual_tolerance", 0.0);

    // And the linear solver options
    solver->max_linear_iterations =
        infile("max_linear_iterations", 50000);
    solver->initial_linear_tolerance =
        infile("initial_linear_tolerance", 1.e-3);

    // Print information about the system to the screen.
    equation_systems.print_info();

    // Now we begin the timestep loop to compute the time-accurate
    // solution of the equations...not that this is transient, but eh, why not...
    for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
    {
        // A pretty update message
        std::cout << "\n\nSolving time step " << t_step << ", time = "
                  << system.time << std::endl;

        // Adaptively solve the timestep
        unsigned int a_step = 0;
        for (; a_step != max_adaptivesteps; ++a_step)
        {   // VESTIGIAL for now ('vestigial' eh ? ;) )

            std::cout << "\n\n I should be skipped what are you doing here lalalalalalala *!**!*!*!*!*!* \n\n";

            system.solve();
            system.postprocess();
            ErrorVector error;
            AutoPtr<ErrorEstimator> error_estimator;

            // To solve to a tolerance in this problem we
            // need a better estimator than Kelly
            if (global_tolerance != 0.)
            {
                // We can't adapt to both a tolerance and a mesh
                // size at once
                libmesh_assert_equal_to (nelem_target, 0);

                UniformRefinementEstimator *u =
                    new UniformRefinementEstimator;

                // The lid-driven cavity problem isn't in H1, so
                // lets estimate L2 error
                u->error_norm = L2;

                error_estimator.reset(u);
            }
            else
            {
                // If we aren't adapting to a tolerance we need a
                // target mesh size
                libmesh_assert_greater (nelem_target, 0);

                // Kelly is a lousy estimator to use for a problem
                // not in H1 - if we were doing more than a few
                // timesteps we'd need to turn off or limit the
                // maximum level of our adaptivity eventually
                error_estimator.reset(new KellyErrorEstimator);
            }

            // Calculate error
            std::vector<Real> weights(9,1.0);  // based on u, v, p, c, their adjoints, and source parameter

            // Keep the same default norm type.
            std::vector<FEMNormType>
            norms(1, error_estimator->error_norm.type(0));
            error_estimator->error_norm = SystemNorm(norms, weights);

            error_estimator->estimate_error(system, error);

            // Print out status at each adaptive step.
            Real global_error = error.l2_norm();
            std::cout << "Adaptive step " << a_step << ": " << std::endl;
            if (global_tolerance != 0.)
                std::cout << "Global_error = " << global_error
                          << std::endl;
            if (global_tolerance != 0.)
                std::cout << "Worst element error = " << error.maximum()
                          << ", mean = " << error.mean() << std::endl;

            if (global_tolerance != 0.)
            {
                // If we've reached our desired tolerance, we
                // don't need any more adaptive steps
                if (global_error < global_tolerance)
                    break;
                mesh_refinement.flag_elements_by_error_tolerance(error);
            }
            else
            {
                // If flag_elements_by_nelem_target returns true, this
                // should be our last adaptive step.
                if (mesh_refinement.flag_elements_by_nelem_target(error))
                {
                    mesh_refinement.refine_and_coarsen_elements();
                    equation_systems.reinit();
                    a_step = max_adaptivesteps;
                    break;
                }
            }

            // Carry out the adaptive mesh refinement/coarsening
            mesh_refinement.refine_and_coarsen_elements();
            equation_systems.reinit();

            std::cout << "Refined mesh to "
                      << mesh.n_active_elem()
                      << " active elements and "
                      << equation_systems.n_active_dofs()
                      << " active dofs." << std::endl;
        } // End loop over adaptive steps

        // Do one last solve if necessary
        if (a_step == max_adaptivesteps)
        {
            QoISet qois;
            std::vector<unsigned int> qoi_indices;

            qoi_indices.push_back(0);
            qois.add_indices(qoi_indices);

            qois.set_weight(0, 1.0);

            system.assemble_qoi_sides = true; //QoI doesn't involve sides

            std::cout << "\n~*~*~*~*~*~*~*~*~ adjoint solve start ~*~*~*~*~*~*~*~*~\n" << std::endl;
            std::pair<unsigned int, Real> adjsolve = system.adjoint_solve();
            std::cout << "number of iterations to solve adjoint: " << adjsolve.first << std::endl;
            std::cout << "final residual of adjoint solve: " << adjsolve.second << std::endl;
            std::cout << "\n~*~*~*~*~*~*~*~*~ adjoint solve end ~*~*~*~*~*~*~*~*~" << std::endl;

            NumericVector<Number> &dual_solution = system.get_adjoint_solution(0);
            NumericVector<Number> &primal_solution = *system.solution;

            primal_solution.swap(dual_solution);
            ExodusII_IO(mesh).write_timestep("super_adjoint.exo",
                                             equation_systems,
                                             1, /* This number indicates how many time steps
	                                       are being written to the file */
                                             system.time);
            primal_solution.swap(dual_solution);

            system.assemble(); //overwrite residual read in from psiLF solve

            // The total error estimate
            system.postprocess(); //to compute M_HF(psiLF) and M_LF(psiLF) terms
            Real QoI_error_estimate = (-0.5*(system.rhs)->dot(dual_solution)) + system.get_MHF_psiLF() - system.get_MLF_psiLF();
            std::cout << "\n\n 0.5*M'_HF(psiLF)(superadj): " << std::setprecision(17) << 0.5*(system.rhs)->dot(dual_solution) << "\n";
            std::cout << " M_HF(psiLF): " << std::setprecision(17) << system.get_MHF_psiLF() << "\n";
            std::cout << " M_LF(psiLF): " << std::setprecision(17) << system.get_MLF_psiLF() << "\n";
            std::cout << "\n\n Residual L2 norm: " << system.calculate_norm(*system.rhs, L2) << "\n";
            std::cout << " Residual discrete L2 norm: " << system.calculate_norm(*system.rhs, DISCRETE_L2) << "\n";
            std::cout << " Super-adjoint L2 norm: " << system.calculate_norm(dual_solution, L2) << "\n";
            std::cout << " Super-adjoint discrete L2 norm: " << system.calculate_norm(dual_solution, DISCRETE_L2) << "\n";
            std::cout << "\n\n QoI error estimate: " << std::setprecision(17) << QoI_error_estimate << "\n\n";

            //DEBUG
            std::cout << "\n------------ herp derp ------------" << std::endl;
            //libMesh::out.precision(16);
            //dual_solution.print();
            //system.get_adjoint_rhs().print();

            AutoPtr<NumericVector<Number> > adjresid = system.solution->clone();
            (system.matrix)->vector_mult(*adjresid,system.get_adjoint_solution(0));
            SparseMatrix<Number>& adjmat = *system.matrix;
            (system.matrix)->get_transpose(adjmat);
            adjmat.vector_mult(*adjresid,system.get_adjoint_solution(0));
            //std::cout << "******************** matrix-superadj product (libmesh) ************************" << std::endl;
            //adjresid->print();
            adjresid->add(-1.0, system.get_adjoint_rhs(0));
            //std::cout << "******************** superadjoint system residual (libmesh) ***********************" << std::endl;
            //adjresid->print();
            std::cout << "\n\nadjoint system residual (discrete L2): " << system.calculate_norm(*adjresid,DISCRETE_L2) << std::endl;
            std::cout << "adjoint system residual (L2, all): " << system.calculate_norm(*adjresid,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 0): " << system.calculate_norm(*adjresid,0,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 1): " << system.calculate_norm(*adjresid,1,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 2): " << system.calculate_norm(*adjresid,2,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 3): " << system.calculate_norm(*adjresid,3,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 4): " << system.calculate_norm(*adjresid,4,L2) << std::endl;
            std::cout << "adjoint system residual (L2, 5): " << system.calculate_norm(*adjresid,5,L2) << std::endl;
            /*
            	AutoPtr<NumericVector<Number> > sadj_matlab = system.solution->clone();
            	AutoPtr<NumericVector<Number> > adjresid_matlab = system.solution->clone();
            	if(FILE *fp=fopen("superadj_matlab.txt","r")){
              	Real value;
              	int counter = 0;
              	int flag = 1;
              	while(flag != -1){
              		flag = fscanf(fp,"%lf",&value);
              		if(flag != -1){
            				sadj_matlab->set(counter, value);
            				counter += 1;
              		}
              	}
              	fclose(fp);
            	}
            	(system.matrix)->vector_mult(*adjresid_matlab,*sadj_matlab);
            	//std::cout << "******************** matrix-superadj product (matlab) ***********************" << std::endl;
            	//adjresid_matlab->print();
            	adjresid_matlab->add(-1.0, system.get_adjoint_rhs(0));
            	//std::cout << "******************** superadjoint system residual (matlab) ***********************" << std::endl;
            	//adjresid_matlab->print();
            	std::cout << "\n\nmatlab import adjoint system residual (discrete L2): " << system.calculate_norm(*adjresid_matlab,DISCRETE_L2) << "\n" << std::endl;
            */
            /*
            	AutoPtr<NumericVector<Number> > sadj_fwd_hack = system.solution->clone();
            	AutoPtr<NumericVector<Number> > adjresid_fwd_hack = system.solution->clone();
            	if(FILE *fp=fopen("superadj_forward_hack.txt","r")){
              	Real value;
              	int counter = 0;
              	int flag = 1;
              	while(flag != -1){
              		flag = fscanf(fp,"%lf",&value);
              		if(flag != -1){
            				sadj_fwd_hack->set(counter, value);
            				counter += 1;
              		}
              	}
              	fclose(fp);
            	}
            	(system.matrix)->vector_mult(*adjresid_fwd_hack,*sadj_fwd_hack);
            	//std::cout << "******************** matrix-superadj product (fwd_hack) ***********************" << std::endl;
            	//adjresid_fwd_hack->print();
            	adjresid_fwd_hack->add(-1.0, system.get_adjoint_rhs(0));
            	//std::cout << "******************** superadjoint system residual (fwd_hack) ***********************" << std::endl;
            	//adjresid_fwd_hack->print();
            	std::cout << "\n\nfwd_hack import adjoint system residual (discrete L2): " << system.calculate_norm(*adjresid_fwd_hack,DISCRETE_L2) << "\n" << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 0): " << system.calculate_norm(*adjresid_fwd_hack,0,L2) << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 1): " << system.calculate_norm(*adjresid_fwd_hack,1,L2) << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 2): " << system.calculate_norm(*adjresid_fwd_hack,2,L2) << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 3): " << system.calculate_norm(*adjresid_fwd_hack,3,L2) << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 4): " << system.calculate_norm(*adjresid_fwd_hack,4,L2) << std::endl;
            	std::cout << "fwd_hack adjoint system residual (L2, 5): " << system.calculate_norm(*adjresid_fwd_hack,5,L2) << std::endl;
            */
            //std::cout << "************************ system.matrix ***********************" << std::endl;
            //system.matrix->print();

            std::cout << "\n------------ herp derp ------------" << std::endl;

            // The cell wise breakdown
            ErrorVector cell_wise_error;
            cell_wise_error.resize((system.rhs)->size());
            for(unsigned int i = 0; i < (system.rhs)->size() ; i++)
            {
                if(i < system.get_mesh().n_elem())
                    cell_wise_error[i] = fabs(-0.5*((system.rhs)->el(i) * dual_solution(i))
                                              + system.get_MHF_psiLF(i) - system.get_MLF_psiLF(i));
                else
                    cell_wise_error[i] = fabs(-0.5*((system.rhs)->el(i) * dual_solution(i)));

                /*csv from 'save data' from gmv output gives a few values at each node point (value
                for every element that shares that node), yet paraview display only seems to show one
                of them -> the value in an element is given at each of the nodes that it has, hence the
                repetition; what is displayed in paraview is each element's value; even though MHF_psiLF
                and MLF_psiLF are stored by element this seems to give elemental contributions that
                agree with if we had taken the superadj-residual dot product by integrating over elements*/

                /*at higher mesh resolutions and lower k, weird-looking artifacts start to appear and
                it no longer agrees with output from manual integration of superadj-residual...*/
            }
            // Plot it
            std::ostringstream error_gmv;
            error_gmv << "error.gmv";
            cell_wise_error.plot_error(error_gmv.str(), equation_systems.get_mesh());

            //alternate element-wise breakdown, outputed as values matched to element centroids; for matlab plotz
            primal_solution.swap(dual_solution);
            system.postprocess(1);
            primal_solution.swap(dual_solution);
            system.postprocess(2);
            std::cout << "\n\n -0.5*M'_HF(psiLF)(superadj): " << std::setprecision(17) << system.get_half_adj_weighted_resid() << "\n";
            primal_solution.swap(dual_solution);

            std::string write_error_here = infileForMesh("error_est_output_file", "error_est_breakdown.dat");
            std::ofstream output(write_error_here);
            for(unsigned int i = 0 ; i < system.get_mesh().n_elem(); i++) {
                Point elem_cent = system.get_mesh().elem(i)->centroid();
                if(output.is_open()) {
                    output << elem_cent(0) << " " << elem_cent(1) << " "
                           << fabs(system.get_half_adj_weighted_resid(i) + system.get_MHF_psiLF(i) - system.get_MLF_psiLF(i)) << "\n";
                }
            }
            output.close();

        } // End if at max adaptive steps

#ifdef LIBMESH_HAVE_EXODUS_API
        // Write out this timestep if we're requested to
        if ((t_step+1)%write_interval == 0)
        {
            std::ostringstream file_name;
            /*
                // We write the file in the ExodusII format.
                file_name << "out_"
                          << std::setw(3)
                          << std::setfill('0')
                          << std::right
                          << t_step+1
                          << ".e";
            			//this should write out the primal which should be the same as what's read in...
            			ExodusII_IO(mesh).write_timestep(file_name.str(),
            							                        equation_systems,
            							                        1, //number of time steps written to file
            							                        system.time);
            */
        }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
    }

    // All done.
    return 0;

} //end main
Пример #18
0
bool NFFParser::readFile() const{
	
	ifstream input(fileLocation, ios::in);
	if (!input.good()){
		std::cout << "Can't find my file!\n";
		return false;
	}

	if (!input){
		cout << "Unable to open file";
		return false;
	}
	else{
		std::string line;
		while (getline(input, line)){
			std::vector<std::string> splitLine = split(line, ' ');
			std::string command = splitLine[0];
			if (command == "s"){
				Vec3f center = read3DVector(splitLine);
				float radius = static_cast<float>(atof(splitLine[4].c_str()));
				Sphere* s = new Sphere(center, radius);
				SceneObject* so = new SceneObject(scene->materialIndex, s);

				scene->octree->insertShape(so, scene->octree->root, 0);
			}
			else if (command == "c"){
				float baseX = static_cast<float>(atof(splitLine[1].c_str()));
				float baseY = static_cast<float>(atof(splitLine[2].c_str()));
				float baseZ = static_cast<float>(atof(splitLine[3].c_str()));
				float baseRadius = static_cast<float>(atof(splitLine[4].c_str()));
				Vec3f base = Vec3f(baseX, baseY, baseZ);

				float apexX = static_cast<float>(atof(splitLine[5].c_str()));
				float apexY = static_cast<float>(atof(splitLine[6].c_str()));
				float apexZ = static_cast<float>(atof(splitLine[7].c_str()));
				float apexRadius = static_cast<float>(atof(splitLine[8].c_str()));
				Vec3f apex = Vec3f(apexX, apexY, apexZ);

				if (baseRadius == apexRadius){
					Cylinder* c = new Cylinder(base, apex, baseRadius);
					SceneObject* so = new SceneObject(scene->materialIndex, static_cast<Primitive*>(c));
					scene->octree->insertShape(so, scene->octree->root, 0);
				}
				else{
					// @TODO  cone code
				}
			}
			else if (command == "p"){
				int numVerts = atoi(splitLine[1].c_str());
				if (numVerts >= 3){
					std::vector<Vec3f> verts(numVerts);
					for (int i = 0; i < numVerts; i++){
						getline(input, line);
						std::vector<std::string> splitLine = split(line, ' ');
						verts[i] = read3DVector(splitLine);
					}
					Polygon* poly = new Polygon(verts);
					std::vector<Triangle*> triangles = poly->triangles;
					for (std::vector<int>::size_type itr = 0; itr != triangles.size(); itr++) {
						Triangle* t = triangles[itr];
						SceneObject* so = new SceneObject(scene->materialIndex, static_cast<Primitive*>(t));
						scene->octree->insertShape(so, scene->octree->root, 0);
					}
				}
			}
			else if (command == "pp"){
				int numVerts = atoi(splitLine[1].c_str());
				if (numVerts >= 3){
					std::vector<Vec3f> verts(numVerts);
					std::vector<Vec3f> norms(numVerts);
					for (int i = 0; i < numVerts; i++){
						getline(input, line);
						std::vector<std::string> splitLine = split(line, ' ');
						float x = static_cast<float>(atof(splitLine[0].c_str()));
						float y = static_cast<float>(atof(splitLine[1].c_str()));
						float z = static_cast<float>(atof(splitLine[2].c_str()));
						verts.push_back(Vec3f(x, y, z));

						float nx = static_cast<float>(atof(splitLine[3].c_str()));
						float ny = static_cast<float>(atof(splitLine[4].c_str()));
						float nz = static_cast<float>(atof(splitLine[5].c_str()));
						norms.push_back(Vec3f(nx, ny, nz));
					}

					Vec3f n = Vec3f(0.f, 0.f, 0.f);
					for (std::vector<int>::size_type itr = 0; itr != norms.size(); itr++) {
						n += norms[itr];
					}
					n /= 3.f;
					Triangle* t = new Triangle(verts[0], verts[1], verts[2], n);
					SceneObject* so = new SceneObject(scene->materialIndex, static_cast<Primitive*>(t));
					scene->octree->insertShape(so, scene->octree->root, 0);
				}
			}
			else if (command == "v"){
				for (int i = 0; i < 6; i++){
					getline(input, line);
					std::vector<std::string> splitLine = split(line, ' ');
					std::string command = splitLine[0];
					if (command == "from"){
						scene->from = read3DVector(splitLine);
					}
					else if (command == "at"){
						scene->at = read3DVector(splitLine);
					}
					else if (command == "up"){
						scene->up = read3DVector(splitLine);
					}
					else if (command == "angle"){
						scene->fov =static_cast<float>(atof(splitLine[1].c_str()));
					}
					else if (command == "hither"){
						scene->hither = static_cast<float>(atof(splitLine[1].c_str()));
					}
					else if (command == "resolution"){
						scene->screenWidth = std::stoi(splitLine[1]);
						scene->screenHeight = std::stoi(splitLine[1]);
					}
				}
			}
			else if (command == "b"){
				scene->bg = read3DVector(splitLine);
			}
			else if (command == "l"){
				Light* const l = new Light(read3DVector(splitLine));
				scene->lights.push_back(l);
			}
			else if (command == "f"){
				float red = static_cast<float>(atof(splitLine[1].c_str()));
				float green = static_cast<float>(atof(splitLine[2].c_str()));
				float blue = static_cast<float>(atof(splitLine[3].c_str()));
				float kd = static_cast<float>(atof(splitLine[4].c_str()));
				float ks = static_cast<float>(atof(splitLine[5].c_str()));
				float shine = static_cast<float>(atof(splitLine[6].c_str()));
				float T = static_cast<float>(atof(splitLine[7].c_str()));
				float refraction = static_cast<float>(atof(splitLine[8].c_str()));
				Material* m = new Material(red, green, blue, kd, ks, shine, T, refraction);
				++scene->materialIndex; // incrementation here on purpose
				scene->materials.push_back(m);

			}
		}
		printf("File reading done.\n");

		input.close();
	}

	return true;
}
Пример #19
0
int CTestNormUnbalance::test(void)
{
    // check to ensure the SOE has been set - this should not happen if the 
    // return from start() is checked
    if (theSOE == 0)
        return -2;
    
    // check to ensure the algo does invoke start() - this is needed otherwise
    // may never get convergence later on in analysis!
    if (currentIter == 0) {
        opserr << "WARNING: CTestNormUnbalance::test() - start() was never invoked.\n";	
        return -2;
    }
    
    // get the B vector & determine it's norm & save the value in norms vector
    const Vector &x = theSOE->getB();
    double norm = x.pNorm(nType);
    if (currentIter <= maxNumIter) 
        norms(currentIter-1) = norm;

    if(currentIter > 1) {
        if(norms(currentIter-2) < norm) {
            numIncr++;
        }
    }
    
    // print the data if required
    if (printFlag == 1) {
        opserr << "CTestNormUnbalance::test() - iteration: " << currentIter;
        opserr << " current Norm: " << norm << " (max: " << tol;
        opserr << ", Norm deltaX: " << theSOE->getX().pNorm(nType) << ")\n";
    }
    if (printFlag == 4) {
        opserr << "CTestNormUnbalance::test() - iteration: " << currentIter;
        opserr << " current Norm: " << norm << " (max: " << tol << ")\n";
        opserr << "\tNorm deltaX: " << theSOE->getX().pNorm(nType) << ", Norm deltaR: " << norm << endln;
        opserr << "\tdeltaX: " << theSOE->getX() << "\tdeltaR: " << x;
    }
    
    //
    // check if the algorithm converged
    //
    
    // if converged - print & return ok
    if (norm <= tol) {
        
        // do some printing first
        if (printFlag != 0) {
            if (printFlag == 1 || printFlag == 4) 
                opserr << endln;
            else if (printFlag == 2 || printFlag == 6) {
                opserr << "CTestNormUnbalance::test() - iteration: " << currentIter;
                opserr << " current Norm: " << norm << " (max: " << tol;
                opserr << ", Norm deltaX: " << theSOE->getX().pNorm(nType) << ")\n";
            }
        }
        
        // return the number of times test has been called
        return currentIter;
    } 
    
    // algo failed to converged after specified number of iterations - but RETURN OK
    else if ((printFlag == 5 || printFlag == 6) && (currentIter >= maxNumIter||numIncr>=maxIncr)) {
        opserr << "WARNING: CTestNormUnbalance::test() - failed to converge but going on -";
        opserr << " current Norm: " << norm << " (max: " << tol;
        opserr << ", Norm deltaX: " << theSOE->getX().pNorm(nType) << ")\n";
        return currentIter;
    }
    
    // algo failed to converged after specified number of iterations - return FAILURE -2
    else if (currentIter >= maxNumIter || numIncr >= maxIncr || norm > maxTol) { // the algorithm failed to converge
        opserr << "WARNING: CTestNormUnbalance::test() - failed to converge \n";
        opserr << "after: " << currentIter << " iterations\n";	
        currentIter++;  // we increment in case analysis does not check for convergence
        return -2;
    } 
    
    // algorithm not yet converged - increment counter and return -1
    else {
        currentIter++;    
        return -1;
    }
}
Пример #20
0
  // Tests two sweeps of ILUT in Ifpack2
  TEUCHOS_UNIT_TEST_TEMPLATE_4_DECL(Ifpack2Smoother, ILU_TwoSweeps, Scalar, LocalOrdinal, GlobalOrdinal, Node)
  {
#   include <MueLu_UseShortNames.hpp>
    MUELU_TESTING_SET_OSTREAM;
    MUELU_TESTING_LIMIT_EPETRA_SCOPE(Scalar,GlobalOrdinal,Node);
    typedef typename Teuchos::ScalarTraits<SC>::magnitudeType magnitude_type;
    MUELU_TEST_ONLY_FOR(Xpetra::UseTpetra) {

      //FIXME this will probably fail in parallel b/c it becomes block Jacobi

      Teuchos::ParameterList paramList;
      Ifpack2Smoother smoother("ILUT",paramList);

      //I don't use the testApply infrastructure because it has no provision for an initial guess.
      Teuchos::RCP<Matrix> A = TestHelpers::TestFactory<SC, LO, GO, NO>::Build1DPoisson(125);
      Level level; TestHelpers::TestFactory<SC,LO,GO,NO>::createSingleLevelHierarchy(level);
      level.Set("A", A);
      smoother.Setup(level);

      RCP<MultiVector> X   = MultiVectorFactory::Build(A->getDomainMap(),1);
      RCP<MultiVector> RHS = MultiVectorFactory::Build(A->getRangeMap(),1);

      // Random X
      X->setSeed(846930886);
      X->randomize();

      // Normalize X
      Array<magnitude_type> norms(1); X->norm2(norms);
      X->scale(1/norms[0]);

      // Compute RHS corresponding to X
      A->apply(*X,*RHS, Teuchos::NO_TRANS,(SC)1.0,(SC)0.0);

      // Reset X to 0
      X->putScalar((SC) 0.0);

      RHS->norm2(norms);
      out << "||RHS|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;

      out << "solve with zero initial guess" << std::endl;
      Teuchos::Array<magnitude_type> initialNorms(1); X->norm2(initialNorms);
      out << "  ||X_initial|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << initialNorms[0] << std::endl;

      smoother.Apply(*X, *RHS, true);  //zero initial guess

      Teuchos::Array<magnitude_type> finalNorms(1); X->norm2(finalNorms);
      Teuchos::Array<magnitude_type> residualNorm1 = Utilities::ResidualNorm(*A, *X, *RHS);
      out << "  ||Residual_final|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(20) << residualNorm1[0] << std::endl;
      out << "  ||X_final|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << finalNorms[0] << std::endl;

      out << "solve with random initial guess" << std::endl;
      X->randomize();
      X->norm2(initialNorms);
      out << "  ||X_initial|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << initialNorms[0] << std::endl;

      smoother.Apply(*X, *RHS, false); //nonzero initial guess

      X->norm2(finalNorms);
      Teuchos::Array<magnitude_type> residualNorm2 = Utilities::ResidualNorm(*A, *X, *RHS);
      out << "  ||Residual_final|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(20) << residualNorm2[0] << std::endl;
      out << "  ||X_final|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << finalNorms[0] << std::endl;

      RCP<const Teuchos::Comm<int> > comm = TestHelpers::Parameters::getDefaultComm();
      if (comm->getSize() == 1) {
        //TEST_EQUALITY(residualNorms < 1e-10, true);
        TEST_EQUALITY(residualNorm1[0] != residualNorm2[0], true);
      } else {
        out << "Pass/Fail is only checked in serial." << std::endl;
      }

    }
  } // ILU
Пример #21
0
int main(int argc, char **argv)
{
#ifdef QUESO_HAVE_LIBMESH
  unsigned int i, j;
  QUESO::EnvOptionsValues opts;
  opts.m_seed = -1;

#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", &opts);
#else
  QUESO::FullEnvironment env("", "", &opts);
#endif

#ifdef LIBMESH_DEFAULT_SINGLE_PRECISION
  // SLEPc currently gives us a nasty crash with Real==float
  libmesh_example_assert(false, "--disable-singleprecision");
#endif

// Need an artificial block here because libmesh needs to
// call PetscFinalize before we call MPI_Finalize
#ifdef LIBMESH_HAVE_SLEPC
{
  libMesh::LibMeshInit init(argc, argv);

  libMesh::Mesh mesh(init.comm());
  libMesh::MeshTools::Generation::build_square(mesh,
      20, 20, 0.0, 1.0, 0.0, 1.0, libMeshEnums::QUAD4);

  QUESO::FunctionOperatorBuilder builder;

  builder.order = "FIRST";
  builder.family = "LAGRANGE";
  builder.num_req_eigenpairs = 10;

  QUESO::LibMeshNegativeLaplacianOperator precision(builder, mesh);

  libMesh::EquationSystems & es = precision.get_equation_systems();
  libMesh::CondensedEigenSystem & eig_sys = es.get_system<libMesh::CondensedEigenSystem>(
      "Eigensystem");

  // Check all eigenfunctions have unit L2 norm
  std::vector<double> norms(builder.num_req_eigenpairs, 0);
  for (i = 0; i < builder.num_req_eigenpairs; i++) {
    eig_sys.get_eigenpair(i);
    norms[i] = eig_sys.calculate_norm(*eig_sys.solution,
                                      libMesh::SystemNorm(libMeshEnums::L2));
    if (abs(norms[i] - 1.0) > TEST_TOL) {
      return 1;
    }
  }

  const unsigned int dim = mesh.mesh_dimension();
  const libMesh::DofMap & dof_map = eig_sys.get_dof_map();
  libMesh::FEType fe_type = dof_map.variable_type(0);
  libMesh::AutoPtr<libMesh::FEBase> fe(libMesh::FEBase::build(dim, fe_type));
  libMesh::QGauss qrule(dim, libMeshEnums::FIFTH);
  fe->attach_quadrature_rule(&qrule);
  const std::vector<libMesh::Real> & JxW = fe->get_JxW();
  const std::vector<std::vector<libMesh::Real> >& phi = fe->get_phi();

  libMesh::AutoPtr<libMesh::NumericVector<libMesh::Real> > u, v;
  double ui = 0.0;
  double vj = 0.0;
  double ip = 0.0;

  for (i = 0; i < builder.num_req_eigenpairs - 1; i++) {
    eig_sys.get_eigenpair(i);
    u = eig_sys.solution->clone();
    for (j = i + 1; j < builder.num_req_eigenpairs; j++) {
      libMesh::MeshBase::const_element_iterator el = mesh.active_local_elements_begin();
      libMesh::MeshBase::const_element_iterator end_el = mesh.active_local_elements_end();
      eig_sys.get_eigenpair(j);
      v = eig_sys.solution->clone();
      for ( ; el != end_el; ++el) {
        const libMesh::Elem * elem = *el;
        fe->reinit(elem);
        for (unsigned int qp = 0; qp < qrule.n_points(); qp++) {
          for (unsigned int dof = 0; dof < phi.size(); dof++) {
            ui += (*u)(dof) * phi[dof][qp];
            vj += (*v)(dof) * phi[dof][qp];
          }
          ip += ui * vj * JxW[qp];
          ui = 0.0;
          vj = 0.0;
        }
      }
      std::cerr << "INTEGRAL of " << i << " against " << j << " is: " << ip << std::endl;
      if (abs(ip) > INTEGRATE_TOL) {
        return 1;
      }
      ip = 0.0;
    }
  }
}
#endif  // LIBMESH_HAVE_SLEPC
#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif
  return 0;
#else
  return 77;
#endif
}
Пример #22
0
  TEUCHOS_UNIT_TEST(GenericRFactory, SymmetricProblem)
  {
    out << "version: " << MueLu::Version() << std::endl;
    RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

    // generate problem
    LO maxLevels = 3;
    LO nEle = 63;
    const RCP<const Map> map = MapFactory::Build(TestHelpers::Parameters::getLib(), nEle, 0, comm);
    Teuchos::ParameterList matrixParameters;
    matrixParameters.set("nx",nEle);

    RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
      Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>("Laplace1D", map, matrixParameters);
    RCP<Matrix> Op = Pr->BuildMatrix();

    // build nullspace
    RCP<MultiVector> nullSpace = MultiVectorFactory::Build(map,1);
    nullSpace->putScalar( (SC) 1.0);
    Teuchos::Array<Teuchos::ScalarTraits<SC>::magnitudeType> norms(1);
    nullSpace->norm1(norms);
    if (comm->getRank() == 0)
      out << "||NS|| = " << norms[0] << std::endl;

    // fill hierarchy
    RCP<Hierarchy> H = rcp( new Hierarchy() );
    H->setDefaultVerbLevel(Teuchos::VERB_HIGH);

    RCP<Level> Finest = H->GetLevel();
    Finest->setDefaultVerbLevel(Teuchos::VERB_HIGH);
    Finest->Set("A",Op);                      // set fine level matrix
    Finest->Set("Nullspace",nullSpace);       // set null space information for finest level

    // define transfer operators
    RCP<CoupledAggregationFactory> CoupledAggFact = rcp(new CoupledAggregationFactory());
    CoupledAggFact->SetMinNodesPerAggregate(3);
    CoupledAggFact->SetMaxNeighAlreadySelected(0);
    CoupledAggFact->SetOrdering("natural");
    CoupledAggFact->SetPhase3AggCreation(0.5);

    RCP<SaPFactory>         Pfact = rcp( new SaPFactory());
    RCP<Factory>           Rfact = rcp( new GenericRFactory() );
    H->SetMaxCoarseSize(1);

    // setup smoothers
    Teuchos::ParameterList smootherParamList;
    smootherParamList.set("relaxation: type", "Symmetric Gauss-Seidel");
    smootherParamList.set("relaxation: sweeps", (LO) 1);
    smootherParamList.set("relaxation: damping factor", (SC) 1.0);
    RCP<SmootherPrototype> smooProto = rcp( new TrilinosSmoother("RELAXATION", smootherParamList) );
    RCP<SmootherFactory> SmooFact = rcp( new SmootherFactory(smooProto) );
    //Acfact->setVerbLevel(Teuchos::VERB_HIGH);

    RCP<SmootherFactory> coarseSolveFact = rcp(new SmootherFactory(smooProto, Teuchos::null));

    FactoryManager M;
    M.SetFactory("P", Pfact);
    M.SetFactory("R", Rfact);
    M.SetFactory("Aggregates", CoupledAggFact);
    M.SetFactory("Smoother", SmooFact);
    M.SetFactory("CoarseSolver", coarseSolveFact);

    H->Setup(M, 0, maxLevels);

    RCP<Level> coarseLevel = H->GetLevel(1);
    RCP<Matrix> P1 = coarseLevel->Get< RCP<Matrix> >("P");
    RCP<Matrix> R1 = coarseLevel->Get< RCP<Matrix> >("R");
    RCP<Level> coarseLevel2 = H->GetLevel(2);
    RCP<Matrix> P2 = coarseLevel2->Get< RCP<Matrix> >("P");
    RCP<Matrix> R2 = coarseLevel2->Get< RCP<Matrix> >("R");

    TEST_EQUALITY(Finest->IsAvailable("PreSmoother"), true);
    TEST_EQUALITY(Finest->IsAvailable("PostSmoother"), true);
    TEST_EQUALITY(coarseLevel->IsAvailable("PreSmoother"), true);
    TEST_EQUALITY(coarseLevel->IsAvailable("PostSmoother"), true);
    TEST_EQUALITY(coarseLevel2->IsAvailable("PreSmoother"), true);
    TEST_EQUALITY(coarseLevel2->IsAvailable("PostSmoother"), false);

    // test some basic multgrid data
    TEST_EQUALITY(P1->getGlobalNumEntries(), R1->getGlobalNumEntries());
    TEST_EQUALITY(P1->getGlobalNumRows(), R1->getGlobalNumCols());
    TEST_EQUALITY(P1->getGlobalNumCols(), R1->getGlobalNumRows());
    TEST_EQUALITY(P2->getGlobalNumEntries(), R2->getGlobalNumEntries());
    TEST_EQUALITY(P2->getGlobalNumRows(), R2->getGlobalNumCols());
    TEST_EQUALITY(P2->getGlobalNumCols(), R2->getGlobalNumRows());


    //RCP<Teuchos::FancyOStream> fos = getFancyOStream(Teuchos::rcpFromRef(cout));

    // since A is chosen symmetric, it is P^T = R
    // check P^T * P = R * P
    // note: the Epetra matrix-matrix multiplication using implicit transpose is buggy in parallel case
    //       (for multiplication of a square matrix with a rectangular matrix)
    //       however it seems to work for two rectangular matrices
    Teuchos::RCP<Xpetra::Matrix<Scalar,LO,GO,Node> > RP = Xpetra::MatrixMatrix<Scalar,LO,GO,Node>::Multiply(*R1,false,*P1,false,out);
    Teuchos::RCP<Xpetra::Matrix<Scalar,LO,GO,Node> > PtP = Xpetra::MatrixMatrix<Scalar,LO,GO,Node>::Multiply(*P1,true,*P1,false,out);

    RCP<Vector> x = VectorFactory::Build(RP->getDomainMap());
    RCP<Vector> bRP  = VectorFactory::Build(RP->getRangeMap());
    RCP<Vector> bPtP = VectorFactory::Build(PtP->getRangeMap());

    x->randomize();
    RP->apply(*x,*bRP);
    PtP->apply(*x,*bPtP);

    TEST_EQUALITY(bRP->norm1() - bPtP->norm1() < 1e-12, true);

    Teuchos::RCP<Xpetra::Matrix<Scalar,LO,GO,Node> > RP2 = Xpetra::MatrixMatrix<Scalar,LO,GO,Node>::Multiply(*R2,false,*P2,false,out);
    Teuchos::RCP<Xpetra::Matrix<Scalar,LO,GO,Node> > PtP2 = Xpetra::MatrixMatrix<Scalar,LO,GO,Node>::Multiply(*P2,true,*P2,false,out);

    x = VectorFactory::Build(RP2->getDomainMap());
    bRP  = VectorFactory::Build(RP2->getRangeMap());
    bPtP = VectorFactory::Build(PtP2->getRangeMap());

    x->randomize();
    RP2->apply(*x,*bRP);
    PtP2->apply(*x,*bPtP);

    TEST_EQUALITY(bRP->norm1() - bPtP->norm1() < 1e-12, true);


    //R1->describe(*fos,Teuchos::VERB_EXTREME);
  }
Пример #23
0
  // check Hierarchy::Setup routine with GenericRFactory as restriction factory
  TEUCHOS_UNIT_TEST(GenericRFactory, GenericRSetup)
  {
    out << "version: " << MueLu::Version() << std::endl;

    for (int i=1; i<5; i++) {
      // generate problem
      RCP<const Teuchos::Comm<int> > comm = TestHelpers::Parameters::getDefaultComm();
      RCP<Matrix> A = TestHelpers::TestFactory<SC, LO, GO, NO>::Build1DPoisson(50*i*comm->getSize());

      // Multigrid Hierarchy
      Hierarchy H(A);
      H.setVerbLevel(Teuchos::VERB_HIGH);

      // build nullspace
      RCP<MultiVector> nullSpace = MultiVectorFactory::Build(A->getRowMap(),1);
      nullSpace->putScalar( (SC) 1.0);
      Teuchos::Array<Teuchos::ScalarTraits<SC>::magnitudeType> norms(1);
      nullSpace->norm1(norms);
      if (comm->getRank() == 0)
        out << "||NS|| = " << norms[0] << std::endl;

      RCP<PgPFactory>        Pfact = rcp( new PgPFactory());
      RCP<Factory>           Rfact = rcp( new GenericRFactory() );
      RCP<RAPFactory>        Acfact = rcp( new RAPFactory() );

      // setup smoothers
      Teuchos::ParameterList smootherParamList;
      smootherParamList.set("relaxation: type", "Symmetric Gauss-Seidel");
      smootherParamList.set("relaxation: sweeps", (LO) 1);
      smootherParamList.set("relaxation: damping factor", (SC) 1.0);
      RCP<SmootherPrototype> smooProto = rcp( new TrilinosSmoother("RELAXATION", smootherParamList) );
      RCP<SmootherFactory> SmooFact = rcp( new SmootherFactory(smooProto) );
      Acfact->setVerbLevel(Teuchos::VERB_HIGH);

      // Multigrid setup phase (using default parameters)
      FactoryManager M0; // how to build aggregates and smoother of the first level
      M0.SetFactory("A",            Acfact);
      M0.SetFactory("P",            Pfact);
      M0.SetFactory("R",            Rfact);
      M0.SetFactory("Smoother",     SmooFact);
      M0.SetFactory("CoarseSolver", SmooFact);

      FactoryManager M1; // first coarse level (Plain aggregation)
      M1.SetFactory("A",            Acfact);
      M1.SetFactory("P",            Pfact);
      M1.SetFactory("R",            Rfact);
      M1.SetFactory("Smoother",     SmooFact);
      M1.SetFactory("CoarseSolver", SmooFact);

      FactoryManager M2; // last level (SA)
      M2.SetFactory("A",            Acfact);
      M2.SetFactory("P",            Pfact);
      M2.SetFactory("R",            Rfact);
      M2.SetFactory("Smoother",     SmooFact);
      M2.SetFactory("CoarseSolver", SmooFact);

      bool bIsLastLevel = false;
      if(!bIsLastLevel) bIsLastLevel = H.Setup(0, Teuchos::null,  rcpFromRef(M0), rcpFromRef(M1));
      if(!bIsLastLevel) bIsLastLevel = H.Setup(1, rcpFromRef(M0), rcpFromRef(M1), rcpFromRef(M2));
      if(!bIsLastLevel) bIsLastLevel = H.Setup(2, rcpFromRef(M1), rcpFromRef(M2), Teuchos::null );

      RCP<Level> l0 = H.GetLevel(0);
      RCP<Level> l1;
      RCP<Level> l2;

      std::cout << "i = " << i << std::endl;

      if (H.GetNumLevels() > 1) l1 = H.GetLevel(1);
      if (H.GetNumLevels() > 2) l2 = H.GetLevel(2);

      /*RCP<Teuchos::FancyOStream> stdout = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
        l0->print(*stdout,Teuchos::VERB_EXTREME);
        if(l1 != Teuchos::null) l1->print(*stdout,Teuchos::VERB_EXTREME);
        if(l2 != Teuchos::null) l2->print(*stdout,Teuchos::VERB_EXTREME);*/

      TEST_EQUALITY(l0->IsAvailable("PreSmoother",  MueLu::NoFactory::get()), true);
      TEST_EQUALITY(l0->IsAvailable("PostSmoother", MueLu::NoFactory::get()), (H.GetNumLevels() > 1 ? true : false));
      TEST_EQUALITY(l0->IsAvailable("R",            MueLu::NoFactory::get()), false);
      TEST_EQUALITY(l0->IsAvailable("A",            MueLu::NoFactory::get()), true);
      TEST_EQUALITY(l0->IsAvailable("P",            MueLu::NoFactory::get()), false);
      TEST_EQUALITY(l0->GetKeepFlag("PreSmoother",  MueLu::NoFactory::get()), MueLu::Final);
      if (H.GetNumLevels() > 1)
        TEST_EQUALITY(l0->GetKeepFlag("PostSmoother", MueLu::NoFactory::get()), MueLu::Final);
      TEST_EQUALITY(l0->IsRequested("R",            MueLu::NoFactory::get()), false);
      TEST_EQUALITY(l0->GetKeepFlag("A",            MueLu::NoFactory::get()), MueLu::UserData);
      TEST_EQUALITY(l0->IsRequested("P",            MueLu::NoFactory::get()), false);

      if (l1 != Teuchos::null) {
        TEST_EQUALITY(l1->IsAvailable("PreSmoother",  MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l1->IsAvailable("PostSmoother", MueLu::NoFactory::get()), (H.GetNumLevels() > 2 ? true : false));
        TEST_EQUALITY(l1->IsAvailable("R",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l1->IsAvailable("A",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l1->IsAvailable("P",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l1->GetKeepFlag("A",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l1->GetKeepFlag("P",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l1->GetKeepFlag("R",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l1->GetKeepFlag("PreSmoother",  MueLu::NoFactory::get()), MueLu::Final);
        if (H.GetNumLevels() > 2)
          TEST_EQUALITY(l1->GetKeepFlag("PostSmoother", MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l1->IsRequested("Graph",        MueLu::NoFactory::get()), false);
        TEST_EQUALITY(l1->IsRequested("Aggregates",   MueLu::NoFactory::get()), false);
        TEST_EQUALITY(l1->IsRequested("Nullspace",    MueLu::NoFactory::get()), false);
      }
      if (l2 != Teuchos::null) {
        TEST_EQUALITY(l2->IsAvailable("PreSmoother",  MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l2->IsAvailable("PostSmoother", MueLu::NoFactory::get()), (H.GetNumLevels() > 3 ? true : false));
        TEST_EQUALITY(l2->IsAvailable("P",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l2->IsAvailable("R",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l2->IsAvailable("A",            MueLu::NoFactory::get()), true);
        TEST_EQUALITY(l2->GetKeepFlag("A",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l2->GetKeepFlag("P",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l2->GetKeepFlag("R",            MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l2->GetKeepFlag("PreSmoother",  MueLu::NoFactory::get()), MueLu::Final);
        if (H.GetNumLevels() > 3)
          TEST_EQUALITY(l2->GetKeepFlag("PostSmoother", MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(l2->IsRequested("Graph",        MueLu::NoFactory::get()), false);
        TEST_EQUALITY(l2->IsRequested("Aggregates",   MueLu::NoFactory::get()), false);
        TEST_EQUALITY(l2->IsRequested("Nullspace",    MueLu::NoFactory::get()), false);
      }
    } // end for i=1..5

  }
Пример #24
0
int CTestRelativeEnergyIncr::test(void)
{
    // check to ensure the SOE has been set - this should not happen if the 
    // return from start() is checked
    if (theSOE == 0)
        return -2;
    
    // check to ensure the algo does invoke start() - this is needed otherwise
    // may never get convergence later on in analysis!
    if (currentIter == 0) {
        opserr << "WARNING: CTestRelativeEnergyIncr::test() - start() was never invoked.\n";	
        return -2;
    }
    
    
    // determine the energy & save value in norms vector
    const Vector &b = theSOE->getB();
    const Vector &x = theSOE->getX();    
    double product = x ^ b;
    if (product < 0.0)
        product *= -0.5;
    else
        product *= 0.5;
    
    if (currentIter <= maxNumIter) 
        norms(currentIter-1) = product;
    
    // if first pass through .. set norm0
    if (currentIter == 1) {
        norm0 = product;
    }
    
    // get ratio
    if (norm0 != 0.0)
        product /= norm0;
    
    // print the data if required
    if (printFlag == 1) {
        opserr << "CTestRelativeEnergyIncr::test() - iteration: " << currentIter;
        opserr << " current Ratio (dX*dR/dX1*dR1): " << product << " (max: " << tol << ")\n";
    }
    if (printFlag == 4) {
        opserr << "CTestRelativeEnergyIncr::test() - iteration: " << currentIter;
        opserr << " current Ratio (dX*dR/dX1*dR1): " << product << " (max: " << tol << ")\n";
        opserr << "\tNorm deltaX: " << x.pNorm(nType) << ", Norm deltaR: " << b.pNorm(nType) << endln;
        opserr << "\tdeltaX: " << x << "\tdeltaR: " << b;
    }
    
    //
    // check if the algorithm converged
    //
    
    // if converged - print & return ok
    if (product <= tol) {
        
        // do some printing first
        if (printFlag != 0) {
            if (printFlag == 1 || printFlag == 4) 
                opserr << endln;
            else if (printFlag == 2 || printFlag == 6) {
                opserr << "CTestRelativeEnergyIncr::test() - iteration: " << currentIter;
                opserr << " last Ratio (dX*dR/dX1*dR1): " << product << " (max: " << tol << ")\n";
            }
        }
        
        // return the number of times test has been called - SUCCESSFULL
        return currentIter;
    }
    
    // algo failed to converged after specified number of iterations - but RETURN OK
    else if ((printFlag == 5 || printFlag == 6) && currentIter >= maxNumIter) {
        opserr << "WARNING: CTestRelativeEnergyIncr::test() - failed to converge but goin on -";
        opserr << " current Ratio (dX*dR/dX1*dR1): " << product << " (max: " << tol << ")\n";
        opserr << "\tNorm deltaX: " << x.pNorm(nType) << ", Norm deltaR: " << b.pNorm(nType) << endln;
        return currentIter;
    }
    
    // algo failed to converged after specified number of iterations - return FAILURE -2
    else if (currentIter >= maxNumIter) { // >= in case algorithm does not check
        opserr << "WARNING: CTestRelativeEnergyIncr::test() - failed to converge \n";
        opserr << "after: " << currentIter << " iterations\n";	
        currentIter++;    
        return -2;
    } 
    
    // algorithm not yet converged - increment counter and return -1
    else {
        currentIter++;    
        return -1;
    }
}
Пример #25
0
//! @brief Comprueba si se ha producido la convergencia.
int XC::CTestRelativeNormUnbalance::test(void)
  {
    // check to ensure the SOE has been set - this should not happen if the 
    // return from start() is checked
    if(!hasLinearSOE()) return -2;
    
    // check to ensure the algo does invoke start() - this is needed otherwise
    // may never get convergence later on in analysis!
    if(currentIter == 0)
      {
        std::cerr << getClassName() << "::" << __FUNCTION__
		  << "; WARNING: start() was never invoked.\n";	
        return -2;
      }
    
    // get the B vector & determine it's norm & save the value in norms vector
    calculatedNormX= getNormX();
    calculatedNormB = getNormB();
    lastRatio= calculatedNormB;
    if(currentIter <= maxNumIter) 
      norms(currentIter)= calculatedNormB;
    
    // determine the ratio
    if(norm0 != 0.0)
      lastRatio/= norm0;
    
    // print the data if required
    if(printFlag)
      std::clog << getStatusMsg(printFlag);
    
    //
    // check if the algorithm converged
    //
    
    // if converged - print & return ok
    
    if(lastRatio <= tol)
      { // the algorithm converged  
        // do some printing first
        if(printFlag != 0)
          {
            if(printFlag == 1 || printFlag == 4) 
              std::cerr << std::endl;
            else if(printFlag == 2 || printFlag == 6)
              {
                std::cerr << getTestIterationMessage();
                std::cerr << getRatioMessage("(|dR|/|dR0|)");
              }
          }
        // return the number of times test has been called
        return currentIter;
      } 
    // algo failed to converged after specified number of iterations - but RETURN OK
    else if((printFlag == 5 || printFlag == 6) && currentIter >= maxNumIter)
      {
        std::cerr << getClassName() << "::" << __FUNCTION__
		  << "; WARNING: failed to converge but going on -"
		  << getRatioMessage("(dR/dR0)");
        return currentIter;
      }
    
    // algo failed to converged after specified number of iterations - return FAILURE -2
    else if(currentIter >= maxNumIter)
      { // the algorithm failed to converge
        std::cerr << getFailedToConvergeMessage();
        currentIter++;  // we increment in case analysis does not check for convergence
        return -2;
      } 
    // algorithm not yet converged - increment counter and return -1
    else
      {
        currentIter++;    
        return -1;
      }
  }
Пример #26
0
int main (int argc, char* argv[])
{
  Teuchos::GlobalMPISession mpisess(&argc, &argv);

  bool success = true;

  Teuchos::RCP<Teuchos::FancyOStream>
    out = Teuchos::VerboseObjectBase::getDefaultOStream();

  try {

    Teuchos::Time timer("total");
    timer.start();

    Tpetra::DefaultPlatform::DefaultPlatformType& platform = Tpetra::DefaultPlatform::getDefaultPlatform();
    Teuchos::RCP<const Teuchos::Comm<int> > comm = platform.getComm();

    typedef double Scalar;
    typedef Tpetra::Map<>::local_ordinal_type LO;
    typedef Tpetra::Map<>::global_ordinal_type GO;
    typedef Tpetra::DefaultPlatform::DefaultPlatformType::NodeType Node;
    typedef Tpetra::MultiVector<Scalar,LO,GO,Node> TMV;
    typedef Tpetra::Operator<Scalar,LO,GO,Node>    TOP;
    typedef Belos::LinearProblem<Scalar,TMV,TOP>   BLinProb;
    typedef Belos::SolverManager<Scalar,TMV,TOP>   BSolverMgr;

    //Just get one parameter from the command-line: the name of an xml file
    //to get parameters from.

    std::string xml_file("calore1_mm.xml");
    {
      bool printedHelp = false;
      process_command_line (printedHelp, xml_file, argc, argv);
      if (printedHelp) {
        return EXIT_SUCCESS;
      }
    }

    //Read the contents of the xml file into a ParameterList. That parameter list
    //should specify a matrix-file and optionally which Belos solver to use, and
    //which Ifpack2 preconditioner to use, etc. If there are sublists of parameters
    //for Belos and Ifpack2, those will be passed to the respective destinations
    //from within the build_problem and build_solver functions.

    *out << "Every proc reading parameters from xml_file: "
         << xml_file << std::endl;
    Teuchos::ParameterList test_params =
      Teuchos::ParameterXMLFileReader(xml_file).getParameters();

    //The build_problem function is located in build_problem.hpp.
    //Note that build_problem calls build_precond and sets a preconditioner on the
    //linear-problem, if a preconditioner is specified.

    Teuchos::RCP<BLinProb> problem =
      build_problem<Scalar,LO,GO,Node>(test_params, comm);

    //The build_solver function is located in build_solver.hpp:

    Teuchos::RCP<BSolverMgr> solver = build_solver<Scalar,TMV,TOP>(test_params, problem);

    Belos::ReturnType ret = solver->solve();

    *out << "Converged in " << solver->getNumIters() << " iterations." << std::endl;

    Teuchos::RCP<TMV> R = Teuchos::rcp(new TMV(*problem->getRHS()));
    problem->computeCurrResVec(&*R, &*problem->getLHS(), &*problem->getRHS());
    Teuchos::Array<Teuchos::ScalarTraits<Scalar>::magnitudeType> norms(R->getNumVectors());
    R->norm2(norms);

    if (norms.size() < 1) {
      throw std::runtime_error("ERROR: norms.size()==0 indicates R->getNumVectors()==0.");
    }

    *out << "2-Norm of 0th residual vec: " << norms[0] << std::endl;

    //If the xml file specified a number of iterations to expect, then we will
    //use that as a test pass/fail criteria.

    if (test_params.isParameter("expectNumIters")) {
      int expected_iters = 0;
      Ifpack2::getParameter(test_params, "expectNumIters", expected_iters);
      int actual_iters = solver->getNumIters();
      if (ret == Belos::Converged && actual_iters <= expected_iters && norms[0] < 1.e-7) {
      }
      else {
        success = false;
        *out << "Actual iters("<<actual_iters
             <<") > expected number of iterations ("
             <<expected_iters<<"), or resid-norm(" << norms[0] << ") >= 1.e-7"<<std::endl;
      }
    }

    timer.stop();
    *out << "proc 0 total program time: " << timer.totalElapsedTime()
         << std::endl;

  }
  TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success)

  if (success) {
    *out << "End Result: TEST PASSED\n";
  }
  else {
    *out << "End Result: TEST FAILED\n";
  }

  return ( success ? 0 : 1 );
}
Пример #27
0
  TEUCHOS_UNIT_TEST(SaPFactory_kokkos, EpetraVsTpetra)
  {
#   include "MueLu_UseShortNames.hpp"
    MueLu::VerboseObject::SetDefaultOStream(Teuchos::rcpFromRef(out));

    out << "version: " << MueLu::Version() << std::endl;
    out << "Compare results of Epetra and Tpetra" << std::endl;
    out << "for 3 level AMG solver using smoothed aggregation with" << std::endl;
    out << "one SGS sweep on each multigrid level as pre- and postsmoother" << std::endl;

    RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

    typedef Teuchos::ScalarTraits<SC> STS;
    SC zero = STS::zero(), one = STS::one();

    Array<STS::magnitudeType> results(2);

    // run test only on 1 proc
    if(comm->getSize() == 1) {
      Xpetra::UnderlyingLib lib = Xpetra::UseEpetra;

      // run Epetra and Tpetra test
      for (int run = 0; run < 2; run++) { //TODO: create a subfunction instead or Tuple of UnderlyingLib
        if (run == 0) lib = Xpetra::UseEpetra;
        else          lib = Xpetra::UseTpetra;

        // generate problem
        LO maxLevels = 3;
        LO its       = 10;
        GO nEle      = 63;
        const RCP<const Map> map = MapFactory::Build(lib, nEle, 0, comm);
        Teuchos::ParameterList matrixParameters;
        matrixParameters.set("nx", nEle);

        RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
          Galeri::Xpetra::BuildProblem<SC,LO,GO,Map,CrsMatrixWrap,MultiVector>("Laplace1D", map, matrixParameters);
        RCP<Matrix> Op = Pr->BuildMatrix();

        // build nullspace
        RCP<MultiVector> nullSpace = MultiVectorFactory::Build(map,1);
        nullSpace->putScalar(one);
        Array<STS::magnitudeType> norms(1);
        nullSpace->norm1(norms);
        if (comm->getRank() == 0)
          out << "||NS|| = " << norms[0] << std::endl;

        // fill hierarchy
        RCP<Hierarchy> H = rcp( new Hierarchy() );
        H->setDefaultVerbLevel(Teuchos::VERB_HIGH);

        RCP<Level> Finest = H->GetLevel();
        Finest->setDefaultVerbLevel(Teuchos::VERB_HIGH);
        Finest->Set("A",Op);                      // set fine level matrix
        Finest->Set("Nullspace",nullSpace);       // set null space information for finest level

        // define transfer operators
        RCP<CoupledAggregationFactory> CoupledAggFact = rcp(new CoupledAggregationFactory());
        CoupledAggFact->SetMinNodesPerAggregate(3);
        CoupledAggFact->SetMaxNeighAlreadySelected(0);
        CoupledAggFact->SetOrdering("natural");
        CoupledAggFact->SetPhase3AggCreation(0.5);

        RCP<TentativePFactory> Ptentfact = rcp(new TentativePFactory());
        RCP<SaPFactory>        Pfact = rcp( new SaPFactory());
        RCP<Factory>      Rfact = rcp( new TransPFactory() );
        RCP<RAPFactory>        Acfact = rcp( new RAPFactory() );
        H->SetMaxCoarseSize(1);

        // setup smoothers
        Teuchos::ParameterList smootherParamList;
        smootherParamList.set("relaxation: type", "Symmetric Gauss-Seidel");
        smootherParamList.set("relaxation: sweeps", (LO) 1);
        smootherParamList.set("relaxation: damping factor", (SC) 1.0);
        RCP<SmootherPrototype> smooProto = rcp( new TrilinosSmoother("RELAXATION", smootherParamList) );
        RCP<SmootherFactory> SmooFact = rcp( new SmootherFactory(smooProto) );
        Acfact->setVerbLevel(Teuchos::VERB_HIGH);

        RCP<SmootherFactory> coarseSolveFact = rcp(new SmootherFactory(smooProto, Teuchos::null));

        FactoryManager M;
        M.SetFactory("P", Pfact);
        M.SetFactory("R", Rfact);
        M.SetFactory("A", Acfact);
        M.SetFactory("Ptent", Ptentfact);
        M.SetFactory("Aggregates", CoupledAggFact);
        M.SetFactory("Smoother", SmooFact);
        M.SetFactory("CoarseSolver", coarseSolveFact);

        H->Setup(M, 0, maxLevels);

        // test some basic multigrid data
        RCP<Level> coarseLevel = H->GetLevel(1);
        TEST_EQUALITY(coarseLevel->IsRequested("A",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("P",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("PreSmoother",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("PostSmoother",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("R",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("A",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel->IsAvailable("P",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel->IsAvailable("PreSmoother",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel->IsAvailable("PostSmoother",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel->IsAvailable("R",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("A",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("P",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("PreSmoother",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("PostSmoother",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("R",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel->IsRequested("P",Pfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("P",Ptentfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("PreSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("PostSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("R",Rfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsRequested("A",Acfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("P",Pfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("P",Ptentfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("PreSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("PostSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("R",Rfact.get()), false);
        TEST_EQUALITY(coarseLevel->IsAvailable("A",Acfact.get()), false);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("P",Pfact.get()), 0);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("P",Ptentfact.get()), 0);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("PreSmoother",SmooFact.get()), 0);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("PostSmoother",SmooFact.get()), 0);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("R",Rfact.get()), 0);
        TEST_EQUALITY(coarseLevel->GetKeepFlag("A",Acfact.get()), 0);
        RCP<Matrix> P1 = coarseLevel->Get< RCP<Matrix> >("P");
        RCP<Matrix> R1 = coarseLevel->Get< RCP<Matrix> >("R");
        TEST_EQUALITY(P1->getGlobalNumRows(), 63);
        TEST_EQUALITY(P1->getGlobalNumCols(), 21);
        TEST_EQUALITY(R1->getGlobalNumRows(), 21);
        TEST_EQUALITY(R1->getGlobalNumCols(), 63);
        RCP<Level> coarseLevel2 = H->GetLevel(2);
        TEST_EQUALITY(coarseLevel2->IsRequested("A",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("P",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("R",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("PreSmoother",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("PostSmoother",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("A",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel2->IsAvailable("P",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel2->IsAvailable("PreSmoother",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel2->IsAvailable("PostSmoother",MueLu::NoFactory::get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("R",MueLu::NoFactory::get()), true);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("A",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("P",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("PreSmoother",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("PostSmoother",MueLu::NoFactory::get()), 0);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("R",MueLu::NoFactory::get()), MueLu::Final);
        TEST_EQUALITY(coarseLevel2->IsRequested("P",Pfact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("P",Ptentfact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsRequested("R",Rfact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("P",Pfact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("P",Ptentfact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("PreSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("PostSmoother",SmooFact.get()), false);
        TEST_EQUALITY(coarseLevel2->IsAvailable("R",Rfact.get()), false);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("P",Pfact.get()), 0);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("P",Ptentfact.get()), 0);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("PreSmoother",SmooFact.get()), 0);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("PostSmoother",SmooFact.get()), 0);
        TEST_EQUALITY(coarseLevel2->GetKeepFlag("R",Rfact.get()), 0);
        RCP<Matrix> P2 = coarseLevel2->Get< RCP<Matrix> >("P");
        RCP<Matrix> R2 = coarseLevel2->Get< RCP<Matrix> >("R");
        TEST_EQUALITY(P2->getGlobalNumRows(), 21);
        TEST_EQUALITY(P2->getGlobalNumCols(), 7);
        TEST_EQUALITY(R2->getGlobalNumRows(), 7);
        TEST_EQUALITY(R2->getGlobalNumCols(), 21);

        Teuchos::RCP<Xpetra::Matrix<Scalar,LO,GO> > PtentTPtent = Xpetra::MatrixMatrix<Scalar,LO,GO>::Multiply(*P1,true,*P1,false,out);
        TEST_EQUALITY(PtentTPtent->getGlobalMaxNumRowEntries()-3<1e-12, true);
        TEST_EQUALITY(P1->getGlobalMaxNumRowEntries()-2<1e-12, true);
        TEST_EQUALITY(P2->getGlobalMaxNumRowEntries()-2<1e-12, true);

        // Define RHS
        RCP<MultiVector> X = MultiVectorFactory::Build(map,1);
        RCP<MultiVector> RHS = MultiVectorFactory::Build(map,1);

        X->putScalar(1.0);
        X->norm2(norms);
        if (comm->getRank() == 0)
          out << "||X_true|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;

        Op->apply(*X,*RHS,Teuchos::NO_TRANS,(SC)1.0,(SC)0.0);

        // Use AMG directly as an iterative method
        {
          X->putScalar( (SC) 0.0);

          H->Iterate(*RHS,*X,its);

          X->norm2(norms);
          if (comm->getRank() == 0)
            out << "||X_" << std::setprecision(2) << its << "|| = " << std::setiosflags(std::ios::fixed) << std::setprecision(10) << norms[0] << std::endl;
          results[run] = norms[0];
        }
      }

      TEST_EQUALITY(results[0] - results[1] < 1e-10, true); // check results of EPETRA vs TPETRA
    } // comm->getSize == 1

  } //SaPFactory_EpetraVsTpetra
Пример #28
0
bool mask_out_artifacts(const QString& timeseries_path, const QString& timeseries_out_path, double threshold, int interval_size)
{
    if ((!threshold) || (!interval_size)) {
        printf("Problem with input parameters. Either threshold or interval_size is zero.\n");
        return false;
    }

    QTime status_timer;
    status_timer.start();

    DiskReadMda X(timeseries_path);
    int M = X.N1();
    int N = X.N2();

    //compute norms of chunks
    Mda norms(M, N / interval_size);
    for (int i = 0; i < N / interval_size; i++) {
        int timepoint = i * interval_size;
        if (status_timer.elapsed() > 5000) {
            printf("mask_out_artifacts compute_norms: %d/%d (%d%%)\n", timepoint, N, (int)(timepoint * 100.0 / N));
            status_timer.restart();
        }
        Mda chunk;
        X.readChunk(chunk, 0, timepoint, M, interval_size);
        for (int m = 0; m < M; m++) {
            double sumsqr = 0;
            for (int aa = 0; aa < interval_size; aa++) {
                sumsqr += chunk.value(m, aa) * chunk.value(m, aa);
            }
            norms.set(sqrt(sumsqr), m, i);
        }
    }

    //determine which chunks to use
    QVector<int> use_it(N / interval_size + 1);
    for (int i = 0; i < use_it.count(); i++)
        use_it[i] = 1;
    for (int m = 0; m < M; m++) {
        QVector<double> vals;
        for (int i = 0; i < norms.N2(); i++) {
            vals << norms.get(m, i);
        }
        double sigma0 = MLCompute::stdev(vals);
        double mean0 = MLCompute::mean(vals);
        printf("For channel %d: mean=%g, stdev=%g, interval size = %d\n", m, mean0, sigma0, interval_size);
        for (int i = 0; i < norms.N2(); i++) {
            if (norms.value(m, i) > mean0 + sigma0 * threshold) {
                use_it[i - 1] = 0; //don't use the neighbor chunks either
                use_it[i] = 0; //don't use the neighbor chunks either
                use_it[i + 1] = 0; //don't use the neighbor chunks either
            }
        }
    }

    //write the data
    int num_timepoints_used = 0;
    int num_timepoints_not_used = 0;
    DiskWriteMda Y;
    Y.open(MDAIO_TYPE_FLOAT32, timeseries_out_path, M, N);
    for (int i = 0; i < N / interval_size; i++) {
        int timepoint = i * interval_size;
        if (status_timer.elapsed() > 5000) {
            printf("mask_out_artifacts write data: %d/%d (%d%%)\n", timepoint, N, (int)(timepoint * 100.0 / N));
            status_timer.restart();
        }
        Mda chunk;
        X.readChunk(chunk, 0, timepoint, M, interval_size);
        if (use_it[i]) {
            num_timepoints_used += interval_size;
            Y.writeChunk(chunk, 0, timepoint);
        }
        else {
            num_timepoints_not_used += interval_size;
        }
    }
    Y.close();

    printf("Using %.2f%% of all timepoints\n", num_timepoints_used * 100.0 / (num_timepoints_used + num_timepoints_not_used));

    return true;
}
Пример #29
0
  TEUCHOS_UNIT_TEST_TEMPLATE_4_DECL(SaPFactory_kokkos, Build, Scalar, LocalOrdinal, GlobalOrdinal, Node)
  {
#   include "MueLu_UseShortNames.hpp"
    MUELU_TESTING_SET_OSTREAM;
    MUELU_TESTING_LIMIT_SCOPE(Scalar,GlobalOrdinal,Node);
    out << "version: " << MueLu::Version() << std::endl;

    RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();

    // construct two levels
    Level fineLevel, coarseLevel;
    TestHelpers_kokkos::TestFactory<SC, LO, GO, NO>::createTwoLevelHierarchy(fineLevel, coarseLevel);

    // construct matrices
    const SC lambdaMax = 5;
    RCP<Matrix> A = TestHelpers_kokkos::TestFactory<SC,LO,GO,NO>::Build2DPoisson(27*comm->getSize());
    A->SetMaxEigenvalueEstimate(lambdaMax);
    RCP<Matrix> Ptent = TestHelpers_kokkos::TestFactory<SC,LO,GO,NO>::Build2DPoisson(27*comm->getSize());

    // set level matrices
    fineLevel  .Set("A", A);
    coarseLevel.Set("P", Ptent);

    // construct the factory to be tested
    const double dampingFactor = 0.5;
    RCP<SaPFactory_kokkos> sapFactory = rcp(new SaPFactory_kokkos);
    ParameterList Pparams;
    Pparams.set("sa: damping factor", dampingFactor);
    sapFactory->SetParameterList(Pparams);
    sapFactory->SetFactory("A", MueLu::NoFactory::getRCP());
    sapFactory->SetFactory("P", MueLu::NoFactory::getRCP());

    // build the data
    coarseLevel.Request("P", sapFactory.get());
    sapFactory->Build(fineLevel, coarseLevel);

    // fetch the data
    RCP<Matrix> Pfact = coarseLevel.Get<RCP<Matrix>>("P", sapFactory.get());

    // construct the data to compare
    SC omega = dampingFactor / lambdaMax;
    RCP<Vector> invDiag = Utilities_kokkos::GetMatrixDiagonalInverse(*A);
    RCP<ParameterList> APparams = rcp(new ParameterList);
    RCP<Matrix> Ptest   = Xpetra::IteratorOps<SC,LO,GO,NO>::Jacobi(omega, *invDiag, *A, *Ptent, Teuchos::null, out, "label", APparams);

    // compare matrices by multiplying them by a random vector
    RCP<MultiVector> X = MultiVectorFactory::Build(A->getDomainMap(), 1);
    X->setSeed(846930886);
    X->randomize();

    RCP<MultiVector> Bfact = MultiVectorFactory::Build(A->getRangeMap(),  1);
    RCP<MultiVector> Btest = MultiVectorFactory::Build(A->getRangeMap(),  1);

    typedef Teuchos::ScalarTraits<SC> STS;
    SC zero = STS::zero(), one = STS::one();

    Pfact->apply(*X, *Bfact, Teuchos::NO_TRANS, one, zero);
    Ptest->apply(*X, *Btest, Teuchos::NO_TRANS, one, zero);
    Btest->update(-one, *Bfact, one);

    Array<typename STS::magnitudeType> norms(1);
    Btest->norm2(norms);
    out << "|| B_factory - B_test || = " << norms[0] << std::endl;
    TEST_EQUALITY(norms[0] < 1e-12, true);
  }
Пример #30
0
  void POVPainter::drawColorMesh(const Mesh & mesh, int mode)
  {
    // Now we draw the given mesh to the OpenGL widget
    switch (mode)
    {
      case 0: // Filled triangles
        break;
      case 1: // Lines
        break;
      case 2: // Points
        break;
    }

    // Render the triangles of the mesh
    std::vector<Eigen::Vector3f> v = mesh.vertices();
    std::vector<Eigen::Vector3f> n = mesh.normals();
    std::vector<Color3f> c = mesh.colors();

    // If there are no triangles then don't bother doing anything
    if (v.size() == 0 || v.size() != c.size())
      return;

    QString vertsStr, ivertsStr, normsStr, texturesStr;
    QTextStream verts(&vertsStr);
    verts << "vertex_vectors{" << v.size() << ",\n";
    QTextStream iverts(&ivertsStr);
    iverts << "face_indices{" << v.size() / 3 << ",\n";
    QTextStream norms(&normsStr);
    norms << "normal_vectors{" << n.size() << ",\n";
    QTextStream textures(&texturesStr);
    textures << "texture_list{" << c.size() << ",\n";
    for(unsigned int i = 0; i < v.size(); ++i) {
      verts << "<" << v[i].x() << "," << v[i].y() << "," << v[i].z() << ">";
      norms << "<" << n[i].x() << "," << n[i].y() << "," << n[i].z() << ">";
      textures << "texture{pigment{rgbt<" << c[i].red() << ","
               << c[i].green() << "," << c[i].blue() << ","
               << 1.0 - d->color.alpha() << ">}}";
      if (i != v.size()-1) {
        verts << ", ";
        norms << ", ";
        textures << ",\n";
      }
      if (i != 0 && i%3 == 0) {
        verts << '\n';
        norms << '\n';
      }
    }
    // Now to write out the indices
    for (unsigned int i = 0; i < v.size(); i += 3) {
      iverts << "<" << i << "," << i+1 << "," << i+2 << ">";
      iverts << "," << i << "," << i+1 << "," << i+2;
      if (i != v.size()-3)
        iverts << ", ";
      if (i != 0 && ((i+1)/3)%3 == 0)
        iverts << '\n';
    }
    // Now to close off all the arrays
    verts << "\n}";
    norms << "\n}";
    iverts << "\n}";
    textures << "\n}";
    // Now to write out the full mesh - could be pretty big...
    *(d->output) << "mesh2 {\n"
                 << vertsStr << '\n'
                 << normsStr << '\n'
                 << texturesStr << '\n'
                 << ivertsStr << '\n'
                 << "}\n\n";
  }