void assembleIRKState(
  const int stageIndex,
  const Teuchos::SerialDenseMatrix<int,Scalar> &A_in,
  const Scalar dt,
  const Thyra::VectorBase<Scalar> &x_base,
  const Thyra::ProductVectorBase<Scalar> &x_stage_bar,
  Teuchos::Ptr<Thyra::VectorBase<Scalar> > x_out_ptr
  )
{

  typedef ScalarTraits<Scalar> ST;

  const int numStages_in = A_in.numRows();
  TEUCHOS_ASSERT_IN_RANGE_UPPER_EXCLUSIVE( stageIndex, 0, numStages_in );
  TEUCHOS_ASSERT_EQUALITY( A_in.numRows(), numStages_in );
  TEUCHOS_ASSERT_EQUALITY( A_in.numCols(), numStages_in );
  TEUCHOS_ASSERT_EQUALITY( x_stage_bar.productSpace()->numBlocks(), numStages_in );
  Thyra::VectorBase<Scalar>& x_out = *x_out_ptr;

  V_V( outArg(x_out), x_base );
  for ( int j = 0; j < numStages_in; ++j ) {
    Vp_StV( outArg(x_out), dt * A_in(stageIndex,j), *x_stage_bar.getVectorBlock(j) );
  }

}
Пример #2
0
// ============================================================================
void
BorderingHelpers::
dissect(const Tpetra::MultiVector<double,int,int> & x,
        Tpetra::MultiVector<double,int,int> & xSmall,
        double * lambda
       )
{
#ifndef NDEBUG
  TEUCHOS_ASSERT_EQUALITY(x.NumVectors(), xSmall.NumVectors());
  // Make sure the maps are matching.
  std::shared_ptr<const Tpetra::Map<int,int>> extendedMap =
    nosh::BorderingHelpers::extendMapBy1(xSmall.getMap());
  TEUCHOS_ASSERT(x.getMap().SameAs(*extendedMap));
#endif

  Epetra_Import importer(xSmall.getMap(), x.getMap());

  // Strip off the phase constraint variable.
  xSmall.Import(x, importer, Insert);

  // TODO Check if we need lambda on all procs.
  if (x.getMap().Comm().MyPID() == 0) {
    const int n = x.MyLength();
    for (int k = 0; k < x.NumVectors(); k++)
      lambda[k] = (*(x(k)))[n - 1];
  }

  return;
}
Пример #3
0
// ============================================================================
void
BorderingHelpers::
merge(const Tpetra::MultiVector<double,int,int> & x,
      const double * lambda,
      Tpetra::MultiVector<double,int,int> & out
    )
{
#ifndef NDEBUG
  // Check if the maps are matching.
  std::shared_ptr<const Tpetra::Map<int,int>> extendedMap =
    nosh::BorderingHelpers::extendMapBy1(x.getMap());
  TEUCHOS_ASSERT(out.getMap().SameAs(*extendedMap));
#endif

  Epetra_Import importer(out.getMap(), x.getMap());

  TEUCHOS_ASSERT_EQUALITY(0, out.Import(x, importer, Insert));

  // Set last entry on proc 0.
  if (x.getMap().Comm().MyPID() == 0) {
    const int numMyElems = x.getMap().NumMyElements();
    for (int k = 0; k < x.NumVectors(); k++)
      (*out(k))[numMyElems] = lambda[k];
  }

  return;
}
TestLagrPolyMeritFunc1D<Scalar>::TestLagrPolyMeritFunc1D(
  const ArrayView<const Scalar> &alpha,
  const ArrayView<const Scalar> &phi
  )
  : alpha_(alpha), phi_(phi)
{
  TEUCHOS_ASSERT_EQUALITY(alpha.size(), phi.size());
}
Пример #5
0
void TableFormat::writeWholeTable(
  std::ostream& out,
  const std::string& header,
  const Array<std::string>& columnNames,
  const Array<TableColumn>& columns
  ) const
{

  /* compute the total width */
  int pgWidth = 0;
  for (Array<TableColumn>::size_type i=0; i<columnNames.size(); i++)
  {
    int cw = defaultColumnWidth();
    if (columnWidths_.size() != 0) cw = columnWidths_[i];
    pgWidth += cw;
  }
  setPageWidth(std::max(pageWidth_, pgWidth));
  
  /* write the header */
  out << thickline() << std::endl;
  out << std::endl;
  int numBlanks = (pageWidth_ - header.length())/2;
  out << blanks(numBlanks) << header << std::endl;
  out << std::endl;

  /* write the column titles */
  for (Array<std::string>::size_type i=0; i<columnNames.size(); i++)
  {
    int cw = defaultColumnWidth();
    if (columnWidths_.size() != 0) cw = columnWidths_[i];

    out << std::left << std::setw(cw) << columnNames[i];
  }
  out << std::endl;

  /* ensure that all columns have the same number of rows */
  int numRows = columns[0].numRows();
  for (Array<TableColumn>::size_type i=1; i<columns.size(); i++)
  {
    TEUCHOS_ASSERT_EQUALITY(columns[i].numRows(), numRows);
  }
  
  /* write the table data */
  for (int i=0; i<numRows; i++)
  {
    if (i % lineInterval_ == 0)
      out << std::left << thinline() << std::endl;   
    writeRow(out, i, columns);
  }
  
  /* write the footer */
  out << thickline() << std::endl;

}
Пример #6
0
void GlobalMPISession::allGather(int localVal, const ArrayView<int> &allVals)
{
  justInTimeInitialize();
  TEUCHOS_ASSERT_EQUALITY(allVals.size(), getNProc());
#ifdef HAVE_MPI
  MPI_Allgather( &localVal, 1, MPI_INT, allVals.getRawPtr(), 1, MPI_INT,
    MPI_COMM_WORLD);
#else
  allVals[0] = localVal;
#endif
}
Пример #7
0
  /*!
  \brief Evaluate the function and derivatives at a given local coordinate

  \param xi (in) : Local coordinate where to evaluate the function
  \param val (out) : Function values at xi
  \param valdim (in) : Dimension of val
  \param deriv (out) : Derivative of functions at xi
  */
  void
  EvaluateFunction(
      const double* xi,
      double*       val,
      const int     valdim,
      double*       deriv)
  {
    TEUCHOS_ASSERT_EQUALITY(valdim, traits_type::valdim);
    TEUCHOS_ASSERT(!xi);

    traits_type::EvaluateFunction(xi, val, valdim, deriv);
  }
void assembleIRKSolution(
  const Teuchos::SerialDenseVector<int,Scalar> &b_in,
  const Scalar dt,
  const Thyra::VectorBase<Scalar> &x_base,
  const Thyra::ProductVectorBase<Scalar> &x_stage_bar,
  Teuchos::Ptr<Thyra::VectorBase<Scalar> > x_out_ptr
  )
{

  typedef ScalarTraits<Scalar> ST;

  const int numStages_in = b_in.length();
  TEUCHOS_ASSERT_EQUALITY( b_in.length(), numStages_in );
  TEUCHOS_ASSERT_EQUALITY( x_stage_bar.productSpace()->numBlocks(), numStages_in );
  Thyra::VectorBase<Scalar>& x_out = *x_out_ptr;

  V_V( outArg(x_out), x_base );
  for ( int j = 0; j < numStages_in; ++j ) {
    Vp_StV( outArg(x_out), dt * b_in(j), *x_stage_bar.getVectorBlock(j) );
  }

}
Пример #9
0
// =============================================================================
Teuchos::RCP<Epetra_Vector>
VIO::EpetraMesh::Reader::
extractStateData_ ( const vtkSmartPointer<vtkDataSet>     & vtkData,
                    const Teuchos::RCP<const Epetra_Comm> & comm
                  ) const
{
    vtkIdType numArrays = vtkData->GetPointData()->GetNumberOfArrays();

    TEUCHOS_ASSERT_EQUALITY ( numArrays, 1 );

    const vtkSmartPointer<vtkDataArray> & array =
        vtkData->GetPointData()->GetArray(0);

    vtkIdType numComponents = array->GetNumberOfComponents();

    TEUCHOS_ASSERT_EQUALITY ( numComponents, 2 );    // for *complex* values

    // this is the total number of grid points
    vtkIdType numPoints = array->GetNumberOfTuples();

    // Create maps.
    // TODO They are created at another spot already. Avoid the work.
    Teuchos::RCP<Epetra_Map> nodesMap = Teuchos::rcp( new Epetra_Map( numPoints, 0, *comm ) );
    Teuchos::RCP<Epetra_Map> complexValuesMap = createComplexValuesMap_ ( *nodesMap );

    Teuchos::RCP<Epetra_Vector> z =
        Teuchos::rcp ( new Epetra_Vector ( *complexValuesMap ) );

    // fill z
    double val[2];
    for ( int k = 0; k < nodesMap->NumMyElements(); k++ )
    {
        array->GetTuple( nodesMap->GID(k), val );
        z->ReplaceMyValue( 2*k  , 0, val[0] );
        z->ReplaceMyValue( 2*k+1, 0, val[1] );
    }

    return z;
}
Пример #10
0
// =============================================================================
void
VIO::EpetraMesh::Writer::
setValues( const Epetra_MultiVector          & x,
           const Teuchos::Array<std::string> & scalarsNames
         )
{
  unsigned int numVecs = x.NumVectors();
  unsigned int numVariables = x.GlobalLength();

  unsigned int numNodes = mesh_->getNodesMap()->NumGlobalElements();

  // make sure the sizes match the mesh
  if ( !mesh_.is_null() )
      TEUCHOS_ASSERT_EQUALITY( numVariables, 2*numNodes );

  // cast into a vtkUnstructuredGrid
  vtkSmartPointer<vtkUnstructuredGrid> vtkMesh =
      dynamic_cast<vtkUnstructuredGrid*> ( vtkDataSet_.GetPointer() );
  TEUCHOS_ASSERT_INEQUALITY( 0, !=, vtkMesh );

  // get scalarsNames, and insert default names if empty
  Teuchos::Array<std::string> scNames ( scalarsNames );
  if ( scNames.empty() )
  {
      scNames.resize ( numVecs );
      for ( int vec=0; vec<numVecs; vec++ )
          scNames[vec] = "x" + EpetraExt::toString ( vec );
  }

  // fill the scalar field
  vtkSmartPointer<vtkDoubleArray> scalars =
      vtkSmartPointer<vtkDoubleArray>::New();

  // real and imaginary part
  scalars->SetNumberOfComponents ( 2 );

  for ( int vec=0; vec<numVecs; vec++ )
  {
      scalars->SetName ( scNames[vec].c_str() );
      for ( int k=0; k<numNodes; k++ )
      {
//           const unsigned int dof_id = libmeshMesh_->node(k).dof_number(0,k,0);
          scalars->InsertNextValue ( x[vec][2*k] );
          scalars->InsertNextValue ( x[vec][2*k+1] );
      }
      vtkMesh->GetPointData()->AddArray ( scalars );
  }

  return;
}
Пример #11
0
// =============================================================================
Eigen::VectorXd
mesh_tri::
edge_coefficients_numerically_(
  const std::vector<Eigen::Vector3d> & edges
  ) const
{
  size_t num_edges = edges.size();
  TEUCHOS_ASSERT_EQUALITY(num_edges, 3);

  // Build an equation system for the edge coefficients alpha_k.
  // They fulfill
  //
  //    |simplex| * <u,v> = \sum_{edges e_i} alpha_i <u,e_i> <e_i,v>
  //
  // for any pair of vectors u, v in the plane of the triangle.
  //
  const double vol = 0.5 * (edges[0].cross(edges[1])).norm();

  Eigen::Matrix3d A;
  Eigen::Vector3d rhs;

  // Build the equation system:
  // The equation
  //
  //    |simplex| ||u||^2 = \sum_i \alpha_i <u,e_i> <e_i,u>
  //
  // has to hold for all vectors u in the plane spanned by the edges,
  // particularly by the edges themselves.
  //
  for (size_t i = 0; i < num_edges; i++) {
    double alpha = edges[i].dot(edges[i]);
    rhs(i) = vol * alpha;
    A(i, i) = alpha * alpha;
    for (size_t j = i+1; j < num_edges; j++) {
      A(i, j) = edges[i].dot(edges[j]) * edges[j].dot(edges[i]);
      A(j, i) = A(i, j);
    }
  }

  // Solve the equation system for the alpha_i.  The system is symmetric and,
  // if the simplex is not degenerate, positive definite.
  //return A.ldlt().solve(rhs);
  const auto x = A.fullPivLu().solve(rhs);
  //auto x = A.colPivHouseholderQr().solve(rhs);

  return x;
}
Пример #12
0
// =============================================================================
// Compute result_p = alpha * dg/dx * input_x.
NOX::Abstract::Group::ReturnType
Ginla::FDM::Constraint::MinDist::
multiplyDX ( double                                    alpha,
             const NOX::Abstract::MultiVector        & input_x,
             NOX::Abstract::MultiVector::DenseMatrix & result_p
           ) const
{ 
  TEUCHOS_ASSERT( komplex_.is_valid_ptr() && !komplex_.is_null() );
  
  TEUCHOS_ASSERT_EQUALITY( result_p.numCols(), input_x.numVectors() );
  
  for ( int k=0; k<input_x.numVectors(); k++ )
  {
      const Epetra_Vector & xE =
              Teuchos::dyn_cast<const NOX::Epetra::Vector>( input_x[0] ).getEpetraVector();
      Teuchos::RCP<ComplexVector> xPsi = komplex_->real2complex( xE );

      result_p(0,k) = alpha * std::imag( psiRef_->dot(*xPsi) );
  }
  
  return NOX::Abstract::Group::Ok;
}
Пример #13
0
template<class T> inline
void ArrayRCP<T>::resize(const size_type n, const T &val)
{
#ifdef TEUCHOS_DEBUG
  TEUCHOS_ASSERT_EQUALITY(lowerOffset(), 0);
#endif
  if (n == 0) {
    clear();
    return;
  }
  const size_type orig_n = size();
  if (n != orig_n) {
    ArrayRCP<T> tmp = *this;
    *this = arcp<T>(n);
    const size_type small_n = std::min(n, orig_n);
    for (size_type i = 0; i < small_n; ++i)
      (*this)[i] = tmp[i];
    for (size_type i = orig_n; i < n; ++i)
      (*this)[i] = val;
    upperOffset_ = n-1;
  }
}
Пример #14
0
// ============================================================================
void
Bordered::
eval_mdel(const InArgs &in_args,
          const OutArgs &out_args
        ) const
{
  // First, dissect x_in into vector and bordering.
  const Teuchos::RCP<const Tpetra::Vector<double,int,int>> &x_in = in_args.get_x();
#ifndef NDEBUG
  TEUCHOS_ASSERT(!x_in.is_null());
#endif
  const Teuchos::RCP<Tpetra::Vector<double,int,int>> inner_x_in =
    Teuchos::rcp(new Tpetra::Vector<double,int,int>(*innerModelEval_->get_x_map()));
  double lambda[1];
  nosh::BorderingHelpers::dissect(*x_in, *inner_x_in, lambda);

  // Get i*x. This assumes a particular data layout in x_in.
  Tpetra::Vector<double,int,int> ix(inner_x_in->Map());
  for (int k = 0; k < ix.getMap().NumMyElements()/2; k++) {
    ix[2*k] = - (*x_in)[2*k+1];
    ix[2*k+1] = (*x_in)[2*k];
  }

  // Copy over the args for use in innerModelEval.
  InArgs inner_in_args = in_args;
  inner_in_args.set_x(inner_x_in);

  OutArgs inner_out_args = out_args;

  const Tpetra::Vector<double,int,int> & bordering = ix;

  // Compute F(x).
  const Teuchos::RCP<Tpetra::Vector<double,int,int>> &f_out = out_args.get_f();
  if (!f_out.is_null()) {
    // Create new temporary f_out.
    const Teuchos::RCP<Tpetra::Vector<double,int,int>> inner_f_out =
      Teuchos::rcp(new Tpetra::Vector<double,int,int>(*innerModelEval_->get_f_map()));

    inner_out_args.set_f(inner_f_out);
    innerModelEval_->eval_mdel(inner_in_args, inner_out_args);
    // Add lambda * x0.
    TEUCHOS_ASSERT_EQUALITY(0, inner_f_out->Update(lambda[0], bordering, 1.0));
    // Append <psi0, x> to f_out.
    double r[1];
    TEUCHOS_ASSERT_EQUALITY(0, bordering.Dot(*inner_x_in, r));
    //r = lambda;
    nosh::BorderingHelpers::merge(*inner_f_out, r, *f_out);
  }

  // Compute df/dp.
  const EpetraExt::ModelEvaluator::DerivativeMultiVector &derivMv =
    out_args.get_DfDp(0).getDerivativeMultiVector();
  const Teuchos::RCP<Tpetra::MultiVector<double,int,int>> &dfdp_out =
    derivMv.multi_vector();
  if (!dfdp_out.is_null()) {
    // Create temporary DerivativeMultiVector inner_dfdp_out.
    const int numParams = derivMv.get_paramIndexes().length();
    const Teuchos::RCP<Tpetra::MultiVector<double,int,int>> inner_dfdp_out =
      Teuchos::rcp(new Tpetra::MultiVector<double,int,int>(*innerModelEval_->get_f_map(),
                                          numParams));
    const EpetraExt::ModelEvaluator::DerivativeMultiVector innerDerivMv(inner_dfdp_out,
        derivMv.getOrientation(),
        derivMv.get_paramIndexes());
    inner_out_args.set_DfDp(0, innerDerivMv);
    innerModelEval_->eval_mdel(inner_in_args, inner_out_args);
    // Append last entry and merge into dfdp_out.
    std::vector<double> r(numParams);
    for (int k = 0; k < numParams; k++)
      r[k] = 0.0;
    nosh::BorderingHelpers::merge(*inner_dfdp_out, &r[0], *dfdp_out);
  }

  // Fill Jacobian.
  const Teuchos::RCP<Tpetra::Operator<double,int,int>> & W_out = out_args.get_W();
  if(!W_out.is_null()) {
    const Teuchos::RCP<nosh::BorderedOperator> & borderedW =
      Teuchos::rcp_dynamic_cast<nosh::BorderedOperator>(W_out, true);

    // Fill inner Jacobian.
    inner_out_args.set_W(Teuchos::rcp(borderedW->getInnerOperator()));
    innerModelEval_->eval_mdel(inner_in_args, inner_out_args);

    // Reset bordering.
    borderedW->resetBordering(bordering, bordering, 0.0);
  }

  // Fill preconditioner.
  const Teuchos::RCP<Tpetra::Operator<double,int,int>> & WPrec_out = out_args.get_WPrec();
  if(!WPrec_out.is_null()) {
    const Teuchos::RCP<nosh::BorderedOperator> & borderedPrec =
      Teuchos::rcp_dynamic_cast<nosh::BorderedOperator>(WPrec_out, true);

    // Fill inner preconditioner.
    inner_out_args.set_WPrec(Teuchos::rcp(borderedPrec->getInnerOperator()));
    innerModelEval_->eval_mdel(inner_in_args, inner_out_args);

    // Reset bordering.
    borderedPrec->resetBordering(bordering, bordering, 0.0);
  }

  return;
}
void panzer::ScatterResidual_Epetra<panzer::Traits::Hessian, TRAITS,LO,GO>::
evaluateFields(typename TRAITS::EvalData workset)
{ 
   std::vector<int> cLIDs, rLIDs;
   std::vector<double> jacRow;

   bool useColumnIndexer = colGlobalIndexer_!=Teuchos::null;

   // for convenience pull out some objects from workset
   std::string blockId = this->wda(workset).block_id;
   const std::vector<std::size_t> & localCellIds = this->wda(workset).cell_local_ids;

   Teuchos::RCP<Epetra_Vector> r = epetraContainer_->get_f(); 
   Teuchos::RCP<Epetra_CrsMatrix> Jac = epetraContainer_->get_A();

   const Teuchos::RCP<const panzer::UniqueGlobalIndexer<LO,GO> >&
     colGlobalIndexer = useColumnIndexer ? colGlobalIndexer_ : globalIndexer_;
   
   // NOTE: A reordering of these loops will likely improve performance
   //       The "getGIDFieldOffsets" may be expensive.  However the
   //       "getElementGIDs" can be cheaper. However the lookup for LIDs
   //       may be more expensive!

   // scatter operation for each cell in workset
   for(std::size_t worksetCellIndex=0;worksetCellIndex<localCellIds.size();++worksetCellIndex) {
      std::size_t cellLocalId = localCellIds[worksetCellIndex];

      rLIDs = globalIndexer_->getElementLIDs(cellLocalId); 
      cLIDs = colGlobalIndexer->getElementLIDs(cellLocalId);
      if (Teuchos::nonnull(workset.other)) {
        const std::size_t other_cellLocalId = workset.other->cell_local_ids[worksetCellIndex];
        const std::vector<int> other_cLIDs = colGlobalIndexer->getElementLIDs(other_cellLocalId);
        cLIDs.insert(cLIDs.end(), other_cLIDs.begin(), other_cLIDs.end());
      }

      // loop over each field to be scattered
      for(std::size_t fieldIndex = 0; fieldIndex < scatterFields_.size(); fieldIndex++) {
         int fieldNum = fieldIds_[fieldIndex];
         const std::vector<int> & elmtOffset = globalIndexer_->getGIDFieldOffsets(blockId,fieldNum);

         // loop over the basis functions (currently they are nodes)
         for(std::size_t rowBasisNum = 0; rowBasisNum < elmtOffset.size(); rowBasisNum++) {
            const ScalarT scatterField = (scatterFields_[fieldIndex])(worksetCellIndex,rowBasisNum);
            int rowOffset = elmtOffset[rowBasisNum];
            int row = rLIDs[rowOffset];
    
            // loop over the sensitivity indices: all DOFs on a cell
            jacRow.resize(scatterField.size());
            
            for(int sensIndex=0;sensIndex<scatterField.size();++sensIndex)
              jacRow[sensIndex] = scatterField.fastAccessDx(sensIndex).fastAccessDx(0);

            {
               int err = Jac->SumIntoMyValues(
                 row,
                 std::min(cLIDs.size(), static_cast<size_t>(scatterField.size())),
                 panzer::ptrFromStlVector(jacRow),
                 panzer::ptrFromStlVector(cLIDs));
               TEUCHOS_ASSERT_EQUALITY(err,0);
            }
         } // end rowBasisNum
      } // end fieldIndex
   }
}
Пример #16
0
int main(int argc, char* argv[])
{
  std::cout << Teuchos::Teuchos_Version() << std::endl << std::endl;

  // Creating a double-precision matrix can be done in several ways:
  // Create an empty matrix with no dimension
  Teuchos::SerialSymDenseMatrix<int,double> Empty_Matrix;
  // Create an empty 4x4 matrix
  Teuchos::SerialSymDenseMatrix<int,double> My_Matrix( 4 );
  // Basic copy of My_Matrix
  Teuchos::SerialSymDenseMatrix<int,double> My_Copy1( My_Matrix ),
    // (Deep) Copy of principle 3x3 submatrix of My_Matrix
    My_Copy2( Teuchos::Copy, My_Matrix, 3 ),
    // (Shallow) Copy of 3x3 submatrix of My_Matrix
    My_Copy3( Teuchos::View, My_Matrix, 3, 1 );

  // The matrix dimensions and strided storage information can be obtained:
  int rows, cols, stride;
  rows = My_Copy3.numRows();  // number of rows
  cols = My_Copy3.numCols();  // number of columns
  stride = My_Copy3.stride(); // storage stride
  TEUCHOS_ASSERT_EQUALITY(rows, 3);
  TEUCHOS_ASSERT_EQUALITY(cols, 3);
  TEUCHOS_ASSERT_EQUALITY(stride, 4);

  // Matrices can change dimension:
  Empty_Matrix.shape( 3 );      // size non-dimensional matrices
  My_Matrix.reshape( 3 );       // resize matrices and save values

  // Filling matrices with numbers can be done in several ways:
  My_Matrix.random();             // random numbers
  My_Copy1.putScalar( 1.0 );      // every entry is 1.0
  My_Copy1 = 1.0;                 // every entry is 1.0 (still)
  My_Copy2(1,1) = 10.0;           // individual element access
  Empty_Matrix = My_Matrix;       // copy My_Matrix to Empty_Matrix 

  // Basic matrix arithmetic can be performed:
  Teuchos::SerialDenseMatrix<int,double> My_Prod( 4, 3 ), My_GenMatrix( 4, 3 );
  My_GenMatrix = 1.0;
  // Matrix multiplication ( My_Prod = 1.0*My_GenMatrix*My_Matrix )
  My_Prod.multiply( Teuchos::RIGHT_SIDE, 1.0, My_Matrix, My_GenMatrix, 0.0 );
  My_Copy2 += My_Matrix;   // Matrix addition
  My_Copy2 *= 0.5;         // Matrix scaling
  
  // Matrices can be compared:
  // Check if the matrices are equal in dimension and values
  if (Empty_Matrix == My_Matrix) {
    std::cout<< "The matrices are the same!" <<std::endl;
  }
  // Check if the matrices are different in dimension or values
  if (My_Copy2 != My_Matrix) {
    std::cout<< "The matrices are different!" <<std::endl;
  }

  // The norm of a matrix can be computed:
  double norm_one, norm_inf, norm_fro;
  norm_one = My_Matrix.normOne();        // one norm
  norm_inf = My_Matrix.normInf();        // infinity norm
  norm_fro = My_Matrix.normFrobenius();  // frobenius norm

  std::cout << std::endl << "|| My_Matrix ||_1 = " << norm_one << std::endl;
  std::cout << "|| My_Matrix ||_Inf = " << norm_inf << std::endl;
  std::cout << "|| My_Matrix ||_F = " << norm_fro << std::endl << std::endl;

  // A matrix can be factored and solved using Teuchos::SerialDenseSolver.
  Teuchos::SerialSpdDenseSolver<int,double> My_Solver;
  Teuchos::SerialSymDenseMatrix<int,double> My_Matrix2( 3 );
  My_Matrix2.random();
  Teuchos::SerialDenseMatrix<int,double> X(3,1), B(3,1);
  X = 1.0;
  B.multiply( Teuchos::LEFT_SIDE, 1.0, My_Matrix2, X, 0.0 );
  X = 0.0;  // Make sure the computed answer is correct.

  int info = 0;
  My_Solver.setMatrix( Teuchos::rcp( &My_Matrix2, false ) );
  My_Solver.setVectors( Teuchos::rcp( &X, false ), Teuchos::rcp( &B, false ) );
  info = My_Solver.factor();
  if (info != 0)
    std::cout << "Teuchos::SerialSpdDenseSolver::factor() returned : " << info << std::endl;
  info = My_Solver.solve();
  if (info != 0)
    std::cout << "Teuchos::SerialSpdDenseSolver::solve() returned : " << info << std::endl;

  // A matrix triple-product can be computed:  C = alpha*W'*A*W
  double alpha=0.5;
  Teuchos::SerialDenseMatrix<int,double> W(3,2);
  Teuchos::SerialSymDenseMatrix<int,double> A1(2), A2(3);
  A1(0,0) = 1.0, A1(1,1) = 2.0;
  A2(0,0) = 1.0, A2(1,1) = 2.0, A2(2,2) = 3.00;
  W = 1.0;

  Teuchos::SerialSymDenseMatrix<int,double> C1(3), C2(2);

  Teuchos::symMatTripleProduct<int,double>( Teuchos::NO_TRANS, alpha, A1, W, C1);
  Teuchos::symMatTripleProduct<int,double>( Teuchos::TRANS, alpha, A2, W, C2 );

  // A matrix can be sent to the output stream:
  std::cout<< My_Matrix << std::endl;
  std::cout<< X << std::endl;

  return 0;
}
Пример #17
0
  virtual
  void evalModelImpl(
      const Thyra::ModelEvaluatorBase::InArgs<double> &in_args,
      const Thyra::ModelEvaluatorBase::OutArgs<double> &out_args
      ) const
  {
    const double alpha = in_args.get_alpha();
    double beta = in_args.get_beta();

    // From packages/piro/test/MockModelEval_A.cpp
    if (alpha == 0.0 && beta == 0.0) {
      // beta = 1.0;
    }
#ifndef NDEBUG
    TEUCHOS_ASSERT_EQUALITY(alpha, 0.0);
    TEUCHOS_ASSERT_EQUALITY(beta,  1.0);
#endif

    const auto & x_in = in_args.get_x();
#ifndef NDEBUG
    TEUCHOS_ASSERT(!x_in.is_null());
#endif
    // create corresponding tpetra vector
    auto x_in_tpetra =
      Thyra::TpetraOperatorVectorExtraction<double,int,int>::getConstTpetraVector(
          x_in
          );

    // Dissect in_args.get_p(0) into parameter sublists.
    const auto & p_in = in_args.get_p(0);
#ifndef NDEBUG
    TEUCHOS_ASSERT(!p_in.is_null());
#endif

#ifndef NDEBUG
    // Make sure the parameters aren't NaNs.
    for (int k = 0; k < p_in->space()->dim(); k++) {
      TEUCHOS_ASSERT(!std::isnan(Thyra::get_ele(*p_in, k)));
    }
#endif

    // Fill the parameters into a std::map.
    const auto param_names = this->get_p_names(0);
    std::map<std::string, double> params;
    for (int k = 0; k < p_in->space()->dim(); k++) {
      params[(*param_names)[k]] = Thyra::get_ele(*p_in, k);
    }

    // compute F
    const auto & f_out = out_args.get_f();
    if (!f_out.is_null()) {

      auto f_out_tpetra =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraVector(
            f_out
            );
      this->f_->set_parameters(params, {});
      this->f_->apply(
          *x_in_tpetra,
          *f_out_tpetra
          );
    }

    // Compute df/dp.
    const auto & derivMv = out_args.get_DfDp(0).getDerivativeMultiVector();
    const auto & dfdp_out = derivMv.getMultiVector();
    if (!dfdp_out.is_null()) {
      auto dfdp_out_tpetra =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraMultiVector(
            dfdp_out
            );

      const int numAllParams = this->get_p_space(0)->dim();
      TEUCHOS_ASSERT_EQUALITY(
          numAllParams,
          dfdp_out_tpetra->getNumVectors()
          );
      // Compute all derivatives.
      this->dfdp_->set_parameters(params, {});
      for (int k = 0; k < numAllParams; k++) {
        this->dfdp_->apply(
            *x_in_tpetra,
            *dfdp_out_tpetra->getVectorNonConst(k)
            );
      }
    }

    // Fill Jacobian.
    const auto & W_out = out_args.get_W_op();
    if(!W_out.is_null()) {
      auto W_outT =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraOperator(
            W_out
            );
      const auto & jac =
        Teuchos::rcp_dynamic_cast<nosh::fvm_operator>(W_outT, true);
      std::shared_ptr<const Tpetra::Vector<double,int,int>> x_std =
        Teuchos::get_shared_ptr(x_in_tpetra);
      jac->set_parameters(params, {{"u0", x_std}});
    }

//     // Fill preconditioner.
//     const auto & WPrec_out = out_args.get_W_prec();
//     if(!WPrec_out.is_null()) {
//       auto WPrec_outT =
//         Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraOperator(
//             WPrec_out->getNonconstUnspecifiedPrecOp()
//             );
//       const auto & keoPrec =
//         Teuchos::rcp_dynamic_cast<nosh::keo_regularized>(WPrec_outT, true);
//       keoPrec->rebuild(
//           params,
//           *x_in_tpetra
//           );
//     }
    return;
  }
Пример #18
0
  virtual
  void evalModelImpl(
      const Thyra::ModelEvaluatorBase::InArgs<double> &in_args,
      const Thyra::ModelEvaluatorBase::OutArgs<double> &out_args
      ) const
  {
    const auto & x_in = in_args.get_x();
#ifndef NDEBUG
    TEUCHOS_ASSERT(!x_in.is_null());
#endif
    // create corresponding tpetra vector
    auto x_in_tpetra =
      Thyra::TpetraOperatorVectorExtraction<double,int,int>::getConstTpetraVector(
          x_in
          );

    // compute F
    const auto & f_out = out_args.get_f();
    if (!f_out.is_null()) {
      // Dissect in_args.get_p(0) into parameter sublists.
      const auto & p_in = in_args.get_p(0);
#ifndef NDEBUG
      TEUCHOS_ASSERT(!p_in.is_null());
      // Make sure the parameters aren't NaNs.
      for (int k = 0; k < p_in->space()->dim(); k++) {
        TEUCHOS_ASSERT(!std::isnan(Thyra::get_ele(*p_in, k)));
      }
#endif
      // Fill the parameters into a std::map.
      const auto param_names = this->get_p_names(0);
      const double alph = Thyra::get_ele(*p_in, 0);

      auto f_out_tpetra =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraVector(
            f_out
            );
      const auto x_data = x_in_tpetra->getData();
      auto f_data = f_out_tpetra->getDataNonConst();
      for (size_t i = 0; i < f_data.size(); i++) {
        f_data[i] = x_data[i] * x_data[i] - alph;
      }
    }

    // Compute df/dp.
    const auto & derivMv = out_args.get_DfDp(0).getDerivativeMultiVector();
    const auto & dfdp_out = derivMv.getMultiVector();
    if (!dfdp_out.is_null()) {
      auto dfdp_out_tpetra =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraMultiVector(
            dfdp_out
            );

      TEUCHOS_ASSERT_EQUALITY(dfdp_out_tpetra->getNumVectors(), 1);
      auto out = dfdp_out_tpetra->getVectorNonConst(0);
      auto out_data = out->getDataNonConst();
      for (size_t k = 0; k < out_data.size(); k++) {
        out_data[k] = -1.0;
      }
    }

    // Fill Jacobian.
    const auto & W_out = out_args.get_W_op();
    if(!W_out.is_null()) {
      auto W_outT =
        Thyra::TpetraOperatorVectorExtraction<double,int,int>::getTpetraOperator(
            W_out
            );
      const auto & jac = Teuchos::rcp_dynamic_cast<jac_sqrt_alpha>(W_outT, true);
      jac->set_x0(*x_in_tpetra);
    }

    return;
  }
Пример #19
0
void panzer::ScatterResidual_Epetra<panzer::Traits::Jacobian, Traits,LO,GO>::
evaluateFields(typename Traits::EvalData workset)
{ 
   std::vector<int> cLIDs, rLIDs;
   std::vector<double> jacRow;

   bool useColumnIndexer = colGlobalIndexer_!=Teuchos::null;

   // for convenience pull out some objects from workset
   std::string blockId = workset.block_id;
   const std::vector<std::size_t> & localCellIds = workset.cell_local_ids;

   Teuchos::RCP<Epetra_Vector> r = epetraContainer_->get_f(); 
   Teuchos::RCP<Epetra_CrsMatrix> Jac = epetraContainer_->get_A();
   
   // NOTE: A reordering of these loops will likely improve performance
   //       The "getGIDFieldOffsets" may be expensive.  However the
   //       "getElementGIDs" can be cheaper. However the lookup for LIDs
   //       may be more expensive!

   // scatter operation for each cell in workset
   for(std::size_t worksetCellIndex=0;worksetCellIndex<localCellIds.size();++worksetCellIndex) {
      std::size_t cellLocalId = localCellIds[worksetCellIndex];

      rLIDs = globalIndexer_->getElementLIDs(cellLocalId); 
      if(useColumnIndexer)
        cLIDs = colGlobalIndexer_->getElementLIDs(cellLocalId); 
      else
        cLIDs = rLIDs;

      // loop over each field to be scattered
      for(std::size_t fieldIndex = 0; fieldIndex < scatterFields_.size(); fieldIndex++) {
         int fieldNum = fieldIds_[fieldIndex];
         const std::vector<int> & elmtOffset = globalIndexer_->getGIDFieldOffsets(blockId,fieldNum);

         // loop over the basis functions (currently they are nodes)
         for(std::size_t rowBasisNum = 0; rowBasisNum < elmtOffset.size(); rowBasisNum++) {
            const ScalarT & scatterField = (scatterFields_[fieldIndex])(worksetCellIndex,rowBasisNum);
            int rowOffset = elmtOffset[rowBasisNum];
            int row = rLIDs[rowOffset];
    
            // Sum residual
            if(r!=Teuchos::null)
    	       r->SumIntoMyValue(row,0,scatterField.val());
            
            // Sum Jacobian
            if(useDiscreteAdjoint_) {
               // loop over the sensitivity indices: all DOFs on a cell
               jacRow.resize(scatterField.size());
            
               for(int sensIndex=0;sensIndex<scatterField.size();++sensIndex)
                  jacRow[sensIndex] = scatterField.fastAccessDx(sensIndex);

               for(std::size_t c=0;c<cLIDs.size();c++) {
                  int err = Jac->SumIntoMyValues(cLIDs[c], 1, &jacRow[c],&row);
                  TEUCHOS_ASSERT_EQUALITY(err,0);
               }
            }
            else {
               int err = Jac->SumIntoMyValues(row,
					   scatterField.size(),
					   scatterField.dx(),
					   panzer::ptrFromStlVector(cLIDs));
               TEUCHOS_ASSERT_EQUALITY(err,0);
            }
         } // end rowBasisNum
      } // end fieldIndex
   }
}
Пример #20
0
// =============================================================================
void
VIO::Image::Writer::Abstract::
setImageData ( const Epetra_MultiVector              & x,
               const Teuchos::Tuple<unsigned int,2>  & Nx,
               const Point                           & h,
               const Teuchos::Array<int>             & p,
               const Teuchos::Array<std::string>     & scalarsNames
             )
{
    int numVecs   = x.NumVectors();
    int numPoints = ( Nx[0]+1 ) * ( Nx[1]+1 );

    // get scalarsNames, and insert default names if empty
    Teuchos::Array<std::string> scNames ( scalarsNames );
    if ( scNames.empty() )
    {
        scNames.resize ( numVecs );
        for ( int vec=0; vec<numVecs; vec++ )
            scNames[vec] = "x" + EpetraExt::toString ( vec );
    }

    // cast into vtkImageData
    vtkSmartPointer<vtkImageData> imageData =
        dynamic_cast<vtkImageData*> ( vtkDataSet_.GetPointer() );
    TEUCHOS_ASSERT_INEQUALITY( 0, !=, imageData );

    // set other image data
    imageData->SetDimensions ( Nx[0]+1, Nx[1]+1, 1 );
    imageData->SetOrigin ( 0.0, 0.0, 0.0 );
    imageData->SetSpacing ( h[0], h[1], 0.0 );

    // fill the scalar field
    vtkSmartPointer<vtkDoubleArray> scalars =
        vtkSmartPointer<vtkDoubleArray>::New();

    bool isScrambled = !p.empty();

    if ( isScrambled )
    {
        TEUCHOS_ASSERT_EQUALITY ( numPoints, p.length() );
        addFieldData ( p, "p" );
    }

    // fill the scalars vector and add it to imageData_
    if ( isScrambled )
    {
        double dummy = 0.0;
        for ( int vec=0; vec<numVecs; vec++ )
        {
            scalars->SetName ( scNames[vec].c_str() );
            for ( int k=0; k<numPoints; k++ )
                scalars->InsertNextValue ( p[k]>=0 ? x[vec][p[k]] : dummy );
            imageData->GetPointData()->AddArray ( scalars );
        }
    }
    else
        for ( int vec=0; vec<numVecs; vec++ )
        {
            scalars->SetName ( scNames[vec].c_str() );
            for ( int k=0; k<numPoints; k++ )
                scalars->InsertNextValue ( x[vec][k] );
            imageData->GetPointData()->AddArray ( scalars );
        }

    return;
}
Пример #21
0
// =============================================================================
void
VIO::Image::Writer::Abstract::
setImageData ( const ComplexMultiVector              & x,
               const Teuchos::Tuple<unsigned int,2>  & Nx,
               const Point                           & h,
               const Teuchos::Array<int>             & p,
               const Teuchos::Array<std::string>     & scalarsNames
             )
{
    int numVecs   = x.getNumVectors();
    int numPoints = ( Nx[0]+1 ) * ( Nx[1]+1 );

    // get scalarsNames, and insert default names if empty
    Teuchos::Array<std::string> scNames ( scalarsNames );
    if ( scNames.empty() )
    {
        scNames.resize ( numVecs );
        for ( int vec=0; vec<numVecs; vec++ )
            scNames[vec] = "z" + EpetraExt::toString ( vec );
    }
    
    // cast into vtkImageData
    vtkSmartPointer<vtkImageData> imageData =
        dynamic_cast<vtkImageData*> ( vtkDataSet_.GetPointer() );
    TEUCHOS_ASSERT_INEQUALITY( 0, !=, imageData );

    // set other image data
    imageData->SetDimensions ( Nx[0]+1, Nx[1]+1, 1 );
    imageData->SetOrigin ( 0.0, 0.0, 0.0 );
    imageData->SetSpacing ( h[0], h[1], 0.0 );

    // fill the scalar field
    vtkSmartPointer<vtkDoubleArray> scalars =
        vtkSmartPointer<vtkDoubleArray>::New();

    double dummy = 0.0;
    bool isScrambled = !p.empty();
    if ( isScrambled )
    {
        TEUCHOS_ASSERT_EQUALITY ( numPoints, p.length() );
        addFieldData ( p, "p" );
    }

    // real and imaginary part
    scalars->SetNumberOfComponents ( 2 );

    // fill the scalars vector and add it to imageData_
    Teuchos::ArrayRCP<const std::complex<double> > xView;
    for ( int vec=0; vec<numVecs; vec++ )
    {
        xView = x.getVector ( vec )->get1dView();
        scalars->SetName ( scNames[vec].c_str() );
        for ( int k=0; k<numPoints; k++ )
        {
            if ( isScrambled )
            {
                // TODO replace by InsertNextTuple
                scalars->InsertNextValue ( p[k]>=0 ? std::real ( xView[p[k]] ) : dummy );
                scalars->InsertNextValue ( p[k]>=0 ? std::imag ( xView[p[k]] ) : dummy );
            }
            else
            {
                scalars->InsertNextValue ( std::real ( xView[k] ) );
                scalars->InsertNextValue ( std::imag ( xView[k] ) );
            }
        }
        imageData->GetPointData()->AddArray ( scalars );
    }

    return;
}