Example #1
0
  TEUCHOS_UNIT_TEST( Stokhos_ProductBasisUtils, TotalOrderBasis ) {
    success = true;

    // Build index set of dimension d and order p
    typedef Stokhos::TotalOrderIndexSet<ordinal_type> index_set_type;
    typedef index_set_type::multiindex_type multiindex_type;
    typedef index_set_type::iterator iterator;
    index_set_type indexSet(setup.d, 0, setup.p);

    // Build total-order basis from index set
    typedef Stokhos::TensorProductElement<ordinal_type,ordinal_type> coeff_type;
    typedef Stokhos::TotalOrderLess<coeff_type> less_type;
    typedef std::map<coeff_type, ordinal_type, less_type> basis_set_type;
    typedef basis_set_type::iterator basis_set_iterator;
    typedef Teuchos::Array<coeff_type> basis_map_type;
    basis_set_type basis_set;
    basis_map_type basis_map;
    Stokhos::ProductBasisUtils::buildProductBasis(
      indexSet, basis_set, basis_map);

    // Build total-order basis directly
    ordinal_type sz;
    Teuchos::Array< Stokhos::MultiIndex<ordinal_type> > terms;
    Teuchos::Array<ordinal_type> num_terms;
    Stokhos::CompletePolynomialBasisUtils<ordinal_type,value_type>::
      compute_terms(setup.p, setup.d, sz, terms, num_terms);

    // Check sizes
    TEUCHOS_TEST_EQUALITY(static_cast<ordinal_type>(basis_set.size()), 
			  static_cast<ordinal_type>(basis_map.size()), 
			  out, success);
    TEUCHOS_TEST_EQUALITY(static_cast<ordinal_type>(basis_set.size()), 
			  static_cast<ordinal_type>(terms.size()), 
			  out, success);
    TEUCHOS_TEST_EQUALITY(sz, static_cast<ordinal_type>(terms.size()), 
			  out, success);

    std::ostream_iterator<ordinal_type> out_iterator(out, " ");
    for (ordinal_type i=0; i<sz; i++) {

      // Verify terms match
      out << "term " << basis_map[i] << " == " << terms[i] << " : ";
      bool is_equal = true;
      for (ordinal_type j=0; j<setup.d; j++)
	is_equal = is_equal && terms[i][j] == basis_map[i][j];
      if (is_equal)
	out << "passed" << std::endl;
      else {
	out << "failed" << std::endl;
	success = false; 
      }

      // Verify global index mapping matches
      TEUCHOS_TEST_EQUALITY(basis_set[basis_map[i]], i, out, success);
    }

  }
      //! Print eigenpair
      void print(std::ostream& os) const {
	os << eig_val << ", ";
	for (std::size_t i=0; i<eig_pairs.size()-1; i++) {
	  os << "(";
	  eig_pairs[i].eig_func->print(os);
	  os << ") * ";
	}
	os << "(";
	eig_pairs[eig_pairs.size()-1].eig_func->print(os);
	os << ")";
      }
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( NanoflannTree, dim_3_factory_test )
{
    int dim = 3;
    int num_points = 10;
    int num_coords = dim*num_points;

    Teuchos::Array<double> coords(num_coords);
    for ( int i = 0; i < num_points; ++i )
    {
        coords[dim*i] = 1.0*i;
        coords[dim*i+1] = 1.0;
        coords[dim*i+2] = 1.0;
    }

    int max_leaf_size = 3;
    Teuchos::RCP<DataTransferKit::StaticSearchTree> tree =
        DataTransferKit::SearchTreeFactory::createStaticTree(
            3, coords(), max_leaf_size );

    Teuchos::Array<double> p1( dim );
    p1[0] = 4.9;
    p1[1] = 1.0;
    p1[2] = 1.0;
    Teuchos::Array<double> p2( dim );
    p2[0] = 11.4;
    p2[1] = 1.0;
    p2[2] = 1.0;

    int num_neighbors = 1;
    Teuchos::Array<unsigned> nnearest =
        tree->nnSearch( p1(), num_neighbors );
    TEST_EQUALITY( num_neighbors, nnearest.size() );
    TEST_EQUALITY( 5, nnearest[0] );

    nnearest = tree->nnSearch( p2(), num_neighbors );
    TEST_EQUALITY( num_neighbors, nnearest.size() );
    TEST_EQUALITY( 9, nnearest[0] );

    double radius = 1.1;
    nnearest = tree->radiusSearch( p1(), radius );
    TEST_EQUALITY( 3, nnearest.size() );
    TEST_EQUALITY( 5, nnearest[0] )
    TEST_EQUALITY( 4, nnearest[1] )
    TEST_EQUALITY( 6, nnearest[2] )

    nnearest = tree->radiusSearch( p2(), radius );
    TEST_EQUALITY( 0, nnearest.size() );

    radius = 2.41;
    nnearest = tree->radiusSearch( p2(), radius );
    TEST_EQUALITY( 1, nnearest.size() );
    TEST_EQUALITY( 9, nnearest[0] )
}
/*
 * Construct from an array of vectors and a specifier for the 
 * domain space. 
 */
template <class Scalar> inline
MultiVectorOperator<Scalar>
::MultiVectorOperator(const Teuchos::Array<Vector<Scalar> >& cols,
  const VectorSpace<Scalar>& domain)
  : LinearOpWithSpaces<Scalar>(domain, cols[0].space()),
    cols_(cols)
{
  TEUCHOS_TEST_FOR_EXCEPTION(cols.size() == 0, std::runtime_error,
    "empty multivector given to MultiVectorOperator ctor");
  for (int i=1; i<cols.size(); i++)
  {
    TEUCHOS_TEST_FOR_EXCEPTION(cols[i].space() != cols[0].space(), std::runtime_error,
      "inconsistent vector spaces in  MultiVectorOperator ctor");
  }
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( NanoflannTree, dim_2_test )
{
    int dim = 2;
    int num_points = 10;
    int num_coords = dim*num_points;

    Teuchos::Array<double> coords(num_coords);
    for ( int i = 0; i < num_points; ++i )
    {
        coords[dim*i] = 1.0*i;
        coords[dim*i+1] = 1.0;
    }

    int max_leaf_size = 2;
    DataTransferKit::NanoflannTree<2> tree( coords(), max_leaf_size );

    Teuchos::Array<double> p1( dim );
    p1[0] = 4.9;
    p1[1] = 1.0;
    Teuchos::Array<double> p2( dim );
    p2[0] = 11.4;
    p2[1] = 1.0;

    int num_neighbors = 1;
    Teuchos::Array<unsigned> nnearest =
        tree.nnSearch( p1(), num_neighbors );
    TEST_EQUALITY( num_neighbors, nnearest.size() );
    TEST_EQUALITY( 5, nnearest[0] );

    nnearest = tree.nnSearch( p2(), num_neighbors );
    TEST_EQUALITY( num_neighbors, nnearest.size() );
    TEST_EQUALITY( 9, nnearest[0] );

    double radius = 1.1;
    nnearest = tree.radiusSearch( p1(), radius );
    TEST_EQUALITY( 3, nnearest.size() );
    TEST_EQUALITY( 5, nnearest[0] )
    TEST_EQUALITY( 4, nnearest[1] )
    TEST_EQUALITY( 6, nnearest[2] )

    nnearest = tree.radiusSearch( p2(), radius );
    TEST_EQUALITY( 0, nnearest.size() );

    radius = 2.41;
    nnearest = tree.radiusSearch( p2(), radius );
    TEST_EQUALITY( 1, nnearest.size() );
    TEST_EQUALITY( 9, nnearest[0] )
}
void
Albany::SamplingBasedScalarResponseFunction::
evaluateSGResponse(
  const double curr_time,
  const Stokhos::EpetraVectorOrthogPoly* sg_xdot,
  const Stokhos::EpetraVectorOrthogPoly* sg_xdotdot,
  const Stokhos::EpetraVectorOrthogPoly& sg_x,
  const Teuchos::Array<ParamVec>& p,
  const Teuchos::Array<int>& sg_p_index,
  const Teuchos::Array< Teuchos::Array<SGType> >& sg_p_vals,
  Stokhos::EpetraVectorOrthogPoly& sg_g)
{
  RCP<const Epetra_BlockMap> x_map = sg_x.coefficientMap();
  RCP<Epetra_Vector> xdot;
  if (sg_xdot != NULL)
    xdot = rcp(new Epetra_Vector(*x_map));
  RCP<Epetra_Vector> xdotdot;
  if (sg_xdotdot != NULL)
    xdotdot = rcp(new Epetra_Vector(*x_map));
  Epetra_Vector x(*x_map);
  Teuchos::Array<ParamVec> pp = p;
  
  RCP<const Epetra_BlockMap> g_map = sg_g.coefficientMap();
  Epetra_Vector g(*g_map);

  // Get quadrature data
  const Teuchos::Array<double>& norms = basis->norm_squared();
  const Teuchos::Array< Teuchos::Array<double> >& points = 
    quad->getQuadPoints();
  const Teuchos::Array<double>& weights = quad->getQuadWeights();
  const Teuchos::Array< Teuchos::Array<double> >& vals = 
    quad->getBasisAtQuadPoints();
  int nqp = points.size();

  // Compute sg_g via quadrature
  sg_g.init(0.0);
  SGConverter c(this, commT);
  for (int qp=0; qp<nqp; qp++) {

    // Evaluate sg_x, sg_xdot at quadrature point
    sg_x.evaluate(vals[qp], x);
    if (sg_xdot != NULL)
      sg_xdot->evaluate(vals[qp], *xdot);
    if (sg_xdotdot != NULL)
      sg_xdotdot->evaluate(vals[qp], *xdotdot);

    // Evaluate parameters at quadrature point
    for (int i=0; i<sg_p_index.size(); i++) {
      int ii = sg_p_index[i];
      for (unsigned int j=0; j<pp[ii].size(); j++)
	pp[ii][j].baseValue = sg_p_vals[ii][j].evaluate(points[qp], vals[qp]);
    }

    // Compute response at quadrature point
    c.evaluateResponse(curr_time, xdot.get(), xdotdot.get(), x, pp, g);

    // Add result into integral
    sg_g.sumIntoAllTerms(weights[qp], vals[qp], norms, g);
  }
}
void
Albany::SamplingBasedScalarResponseFunction::
evaluateMPResponse(
  const double curr_time,
  const Stokhos::ProductEpetraVector* mp_xdot,
  const Stokhos::ProductEpetraVector* mp_xdotdot,
  const Stokhos::ProductEpetraVector& mp_x,
  const Teuchos::Array<ParamVec>& p,
  const Teuchos::Array<int>& mp_p_index,
  const Teuchos::Array< Teuchos::Array<MPType> >& mp_p_vals,
  Stokhos::ProductEpetraVector& mp_g)
{
  Teuchos::Array<ParamVec> pp = p;
  const Epetra_Vector* xdot = NULL;
  const Epetra_Vector* xdotdot = NULL;

  SGConverter c(this, commT);
  for (int i=0; i<mp_x.size(); i++) {

    for (int k=0; k<mp_p_index.size(); k++) {
      int kk = mp_p_index[k];
      for (unsigned int j=0; j<pp[kk].size(); j++)
	pp[kk][j].baseValue = mp_p_vals[kk][j].coeff(i);
    }

    if (mp_xdot != NULL)
      xdot = mp_xdot->getCoeffPtr(i).get();
    if (mp_xdotdot != NULL)
      xdotdot = mp_xdotdot->getCoeffPtr(i).get();
    
    // Evaluate response function
    c.evaluateResponse(curr_time, xdot, xdotdot, mp_x[i], pp, mp_g[i]);
  }
}
Example #8
0
void getD2_ij_FromMultiplicities(int &i, int &j, const Teuchos::Array<int> &multiplicities)
{
  bool i_assigned = false;
  for (int k=0; k<multiplicities.size(); k++)
  {
    if (multiplicities[k] == 2)
    {
      i = k;
      j = k;
      return;
    }
    else if (multiplicities[k] == 1)
    {
      if (! i_assigned)
      {
        i = k;
        i_assigned = true;
      }
      else
      {
        j = k;
        return;
      }
    }
  }
  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, "i,j not identified from multiplicities...")
}
 RiskVector( Teuchos::ParameterList &parlist,
       const Teuchos::RCP<Vector<Real> > &vec,
       const Real stat = 1. )
   : vec_(vec), augmented_(false), nStat_(0) {
   stat_.clear();
   dual_vec1_ = vec->dual().clone();
   std::string type = parlist.sublist("SOL").sublist("Risk Measure").get("Name","CVaR");
   if ( type == "CVaR"                       ||
        type == "HMCR"                       ||
        type == "KL Divergence"              ||
        type == "Moreau-Yosida CVaR"         ||
        type == "Log-Exponential Quadrangle" ||
        type == "Log-Quantile Quadrangle"    ||
        type == "Quantile-Based Quadrangle"  ||
        type == "Truncated Mean Quadrangle" ) {
     augmented_ = true;
     nStat_     = 1;
     stat_.resize(nStat_,stat);
   }
   else if ( type == "Mixed-Quantile Quadrangle" ) {
     Teuchos::ParameterList &list
       = parlist.sublist("SOL").sublist("Risk Measure").sublist("Mixed-Quantile Quadrangle");
     Teuchos::Array<Real> prob
       = Teuchos::getArrayFromStringParameter<Real>(list,"Probability Array");
     augmented_ = true;
     nStat_     = prob.size();
     stat_.resize(nStat_,stat);
   }
   else if ( type == "Quantile-Radius Quadrangle" ) {
     augmented_ = true;
     nStat_     = 2;
     stat_.resize(nStat_,stat);
   }
 }
Teuchos::RCP<Epetra_Map>
Albany::SolutionResponseFunction::
buildCulledMap(const Epetra_Map& x_map,
	       const Teuchos::Array<int>& keepDOF) const
{
  int numKeepDOF = std::accumulate(keepDOF.begin(), keepDOF.end(), 0);
  int Neqns = keepDOF.size();
  int N = x_map.NumMyElements(); // x_map is map for solution vector

  TEUCHOS_ASSERT( !(N % Neqns) ); // Assume that all the equations for
                                  // a given node are on the assigned
                                  // processor. I.e. need to ensure
                                  // that N is exactly Neqns-divisible

  int nnodes = N / Neqns;          // number of fem nodes
  int N_new = nnodes * numKeepDOF; // length of local x_new

  int *gids = x_map.MyGlobalElements(); // Fill local x_map into gids array
  Teuchos::Array<int> gids_new(N_new);
  int idx = 0;
  for ( int inode = 0; inode < N/Neqns ; ++inode) // For every node
    for ( int ieqn = 0; ieqn < Neqns; ++ieqn )  // Check every dof on the node
      if ( keepDOF[ieqn] == 1 )  // then want to keep this dof
	gids_new[idx++] = gids[(inode*Neqns)+ieqn];
  // end cull

  Teuchos::RCP<Epetra_Map> x_new_map =
    Teuchos::rcp( new Epetra_Map( -1, N_new, &gids_new[0], 0, x_map.Comm() ) );

  return x_new_map;
}
Example #11
0
 void values(FieldContainer<double> &values, BasisCachePtr sliceBasisCache) {
   vector<GlobalIndexType> sliceCellIDs = sliceBasisCache->cellIDs();
   
   Teuchos::Array<int> dim;
   values.dimensions(dim);
   dim[0] = 1; // one cell
   Teuchos::Array<int> offset(dim.size());
   
   for (int cellOrdinal = 0; cellOrdinal < sliceCellIDs.size(); cellOrdinal++) {
     offset[0] = cellOrdinal;
     int enumeration = values.getEnumeration(offset);
     FieldContainer<double>valuesForCell(dim,&values[enumeration]);
     GlobalIndexType sliceCellID = sliceCellIDs[cellOrdinal];
     int numPoints = sliceBasisCache->getPhysicalCubaturePoints().dimension(1);
     int spaceDim = sliceBasisCache->getPhysicalCubaturePoints().dimension(2);
     FieldContainer<double> spaceTimePhysicalPoints(1,numPoints,spaceDim+1);
     for (int ptOrdinal=0; ptOrdinal<numPoints; ptOrdinal++) {
       for (int d=0; d<spaceDim; d++) {
         spaceTimePhysicalPoints(0,ptOrdinal,d) = sliceBasisCache->getPhysicalCubaturePoints()(cellOrdinal,ptOrdinal,d);
       }
       spaceTimePhysicalPoints(0,ptOrdinal,spaceDim) = _t;
     }
     
     GlobalIndexType cellID = _cellIDMap[sliceCellID];
     BasisCachePtr spaceTimeBasisCache = BasisCache::basisCacheForCell(_spaceTimeMesh, cellID);
     
     FieldContainer<double> spaceTimeRefPoints(1,numPoints,spaceDim+1);
     CamelliaCellTools::mapToReferenceFrame(spaceTimeRefPoints, spaceTimePhysicalPoints, _spaceTimeMesh, cellID);
     spaceTimeRefPoints.resize(numPoints,spaceDim+1);
     spaceTimeBasisCache->setRefCellPoints(spaceTimeRefPoints);
     _spaceTimeFunction->values(valuesForCell, spaceTimeBasisCache);
   }
 }
Example #12
0
Teuchos::Array<EpetraGlobalIndex> getMyLIDs(
    const Epetra_BlockMap &map,
    const Teuchos::ArrayView<const EpetraGlobalIndex> &selectedGIDs)
{
  Teuchos::Array<EpetraGlobalIndex> sortedMyGIDs(map.MyGlobalElements(), map.MyGlobalElements() + map.NumMyElements());
  std::sort(sortedMyGIDs.begin(), sortedMyGIDs.end());

  Teuchos::Array<EpetraGlobalIndex> sortedSelectedGIDs(selectedGIDs);
  std::sort(sortedSelectedGIDs.begin(), sortedSelectedGIDs.end());

  Teuchos::Array<EpetraGlobalIndex> mySelectedGIDs;
  std::set_intersection(sortedMyGIDs.begin(), sortedMyGIDs.end(),
                        sortedSelectedGIDs.begin(), sortedSelectedGIDs.end(),
                        std::back_inserter(mySelectedGIDs));

  Teuchos::Array<EpetraGlobalIndex> result;
  result.reserve(mySelectedGIDs.size());

  std::transform(
      mySelectedGIDs.begin(), mySelectedGIDs.end(),
      std::back_inserter(result),
      std::bind1st(std::mem_fun_ref(static_cast<int(Epetra_BlockMap::*)(EpetraGlobalIndex) const>(&Epetra_BlockMap::LID)), map));

  return result;
}
Example #13
0
      //! Evaluate eigenfunction at a given point
      value_type evalEigenfunction(const Teuchos::Array<value_type>& x) const {
	value_type result = 1.0;
	std::size_t sz = eig_pairs.size();
	for (std::size_t i=0; i<sz; i++)
	  result *= eig_pairs[i].eig_func->evaluate(x[i]);
	return result;
      }
Example #14
0
      //! Constructor
      ProductEigenPair(
	const Teuchos::Array< OneDEigenPair<value_type> >& eig_pairs_) 
	: eig_val(1.0), eig_pairs(eig_pairs_) {
	std::size_t sz = eig_pairs.size();
	for (std::size_t i=0; i<sz; i++)
	  eig_val *= eig_pairs[i].eig_val;
      }
Teuchos::RCP<const Tpetra_Map>
Albany::SolutionResponseFunction::
buildCulledMapT(const Tpetra_Map& x_mapT,
	       const Teuchos::Array<int>& keepDOF) const
{
  int numKeepDOF = std::accumulate(keepDOF.begin(), keepDOF.end(), 0);
  int Neqns = keepDOF.size();
  int N = x_mapT.getNodeNumElements(); // x_mapT is map for solution vector

  TEUCHOS_ASSERT( !(N % Neqns) ); // Assume that all the equations for
                                  // a given node are on the assigned
                                  // processor. I.e. need to ensure
                                  // that N is exactly Neqns-divisible

  int nnodes = N / Neqns;          // number of fem nodes
  int N_new = nnodes * numKeepDOF; // length of local x_new

  Teuchos::ArrayView<const GO> gidsT = x_mapT.getNodeElementList();
  Teuchos::Array<GO> gids_new(N_new);
  int idx = 0;
  for ( int inode = 0; inode < N/Neqns ; ++inode) // For every node
    for ( int ieqn = 0; ieqn < Neqns; ++ieqn )  // Check every dof on the node
      if ( keepDOF[ieqn] == 1 )  // then want to keep this dof
	gids_new[idx++] = gidsT[(inode*Neqns)+ieqn];
  // end cull

  Teuchos::RCP<const Tpetra_Map> x_new_mapT = Tpetra::createNonContigMapWithNode<LO, GO, KokkosNode> (gids_new, x_mapT.getComm(), x_mapT.getNode());

  return x_new_mapT;

}
Teuchos::Array<int>
Albany::NodeSetSolutionCullingStrategy::
selectedGIDs(const Epetra_BlockMap &sourceMap) const
{
  Teuchos::Array<int> result;
  {
    Teuchos::Array<int> mySelectedGIDs;
    {
      const NodeSetList &nodeSets = disc_->getNodeSets();

      const NodeSetList::const_iterator it = nodeSets.find(nodeSetLabel_);
      if (it != nodeSets.end()) {
        typedef NodeSetList::mapped_type NodeSetEntryList;
        const NodeSetEntryList &sampleNodeEntries = it->second;

        for (NodeSetEntryList::const_iterator jt = sampleNodeEntries.begin(); jt != sampleNodeEntries.end(); ++jt) {
          typedef NodeSetEntryList::value_type NodeEntryList;
          const NodeEntryList &sampleEntries = *jt;
          for (NodeEntryList::const_iterator kt = sampleEntries.begin(); kt != sampleEntries.end(); ++kt) {
            mySelectedGIDs.push_back(sourceMap.GID(*kt));
          }
        }
      }
    }

    const Epetra_Comm &comm = sourceMap.Comm();

    {
      int selectedGIDCount;
      {
        int mySelectedGIDCount = mySelectedGIDs.size();
        comm.SumAll(&mySelectedGIDCount, &selectedGIDCount, 1);
      }
      result.resize(selectedGIDCount);
    }

    const int ierr = Epetra::GatherAllV(
        comm,
        mySelectedGIDs.getRawPtr(), mySelectedGIDs.size(),
        result.getRawPtr(), result.size());
    TEUCHOS_ASSERT(ierr == 0);
  }

  std::sort(result.begin(), result.end());

  return result;
}
void
Albany::SamplingBasedScalarResponseFunction::
evaluateMPGradient(
  const double current_time,
  const Stokhos::ProductEpetraVector* mp_xdot,
  const Stokhos::ProductEpetraVector* mp_xdotdot,
  const Stokhos::ProductEpetraVector& mp_x,
  const Teuchos::Array<ParamVec>& p,
  const Teuchos::Array<int>& mp_p_index,
  const Teuchos::Array< Teuchos::Array<MPType> >& mp_p_vals,
  ParamVec* deriv_p,
  Stokhos::ProductEpetraVector* mp_g,
  Stokhos::ProductEpetraMultiVector* mp_dg_dx,
  Stokhos::ProductEpetraMultiVector* mp_dg_dxdot,
  Stokhos::ProductEpetraMultiVector* mp_dg_dxdotdot,
  Stokhos::ProductEpetraMultiVector* mp_dg_dp)
{
  Teuchos::Array<ParamVec> pp = p;
  const Epetra_Vector* xdot = NULL;
  const Epetra_Vector* xdotdot = NULL;
  Epetra_Vector* g = NULL;
  Epetra_MultiVector* dg_dx = NULL;
  Epetra_MultiVector* dg_dxdot = NULL;
  Epetra_MultiVector* dg_dxdotdot = NULL;
  Epetra_MultiVector* dg_dp = NULL;
  for (int i=0; i<mp_x.size(); i++) {

    for (int k=0; k<mp_p_index.size(); k++) {
      int kk = mp_p_index[k];
      for (unsigned int j=0; j<pp[kk].size(); j++) {
	pp[kk][j].baseValue = mp_p_vals[kk][j].coeff(i);
	if (deriv_p != NULL) {
	  for (unsigned int l=0; l<deriv_p->size(); l++)
	    if ((*deriv_p)[l].family->getName() == pp[kk][j].family->getName())
	      (*deriv_p)[l].baseValue = pp[kk][j].baseValue;
	}
      }
    }

    if (mp_xdot != NULL)
      xdot = mp_xdot->getCoeffPtr(i).get();
    if (mp_xdotdot != NULL)
      xdotdot = mp_xdotdot->getCoeffPtr(i).get();
    if (mp_g != NULL)
      g = mp_g->getCoeffPtr(i).get();
    if (mp_dg_dx != NULL)
      dg_dx = mp_dg_dx->getCoeffPtr(i).get();
    if(mp_dg_dxdot != NULL)
      dg_dxdot = mp_dg_dxdot->getCoeffPtr(i).get();
    if(mp_dg_dxdotdot != NULL)
      dg_dxdotdot = mp_dg_dxdotdot->getCoeffPtr(i).get();
    if (mp_dg_dp != NULL)
      dg_dp = mp_dg_dp->getCoeffPtr(i).get();
    
    // Evaluate response function
    evaluateGradient(current_time, xdot, xdotdot,  mp_x[i], pp, deriv_p, 
		     g, dg_dx, dg_dxdot, dg_dxdotdot, dg_dp);
  }
}
Example #18
0
Stokhos::TensorProductBasis<ordinal_type, value_type, ordering_type>::
TensorProductBasis(
  const Teuchos::Array< Teuchos::RCP<const OneDOrthogPolyBasis<ordinal_type, value_type> > >& bases_,
  const value_type& sparse_tol_,
  const Stokhos::MultiIndex<ordinal_type>& index,
  const ordering_type& coeff_compare) :
  p(0),
  d(bases_.size()),
  sz(0),
  bases(bases_),
  sparse_tol(sparse_tol_),
  max_orders(d),
  basis_set(coeff_compare),
  norms()
{
  // Resize bases for given index if necessary
  if (index.dimension() > 0) {
    for (ordinal_type i=0; i<d; i++) {
      if (index[i] != bases[i]->order())
	bases[i] = bases[i]->cloneWithOrder(index[i]);
    }
  }

  // Compute largest order
  for (ordinal_type i=0; i<d; i++) {
    max_orders[i] = bases[i]->order();
    if (max_orders[i] > p)
      p = max_orders[i];
  }

  // Compute basis terms
  MultiIndex<ordinal_type> orders(d);
  for (ordinal_type i=0; i<d; ++i)
    orders[i] = bases[i]->order();
  TensorProductIndexSet<ordinal_type> index_set(orders);
  ProductBasisUtils::buildProductBasis(index_set, basis_set, basis_map);
  sz = basis_map.size();
    
  // Compute norms
  norms.resize(sz);
  value_type nrm;
  for (ordinal_type k=0; k<sz; k++) {
    nrm = value_type(1.0);
    for (ordinal_type i=0; i<d; i++)
      nrm = nrm * bases[i]->norm_squared(basis_map[k][i]);
    norms[k] = nrm;
  }

  // Create name
  name = "Tensor product basis (";
  for (ordinal_type i=0; i<d-1; i++)
    name += bases[i]->getName() + ", ";
  name += bases[d-1]->getName() + ")";

  // Allocate array for basis evaluation
  basis_eval_tmp.resize(d);
  for (ordinal_type j=0; j<d; j++)
    basis_eval_tmp[j].resize(max_orders[j]+1);
}
 void checkInputs(void) const {
   int pSize = prob_.size(), cSize = coeff_.size();
   TEUCHOS_TEST_FOR_EXCEPTION((pSize!=cSize),std::invalid_argument,
     ">>> ERROR (ROL::MixedQuantileQuadrangle): Probability and coefficient arrays have different sizes!");
   Real sum(0), zero(0), one(1);
   for (int i = 0; i < pSize; i++) {
     TEUCHOS_TEST_FOR_EXCEPTION((prob_[i]>one || prob_[i]<zero), std::invalid_argument,
       ">>> ERROR (ROL::MixedQuantileQuadrangle): Element of probability array out of range!");
     TEUCHOS_TEST_FOR_EXCEPTION((coeff_[i]>one || coeff_[i]<zero), std::invalid_argument,
       ">>> ERROR (ROL::MixedQuantileQuadrangle): Element of coefficient array out of range!");
     sum += coeff_[i];
   }
   TEUCHOS_TEST_FOR_EXCEPTION((std::abs(sum-one) > std::sqrt(ROL_EPSILON<Real>())),std::invalid_argument,
     ">>> ERROR (ROL::MixedQuantileQuadrangle): Coefficients do not sum to one!");
   TEUCHOS_TEST_FOR_EXCEPTION(plusFunction_ == Teuchos::null, std::invalid_argument,
     ">>> ERROR (ROL::MixedQuantileQuadrangle): PlusFunction pointer is null!");
 }
Example #20
0
void
Stokhos::StieltjesPCEBasis<ordinal_type, value_type>::
getQuadPoints(ordinal_type quad_order,
	      Teuchos::Array<value_type>& quad_points,
	      Teuchos::Array<value_type>& quad_weights,
	      Teuchos::Array< Teuchos::Array<value_type> >& quad_values) const
{
#ifdef STOKHOS_TEUCHOS_TIME_MONITOR
  TEUCHOS_FUNC_TIME_MONITOR("Stokhos::StieltjesPCEBasis -- compute Gauss points");
#endif

  // Use underlying pce's quad points, weights, values
  if (use_pce_quad_points) {
    quad_points = pce_vals;
    quad_weights = pce_weights;
    quad_values = phi_vals;
    return;
  }

  // Call base class
  ordinal_type num_points = 
    static_cast<ordinal_type>(std::ceil((quad_order+1)/2.0));

  // We can't reliably generate quadrature points of order > 2*p
  //if (!project_integrals && quad_order > 2*this->p)
  if (quad_order > 2*this->p)
    quad_order = 2*this->p;
  Stokhos::RecurrenceBasis<ordinal_type,value_type>::getQuadPoints(quad_order, 
								   quad_points, 
								   quad_weights,
								   quad_values);

  // Fill in the rest of the points with zero weight
  if (quad_weights.size() < num_points) {
    ordinal_type old_size = quad_weights.size();
    quad_weights.resize(num_points);
    quad_points.resize(num_points);
    quad_values.resize(num_points);
    for (ordinal_type i=old_size; i<num_points; i++) {
      quad_weights[i] = value_type(0);
      quad_points[i] = quad_points[0];
      quad_values[i].resize(this->p+1);
      this->evaluateBases(quad_points[i], quad_values[i]);
    }
  }
}
Teuchos::Array<GO>
Albany::NodeSetSolutionCullingStrategy::
selectedGIDsT(Teuchos::RCP<const Tpetra_Map> sourceMapT) const
{
  Teuchos::Array<GO> result;
  {
    Teuchos::Array<GO> mySelectedGIDs;
    {
      const NodeSetList &nodeSets = disc_->getNodeSets();

      const NodeSetList::const_iterator it = nodeSets.find(nodeSetLabel_);
      if (it != nodeSets.end()) {
        typedef NodeSetList::mapped_type NodeSetEntryList;
        const NodeSetEntryList &sampleNodeEntries = it->second;

        for (NodeSetEntryList::const_iterator jt = sampleNodeEntries.begin(); jt != sampleNodeEntries.end(); ++jt) {
          typedef NodeSetEntryList::value_type NodeEntryList;
          const NodeEntryList &sampleEntries = *jt;
          for (NodeEntryList::const_iterator kt = sampleEntries.begin(); kt != sampleEntries.end(); ++kt) {
            mySelectedGIDs.push_back(sourceMapT->getGlobalElement(*kt));
          }
        }
      }
    }

    Teuchos::RCP<const Teuchos::Comm<int> >commT = sourceMapT->getComm(); 
    {
      GO selectedGIDCount;
      {
        GO mySelectedGIDCount = mySelectedGIDs.size();
        Teuchos::reduceAll<LO, GO>(*commT, Teuchos::REDUCE_SUM, 1, &mySelectedGIDCount, &selectedGIDCount); 
      }
      result.resize(selectedGIDCount);
    }

    const int ierr = Tpetra::GatherAllV(
        commT,
        mySelectedGIDs.getRawPtr(), mySelectedGIDs.size(),
        result.getRawPtr(), result.size());
    TEUCHOS_ASSERT(ierr == 0);
  }

  std::sort(result.begin(), result.end());

  return result;
}
 void initialize(void) {
   size_ = prob_.size();
   // Initialize temporary storage
   Real zero(0);
   xvar_.clear(); xvar_.resize(size_,zero);
   vvar_.clear(); vvar_.resize(size_,zero);
   vec_.clear();  vec_.resize(size_,zero);
 }
 void interpolate(const std::vector<double>& positions,
   std::vector<double>& results) const 
   {
     Teuchos::Array<double> in(positions.size());
     for (int i=0; i<in.size(); i++) in[i] = positions[i];
     Teuchos::Array<double> out;
     interpolate(in, out);
     for (int i=0; i<out.size(); i++) results[i] = out[i];
   }
void
Stokhos::StieltjesGramSchmidtBuilder<ordinal_type,value_type>::
computeReducedPCEs(
  const Teuchos::Array< Stokhos::OrthogPolyApprox<ordinal_type, value_type> >& pces,
  Teuchos::Array< Stokhos::OrthogPolyApprox<ordinal_type, value_type> >& new_pces)
{
  // Map pce coefficients to tensor basis to Gram-Schmidt basis
  ordinal_type dim = pces.size();
  if (new_pces.size() != pces.size())
    new_pces.resize(dim);
  for (ordinal_type k=0; k<dim; k++) {
    OrthogPolyApprox<ordinal_type,value_type> p_tensor(tensor_basis);
    p_tensor.term(k, 0) = pces[k].mean();
    p_tensor.term(k, 1) = 1.0; 
    new_pces[k].reset(gs_basis);
    gs_basis->transformCoeffs(p_tensor.coeff(), new_pces[k].coeff());
  }
}
Example #25
0
FELIX::StokesFO::
StokesFO( const Teuchos::RCP<Teuchos::ParameterList>& params_,
             const Teuchos::RCP<ParamLib>& paramLib_,
             const int numDim_) :
  Albany::AbstractProblem(params_, paramLib_, numDim_),
  numDim(numDim_)
{
  //Set # of PDEs per node based on the Equation Set.  
  //Equation Set is FELIX by default (2 dofs / node -- usual FELIX Stokes FO).
  std::string eqnSet = params_->sublist("Equation Set").get<std::string>("Type", "FELIX"); 
  if (eqnSet == "FELIX") 
    neq = 2; //FELIX FO Stokes system is a system of 2 PDEs
  else if (eqnSet == "Poisson" || eqnSet == "FELIX X-Z") 
    neq = 1; //1 PDE/node for Poisson or FELIX X-Z physics


  // Set the num PDEs for the null space object to pass to ML
  this->rigidBodyModes->setNumPDEs(neq);

  // the following function returns the problem information required for setting the rigid body modes (RBMs) for elasticity problems
  //written by IK, Feb. 2012
  //Check if we want to give ML RBMs (from parameterlist)
  int numRBMs = params_->get<int>("Number RBMs for ML", 0); 
  bool setRBMs = false;   
  if (numRBMs > 0) {
    setRBMs = true; 
    int numScalar = 0;
    if (numRBMs == 2 || numRBMs == 3) 
      rigidBodyModes->setParameters(neq, numDim, numScalar, numRBMs, setRBMs);
    else
      TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,"The specified number of RBMs " 
                                     << numRBMs << " is not valid!  Valid values are 0, 2 and 3.");
  }

  // Need to allocate a fields in mesh database
  if (params->isParameter("RequiredFields"))
  {
    // Need to allocate a fields in mesh database
    Teuchos::Array<std::string> req = params->get<Teuchos::Array<std::string> > ("Required Fields");
    for (int i(0); i<req.size(); ++i)
      this->requirements.push_back(req[i]);
  }
  else
  {
    this->requirements.push_back("surface_height");
#ifdef CISM_HAS_FELIX
    this->requirements.push_back("xgrad_surface_height"); //ds/dx which can be passed from CISM
    this->requirements.push_back("ygrad_surface_height"); //ds/dy which can be passed from CISM
#endif
    this->requirements.push_back("temperature");
    this->requirements.push_back("basal_friction");
    this->requirements.push_back("thickness");
    this->requirements.push_back("flow_factor");
    this->requirements.push_back("surface_velocity");
    this->requirements.push_back("surface_velocity_rms");
  }
}
bool testNestedSerializationObject(const Serializer& serializer,
				   Teuchos::Array<TayType>& x, 
				   const std::string& tag,
				   Teuchos::FancyOStream& out) {
  
  typedef int Ordinal;
  
  // Serialize
  Ordinal count = x.size();
  Ordinal bytes = serializer.fromCountToIndirectBytes(count, &x[0]);
  char *charBuffer = new char[bytes];
  serializer.serialize(count, &x[0], bytes, charBuffer);

  // Expand x to serializer size
  Ordinal sz = serializer.getSerializerSize();
  typedef typename Serializer::value_serializer_type VST;
  RCP<const VST> vs = serializer.getValueSerializer();
  Ordinal sz_inner = vs->getSerializerSize();
  for (Ordinal i=0; i<count; i++) {
    x[i].resize(sz-1, true);
    for (Ordinal j=0; j<sz; j++)
      x[i].fastAccessCoeff(j).resize(sz_inner-1, true);
    x[i].val().resize(sz_inner-1, true);
  }
  
  // Deserialize
  Ordinal count2 = serializer.fromIndirectBytesToCount(bytes, charBuffer);
  Teuchos::Array<TayType> x2(count2);
  serializer.deserialize(bytes, charBuffer, count2, &x2[0]);

  delete [] charBuffer;
  
  // Check counts match
  bool success = (count == count2);
  out << tag << " serialize/deserialize count test";
  if (success)
    out << " passed";
  else
    out << " failed";
  out << ":  \n\tExpected:  " << count << ", \n\tGot:       " << count2 << "." 
      << std::endl;
  
  // Check coefficients match
  for (Ordinal i=0; i<count; i++) {
    bool success2 = Sacado::IsEqual<TayType>::eval(x[i], x2[i]);
    out << tag << " serialize/deserialize taylor test " << i;
    if (success2)
      out << " passed";
    else
	out << " failed";
    out << ":  \n\tExpected:  " << x[i] << ", \n\tGot:       " << x2[i] 
	<< "." << std::endl;
    success = success && success2;
  }

  return success;
}
Example #27
0
void
Stokhos::SmolyakPseudoSpectralOperator<ordinal_type,value_type,point_compare_type>::
scatter(
  const Teuchos::Array<ordinal_type>& map, 
  const Teuchos::SerialDenseMatrix<ordinal_type,value_type>& input, 
  bool trans, 
  Teuchos::SerialDenseMatrix<ordinal_type,value_type>& result) const {
  if (trans) {
    for (ordinal_type j=0; j<map.size(); j++)
      for (ordinal_type i=0; i<input.numRows(); i++)
	result(i,map[j]) += input(i,j);
  }
  else {
    for (ordinal_type j=0; j<input.numCols(); j++)
      for (ordinal_type i=0; i<map.size(); i++)
	result(map[i],j) += input(i,j);
  }
}
Example #28
0
Stokhos::CompletePolynomialBasis<ordinal_type, value_type>::
CompletePolynomialBasis(
	const Teuchos::Array< Teuchos::RCP<const OneDOrthogPolyBasis<ordinal_type, value_type> > >& bases_,
	const value_type& sparse_tol_,
	bool use_old_cijk_alg_,
	const Teuchos::RCP< Teuchos::Array<value_type> >& deriv_coeffs_) :
  p(0),
  d(bases_.size()),
  sz(0),
  bases(bases_),
  basis_orders(d),
  sparse_tol(sparse_tol_),
  use_old_cijk_alg(use_old_cijk_alg_),
  deriv_coeffs(deriv_coeffs_),
  norms(),
  terms()
{

  // Compute total order
  for (ordinal_type i=0; i<d; i++) {
    basis_orders[i] = bases[i]->order();
    if (basis_orders[i] > p)
      p = basis_orders[i];
  }

  // Compute basis terms
  CPBUtils::compute_terms(basis_orders, sz, terms, num_terms);
    
  // Compute norms
  norms.resize(sz);
  value_type nrm;
  for (ordinal_type k=0; k<sz; k++) {
    nrm = value_type(1.0);
    for (ordinal_type i=0; i<d; i++)
      nrm = nrm * bases[i]->norm_squared(terms[k][i]);
    norms[k] = nrm;
  }

  // Create name
  name = "Complete polynomial basis (";
  for (ordinal_type i=0; i<d-1; i++)
    name += bases[i]->getName() + ", ";
  name += bases[d-1]->getName() + ")";

  // Allocate array for basis evaluation
  basis_eval_tmp.resize(d);
  for (ordinal_type j=0; j<d; j++)
    basis_eval_tmp[j].resize(basis_orders[j]+1);

  // Set up deriv_coeffs
  if (deriv_coeffs == Teuchos::null) {
    deriv_coeffs = Teuchos::rcp(new Teuchos::Array<value_type>(d));
    for (ordinal_type j=0; j<d; j++)
      (*deriv_coeffs)[j] = value_type(1.0);
  }
}
  Teuchos::ArrayView<Integral> getList(Teuchos::Array<Integral> &irl)
{
  Teuchos::ArrayView<Integral> av;  // av.size() == 0

  if (!Zoltan2::allValuesAreInRangeList(irl) &&
      !Zoltan2::noValuesAreInRangeList(irl))
    av = irl.view(0, irl.size()-1); // skip last value, it's a flag

  return av;
}
void run_samples(
  const Teuchos::Comm<int>& comm ,
  ProblemType& problem,
  const CoeffFunctionType& coeff_function,
  const Teuchos::RCP<Kokkos::Example::FENL::SampleGrouping<double> >& grouper,
  const Teuchos::RCP<Teuchos::ParameterList>& fenlParams,
  const CMD & cmd ,
  const double bc_lower_value,
  const double bc_upper_value,
  const Teuchos::Array< Teuchos::Array<double> >& points,
  Teuchos::Array<double>& responses,
  Teuchos::Array<int>& iterations,
  Kokkos::Example::FENL::Perf& perf_total)
{
  typedef typename CoeffFunctionType::RandomVariableView RV;
  typedef typename RV::HostMirror HRV;
  RV rv = coeff_function.getRandomVariables();
  HRV hrv = Kokkos::create_mirror_view(rv);

  const int num_samples = points.size();
  const int dim = rv.dimension_0();;
  for (int sample=0; sample<num_samples; ++sample) {

    // Set random variable values to this sample
    for (int i=0; i<dim; ++i)
      hrv(i) = points[sample][i];
    Kokkos::deep_copy( rv, hrv );

    // Evaluate response at quadrature point
    double response = 0;
    Kokkos::Example::FENL::Perf perf =
      fenl( problem , fenlParams ,
            cmd.PRINT , cmd.USE_TRIALS , cmd.USE_ATOMIC ,
            cmd.USE_BELOS , cmd.USE_MUELU , cmd.USE_MEANBASED ,
            coeff_function , cmd.USE_ISOTROPIC ,
            cmd.USE_COEFF_SRC , cmd.USE_COEFF_ADV ,
            bc_lower_value , bc_upper_value ,
            response);

    responses[sample] = response;
    iterations[sample] = perf.cg_iter_count;

    if (cmd.PRINT_ITS && 0 == comm.getRank()) {
      std::cout << sample << " : " << perf.cg_iter_count << " ( ";
      for (int i=0; i<dim; ++i)
        std::cout << hrv(i) << " ";
      std::cout << ")" << std::endl;
    }

     // Increment timing statistics
    perf_total.increment(perf, !cmd.USE_BELOS);

  }
}