IFPACK  Development
 All Classes Files Functions Variables Enumerations Friends Pages
Ifpack_ICT.cpp
1 /*@HEADER
2 // ***********************************************************************
3 //
4 // Ifpack: Object-Oriented Algebraic Preconditioner Package
5 // Copyright (2002) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 //@HEADER
41 */
42 
43 #include "Ifpack_ConfigDefs.h"
44 #include "Ifpack_Preconditioner.h"
45 #include "Ifpack_ICT.h"
46 #include "Ifpack_Condest.h"
47 #include "Ifpack_Utils.h"
48 #include "Ifpack_HashTable.h"
49 #include "Epetra_SerialComm.h"
50 #include "Epetra_Comm.h"
51 #include "Epetra_Map.h"
52 #include "Epetra_RowMatrix.h"
53 #include "Epetra_CrsMatrix.h"
54 #include "Epetra_Vector.h"
55 #include "Epetra_MultiVector.h"
56 #include "Epetra_Util.h"
57 #include "Teuchos_ParameterList.hpp"
58 #include "Teuchos_RefCountPtr.hpp"
59 #include <functional>
60 
61 //==============================================================================
62 // FIXME: allocate Comm_ and Time_ the first Initialize() call
63 Ifpack_ICT::Ifpack_ICT(const Epetra_RowMatrix* A) :
64  A_(*A),
65  Comm_(A_.Comm()),
66  Condest_(-1.0),
67  Athresh_(0.0),
68  Rthresh_(1.0),
69  LevelOfFill_(1.0),
70  DropTolerance_(0.0),
71  Relax_(0.0),
72  IsInitialized_(false),
73  IsComputed_(false),
74  UseTranspose_(false),
75  NumMyRows_(0),
76  NumInitialize_(0),
77  NumCompute_(0),
78  NumApplyInverse_(0),
79  InitializeTime_(0.0),
80  ComputeTime_(0.0),
81  ApplyInverseTime_(0.0),
82  ComputeFlops_(0.0),
83  ApplyInverseFlops_(0.0),
84  Time_(Comm()),
85  GlobalNonzeros_(0)
86 {
87  // do nothing here
88 }
89 
90 //==============================================================================
92 {
93  Destroy();
94 }
95 
96 //==============================================================================
97 void Ifpack_ICT::Destroy()
98 {
99  IsInitialized_ = false;
100  IsComputed_ = false;
101 }
102 
103 //==========================================================================
104 int Ifpack_ICT::SetParameters(Teuchos::ParameterList& List)
105 {
106 
107  try
108  {
109  LevelOfFill_ = List.get("fact: ict level-of-fill",LevelOfFill_);
110  Athresh_ = List.get("fact: absolute threshold", Athresh_);
111  Rthresh_ = List.get("fact: relative threshold", Rthresh_);
112  Relax_ = List.get("fact: relax value", Relax_);
113  DropTolerance_ = List.get("fact: drop tolerance", DropTolerance_);
114 
115  // set label
116  Label_ = "ICT (fill=" + Ifpack_toString(LevelOfFill())
117  + ", athr=" + Ifpack_toString(AbsoluteThreshold())
118  + ", rthr=" + Ifpack_toString(RelativeThreshold())
119  + ", relax=" + Ifpack_toString(RelaxValue())
120  + ", droptol=" + Ifpack_toString(DropTolerance())
121  + ")";
122 
123  return(0);
124  }
125  catch (...)
126  {
127  cerr << "Caught an exception while parsing the parameter list" << endl;
128  cerr << "This typically means that a parameter was set with the" << endl;
129  cerr << "wrong type (for example, int instead of double). " << endl;
130  cerr << "please check the documentation for the type required by each parameer." << endl;
131  IFPACK_CHK_ERR(-1);
132  }
133 }
134 
135 //==========================================================================
137 {
138  // clean data if present
139  Destroy();
140 
141  Time_.ResetStartTime();
142 
143  // matrix must be square. Check only on one processor
144  if (Comm().NumProc() == 1 && Matrix().NumMyRows() != Matrix().NumMyCols())
145  IFPACK_CHK_ERR(-2);
146 
147  NumMyRows_ = Matrix().NumMyRows();
148 
149  // nothing else to do here
150  IsInitialized_ = true;
151  ++NumInitialize_;
152  InitializeTime_ += Time_.ElapsedTime();
153 
154  return(0);
155 }
156 
157 //==========================================================================
159 {
160  if (!IsInitialized())
161  IFPACK_CHK_ERR(Initialize());
162 
163  Time_.ResetStartTime();
164  IsComputed_ = false;
165 
166  NumMyRows_ = A_.NumMyRows();
167  int Length = A_.MaxNumEntries();
168  vector<int> RowIndices(Length);
169  vector<double> RowValues(Length);
170 
171  bool distributed = (Comm().NumProc() > 1)?true:false;
172 
173  if (distributed)
174  {
175  SerialComm_ = Teuchos::rcp(new Epetra_SerialComm);
176  SerialMap_ = Teuchos::rcp(new Epetra_Map(NumMyRows_, 0, *SerialComm_));
177  assert (SerialComm_.get() != 0);
178  assert (SerialMap_.get() != 0);
179  }
180  else
181  SerialMap_ = Teuchos::rcp(const_cast<Epetra_Map*>(&A_.RowMatrixRowMap()), false);
182 
183  int RowNnz;
184 #ifdef IFPACK_FLOPCOUNTERS
185  double flops = 0.0;
186 #endif
187 
188  H_ = Teuchos::rcp(new Epetra_CrsMatrix(Copy,*SerialMap_,0));
189  if (H_.get() == 0)
190  IFPACK_CHK_ERR(-5); // memory allocation error
191 
192  // get A(0,0) element and insert it (after sqrt)
193  IFPACK_CHK_ERR(A_.ExtractMyRowCopy(0,Length,RowNnz,
194  &RowValues[0],&RowIndices[0]));
195 
196  // skip off-processor elements
197  if (distributed)
198  {
199  int count = 0;
200  for (int i = 0 ;i < RowNnz ; ++i)
201  {
202  if (RowIndices[i] < NumMyRows_){
203  RowIndices[count] = RowIndices[i];
204  RowValues[count] = RowValues[i];
205  ++count;
206  }
207  else
208  continue;
209  }
210  RowNnz = count;
211  }
212 
213  // modify diagonal
214  double diag_val = 0.0;
215  for (int i = 0 ;i < RowNnz ; ++i) {
216  if (RowIndices[i] == 0) {
217  double& v = RowValues[i];
218  diag_val = AbsoluteThreshold() * EPETRA_SGN(v) +
219  RelativeThreshold() * v;
220  break;
221  }
222  }
223 
224  diag_val = sqrt(diag_val);
225  int diag_idx = 0;
226  EPETRA_CHK_ERR(H_->InsertGlobalValues(0,1,&diag_val, &diag_idx));
227 
228  // The 10 is just a small constant to limit collisons as the actual keys
229  // we store are the indices and not integers
230  // [0..A_.MaxNumEntries()*LevelofFill()].
231  Ifpack_HashTable Hash( 10 * A_.MaxNumEntries() * LevelOfFill(), 1);
232 
233  // start factorization for line 1
234  for (int row_i = 1 ; row_i < NumMyRows_ ; ++row_i) {
235 
236  // get row `row_i' of the matrix
237  IFPACK_CHK_ERR(A_.ExtractMyRowCopy(row_i,Length,RowNnz,
238  &RowValues[0],&RowIndices[0]));
239 
240  // skip off-processor elements
241  if (distributed)
242  {
243  int count = 0;
244  for (int i = 0 ;i < RowNnz ; ++i)
245  {
246  if (RowIndices[i] < NumMyRows_){
247  RowIndices[count] = RowIndices[i];
248  RowValues[count] = RowValues[i];
249  ++count;
250  }
251  else
252  continue;
253  }
254  RowNnz = count;
255  }
256 
257  // number of nonzeros in this row are defined as the nonzeros
258  // of the matrix, plus the level of fill
259  int LOF = (int)(LevelOfFill() * RowNnz);
260  if (LOF == 0) LOF = 1;
261 
262  // convert line `row_i' into hash for fast access
263  Hash.reset();
264 
265  double h_ii = 0.0;
266  for (int i = 0 ; i < RowNnz ; ++i) {
267  if (RowIndices[i] == row_i) {
268  double& v = RowValues[i];
269  h_ii = AbsoluteThreshold() * EPETRA_SGN(v) + RelativeThreshold() * v;
270  }
271  else if (RowIndices[i] < row_i)
272  {
273  Hash.set(RowIndices[i], RowValues[i], true);
274  }
275  }
276 
277  // form element (row_i, col_j)
278  // I start from the first row that has a nonzero column
279  // index in row_i.
280  for (int col_j = RowIndices[0] ; col_j < row_i ; ++col_j) {
281 
282  double h_ij = 0.0, h_jj = 0.0;
283  // note: get() returns 0.0 if col_j is not found
284  h_ij = Hash.get(col_j);
285 
286  // get pointers to row `col_j'
287  int* ColIndices;
288  double* ColValues;
289  int ColNnz;
290  H_->ExtractGlobalRowView(col_j, ColNnz, ColValues, ColIndices);
291 
292  for (int k = 0 ; k < ColNnz ; ++k) {
293  int col_k = ColIndices[k];
294 
295  if (col_k == col_j)
296  h_jj = ColValues[k];
297  else {
298  double xxx = Hash.get(col_k);
299  if (xxx != 0.0)
300  {
301  h_ij -= ColValues[k] * xxx;
302 #ifdef IFPACK_FLOPCOUNTERS
303  flops += 2.0;
304 #endif
305  }
306  }
307  }
308 
309  h_ij /= h_jj;
310 
311  if (IFPACK_ABS(h_ij) > DropTolerance_)
312  {
313  Hash.set(col_j, h_ij);
314  }
315 
316 #ifdef IFPACK_FLOPCOUNTERS
317  // only approx
318  ComputeFlops_ += 2.0 * flops + 1.0;
319 #endif
320  }
321 
322  int size = Hash.getNumEntries();
323 
324  vector<double> AbsRow(size);
325  int count = 0;
326 
327  // +1 because I use the extra position for diagonal in insert
328  vector<int> keys(size + 1);
329  vector<double> values(size + 1);
330 
331  Hash.arrayify(&keys[0], &values[0]);
332 
333  for (int i = 0 ; i < size ; ++i)
334  {
335  AbsRow[i] = IFPACK_ABS(values[i]);
336  }
337  count = size;
338 
339  double cutoff = 0.0;
340  if (count > LOF) {
341  nth_element(AbsRow.begin(), AbsRow.begin() + LOF, AbsRow.begin() + count,
342 
343  std::greater<double>());
344  cutoff = AbsRow[LOF];
345  }
346 
347  for (int i = 0 ; i < size ; ++i)
348  {
349  h_ii -= values[i] * values[i];
350  }
351 
352  if (h_ii < 0.0) h_ii = 1e-12;;
353 
354  h_ii = sqrt(h_ii);
355 
356 #ifdef IFPACK_FLOPCOUNTERS
357  // only approx, + 1 == sqrt
358  ComputeFlops_ += 2 * size + 1;
359 #endif
360 
361  double DiscardedElements = 0.0;
362 
363  count = 0;
364  for (int i = 0 ; i < size ; ++i)
365  {
366  if (IFPACK_ABS(values[i]) > cutoff)
367  {
368  values[count] = values[i];
369  keys[count] = keys[i];
370  ++count;
371  }
372  else
373  DiscardedElements += values[i];
374  }
375 
376  if (RelaxValue() != 0.0) {
377  DiscardedElements *= RelaxValue();
378  h_ii += DiscardedElements;
379  }
380 
381  values[count] = h_ii;
382  keys[count] = row_i;
383  ++count;
384 
385  H_->InsertGlobalValues(row_i, count, &(values[0]), (int*)&(keys[0]));
386  }
387 
388  IFPACK_CHK_ERR(H_->FillComplete());
389 
390 #if 0
391  // to check the complete factorization
392  Epetra_Vector LHS(Matrix().RowMatrixRowMap());
393  Epetra_Vector RHS1(Matrix().RowMatrixRowMap());
394  Epetra_Vector RHS2(Matrix().RowMatrixRowMap());
395  Epetra_Vector RHS3(Matrix().RowMatrixRowMap());
396  LHS.Random();
397 
398  Matrix().Multiply(false,LHS,RHS1);
399  H_->Multiply(true,LHS,RHS2);
400  H_->Multiply(false,RHS2,RHS3);
401 
402  RHS1.Update(-1.0, RHS3, 1.0);
403  cout << endl;
404  cout << RHS1;
405 #endif
406  int MyNonzeros = H_->NumGlobalNonzeros();
407  Comm().SumAll(&MyNonzeros, &GlobalNonzeros_, 1);
408 
409  IsComputed_ = true;
410 #ifdef IFPACK_FLOPCOUNTERS
411  double TotalFlops; // sum across all the processors
412  A_.Comm().SumAll(&flops, &TotalFlops, 1);
413  ComputeFlops_ += TotalFlops;
414 #endif
415  ++NumCompute_;
416  ComputeTime_ += Time_.ElapsedTime();
417 
418  return(0);
419 
420 }
421 
422 //=============================================================================
423 int Ifpack_ICT::ApplyInverse(const Epetra_MultiVector& X,
424  Epetra_MultiVector& Y) const
425 {
426 
427  if (!IsComputed())
428  IFPACK_CHK_ERR(-3); // compute preconditioner first
429 
430  if (X.NumVectors() != Y.NumVectors())
431  IFPACK_CHK_ERR(-2); // Return error: X and Y not the same size
432 
433  Time_.ResetStartTime();
434 
435  // AztecOO gives X and Y pointing to the same memory location,
436  // need to create an auxiliary vector, Xcopy
437  Teuchos::RefCountPtr<const Epetra_MultiVector> Xcopy;
438  if (X.Pointers()[0] == Y.Pointers()[0])
439  Xcopy = Teuchos::rcp( new Epetra_MultiVector(X) );
440  else
441  Xcopy = Teuchos::rcp( &X, false );
442 
443  // NOTE: H_ is based on SerialMap_, while Xcopy is based
444  // on A.Map()... which are in general different. However, Solve()
445  // does not seem to care... which is fine with me.
446  //
447  EPETRA_CHK_ERR(H_->Solve(false,false,false,*Xcopy,Y));
448  EPETRA_CHK_ERR(H_->Solve(false,true,false,Y,Y));
449 
450 #ifdef IFPACK_FLOPCOUNTERS
451  // these are global flop count
452  ApplyInverseFlops_ += 4.0 * GlobalNonzeros_;
453 #endif
454 
455  ++NumApplyInverse_;
456  ApplyInverseTime_ += Time_.ElapsedTime();
457 
458  return(0);
459 }
460 //=============================================================================
461 // This function finds X such that LDU Y = X or U(trans) D L(trans) Y = X for multiple RHS
462 int Ifpack_ICT::Apply(const Epetra_MultiVector& X,
463  Epetra_MultiVector& Y) const
464 {
465 
466  IFPACK_CHK_ERR(-98);
467 }
468 
469 //=============================================================================
470 double Ifpack_ICT::Condest(const Ifpack_CondestType CT,
471  const int MaxIters, const double Tol,
472  Epetra_RowMatrix* Matrix_in)
473 {
474  if (!IsComputed()) // cannot compute right now
475  return(-1.0);
476 
477  // NOTE: this is computing the *local* condest
478  if (Condest_ == -1.0)
479  Condest_ = Ifpack_Condest(*this, CT, MaxIters, Tol, Matrix_in);
480 
481  return(Condest_);
482 }
483 
484 //=============================================================================
485 std::ostream&
486 Ifpack_ICT::Print(std::ostream& os) const
487 {
488  if (!Comm().MyPID()) {
489  os << endl;
490  os << "================================================================================" << endl;
491  os << "Ifpack_ICT: " << Label() << endl << endl;
492  os << "Level-of-fill = " << LevelOfFill() << endl;
493  os << "Absolute threshold = " << AbsoluteThreshold() << endl;
494  os << "Relative threshold = " << RelativeThreshold() << endl;
495  os << "Relax value = " << RelaxValue() << endl;
496  os << "Condition number estimate = " << Condest() << endl;
497  os << "Global number of rows = " << Matrix().NumGlobalRows() << endl;
498  if (IsComputed_) {
499  os << "Number of nonzeros of H = " << H_->NumGlobalNonzeros() << endl;
500  os << "nonzeros / rows = "
501  << 1.0 * H_->NumGlobalNonzeros() / H_->NumGlobalRows() << endl;
502  }
503  os << endl;
504  os << "Phase # calls Total Time (s) Total MFlops MFlops/s" << endl;
505  os << "----- ------- -------------- ------------ --------" << endl;
506  os << "Initialize() " << std::setw(5) << NumInitialize()
507  << " " << std::setw(15) << InitializeTime()
508  << " 0.0 0.0" << endl;
509  os << "Compute() " << std::setw(5) << NumCompute()
510  << " " << std::setw(15) << ComputeTime()
511  << " " << std::setw(15) << 1.0e-6 * ComputeFlops();
512  if (ComputeTime() != 0.0)
513  os << " " << std::setw(15) << 1.0e-6 * ComputeFlops() / ComputeTime() << endl;
514  else
515  os << " " << std::setw(15) << 0.0 << endl;
516  os << "ApplyInverse() " << std::setw(5) << NumApplyInverse()
517  << " " << std::setw(15) << ApplyInverseTime()
518  << " " << std::setw(15) << 1.0e-6 * ApplyInverseFlops();
519  if (ApplyInverseTime() != 0.0)
520  os << " " << std::setw(15) << 1.0e-6 * ApplyInverseFlops() / ApplyInverseTime() << endl;
521  else
522  os << " " << std::setw(15) << 0.0 << endl;
523  os << "================================================================================" << endl;
524  os << endl;
525  }
526 
527 
528  return(os);
529 }
double RelaxValue() const
Returns the relaxation value.
Definition: Ifpack_ICT.h:314
virtual ostream & Print(std::ostream &os) const
Prints basic information on iostream. This function is used by operator&lt;&lt;.
Definition: Ifpack_ICT.cpp:486
double LevelOfFill() const
Returns the level-of-fill.
Definition: Ifpack_ICT.h:296
const Epetra_Comm & Comm() const
Returns the Epetra_BlockMap object associated with the range of this matrix operator.
Definition: Ifpack_ICT.h:221
int SetParameters(Teuchos::ParameterList &parameterlis)
Set parameters using a Teuchos::ParameterList object.
Definition: Ifpack_ICT.cpp:104
bool IsInitialized() const
Returns true is the preconditioner has been successfully initialized.
Definition: Ifpack_ICT.h:116
int ApplyInverse(const Epetra_MultiVector &X, Epetra_MultiVector &Y) const
Returns the result of a Ifpack_ICT forward/back solve on a Epetra_MultiVector X in Y...
Definition: Ifpack_ICT.cpp:423
string Ifpack_toString(const int &x)
Convertes an integer to string.
int Initialize()
Initialize L and U with values from user matrix A.
Definition: Ifpack_ICT.cpp:136
double DropTolerance() const
Returns the drop threshold.
Definition: Ifpack_ICT.h:320
Ifpack_ICT(const Epetra_RowMatrix *A)
Ifpack_ICT constuctor with variable number of indices per row.
Definition: Ifpack_ICT.cpp:63
virtual int NumInitialize() const
Returns the number of calls to Initialize().
Definition: Ifpack_ICT.h:239
virtual int NumCompute() const
Returns the number of calls to Compute().
Definition: Ifpack_ICT.h:245
double Condest() const
Returns the computed condition number estimate, or -1.0 if not computed.
Definition: Ifpack_ICT.h:175
virtual double ComputeTime() const
Returns the time spent in Compute().
Definition: Ifpack_ICT.h:263
virtual double ApplyInverseTime() const
Returns the time spent in ApplyInverse().
Definition: Ifpack_ICT.h:269
virtual double ComputeFlops() const
Returns the number of flops in all applications of Compute().
Definition: Ifpack_ICT.h:281
bool IsComputed() const
If factor is completed, this query returns true, otherwise it returns false.
Definition: Ifpack_ICT.h:142
double RelativeThreshold() const
Returns the relative threshold.
Definition: Ifpack_ICT.h:308
const Epetra_RowMatrix & Matrix() const
Returns a reference to the matrix to be preconditioned.
Definition: Ifpack_ICT.h:110
virtual double ApplyInverseFlops() const
Returns the number of flops in all applications of ApplyInverse().
Definition: Ifpack_ICT.h:287
virtual double InitializeTime() const
Returns the time spent in Initialize().
Definition: Ifpack_ICT.h:257
int Compute()
Compute IC factor U using the specified graph, diagonal perturbation thresholds and relaxation parame...
Definition: Ifpack_ICT.cpp:158
virtual int NumApplyInverse() const
Returns the number of calls to ApplyInverse().
Definition: Ifpack_ICT.h:251
double AbsoluteThreshold() const
Returns the absolute threshold.
Definition: Ifpack_ICT.h:302
virtual ~Ifpack_ICT()
Ifpack_ICT Destructor.
Definition: Ifpack_ICT.cpp:91