EpetraExt  Development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
EpetraExt_CrsSingletonFilter_LinearProblem.cpp
Go to the documentation of this file.
1 
2 //@HEADER
3 // ***********************************************************************
4 //
5 // EpetraExt: Epetra Extended - Linear Algebra Services Package
6 // Copyright (2011) Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
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 #include "Epetra_Map.h"
44 #include "Epetra_Util.h"
45 #include "Epetra_Export.h"
46 #include "Epetra_Import.h"
47 #include "Epetra_MultiVector.h"
48 #include "Epetra_Vector.h"
49 #include "Epetra_IntVector.h"
50 #include "Epetra_Comm.h"
51 #include "Epetra_LinearProblem.h"
52 #include "Epetra_MapColoring.h"
54 
55 namespace EpetraExt {
56 
57 //==============================================================================
60 : verbose_(verbose)
61 {
63 }
64 //==============================================================================
67 {
68  if (ReducedLHS_!=0) delete ReducedLHS_;
69  if (ReducedRHS_!=0) delete ReducedRHS_;
79  if (RowMapColors_!=0) delete RowMapColors_;
80  if (ColMapColors_!=0) delete ColMapColors_;
81 
82  if (ColSingletonRowLIDs_ != 0) delete [] ColSingletonRowLIDs_;
83  if (ColSingletonColLIDs_ != 0) delete [] ColSingletonColLIDs_;
85  if (ColSingletonPivots_ != 0) delete [] ColSingletonPivots_;
86  if (tempExportX_ != 0) delete tempExportX_;
87  if (Indices_ != 0) delete [] Indices_;
88  if (tempX_ != 0) delete tempX_;
89  if (tempB_ != 0) delete tempB_;
90 
91 }
92 
93 //==============================================================================
97 {
98  analyze( orig );
99  return construct();
100 }
101 
102 //==============================================================================
103 bool
106 {
107  origObj_ = &orig;
108 
109  FullMatrix_ = orig.GetMatrix();
110 
111  int flag = Analyze( FullMatrix_ );
112  assert( flag >= 0 );
113 
114  if ( verbose_ && FullMatrix_->Comm().MyPID()==0 ) {
115  cout << "\nAnalyzed Singleton Problem:\n";
116  cout << "---------------------------\n";
117  }
118  if ( SingletonsDetected() ) {
119  if ( verbose_ && FullMatrix_->Comm().MyPID()==0 ) {
120  cout << "Singletons Detected!" << endl;;
121  cout << "Num Singletons: " << NumSingletons() << endl;
122  }
123  }
124  else {
125  if ( verbose_ && FullMatrix_->Comm().MyPID()==0 )
126  cout << "No Singletons Detected!" << endl;
127  }
128 /*
129  cout << "List of Row Singletons:\n";
130  int * slist = RowMapColors_->ColorLIDList(1);
131  for( int i = 0; i < RowMapColors_->NumElementsWithColor(1); ++i )
132  cout << slist[i] << " ";
133  cout << "\n";
134  cout << "List of Col Singletons:\n";
135  slist = ColMapColors_->ColorLIDList(1);
136  for( int i = 0; i < ColMapColors_->NumElementsWithColor(1); ++i )
137  cout << slist[i] << " ";
138  cout << "\n";
139 */
140  if ( verbose_ && FullMatrix_->Comm().MyPID()==0 )
141  cout << "---------------------------\n\n";
142 
143  return true;
144 }
145 
146 //==============================================================================
150 {
151  if( !origObj_ ) abort();
152 
153  int flag = ConstructReducedProblem( origObj_ );
154  assert( flag >= 0 );
155 
157 
158  if( verbose_ && SingletonsDetected() && FullMatrix_->Comm().MyPID()==0 )
159  {
160  cout << "\nConstructedSingleton Problem:\n";
161  cout << "---------------------------\n";
162  cout << "RatioOfDimensions: " << RatioOfDimensions() << endl;
163  cout << "RatioOfNonzeros: " << RatioOfNonzeros() << endl;
164  cout << "---------------------------\n\n";
165  }
166 
167  return *newObj_;
168 }
169 
170 //==============================================================================
172 {
173  int ierr = UpdateReducedProblem( FullProblem_ );
174  if( ierr ) cout << "EDT_LinearProblem_CrsSingletonFilter::UpdateReducedProblem FAILED!\n";
175 
176  return (ierr==0);
177 }
178 
179 //==============================================================================
181 {
182  int ierr = ComputeFullSolution();
183  if( ierr ) cout << "EDT_LinearProblem_CrsSingletonFilter::ComputeFullSolution FAILED!\n";
184 
185  return (ierr==0);
186 }
187 
188 //==============================================================================
190 
191 // Initialize all attributes that have trivial default values
192 
193  FullProblem_ = 0;
194  FullMatrix_ = 0;
195  ReducedRHS_ = 0;
196  ReducedLHS_ = 0;
205 
210 
211  AbsoluteThreshold_ = 0;
212  RelativeThreshold_ = 0;
213 
214  NumMyRowSingletons_ = -1;
215  NumMyColSingletons_ = -1;
218  RatioOfDimensions_ = -1.0;
219  RatioOfNonzeros_ = -1.0;
220 
221  HaveReducedProblem_ = false;
223  AnalysisDone_ = false;
224  SymmetricElimination_ = true;
225 
226  tempExportX_ = 0;
227  tempX_ = 0;
228  tempB_ = 0;
229 
230  Indices_ = 0;
231 
232  RowMapColors_ = 0;
233  ColMapColors_ = 0;
234 
235  FullMatrixIsCrsMatrix_ = false;
236  MaxNumMyEntries_ = 0;
237  return;
238 }
239 //==============================================================================
240 int LinearProblem_CrsSingletonFilter::Analyze(Epetra_RowMatrix * FullMatrix) {
241 
242  int i, j, jj;
243 
245 
246  if (AnalysisDone_) EPETRA_CHK_ERR(-1); // Analysis already done once. Cannot do it again
247  if (FullMatrix==0) EPETRA_CHK_ERR(-2); // Input matrix pointer is zero
248  if (FullMatrix->NumGlobalRows()==0) EPETRA_CHK_ERR(-3); // Full matrix has zero dimension.
249  if (FullMatrix->NumGlobalNonzeros()==0) EPETRA_CHK_ERR(-4); // Full matrix has no nonzero terms.
250 
251  // First check for columns with single entries and find columns with singleton rows
252  Epetra_IntVector ColProfiles(FullMatrixColMap()); ColProfiles.PutValue(0);
253  Epetra_IntVector ColHasRowWithSingleton(FullMatrixColMap()); ColHasRowWithSingleton.PutValue(0);
254 
255  // RowIDs[j] will contain the local row ID associated with the jth column,
256  // if the jth col has a single entry
257  Epetra_IntVector RowIDs(FullMatrixColMap()); RowIDs.PutValue(-1);
258 
259  // Define MapColoring objects
260  RowMapColors_ = new Epetra_MapColoring(FullMatrixRowMap()); // Initial colors are all 0
261  ColMapColors_ = new Epetra_MapColoring(FullMatrixColMap());
262  Epetra_MapColoring & RowMapColors = *RowMapColors_;
263  Epetra_MapColoring & ColMapColors = *ColMapColors_;
264 
265  int NumMyRows = FullMatrix->NumMyRows();
266  int NumMyCols = FullMatrix->NumMyCols();
267 
268  // Set up for accessing full matrix. Will do so row-by-row.
269  EPETRA_CHK_ERR(InitFullMatrixAccess());
270 
271  // Scan matrix for singleton rows, build up column profiles
272  int NumIndices;
273  int * Indices;
275  for (i=0; i<NumMyRows; i++) {
276  // Get ith row
277  EPETRA_CHK_ERR(GetRow(i, NumIndices, Indices));
278  for (j=0; j<NumIndices; j++) {
279  int ColumnIndex = Indices[j];
280  ColProfiles[ColumnIndex]++; // Increment column count
281  // Record local row ID for current column
282  // will use to identify row to eliminate if column is a singleton
283  RowIDs[ColumnIndex] = i;
284  }
285  // If row has single entry, color it and associated column with color=1
286  if (NumIndices==1) {
287  int j = Indices[0];
288  ColHasRowWithSingleton[j]++;
289  RowMapColors[i] = 1;
290  ColMapColors[j] = 1;
292  }
293  }
294 
295  // 1) The vector ColProfiles has column nonzero counts for each processor's contribution
296  // Combine these to get total column profile information and then redistribute to processors
297  // so each can determine if it is the owner of the row associated with the singleton column
298  // 2) The vector ColHasRowWithSingleton[i] contain count of singleton rows that are associated with
299  // the ith column on this processor. Must tell other processors that they should also eliminate
300  // these columns.
301 
302  // Make a copy of ColProfiles for later use when detecting columns that disappear locally
303 
304  Epetra_IntVector NewColProfiles(ColProfiles);
305 
306  // If RowMatrixImporter is non-trivial, we need to perform a gather/scatter to accumulate results
307 
308  if (FullMatrix->RowMatrixImporter()!=0) {
309  Epetra_IntVector tmpVec(FullMatrixDomainMap()); // Use for gather/scatter of column vectors
310  EPETRA_CHK_ERR(tmpVec.PutValue(0));
311  EPETRA_CHK_ERR(tmpVec.Export(ColProfiles, *FullMatrix->RowMatrixImporter(), Add));
312  EPETRA_CHK_ERR(ColProfiles.Import(tmpVec, *FullMatrix->RowMatrixImporter(), Insert));
313 
314  EPETRA_CHK_ERR(tmpVec.PutValue(0));
315  EPETRA_CHK_ERR(tmpVec.Export(ColHasRowWithSingleton, *FullMatrix->RowMatrixImporter(), Add));
316  EPETRA_CHK_ERR(ColHasRowWithSingleton.Import(tmpVec, *FullMatrix->RowMatrixImporter(), Insert));
317  }
318  // ColProfiles now contains the nonzero column entry count for all columns that have
319  // an entry on this processor.
320  // ColHasRowWithSingleton now contains a count of singleton rows associated with the corresponding
321  // local column. Next we check to make sure no column is associated with more than one singleton row.
322 
323  if (ColHasRowWithSingleton.MaxValue()>1) {
324  EPETRA_CHK_ERR(-2); // At least one col is associated with two singleton rows, can't handle it.
325  }
326 
327  Epetra_IntVector RowHasColWithSingleton(FullMatrix->RowMatrixRowMap()); // Use to check for errors
328  RowHasColWithSingleton.PutValue(0);
329 
331  // Count singleton columns (that were not already counted as singleton rows)
332  for (j=0; j<NumMyCols; j++) {
333  int i = RowIDs[j];
334  // Check if column is a singleton
335  if (ColProfiles[j]==1 ) {
336  // Check to make sure RowID is not invalid
337 // assert(i!=-1);
338  // Check to see if this column already eliminated by the row check above
339  if (RowMapColors[i]!=1) {
340  RowHasColWithSingleton[i]++; // Increment col singleton counter for ith row
341  RowMapColors[i] = 2; // Use 2 for now, to distinguish between row eliminated directly or via column singletons
342  ColMapColors[j] = 1;
344  // If we delete a row, we need to keep track of associated column entries that were also deleted
345  // in case all entries in a column are eventually deleted, in which case the column should
346  // also be deleted.
347  EPETRA_CHK_ERR(GetRow(i, NumIndices, Indices));
348  for (jj=0; jj<NumIndices; jj++) NewColProfiles[Indices[jj]]--;
349 
350  }
351  }
352  // Check if some other processor eliminated this column
353  else if (ColHasRowWithSingleton[j]==1 && RowMapColors[i]!=1) {
354  ColMapColors[j] = 1;
355  }
356  }
357  if (RowHasColWithSingleton.MaxValue()>1) {
358  EPETRA_CHK_ERR(-3); // At lease one row is associated with two singleton cols, can't handle it.
359  }
360 
361  // Generate arrays that keep track of column singleton row, col and pivot info needed for post-solve phase
362  EPETRA_CHK_ERR(CreatePostSolveArrays(RowIDs, RowMapColors, ColProfiles, NewColProfiles,
363  ColHasRowWithSingleton));
364 
365  for (i=0; i<NumMyRows; i++) if (RowMapColors[i]==2) RowMapColors[i] = 1; // Convert all eliminated rows to same color
366 
367  FullMatrix->RowMatrixRowMap().Comm().SumAll(&NumMyRowSingletons_, &NumGlobalRowSingletons_, 1);
368  FullMatrix->RowMatrixRowMap().Comm().SumAll(&NumMyColSingletons_, &NumGlobalColSingletons_, 1);
369  AnalysisDone_ = true;
370  return(0);
371 }
372 //==============================================================================
374 
375  int i, j;
376  if (HaveReducedProblem_) EPETRA_CHK_ERR(-1); // Setup already done once. Cannot do it again
377  if (Problem==0) EPETRA_CHK_ERR(-2); // Null problem pointer
378 
379  FullProblem_ = Problem;
380  FullMatrix_ = dynamic_cast<Epetra_RowMatrix *>(Problem->GetMatrix());
381  if (FullMatrix_==0) EPETRA_CHK_ERR(-3); // Need a RowMatrix
382  if (Problem->GetRHS()==0) EPETRA_CHK_ERR(-4); // Need a RHS
383  if (Problem->GetLHS()==0) EPETRA_CHK_ERR(-5); // Need a LHS
384  // Generate reduced row and column maps
385 
386  if ( SingletonsDetected() ) {
387 
388  Epetra_MapColoring & RowMapColors = *RowMapColors_;
389  Epetra_MapColoring & ColMapColors = *ColMapColors_;
390 
391  ReducedMatrixRowMap_ = RowMapColors.GenerateMap(0);
392  ReducedMatrixColMap_ = ColMapColors.GenerateMap(0);
393 
394  // Create domain and range map colorings by exporting map coloring of column and row maps
395 
396  if (FullMatrix()->RowMatrixImporter()!=0) {
397  Epetra_MapColoring DomainMapColors(FullMatrixDomainMap());
398  EPETRA_CHK_ERR(DomainMapColors.Export(*ColMapColors_, *FullMatrix()->RowMatrixImporter(), AbsMax));
399  OrigReducedMatrixDomainMap_ = DomainMapColors.GenerateMap(0);
400  }
401  else
403 
405  if (FullCrsMatrix()->Exporter()!=0) { // Non-trivial exporter
406  Epetra_MapColoring RangeMapColors(FullMatrixRangeMap());
407  EPETRA_CHK_ERR(RangeMapColors.Export(*RowMapColors_, *FullCrsMatrix()->Exporter(),
408  AbsMax));
409  ReducedMatrixRangeMap_ = RangeMapColors.GenerateMap(0);
410  }
411  else
413  }
414  else
416 
417  // Check to see if the reduced system domain and range maps are the same.
418  // If not, we need to remap entries of the LHS multivector so that they are distributed
419  // conformally with the rows of the reduced matrix and the RHS multivector
421  if (!SymmetricElimination_)
424  else {
428  }
429 
430  // Create pointer to Full RHS, LHS
431  Epetra_MultiVector * FullRHS = FullProblem()->GetRHS();
432  Epetra_MultiVector * FullLHS = FullProblem()->GetLHS();
433  int NumVectors = FullLHS->NumVectors();
434 
435  // Create importers
437  Full2ReducedRHSImporter_ = new Epetra_Import(*ReducedMatrixRowMap(), FullRHS->Map());
438 
439  // Construct Reduced Matrix
440  ReducedMatrix_ = Teuchos::rcp( new Epetra_CrsMatrix(Copy, *ReducedMatrixRowMap(), *ReducedMatrixColMap(), 0) );
441 
442  // Create storage for temporary X values due to explicit elimination of rows
443  tempExportX_ = new Epetra_MultiVector(FullMatrixColMap(), NumVectors);
444 
445  int NumEntries;
446  int * Indices;
447  double * Values;
448  int NumMyRows = FullMatrix()->NumMyRows();
449  int ColSingletonCounter = 0;
450  for (i=0; i<NumMyRows; i++) {
451  int curGRID = FullMatrixRowMap().GID(i);
452  if (ReducedMatrixRowMap()->MyGID(curGRID)) { // Check if this row should go into reduced matrix
453 
454  EPETRA_CHK_ERR(GetRowGCIDs(i, NumEntries, Values, Indices)); // Get current row (Indices are global)
455 
456  int ierr = ReducedMatrix()->InsertGlobalValues(curGRID, NumEntries,
457  Values, Indices); // Insert into reduce matrix
458  // Positive errors will occur because we are submitting col entries that are not part of
459  // reduced system. However, because we specified a column map to the ReducedMatrix constructor
460  // these extra column entries will be ignored and we will be politely reminded by a positive
461  // error code
462  if (ierr<0) EPETRA_CHK_ERR(ierr);
463  }
464  else {
465  EPETRA_CHK_ERR(GetRow(i, NumEntries, Values, Indices)); // Get current row
466  if (NumEntries==1) {
467  double pivot = Values[0];
468  if (pivot==0.0) EPETRA_CHK_ERR(-1); // Encountered zero row, unable to continue
469  int indX = Indices[0];
470  for (j=0; j<NumVectors; j++)
471  (*tempExportX_)[j][indX] = (*FullRHS)[j][i]/pivot;
472  }
473  // Otherwise, this is a singleton column and we will scan for the pivot element needed
474  // for post-solve equations
475  else {
476  int targetCol = ColSingletonColLIDs_[ColSingletonCounter];
477  for (j=0; j<NumEntries; j++) {
478  if (Indices[j]==targetCol) {
479  double pivot = Values[j];
480  if (pivot==0.0) EPETRA_CHK_ERR(-2); // Encountered zero column, unable to continue
481  ColSingletonPivotLIDs_[ColSingletonCounter] = j; // Save for later use
482  ColSingletonPivots_[ColSingletonCounter] = pivot;
483  ColSingletonCounter++;
484  break;
485  }
486  }
487  }
488  }
489  }
490 
491  // Now convert to local indexing. We have constructed things so that the domain and range of the
492  // matrix will have the same map. If the reduced matrix domain and range maps were not the same, the
493  // differences were addressed in the ConstructRedistributeExporter() method
494  EPETRA_CHK_ERR(ReducedMatrix()->FillComplete(*ReducedMatrixDomainMap(), *ReducedMatrixRangeMap()));
495 
496  // 1) The vector ColProfiles has column nonzero counts for each processor's contribution
497  // Construct Reduced LHS (Puts any initial guess values into reduced system)
498 
499  ReducedLHS_ = new Epetra_MultiVector(*ReducedMatrixDomainMap(), NumVectors);
500  EPETRA_CHK_ERR(ReducedLHS_->Import(*FullLHS, *Full2ReducedLHSImporter_, Insert));
501  FullLHS->PutScalar(0.0); // zero out Full LHS since we will inject values as we get them
502 
503  // Construct Reduced RHS
504 
505  // First compute influence of already-known values of X on RHS
506  tempX_ = new Epetra_MultiVector(FullMatrixDomainMap(), NumVectors);
507  tempB_ = new Epetra_MultiVector(FullRHS->Map(), NumVectors);
508 
509  //Inject known X values into tempX for purpose of computing tempB = FullMatrix*tempX
510  // Also inject into full X since we already know the solution
511 
512  if (FullMatrix()->RowMatrixImporter()!=0) {
513  EPETRA_CHK_ERR(tempX_->Export(*tempExportX_, *FullMatrix()->RowMatrixImporter(), Add));
514  EPETRA_CHK_ERR(FullLHS->Export(*tempExportX_, *FullMatrix()->RowMatrixImporter(), Add));
515  }
516  else {
517  tempX_->Update(1.0, *tempExportX_, 0.0);
518  FullLHS->Update(1.0, *tempExportX_, 0.0);
519  }
520 
521  EPETRA_CHK_ERR(FullMatrix()->Multiply(false, *tempX_, *tempB_));
522 
523  EPETRA_CHK_ERR(tempB_->Update(1.0, *FullRHS, -1.0)); // tempB now has influence of already-known X values
524 
525  ReducedRHS_ = new Epetra_MultiVector(*ReducedMatrixRowMap(), FullRHS->NumVectors());
526  EPETRA_CHK_ERR(ReducedRHS_->Import(*tempB_, *Full2ReducedRHSImporter_, Insert));
527 
528  // Finally construct Reduced Linear Problem
529  ReducedProblem_ = Teuchos::rcp( new Epetra_LinearProblem(ReducedMatrix_.get(), ReducedLHS_, ReducedRHS_) );
530  }
531  else {
532 
533  // There are no singletons, so don't bother building a reduced problem.
534  ReducedProblem_ = Teuchos::rcp( Problem, false );
535  ReducedMatrix_ = Teuchos::rcp( dynamic_cast<Epetra_CrsMatrix *>(Problem->GetMatrix()), false );
536  }
537 
538  double fn = FullMatrix()->NumGlobalRows();
539  double fnnz = FullMatrix()->NumGlobalNonzeros();
540  double rn = ReducedMatrix()->NumGlobalRows();
541  double rnnz = ReducedMatrix()->NumGlobalNonzeros();
542 
543  RatioOfDimensions_ = rn/fn;
544  RatioOfNonzeros_ = rnnz/fnnz;
545  HaveReducedProblem_ = true;
546 
547  return(0);
548 }
549 //==============================================================================
550 int LinearProblem_CrsSingletonFilter::UpdateReducedProblem(Epetra_LinearProblem * Problem) {
551 
552  int i, j;
553 
554  if (Problem==0) EPETRA_CHK_ERR(-1); // Null problem pointer
555 
556  FullProblem_ = Problem;
557  FullMatrix_ = dynamic_cast<Epetra_RowMatrix *>(Problem->GetMatrix());
558  if (FullMatrix_==0) EPETRA_CHK_ERR(-2); // Need a RowMatrix
559  if (Problem->GetRHS()==0) EPETRA_CHK_ERR(-3); // Need a RHS
560  if (Problem->GetLHS()==0) EPETRA_CHK_ERR(-4); // Need a LHS
561  if (!HaveReducedProblem_) EPETRA_CHK_ERR(-5); // Must have set up reduced problem
562 
563  if ( SingletonsDetected() ) {
564 
565  // Create pointer to Full RHS, LHS
566  Epetra_MultiVector * FullRHS = FullProblem()->GetRHS();
567  Epetra_MultiVector * FullLHS = FullProblem()->GetLHS();
568 
569  int NumVectors = FullLHS->NumVectors();
570  tempExportX_->PutScalar(0.0);
571 
572  int NumEntries;
573  int * Indices;
574  double * Values;
575  int NumMyRows = FullMatrix()->NumMyRows();
576  int ColSingletonCounter = 0;
577  for (i=0; i<NumMyRows; i++) {
578  int curGRID = FullMatrixRowMap().GID(i);
579  if (ReducedMatrixRowMap()->MyGID(curGRID)) { // Check if this row should go into reduced matrix
580  EPETRA_CHK_ERR(GetRowGCIDs(i, NumEntries, Values, Indices)); // Get current row (indices global)
581  int ierr = ReducedMatrix()->ReplaceGlobalValues(curGRID, NumEntries,
582  Values, Indices);
583  // Positive errors will occur because we are submitting col entries that are not part of
584  // reduced system. However, because we specified a column map to the ReducedMatrix constructor
585  // these extra column entries will be ignored and we will be politely reminded by a positive
586  // error code
587  if (ierr<0) EPETRA_CHK_ERR(ierr);
588  }
589  // Otherwise if singleton row we explicitly eliminate this row and solve for corresponding X value
590  else {
591  EPETRA_CHK_ERR(GetRow(i, NumEntries, Values, Indices)); // Get current row
592  if (NumEntries==1) {
593  double pivot = Values[0];
594  if (pivot==0.0) EPETRA_CHK_ERR(-1); // Encountered zero row, unable to continue
595  int indX = Indices[0];
596  for (j=0; j<NumVectors; j++)
597  (*tempExportX_)[j][indX] = (*FullRHS)[j][i]/pivot;
598  }
599  // Otherwise, this is a singleton column and we will scan for the pivot element needed
600  // for post-solve equations
601  else {
602  j = ColSingletonPivotLIDs_[ColSingletonCounter];
603  double pivot = Values[j];
604  if (pivot==0.0) EPETRA_CHK_ERR(-2); // Encountered zero column, unable to continue
605  ColSingletonPivots_[ColSingletonCounter] = pivot;
606  ColSingletonCounter++;
607  }
608  }
609  }
610 
611  assert(ColSingletonCounter==NumMyColSingletons_); // Sanity test
612 
613  // Update Reduced LHS (Puts any initial guess values into reduced system)
614 
615  ReducedLHS_->PutScalar(0.0); // zero out Reduced LHS
616  EPETRA_CHK_ERR(ReducedLHS_->Import(*FullLHS, *Full2ReducedLHSImporter_, Insert));
617  FullLHS->PutScalar(0.0); // zero out Full LHS since we will inject values as we get them
618 
619  // Construct Reduced RHS
620 
621  // Zero out temp space
622  tempX_->PutScalar(0.0);
623  tempB_->PutScalar(0.0);
624 
625  //Inject known X values into tempX for purpose of computing tempB = FullMatrix*tempX
626  // Also inject into full X since we already know the solution
627 
628  if (FullMatrix()->RowMatrixImporter()!=0) {
629  EPETRA_CHK_ERR(tempX_->Export(*tempExportX_, *FullMatrix()->RowMatrixImporter(), Add));
630  EPETRA_CHK_ERR(FullLHS->Export(*tempExportX_, *FullMatrix()->RowMatrixImporter(), Add));
631  }
632  else {
633  tempX_->Update(1.0, *tempExportX_, 0.0);
634  FullLHS->Update(1.0, *tempExportX_, 0.0);
635  }
636 
637  EPETRA_CHK_ERR(FullMatrix()->Multiply(false, *tempX_, *tempB_));
638 
639  EPETRA_CHK_ERR(tempB_->Update(1.0, *FullRHS, -1.0)); // tempB now has influence of already-known X values
640 
641  ReducedRHS_->PutScalar(0.0);
642  EPETRA_CHK_ERR(ReducedRHS_->Import(*tempB_, *Full2ReducedRHSImporter_, Insert));
643  }
644  else {
645 
646  // There are no singletons, so don't bother building a reduced problem.
647  ReducedProblem_ = Teuchos::rcp( Problem, false );
648  ReducedMatrix_ = Teuchos::rcp( dynamic_cast<Epetra_CrsMatrix *>(Problem->GetMatrix()), false );
649  }
650 
651  return(0);
652 }
653 //==============================================================================
654 int LinearProblem_CrsSingletonFilter::ConstructRedistributeExporter(Epetra_Map * SourceMap, Epetra_Map * TargetMap,
655  Epetra_Export * & RedistributeExporter,
656  Epetra_Map * & RedistributeMap) {
657 
658  int IndexBase = SourceMap->IndexBase();
659  if (IndexBase!=TargetMap->IndexBase()) EPETRA_CHK_ERR(-1);
660 
661  const Epetra_Comm & Comm = TargetMap->Comm();
662 
663  int TargetNumMyElements = TargetMap->NumMyElements();
664  int SourceNumMyElements = SourceMap->NumMyElements();
665 
666  // ContiguousTargetMap has same number of elements per PE as TargetMap, but uses contigious indexing
667  Epetra_Map ContiguousTargetMap(-1, TargetNumMyElements, IndexBase,Comm);
668 
669  // Same for ContiguousSourceMap
670  Epetra_Map ContiguousSourceMap(-1, SourceNumMyElements, IndexBase, Comm);
671 
672  assert(ContiguousSourceMap.NumGlobalElements()==ContiguousTargetMap.NumGlobalElements());
673 
674  // Now create a vector that contains the global indices of the Source Epetra_MultiVector
675  Epetra_IntVector SourceIndices(View, ContiguousSourceMap, SourceMap->MyGlobalElements());
676 
677  // Create an exporter to send the SourceMap global IDs to the target distribution
678  Epetra_Export Exporter(ContiguousSourceMap, ContiguousTargetMap);
679 
680  // Create a vector to catch the global IDs in the target distribution
681  Epetra_IntVector TargetIndices(ContiguousTargetMap);
682  TargetIndices.Export(SourceIndices, Exporter, Insert);
683 
684  // Create a new map that describes how the Source MultiVector should be laid out so that it has
685  // the same number of elements on each processor as the TargetMap
686  RedistributeMap = new Epetra_Map(-1, TargetNumMyElements, TargetIndices.Values(), IndexBase, Comm);
687 
688  // This exporter will finally redistribute the Source MultiVector to the same layout as the TargetMap
689  RedistributeExporter = new Epetra_Export(*SourceMap, *RedistributeMap);
690  return(0);
691 }
692 //==============================================================================
694 
695  if ( SingletonsDetected() ) {
696  int jj, k;
697 
698  Epetra_MultiVector * FullLHS = FullProblem()->GetLHS();
699  Epetra_MultiVector * FullRHS = FullProblem()->GetRHS();
700 
701  tempX_->PutScalar(0.0); tempExportX_->PutScalar(0.0);
702  // Inject values that the user computed for the reduced problem into the full solution vector
703  EPETRA_CHK_ERR(tempX_->Export(*ReducedLHS_, *Full2ReducedLHSImporter_, Add));
704 
705  FullLHS->Update(1.0, *tempX_, 1.0);
706 
707  // Next we will use our full solution vector which is populated with pre-filter solution
708  // values and reduced system solution values to compute the sum of the row contributions
709  // that must be subtracted to get the post-filter solution values
710 
711  EPETRA_CHK_ERR(FullMatrix()->Multiply(false, *FullLHS, *tempB_));
712 
713  // Finally we loop through the local rows that were associated with column singletons and compute the
714  // solution for these equations.
715 
716  int NumVectors = tempB_->NumVectors();
717  for (k=0; k<NumMyColSingletons_; k++) {
718  int i = ColSingletonRowLIDs_[k];
719  int j = ColSingletonColLIDs_[k];
720  double pivot = ColSingletonPivots_[k];
721  for (jj=0; jj<NumVectors; jj++)
722  (*tempExportX_)[jj][j]= ((*FullRHS)[jj][i] - (*tempB_)[jj][i])/pivot;
723  }
724 
725  // Finally, insert values from post-solve step and we are done!!!!
726 
727  if (FullMatrix()->RowMatrixImporter()!=0) {
728  EPETRA_CHK_ERR(tempX_->Export(*tempExportX_, *FullMatrix()->RowMatrixImporter(), Add));
729  }
730  else {
731  tempX_->Update(1.0, *tempExportX_, 0.0);
732  }
733 
734  FullLHS->Update(1.0, *tempX_, 1.0);
735  }
736 
737  return(0);
738 }
739 //==============================================================================
741 
742  MaxNumMyEntries_ = FullMatrix()->MaxNumEntries();
743 
744  // Cast to CrsMatrix, if possible. Can save some work.
745  FullCrsMatrix_ = dynamic_cast<Epetra_CrsMatrix *>(FullMatrix());
746  FullMatrixIsCrsMatrix_ = (FullCrsMatrix_!=0); // Pointer is non-zero if cast worked
747  Indices_ = new int[MaxNumMyEntries_];
749 
750  return(0);
751 }
752 //==============================================================================
753 int LinearProblem_CrsSingletonFilter::GetRow(int Row, int & NumIndices, int * & Indices) {
754 
755  if (FullMatrixIsCrsMatrix_) { // View of current row
756  EPETRA_CHK_ERR(FullCrsMatrix()->Graph().ExtractMyRowView(Row, NumIndices, Indices));
757  }
758  else { // Copy of current row (we must get the values, but we ignore them)
759  EPETRA_CHK_ERR(FullMatrix()->ExtractMyRowCopy(Row, MaxNumMyEntries_, NumIndices,
760  Values_.Values(), Indices_));
761  Indices = Indices_;
762  }
763  return(0);
764 }
765 //==============================================================================
766 int LinearProblem_CrsSingletonFilter::GetRow(int Row, int & NumIndices,
767  double * & Values, int * & Indices) {
768 
769  if (FullMatrixIsCrsMatrix_) { // View of current row
770  EPETRA_CHK_ERR(FullCrsMatrix_->ExtractMyRowView(Row, NumIndices, Values, Indices));
771  }
772  else { // Copy of current row (we must get the values, but we ignore them)
773  EPETRA_CHK_ERR(FullMatrix()->ExtractMyRowCopy(Row, MaxNumMyEntries_, NumIndices,
774  Values_.Values(), Indices_));
775  Values = Values_.Values();
776  Indices = Indices_;
777  }
778  return(0);
779 }
780 //==============================================================================
781 int LinearProblem_CrsSingletonFilter::GetRowGCIDs(int Row, int & NumIndices,
782  double * & Values, int * & GlobalIndices) {
783 
784  EPETRA_CHK_ERR(FullMatrix()->ExtractMyRowCopy(Row, MaxNumMyEntries_, NumIndices,
785  Values_.Values(), Indices_));
786  for (int j=0; j<NumIndices; j++) Indices_[j] = FullMatrixColMap().GID(Indices_[j]);
787  Values = Values_.Values();
788  GlobalIndices = Indices_;
789  return(0);
790 }
791 //==============================================================================
793  const Epetra_MapColoring & RowMapColors,
794  const Epetra_IntVector & ColProfiles,
795  const Epetra_IntVector & NewColProfiles,
796  const Epetra_IntVector & ColHasRowWithSingleton) {
797 
798  int j;
799 
800  if (NumMyColSingletons_==0) return(0); // Nothing to do
801 
802  Epetra_MapColoring & ColMapColors = *ColMapColors_;
803 
804  int NumMyCols = FullMatrix()->NumMyCols();
805 
806  // We will need these arrays for the post-solve phase
811 
812  // Register singleton columns (that were not already counted as singleton rows)
813  // Check to see if any columns disappeared because all associated rows were eliminated
814  int NumMyColSingletonstmp = 0;
815  for (j=0; j<NumMyCols; j++) {
816  int i = RowIDs[j];
817  if ( ColProfiles[j]==1 && RowMapColors[i]!=1 ) {
818  ColSingletonRowLIDs_[NumMyColSingletonstmp] = i;
819  ColSingletonColLIDs_[NumMyColSingletonstmp] = j;
820  NumMyColSingletonstmp++;
821  }
822  // Also check for columns that were eliminated implicitly by
823  // having all associated row eliminated
824  else if (NewColProfiles[j]==0 && ColHasRowWithSingleton[j]!=1 && RowMapColors[i]==0) {
825  ColMapColors[j] = 1;
826  }
827  }
828 
829  assert(NumMyColSingletonstmp==NumMyColSingletons_); //Sanity check
830  Epetra_Util sorter;
831  sorter.Sort(true, NumMyColSingletons_, ColSingletonRowLIDs_, 0, 0, 1, &ColSingletonColLIDs_);
832 
833  return(0);
834 }
835 
836 } //namespace EpetraExt
837 
int GetRowGCIDs(int Row, int &NumIndices, double *&Values, int *&GlobalIndices)
Epetra_Map * ReducedMatrixDomainMap() const
Returns pointer to Epetra_Map describing the domain map for the reduced system.
Epetra_Map * ReducedMatrixRangeMap() const
Returns pointer to Epetra_Map describing the range map for the reduced system.
double RatioOfDimensions() const
Returns ratio of reduced system to full system dimensions, returns -1.0 if reduced problem not constr...
NewTypeRef operator()(OriginalTypeRef orig)
Analysis of transform operation on original object and construction of new object.
bool fwd()
Forward transfer of data from orig object input in the operator() method call to the new object creat...
NewTypeRef construct()
Construction of new object as a result of the transform.
virtual ~LinearProblem_CrsSingletonFilter()
Epetra_CrsSingletonFilter Destructor.
bool rvs()
Reverse transfer of data from new object created in the operator() method call to the orig object inp...
bool SingletonsDetected() const
Returns true if singletons were detected in this matrix (must be called after Analyze() to be effecti...
int Analyze(Epetra_RowMatrix *FullMatrix)
Analyze the input matrix, removing row/column pairs that have singletons.
Epetra_Map * ReducedMatrixRowMap() const
Returns pointer to Epetra_Map describing the reduced system row distribution.
Epetra_CrsMatrix * ReducedMatrix() const
Returns pointer to Epetra_CrsMatrix from full problem.
Epetra_MapColoring * RowMapColors() const
Returns pointer to Epetra_MapColoring object: color 0 rows are part of reduced system.
int ComputeFullSolution()
Compute a solution for the full problem using the solution of the reduced problem, put in LHS of FullProblem().
LinearProblem_CrsSingletonFilter(bool verbose=false)
Epetra_CrsSingletonFilter default constructor.
Epetra_LinearProblem * ReducedProblem() const
Returns pointer to the derived reduced Epetra_LinearProblem.
bool analyze(OriginalTypeRef orig)
Initial analysis phase of transform.
double RatioOfNonzeros() const
Returns ratio of reduced system to full system nonzero count, returns -1.0 if reduced problem not con...
int ConstructRedistributeExporter(Epetra_Map *SourceMap, Epetra_Map *TargetMap, Epetra_Export *&RedistributeExporter, Epetra_Map *&RedistributeMap)
int CreatePostSolveArrays(const Epetra_IntVector &RowIDs, const Epetra_MapColoring &RowMapColors, const Epetra_IntVector &ColProfiles, const Epetra_IntVector &NewColProfiles, const Epetra_IntVector &ColHasRowWithSingleton)
Epetra_RowMatrix * FullMatrix() const
Returns pointer to Epetra_CrsMatrix from full problem.
int UpdateReducedProblem(Epetra_LinearProblem *Problem)
Update a reduced linear problem using new values.
Epetra_Map * ReducedMatrixColMap() const
Returns pointer to Epetra_Map describing the reduced system column distribution.
int ConstructReducedProblem(Epetra_LinearProblem *Problem)
Return a reduced linear problem based on results of Analyze().
Epetra_LinearProblem * FullProblem() const
Returns pointer to the original unreduced Epetra_LinearProblem.
int NumSingletons() const
Return total number of singletons detected, returns -1 if Analysis not performed yet.
Epetra_MapColoring * ColMapColors() const
Returns pointer to Epetra_MapColoring object: color 0 columns are part of reduced system...