Esempio n. 1
0
void SpmdMultiVectorBase<Scalar>::acquireNonconstDetachedMultiVectorViewImpl(
  const Range1D &rowRng_in,
  const Range1D &colRng_in,
  RTOpPack::SubMultiVectorView<Scalar> *sub_mv
  )
{
  using Teuchos::outArg;
  const Range1D rowRng = validateRowRange(rowRng_in);
  const Range1D colRng = validateColRange(colRng_in);
  if(
    rowRng.lbound() < localOffset_
    ||
    localOffset_+localSubDim_-1 < rowRng.ubound()
    )
  {
    // rng consists of off-processor elements so use the default implementation!
    MultiVectorDefaultBase<Scalar>::acquireNonconstDetachedMultiVectorViewImpl(
      rowRng_in, colRng_in, sub_mv
      );
    return;
  }
  ArrayRCP<Scalar> localValues;
  Ordinal leadingDim = 0;
  this->getNonconstLocalData(outArg(localValues), outArg(leadingDim));
  sub_mv->initialize(
    rowRng.lbound() // globalOffset
    ,rowRng.size() // subDim
    ,colRng.lbound() // colOffset
    ,colRng.size() // numSubCols
    ,localValues
    +(rowRng.lbound()-localOffset_)
    +colRng.lbound()*leadingDim // values
    ,leadingDim // leadingDim
    );
}
Esempio n. 2
0
Teuchos::RCP<const Epetra_MultiVector>
Thyra::get_Epetra_MultiVector(
  const Epetra_Map &map,
  const MultiVectorBase<double> &mv
  )
{
  using Teuchos::rcpWithEmbeddedObj;
  using Teuchos::rcpFromRef;
  using Teuchos::outArg;
  ArrayRCP<const double> mvData;
  Ordinal mvLeadingDim = -1;
  const SpmdMultiVectorBase<double> *mvSpmdMv = 0;
  const SpmdVectorBase<double> *mvSpmdV = 0;
  if ((mvSpmdMv = dynamic_cast<const SpmdMultiVectorBase<double>*>(&mv))) {
    mvSpmdMv->getLocalData(outArg(mvData), outArg(mvLeadingDim));
  }
  else if ((mvSpmdV = dynamic_cast<const SpmdVectorBase<double>*>(&mv))) {
    mvSpmdV->getLocalData(outArg(mvData));
    mvLeadingDim = mvSpmdV->spmdSpace()->localSubDim();
  }
  if (nonnull(mvData)) {
    return rcpWithEmbeddedObj(
      new Epetra_MultiVector(
        ::View,map, const_cast<double*>(mvData.getRawPtr()), mvLeadingDim, mv.domain()->dim()
        ),
      mvData
      );
  }
  return ::Thyra::get_Epetra_MultiVector(map, rcpFromRef(mv));
}
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, ScalarsAndInts ) {
  std::string data;
  {
    std::ostringstream oss;
    int i = -1;
    double d = 31.4159e-1;
    int k = 600;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeInt(i,oss);
    ss.serializeScalar(d,oss);
    ss.serializeInt(k,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    int i = 0;
    double d = 0.0;
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeInt(outArg(i),iss);
    TEST_EQUALITY_CONST(i,-1);
    ss.deSerializeScalar(outArg(d),iss);
    TEST_EQUALITY_CONST(d,3.14159);
    ss.deSerializeInt(outArg(i),iss);
    TEST_EQUALITY_CONST(i,600);
  }
}
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, Scalars ) {
  std::string data;
  {
    std::ostringstream oss;
    double d = 4.2;
    double e = 4.3;
    double f = 4.4;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeScalar(d,oss);
    ss.serializeScalar(e,oss);
    ss.serializeScalar(f,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    double d = 0.0;
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeScalar(outArg(d),iss);
    TEST_EQUALITY_CONST(d,4.2);
    ss.deSerializeScalar(outArg(d),iss);
    TEST_EQUALITY_CONST(d,4.3);
    ss.deSerializeScalar(outArg(d),iss);
    TEST_EQUALITY_CONST(d,4.4);
  }
}
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, ints ) {
  std::string data;
  {
    std::ostringstream oss;
    int i = -1;
    int j = 3;
    int k = 600;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeInt(i,oss);
    ss.serializeInt(j,oss);
    ss.serializeInt(k,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    int i = 0;
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeInt(outArg(i),iss);
    TEST_EQUALITY_CONST(i,-1);
    ss.deSerializeInt(outArg(i),iss);
    TEST_EQUALITY_CONST(i,3);
    ss.deSerializeInt(outArg(i),iss);
    TEST_EQUALITY_CONST(i,600);
  }
}
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, paramLists ) {
  std::string data;
  Teuchos::ParameterList plGold_A;
  {
    plGold_A.set("Hello","World");
    plGold_A.set("alpha", 1.2345 );
  }
  Teuchos::ParameterList plGold_B;
  {
    plGold_B.set("isTrue", false );
    plGold_B.set("NumTimes", 35 );
  }
  {
    std::ostringstream oss;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeParameterList(plGold_A,oss);
    ss.serializeParameterList(plGold_B,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    Teuchos::ParameterList pl_A;
    Teuchos::ParameterList pl_B;
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeParameterList(outArg(pl_A),iss);
    ss.deSerializeParameterList(outArg(pl_B),iss);

    TEST_ASSERT( plGold_A == pl_A ); // BROKEN at the moment
    TEST_ASSERT( plGold_B == pl_B ); // BROKEN at the moment
    TEST_EQUALITY_CONST( pl_A.get<std::string>("Hello"), "World" );
    TEST_EQUALITY_CONST( pl_A.get<double>("alpha"), 1.2345 );
    TEST_EQUALITY_CONST( pl_B.get<bool>("isTrue"), false );
    TEST_EQUALITY_CONST( pl_B.get<int>("NumTimes"), 35 );
  }
}
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, vectors ) {
  std::string data;
  int N = 15;
  {
    RCP<VectorBase<double> > vectorGold_A = createDefaultVector<double>(N,0.0);
    RCP<VectorBase<double> > vectorGold_B = createDefaultVector<double>(N,0.0);
    Thyra::DetachedVectorView<double> vector_A_view( *vectorGold_A );
    Thyra::DetachedVectorView<double> vector_B_view( *vectorGold_B );
    for (int i=0 ; i<N ; ++i ) {
      vector_A_view[i] = i*1.0;
      vector_B_view[i] = i*2.0;
    }
    std::ostringstream oss;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeVectorBase(*vectorGold_A,oss);
    ss.serializeVectorBase(*vectorGold_B,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    RCP<VectorBase<double> > vector_A = createDefaultVector<double>(N,0.0);
    RCP<VectorBase<double> > vector_B = createDefaultVector<double>(N,0.0);
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeVectorBase(outArg(*vector_A),iss);
    ss.deSerializeVectorBase(outArg(*vector_B),iss);
    {
      Thyra::ConstDetachedVectorView<double> vector_A_view( *vector_A );
      Thyra::ConstDetachedVectorView<double> vector_B_view( *vector_B );
      for (int i=0 ; i<N ; ++i) {
        TEST_EQUALITY_CONST( vector_A_view[i], i*1.0 );
        TEST_EQUALITY_CONST( vector_B_view[i], i*2.0 );
      }
    }
  }
}
void
gathervPrint (std::ostream& out,
              const std::string& s,
              const Teuchos::Comm<int>& comm)
{
  using Teuchos::ArrayRCP;
  using Teuchos::CommRequest;
  using Teuchos::ireceive;
  using Teuchos::isend;
  using Teuchos::outArg;
  using Teuchos::RCP;
  using Teuchos::wait;

  const int myRank = comm.getRank ();
  const int rootRank = 0;
  if (myRank == rootRank) {
    out << s; // Proc 0 prints its buffer first
  }

  const int numProcs = comm.getSize ();
  const int sizeTag = 42;
  const int msgTag = 43;

  ArrayRCP<size_t> sizeBuf (1);
  ArrayRCP<char> msgBuf; // to be resized later
  RCP<CommRequest<int> > req;

  for (int p = 1; p < numProcs; ++p) {
    if (myRank == p) {
      sizeBuf[0] = s.size ();
      req = isend<int, size_t> (sizeBuf, rootRank, sizeTag, comm);
      (void) wait<int> (comm, outArg (req));

      const size_t msgSize = s.size ();
      msgBuf.resize (msgSize + 1); // for the '\0'
      std::copy (s.begin (), s.end (), msgBuf.begin ());
      msgBuf[msgSize] = '\0';

      req = isend<int, char> (msgBuf, rootRank, msgTag, comm);
      (void) wait<int> (comm, outArg (req));
    }
    else if (myRank == rootRank) {
      sizeBuf[0] = 0; // just a precaution
      req = ireceive<int, size_t> (sizeBuf, p, sizeTag, comm);
      (void) wait<int> (comm, outArg (req));

      const size_t msgSize = sizeBuf[0];
      msgBuf.resize (msgSize + 1); // for the '\0'
      req = ireceive<int, char> (msgBuf, p, msgTag, comm);
      (void) wait<int> (comm, outArg (req));

      std::string msg (msgBuf.getRawPtr ());
      out << msg;
    }
  }
}
PointEval1D<Scalar>
computePoint(const MeritFunc1DBase<Scalar> &phi, const Scalar &alpha,
             const bool compute_phi = true, const bool compute_Dphi = false)
{
    using Teuchos::null;
    using Teuchos::outArg;
    PointEval1D<Scalar> p;
    p.alpha = alpha;
    phi.eval( alpha, compute_phi ? outArg(p.phi) : null ,
              compute_Dphi ? outArg(p.Dphi) : null );
    return p;
}
ReductTargetSerializer<Scalar>::ReductTargetSerializer(
  const Teuchos::RCP<const RTOpT<Scalar> > &op
  )
  :op_(op.assert_not_null())
{
  using Teuchos::outArg;
  typedef typename RTOpT<Scalar>::primitive_value_type PrimitiveScalar;
  op_->get_reduct_type_num_entries(
    outArg(num_values_), outArg(num_indexes_), outArg(num_chars_) );
  reduct_obj_ext_size_ =
    serializedSize<PrimitiveScalar>(num_values_,num_indexes_,num_chars_);
}
int
Piro::Thyra::PerformOptiPackAnalysis(
    ::Thyra::ModelEvaluatorDefaultBase<double>& piroModel,
    Teuchos::ParameterList& optipackParams,
    Teuchos::ParameterList& globipackParams,
    RCP< ::Thyra::VectorBase<double> >& p)
{
    RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream();
#ifdef Piro_ENABLE_OptiPack
    // First, Linesearch stuff
    const RCP<GlobiPack::BrentsLineSearch<double> >
    linesearch = GlobiPack::brentsLineSearch<double>();
    const RCP<ParameterList> lsPL = rcp(&globipackParams, false);
    linesearch->setParameterList(lsPL);

    // Temporary Debug
    *out << "\nCurrent LineSearch parameters" << endl;
    lsPL->print(*out);

    // Second, Optimization stuff

    p = ::Thyra::createMember(piroModel.get_p_space(0));

    RCP<const ::Thyra::VectorBase<double> > p_init = piroModel.getNominalValues().get_p(0);

    ::Thyra::copy(*p_init, p.ptr());

    const RCP<OptiPack::NonlinearCG<double> > cgSolver =
        OptiPack::nonlinearCG<double>(rcp(&piroModel,false), 0, 0, linesearch);

    const RCP<ParameterList> pl = rcp(&optipackParams,false);
    cgSolver->setParameterList(pl);

    // Temporary Debug Info
    *out << "\nCurrent nonlinearCG parameter list" << endl;
    pl->print(*out);

    // Solve the prob
    double g_opt;  // optimal value of the response
    int numIters;  // number of iteration taken
    const OptiPack::NonlinearCGUtils::ESolveReturn solveResult =
        cgSolver->doSolve( p.ptr(), outArg(g_opt),
                           null, null, null, outArg(numIters) );

    return (int) solveResult;
#else
    *out << "ERROR: Trilinos/Piro was not configured to include OptiPack analysis."
         << endl;
    return 0;  // should not fail tests
#endif
}
Esempio n. 12
0
  Scalar
  Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node,true>::
  dot (const Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node,true>& a) const
  {
    using Teuchos::outArg;
    using Teuchos::REDUCE_SUM;
    using Teuchos::reduceAll;

    TEUCHOS_TEST_FOR_EXCEPTION(
      this->getGlobalLength () != a.getGlobalLength (), std::runtime_error,
      "Tpetra::Vector::dots: Vectors do not have the same global length.  "
      "this->getGlobalLength() = " << this->getGlobalLength () << " != "
      "a.getGlobalLength() = " << a.getGlobalLength () << ".");

#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      ! this->getMap ()->isCompatible (*a.getMap ()), std::runtime_error,
      "Tpetra::Vector::dots: Vectors do not have compatible Maps:" << std::endl
      << "this->getMap(): " << std::endl << * (this->getMap ())
      << "a.getMap(): " << std::endl << * (a.getMap ()) << std::endl);
#else
    TEUCHOS_TEST_FOR_EXCEPTION(
      this->getLocalLength () != a.getLocalLength (), std::runtime_error,
      "Tpetra::Vector::dots: Vectors do not have the same local length.");
#endif
    Scalar gbldot;
    gbldot = MVT::Dot (this->lclMV_, a.lclMV_);
    if (this->isDistributed ()) {
      Scalar lcldot = gbldot;
      reduceAll (*this->getMap ()->getComm (), REDUCE_SUM,
                 lcldot, outArg (gbldot));
    }
    return gbldot;
  }
  Teuchos::RCP<const Map<LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType> > >
  Map<LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType> >::
  replaceCommWithSubset (const Teuchos::RCP<const Teuchos::Comm<int> >& newComm) const
  {
    using Teuchos::ArrayView;
    using Teuchos::outArg;
    using Teuchos::RCP;
    using Teuchos::REDUCE_MIN;
    using Teuchos::reduceAll;
    typedef global_size_t GST;
    typedef LocalOrdinal LO;
    typedef GlobalOrdinal GO;
    typedef Map<LO, GO, node_type> map_type;

    // mfh 26 Mar 2013: The lazy way to do this is simply to recreate
    // the Map by calling its ordinary public constructor, using the
    // original Map's data.  This only involves O(1) all-reduces over
    // the new communicator, which in the common case only includes a
    // small number of processes.

    // Create the Map to return.
    if (newComm.is_null ()) {
      return Teuchos::null; // my process does not participate in the new Map
    } else {
      // Map requires that the index base equal the global min GID.
      // Figuring out the global min GID requires a reduction over all
      // processes in the new communicator.  It could be that some (or
      // even all) of these processes contain zero entries.  (Recall
      // that this method, unlike removeEmptyProcesses(), may remove
      // an arbitrary subset of processes.)  We deal with this by
      // doing a min over the min GID on each process if the process
      // has more than zero entries, or the global max GID, if that
      // process has zero entries.  If no processes have any entries,
      // then the index base doesn't matter anyway.
      const GO myMinGid = (this->getNodeNumElements () == 0) ?
        this->getMaxAllGlobalIndex () : this->getMinGlobalIndex ();
      GO newIndexBase = this->getInvalidGlobalIndex ();
      reduceAll<int, GO> (*newComm, REDUCE_MIN, myMinGid, outArg (newIndexBase));

      // Make Map's constructor compute the global number of indices.
      const GST globalNumInds = Teuchos::OrdinalTraits<GST>::invalid ();

      if (mapDevice_.initialized ()) {
        Kokkos::View<const GO*, DeviceType> myGIDs =
          mapDevice_.getMyGlobalIndices ();
        return rcp (new map_type (globalNumInds, myGIDs, newIndexBase,
                                  newComm, this->getNode ()));
      }
      else {
        Kokkos::View<const GO*, host_mirror_device_type> myGidsHostView =
          mapHost_.getMyGlobalIndices ();
        ArrayView<const GO> myGidsArrayView (myGidsHostView.ptr_on_device (),
                                             myGidsHostView.dimension_0 ());
        return rcp (new map_type (globalNumInds, myGidsArrayView, newIndexBase,
                                  newComm, this->getNode ()));
      }
    }
  }
Esempio n. 14
0
 typename Teuchos::ScalarTraits<Scalar>::magnitudeType Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node>::normInf() const {
   using Teuchos::outArg;
   typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType Mag;
   Mag norm = MVT::NormInf(this->lclMV_);
   if (this->isDistributed()) {
     Mag lnorm = norm;
     Teuchos::reduceAll(*this->getMap()->getComm(),Teuchos::REDUCE_MAX,lnorm,outArg(norm));
   }
   return norm;
 }
Esempio n. 15
0
void DiagonalROME<Scalar>::evalModelImpl(
    const Thyra::ModelEvaluatorBase::InArgs<Scalar>& inArgs,
    const Thyra::ModelEvaluatorBase::OutArgs<Scalar>& outArgs
) const
{

    using Teuchos::as;
    using Teuchos::outArg;
    typedef Teuchos::ScalarTraits<Scalar> ST;
    using Thyra::get_mv;
    using Thyra::ConstDetachedSpmdVectorView;
    using Thyra::DetachedSpmdVectorView;
    typedef Thyra::Ordinal Ordinal;
    typedef Thyra::ModelEvaluatorBase MEB;
    typedef MEB::DerivativeMultiVector<Scalar> DMV;

    const ConstDetachedSpmdVectorView<Scalar> p(inArgs.get_p(0));
    const ConstDetachedSpmdVectorView<Scalar> ps(ps_);
    const ConstDetachedSpmdVectorView<Scalar> diag(diag_);
    const ConstDetachedSpmdVectorView<Scalar> s_bar(s_bar_);

    // g(p)
    if (!is_null(outArgs.get_g(0))) {
        Scalar g_val = ST::zero();
        for (Ordinal i = 0; i < p.subDim(); ++i) {
            const Scalar p_ps = p[i] - ps[i];
            g_val += diag[i] * p_ps*p_ps;
            if (nonlinearTermFactor_ != ST::zero()) {
                g_val += nonlinearTermFactor_ * p_ps * p_ps * p_ps;
            }
        }
        Scalar global_g_val;
        Teuchos::reduceAll<Ordinal, Scalar>(*comm_, Teuchos::REDUCE_SUM,
                                            g_val, outArg(global_g_val) );
        DetachedSpmdVectorView<Scalar>(outArgs.get_g(0))[0] =
            as<Scalar>(0.5) * global_g_val + g_offset_;
    }

    // DgDp[i]
    if (!outArgs.get_DgDp(0,0).isEmpty()) {
        const RCP<Thyra::MultiVectorBase<Scalar> > DgDp_trans_mv =
            get_mv<Scalar>(outArgs.get_DgDp(0,0), "DgDp^T", MEB::DERIV_TRANS_MV_BY_ROW);
        const DetachedSpmdVectorView<Scalar> DgDp_grad(DgDp_trans_mv->col(0));
        for (Thyra::Ordinal i = 0; i < p.subDim(); ++i) {
            const Scalar p_ps = p[i] - ps[i];
            Scalar DgDp_grad_i = diag[i] * p_ps;
            if (nonlinearTermFactor_ != ST::zero()) {
                DgDp_grad_i += as<Scalar>(1.5) * nonlinearTermFactor_ * p_ps * p_ps;
            }
            DgDp_grad[i] = DgDp_grad_i / s_bar[i];

        }
    }

}
bool IfpackPreconditionerFactory::isCompatible(
  const LinearOpSourceBase<double> &fwdOpSrc
  ) const
{
  using Teuchos::outArg;
  Teuchos::RCP<const Epetra_Operator> epetraFwdOp;
  EOpTransp epetraFwdOpTransp;
  EApplyEpetraOpAs epetraFwdOpApplyAs;
  EAdjointEpetraOp epetraFwdOpAdjointSupport;
  double epetraFwdOpScalar;
  epetraFwdOpViewExtractor_->getEpetraOpView(
    fwdOpSrc.getOp(), 
    outArg(epetraFwdOp), outArg(epetraFwdOpTransp),
    outArg(epetraFwdOpApplyAs), outArg(epetraFwdOpAdjointSupport),
    outArg(epetraFwdOpScalar)
    );
  if( !dynamic_cast<const Epetra_RowMatrix*>(&*epetraFwdOp) )
    return false;
  return true;
}
bool DiagonalEpetraLinearOpWithSolveFactory::isCompatible(
  const LinearOpSourceBase<double> &fwdOpSrc
  ) const
{
  using Teuchos::outArg;
  RCP<const LinearOpBase<double> >
    fwdOp = fwdOpSrc.getOp();
  const EpetraLinearOpBase *eFwdOp = NULL;
  if( ! (eFwdOp = dynamic_cast<const EpetraLinearOpBase*>(&*fwdOp)) )
    return false;
  RCP<const Epetra_Operator> epetraFwdOp;
  EOpTransp epetraFwdOpTransp;
  EApplyEpetraOpAs epetraFwdOpApplyAs;
  EAdjointEpetraOp epetraFwdOpAdjointSupport;
  eFwdOp->getEpetraOpView(outArg(epetraFwdOp), outArg(epetraFwdOpTransp),
    outArg(epetraFwdOpApplyAs), outArg(epetraFwdOpAdjointSupport) );
  if( !dynamic_cast<const Epetra_RowMatrix*>(&*epetraFwdOp) )
    return false;
  return true;
}
Ordinal SpmdVectorSpaceUtilities::computeGlobalDim(
  const Teuchos::Comm<Ordinal> &comm, const Ordinal localSubDim
  )
{
  using Teuchos::outArg;
  using Teuchos::REDUCE_SUM;
  using Teuchos::reduceAll;

  Ordinal globalDim = -1;
  reduceAll<Ordinal, Ordinal> (comm, REDUCE_SUM, localSubDim, outArg (globalDim));
  return globalDim;
}
Ordinal SpmdVectorSpaceUtilities::computeLocalOffset(
  const Teuchos::Comm<Ordinal> &comm, const Ordinal localSubDim
  )
{
  using Teuchos::outArg;
  using Teuchos::REDUCE_SUM;
  using Teuchos::scan;

  Ordinal localOffset;
  const Ordinal _localOffset = localSubDim;
  scan<Ordinal, Ordinal> (comm, REDUCE_SUM, _localOffset, outArg (localOffset));
  localOffset -= localSubDim;
  return localOffset;
}
void DiagonalEpetraLinearOpWithSolveFactory::initializeOp(
  const RCP<const LinearOpSourceBase<double> >    &fwdOpSrc
  ,LinearOpWithSolveBase<double>                                   *Op
  ,const ESupportSolveUse                                          supportSolveUse
  ) const
{
  using Teuchos::outArg;
  TEST_FOR_EXCEPT(Op==NULL);
  TEST_FOR_EXCEPT(fwdOpSrc.get()==NULL);
  TEST_FOR_EXCEPT(fwdOpSrc->getOp().get()==NULL);
  RCP<const LinearOpBase<double> > fwdOp = fwdOpSrc->getOp();
  const EpetraLinearOpBase &eFwdOp = Teuchos::dyn_cast<const EpetraLinearOpBase>(*fwdOp);
  RCP<const Epetra_Operator> epetraFwdOp;
  EOpTransp epetraFwdOpTransp;
  EApplyEpetraOpAs epetraFwdOpApplyAs;
  EAdjointEpetraOp epetraFwdOpAdjointSupport;
  eFwdOp.getEpetraOpView(outArg(epetraFwdOp), outArg(epetraFwdOpTransp),
    outArg(epetraFwdOpApplyAs), outArg(epetraFwdOpAdjointSupport) );
  const Epetra_RowMatrix &eRMOp  =
    Teuchos::dyn_cast<const Epetra_RowMatrix>(*epetraFwdOp);
  const Epetra_Map &map = eRMOp.OperatorDomainMap();
  RCP<Epetra_Vector>
    e_diag = Teuchos::rcp(new Epetra_Vector(map));
  eRMOp.ExtractDiagonalCopy(*e_diag);
  RCP< const VectorSpaceBase<double> >
    space = create_VectorSpace(Teuchos::rcp(new Epetra_Map(map)));
  RCP< const VectorBase<double> >
    diag = create_Vector(e_diag,space);
  Teuchos::set_extra_data<RCP<const LinearOpSourceBase<double> > >(
    fwdOpSrc, "Thyra::DiagonalEpetraLinearOpWithSolveFactory::fwdOpSrc",
    Teuchos::inOutArg(diag)
    );
  Teuchos::dyn_cast< DefaultDiagonalLinearOpWithSolve<double> >(*Op).initialize(
    Teuchos::rcp_implicit_cast<const VectorBase<double> >(diag)
    );
  // Above cast is questionable but should be okay based on use.
}
  bool
  Map<LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType> >::
  isCompatible (const Map<LocalOrdinal, GlobalOrdinal, node_type>& map) const
  {
    using Teuchos::outArg;
    using Teuchos::REDUCE_MIN;
    using Teuchos::reduceAll;
    //
    // Tests that avoid the Boolean all-reduce below by using
    // globally consistent quantities.
    //
    if (this == &map) {
      // Pointer equality on one process always implies pointer
      // equality on all processes, since Map is immutable.
      return true;
    }
    else if (getComm ()->getSize () != map.getComm ()->getSize ()) {
      // The two communicators have different numbers of processes.
      // It's not correct to call isCompatible() in that case.  This
      // may result in the all-reduce hanging below.
      return false;
    }
    else if (getGlobalNumElements () != map.getGlobalNumElements ()) {
      // Two Maps are definitely NOT compatible if they have different
      // global numbers of indices.
      return false;
    }
    else if (isContiguous () && isUniform () &&
             map.isContiguous () && map.isUniform ()) {
      // Contiguous uniform Maps with the same number of processes in
      // their communicators, and with the same global numbers of
      // indices, are always compatible.
      return true;
    }

    TEUCHOS_TEST_FOR_EXCEPTION(
      getGlobalNumElements () != map.getGlobalNumElements (), std::logic_error,
      "Tpetra::Map::isCompatible: There's a bug in this method.  We've already "
      "checked that this condition is true above, but it's false here.  "
      "Please report this bug to the Tpetra developers.");

    // Do both Maps have the same number of indices on each process?
    const int locallyCompat =
      (getNodeNumElements () == map.getNodeNumElements ()) ? 1 : 0;

    int globallyCompat = 0;
    reduceAll<int, int> (*comm_, REDUCE_MIN, locallyCompat, outArg (globallyCompat));
    return (globallyCompat == 1);
  }
TEUCHOS_UNIT_TEST( Rythmos_StateSerializerStrategy, bools ) {
  std::string data;
  {
    std::ostringstream oss;
    bool a = true;
    XMLStateSerializerStrategy<double> ss;
    ss.serializeBool(a,oss);
    a = false;
    ss.serializeBool(a,oss);
    ss.serializeBool(a,oss);
    data = oss.str();
  }
  {
    std::istringstream iss(data);
    bool a = false;
    XMLStateSerializerStrategy<double> ss;
    ss.deSerializeBool(outArg(a),iss);
    TEST_EQUALITY_CONST(a,true);
    ss.deSerializeBool(outArg(a),iss);
    TEST_EQUALITY_CONST(a,false);
    ss.deSerializeBool(outArg(a),iss);
    TEST_EQUALITY_CONST(a,false);
  }
}
Esempio n. 23
0
  Scalar Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node>::meanValue() const {
    using Teuchos::as;
    using Teuchos::outArg;
    typedef Teuchos::ScalarTraits<Scalar> SCT;

    Scalar sum = MVT::Sum(this->lclMV_);
    if (this->isDistributed()) {
      Scalar lsum = sum;
      Teuchos::reduceAll(*this->getMap()->getComm(),Teuchos::REDUCE_SUM,lsum,outArg(sum));
    }
    // mfh 12 Apr 2012: Don't take out the cast from the ordinal type
    // to the magnitude type, since operator/ (std::complex<T>, int)
    // isn't necessarily defined.
    return sum / as<typename SCT::magnitudeType> (this->getGlobalLength ());
  }
Ordinal SpmdVectorSpaceUtilities::computeMapCode(
  const Teuchos::Comm<Ordinal> &comm, const Ordinal localSubDim
  )
{
  using Teuchos::outArg;
  using Teuchos::REDUCE_SUM;
  using Teuchos::reduceAll;
  //
  // Here we will make a map code out of just the local sub-dimension on each
  // processor.  If each processor has the same number of local elements, then
  // the map codes will be the same and this is all you need for RTOp
  // compatibility.
  //
  const int procRank = comm.getSize ();
  Ordinal mapCode = -1;
  Ordinal localCode = localSubDim % (procRank+1) + localSubDim;
  reduceAll<Ordinal, Ordinal> (comm, REDUCE_SUM, localCode, outArg (mapCode));
  return mapCode;
}
Esempio n. 25
0
  typename Teuchos::ScalarTraits<Scalar>::magnitudeType Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node>::normWeighted(const Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node> &weights) const {
    using Teuchos::ScalarTraits;
    using Teuchos::outArg;
    typedef typename ScalarTraits<Scalar>::magnitudeType Mag;
#ifdef HAVE_TPETRA_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION( !this->getMap()->isCompatible(*weights.getMap()), std::runtime_error,
        "Tpetra::Vector::normWeighted(): Vectors do not have compatible Maps:" << std::endl
        << "this->getMap(): " << std::endl << *this->getMap()
        << "weights.getMap(): " << std::endl << *weights.getMap() << std::endl);
#else
    TEUCHOS_TEST_FOR_EXCEPTION( this->getLocalLength() != weights.getLocalLength(), std::runtime_error,
        "Tpetra::Vector::normWeighted(): Vectors do not have the same local length.");
#endif
    Mag norm = MVT::WeightedNorm(this->lclMV_,weights.lclMV_);
    if (this->isDistributed()) {
      Mag lnorm = norm;
      Teuchos::reduceAll(*this->getMap()->getComm(),Teuchos::REDUCE_SUM,lnorm,outArg(norm));
    }
    return ScalarTraits<Mag>::squareroot(norm / this->getGlobalLength());
  }
SolveStatus<Scalar>
DefaultMultiVectorLinearOpWithSolve<Scalar>::solveImpl(
  const EOpTransp transp,
  const MultiVectorBase<Scalar> &BB,
  const Ptr<MultiVectorBase<Scalar> > &XX,
  const Ptr<const SolveCriteria<Scalar> > solveCriteria
  ) const
{

  using Teuchos::dyn_cast;
  using Teuchos::outArg;
  using Teuchos::inOutArg;
  typedef DefaultMultiVectorProductVector<Scalar> MVPV;

  const Ordinal numCols = BB.domain()->dim();

  SolveStatus<Scalar> overallSolveStatus;
  accumulateSolveStatusInit(outArg(overallSolveStatus));
  
  for (Ordinal col_j = 0; col_j < numCols; ++col_j) {

    const RCP<const VectorBase<Scalar> > b = BB.col(col_j);
    const RCP<VectorBase<Scalar> > x = XX->col(col_j);

    RCP<const MultiVectorBase<Scalar> >
      B = dyn_cast<const MVPV>(*b).getMultiVector().assert_not_null();
    RCP<MultiVectorBase<Scalar> >
      X = dyn_cast<MVPV>(*x).getNonconstMultiVector().assert_not_null();

    const SolveStatus<Scalar> solveStatus =
      Thyra::solve(*lows_.getConstObj(), transp, *B, X.ptr(), solveCriteria);

    accumulateSolveStatus(
      SolveCriteria<Scalar>(), // Never used
      solveStatus, inOutArg(overallSolveStatus) );

  }
  
  return overallSolveStatus;

}
void EpetraOperatorViewExtractorStd::getEpetraOpView(
  const RCP<const LinearOpBase<double> > &fwdOp,
  const Ptr<RCP<const Epetra_Operator> > &epetraOp,
  const Ptr<EOpTransp> &epetraOpTransp,
  const Ptr<EApplyEpetraOpAs> &epetraOpApplyAs,
  const Ptr<EAdjointEpetraOp> &epetraOpAdjointSupport,
    const Ptr<double> &epetraOpScalar
  ) const
{
  using Teuchos::outArg;
  double wrappedFwdOpScalar = 0.0;
  EOpTransp wrappedFwdOpTransp = NOTRANS;
  Teuchos::RCP<const LinearOpBase<double> > wrappedFwdOp; 
  unwrap(fwdOp,&wrappedFwdOpScalar, &wrappedFwdOpTransp, &wrappedFwdOp);
  Teuchos::RCP<const EpetraLinearOpBase> epetraFwdOp =
    Teuchos::rcp_dynamic_cast<const EpetraLinearOpBase>(wrappedFwdOp,true);
  EOpTransp epetra_epetraOpTransp;
  epetraFwdOp->getEpetraOpView(epetraOp, outArg(epetra_epetraOpTransp),
    epetraOpApplyAs, epetraOpAdjointSupport);
  *epetraOpTransp = trans_trans(real_trans(epetra_epetraOpTransp), wrappedFwdOpTransp);
  *epetraOpScalar = wrappedFwdOpScalar;
}
void evaluateCubicSpline(
    const CubicSplineCoeff<Scalar>& coeff,
    Teuchos::Ordinal j, 
    const Scalar& t,
    const Ptr<Thyra::VectorBase<Scalar> >& S,
    const Ptr<Thyra::VectorBase<Scalar> >& Sp, 
    const Ptr<Thyra::VectorBase<Scalar> >& Spp
    )
{
  using Teuchos::outArg;
  using Teuchos::as;
  typedef Teuchos::ScalarTraits<Scalar> ST;
  // Assert preconditions:
  validateCubicSplineCoeff<Scalar>(coeff);
  TEUCHOS_TEST_FOR_EXCEPTION( as<Teuchos::Ordinal>(j) >= coeff.a.size(),
     std::out_of_range, "Error!, j is out of range" );

  Scalar dt = t-coeff.t[j];
  const Thyra::VectorBase<Scalar>& a = *(coeff.a[j]);
  const Thyra::VectorBase<Scalar>& b = *(coeff.b[j]);
  const Thyra::VectorBase<Scalar>& c = *(coeff.c[j]);
  const Thyra::VectorBase<Scalar>& d = *(coeff.d[j]);
  
  if (!Teuchos::is_null(S)) {
    // Evaluate S:
    //*S = (a) + (b)*dt + (c)*dt*dt + (d)*dt*dt*dt;
    V_StVpStV(outArg(*S),dt*dt*dt,d,dt*dt,c);
    Vp_StV(outArg(*S),dt,b);
    Vp_StV(outArg(*S),ST::one(),a);
  } 
  if (!Teuchos::is_null(Sp)) {
    // Evaluate S':
    //*Sp = (b) + (c)*2*dt + (d)*3*dt*dt;
    V_StVpStV(outArg(*Sp),Scalar(3*ST::one())*dt*dt,d,Scalar(2*ST::one())*dt,c);
    Vp_StV(outArg(*Sp),ST::one(),b);
  }
  if (!Teuchos::is_null(Spp)) {
    // Evaluate S'':
    //*Spp = (c)*2 + (d)*6*dt;
    V_StVpStV(outArg(*Spp),Scalar(6*ST::one())*dt,d,Scalar(2*ST::one()),c);
  }
}
void MLPreconditionerFactory::initializePrec(
  const Teuchos::RCP<const LinearOpSourceBase<double> > &fwdOpSrc,
  PreconditionerBase<double> *prec,
  const ESupportSolveUse supportSolveUse
  ) const
{
  using Teuchos::outArg;
  using Teuchos::OSTab;
  using Teuchos::dyn_cast;
  using Teuchos::RCP;
  using Teuchos::null;
  using Teuchos::rcp;
  using Teuchos::rcp_dynamic_cast;
  using Teuchos::rcp_const_cast;
  using Teuchos::set_extra_data;
  using Teuchos::get_optional_extra_data;
  using Teuchos::implicit_cast;
  Teuchos::Time totalTimer(""), timer("");
  totalTimer.start(true);
  const RCP<Teuchos::FancyOStream> out = this->getOStream();
  const Teuchos::EVerbosityLevel verbLevel = this->getVerbLevel();
  Teuchos::OSTab tab(out);
  if(out.get() && implicit_cast<int>(verbLevel) > implicit_cast<int>(Teuchos::VERB_LOW))
    *out << "\nEntering Thyra::MLPreconditionerFactory::initializePrec(...) ...\n";

  Teuchos::RCP<const LinearOpBase<double> > fwdOp = fwdOpSrc->getOp();
#ifdef _DEBUG
  TEUCHOS_TEST_FOR_EXCEPT(fwdOp.get()==NULL);
  TEUCHOS_TEST_FOR_EXCEPT(prec==NULL);
#endif
  //
  // Unwrap and get the forward Epetra_Operator object
  //
  Teuchos::RCP<const Epetra_Operator> epetraFwdOp;
  EOpTransp epetraFwdOpTransp;
  EApplyEpetraOpAs epetraFwdOpApplyAs;
  EAdjointEpetraOp epetraFwdOpAdjointSupport;
  double epetraFwdOpScalar;
  epetraFwdOpViewExtractor_->getEpetraOpView(
    fwdOp,outArg(epetraFwdOp),outArg(epetraFwdOpTransp),outArg(epetraFwdOpApplyAs),
    outArg(epetraFwdOpAdjointSupport),outArg(epetraFwdOpScalar)
                                             );
  // Validate what we get is what we need
  RCP<const Epetra_RowMatrix>
    epetraFwdRowMat = rcp_dynamic_cast<const Epetra_RowMatrix>(epetraFwdOp,true);
  TEUCHOS_TEST_FOR_EXCEPTION(
    epetraFwdOpApplyAs != EPETRA_OP_APPLY_APPLY, std::logic_error
    ,"Error, incorrect apply mode for an Epetra_RowMatrix"
    );

  //
  // Get the concrete preconditioner object
  //
  DefaultPreconditioner<double>
    *defaultPrec = &Teuchos::dyn_cast<DefaultPreconditioner<double> >(*prec);
  //
  // Get the EpetraLinearOp object that is used to implement the preconditoner linear op
  //
  RCP<EpetraLinearOp>
    epetra_precOp = rcp_dynamic_cast<EpetraLinearOp>(defaultPrec->getNonconstUnspecifiedPrecOp(),true);
  //
  // Get the embedded ML_Epetra::MultiLevelPreconditioner object if it exists
  //
  Teuchos::RCP<ML_Epetra::MultiLevelPreconditioner> ml_precOp;
  if(epetra_precOp.get())
    ml_precOp = rcp_dynamic_cast<ML_Epetra::MultiLevelPreconditioner>(epetra_precOp->epetra_op(),true);
  //
  // Get the attached forward operator if it exists and make sure that it matches
  //
  if(ml_precOp!=Teuchos::null) {
    // Get the forward operator and make sure that it matches what is
    // already being used!
    const Epetra_RowMatrix & rm = ml_precOp->RowMatrix();
   
    TEUCHOS_TEST_FOR_EXCEPTION(
       &rm!=&*epetraFwdRowMat, std::logic_error
       ,"ML requires Epetra_RowMatrix to be the same for each initialization of the preconditioner"
       );
  }
  //
  // Perform initialization if needed
  //
  const bool startingOver = (ml_precOp.get() == NULL);
  if(startingOver) 
  {
    if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
      *out << "\nCreating the initial ML_Epetra::MultiLevelPreconditioner object...\n";
    timer.start(true);
    // Create the initial preconditioner: DO NOT compute it yet
    ml_precOp = rcp(
      new ML_Epetra::MultiLevelPreconditioner(
        *epetraFwdRowMat, paramList_->sublist(MLSettings_name),false
        )
      );
    
    timer.stop();
    if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
      OSTab(out).o() <<"> Creation time = "<<timer.totalElapsedTime()<<" sec\n";
    // RAB: Above, I am just passing a string to ML::Create(...) in order
    // get this code written.  However, in the future, it would be good to
    // copy the contents of what is in ML::Create(...) into a local
    // function and then use switch(...) to create the initial
    // ML_Epetra::MultiLevelPreconditioner object.  This would result in better validation
    // and faster code.
    // Set parameters if the list exists
    if(paramList_.get())
      TEUCHOS_TEST_FOR_EXCEPT(
        0!=ml_precOp->SetParameterList(paramList_->sublist(MLSettings_name))
        );
    // Initialize the structure for the preconditioner
    //        TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->Initialize());
  }
  //
  // Attach the epetraFwdOp to the ml_precOp to guarantee that it will not go away
  //
  set_extra_data(epetraFwdOp, "IFPF::epetraFwdOp", Teuchos::inOutArg(ml_precOp),
    Teuchos::POST_DESTROY, false);
  //
  // Update the factorization
  //
  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
    *out << "\nComputing the preconditioner ...\n";
  timer.start(true);
  if (startingOver) {
    TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->ComputePreconditioner());
  }
  else {
    TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->ReComputePreconditioner(paramList_->get<bool>(ReuseFineLevelSmoother_name)));
  }
  timer.stop();
  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
    OSTab(out).o() <<"=> Setup time = "<<timer.totalElapsedTime()<<" sec\n";
  //
  // Compute the conditioner number estimate if asked
  //

  // ToDo: Implement

  //
  // Attach fwdOp to the ml_precOp
  //
  set_extra_data(fwdOp, "IFPF::fwdOp", Teuchos::inOutArg(ml_precOp),
    Teuchos::POST_DESTROY, false);
  //
  // Initialize the output EpetraLinearOp
  //
  if(startingOver) {
    epetra_precOp = rcp(new EpetraLinearOp);
  }
  epetra_precOp->initialize(
    ml_precOp
    ,epetraFwdOpTransp
    ,EPETRA_OP_APPLY_APPLY_INVERSE
    ,EPETRA_OP_ADJOINT_UNSUPPORTED  // ToDo: Look into adjoints again.
    );
  //
  // Initialize the preconditioner
  //
  defaultPrec->initializeUnspecified(
    Teuchos::rcp_implicit_cast<LinearOpBase<double> >(epetra_precOp)
    );
  totalTimer.stop();
  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
    *out << "\nTotal time in MLPreconditionerFactory = "<<totalTimer.totalElapsedTime()<<" sec\n";
  if(out.get() && implicit_cast<int>(verbLevel) > implicit_cast<int>(Teuchos::VERB_LOW))
    *out << "\nLeaving Thyra::MLPreconditionerFactory::initializePrec(...) ...\n";
}
bool BrentsLineSearch<Scalar>::doLineSearch(
  const MeritFunc1DBase<Scalar> &phi,
  const PointEval1D<Scalar> &point_k,
  const Ptr<PointEval1D<Scalar> > &point_kp1,
  const Ptr<int> &numIters
  ) const
{

  using Teuchos::as;
  using Teuchos::OSTab;
  using Teuchos::outArg;
  using Teuchos::inOutArg;
  typedef ScalarTraits<Scalar> ST;
  typedef PointEval1D<Scalar> PE1D;

#ifdef TEUCHOS_DEBUG
  TEUCHOS_ASSERT_EQUALITY(point_k.alpha, ST::zero());
  TEUCHOS_ASSERT_INEQUALITY(point_k.phi, !=, PE1D::valNotGiven());
  TEUCHOS_ASSERT_EQUALITY(point_k.Dphi, PE1D::valNotGiven());
  TEUCHOS_ASSERT(!is_null(point_kp1));
  TEUCHOS_ASSERT_INEQUALITY(point_kp1->alpha, >, ST::zero());
  TEUCHOS_ASSERT_INEQUALITY(point_kp1->phi, !=, PE1D::valNotGiven());
  TEUCHOS_ASSERT_EQUALITY(point_kp1->Dphi, PE1D::valNotGiven());
#endif

  const RCP<Teuchos::FancyOStream> out = this->getOStream();
  bracket_.setOStream(out);
  brentsMin_.setOStream(out);

  *out << "\nStarting bracketing and brents 1D minimization linesearch ...\n";

  OSTab tab(out);

  int totalNumIters = 0;

  PointEval1D<Scalar> p_l = point_k;
  PointEval1D<Scalar> &p_m = *point_kp1; // Update in place!
  PointEval1D<Scalar> p_u;

  bool success = true;

  // A) Bracket the minimum

  int numBracketIters = -1;

  const bool bracketSuccess = bracket_.bracketMinimum(
    phi, inOutArg(p_l), inOutArg(p_m), outArg(p_u), outArg(numBracketIters) );

  if (!bracketSuccess) success = false;

  totalNumIters += numBracketIters;

  // B) Do approximate mimimization in the bracket

  if (bracketSuccess) {

    int numBrentsIters = -1;
    
    const bool brentsSuccess = brentsMin_.approxMinimize(
      phi, p_l, inOutArg(p_m), p_u, outArg(numBrentsIters) );
    
    if (!brentsSuccess) success = false;
    
    totalNumIters += numBrentsIters;

  }

  // C) Overall success?

  if (!is_null(numIters))
    *numIters = totalNumIters;

  return success;
  
}