Esempio n. 1
0
void Tpetra_RowGraph<MatrixType>::getLocalRowCopy(local_ordinal_type LocalRow,
                                              const Teuchos::ArrayView<local_ordinal_type> &Indices,
                                              size_t &NumEntries) const
{
  Teuchos::Array<scalar_type> Values(Indices.size());
  A_->getLocalRowCopy(LocalRow,Indices,Values (),NumEntries);
}
Esempio n. 2
0
int main()
{
char s[100];
int i=0;
int number=0;
printf("Enter Roman number:");
scanf("%s",s);

while(Values(s[i])!=0)
    {
        if(Values(s[i])<0)
            {
                printf("Invalid number.");
                return 0;
            }
        number=number+Values(s[i]);
        i++;
    }
if(number>256)
    {
        printf("Invalid number.");
        return 0;
    }
printf("%d",number);
return 0;
}
Esempio n. 3
0
	Values AsebaNetworkInterface::GetVariable(const QString& node, const QString& variable, const QDBusMessage &message)
	{
		// make sure the node exists
		NodesNamesMap::const_iterator nodeIt(nodesNames.find(node));
		if (nodeIt == nodesNames.end())
		{
			DBusConnectionBus().send(message.createErrorReply(QDBusError::InvalidArgs, QString("node %0 does not exists").arg(node)));
			return Values();
		}
		const unsigned nodeId(nodeIt.value());
		
		unsigned pos(unsigned(-1));
		unsigned length(unsigned(-1));
		
		// check whether variable is user-defined
		const UserDefinedVariablesMap::const_iterator userVarMapIt(userDefinedVariablesMap.find(node));
		if (userVarMapIt != userDefinedVariablesMap.end())
		{
			const VariablesMap& userVarMap(userVarMapIt.value());
			const VariablesMap::const_iterator userVarIt(userVarMap.find(variable.toStdWString()));
			if (userVarIt != userVarMap.end())
			{
				pos = userVarIt->second.first;
				length = userVarIt->second.second;
			}
		}
		
		// if variable is not user-defined, check whether it is provided by this node
		if (pos == unsigned(-1))
		{
			bool ok1, ok2;
			pos = getVariablePos(nodeId, variable.toStdWString(), &ok1);
			length = getVariableSize(nodeId, variable.toStdWString(), &ok2);
			if (!(ok1 && ok2))
			{
				DBusConnectionBus().send(message.createErrorReply(QDBusError::InvalidArgs, QString("variable %0 does not exists in node %1").arg(variable).arg(node)));
				return Values();
			}
		}
		
		// send request to aseba network
		{
			GetVariables msg(nodeId, pos, length);
			hub->sendMessage(msg);
		}
		
		// build bookkeeping for async reply
		RequestData *request = new RequestData;
		request->nodeId = nodeId;
		request->pos = pos;
		message.setDelayedReply(true);
		request->reply = message.createReply();
		
		pendingReads.push_back(request);
		return Values();
	}
void Mouse::updateMethod()
{
    // Mouse position
    {
        GLFWwindow* win;
        int xpos, ypos;
        Window::getMousePos(win, xpos, ypos);

        State substate;
        substate.action = "mouse_position";
        substate.value = Values({xpos, ypos});
        substate.window = getWindowName(win);
        _state.emplace_back(std::move(substate));
    }

    // Buttons events
    while (true)
    {
        GLFWwindow* win;
        int btn, action, mods;
        if (!Window::getMouseBtn(win, btn, action, mods))
            break;

        State substate;
        switch (action)
        {
        default:
            continue;
        case GLFW_PRESS:
            substate.action = "mouse_press";
            break;
        case GLFW_RELEASE:
            substate.action = "mouse_release";
            break;
        }
        substate.value = Values({Value(btn)});
        substate.modifiers = mods;
        substate.window = getWindowName(win);
        _state.emplace_back(std::move(substate));
    }

    // Scrolling events
    while (true)
    {
        GLFWwindow* win;
        double xoffset, yoffset;
        if (!Window::getScroll(win, xoffset, yoffset))
            break;

        State substate;
        substate.action = "mouse_scroll";
        substate.value = Values({xoffset, yoffset});
        substate.window = getWindowName(win);
        _state.emplace_back(std::move(substate));
    }
}
  Teuchos::RCP<Xpetra::CrsMatrixWrap<Scalar,LocalOrdinal, GlobalOrdinal, Node> >
  GenerateProblemMatrix(const Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > map,
                        Scalar a = 2.0, Scalar b = -1.0, Scalar c = -1.0) {
#   include "MueLu_UseShortNames.hpp"

    Teuchos::RCP<CrsMatrixWrap> mtx = Galeri::Xpetra::MatrixTraits<Map,CrsMatrixWrap>::Build(map, 3);

    LocalOrdinal NumMyElements = map->getNodeNumElements();
    Teuchos::ArrayView<const GlobalOrdinal> MyGlobalElements = map->getNodeElementList();
    GlobalOrdinal NumGlobalElements = map->getGlobalNumElements();
    GlobalOrdinal nIndexBase = map->getIndexBase();

    GlobalOrdinal NumEntries;
    LocalOrdinal nnz=2;
    std::vector<Scalar> Values(nnz);
    std::vector<GlobalOrdinal> Indices(nnz);

    for (LocalOrdinal i = 0; i < NumMyElements; ++i)
    {
      if (MyGlobalElements[i] == nIndexBase)
      {
        // off-diagonal for first row
        Indices[0] = nIndexBase;
        NumEntries = 1;
        Values[0] = c;
      }
      else if (MyGlobalElements[i] == nIndexBase + NumGlobalElements - 1)
      {
        // off-diagonal for last row
        Indices[0] = nIndexBase + NumGlobalElements - 2;
        NumEntries = 1;
        Values[0] = b;
      }
      else
      {
        // off-diagonal for internal row
        Indices[0] = MyGlobalElements[i] - 1;
        Values[1] = b;
        Indices[1] = MyGlobalElements[i] + 1;
        Values[0] = c;
        NumEntries = 2;
      }

      // put the off-diagonal entries
      // Xpetra wants ArrayViews (sigh)
      Teuchos::ArrayView<Scalar> av(&Values[0],NumEntries);
      Teuchos::ArrayView<GlobalOrdinal> iv(&Indices[0],NumEntries);
      mtx->insertGlobalValues(MyGlobalElements[i], iv, av);

      // Put in the diagonal entry
      mtx->insertGlobalValues(MyGlobalElements[i],
          Teuchos::tuple<GlobalOrdinal>(MyGlobalElements[i]),
          Teuchos::tuple<Scalar>(a) );

    } //for (LocalOrdinal i = 0; i < NumMyElements; ++i)

    mtx->fillComplete(map,map);

    return mtx;
  }
Esempio n. 6
0
/// building the stencil
void PoissonSolver::StencilGeometry(Teuchos::RCP<Epetra_Vector> & RHS,
                                    Teuchos::RCP<Epetra_CrsMatrix> & A)
{
    const Epetra_BlockMap & MyMap = RHS->Map();
    int NumMyElements = MyMap.NumMyElements();
    int* MyGlobalElements = MyMap.MyGlobalElements();
    double * rhsvalues = RHS->Values();

    std::vector<double> Values(5);
    std::vector<int> Indices(5);

    const auto & inside = _bend.getInsideMask();

    for (int lid = 0; lid < NumMyElements; ++ lid) {
        size_t NumEntries = 0;

        const size_t & gid = MyGlobalElements[lid];

        cutoffStencil(Indices,
                      Values,
                      rhsvalues[lid],
                      NumEntries,
                      inside,
                      gid);
        A->InsertGlobalValues(gid, NumEntries, &Values[0], &Indices[0]);
    }

    A->FillComplete();
    A->OptimizeStorage();
}
Esempio n. 7
0
//==============================================================================
Ifpack_DiagonalFilter::Ifpack_DiagonalFilter(const Teuchos::RefCountPtr<Epetra_RowMatrix>& Matrix,
					     double AbsoluteThreshold,
					     double RelativeThreshold) :
  A_(Matrix),
  AbsoluteThreshold_(AbsoluteThreshold),
  RelativeThreshold_(RelativeThreshold)
{
  Epetra_Time Time(Comm());
  
  pos_.resize(NumMyRows());
  val_.resize(NumMyRows());
  
  std::vector<int> Indices(MaxNumEntries());
  std::vector<double> Values(MaxNumEntries());
  int NumEntries;
  
  for (int MyRow = 0 ; MyRow < NumMyRows() ; ++MyRow) {
    
    pos_[MyRow] = -1;
    val_[MyRow] = 0.0;
    int ierr = A_->ExtractMyRowCopy(MyRow, MaxNumEntries(), NumEntries,
				    &Values[0], &Indices[0]);
    assert (ierr == 0);
    
    for (int i = 0 ; i < NumEntries ; ++i) {
      if (Indices[i] == MyRow) {
	pos_[MyRow] = i;
	val_[MyRow] = Values[i] * (RelativeThreshold_ - 1) +
	  AbsoluteThreshold_ * EPETRA_SGN(Values[i]);
      }
      break;
    }
  }
  cout << "TIME = " << Time.ElapsedTime() << endl;
}
Esempio n. 8
0
// ============================================================================
void
Solve(const Epetra_RowMatrix* Matrix, const Epetra_MultiVector* LHS,
      const Epetra_MultiVector* RHS)
{
  if (Matrix->Comm().NumProc() != 1)
    throw(Exception(__FILE__, __LINE__,
                    "Solve() works only in serial"));
  if (LHS->NumVectors() != RHS->NumVectors())
    throw(Exception(__FILE__, __LINE__,
                    "number of vectors in multivectors not consistent"));

  if(Matrix->NumGlobalRows64() > std::numeric_limits<int>::max())
    throw(Exception(__FILE__, __LINE__,
                    "Matrix->NumGlobalRows64() > std::numeric_limits<int>::max()"));

  int n = static_cast<int>(Matrix->NumGlobalRows64());
  int NumVectors = LHS->NumVectors();

  Epetra_SerialDenseMatrix DenseMatrix;
  DenseMatrix.Shape(n, n);

  for (int i = 0 ; i < n ; ++i)
    for (int j = 0 ; j < n ; ++j)
      DenseMatrix(i,j) = 0.0;

  // allocate storage to extract matrix rows.
  int Length = Matrix->MaxNumEntries();
  vector<double> Values(Length);
  vector<int>    Indices(Length);

  for (int j = 0 ; j < Matrix->NumMyRows() ; ++j)
  {
    int NumEntries;
    int ierr = Matrix->ExtractMyRowCopy(j, Length, NumEntries,
                                        &Values[0], &Indices[0]);

    for (int k = 0 ; k < NumEntries ; ++k)
      DenseMatrix(j,Indices[k]) = Values[k];
  }

  Epetra_SerialDenseMatrix DenseX(n, NumVectors);
  Epetra_SerialDenseMatrix DenseB(n, NumVectors);

  for (int i = 0 ; i < n ; ++i)
    for (int j = 0 ; j < NumVectors ; ++j)
      DenseB(i,j) = (*RHS)[j][i];

  Epetra_SerialDenseSolver DenseSolver;

  DenseSolver.SetMatrix(DenseMatrix);
  DenseSolver.SetVectors(DenseX,DenseB);

  DenseSolver.Factor();
  DenseSolver.Solve();

  for (int i = 0 ; i < n ; ++i)
    for (int j = 0 ; j < NumVectors ; ++j)
       (*LHS)[j][i] = DenseX(i,j);
}
Esempio n. 9
0
AnsiString TFastIniSection::ReadString(AnsiString Key, AnsiString Default)
{
    int index = SearchKey(Key);
    if (index >= 0){
        return Values(index);
    }else{
        return Default;
    }
}
    Teuchos::RCP<Matrix>
    TriDiag_Helmholtz(const Teuchos::RCP<const Map> & map, const GlobalOrdinal nx,
                      const double h, const double omega, const Scalar shift) {

      Teuchos::RCP<Matrix> mtx = MatrixTraits<Map,Matrix>::Build(map, 3);
      LocalOrdinal NumMyElements = map->getNodeNumElements();
      Teuchos::ArrayView<const GlobalOrdinal> MyGlobalElements = map->getNodeElementList();
      Teuchos::RCP<const Teuchos::Comm<int> > comm = map->getComm();
      GlobalOrdinal NumGlobalElements = map->getGlobalNumElements();
      GlobalOrdinal NumEntries;
      LocalOrdinal nnz=2;
      std::vector<Scalar> Values(nnz);
      std::vector<GlobalOrdinal> Indices(nnz);
      Scalar one = (Scalar) 1.0;
      Scalar two = (Scalar) 2.0;
      comm->barrier();
      Teuchos::RCP<Teuchos::Time> timer = rcp(new Teuchos::Time("TriDiag global insert"));
      timer->start(true);
      for (LocalOrdinal i = 0; i < NumMyElements; ++i) {
        if (MyGlobalElements[i] == 0) {
          // off-diagonal for first row
          Indices[0] = 1;
          NumEntries = 1;
          Values[0] = -one;
        }
        else if (MyGlobalElements[i] == NumGlobalElements - 1) {
          // off-diagonal for last row
          Indices[0] = NumGlobalElements - 2;
          NumEntries = 1;
          Values[0] = -one;
        }
        else {
          // off-diagonal for internal row
          Indices[0] = MyGlobalElements[i] - 1;
          Indices[1] = MyGlobalElements[i] + 1;
          Values[0] = -one;
          Values[1] = -one;
          NumEntries = 2;
        }
        // put the off-diagonal entries
        // Xpetra wants ArrayViews (sigh)
        Teuchos::ArrayView<Scalar> av(&Values[0],NumEntries);
        Teuchos::ArrayView<GlobalOrdinal> iv(&Indices[0],NumEntries);
        mtx->insertGlobalValues(MyGlobalElements[i], iv, av);
        // Put in the diagonal entry
        mtx->insertGlobalValues(MyGlobalElements[i],
                                Teuchos::tuple<GlobalOrdinal>(MyGlobalElements[i]),
                                Teuchos::tuple<Scalar>(two-shift*omega*omega*h*h) );
      }
      timer->stop();
      timer = rcp(new Teuchos::Time("TriDiag fillComplete"));
      timer->start(true);
      mtx->fillComplete();
      timer->stop();
      return mtx;

    } //TriDiag_Helmholtz
Esempio n. 11
0
float TFastIniSection::ReadFloat(AnsiString Key, float Default)
{
    int index = SearchKey(Key);
    if (index >= 0){
        return StrToFloatDef(Values(index), Default);
    }else{
        return Default;
    }
}
Esempio n. 12
0
int TFastIniSection::ReadInteger(AnsiString Key, int Default)
{
    int index = SearchKey(Key);
    if (index >= 0){
        return StrToIntDef(Values(index), Default);
    }else{
        return Default;
    }
}
Esempio n. 13
0
int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        STXXL_MSG("Usage: " << argv[0] << " #log_ins");
        return -1;
    }

    const int log_nins = atoi(argv[1]);
    if (log_nins > 31) {
        STXXL_ERRMSG("This test can't do more than 2^31 operations, you requested 2^" << log_nins);
        return -1;
    }

    btree_type BTree(1024 * 128, 1024 * 128);

    const stxxl::uint64 nins = 1ULL << log_nins;

    stxxl::ran32State = (unsigned int)time(NULL);


    stxxl::vector<int> Values(nins);
    STXXL_MSG("Generating " << nins << " random values");
    stxxl::generate(Values.begin(), Values.end(), rnd_gen(), 4);

    stxxl::vector<int>::const_iterator it = Values.begin();
    STXXL_MSG("Inserting " << nins << " random values into btree");
    for ( ; it != Values.end(); ++it)
        BTree.insert(std::pair<int, double>(*it, double(*it) + 1.0));


    STXXL_MSG("Number of elements in btree: " << BTree.size());

    STXXL_MSG("Searching " << nins << " existing elements");
    stxxl::vector<int>::const_iterator vIt = Values.begin();

    for ( ; vIt != Values.end(); ++vIt)
    {
        btree_type::iterator bIt = BTree.find(*vIt);
        STXXL_CHECK(bIt != BTree.end());
        STXXL_CHECK(bIt->first == *vIt);
    }

    STXXL_MSG("Searching " << nins << " non-existing elements");
    stxxl::vector<int>::const_iterator vIt1 = Values.begin();

    for ( ; vIt1 != Values.end(); ++vIt1)
    {
        btree_type::iterator bIt = BTree.find((*vIt1) + 1);
        STXXL_CHECK(bIt == BTree.end());
    }

    STXXL_MSG("Test passed.");

    return 0;
}
Esempio n. 14
0
 Values Template::slot_range( const std::string & slot_name ) {
   DATA_OBJECT clipsdo;
   if ( !m_cobj )
     return Values();
   EnvDeftemplateSlotRange( m_environment.cobj(),
                            m_cobj,
                            const_cast<char*>( slot_name.c_str() ),
                            &clipsdo );
   return data_object_to_values( clipsdo );
 }
Esempio n. 15
0
Values Fact::slot_value( const std::string & name )
	{
		DATA_OBJECT data_object;
		int result;

		if ( !m_cobj )
			return Values();

    if ( name == "" ) {
      result = EnvGetFactSlot( m_environment.cobj(), m_cobj, NULL, &data_object );
//       result = EnvGetFactSlot( m_environment.cobj(), m_cobj, "", &data_object );
    }
    else
  		result = EnvGetFactSlot( m_environment.cobj(), m_cobj, const_cast<char*>(name.c_str()), &data_object );
		if (result)
			return data_object_to_values( data_object );
    else
			return Values();
	}
//=========================================================================
double  Epetra_SerialDenseVector::Norm2() const {

  // 2-norm of vector

  double result = NRM2(Length(), Values());

  UpdateFlops(2*Length());

  return(result);
}
Esempio n. 17
0
 Values Template::slot_cardinality( const std::string & slot_name ) {
   DATA_OBJECT clipsdo;
   if ( m_cobj ) {
     EnvDeftemplateSlotCardinality( m_environment.cobj(),
                                    m_cobj,
                                    const_cast<char*>( slot_name.c_str() ),
                                    &clipsdo );
     return data_object_to_values( clipsdo );
   } else
     return Values();
 }
Esempio n. 18
0
void ChannelServer::sendNotification(const std::string &name, T &&... values) {
    notificationBuf_.clear();

    using Values = msgpack::type::tuple<T...>;
    using Msg = msgpack::type::tuple<unsigned, const std::string &, Values>;
    msgpack::pack(notificationBuf_, Msg(msgpackrpc::notification, name,
                                        Values(std::forward<T>(values)...)));

    notificationSocket_.socket.send(
        buffer(notificationBuf_.data(), notificationBuf_.size()));
}
//=========================================================================
double  Epetra_SerialDenseVector::NormInf() const {

  // Inf-norm of vector
  double result = 0.0;
  int j = IAMAX(Length(), Values()); // Location of max (-1) if length zero

  if (j>-1) result = std::abs( (*this)[j]);

  // UpdateFlops(2*Length()); // Technically there are no FLOPS

  return(result);
}
Esempio n. 20
0
Epetra_CrsMatrix* TridiagMatrix(const Epetra_Map* Map, const double a, const double b, const double c)
{
  Epetra_CrsMatrix* Matrix = new Epetra_CrsMatrix(Copy, *Map,  3);

  int NumGlobalElements = Map->NumGlobalElements();
  int NumMyElements = Map->NumMyElements();
  int* MyGlobalElements = Map->MyGlobalElements();

  std::vector<double> Values(2);
  std::vector<int> Indices(2);
  int NumEntries;

  for (int i = 0; i < NumMyElements; ++i)
  {
    if (MyGlobalElements[i] == 0)
    {
      // off-diagonal for first row
      Indices[0] = 1;
      NumEntries = 1;
      Values[0] = c;
    }
    else if (MyGlobalElements[i] == NumGlobalElements - 1)
    {
      // off-diagonal for last row
      Indices[0] = NumGlobalElements - 2;
      NumEntries = 1;
      Values[0] = b;
    }
    else
    {
      // off-diagonal for internal row
      Indices[0] = MyGlobalElements[i] - 1;
      Values[1] = b;
      Indices[1] = MyGlobalElements[i] + 1;
      Values[0] = c;
      NumEntries = 2;
    }
    Matrix->InsertGlobalValues(MyGlobalElements[i], NumEntries, &Values[0],
                               &Indices[0]);
    // Put in the diagonal entry
    Values[0] = a;
    Matrix->InsertGlobalValues(MyGlobalElements[i], 1, &Values[0],
                               MyGlobalElements + i);
  }

  // Finish up, trasforming the matrix entries into local numbering,
  // to optimize data transfert during matrix-vector products
  Matrix->FillComplete();
  Matrix->OptimizeStorage();

  return(Matrix);
}
Esempio n. 21
0
void Http::set_header(const Key &key, const Value &value) {
    Header::iterator it;

    it = headers.find(Key(key));

    if (it == headers.end()) {
        std::pair<Header::iterator, bool> res;
        res = headers.insert(std::make_pair(Key(key), Values()));
        it = res.first;
    }

    it->second.push_back(Value(value));
}
Esempio n. 22
0
Matrix::Matrix(int row, int column, double initValue) : row(row), column(column) {
	if (Row() < 1 || Column() < 1) {
		throw "Exception : Invailed matrix size.\n";
		exit(EXIT_FAILURE);
	}

	this->values = new double[Size()];
	if (!Values()) {
		throw "Exception : Can not allocate memory.\n";
		exit(EXIT_FAILURE);
	}

	for (long i = 0; i < Size(); i++) {
		(*this)(i) = initValue;
	}
}
//=========================================================================
double  Epetra_SerialDenseVector::Dot(const Epetra_SerialDenseVector & x) const {

#ifdef HAVE_EPETRA_ARRAY_BOUNDS_CHECK
  if (Length()!=x.Length())
    throw ReportError("Length of this object = " +
		      toString(Length()) + " is not equal to length of x = "  + toString(x.Length()), -1);
#endif

  // dot-product of this and x.

  double result = DOT(Length(), Values(), x.Values());

  UpdateFlops(2*Length());

  return(result);
}
Esempio n. 24
0
void LtcClock::getClock(Values& clockValues)
{
    if (!_ready)
        return;

    Clock clock = _clock;
    clockValues = Values({(int)clock.years,
                          (int)clock.months,
                          (int)clock.days,
                          (int)clock.hours,
                          (int)clock.mins,
                          (int)clock.secs,
                          (int)clock.frame,
                          (int)clock.paused
                         });
}
Esempio n. 25
0
//============================================================================
// very simple debugging function that prints on screen the structure
// of the input matrix.
void Ifpack_PrintSparsity_Simple(const Epetra_RowMatrix& A)
{
  int MaxEntries = A.MaxNumEntries();
  std::vector<int> Indices(MaxEntries);
  std::vector<double> Values(MaxEntries);
  std::vector<bool> FullRow(A.NumMyRows());

  cout << "+-";
  for (int j = 0 ; j < A.NumMyRows() ; ++j)
    cout << '-';
  cout << "-+" << endl;

  for (int i = 0 ; i < A.NumMyRows() ; ++i) {

    int Length;
    A.ExtractMyRowCopy(i,MaxEntries,Length,
                       &Values[0], &Indices[0]);

    for (int j = 0 ; j < A.NumMyRows() ; ++j)
      FullRow[j] = false;

    for (int j = 0 ; j < Length ; ++j) {
      FullRow[Indices[j]] = true;
    }

    cout << "| ";
    for (int j = 0 ; j < A.NumMyRows() ; ++j) {
      if (FullRow[j])
        cout << '*';
      else
        cout << ' ';
    }
    cout << " |" << endl;
  }

  cout << "+-";
  for (int j = 0 ; j < A.NumMyRows() ; ++j)
    cout << '-';
  cout << "-+" << endl << endl;

}
Esempio n. 26
0
const vector<LongInt>
EngineBase::insert(const Table &table, const RowsData &rows,
        bool collect_new_ids)
{
    if (get_mode() == READ_ONLY)
        throw BadOperationInMode(
                _T("Using INSERT operation in read-only mode"));
    vector<LongInt> ids;
    if (!rows.size())
        return ids;
    touch();
    String sql;
    TypeCodes type_codes;
    ParamNums param_nums;
    gen_sql_insert(sql, type_codes, param_nums, table,
            !collect_new_ids, get_conn()->get_driver()->numbered_params());
    Values params(type_codes.size());
    auto_ptr<SqlCursor> cursor = get_conn()->new_cursor();
    cursor->prepare(sql);
    cursor->bind_params(type_codes);
    auto_ptr<SqlCursor> cursor2;
    if (collect_new_ids)
        cursor2.reset(get_conn()->new_cursor().release());
    RowsData::const_iterator r = rows.begin(), rend = rows.end();
    for (; r != rend; ++r) {
        ParamNums::const_iterator f = param_nums.begin(),
            fend = param_nums.end();
        for (; f != fend; ++f)
            params[f->second] = (**r)[table.idx_by_name(f->first)];
        cursor->exec(params);
        if (collect_new_ids) {
            cursor2->prepare(get_dialect()->
                    select_last_inserted_id(table.name()));
            cursor2->exec(Values());
            RowsPtr id_rows = cursor2->fetch_rows();
            ids.push_back((*id_rows)[0][0].second.as_longint());
        }
    }
    return ids;
}
//==============================================================================
int Ifpack_DropFilter::
Multiply(bool TransA, const Epetra_MultiVector& X, 
	 Epetra_MultiVector& Y) const
{
  // NOTE: I suppose that the matrix has been localized,
  // hence all maps are trivial.
  int NumVectors = X.NumVectors();
  if (NumVectors != Y.NumVectors())
    IFPACK_CHK_ERR(-1);

  Y.PutScalar(0.0);

  vector<int> Indices(MaxNumEntries_);
  vector<double> Values(MaxNumEntries_);

  for (int i = 0 ; i < NumRows_ ; ++i) {

    int Nnz;
    ExtractMyRowCopy(i,MaxNumEntries_,Nnz,
		     &Values[0], &Indices[0]);
    if (!TransA) {
      // no transpose first
      for (int j = 0 ; j < NumVectors ; ++j) {
	for (int k = 0 ; k < Nnz ; ++k) {
	  Y[j][i] += Values[k] * X[j][Indices[k]];
	}
      }
    }
    else {
      // transpose here
      for (int j = 0 ; j < NumVectors ; ++j) {
	for (int k = 0 ; k < Nnz ; ++k) {
	  Y[j][Indices[k]] += Values[k] * X[j][i];
	}
      }
    }
  }

  return(0);
}
DiagonalFilter<MatrixType>::DiagonalFilter(const Teuchos::RCP<const Tpetra::RowMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node> >& Matrix,
					   typename Teuchos::ScalarTraits<Scalar>::magnitudeType AbsoluteThreshold,
					   typename Teuchos::ScalarTraits<Scalar>::magnitudeType RelativeThreshold):
  A_(Matrix),  
  AbsoluteThreshold_(AbsoluteThreshold),
  RelativeThreshold_(RelativeThreshold)
{
  pos_.resize(getNodeNumRows());
  val_=Teuchos::rcp(new Tpetra::Vector<Scalar,LocalOrdinal,GlobalOrdinal,Node>(A_->getRowMap()));
  
  std::vector<LocalOrdinal> Indices(getNodeMaxNumRowEntries());
  std::vector<Scalar> Values(getNodeMaxNumRowEntries());
  size_t NumEntries;
  magnitudeType mysign;
 

  for (size_t MyRow = 0 ; MyRow < getNodeNumRows() ; ++MyRow) {    
    pos_[MyRow] = -1;
    A_->getLocalRowCopy(MyRow,Indices,Values,NumEntries);

    for (size_t i = 0 ; i < NumEntries ; ++i) {
      if ((size_t)Indices[i] == MyRow) {
	pos_[MyRow] = i;
	if(Teuchos::ScalarTraits<Scalar>::real(Values[i]) < 0)
	  mysign=-Teuchos::ScalarTraits<magnitudeType>::one();
	else
	  mysign=Teuchos::ScalarTraits<magnitudeType>::one();


	val_->replaceLocalValue(MyRow, Values[i] * (RelativeThreshold_ - 1) +
				AbsoluteThreshold_ * mysign);
	break;
      }
    }
  }
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
  int ierr = 0;

#ifdef EPETRA_MPI

  // Initialize MPI

  MPI_Init(&argc, &argv);
  int rank; // My process ID

  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  Epetra_MpiComm Comm( MPI_COMM_WORLD );

#else

  int rank = 0;
  Epetra_SerialComm Comm;

#endif

  bool verbose = false;

  // Check if we should print results to standard out
  if (argc>1) if (argv[1][0]=='-' && argv[1][1]=='v') verbose = true;

  int verbose_int = verbose ? 1 : 0;
  Comm.Broadcast(&verbose_int, 1, 0);
  verbose = verbose_int==1 ? true : false;

  Comm.SetTracebackMode(0); // This should shut down any error traceback reporting
  int MyPID = Comm.MyPID();
  int NumProc = Comm.NumProc();

  if(verbose && MyPID==0)
    std::cout << Epetra_Version() << std::endl << std::endl;

  if (verbose) std::cout << "Processor "<<MyPID<<" of "<< NumProc
		    << " is alive."<< std::endl;

  // unused: bool verbose1 = verbose;

  // Redefine verbose to only print on PE 0
  if(verbose && rank!=0) 
    verbose = false;

  if (verbose) std::cout << "Test the memory management system of the class CrsMatrix (memory leak, invalid free)" << std::endl;

  //
  // Test 1: code initially proposed to illustrate bug #5499
  //
  
  if(Comm.NumProc() == 1) { // this is a sequential test

    if (verbose) std::cout << "* Using Copy, ColMap, Variable number of indices per row and Static profile (cf. bug #5499)." << std::endl;

    // Row Map
    Epetra_Map RowMap(2LL, 0LL, Comm);
    
    // ColMap  
    std::vector<long long> colids(2);
    colids[0]=0;
    colids[1]=1;
    Epetra_Map ColMap(-1LL, 2, &colids[0], 0LL, Comm);

    // NumEntriesPerRow
    std::vector<int> NumEntriesPerRow(2);
    NumEntriesPerRow[0]=2;
    NumEntriesPerRow[1]=2;
    
    // Test
    Epetra_CrsMatrix A(Copy, RowMap, ColMap, &NumEntriesPerRow[0], true);
    // Bug #5499 shows up because InsertGlobalValues() is not called (CrsMatrix::Values_ not allocated but freed)
    A.FillComplete();
    
  }

  //
  // Test 1 Bis: same as Test1, but without ColMap and variable number of indices per row. Does not seems to matter
  //
  
  if(Comm.NumProc() == 1) { // this is a sequential test

    if (verbose) std::cout << "* Using Copy, Fixed number of indices per row and Static profile" << std::endl;

    Epetra_Map RowMap(2LL, 0LL, Comm);

    // Test
    Epetra_CrsMatrix    A(Copy, RowMap, 1, true);
    // Bug #5499 shows up because InsertGlobalValues() is not called (CrsMatrix::Values_ not allocated but freed)
    A.FillComplete();
    
  }

  //
  // Test 2: same as Test 1 Bis but with one call to InsertGlobalValues.
  //

  if(Comm.NumProc() == 1) {

    if (verbose) std::cout << "* Using Copy, Fixed number of indices per row and Static profile + InsertGlobalValues()." << std::endl;

    Epetra_Map RowMap(2LL, 0LL, Comm);

    // Test
    Epetra_CrsMatrix    A(Copy, RowMap, 1, true);
    std::vector<long long>    Indices(1);
    std::vector<double> Values(1);
    Values[0] = 2;
    Indices[0] = 0;

    A.InsertGlobalValues(0, 1, &Values[0], &Indices[0]); // Memory leak if CrsMatrix::Values not freed

    A.FillComplete();

  }

  // 
  // Test 3: check if the patch is not introducing some obvious regression
  //

  if(Comm.NumProc() == 1) {
    
    if (verbose) std::cout << "* Using Copy, Fixed number of indices per row and Dynamic profile" << std::endl;
    
    Epetra_Map RowMap(2LL, 0LL, Comm);

    // Test
    Epetra_CrsMatrix    A(Copy, RowMap, 1, false);
    A.FillComplete();
    
  }

  // 
  // Test 4: idem but with one call to InsertGlobalValues.
  // 

  if(Comm.NumProc() == 1) {
    
    if (verbose) std::cout << "* Using Copy, Fixed number of indices per row and Dynamic profile + InsertGlobalValues()." << std::endl;
    
    Epetra_Map RowMap(2LL, 0LL, Comm);

    // Test
    Epetra_CrsMatrix    A(Copy, RowMap, 1, false);
    std::vector<long long>    Indices(1);
    std::vector<double> Values(1);
    Values[0] = 2;
    Indices[0] = 0;
    
    A.InsertGlobalValues(0, 1, &Values[0], &Indices[0]);
    A.FillComplete();
    
  }

  if(Comm.NumProc() == 1) {
    
    if (verbose) std::cout << "* Using Copy, Static Graph()." << std::endl;
    
    Epetra_Map RowMap(1LL, 0LL, Comm);

    // Test
    Epetra_CrsGraph    G(Copy, RowMap, 1);
    std::vector<long long>    Indices(1);
    Indices[0] = 0;
    G.InsertGlobalIndices(0, 1, &Indices[0]);
    G.FillComplete();
    
    Epetra_CrsMatrix    A(Copy, G);
    std::vector<double> Values(1);
    Values[0] = 2;
    A.ReplaceGlobalValues(0, 1, &Values[0], &Indices[0]);
    A.FillComplete();
    double norminf = A.NormInf();
    if (verbose) std::cout << "** Inf Norm of Matrix = " << norminf << "." << std::endl;
    std::cout << A << std::endl;

    
  }


  if(Comm.NumProc() == 1) {
    
    if (verbose) std::cout << "* Using Copy, Fixed number of indices per row and static profile + InsertGlobalValues() for a single row." << std::endl;
    
    Epetra_Map RowMap(1LL, 0LL, Comm);

    // Test
    Epetra_CrsMatrix    A(Copy, RowMap, 1, true);
    std::vector<long long>    Indices(1);
    std::vector<double> Values(1);
    Values[0] = 2;
    Indices[0] = 0;
    
    A.InsertGlobalValues(0, 1, &Values[0], &Indices[0]);
    A.FillComplete();
    
  }

  /*
    if (bool) {
    if (verbose) std::cout << std::endl << "tests FAILED" << std::endl << std::endl;
    }
    else {*/
  if (verbose) std::cout << std::endl << "tests PASSED" << std::endl << std::endl;
  /*    } */

#ifdef EPETRA_MPI
  MPI_Finalize();
#endif

  return ierr;
}
Esempio n. 30
0
int main(int argc, char *argv[])
{
  int i;
  bool ierr, gerr;
  gerr = true;

#ifdef HAVE_MPI
  // Initialize MPI and setup an Epetra communicator
  MPI_Init(&argc,&argv);
  Teuchos::RCP<Epetra_MpiComm> Comm = Teuchos::rcp( new Epetra_MpiComm(MPI_COMM_WORLD) );
#else
  // If we aren't using MPI, then setup a serial communicator.
  Teuchos::RCP<Epetra_SerialComm> Comm = Teuchos::rcp( new Epetra_SerialComm() );
#endif

   // number of global elements
  int dim = 100;
  int blockSize = 5;

  bool verbose = false;
  if (argc>1) {
    if (argv[1][0]=='-' && argv[1][1]=='v') {
      verbose = true;
    }
  }

  // Construct a Map that puts approximately the same number of 
  // equations on each processor.
  Teuchos::RCP<Epetra_Map> Map = Teuchos::rcp( new Epetra_Map(dim, 0, *Comm) );
  
  // Get update list and number of local equations from newly created Map.
  int NumMyElements = Map->NumMyElements();
  std::vector<int> MyGlobalElements(NumMyElements);
  Map->MyGlobalElements(&MyGlobalElements[0]);

  // Create an integer std::vector NumNz that is used to build the Petra Matrix.
  // NumNz[i] is the Number of OFF-DIAGONAL term for the ith global equation 
  // on this processor
  std::vector<int> NumNz(NumMyElements);

  // We are building a tridiagonal matrix where each row has (-1 2 -1)
  // So we need 2 off-diagonal terms (except for the first and last equation)
  for (i=0; i<NumMyElements; i++) {
    if (MyGlobalElements[i]==0 || MyGlobalElements[i] == dim-1) {
      NumNz[i] = 2;
    }
    else {
      NumNz[i] = 3;
    }
  }

  // Create an Epetra_Matrix
  Teuchos::RCP<Epetra_CrsMatrix> A = Teuchos::rcp( new Epetra_CrsMatrix(Copy, *Map, &NumNz[0]) );
   
  // Add  rows one-at-a-time
  // Need some vectors to help
  // Off diagonal Values will always be -1
  std::vector<double> Values(2);
  Values[0] = -1.0; Values[1] = -1.0;
  std::vector<int> Indices(2);
  double two = 2.0;
  int NumEntries;
  for (i=0; i<NumMyElements; i++) {
    if (MyGlobalElements[i]==0) {
      Indices[0] = 1;
      NumEntries = 1;
    }
    else if (MyGlobalElements[i] == dim-1) {
      Indices[0] = dim-2;
      NumEntries = 1;
    }
    else {
      Indices[0] = MyGlobalElements[i]-1;
      Indices[1] = MyGlobalElements[i]+1;
      NumEntries = 2;
    }
    ierr = A->InsertGlobalValues(MyGlobalElements[i],NumEntries,&Values[0],&Indices[0]);
    assert(ierr==0);
    // Put in the diagonal entry
    ierr = A->InsertGlobalValues(MyGlobalElements[i],1,&two,&MyGlobalElements[i]);
    assert(ierr==0);
  }
   
  // Finish building the epetra matrix A
  ierr = A->FillComplete();
  assert(ierr==0);

  // Issue several useful typedefs;
  typedef Belos::MultiVec<double> EMV;
  typedef Belos::Operator<double> EOP;

  // Create an Epetra_MultiVector for an initial std::vector to start the solver.
  // Note that this needs to have the same number of columns as the blocksize.
  Teuchos::RCP<Belos::EpetraMultiVec> ivec = Teuchos::rcp( new Belos::EpetraMultiVec(*Map, blockSize) );
  ivec->Random();

  // Create an output manager to handle the I/O from the solver
  Teuchos::RCP<Belos::OutputManager<double> > MyOM = Teuchos::rcp( new Belos::OutputManager<double>() );
  if (verbose) {
    MyOM->setVerbosity( Belos::Warnings );
  }

  // test the Epetra adapter multivector
  ierr = Belos::TestMultiVecTraits<double,EMV>(MyOM,ivec);
  gerr &= ierr;
  if (ierr) {
    MyOM->print(Belos::Warnings,"*** EpetraAdapter PASSED TestMultiVecTraits()\n");
  }
  else {
    MyOM->print(Belos::Warnings,"*** EpetraAdapter FAILED TestMultiVecTraits() ***\n\n");
  }

#ifdef HAVE_MPI
  MPI_Finalize();
#endif

  if (gerr == false) {
    MyOM->print(Belos::Warnings,"End Result: TEST FAILED\n");
    return -1;
  }
  //
  // Default return value
  //
  MyOM->print(Belos::Warnings,"End Result: TEST PASSED\n");
  return 0;

}