IFPACK  Development
 All Classes Files Functions Variables Enumerations Friends Pages
Ifpack_SORa.cpp
1 /*
2 //@HEADER
3 // ***********************************************************************
4 //
5 // Ifpack: Object-Oriented Algebraic Preconditioner Package
6 // Copyright (2002) Sandia Corporation
7 //
8 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
9 // license for use of this work by or on behalf of the U.S. Government.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
39 //
40 // ***********************************************************************
41 //@HEADER
42 */
43 
44 #include "Ifpack_SORa.h"
45 #include "Ifpack.h"
46 #include "Ifpack_Utils.h"
47 #include "Teuchos_ParameterList.hpp"
48 #include "Teuchos_RefCountPtr.hpp"
49 #include "Epetra_Import.h"
50 #include "Epetra_Export.h"
51 #include "Epetra_IntVector.h"
52 
53 using Teuchos::RefCountPtr;
54 using Teuchos::rcp;
55 
56 
57 
58 #ifdef HAVE_IFPACK_EPETRAEXT
59 #include "EpetraExt_MatrixMatrix.h"
60 #include "EpetraExt_RowMatrixOut.h"
61 #include "EpetraExt_MultiVectorOut.h"
62 #include "EpetraExt_Transpose_RowMatrix.h"
63 
64 
65 #define ABS(x) ((x)>=0?(x):-(x))
66 #define MIN(x,y) ((x)<(y)?(x):(y))
67 #define MAX(x,y) ((x)>(y)?(x):(y))
68 
69 // Useful functions horked from ML
70 int* FindLocalDiricheltRowsFromOnesAndZeros(const Epetra_CrsMatrix & Matrix, int &numBCRows);
71 void Apply_BCsToMatrixRowsAndColumns(const int *dirichletRows, int numBCRows,const Epetra_IntVector &dirichletColumns,const Epetra_CrsMatrix & Matrix);
72 Epetra_IntVector * FindLocalDirichletColumnsFromRows(const int *dirichletRows, int numBCRows,const Epetra_CrsMatrix & Matrix);
73 
74 Ifpack_SORa::Ifpack_SORa(Epetra_RowMatrix* A):
75  IsInitialized_(false),
76  IsComputed_(false),
77  Label_(),
78  Alpha_(1.5),
79  Gamma_(1.0),
80  NumSweeps_(1),
81  IsParallel_(false),
82  HaveOAZBoundaries_(false),
83  UseInterprocDamping_(false),
84  UseGlobalDamping_(false),
85  LambdaMax_(-1.0),
86  Time_(A->Comm())
87 {
88  Epetra_CrsMatrix *Acrs=dynamic_cast<Epetra_CrsMatrix*>(A);
89  if(Acrs) Acrs_=rcp(Acrs,false);
90  A_=rcp(A,false);
91 }
92 
93 void Ifpack_SORa::Destroy(){
94 }
95 
96 
97 
98 int Ifpack_SORa::Initialize(){
99  Alpha_ = List_.get("sora: alpha", Alpha_);
100  Gamma_ = List_.get("sora: gamma",Gamma_);
101  NumSweeps_ = List_.get("sora: sweeps",NumSweeps_);
102  HaveOAZBoundaries_= List_.get("sora: oaz boundaries", HaveOAZBoundaries_);
103  UseInterprocDamping_ = List_.get("sora: use interproc damping",UseInterprocDamping_);
104  UseGlobalDamping_ = List_.get("sora: use global damping",UseGlobalDamping_);
105 
106  if (A_->Comm().NumProc() != 1) IsParallel_ = true;
107  else {
108  IsParallel_ = false;
109  // Don't use interproc damping, for obvious reasons
110  UseInterprocDamping_=false;
111  }
112 
113  // Counters
114  IsInitialized_=true;
115  NumInitialize_++;
116  return 0;
117 }
118 
119 int Ifpack_SORa::SetParameters(Teuchos::ParameterList& parameterlist){
120  List_=parameterlist;
121  return 0;
122 }
123 
124 
125 int Ifpack_SORa::Compute(){
126  if(!IsInitialized_) Initialize();
127  Epetra_Map *RowMap=const_cast<Epetra_Map*>(&A_->RowMatrixRowMap());
128  Epetra_Vector Adiag(*RowMap);
129  Epetra_CrsMatrix *Askew2=0, *Aherm2=0,*W=0;
130  int *rowptr_s,*colind_s,*rowptr_h,*colind_h;
131  double *vals_s,*vals_h;
132  bool RowMatrixMode=(Acrs_==Teuchos::null);
133 
134  // Label
135  sprintf(Label_, "IFPACK SORa (alpha=%5.2f gamma=%5.2f)",Alpha_,Gamma_);
136 
137  if(RowMatrixMode){
138  if(!A_->Comm().MyPID()) cout<<"SORa: RowMatrix mode enabled"<<endl;
139  // RowMatrix mode, build Acrs_ the hard way.
140  Epetra_RowMatrix *Arow=&*A_;
141  Epetra_Map *ColMap=const_cast<Epetra_Map*>(&A_->RowMatrixColMap());
142 
143  int Nmax=A_->MaxNumEntries();
144  int length;
145  vector<int> indices(Nmax);
146  vector<double> values(Nmax);
147  Epetra_CrsMatrix *Acrs=new Epetra_CrsMatrix(Copy,*RowMap,Nmax);
148 
149  for(int i=0;i<Arow->NumMyRows();i++){
150  Arow->ExtractMyRowCopy(i,Nmax,length,&values[0],&indices[0]);
151  for(int j=0;j<length;j++)
152  indices[j]=ColMap->GID(indices[j]);
153  Acrs->InsertGlobalValues(RowMap->GID(i),length,&values[0],&indices[0]);
154  }
155  Acrs->FillComplete(A_->OperatorDomainMap(),A_->OperatorRangeMap());
156  Acrs_=rcp(Acrs,true);
157  }
158 
159  // Create Askew2
160  // Note: Here I let EpetraExt do the thinking for me. Since it gets all the maps correct for the E + F^T stencil.
161  // There are probably more efficient ways to do this but this method has the bonus of allowing code reuse.
162  IFPACK_CHK_ERR(EpetraExt::MatrixMatrix::Add(*Acrs_,false,1,*Acrs_,true,-1,Askew2));
163  Askew2->FillComplete();
164 
165  // Create Aherm2
166  IFPACK_CHK_ERR(EpetraExt::MatrixMatrix::Add(*Acrs_,false,1,*Acrs_,true,1,Aherm2));
167  Aherm2->FillComplete();
168 
169  int nnz2=Askew2->NumMyNonzeros();
170  int N=Askew2->NumMyRows();
171 
172 
173  // Grab pointers
174  IFPACK_CHK_ERR(Askew2->ExtractCrsDataPointers(rowptr_s,colind_s,vals_s));
175  IFPACK_CHK_ERR(Aherm2->ExtractCrsDataPointers(rowptr_h,colind_h,vals_h));
176 
177  // Sanity checking: Make sure the sparsity patterns are the same
178 #define SANITY_CHECK
179 #ifdef SANITY_CHECK
180  for(int i=0;i<N;i++)
181  if(rowptr_s[i]!=rowptr_h[i]) IFPACK_CHK_ERR(-2);
182  for(int i=0;i<nnz2;i++)
183  if(colind_s[i]!=colind_h[i]) IFPACK_CHK_ERR(-3);
184 #endif
185 
186  // Dirichlet Detection & Nuking of Aherm2 and Askew2
187  // Note: Relies on Aherm2/Askew2 having identical sparsity patterns (see sanity check above)
188  if(HaveOAZBoundaries_){
189  int numBCRows;
190  int* dirRows=FindLocalDiricheltRowsFromOnesAndZeros(*Acrs_,numBCRows);
191  Epetra_IntVector* dirCols=FindLocalDirichletColumnsFromRows(dirRows,numBCRows,*Aherm2);
192  Apply_BCsToMatrixRowsAndColumns(dirRows,numBCRows,*dirCols,*Aherm2);
193  Apply_BCsToMatrixRowsAndColumns(dirRows,numBCRows,*dirCols,*Askew2);
194  delete [] dirRows;
195  delete dirCols;
196  }
197 
198  // Grab diagonal of A
199  A_->ExtractDiagonalCopy(Adiag);
200 
201  // Allocate the diagonal for W
202  Epetra_Vector *Wdiag = new Epetra_Vector(*RowMap);
203 
204  // Build the W matrix (lower triangle only)
205  // Note: Relies on EpetraExt giving me identical sparsity patterns for both Askew2 and Aherm2 (see sanity check above)
206  int maxentries=Askew2->MaxNumEntries();
207  int* gids=new int [maxentries];
208  double* newvals=new double[maxentries];
209  W=new Epetra_CrsMatrix(Copy,*RowMap,0);
210  for(int i=0;i<N;i++){
211  // Build the - (1+alpha)/2 E - (1-alpha)/2 F part of the W matrix
212  int rowgid=Acrs_->GRID(i);
213  double c_data=0.0;
214  double ipdamp=0.0;
215  int idx=0;
216 
217  for(int j=rowptr_s[i];j<rowptr_s[i+1];j++){
218  int colgid=Askew2->GCID(colind_s[j]);
219  c_data+=fabs(vals_s[j]);
220  if(rowgid>colgid){
221  // Rely on the fact that off-diagonal entries are always numbered last, dropping the entry entirely.
222  if(colind_s[j] < N) {
223  gids[idx]=colgid;
224  newvals[idx]=vals_h[j]/2 + Alpha_ * vals_s[j]/2;
225  idx++;
226  }
227  else{
228  ipdamp+=fabs(vals_h[j]/2 + Alpha_ * vals_s[j]/2);
229  }
230  }
231  }
232  if(idx>0)
233  IFPACK_CHK_ERR(W->InsertGlobalValues(rowgid,idx,newvals,gids));
234 
235  // Do the diagonal
236  double w_val= c_data*Alpha_*Gamma_/4 + Adiag[Acrs_->LRID(rowgid)];
237  if(UseInterprocDamping_) w_val+=ipdamp;
238 
239  W->InsertGlobalValues(rowgid,1,&w_val,&rowgid);
240  IFPACK_CHK_ERR(Wdiag->ReplaceGlobalValues(1,&w_val,&rowgid));
241  }
242  W->FillComplete(A_->OperatorDomainMap(),A_->OperatorRangeMap());
243  W_=rcp(W);
244  Wdiag_=rcp(Wdiag);
245 
246  // Mark as computed
247  IsComputed_=true;
248 
249  // Global damping, if wanted
250  if(UseGlobalDamping_) {
251  PowerMethod(10,LambdaMax_);
252  if(!A_->Comm().MyPID()) printf("SORa: Global damping parameter = %6.4e (lmax=%6.4e)\n",GetOmega(),LambdaMax_);
253  }
254 
255  // Cleanup
256  delete [] gids;
257  delete [] newvals;
258  delete Aherm2;
259  delete Askew2;
260  if(RowMatrixMode) {
261  Acrs_=Teuchos::null;
262  }
263 
264  // Counters
265  NumCompute_++;
266  ComputeTime_ += Time_.ElapsedTime();
267  return 0;
268 }
269 
270 
271 
272 int Ifpack_SORa::ApplyInverse(const Epetra_MultiVector& X, Epetra_MultiVector& Y) const{
273  if(!IsComputed_) return -1;
274  Time_.ResetStartTime();
275  bool initial_guess_is_zero=false;
276  int NumMyRows=W_->NumMyRows();
277  int NumVectors = X.NumVectors();
278  Epetra_MultiVector Temp(A_->RowMatrixRowMap(),NumVectors);
279 
280  double omega=GetOmega();
281 
282  // need to create an auxiliary vector, Xcopy
283  Teuchos::RefCountPtr<const Epetra_MultiVector> Xcopy;
284  if (X.Pointers()[0] == Y.Pointers()[0]){
285  Xcopy = Teuchos::rcp( new Epetra_MultiVector(X) );
286  // Since the user didn't give us anything better, our initial guess is zero.
287  Y.Scale(0.0);
288  initial_guess_is_zero=true;
289  }
290  else
291  Xcopy = Teuchos::rcp( &X, false );
292 
293  Teuchos::RefCountPtr< Epetra_MultiVector > T2;
294  // Note: Assuming that the matrix has an importer. Ifpack_PointRelaxation doesn't do this, but given that
295  // I have a CrsMatrix, I'm probably OK.
296  // Note: This is the lazy man's version sacrificing a few extra flops for avoiding if statements to determine
297  // if things are on or off processor.
298  // Note: T2 must be zero'd out
299  if (IsParallel_ && W_->Importer()) T2 = Teuchos::rcp( new Epetra_MultiVector(W_->Importer()->TargetMap(),NumVectors,true));
300  else T2 = Teuchos::rcp( new Epetra_MultiVector(A_->RowMatrixRowMap(),NumVectors,true));
301 
302  // Pointer grabs
303  int* rowptr,*colind;
304  double *values;
305  double **t_ptr,** y_ptr, ** t2_ptr, **x_ptr,*d_ptr;
306  T2->ExtractView(&t2_ptr);
307  Y.ExtractView(&y_ptr);
308  Temp.ExtractView(&t_ptr);
309  Xcopy->ExtractView(&x_ptr);
310  Wdiag_->ExtractView(&d_ptr);
311  IFPACK_CHK_ERR(W_->ExtractCrsDataPointers(rowptr,colind,values));
312 
313 
314  for(int i=0; i<NumSweeps_; i++){
315  // Calculate b-Ax
316  if(!initial_guess_is_zero || i > 0) {
317  A_->Apply(Y,Temp);
318  Temp.Update(1.0,*Xcopy,-1.0);
319  }
320  else
321  Temp.Update(1.0,*Xcopy,0.0);
322 
323  // Note: The off-processor entries of T2 never get touched (they're always zero) and the other entries are updated
324  // in this sweep before they are used, so we don't need to reset T2 to zero here.
325 
326  // Do backsolve & update
327  // x = x + W^{-1} (b - A x)
328  for(int j=0; j<NumMyRows; j++){
329  double diag=d_ptr[j];
330  for (int m=0 ; m<NumVectors; m++) {
331  double dtmp=0.0;
332  // Note: Since the diagonal is in the matrix, we need to zero that entry of T2 here to make sure it doesn't contribute.
333  t2_ptr[m][j]=0.0;
334  for(int k=rowptr[j];k<rowptr[j+1];k++){
335  dtmp+= values[k]*t2_ptr[m][colind[k]];
336  }
337  // Yes, we need to update both of these.
338  t2_ptr[m][j] = (t_ptr[m][j]- dtmp)/diag;
339  y_ptr[m][j] += omega*t2_ptr[m][j];
340  }
341  }
342  }
343 
344  // Counter update
345  NumApplyInverse_++;
346  ApplyInverseTime_ += Time_.ElapsedTime();
347  return 0;
348 }
349 
350 
351 ostream& Ifpack_SORa::Print(ostream& os) const{
352  os<<"Ifpack_SORa"<<endl;
353  os<<" alpha = "<<Alpha_<<endl;
354  os<<" gamma = "<<Gamma_<<endl;
355  os<<endl;
356  return os;
357 }
358 
359 
360 double Ifpack_SORa::Condest(const Ifpack_CondestType CT,
361  const int MaxIters,
362  const double Tol,
363  Epetra_RowMatrix* Matrix_in){
364  return -1.0;
365 }
366 
367 
368 
369 
370 
371 // ============================================================================
372 inline int* FindLocalDiricheltRowsFromOnesAndZeros(const Epetra_CrsMatrix & Matrix, int &numBCRows){
373  int *dirichletRows = new int[Matrix.NumMyRows()];
374  numBCRows = 0;
375  for (int i=0; i<Matrix.NumMyRows(); i++) {
376  int numEntries, *cols;
377  double *vals;
378  int ierr = Matrix.ExtractMyRowView(i,numEntries,vals,cols);
379  if (ierr == 0) {
380  int nz=0;
381  for (int j=0; j<numEntries; j++) if (vals[j]!=0) nz++;
382  if (nz==1) dirichletRows[numBCRows++] = i;
383  // EXPERIMENTAL: Treat Special Inflow Boundaries as Dirichlet Boundaries
384  if(nz==2) dirichletRows[numBCRows++] = i;
385  }/*end if*/
386  }/*end for*/
387  return dirichletRows;
388 }/*end FindLocalDiricheltRowsFromOnesAndZeros*/
389 
390 
391 // ======================================================================
393 inline Epetra_IntVector * FindLocalDirichletColumnsFromRows(const int *dirichletRows, int numBCRows,const Epetra_CrsMatrix & Matrix){
394  // Zero the columns corresponding to the Dirichlet rows. Completely ignore the matrix maps.
395 
396  // Build rows
397  Epetra_IntVector ZeroRows(Matrix.RowMap());
398  Epetra_IntVector *ZeroCols=new Epetra_IntVector(Matrix.ColMap());
399  ZeroRows.PutValue(0);
400  ZeroCols->PutValue(0);
401 
402  // Easy Case: We're all on one processor
403  if(Matrix.RowMap().SameAs(Matrix.ColMap())){
404  for (int i=0; i < numBCRows; i++)
405  (*ZeroCols)[dirichletRows[i]]=1;
406  return ZeroCols;
407  }
408 
409  // Flag the rows which are zero locally
410  for (int i=0; i < numBCRows; i++)
411  ZeroRows[dirichletRows[i]]=1;
412 
413  // Boundary exchange to move the data
414  if(Matrix.RowMap().SameAs(Matrix.DomainMap())){
415  // Use A's Importer if we have one
416  ZeroCols->Import(ZeroRows,*Matrix.Importer(),Insert);
417  }
418  else{
419  // Use custom importer if we don't
420  Epetra_Import Importer(Matrix.ColMap(),Matrix.RowMap());
421  ZeroCols->Import(ZeroRows,Importer,Insert);
422  }
423  return ZeroCols;
424 }
425 
426 
427 // ======================================================================
428 inline void Apply_BCsToMatrixRowsAndColumns(const int *dirichletRows, int numBCRows,const Epetra_IntVector &dirichletColumns,const Epetra_CrsMatrix & Matrix){
429  /* This function zeros out rows & columns of Matrix.
430  Comments: The graph of Matrix is unchanged.
431  */
432  // Nuke the rows
433  for(int i=0;i<numBCRows;i++){
434  int numEntries, *cols;
435  double *vals;
436  Matrix.ExtractMyRowView(dirichletRows[i],numEntries,vals,cols);
437  for (int j=0; j<numEntries; j++) vals[j]=0.0;
438  }/*end for*/
439 
440  // Nuke the columns
441  for (int i=0; i < Matrix.NumMyRows(); i++) {
442  int numEntries;
443  double *vals;
444  int *cols;
445  Matrix.ExtractMyRowView(i,numEntries,vals,cols);
446  for (int j=0; j < numEntries; j++) {
447  if (dirichletColumns[ cols[j] ] > 0) vals[j] = 0.0;
448  }/*end for*/
449  }/*end for*/
450 }/* end Apply_BCsToMatrixColumns */
451 
452 
453 
454 
455 
456 int Ifpack_SORa::
457 PowerMethod(const int MaximumIterations, double& lambda_max)
458 {
459  // this is a simple power method
460  lambda_max = 0.0;
461  double RQ_top, RQ_bottom, norm;
462  Epetra_Vector x(A_->OperatorDomainMap());
463  Epetra_Vector y(A_->OperatorRangeMap());
464  Epetra_Vector z(A_->OperatorRangeMap());
465  x.Random();
466  x.Norm2(&norm);
467  if (norm == 0.0) IFPACK_CHK_ERR(-1);
468 
469  x.Scale(1.0 / norm);
470 
471  // Only do 1 sweep per PM step, turn off global damping
472  int NumSweepsBackup=NumSweeps_;
473  bool UseGlobalDampingBackup=UseGlobalDamping_;
474  NumSweeps_=1;UseGlobalDamping_=false;
475 
476  for (int iter = 0; iter < MaximumIterations; ++iter)
477  {
478  y.PutScalar(0.0);
479  A_->Apply(x, z);
480  ApplyInverse(z,y);
481  y.Update(1.0,x,-1.0);
482 
483  // Compute the Rayleigh Quotient
484  y.Dot(x, &RQ_top);
485  x.Dot(x, &RQ_bottom);
486  lambda_max = RQ_top / RQ_bottom;
487  y.Norm2(&norm);
488  if (norm == 0.0) IFPACK_CHK_ERR(-1);
489  x.Update(1.0 / norm, y, 0.0);
490 
491  }
492 
493  // Enable if we want to prevent over-relaxation
494  // lambda_max=MAX(lambda_max,1.0);
495 
496  // Reset parameters
497  NumSweeps_=NumSweepsBackup;
498  UseGlobalDamping_=UseGlobalDampingBackup;
499 
500  return(0);
501 }
502 
503 #endif