コード例 #1
0
ファイル: MLAPI_Eig.cpp プロジェクト: gitter-badger/quinoa
// ====================================================================== 
void Eig(const Operator& Op, MultiVector& ER, MultiVector& EI)
{
  int ierr;
  if (Op.GetDomainSpace() != Op.GetRangeSpace())
    ML_THROW("Matrix is not square", -1);

  ER.Reshape(Op.GetDomainSpace());
  EI.Reshape(Op.GetDomainSpace());

  Epetra_LinearProblem Problem;
  Problem.SetOperator(const_cast<Epetra_RowMatrix*>(Op.GetRowMatrix()));
  Amesos_Lapack Lapack(Problem);

  Epetra_Vector ER_Epetra(Op.GetRowMatrix()->RowMatrixRowMap());
  Epetra_Vector EI_Epetra(Op.GetRowMatrix()->RowMatrixRowMap());

  ierr = Lapack.GEEV(ER_Epetra, EI_Epetra);

  if (ierr)
    ML_THROW("GEEV returned error code = " + GetString(ierr), -1);
  
  for (int i = 0 ; i < ER.GetMyLength() ; ++i) {
    ER(i) = ER_Epetra[i];
    EI(i) = EI_Epetra[i];
  }
}
//---------------------------------------------------------------------------
const std::vector<int> ManyDigitIndexTable::FindInternal(
  const std::vector<int>& indices,
  const MultiVector<int>& v,
  const int value)
{
  //Check indices
  {
    const auto begin = v.PeekIndices().begin();
    const auto end   = v.PeekIndices().end();
    const auto x = std::find(begin,end,value);
    if (x!=end)
    {
      const int index_found = std::distance(begin,x);
      assert(index_found >= 0);
      assert(index_found < boost::numeric_cast<int>(v.PeekIndices().size()));
      std::vector<int> result = indices;
      result.push_back(index_found);
      return result;
    }
  }

  //Check MultiVector
  const auto& mvs = v.PeekMultiVectors();
  const int size = mvs.size();
  for (int i=0; i!=size; ++i)
  {
    std::vector<int> indices_deeper = indices;
    indices_deeper.push_back(i);
    const auto result
      = FindInternal(
        indices_deeper,mvs[i],value);
    if (!result.empty()) return result;
  }
  return std::vector<int>();
}
コード例 #3
0
/*----------------------------------------------------------------------*
 |  apply multigrid linear preconditioner (private)          m.gee 03/06|
 *----------------------------------------------------------------------*/
int MOERTEL::Mortar_ML_Preconditioner::MultiLevelSA(
    const MultiVector& b1_f,
    const MultiVector& b2_f,
    MultiVector& x1_f,
    MultiVector& x2_f,
    int level) const
{
    MultiVector r1_f(b1_f.GetVectorSpace(),1,false);
    MultiVector z1_f(b1_f.GetVectorSpace(),1,false);

    // presmoothing
    x1_f = 0;
    G_.Apply(b1_f,x1_f);
    x2_f = mlapiMT_ * x1_f;
    x2_f.Scale(-1.0);

    // compute residual
    r1_f = b1_f - mlapiAhat11_ * x1_f;

    // postsmoothing
    z1_f = 0;
    G_.Apply(r1_f,z1_f);
    x1_f = x1_f + z1_f;
    x2_f = mlapiMT_ * x1_f;
    x2_f.Scale(-1.0);



    return 0;
}
コード例 #4
0
  void IfpackSmoother::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
    TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IfpackSmoother::Apply(): Setup() has not been called");

    // Forward the InitialGuessIsZero option to Ifpack
    Teuchos::ParameterList  paramList;
    if (type_ == "Chebyshev")
      paramList.set("chebyshev: zero starting solution",  InitialGuessIsZero);

    else if (type_ == "point relaxation stand-alone")
      paramList.set("relaxation: zero starting solution", InitialGuessIsZero);

    SetPrecParameters(paramList);

    // Apply
    if (InitialGuessIsZero) {
      Epetra_MultiVector&       epX = Utils::MV2NonConstEpetraMV(X);
      const Epetra_MultiVector& epB = Utils::MV2EpetraMV(B);
      prec_->ApplyInverse(epB, epX);

    } else {
      RCP<MultiVector> Residual = Utils::Residual(*A_,X,B);
      RCP<MultiVector> Correction = MultiVectorFactory::Build(A_->getDomainMap(), X.getNumVectors());
      Epetra_MultiVector&       epX = Utils::MV2NonConstEpetraMV(*Correction);
      const Epetra_MultiVector& epB = Utils::MV2EpetraMV(*Residual);
      prec_->ApplyInverse(epB, epX);
      X.update(1.0, *Correction, 1.0);
    }
  }
コード例 #5
0
  void ZoltanInterface<LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::
  GetProblemGeometry(void *data, int numGIDEntries, int numLIDEntries, int numObjectIDs,
                     ZOLTAN_ID_PTR gids, ZOLTAN_ID_PTR lids, int dim, double *coordinates, int *ierr)
  {
    if (data == NULL) {
      *ierr = ZOLTAN_FATAL;
      return;
    }

    MultiVector *Coords = (MultiVector*) data;

    if (dim != Teuchos::as<int>(Coords->getNumVectors())) {
      //FIXME I'm assuming dim should be 1, 2, or 3 coming in?!
      *ierr = ZOLTAN_FATAL;
      return;
    }

    TEUCHOS_TEST_FOR_EXCEPTION(numObjectIDs != Teuchos::as<int>(Coords->getLocalLength()), Exceptions::Incompatible, "Length of coordinates must be the same as the number of objects");

    ArrayRCP<ArrayRCP<const SC> > CoordsData(dim);
    for (int j = 0; j < dim; ++j)
      CoordsData[j] = Coords->getData(j);

    size_t numElements = Coords->getLocalLength();
    for (size_t i = 0; i < numElements; ++i)
      for (int j = 0; j < dim; ++j)
        coordinates[i*dim+j] = (double) CoordsData[j][i];

    *ierr = ZOLTAN_OK;

  } //GetProblemGeometry
コード例 #6
0
ファイル: vectest.cpp プロジェクト: andy-thomason/Sire
void test_rotate()
{
    QVector<Vector> axis(MultiVector::count()), vec(MultiVector::count());
    QVector<double> angle(MultiVector::count());
    QVector<Vector> result(MultiVector::count());

    for (int i=0; i<MultiVector::count(); ++i)
    {
        axis[i] = rangen.vectorOnSphere(1);
        vec[i] = rangen.vectorOnSphere(5);
        angle[i] = rangen.rand(-2.0*SireMaths::pi, 2.0*SireMaths::pi);
        result[i] = Quaternion(Angle(angle[i]),axis[i]).rotate(vec[i]);
    }

    MultiVector maxis(axis);
    MultiVector mvec(vec);
    MultiDouble mangle(angle);

    MultiVector mresult = MultiQuaternion(mangle, maxis).rotate(mvec);

    for (int i=0; i<MultiVector::count(); ++i)
    {
        for (int j=0; j<3; ++j)
        {
            assert_nearly_equal( mresult.at(i)[j], result[i][j], 1e-5 );
        }
    }
}
コード例 #7
0
ファイル: MLAPI_Eig.cpp プロジェクト: gitter-badger/quinoa
// ====================================================================== 
// FIXME: Add List
void Eigs(const Operator& A, int NumEigenvalues, 
          MultiVector& ER, MultiVector& EI)
{

  if (A.GetDomainSpace() != A.GetRangeSpace())
    ML_THROW("Input Operator is not square", -1);

  double time;

  time = GetClock();

  int length = NumEigenvalues;
  double tol = 1e-3;
  int restarts = 1;
  int output = 10;
  bool PrintStatus = true;

  // 1.- set parameters for Anasazi
  Teuchos::ParameterList AnasaziList;
  // MatVec should be either "A" or "ML^{-1}A"
  AnasaziList.set("eigen-analysis: matrix operation", "A");
  AnasaziList.set("eigen-analysis: use diagonal scaling", false);
  AnasaziList.set("eigen-analysis: symmetric problem", false);
  AnasaziList.set("eigen-analysis: length", length);
  AnasaziList.set("eigen-analysis: block-size",1);
  AnasaziList.set("eigen-analysis: tolerance", tol);
  AnasaziList.set("eigen-analysis: restart", restarts);
  AnasaziList.set("eigen-analysis: output", output);
  AnasaziList.get("eigen-analysis: print current status",PrintStatus);

  // data to hold real and imag for eigenvalues and eigenvectors
  Space ESpace(-1, NumEigenvalues);
  ER.Reshape(ESpace);
  EI.Reshape(ESpace);

  // this is the starting value -- random
  Epetra_MultiVector EigenVectors(A.GetRowMatrix()->OperatorDomainMap(),
                                  NumEigenvalues);
  EigenVectors.Random();
#ifdef HAVE_ML_ANASAxI
  //int NumRealEigenvectors, NumImagEigenvectors;
#endif

  AnasaziList.set("eigen-analysis: action", "LM");

#ifdef HAVE_ML_ANASAxI
  ML_THROW("fixme...", -1);
  /* FIXME
  ML_Anasazi::Interface(A.GetRowMatrix(),EigenVectors,ER.GetValues(),
			EI.GetValues(), AnasaziList, 0, 0,
			&NumRealEigenvectors, &NumImagEigenvectors, 0);
                        */
#else
  ML_THROW("Anasazi is no longer supported", -1);
#endif

  return;
}
コード例 #8
0
  void IndefBlockedDiagonalSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const
  {
    TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::Apply(): Setup() has not been called");

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

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

    // extract parameters from internal parameter list
    const ParameterList & pL = Factory::GetParameterList();
    LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
    Scalar omega = pL.get<Scalar>("Damping factor");

    // wrap current solution vector in RCP
    RCP<MultiVector> rcpX = Teuchos::rcpFromRef(X);

    // create residual vector
    // contains current residual of current solution X with rhs B
    RCP<MultiVector> residual = MultiVectorFactory::Build(B.getMap(), B.getNumVectors());

    // incrementally improve solution vector X
    for (LocalOrdinal run = 0; run < nSweeps; ++run) {
      // 1) calculate current residual
      residual->update(one,B,zero); // residual = B
      A_->apply(*rcpX, *residual, Teuchos::NO_TRANS, -one, one);

      // split residual vector
      Teuchos::RCP<MultiVector> r1 = rangeMapExtractor_->ExtractVector(residual, 0);
      Teuchos::RCP<MultiVector> r2 = rangeMapExtractor_->ExtractVector(residual, 1);

      // 2) solve F * \Delta \tilde{x}_1 = r_1
      //    start with zero guess \Delta \tilde{x}_1
      RCP<MultiVector> xtilde1 = MultiVectorFactory::Build(F_->getRowMap(),1);
      xtilde1->putScalar(zero);
      velPredictSmoo_->Apply(*xtilde1,*r1);

      // 3) solve SchurComp equation
      //    start with zero guess \Delta \tilde{x}_2
      RCP<MultiVector> xtilde2 = MultiVectorFactory::Build(Z_->getRowMap(),1);
      xtilde2->putScalar(zero);
      schurCompSmoo_->Apply(*xtilde2,*r2);

      // 4) extract parts of solution vector X
      Teuchos::RCP<MultiVector> x1 = domainMapExtractor_->ExtractVector(rcpX, 0);
      Teuchos::RCP<MultiVector> x2 = domainMapExtractor_->ExtractVector(rcpX, 1);

      // 5) update solution vector with increments xhat1 and xhat2
      //    rescale increment for x2 with omega_
      x1->update(omega,*xtilde1,one); // x1 = x1_old + omega xtilde1
      x2->update(omega,*xtilde2,one); // x2 = x2_old + omega xtilde2

      // write back solution in global vector X
      domainMapExtractor_->InsertVector(x1, 0, rcpX);
      domainMapExtractor_->InsertVector(x2, 1, rcpX);

    }

  }
コード例 #9
0
// ======================================================================
MultiVector Extract(const MultiVector& y, const int v)
{
  if ((v < 0) || v >= y.GetNumVectors())
    ML_THROW("Wrong input parameter v (" +
             GetString(v) + ")", -1);

  MultiVector x(y.GetVectorSpace(), y.GetRCPValues(v));

  return(x);
}
コード例 #10
0
/** Use this quaternion to rotate 'p' */
MultiVector MultiQuaternion::rotate(const MultiVector &p) const
{
    const MultiDouble sx2 = sc[0]*sc[0];
    const MultiDouble sy2 = sc[1]*sc[1];
    const MultiDouble sz2 = sc[2]*sc[2];

    const MultiDouble sxy = sc[0]*sc[1];
    const MultiDouble sxz = sc[0]*sc[2];
    const MultiDouble syz = sc[1]*sc[2];

    const MultiDouble swx = sc[0]*sc[3];
    const MultiDouble swy = sc[1]*sc[3];
    const MultiDouble swz = sc[2]*sc[3];

    const MultiDouble two(2.0);
    const MultiDouble half(0.5);

    return MultiVector( two*( ( half - sy2 - sz2 )*p.x()
                           + ( sxy - swz )       *p.y()
                           + ( sxz + swy )       *p.z()),

                        two*( ( sxy + swz )      *p.x()
                           + ( half - sx2 - sz2 ) *p.y()
                           + ( syz - swx )       *p.z()),

                        two*( ( sxz - swy )      *p.x()
                           + ( syz + swx )       *p.y()
                           + ( half - sx2 - sy2 ) *p.z()) );
}
コード例 #11
0
// ======================================================================
MultiVector Duplicate(const MultiVector& y, const int v)
{
  if ((v < 0) || v >= y.GetNumVectors())
    ML_THROW("Wrong input parameter v (" +
             GetString(v) + ")", -1);

  // FIXME: use Extract
  MultiVector x(y.GetVectorSpace(), 1);
  for (int i = 0 ; i < x.GetMyLength() ; ++i)
    x(i) = y(i,v);

  return(x);
}
コード例 #12
0
void LinearCheckNodeUpdater::updateNode(
										unsigned int nodeInd,
										MultiVector<float>& messages)

{
	uint32_t begin = messages.begin(nodeInd);
	uint32_t end = messages.end(nodeInd);
	uint32_t N = end - begin;

	if(N == 1) {
		messages[begin] = m_checkNodesPriorLogPmQ[nodeInd].getFloat();
		return;
	}

	// Convert all message values into log(p-q) values
	for (unsigned int j = begin; j < end; j++) {
		m_messagesPmQ.push_back(LogPmQ(messages[j]));
	}

	// calculate the multiplication from the right of p-q values:
	// rightSum[j] = encodedSoftBit[i] * messages[-1].p-q * messages[-2].p-q * ... * messages[-j].p-q
	LogPmQ curSum = m_checkNodesPriorLogPmQ[nodeInd]; // get log(p-q)

	m_rightSum.push_back(curSum);
	// go over all messages except the first one (which will never be
	// needed anyway)
	for(unsigned int rightInd = N - 1; rightInd > 0; rightInd--) {
		curSum += m_messagesPmQ[rightInd];

		m_rightSum.push_back(curSum);
	}


	// special case for j = 0
	messages[begin] = m_rightSum[N - 1].getFloat();

	// now we use curSum as the cumulative multiplication from the
	// left rather than right
	curSum = m_messagesPmQ[0];

	for (unsigned int j = 1; j < N; j++) {
		messages[begin + j] = (curSum + m_rightSum[N - j - 1]).getFloat();

		//assert(isfinite(messages[begin + j]));

		curSum += m_messagesPmQ[j];
	}

	m_rightSum.clear();
	m_messagesPmQ.clear();
}
コード例 #13
0
ファイル: Tpetra_RTIOp.hpp プロジェクト: 00liujj/trilinos
      void
      apply (const MultiVector<S,LO,GO,Node> &X, 
	     MultiVector<S,LO,GO,Node> &Y,
	     Teuchos::ETransp mode = Teuchos::NO_TRANS, 
	     S alpha = Teuchos::ScalarTraits<S>::one (), 
	     S beta = Teuchos::ScalarTraits<S>::zero ()) const
      {
	const size_t numVectors = X.getNumVectors ();
	RCP<MultiVector<S,LO,GO,Node> > mvec_inout;
	RCP<const MultiVector<S,LO,GO,Node> > mvec_in2;

	if (_importer != null) {
	  if (_importMV != null && _importMV->getNumVectors () != numVectors) {
	    _importMV = null;
	  }
	  if (_importMV == null) {
	    _importMV = createMultiVector<S> (_importer->getTargetMap (), numVectors);
	  }
	  _importMV->doImport (X, *_importer, INSERT);
	  mvec_in2 = _importMV;
	}
	else {
	  mvec_in2 = rcpFromRef(X);
	}

	if (_exporter != null) {
	  if (_exportMV != null && _exportMV->getNumVectors () != numVectors) {
	    _exportMV = null;
	  }
	  if (_exportMV == null) {
	    _exportMV = createMultiVector<S> (_exporter->getSourceMap (), numVectors);
	  }
	  mvec_inout = _exportMV;
	}
	else {
	  mvec_inout = rcpFromRef (Y);
	}
	_kernel.setAlphaBeta (alpha, beta);
	//
	for (size_t j=0; j < numVectors; ++j) {
	  RCP<       Vector<S,LO,GO,Node> > vec_inout = mvec_inout->getVectorNonConst(j);
	  RCP< const Vector<S,LO,GO,Node> > vec_in2   = mvec_in2->getVector(j);
	  Tpetra::RTI::detail::binary_transform( *vec_inout, *vec_in2, _kernel );
	}
	// export
	if (_exporter != null) {
	  Y.doExport (*_exportMV, *_exporter, ADD);
	}
      }
コード例 #14
0
ファイル: Teko_Utilities.hpp プロジェクト: agrippa/Trilinos
/** \brief Copy the contents of a multivector to a destination vector.
  *
  * Copy the contents of a multivector to a new vector. If the destination
  * vector is null, a deep copy of the source multivector is made to a newly allocated
  * vector. Also, if the destination and the source do not match, a new destination
  * object is allocated and returned to the user.
  *
  * \param[in] src Source multivector to be copied.
  * \param[in] dst Destination multivector.  If null a new multivector will be allocated.
  *
  * \returns A copy of the source multivector. If dst is not null a pointer to this object
  *          is returned. Otherwise a new multivector is returned.
  */
inline MultiVector datacopy(const MultiVector & src,MultiVector & dst)
{ 
   if(dst==Teuchos::null)
      return deepcopy(src);

   bool rangeCompat = src->range()->isCompatible(*dst->range());
   bool domainCompat = src->domain()->isCompatible(*dst->domain());
 
   if(not (rangeCompat && domainCompat))
      return deepcopy(src);

   // perform data copy
   Thyra::assign<double>(dst.ptr(),*src);
   return dst;
}
コード例 #15
0
// ====================================================================== 
Operator GetPtent1D(const MultiVector& D, const int offset = 0)
{
  if (D.GetNumVectors() != 1)
    ML_THROW("D.GetNumVectors() != 1", -1);

  int size = D.GetMyLength();
  if (size == 0)
    ML_THROW("empty diagonal vector in input", -1);

  double* diag = new double[size];
  for (int i = 0 ; i < size ; ++i)
    diag[i] = D(i);

  // creates the ML operator and store the diag pointer,
  // as well as the function pointers
  ML_Operator* MLDiag = ML_Operator_Create(GetML_Comm());

  int invec_leng = size / 3 + size % 3;
  int outvec_leng = size;

  MLDiag->invec_leng = invec_leng;
  MLDiag->outvec_leng = outvec_leng;
  MLDiag->data = (void*)diag;
  MLDiag->data_destroy = Ptent1D_destroy;
  MLDiag->matvec->func_ptr = Ptent1D_matvec;

  MLDiag->matvec->ML_id = ML_NONEMPTY;
  MLDiag->matvec->Nrows = outvec_leng;
  MLDiag->from_an_ml_operator = 0;

  MLDiag->getrow->func_ptr = Ptent1D_getrows;

  MLDiag->getrow->ML_id = ML_NONEMPTY;
  MLDiag->getrow->Nrows = outvec_leng;

  // creates the domain space
  vector<int> MyGlobalElements(invec_leng);
  for (int i = 0 ; i < invec_leng ; ++i) 
    MyGlobalElements[i] = D.GetVectorSpace()(i * 3) / 3;
  Space DomainSpace(invec_leng, -1, &MyGlobalElements[0]);
  Space RangeSpace = D.GetVectorSpace();

  // creates the MLAPI wrapper
  Operator Diag(DomainSpace,RangeSpace,MLDiag,true);
  return(Diag);
}
コード例 #16
0
  void Amesos2Smoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
    TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::Amesos2Smoother::Apply(): Setup() has not been called");

    RCP<Tpetra_MultiVector> tX, tB;
    if (!useTransformation_) {
      tX = Utilities::MV2NonConstTpetraMV2(X);
      tB = Utilities::MV2NonConstTpetraMV2(const_cast<MultiVector&>(B));
    } else {
      // Copy data of the original vectors into the transformed ones
      size_t numVectors = X.getNumVectors();
      size_t length     = X.getLocalLength();

      TEUCHOS_TEST_FOR_EXCEPTION(numVectors > 1, Exceptions::RuntimeError,
        "MueLu::Amesos2Smoother::Apply: Fixing coarse matrix for Amesos2 for multivectors has not been implemented yet.");
      ArrayRCP<const SC> Xdata  = X.  getData(0),         Bdata  = B.  getData(0);
      ArrayRCP<SC>       X_data = X_->getDataNonConst(0), B_data = B_->getDataNonConst(0);

      for (size_t i = 0; i < length; i++) {
        X_data[i] = Xdata[i];
        B_data[i] = Bdata[i];
      }

      tX = Utilities::MV2NonConstTpetraMV2(*X_);
      tB = Utilities::MV2NonConstTpetraMV2(*B_);
    }

    prec_->setX(tX);
    prec_->setB(tB);

    prec_->solve();

    prec_->setX(Teuchos::null);
    prec_->setB(Teuchos::null);

    if (useTransformation_) {
      // Copy data from the transformed vectors into the original ones
      size_t length     = X.getLocalLength();

      ArrayRCP<SC>       Xdata  = X.  getDataNonConst(0);
      ArrayRCP<const SC> X_data = X_->getData(0);

      for (size_t i = 0; i < length; i++)
        Xdata[i] = X_data[i];
    }
  }
コード例 #17
0
ファイル: MLAPI_Krylov.cpp プロジェクト: 00liujj/trilinos
// ======================================================================
void Krylov(const Operator& A, const MultiVector& LHS,
            const MultiVector& RHS, const BaseOperator& Prec,
            Teuchos::ParameterList& List)
{
#ifndef HAVE_ML_AZTECOO
      std::cerr << "Please configure ML with --enable-aztecoo to use" << std::endl;
      std::cerr << "MLAPI Krylov solvers" << std::endl;
      exit(EXIT_FAILURE);
#else
  if (LHS.GetNumVectors() != 1)
    ML_THROW("FIXME: only one vector is currently supported", -1);

  Epetra_LinearProblem Problem;

  const Epetra_RowMatrix& A_Epetra = *(A.GetRowMatrix());

  Epetra_Vector LHS_Epetra(View,A_Epetra.OperatorDomainMap(),
                           (double*)&(LHS(0)));
  Epetra_Vector RHS_Epetra(View,A_Epetra.OperatorRangeMap(),
                           (double*)&(RHS(0)));

  // FIXME: this works only for Epetra-based operators
  Problem.SetOperator((const_cast<Epetra_RowMatrix*>(&A_Epetra)));
  Problem.SetLHS(&LHS_Epetra);
  Problem.SetRHS(&RHS_Epetra);

  AztecOO solver(Problem);

  EpetraBaseOperator Prec_Epetra(A_Epetra.OperatorDomainMap(),Prec);
  solver.SetPrecOperator(&Prec_Epetra);

  // get options from List
  int    NumIters = List.get("krylov: max iterations", 1550);
  double Tol      = List.get("krylov: tolerance", 1e-9);
  std::string type     = List.get("krylov: type", "gmres");
  int    output   = List.get("krylov: output level", GetPrintLevel());

  // set options in `solver'
  if (type == "cg")
    solver.SetAztecOption(AZ_solver, AZ_cg);
  else if (type == "cg_condnum")
    solver.SetAztecOption(AZ_solver, AZ_cg_condnum);
  else if (type == "gmres")
    solver.SetAztecOption(AZ_solver, AZ_gmres);
  else if (type == "gmres_condnum")
    solver.SetAztecOption(AZ_solver, AZ_gmres_condnum);
  else if (type == "fixed point")
    solver.SetAztecOption(AZ_solver, AZ_fixed_pt);
  else
    ML_THROW("krylov: type has incorrect value (" +
             type + ")", -1);

  solver.SetAztecOption(AZ_output, output);
  solver.Iterate(NumIters, Tol);
#endif

}
コード例 #18
0
int 
InverseOperator::Apply(const MultiVector& x, MultiVector& y) const
{
  ResetTimer();
  StackPush();

  if (GetDomainSpace() != x.GetVectorSpace())
    ML_THROW("DomainSpace and x.GetVectorSpace() differ", -1);

  if (GetRangeSpace() != y.GetVectorSpace())
    ML_THROW("RangeSpace and y.GetVectorSpace() differ", -1);

  int x_nv = x.GetNumVectors();
  int y_nv = y.GetNumVectors();
  double FL = 0.0;
  if (RCPData_ != Teuchos::null)
    FL = RCPData_->ComputeFlops();

  if (x_nv != y_nv)
    ML_THROW("Number of vectors of x and y differ (" +
             GetString(x_nv) + " vs. " + GetString(x_nv), -1);

  for (int v = 0 ; v < x_nv ; ++v) {

    Epetra_Vector x_Epetra(View,RowMatrix()->OperatorDomainMap(),
                           (double*)&(x(0,v)));
    Epetra_Vector y_Epetra(View,RowMatrix()->OperatorRangeMap(),
                           (double*)&(y(0,v)));

    if (RCPData_ != Teuchos::null)
      RCPData_->ApplyInverse(x_Epetra,y_Epetra);
    else if (RCPMLPrec_ != Teuchos::null)
      RCPMLPrec_->ApplyInverse(x_Epetra,y_Epetra);
    else
      ML_THROW("Neither Ifpack nor ML smoother is properly set up", -1);
  }

  StackPop();
  if (RCPData_ != Teuchos::null)
    UpdateFlops(RCPData_->ComputeFlops() - FL);
  UpdateTime();

  return(0);
}
コード例 #19
0
    // 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];
    }
コード例 #20
0
  void PermutingSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Apply(MultiVector &X, MultiVector const &B, bool const &InitialGuessIsZero) const
  {
    TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::PermutingSmoother::Apply(): Setup() has not been called");
    TEUCHOS_TEST_FOR_EXCEPTION(s_ == Teuchos::null, Exceptions::RuntimeError, "IsSetup() == true but s_ == Teuchos::null. This does not make sense");

    Teuchos::RCP<MultiVector> Xtemp = MultiVectorFactory::Build(X.getMap(),1,true);
    Xtemp->update(1.0,X,0.0);

    // TODO: unify scaling and left permutation operator
    Teuchos::RCP<MultiVector> Btemp = MultiVectorFactory::Build(B.getMap(),1,true);
    Teuchos::RCP<MultiVector> Btemp2 = MultiVectorFactory::Build(B.getMap(),1,true);
    permP_->apply(B, *Btemp, Teuchos::NO_TRANS);   // apply permutation operator to rhs
    diagScalingOp_->apply(*Btemp,*Btemp2, Teuchos::NO_TRANS);  // apply scaling operator to rhs

    // apply smoother to permuted linear system
    s_->Apply(*Xtemp, *Btemp2, InitialGuessIsZero);

    // retransform smooth solution
    permQT_->apply(*Xtemp, X, Teuchos::NO_TRANS);
  }
コード例 #21
0
  void PermutingSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node, LocalMatOps>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
    TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::PermutingSmoother::Apply(): Setup() has not been called");

    typedef Teuchos::ScalarTraits<Scalar> STS;

    Teuchos::RCP<MultiVector> Xtemp = MultiVectorFactory::Build(X.getMap(), 1, true);
    Xtemp->update(STS::one(), X, STS::zero());

    // TODO: unify scaling and left permutation operator
    Teuchos::RCP<MultiVector> Btemp  = MultiVectorFactory::Build(B.getMap(), 1, true);
    Teuchos::RCP<MultiVector> Btemp2 = MultiVectorFactory::Build(B.getMap(), 1, true);
    permP_->apply(B, *Btemp, Teuchos::NO_TRANS);                // apply permutation operator to rhs
    diagScalingOp_->apply(*Btemp, *Btemp2, Teuchos::NO_TRANS);  // apply scaling operator to rhs

    // apply smoother to permuted linear system
    s_->Apply(*Xtemp, *Btemp2, InitialGuessIsZero);

    // retransform smooth solution
    permQT_->apply(*Xtemp, X, Teuchos::NO_TRANS);
  }
コード例 #22
0
ファイル: vectest.cpp プロジェクト: andy-thomason/Sire
void test_getset()
{
    QVector<Vector> v(MultiVector::count());

    for (int i=0; i<MultiVector::count(); ++i)
    {
        v[i] = Vector( rangen.rand(-10,10), rangen.rand(-10,10),
                       rangen.rand(-10,10) );
    }

    MultiVector mv;

    for (int i=0; i<MultiVector::count(); ++i)
    {
        mv.set(i, v[i]);
        assert_equal( mv.getitem(i), v[i] );
    }

    assert_equal( MultiVector(v), mv );
}
コード例 #23
0
MultiQuaternion SIREMATHS_EXPORT SireMaths::operator*(const MultiQuaternion &q,
                                                      const MultiVector &p)
{
    //quaternion multiplication - p is [0, p]
    MultiDouble nw = -p.sc[0]*q.sc[0] - p.sc[1]*q.sc[1] - p.sc[2]*q.sc[2];

    //do the cross product
    MultiDouble cx = (q.sc[1]*p.z())-(q.sc[2]*p.y());
    MultiDouble cy = (q.sc[2]*p.x())-(q.sc[0]*p.z());
    MultiDouble cz = (q.sc[0]*p.y())-(q.sc[1]*p.x());

    MultiDouble nx = q.sc[3]*p.x() + cx;
    MultiDouble ny = q.sc[3]*p.y() + cy;
    MultiDouble nz = q.sc[3]*p.z() + cz;

    return MultiQuaternion(nx,ny,nz,nw);
}
コード例 #24
0
void LinearCheckNodeUpdater::update(MultiVector<float> & messages)
{
	uint32_t N_nodes = messages.size();

	assert(N_nodes == m_checkNodesPriorLogPmQ.size());

	// for each check node
	for (uint32_t node_ind = 0; node_ind < N_nodes; node_ind++) {
		updateNode(node_ind, messages);
	}

}
コード例 #25
0
ファイル: vectest.cpp プロジェクト: andy-thomason/Sire
void test_cross()
{
    QVector<Vector> v0(MultiVector::count()), v1(MultiVector::count());
    QVector<Vector> cross(MultiVector::count());

    for (int i=0; i<MultiVector::count(); ++i)
    {
        v0[i] = rangen.vectorOnSphere(5);
        v1[i] = rangen.vectorOnSphere(5);
        cross[i] = Vector::cross(v0[i], v1[i]);
    }

    MultiVector mv0(v0);
    MultiVector mv1(v1);
    MultiVector mcross = MultiVector::cross(mv0, mv1);

    for (int i=0; i<MultiVector::count(); ++i)
    {
        assert_equal( mcross.at(i), cross.at(i) );
    }
}
コード例 #26
0
 void 
 CrsMatrixSolveOp<OpScalar,MatScalar,LocalOrdinal,GlobalOrdinal,Node,LocalMatOps>::apply(
             const MultiVector<OpScalar,LocalOrdinal,GlobalOrdinal,Node> & X,
                   MultiVector<OpScalar,LocalOrdinal,GlobalOrdinal,Node> & Y,
                   Teuchos::ETransp mode, OpScalar alpha, OpScalar beta) const 
 {
   TEUCHOS_TEST_FOR_EXCEPTION(!matrix_->isFillComplete(), std::runtime_error, 
       Teuchos::typeName(*this) << "::apply(): underlying matrix is not fill-complete.");
   TEUCHOS_TEST_FOR_EXCEPTION(X.getNumVectors() != Y.getNumVectors(), std::runtime_error,
       Teuchos::typeName(*this) << "::apply(X,Y): X and Y must have the same number of vectors.");
   TEUCHOS_TEST_FOR_EXCEPTION(matrix_->isLowerTriangular() == false && matrix_->isUpperTriangular() == false, std::runtime_error,
       Teuchos::typeName(*this) << "::apply() requires either upper or lower triangular structure in underlying matrix.");
   TEUCHOS_TEST_FOR_EXCEPTION( alpha != Teuchos::ScalarTraits<OpScalar>::one() || beta != Teuchos::ScalarTraits<OpScalar>::zero(), std::runtime_error,
       Teuchos::typeName(*this) << "::apply(): non-trivial alpha,beta not supported at this time.");
   if (mode == Teuchos::NO_TRANS) {
     applyNonTranspose(X,Y);
   }
   else {
     applyTranspose(X,Y);
   }
 }
コード例 #27
0
MultiVector LoadBalanceInverseOperator::operator()(const MultiVector& LHS)
{
  StackPush();

  MultiVector RHS(LHS.GetVectorSpace());
  RHS = 0.0;
  Apply(LHS,RHS);

  StackPop();

  return(RHS);
}
コード例 #28
0
    /// \brief Compute \f$Y = \beta Y + \alpha B X\f$, where \f$B X\f$
    ///   represents the result of the local triangular solve.
    void
    apply (const MultiVector<Scalar,LocalOrdinal,GlobalOrdinal,Node> & X,
           MultiVector<Scalar,LocalOrdinal,GlobalOrdinal,Node> &Y,
           Teuchos::ETransp mode = Teuchos::NO_TRANS,
           Scalar alpha = Teuchos::ScalarTraits<Scalar>::one (),
           Scalar beta = Teuchos::ScalarTraits<Scalar>::zero ()) const
    {
      typedef Teuchos::ScalarTraits<Scalar> STOS;
      const char prefix[] = "Tpetra::CrsMatrixSolveOp::apply: ";

      TEUCHOS_TEST_FOR_EXCEPTION
        (! matrix_->isFillComplete (), std::runtime_error,
         prefix << "Underlying matrix is not fill complete.");
      TEUCHOS_TEST_FOR_EXCEPTION
        (! matrix_->isLowerTriangular () && ! matrix_->isUpperTriangular (),
         std::runtime_error, prefix << "The matrix is neither lower nor upper "
         "triangular.  Remember that in Tpetra, triangular-ness is a local "
         "(per MPI process) property.");
      TEUCHOS_TEST_FOR_EXCEPTION
        (X.getNumVectors () != Y.getNumVectors (), std::invalid_argument,
         prefix << "X and Y must have the same number of columns (vectors).  "
         "X.getNumVectors() = " << X.getNumVectors ()
         << " != Y.getNumVectors() = " << Y.getNumVectors () << ".");
      TEUCHOS_TEST_FOR_EXCEPTION
        (alpha != STOS::one () || beta != STOS::zero (), std::logic_error,
         prefix << "The case alpha != 1 or beta != 0 has not yet been "
         "implemented.  Please speak with the Tpetra developers.");
      if (mode == Teuchos::NO_TRANS) {
        applyNonTranspose (X,Y);
      } else if (mode == Teuchos::TRANS || mode == Teuchos::CONJ_TRANS) {
        applyTranspose (X, Y, mode);
      } else {
        TEUCHOS_TEST_FOR_EXCEPTION
          (true, std::invalid_argument, prefix << "The 'mode' argument has an "
           "invalid value " << mode << ".  Valid values are Teuchos::NO_TRANS="
           << Teuchos::NO_TRANS << ", Teuchos::TRANS=" << Teuchos::TRANS << ", "
           "and Teuchos::CONJ_TRANS=" << Teuchos::CONJ_TRANS << ".");
      }
    }
コード例 #29
0
// ======================================================================
MultiVector Redistribute(const MultiVector& y, const int NumEquations)
{
  StackPush();

  if (y.GetMyLength() % NumEquations)
    ML_THROW("NumEquations does not divide MyLength()", -1);

  if (y.GetNumVectors() != 1)
    ML_THROW("Redistribute() works with single vectors only", -1);

  Space NewSpace(y.GetMyLength() / NumEquations);

  MultiVector y2(NewSpace, NumEquations);

  for (int i = 0 ; i < y2.GetMyLength() ; ++i)
    for (int j = 0 ; j < NumEquations ; ++j)
      y2(i, j) = y(j + NumEquations * i);

  StackPop();

  return(y2);
}
コード例 #30
0
/** Construct a quaternion which represents a rotation of 'angle' around 'axis' */
MultiQuaternion::MultiQuaternion(const MultiDouble &angle, const MultiVector &axis)
{
    //the unit quaternion can be represented by;
    // Q = cos(theta) + u*sin(theta)
    // which represents a rotation of 2*theta around the
    // vector u

    MultiFloat sintheta;
    {
        MultiFloat half_angle(angle);
        half_angle *= 0.5;
        MultiFloat costheta;
        sincos(half_angle, sintheta, costheta);
        sc[3] = costheta;
    }

    //the vector must be normalised
    MultiVector norm = axis.normalise();

    sc[0] = sintheta * axis.x();
    sc[1] = sintheta * axis.y();
    sc[2] = sintheta * axis.z();
}