IFPACK  Development
 All Classes Files Functions Variables Enumerations Friends Pages
Ifpack_IKLU.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_IKLU.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 using namespace Teuchos;
62 
63 //==============================================================================
64 // FIXME: allocate Comm_ and Time_ the first Initialize() call
65 Ifpack_IKLU::Ifpack_IKLU(const Epetra_RowMatrix* A) :
66  A_(*A),
67  Comm_(A->Comm()),
68  Condest_(-1.0),
69  Relax_(0.),
70  Athresh_(0.0),
71  Rthresh_(1.0),
72  LevelOfFill_(1.0),
73  DropTolerance_(1e-12),
74  IsInitialized_(false),
75  IsComputed_(false),
76  UseTranspose_(false),
77  NumMyRows_(-1),
78  NumInitialize_(0),
79  NumCompute_(0),
80  NumApplyInverse_(0),
81  InitializeTime_(0.0),
82  ComputeTime_(0.0),
83  ApplyInverseTime_(0.0),
84  ComputeFlops_(0.0),
85  ApplyInverseFlops_(0.0),
86  Time_(Comm()),
87  GlobalNonzeros_(0),
88  csrA_(0),
89  cssS_(0),
90  csrnN_(0)
91 {
92  // do nothing here..
93 }
94 
95 //==============================================================================
97 {
98  Destroy();
99 }
100 
101 //==============================================================================
102 void Ifpack_IKLU::Destroy()
103 {
104  IsInitialized_ = false;
105  IsComputed_ = false;
106  if (csrA_)
107  csr_spfree( csrA_ );
108  if (cssS_)
109  csr_sfree( cssS_ );
110  if (csrnN_)
111  csr_nfree( csrnN_ );
112 }
113 
114 //==========================================================================
115 int Ifpack_IKLU::SetParameters(Teuchos::ParameterList& List)
116 {
117  try
118  {
119  LevelOfFill_ = List.get<double>("fact: ilut level-of-fill", LevelOfFill());
120  if (LevelOfFill_ <= 0.0)
121  IFPACK_CHK_ERR(-2); // must be greater than 0.0
122 
123  Athresh_ = List.get<double>("fact: absolute threshold", Athresh_);
124  Rthresh_ = List.get<double>("fact: relative threshold", Rthresh_);
125  Relax_ = List.get<double>("fact: relax value", Relax_);
126  DropTolerance_ = List.get<double>("fact: drop tolerance", DropTolerance_);
127 
128  Label_ = "IFPACK IKLU (fill=" + Ifpack_toString(LevelOfFill())
129  + ", relax=" + Ifpack_toString(RelaxValue())
130  + ", athr=" + Ifpack_toString(AbsoluteThreshold())
131  + ", rthr=" + Ifpack_toString(RelativeThreshold())
132  + ", droptol=" + Ifpack_toString(DropTolerance())
133  + ")";
134  return(0);
135  }
136  catch (...)
137  {
138  cerr << "Caught an exception while parsing the parameter list" << endl;
139  cerr << "This typically means that a parameter was set with the" << endl;
140  cerr << "wrong type (for example, int instead of double). " << endl;
141  cerr << "please check the documentation for the type required by each parameer." << endl;
142  IFPACK_CHK_ERR(-1);
143  }
144 
145  return(0);
146 }
147 
148 //==========================================================================
150 {
151  // delete previously allocated factorization
152  Destroy();
153 
154  Time_.ResetStartTime();
155 
156  if (A_.Comm().NumProc() != 1) {
157  cout << " There are too many processors !!! " << endl;
158  cerr << "Ifpack_IKLU can be used with Comm().NumProc() == 1" << endl;
159  cerr << "only. This class is a subdomain solver for Ifpack_AdditiveSchwarz," << endl;
160  cerr << "and it is currently not meant to be used otherwise." << endl;
161  exit(EXIT_FAILURE);
162  }
163 
164  // check dimensions of input matrix only in serial
165  if (Comm().NumProc() == 1 && Matrix().NumMyRows() != Matrix().NumMyCols())
166  IFPACK_CHK_ERR(-2);
167 
168  NumMyRows_ = Matrix().NumMyRows();
169  NumMyNonzeros_ = Matrix().NumMyNonzeros();
170 
171  int RowNnz, Length = Matrix().MaxNumEntries();
172  vector<int> RowIndices(Length);
173  vector<double> RowValues(Length);
174 
175  //cout << "Processor " << Comm().MyPID() << " owns " << NumMyRows_ << " rows and has " << NumMyNonzeros_ << " nonzeros " << endl;
176  // get general symbolic structure of the matrix
177  csrA_ = csr_spalloc( NumMyRows_, NumMyRows_, NumMyNonzeros_, 1, 0 );
178 
179  // copy the symbolic structure into csrA_
180  int count = 0;
181  csrA_->p[0] = 0;
182  for (int i = 0; i < NumMyRows_; ++i ) {
183 
184  IFPACK_CHK_ERR(A_.ExtractMyRowCopy(i,Length,RowNnz,
185  &RowValues[0],&RowIndices[0]));
186  for (int j = 0 ; j < RowNnz ; ++j) {
187  csrA_->j[count++] = RowIndices[j];
188  //cout << "Row = " << i << ", Column = " << RowIndices[j] << ", Value = " << RowValues[j] << endl;
189  }
190  csrA_->p[i+1] = csrA_->p[i] + RowNnz;
191  }
192 
193  // Perform symbolic analysis on the current matrix structure
194  int order = 1;
195  cssS_ = csr_sqr( order, csrA_ );
196  for (int i = 0; i < NumMyRows_; ++i ) {
197  cout << "AMD Perm (from inside KLU) [" << i << "] = " << cssS_->q[i] << endl;
198  }
199 
200  // nothing else to do here
201  IsInitialized_ = true;
202  ++NumInitialize_;
203  InitializeTime_ += Time_.ElapsedTime();
204 
205  return(0);
206 }
207 
208 //==========================================================================
210 {
211  public:
212  inline bool operator()(const double& x, const double& y)
213  {
214  return(IFPACK_ABS(x) > IFPACK_ABS(y));
215  }
216 };
217 
218 //==========================================================================
219 
221 {
222  if (!IsInitialized())
223  IFPACK_CHK_ERR(Initialize());
224 
225  Time_.ResetStartTime();
226  IsComputed_ = false;
227 
228  NumMyRows_ = A_.NumMyRows();
229  int Length = A_.MaxNumEntries();
230 
231  bool distributed = (Comm().NumProc() > 1)?true:false;
232  if (distributed)
233  {
234  SerialComm_ = rcp(new Epetra_SerialComm);
235  SerialMap_ = rcp(new Epetra_Map(NumMyRows_, 0, *SerialComm_));
236  assert (SerialComm_.get() != 0);
237  assert (SerialMap_.get() != 0);
238  }
239  else
240  SerialMap_ = rcp(const_cast<Epetra_Map*>(&A_.RowMatrixRowMap()), false);
241 
242  int RowNnz;
243  vector<int> RowIndices(Length);
244  vector<double> RowValues(Length);
245 
246  // copy the values from A_ into csrA_
247  int count = 0;
248  for (int i = 0; i < NumMyRows_; ++i ) {
249 
250  IFPACK_CHK_ERR(A_.ExtractMyRowCopy(i,Length,RowNnz,
251  &RowValues[0],&RowIndices[0]));
252  // make sure each row has the same number of nonzeros
253  if (RowNnz != (csrA_->p[i+1]-csrA_->p[i])) {
254  cout << "The number of nonzeros for this row does not math the expected number of nonzeros!!!" << endl;
255  }
256  for (int j = 0 ; j < RowNnz ; ++j) {
257 
258  csrA_->x[count++] = RowValues[j];
259  //cout << "Row = " << i << ", Column = " << RowIndices[j] << ", Value = " << RowValues[j] << endl;
260  }
261  }
262 
263  // compute the lu factors
264  double tol = 0.1;
265  csrnN_ = csr_lu( &*csrA_, &*cssS_, tol );
266 
267  // Create L and U as a view of the information stored in csrnN_->L and csrnN_->U
268  csr* L_tmp = csrnN_->L;
269  csr* U_tmp = csrnN_->U;
270  vector<int> numEntriesL( NumMyRows_ ), numEntriesU( NumMyRows_ );
271  for (int i=0; i < NumMyRows_; ++i) {
272  numEntriesL[i] = ( L_tmp->p[i+1] - L_tmp->p[i] );
273  numEntriesU[i] = ( U_tmp->p[i+1] - U_tmp->p[i] );
274  }
275  L_ = rcp(new Epetra_CrsMatrix(View, *SerialMap_, &numEntriesL[0]));
276  U_ = rcp(new Epetra_CrsMatrix(View, *SerialMap_, &numEntriesU[0]));
277 
278  // Insert the values into L and U
279  for (int i=0; i < NumMyRows_; ++i) {
280  L_->InsertGlobalValues( i, numEntriesL[i], &(L_tmp->x[L_tmp->p[i]]), &(L_tmp->j[L_tmp->p[i]]) );
281  U_->InsertGlobalValues( i, numEntriesU[i], &(U_tmp->x[U_tmp->p[i]]), &(U_tmp->j[U_tmp->p[i]]) );
282  }
283 
284  IFPACK_CHK_ERR(L_->FillComplete());
285  IFPACK_CHK_ERR(U_->FillComplete());
286 
287  int MyNonzeros = L_->NumGlobalNonzeros() + U_->NumGlobalNonzeros();
288  Comm().SumAll(&MyNonzeros, &GlobalNonzeros_, 1);
289 
290  IsComputed_ = true;
291 
292  ++NumCompute_;
293  ComputeTime_ += Time_.ElapsedTime();
294 
295  return(0);
296 
297 }
298 
299 //=============================================================================
300 int Ifpack_IKLU::ApplyInverse(const Epetra_MultiVector& X,
301  Epetra_MultiVector& Y) const
302 {
303  if (!IsComputed())
304  IFPACK_CHK_ERR(-2); // compute preconditioner first
305 
306  if (X.NumVectors() != Y.NumVectors())
307  IFPACK_CHK_ERR(-3); // Return error: X and Y not the same size
308 
309  Time_.ResetStartTime();
310 
311  // NOTE: L_ and U_ are based on SerialMap_, while Xcopy is based
312  // on A.Map()... which are in general different. However, Solve()
313  // does not seem to care... which is fine with me.
314  //
315  // AztecOO gives X and Y pointing to the same memory location,
316  // need to create an auxiliary vector, Xcopy and apply permutation.
317  vector<int> invq( NumMyRows_ );
318 
319  for (int i=0; i<NumMyRows_; ++i ) {
320  csrnN_->perm[ csrnN_->pinv[i] ] = i;
321  invq[ cssS_->q[i] ] = i;
322  }
323 
324  Teuchos::RefCountPtr<Epetra_MultiVector> Xcopy = Teuchos::rcp( new Epetra_MultiVector(X.Map(),X.NumVectors()), false );
325  Teuchos::RefCountPtr<Epetra_MultiVector> Ytemp = Teuchos::rcp( new Epetra_MultiVector(Y.Map(),Y.NumVectors()) );
326 
327  for (int i=0; i<NumMyRows_; ++i) {
328  for (int j=0; j<X.NumVectors(); ++j) {
329  Xcopy->ReplaceMyValue( invq[i], j, (*X(j))[i] );
330  }
331  }
332 
333  if (!UseTranspose_)
334  {
335  // solves LU Y = X
336  IFPACK_CHK_ERR(L_->Solve(false,false,false,*Xcopy,*Ytemp));
337  IFPACK_CHK_ERR(U_->Solve(true,false,false,*Ytemp,*Ytemp));
338  }
339  else
340  {
341  // solves U(trans) L(trans) Y = X
342  IFPACK_CHK_ERR(U_->Solve(true,true,false,*Xcopy,*Ytemp));
343  IFPACK_CHK_ERR(L_->Solve(false,true,false,*Ytemp,*Ytemp));
344  }
345 
346  // Reverse the permutation.
347  for (int i=0; i<NumMyRows_; ++i) {
348  for (int j=0; j<Y.NumVectors(); ++j) {
349  Y.ReplaceMyValue( csrnN_->perm[i], j, (*(*Ytemp)(j))[i] );
350  }
351  }
352 
353  ++NumApplyInverse_;
354 #ifdef IFPACK_FLOPCOUNTERS
355  ApplyInverseFlops_ += X.NumVectors() * 2 * GlobalNonzeros_;
356 #endif
357  ApplyInverseTime_ += Time_.ElapsedTime();
358 
359  return(0);
360 
361 }
362 //=============================================================================
363 // This function finds X such that LDU Y = X or U(trans) D L(trans) Y = X for multiple RHS
364 int Ifpack_IKLU::Apply(const Epetra_MultiVector& X,
365  Epetra_MultiVector& Y) const
366 {
367 
368  return(-98);
369 }
370 
371 //=============================================================================
372 double Ifpack_IKLU::Condest(const Ifpack_CondestType CT,
373  const int MaxIters, const double Tol,
374  Epetra_RowMatrix* Matrix_in)
375 {
376  if (!IsComputed()) // cannot compute right now
377  return(-1.0);
378 
379  // NOTE: this is computing the *local* condest
380  if (Condest_ == -1.0)
381  Condest_ = Ifpack_Condest(*this, CT, MaxIters, Tol, Matrix_in);
382 
383  return(Condest_);
384 }
385 
386 //=============================================================================
387 std::ostream&
388 Ifpack_IKLU::Print(std::ostream& os) const
389 {
390  if (!Comm().MyPID()) {
391  os << endl;
392  os << "================================================================================" << endl;
393  os << "Ifpack_IKLU: " << Label() << endl << endl;
394  os << "Level-of-fill = " << LevelOfFill() << endl;
395  os << "Absolute threshold = " << AbsoluteThreshold() << endl;
396  os << "Relative threshold = " << RelativeThreshold() << endl;
397  os << "Relax value = " << RelaxValue() << endl;
398  os << "Condition number estimate = " << Condest() << endl;
399  os << "Global number of rows = " << A_.NumGlobalRows() << endl;
400  if (IsComputed_) {
401  os << "Number of nonzeros in A = " << A_.NumGlobalNonzeros() << endl;
402  os << "Number of nonzeros in L + U = " << NumGlobalNonzeros()
403  << " ( = " << 100.0 * NumGlobalNonzeros() / A_.NumGlobalNonzeros()
404  << " % of A)" << endl;
405  os << "nonzeros / rows = "
406  << 1.0 * NumGlobalNonzeros() / U_->NumGlobalRows() << endl;
407  }
408  os << endl;
409  os << "Phase # calls Total Time (s) Total MFlops MFlops/s" << endl;
410  os << "----- ------- -------------- ------------ --------" << endl;
411  os << "Initialize() " << std::setw(5) << NumInitialize()
412  << " " << std::setw(15) << InitializeTime()
413  << " 0.0 0.0" << endl;
414  os << "Compute() " << std::setw(5) << NumCompute()
415  << " " << std::setw(15) << ComputeTime()
416  << " " << std::setw(15) << 1.0e-6 * ComputeFlops();
417  if (ComputeTime() != 0.0)
418  os << " " << std::setw(15) << 1.0e-6 * ComputeFlops() / ComputeTime() << endl;
419  else
420  os << " " << std::setw(15) << 0.0 << endl;
421  os << "ApplyInverse() " << std::setw(5) << NumApplyInverse()
422  << " " << std::setw(15) << ApplyInverseTime()
423  << " " << std::setw(15) << 1.0e-6 * ApplyInverseFlops();
424  if (ApplyInverseTime() != 0.0)
425  os << " " << std::setw(15) << 1.0e-6 * ApplyInverseFlops() / ApplyInverseTime() << endl;
426  else
427  os << " " << std::setw(15) << 0.0 << endl;
428  os << "================================================================================" << endl;
429  os << endl;
430  }
431 
432  return(os);
433 }
Ifpack_IKLU(const Epetra_RowMatrix *A)
Ifpack_IKLU constuctor with variable number of indices per row.
Definition: Ifpack_IKLU.cpp:65
const Epetra_RowMatrix & Matrix() const
Returns a reference to the matrix to be preconditioned.
Definition: Ifpack_IKLU.h:188
virtual ostream & Print(std::ostream &os) const
Prints basic information on iostream. This function is used by operator&lt;&lt;.
int SetParameters(Teuchos::ParameterList &parameterlis)
Set parameters using a Teuchos::ParameterList object.
virtual int NumApplyInverse() const
Returns the number of calls to ApplyInverse().
Definition: Ifpack_IKLU.h:228
string Ifpack_toString(const int &x)
Convertes an integer to string.
virtual double InitializeTime() const
Returns the time spent in Initialize().
Definition: Ifpack_IKLU.h:234
int NumGlobalNonzeros() const
Returns the number of nonzero entries in the global graph.
Definition: Ifpack_IKLU.h:295
virtual double ComputeTime() const
Returns the time spent in Compute().
Definition: Ifpack_IKLU.h:240
virtual double ApplyInverseFlops() const
Returns the number of flops in the application of the preconditioner.
Definition: Ifpack_IKLU.h:262
const char * Label() const
Returns the label of this object.
Definition: Ifpack_IKLU.h:200
bool IsInitialized() const
Returns true if the preconditioner has been successfully initialized.
Definition: Ifpack_IKLU.h:111
virtual double ApplyInverseTime() const
Returns the time spent in ApplyInverse().
Definition: Ifpack_IKLU.h:246
bool IsComputed() const
If factor is completed, this query returns true, otherwise it returns false.
Definition: Ifpack_IKLU.h:128
virtual int NumCompute() const
Returns the number of calls to Compute().
Definition: Ifpack_IKLU.h:222
virtual ~Ifpack_IKLU()
Ifpack_IKLU Destructor.
Definition: Ifpack_IKLU.cpp:96
double DropTolerance() const
Gets the dropping tolerance.
Definition: Ifpack_IKLU.h:289
int ApplyInverse(const Epetra_MultiVector &X, Epetra_MultiVector &Y) const
Returns the result of a Ifpack_IKLU forward/back solve on a Epetra_MultiVector X in Y...
double RelativeThreshold() const
Get relative threshold value.
Definition: Ifpack_IKLU.h:283
double RelaxValue() const
Set relative threshold value.
Definition: Ifpack_IKLU.h:272
const Epetra_Comm & Comm() const
Returns the Epetra_BlockMap object associated with the range of this matrix operator.
Definition: Ifpack_IKLU.h:185
virtual int NumInitialize() const
Returns the number of calls to Initialize().
Definition: Ifpack_IKLU.h:216
double AbsoluteThreshold() const
Get absolute threshold value.
Definition: Ifpack_IKLU.h:277
int Initialize()
Initialize L and U with values from user matrix A.
double Condest() const
Returns the computed estimated condition number, or -1.0 if no computed.
Definition: Ifpack_IKLU.h:152
int Compute()
Compute IC factor U using the specified graph, diagonal perturbation thresholds and relaxation parame...
virtual double ComputeFlops() const
Returns the number of flops in the computation phase.
Definition: Ifpack_IKLU.h:257