Debian Codegraph @

packages/trilinoscouplings/src/ml/NonlinML/nlnml_preconditioner1.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Trilinos: An Object-Oriented Solver Framework
4 //
5 // Copyright 2001-2024 NTESS and the Trilinos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /* ******************************************************************** */
11 /* See the file COPYRIGHT for a complete copyright notice, contact */
12 /* person and disclaimer. */
13 /* ******************************************************************** */
14 /*!
15 * \file nlnml_preconditioner1.cpp
16 *
17 * \class ML_Nox_Preconditioner
18 *
19 * \brief ML nonlinear preconditioner and solver
20 *
21 * \date Last update do Doxygen: 31-Mar-05
22 *
23 */
24 #include "ml_common.h"
25 #include "TrilinosCouplings_config.h"
26
27 #if defined(HAVE_ML_NOX) && defined(HAVE_ML_EPETRA) && defined(HAVE_ML_AZTECOO) && defined(HAVE_ML_TEUCHOS) && defined(HAVE_ML_IFPACK) && defined(HAVE_ML_AMESOS) && defined(HAVE_ML_EPETRAEXT)
28
29 // ---------- Includes ----------
30 #include <ctime>
31 #include <cstdlib>
32 #include <iostream>
33 #include <string>
34 #include <vector>
35
36 #ifdef HAVE_ML_MLAPI
37 #include "MLAPI_Space.h"
38 #include "MLAPI_Operator.h"
39 #include "MLAPI_MultiVector.h"
40 #include "MLAPI_Gallery.h"
41 #include "MLAPI_Expressions.h"
42 #include "MLAPI_MultiLevelAdaptiveSA.h"
43 #include "MLAPI_DistributedMatrix.h"
44 #endif
45
46 // this class
47 #include "nlnml_preconditioner.H"
48
49 using namespace std;
50
51 /*----------------------------------------------------------------------*
52 | ctor (public) m.gee 3/06|
53 *----------------------------------------------------------------------*/
54 NLNML::NLNML_Preconditioner::NLNML_Preconditioner(
55 RefCountPtr<NLNML::NLNML_FineLevelNoxInterface> interface,
56 ParameterList& mlparams,
57 const Epetra_Comm& comm) :
58 label_("nlnML_Preconditioner"),
59 isinit_(false),
60 comm_(comm),
61 interface_(interface),
62 ml_(NULL),
63 ag_(NULL)
64 {
65 CheckInputParameters(mlparams);
66 params_ = rcp(new Teuchos::ParameterList(mlparams));
67 // we make a backup of the nullspace dimension as it might be
68 // overwritten by the adaptive ns procedure
69 int dimns = getParameter("nlnML null space: dimension",1);
70 setParameter("nlnML null space: dimension2",dimns);
71 return;
72 }
73
74
75 /*----------------------------------------------------------------------*
76 | dtor (public) m.gee 3/06|
77 *----------------------------------------------------------------------*/
78 NLNML::NLNML_Preconditioner::~NLNML_Preconditioner()
79 {
80 if (ag_) ML_Aggregate_Destroy(&ag_);
81 if (ml_) ML_Destroy(&ml_);
82 return;
83 }
84
85
86 /*----------------------------------------------------------------------*
87 | (private) m.gee 3/06|
88 *----------------------------------------------------------------------*/
89 bool NLNML::NLNML_Preconditioner::CheckInputParameters(ParameterList& params)
90 {
91 int missing = 0;
92 vector<string> missingparams(38);
93
94 if (!params.isParameter("nlnML output"))
95 { missingparams[missing] = "\"nlnML output\" [int]"; ++missing; }
96 if (!params.isParameter("nlnML max levels"))
97 { missingparams[missing] = "\"nlnML max levels\" [int]"; ++missing; }
98 if (!params.isParameter("nlnML coarse: max size"))
99 { missingparams[missing] = "\"nlnML coarse: max size\" [int]"; ++missing; }
100 if (!params.isParameter("nlnML is linear preconditioner"))
101 { missingparams[missing] = "\"nlnML is linear preconditioner\" [bool]"; ++missing; }
102 if (!params.isParameter("nlnML apply constraints"))
103 { missingparams[missing] = "\"nlnML apply constraints\" [bool]"; ++missing; }
104 if (!params.isParameter("nlnML is matrixfree"))
105 { missingparams[missing] = "\"nlnML is matrixfree\" [bool]"; ++missing; }
106 if (!params.isParameter("nlnML finite difference fine level"))
107 { missingparams[missing] = "\"nlnML finite difference fine level\" [bool]"; ++missing; }
108 if (!params.isParameter("nlnML finite difference alpha"))
109 { missingparams[missing] = "\"nlnML finite difference alpha\" [double]"; ++missing; }
110 if (!params.isParameter("nlnML finite difference beta"))
111 { missingparams[missing] = "\"nlnML finite difference beta\" [double]"; ++missing; }
112 if (!params.isParameter("nlnML finite difference centered"))
113 { missingparams[missing] = "\"nlnML finite difference centered\" [bool]"; ++missing; }
114 if (!params.isParameter("nlnML Jacobian fix diagonal"))
115 { missingparams[missing] = "\"nlnML Jacobian fix diagonal\" [bool]"; ++missing; }
116 if (!params.isParameter("nlnML absolute residual tolerance"))
117 { missingparams[missing] = "\"nlnML absolute residual tolerance\" [double]"; ++missing; }
118 if (!params.isParameter("nlnML max cycles"))
119 { missingparams[missing] = "\"nlnML max cycles\" [int]"; ++missing; }
120 if (!params.isParameter("nlnML adaptive recompute"))
121 { missingparams[missing] = "\"nlnML adaptive recompute\" [double]"; ++missing; }
122 if (!params.isParameter("nlnML offset recompute"))
123 { missingparams[missing] = "\"nlnML offset recompute\" [int]"; ++missing; }
124 if (!params.isParameter("nlnML additional adaptive nullspace"))
125 { missingparams[missing] = "\"nlnML additional adaptive nullspace\" [int]"; ++missing; }
126 if (!params.isParameter("nlnML PDE equations"))
127 { missingparams[missing] = "\"nlnML PDE equations\" [int]"; ++missing; }
128 if (!params.isParameter("nlnML null space: dimension"))
129 { missingparams[missing] = "\"nlnML null space: dimension\" [int]"; ++missing; }
130 if (!params.isParameter("nlnML spatial dimension"))
131 { missingparams[missing] = "\"nlnML spatial dimension\" [int]"; ++missing; }
132 if (!params.isParameter("nlnML coarse: type"))
133 { missingparams[missing] = "\"nlnML coarse: type\" [std::string]"; ++missing; }
134 if (!params.isParameter("nlnML nodes per aggregate"))
135 { missingparams[missing] = "\"nlnML nodes per aggregate\" [int]"; ++missing; }
136 if (!params.isParameter("nlnML use nlncg on fine level"))
137 { missingparams[missing] = "\"nlnML use nlncg on fine level\" [bool]"; ++missing; }
138 if (!params.isParameter("nlnML use nlncg on medium level"))
139 { missingparams[missing] = "\"nlnML use nlncg on medium level\" [bool]"; ++missing; }
140 if (!params.isParameter("nlnML use nlncg on coarsest level"))
141 { missingparams[missing] = "\"nlnML use nlncg on coarsest level\" [bool]"; ++missing; }
142 if (!params.isParameter("nlnML max iterations newton-krylov fine level"))
143 { missingparams[missing] = "\"nlnML max iterations newton-krylov fine level\" [int]"; ++missing; }
144 if (!params.isParameter("nlnML max iterations newton-krylov medium level"))
145 { missingparams[missing] = "\"nlnML max iterations newton-krylov medium level\" [int]"; ++missing; }
146 if (!params.isParameter("nlnML max iterations newton-krylov coarsest level"))
147 { missingparams[missing] = "\"nlnML max iterations newton-krylov coarsest level\" [int]"; ++missing; }
148 if (!params.isParameter("nlnML linear smoother type fine level"))
149 { missingparams[missing] = "\"nlnML linear smoother type fine level\" [std::string]"; ++missing; }
150 if (!params.isParameter("nlnML linear smoother type medium level"))
151 { missingparams[missing] = "\"nlnML linear smoother type medium level\" [std::string]"; ++missing; }
152 if (!params.isParameter("nlnML linear smoother type coarsest level"))
153 { missingparams[missing] = "\"nlnML linear smoother type coarsest level\" [std::string]"; ++missing; }
154 if (!params.isParameter("nlnML linear smoother sweeps fine level"))
155 { missingparams[missing] = "\"nlnML linear smoother sweeps fine level\" [int]"; ++missing; }
156 if (!params.isParameter("nlnML linear smoother sweeps medium level"))
157 { missingparams[missing] = "\"nlnML linear smoother sweeps medium level\" [int]"; ++missing; }
158 if (!params.isParameter("nlnML linear smoother sweeps coarsest level"))
159 { missingparams[missing] = "\"nlnML linear smoother sweeps coarsest level\" [int]"; ++missing; }
160 if (!params.isParameter("nlnML nonlinear presmoothing sweeps fine level"))
161 { missingparams[missing] = "\"nlnML nonlinear presmoothing sweeps fine level\" [int]"; ++missing; }
162 if (!params.isParameter("nlnML nonlinear presmoothing sweeps medium level"))
163 { missingparams[missing] = "\"nlnML nonlinear presmoothing sweeps medium level\" [int]"; ++missing; }
164 if (!params.isParameter("nlnML nonlinear smoothing sweeps coarse level"))
165 { missingparams[missing] = "\"nlnML nonlinear smoothing sweeps coarse level\" [int]"; ++missing; }
166 if (!params.isParameter("nlnML nonlinear postsmoothing sweeps medium level"))
167 { missingparams[missing] = "\"nlnML nonlinear postsmoothing sweeps medium level\" [int]"; ++missing; }
168 if (!params.isParameter("nlnML nonlinear postsmoothing sweeps fine level"))
169 { missingparams[missing] = "\"nlnML nonlinear postsmoothing sweeps fine level\" [int]"; ++missing; }
170 // 38 parameters right now
171
172
173 if (missing && Comm().MyPID()==0)
174 {
175 std::cout << "======================================================\n";
176 std::cout << "nlnML (level 0): missing parameters in parameter list:\n";
177 std::cout << "------------------------------------------------------\n";
178 for (int i=0; i<missing; ++i)
179 std::cout << missingparams[i] << std::endl;
180 std::cout << "------------------------------------------------------\n";
181 std::cout << "nlnML (level 0): Note that depending on what method you would like\n"
182 << " to run it's ok to miss some while for others\n"
183 << " suboptimal default values will be used.\n";
184 std::cout << "======================================================\n";
185 fflush(stdout);
186 }
187
188 return true;
189 }
190
191
192 /*----------------------------------------------------------------------*
193 | compute this preconditioner (public, derived) m.gee 3/06|
194 *----------------------------------------------------------------------*/
195 bool NLNML::NLNML_Preconditioner::computePreconditioner(
196 const Epetra_Vector& x,
197 Epetra_Operator& M,
198 Teuchos::ParameterList* precParams)
199 {
200 if (&M != this)
201 {
202 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::computePreconditioner:\n"
203 << "**ERR**: supplied preconditioner is not this\n"
204 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
205 }
206
207 bool flag = true;
208 int offset = getoffset();
209
210 if (offset && ncalls_NewPrec_)
211 {
212 if (ncalls_NewPrec_ % offset == 0)
213 {
214 setinit(false);
215 }
216 }
217 else if ( params_->get("nlnML adaptive recompute",0.0) &&
218 ncalls_NewPrec_ &&
219 !params_->get("nlnML is linear preconditioner",true))
220 {
221 if (noxsolver_ == null)
222 {
223 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::computePreconditioner:\n"
224 << "**ERR**: outer nox solver not registered\n"
225 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
226 }
227 const NOX::Epetra::Group& finalGroup =
228 dynamic_cast<const NOX::Epetra::Group&>(noxsolver_->getSolutionGroup());
229 const Epetra_Vector& currentF =
230 (dynamic_cast<const NOX::Epetra::Vector&>(finalGroup.getF())).getEpetraVector();
231 double norm;
232 currentF.Norm2(&norm);
233 if (norm > params_->get("nlnML adaptive recompute",0.0))
234 setinit(false);
235 }
236
237 if (!isinit())
238 {
239 if (Comm().MyPID() && OutLevel())
240 {
241 std::cout << "ML: NLNML_Preconditioner::computePreconditioner: (re)computing ML-Preconditioner\n";
242 }
243
244 // save number of calls to computeF
245 int ncalls = interface_->getnumcallscomputeF();
246
247 interface_->setnumcallscomputeF(0);
248
249 double t0 = GetClock();
250 flag = compPrec(x);
251 double t1 = GetClock();
252
253 if (Comm().MyPID() && OutLevel())
254 {
255 std::cout << "ML: Setup time for preconditioner: " << (t1-t0) << " sec\n";
256 std::cout << "ML: Number of calls to fineinterface.computeF() in setup: "
257 << interface_->getnumcallscomputeF() << std::endl;
258 }
259
260 // reset the number of calls to computeF
261 interface_->setnumcallscomputeF(ncalls);
262
263 if (flag)
264 {
265 setinit(true);
266 }
267 else
268 {
269 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::computePreconditioner:\n"
270 << "**ERR**: setup of Preconditioner failed\n"
271 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
272 }
273 setinit(true);
274 }
275 ++ncalls_NewPrec_;
276 return flag;
277 }
278
279
280
281 /*----------------------------------------------------------------------*
282 | compute this preconditioner m.gee 3/06|
283 *----------------------------------------------------------------------*/
284 bool NLNML::NLNML_Preconditioner::compPrec(const Epetra_Vector& x)
285 {
286 if ( getParameter("nlnML finite difference fine level",false)==true)
287 setParameter("nlnML is matrixfree",true);
288
289 // Jacobian is supposed to be supplied by application
290 if (getParameter("nlnML is matrixfree",false)==false)
291 {
292 // recompute the Jacobian
293 fineJac_ = rcp(interface_->getJacobian());
294 fineJac_.release();
295 interface_->computeJacobian(x,*fineJac_);
296 fineJac_ = rcp(interface_->getJacobian());
297 fineJac_.release();
298 // check for zero diagonal entries
299 if (getParameter("nlnML Jacobian fix diagonal",true)==true)
300 fix_MainDiagonal(fineJac_,0);
301
302 fineJac_ = NLNML::StripZeros(fineJac_,1.0e-11);
303 }
304 else if (getParameter("nlnML is matrixfree",false)==true &&
305 getParameter("nlnML finite difference fine level",false)==true)
306 {
307 fineJac_ = ComputeFineLevelJacobian(x);
308 setParameter("nlnML is matrixfree",false);
309 if (getParameter("nlnML Jacobian fix diagonal",true)==true)
310 fix_MainDiagonal(fineJac_,0);
311 }
312 else
313 {
314 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::compPrec:\n"
315 << "**ERR**: unknown parameter combination for Jacobian\n"
316 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
317 }
318
319 // create ml
320 if (ag_) ML_Aggregate_Destroy(&ag_);
321 if (ml_) ML_Destroy(&ml_);
322 ML_Aggregate_Create(&ag_);
323 int maxnlevel = getParameter("nlnML max levels",10);
324 ML_Create(&ml_,maxnlevel);
325
326 // set fine grid matrix
327 EpetraMatrix2MLMatrix(ml_,0,(dynamic_cast<Epetra_RowMatrix*>(fineJac_.get())));
328
329 // set coarsening type
330 std::string coarsentype = getParameter("nlnML coarse: type",(std::string)"Uncoupled");
331 if (coarsentype=="Uncoupled")
332 ML_Aggregate_Set_CoarsenScheme_Uncoupled(ag_);
333 else if (coarsentype=="MIS")
334 ML_Aggregate_Set_CoarsenScheme_MIS(ag_);
335 else if (coarsentype=="METIS")
336 {
337 ML_Aggregate_Set_CoarsenScheme_METIS(ag_);
338 int nnodeperagg = getParameter("nlnML nodes per aggregate",27);
339 for (int i=0; i<maxnlevel; ++i)
340 ML_Aggregate_Set_NodesPerAggr(ml_,ag_,i,nnodeperagg);
341 }
342 else if (coarsentype=="VBMETIS")
343 {
344 vector<int> blocks(0);
345 vector<int> block_pde(0);
346 int nblocks = 0;
347 bool ok = interface_->getBlockInfo(&nblocks,blocks,block_pde);
348 if (!ok)
349 {
350 std::cout << "**WRN**: NLNML::NLNML_Preconditioner::compPrec:\n"
351 << "**WRN**: interface returned no blocks,\n"
352 << "**WRN**: using aggregation scheme METIS instead of VBMETIS\n";
353 setParameter("nlnML coarse: type",(std::string)"METIS");
354 ML_Aggregate_Set_CoarsenScheme_METIS(ag_);
355 }
356 else
357 {
358 ML_Aggregate_Set_CoarsenScheme_VBMETIS(ag_);
359 int nupdate = interface_->getMap().NumMyElements();
360 ML_Aggregate_Set_Vblocks_CoarsenScheme_VBMETIS(ag_,0,maxnlevel,
361 nblocks,&blocks[0],
362 &block_pde[0],nupdate);
363 blocks.clear();
364 block_pde.clear();
365 }
366 int nnodeperagg = getParameter("nlnML nodes per aggregate",27);
367 for (int i=0; i<maxnlevel; ++i)
368 ML_Aggregate_Set_NodesPerAggr(ml_,ag_,i,nnodeperagg);
369 }
370
371 // set damping factor and threshold for smoothed aggregation
372 ML_Aggregate_Set_DampingFactor(ag_, 1.3333);
373 ML_Aggregate_Set_Threshold(ag_, 0.0);
374
375 // set max coarse grid size
376 ML_Aggregate_Set_MaxCoarseSize(ag_,getParameter("nlnML coarse: max size",128));
377
378 // Calculate spectral norm
379 ML_Set_SpectralNormScheme_Calc(ml_);
380
381 // Set output level
382 ML_Set_PrintLevel(OutLevel());
383
384 // get nullspace
385 int nummyrows = fineJac_->NumMyRows();
386 int dimnullsp = getParameter("nlnML null space: dimension",1);
387 int blocksize = getParameter("nlnML PDE equations",1);
388 double* nullsp = interface_->Get_Nullspace(nummyrows,blocksize,dimnullsp);
389
390 // run adaptive nullspace procedure
391 int adaptns = getParameter("nlnML additional adaptive nullspace",0);
392 if (adaptns)
393 {
394 Adaptivesetup(&nullsp,fineJac_.get(),blocksize,dimnullsp);
395 setParameter("nlnML null space: dimension",(dimnullsp+adaptns));
396 }
397
398 // Pass nullspace to ml
399 if (nullsp)
400 {
401 dimnullsp = getParameter("nlnML null space: dimension",1);
402 ML_Aggregate_Set_NullSpace(ag_,blocksize,dimnullsp,nullsp,nummyrows);
403 delete [] nullsp; nullsp = NULL;
404 }
405 else
406 {
407 dimnullsp = getParameter("nlnML null space: dimension",1);
408 std::cout << "**WRN**: NLNML_Preconditioner::compPrec:\n"
409 << "**WRN**: interface returned no nullspace,\n"
410 << "**WRN**: using ML's default nullspace\n";
411 if (blocksize != dimnullsp)
412 {
413 std::cout << "**WRN**: ML_Nox_Preconditioner::compPrec:\n"
414 << "**WRN**: with default nullspace, nullspace-dimension must match number of PDEs per node\n"
415 << "**WRN**: numPDE = " << blocksize << ", dimnullsp = " << dimnullsp << "\n"
416 << "**WRN**: continue with setting dimnullsp = numPDE\n";
417 setParameter("nlnML null space: dimension",blocksize);
418 setParameter("nlnML null space: dimension2",blocksize);
419 }
420 ML_Aggregate_Set_NullSpace(ag_,blocksize,dimnullsp,NULL,nummyrows);
421 }
422
423 // keep the aggregation info
424 ag_->keep_agg_information = 1;
425
426 // build amg hierarchy
427 int nlevel = ML_Gen_MGHierarchy_UsingAggregation(ml_,0,ML_INCREASING,ag_);
428 setParameter("nlnML max levels",nlevel);
429
430 if (nlevel<2)
431 {
432 std::cout << "**ERR**: NLNML_Preconditioner::compPrec:\n"
433 << "**ERR**: number of levels generated is " << nlevel << "\n"
434 << "**ERR**: this algorithm relies on at least nlevel >=2 !\n"
435 << "**ERR**: file/line: " << __FILE__ << "(" << __LINE__ << ")\n"; throw -1;
436 }
437
438 // do rest of setup
439 bool islinearPrec = getParameter("nlnML is linear preconditioner",true);
440 if (islinearPrec)
441 {
442 isinit_ = Compute_Linearpreconditioner(x);
443 if (isinit_) return true;
444 else return false;
445 }
446 else
447 {
448 isinit_ = Compute_Nonlinearpreconditioner(x);
449 if (isinit_) return true;
450 else return false;
451 }
452 }
453
454
455
456 /*----------------------------------------------------------------------*
457 | compute linear preconditioner m.gee 3/06|
458 *----------------------------------------------------------------------*/
459 bool NLNML::NLNML_Preconditioner::Compute_Linearpreconditioner(
460 const Epetra_Vector& x)
461 {
462 // choose some smoothers
463 Set_Smoothers();
464 rowmap_ = rcp(new Epetra_Map(interface_->getMap()));
465 linPrec_ = rcp(new ML_Epetra::MultiLevelOperator(ml_,Comm(),*rowmap_,*rowmap_));
466 return true;
467 }
468
469
470
471 /*----------------------------------------------------------------------*
472 | compute nonlinear preconditioner m.gee 3/06|
473 *----------------------------------------------------------------------*/
474 bool NLNML::NLNML_Preconditioner::Compute_Nonlinearpreconditioner(
475 const Epetra_Vector& x)
476 {
477 // extract the prolongations from the hierachy
478 int maxlevel = getParameter("nlnML max levels",10);
479
480 RefCountPtr< vector< RefCountPtr<Epetra_CrsMatrix> > > P =
481 rcp( new vector< RefCountPtr<Epetra_CrsMatrix> >(maxlevel) );
482
483 vector< RefCountPtr<Epetra_CrsMatrix> >& Pref = *P;
484 for (int i=0; i<maxlevel; ++i) Pref[i] = null;
485 for (int i=1; i<maxlevel; ++i) // there is not Pmat on level 0
486 {
487 double t1 = GetClock();
488 int maxnnz = 0;
489 double cputime;
490 Epetra_CrsMatrix* tmp;
491 ML_Operator2EpetraCrsMatrix(&(ml_->Pmat[i]), tmp, maxnnz,
492 false, cputime);
493 (*P)[i] = rcp(tmp);
494 (*P)[i]->OptimizeStorage();
495 double t2 = GetClock() - t1;
496 if (OutLevel()>5 && Comm().MyPID()==0)
497 std::cout << "nlnML (level " << i << "): extraction of P in " << t2 << " sec\n";
498 }
499
500 // create the vector of nonlinear levels
501 nlnlevel_ = rcp( new vector<RefCountPtr<NLNML::NLNML_NonlinearLevel> >(maxlevel));
502
503 // loop all levels and allocate the nonlinear level class
504 for (int i=0; i<maxlevel; ++i)
505 {
506 int spatial = getParameter("nlnML spatial dimension",1);
507 int dimns = getParameter("nlnML null space: dimension",1);
508 int numpde = 0;
509 if (i==0) numpde = getParameter("nlnML PDE equations",1);
510 else if (spatial==1)
511 numpde=1;
512 else if (spatial==2)
513 numpde=3;
514 else if (spatial==3)
515 numpde=6;
516 else
517 {
518 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::Compute_Nonlinearpreconditioner:\n"
519 << "**ERR**: nlnML spatial dimension = " << spatial << " unknown\n"
520 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
521 }
522
523 // choose the nonlinear solver
524 bool isnlncg = true;
525 int niterscg = 0;
526 if (i==0) // fine
527 {
528 isnlncg = getParameter("nlnML use nlncg on fine level",true);
529 niterscg = getParameter("nlnML max iterations newton-krylov fine level",40);
530 }
531 else if (i==maxlevel-1) // coarse
532 {
533 isnlncg = getParameter("nlnML use nlncg on coarsest level",true);
534 niterscg = getParameter("nlnML max iterations newton-krylov coarsest level",40);
535 }
536 else // intermediate
537 {
538 isnlncg = getParameter("nlnML use nlncg on medium level",true);
539 niterscg = getParameter("nlnML max iterations newton-krylov medium level",40);
540 }
541
542 // Allocate the nonlinear level class
543 (*nlnlevel_)[i] = rcp( new NLNML::NLNML_NonlinearLevel(i,params_,ml_,ag_,
544 P,interface_,Comm(),
545 fineJac_,
546 x,isnlncg,niterscg,
547 numpde,dimns));
548 } // for (int i=0; i<maxlevel; ++i)
549
550 // don't need the ag_ and ml_ objects anymore
551 if (ag_)
552 {
553 ML_Aggregate_Destroy(&ag_);
554 ag_ = 0;
555 }
556 if (ml_)
557 {
558 ML_Destroy(&ml_);
559 ml_ = 0;
560 }
561 return true;
562 }
563
564
565
566 /*----------------------------------------------------------------------*
567 | apply this preconditioner (public, derived) m.gee 3/06|
568 *----------------------------------------------------------------------*/
569 int NLNML::NLNML_Preconditioner::ApplyInverse(
570 const Epetra_MultiVector& X,
571 Epetra_MultiVector& Y) const
572 {
573 if (!isinit())
574 {
575 Epetra_Vector x(View,X,0);
576 NLNML::NLNML_Preconditioner* tmp =
577 const_cast<NLNML::NLNML_Preconditioner*>(this);
578 tmp->computePreconditioner(x,*tmp);
579 }
580
581 double t0 = GetClock();
582 int ncalls0 = interface_->getnumcallscomputeF();
583
584 int err = 0;
585 if (getParameter("nlnML is linear preconditioner",true)==true)
586 err = ApplyInverse_Linear(X,Y);
587 else
588 err = ApplyInverse_NonLinear(X,Y);
589
590 // let application enforce constraints on the gradient
591 Epetra_Vector epetragradient(View,Y,0);
592 interface_->ApplyAllConstraints(epetragradient,0);
593
594 int ncalls1 = interface_->getnumcallscomputeF();
595 double t1 = GetClock();
596
597 if (OutLevel()>7 && Comm().MyPID()==0)
598 std::cout << "nlnML (level 0): Preconditioner time " << (t1-t0)
599 << " sec, # evaluateF total/this "
600 << ncalls1 << "/" << (ncalls1-ncalls0) << std::endl;
601
602 if (!err) return 0;
603 else return -1;
604 }
605
606
607
608 /*----------------------------------------------------------------------*
609 | apply inverse for linear preconditioner m.gee 3/06|
610 *----------------------------------------------------------------------*/
611 int NLNML::NLNML_Preconditioner::ApplyInverse_Linear(const Epetra_MultiVector& X,
612 Epetra_MultiVector& Y) const
613 {
614 if (linPrec_==null)
615 {
616 std::cout << "**ERR**: NLNML_Preconditioner::ApplyInverse_Linear:\n";
617 std::cout << "**ERR**: ptr to ML_Epetra::MultiLevelOperator is NULL\n";
618 std::cout << "**ERR**: file/line: " << __FILE__ << "(" << __LINE__ << ")\n"; throw -1;
619 }
620
621 // apply ML
622 return linPrec_->ApplyInverse(X,Y);
623 }
624
625
626
627 /*----------------------------------------------------------------------*
628 | apply inverse for nonlinear preconditioner m.gee 3/06|
629 *----------------------------------------------------------------------*/
630 int NLNML::NLNML_Preconditioner::ApplyInverse_NonLinear(const Epetra_MultiVector& X,
631 Epetra_MultiVector& Y) const
632 {
633 if (noxsolver_==null)
634 {
635 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::ApplyInverse_NonLinear:\n"
636 << "**ERR**: noxsolver not registered, use SetNoxSolver(solver)!\n"
637 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
638 }
639
640 const NOX::Epetra::Group& finalGroup =
641 dynamic_cast<const NOX::Epetra::Group&>(noxsolver_->getSolutionGroup());
642 const Epetra_Vector& currentSolution =
643 (dynamic_cast<const NOX::Epetra::Vector&>(finalGroup.getX())).getEpetraVector();
644 const Epetra_Vector& currentF =
645 (dynamic_cast<const NOX::Epetra::Vector&>(finalGroup.getF())).getEpetraVector();
646 double norm2;
647 currentF.Norm2(&norm2);
648
649 // make a copy of currentSolution and currentF
650 RefCountPtr<Epetra_Vector> f = rcp(new Epetra_Vector(View,X,0));
651 RefCountPtr<Epetra_Vector> x = rcp(new Epetra_Vector(Copy,currentSolution,0));
652
653 // call the cycle
654 if (OutLevel() && !Comm().MyPID())
655 std::cout << "\n\nnlnML :============Entering Nonlinear V-cycle============\n";
656 bool converged = false;
657 double t3 = GetClock();
658 FAS_cycle(f.get(),x.get(),0,&converged,&norm2);
659 double t4 = GetClock();
660 if (OutLevel() && !Comm().MyPID())
661 {
662 std::cout << "nlnML :============V-cycle time is : " << (t4-t3) << " sec\n";
663 if (converged)
664 std::cout << "nlnML :============Nonlinear preconditioner converged====\n";
665 }
666 f = null;
667 Y.Scale(1.0,*x);
668 return 0;
669 }
670
671
672
673
674 /*----------------------------------------------------------------------*
675 | run FAS preconditioner as a solver m.gee 3/06|
676 *----------------------------------------------------------------------*/
677 int NLNML::NLNML_Preconditioner::solve() const
678 {
679 // get starting solution form the interface
680 const Epetra_Vector* xfine = interface_->getSolution();
681
682 // compute preconditioner
683 double t5 = GetClock();
684 NLNML::NLNML_Preconditioner* tmp =
685 const_cast<NLNML::NLNML_Preconditioner*>(this);
686 tmp->computePreconditioner(*xfine,*tmp);
687 double t6 = GetClock();
688
689 // check sanity
690 if (!isinit())
691 {
692 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::solve:\n"
693 << "**ERR**: initflag is false\n"
694 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
695 }
696 if (getParameter("nlnML is linear preconditioner",true) != false)
697 {
698 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::solve:\n"
699 << "**ERR**: Preconditioner has to be nonlinear preconditioner to run as solver\n"
700 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
701 }
702
703 // compute current residual
704 RefCountPtr<Epetra_Vector> f = rcp(new Epetra_Vector(xfine->Map(),false));
705 RefCountPtr<Epetra_Vector> x = rcp(new Epetra_Vector(Copy,*xfine,0));
706 (*nlnlevel_)[0]->setModifiedSystem(false,NULL,NULL);
707 (*nlnlevel_)[0]->computeF(*x,*f,NOX::Epetra::Interface::Required::Residual);
708
709 // max cycles
710 int maxcycle = getParameter("nlnML max cycles",10);
711
712 {
713 double t1 = GetClock();
714 bool converged = false;
715 for (int i=1; i<=maxcycle; ++i)
716 {
717 if (OutLevel() && Comm().MyPID()==0)
718 {
719 std::cout << "\n\nnlnML (level 0):============ nonlinear V-cycle # " << i << " ================\n";
720 fflush(stdout);
721 }
722 double t3 = GetClock();
723 double norm = getParameter("nlnML absolute residual tolerance",1.0e-06);
724
725 //===== presmooth level 0=================================================
726 int nsmooth = getParameter("nlnML nonlinear presmoothing sweeps fine level",2);
727 double prenorm = norm;
728 if (nsmooth)
729 converged = (*nlnlevel_)[0]->Iterate(f.get(),x.get(),nsmooth,&prenorm);
730 if (converged) break;
731
732 //===== restrict to level 0===============================================
733 RefCountPtr<Epetra_Vector> xcoarse = rcp((*nlnlevel_)[0]->restrict_to_next_coarser_level(x.get(),0,1));
734 RefCountPtr<Epetra_Vector> fcoarse = rcp((*nlnlevel_)[0]->restrict_to_next_coarser_level(f.get(),0,1));
735
736 //===== call FAS-cycle on level 1=========================================
737 bool coarseconverged=false;
738 FAS_cycle(fcoarse.get(),xcoarse.get(),1,&coarseconverged,&prenorm);
739 fcoarse = null;
740
741 //===== prolongate correction=============================================
742 RefCountPtr<Epetra_Vector> xcorrect = rcp((*nlnlevel_)[0]->prolong_to_this_level(xcoarse.get(),0,1));
743 xcoarse = null;
744
745 //=====apply correction===================================================
746 x->Update(1.0,*xcorrect,1.0);
747 xcorrect = null;
748
749 //=====postsmoothing level 0==============================================
750 nsmooth = getParameter("nlnML nonlinear postsmoothing sweeps fine level",2);
751 double postnorm = norm;
752 if (nsmooth)
753 converged = (*nlnlevel_)[0]->Iterate(f.get(),x.get(),nsmooth,&postnorm);
754 if (converged) break;
755 if (OutLevel() && Comm().MyPID()==0)
756 {
757 double t4 = GetClock();
758 std::cout << "nlnML (level 0):============ time this cycle: " << t4-t3 << " sec\n";
759 fflush(stdout);
760 }
761 }
762 double t2 = GetClock();
763 if (OutLevel() && Comm().MyPID()==0)
764 {
765 std::cout << "nlnML (level 0):============solve time incl. setup "
766 << t2-t1+t6-t5 << " sec\n";
767 fflush(stdout);
768 }
769 if (converged) return 0;
770 else return -1;
771 }
772 }
773
774
775
776
777 /*----------------------------------------------------------------------*
778 | choose smoothers m.gee 3/06|
779 *----------------------------------------------------------------------*/
780 void NLNML::NLNML_Preconditioner::Set_Smoothers()
781 {
782 // choose fine grid smoother
783 int maxnlevel = getParameter("nlnML max levels",2);
784 std::string fsmoother = getParameter("nlnML linear smoother type fine level",(std::string)"SGS");
785 int nsmoothfine = getParameter("nlnML linear smoother sweeps fine level",1);
786 std::string smoother = getParameter("nlnML linear smoother type medium level",(std::string)"SGS");
787 int nsmooth = getParameter("nlnML linear smoother sweeps medium level",1);
788 std::string csmoother = getParameter("nlnML linear smoother type coarsest level",(std::string)"AmesosKLU");
789 int ncsmooth = getParameter("nlnML linear smoother sweeps coarsest level",1);
790 int coarsegrid = maxnlevel - 1;
791
792 // choose fine level smoother
793 if (fsmoother=="SGS")
794 ML_Gen_Smoother_SymGaussSeidel(ml_,0,ML_BOTH,nsmoothfine,0.67);
795 else if (fsmoother=="Jacobi")
796 {
797 ML_Gen_Smoother_Jacobi(ml_,0,ML_PRESMOOTHER, nsmoothfine,0.2);
798 ML_Gen_Smoother_Jacobi(ml_,0,ML_POSTSMOOTHER,nsmoothfine,0.2);
799 }
800 else if (fsmoother=="BSGS")
801 {
802 int nblocks = 0;
803 int* blocks = NULL;
804 int* blockpde = NULL;
805 // try to get nodal blocks from the VBMETIS aggregation scheme
806 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,0,maxnlevel,
807 &nblocks,&blocks,&blockpde);
808 if (!nblocks && !blocks)
809 ML_Gen_Blocks_Aggregates(ag_,0,&nblocks,&blocks);
810
811 ML_Gen_Smoother_VBlockSymGaussSeidel(ml_,0,ML_BOTH,nsmoothfine,0.67,
812 nblocks,blocks);
813 if (nblocks && blocks)
814 {
815 ML_free(blocks);
816 ML_free(blockpde);
817 }
818 }
819 else if (fsmoother=="Bcheby")
820 {
821 int nblocks = 0;
822 int* blocks = NULL;
823 int* blockpde = NULL;
824 // try to get nodal blocks from the VBMETIS aggregation scheme
825 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,0,maxnlevel,
826 &nblocks,&blocks,&blockpde);
827 if (!nblocks && !blocks)
828 ML_Gen_Blocks_Aggregates(ag_,0,&nblocks,&blocks);
829
830 ML_Gen_Smoother_BlockDiagScaledCheby(ml_,0,ML_BOTH,30.,nsmoothfine,
831 nblocks,blocks);
832 if (nblocks && blocks)
833 {
834 ML_free(blocks);
835 ML_free(blockpde);
836 }
837 }
838 else if ((fsmoother=="MLS")||(fsmoother=="Cheby"))
839 ML_Gen_Smoother_Cheby(ml_,0,ML_BOTH,30.,nsmoothfine);
840 else if (fsmoother=="AmesosKLU")
841 ML_Gen_Smoother_Amesos(ml_,0,ML_AMESOS_KLU,-1,0.0,1);
842 else
843 {
844 std::cout << "**ERR**: NLNML_Preconditioner::Set_Smoothers:\n"
845 << "**ERR**: smoother " << fsmoother << " not recognized\n"
846 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
847 }
848
849 // for intermediate levels)
850 for (int i=1; i<coarsegrid; ++i)
851 {
852 if (smoother=="SGS")
853 ML_Gen_Smoother_SymGaussSeidel(ml_,i,ML_BOTH,nsmooth,0.67);
854 else if (smoother=="Jacobi")
855 {
856 ML_Gen_Smoother_Jacobi(ml_,i,ML_PRESMOOTHER, nsmooth,.2);
857 ML_Gen_Smoother_Jacobi(ml_,i,ML_POSTSMOOTHER,nsmooth,.2);
858 }
859 else if (smoother=="BSGS")
860 {
861 int nblocks = 0;
862 int* blocks = NULL;
863 int* blockpde = NULL;
864 // try to get nodal blocks from the VBMETIS aggregation scheme
865 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,i,maxnlevel,
866 &nblocks,&blocks,&blockpde);
867 if (!nblocks && !blocks)
868 ML_Gen_Blocks_Aggregates(ag_,i,&nblocks,&blocks);
869
870 ML_Gen_Smoother_VBlockSymGaussSeidel(ml_,i,ML_BOTH,nsmooth,0.67,nblocks,blocks);
871 if (nblocks && blocks)
872 {
873 ML_free(blocks);
874 ML_free(blockpde);
875 }
876 }
877 else if (smoother=="Bcheby")
878 {
879 int nblocks = 0;
880 int* blocks = NULL;
881 int* blockpde = NULL;
882 // try to get nodal blocks from the VBMETIS aggregation scheme
883 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,i,maxnlevel,
884 &nblocks,&blocks,&blockpde);
885 if (!nblocks && !blocks)
886 ML_Gen_Blocks_Aggregates(ag_,i,&nblocks,&blocks);
887
888 ML_Gen_Smoother_BlockDiagScaledCheby(ml_,i,ML_BOTH,30.,nsmooth,
889 nblocks,blocks);
890 if (nblocks && blocks)
891 {
892 ML_free(blocks);
893 ML_free(blockpde);
894 }
895 }
896 else if ((smoother=="MLS")||(smoother=="Cheby"))
897 ML_Gen_Smoother_Cheby(ml_,i,ML_BOTH,30.,nsmooth);
898 else if (smoother=="AmesosKLU")
899 ML_Gen_Smoother_Amesos(ml_,i,ML_AMESOS_KLU,-1,0.0,1);
900 else
901 {
902 std::cout << "**ERR**: NLNML_Preconditioner::Set_Smoothers:\n"
903 << "**ERR**: smoother " << smoother << " not recognized\n"
904 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
905 }
906 } // for (int i=1; i<coarsegrid; ++i)
907
908 // choose coarse grid smoother
909 if (csmoother=="SGS")
910 ML_Gen_Smoother_SymGaussSeidel(ml_,coarsegrid,ML_BOTH,ncsmooth,0.67);
911 else if (csmoother=="Jacobi")
912 {
913 ML_Gen_Smoother_Jacobi(ml_,coarsegrid,ML_PRESMOOTHER, ncsmooth,0.2);
914 ML_Gen_Smoother_Jacobi(ml_,coarsegrid,ML_POSTSMOOTHER,ncsmooth,0.2);
915 }
916 else if (csmoother=="BSGS")
917 {
918 int nblocks = 0;
919 int* blocks = NULL;
920 int* blockpde = NULL;
921 // try to get nodal blocks from the VBMETIS aggregation scheme
922 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,coarsegrid,maxnlevel,
923 &nblocks,&blocks,&blockpde);
924 if (!nblocks && !blocks)
925 ML_Gen_Blocks_Aggregates(ag_,0,&nblocks,&blocks);
926
927 ML_Gen_Smoother_VBlockSymGaussSeidel(ml_,coarsegrid,ML_BOTH,ncsmooth,0.67,
928 nblocks,blocks);
929 if (nblocks && blocks)
930 {
931 ML_free(blocks);
932 ML_free(blockpde);
933 }
934 }
935 else if (csmoother=="Bcheby")
936 {
937 int nblocks = 0;
938 int* blocks = NULL;
939 int* blockpde = NULL;
940 // try to get nodal blocks from the VBMETIS aggregation scheme
941 ML_Aggregate_Get_Vblocks_CoarsenScheme_VBMETIS(ag_,coarsegrid,maxnlevel,
942 &nblocks,&blocks,&blockpde);
943 if (!nblocks && !blocks)
944 ML_Gen_Blocks_Aggregates(ag_,0,&nblocks,&blocks);
945
946 ML_Gen_Smoother_BlockDiagScaledCheby(ml_,coarsegrid,ML_BOTH,30.,ncsmooth,
947 nblocks,blocks);
948 if (nblocks && blocks)
949 {
950 ML_free(blocks);
951 ML_free(blockpde);
952 }
953 }
954 else if ((csmoother=="MLS")||(csmoother=="Cheby"))
955 ML_Gen_Smoother_Cheby(ml_,coarsegrid,ML_BOTH,30.,ncsmooth);
956 else if (csmoother=="AmesosKLU")
957 ML_Gen_Smoother_Amesos(ml_,coarsegrid,ML_AMESOS_KLU,-1,0.0,1);
958 else
959 {
960 std::cout << "**ERR**: NLNML_Preconditioner::Set_Smoothers:\n"
961 << "**ERR**: smoother " << csmoother << " not recognized\n"
962 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
963 }
964 return;
965 }
966
967
968
969 /*----------------------------------------------------------------------*
970 | fix main diagonal of Jacobian m.gee 3/06|
971 *----------------------------------------------------------------------*/
972 void NLNML::NLNML_Preconditioner::fix_MainDiagonal(
973 RefCountPtr<Epetra_CrsMatrix> A, int level)
974 {
975 if (!A->Filled()) A->FillComplete();
976
977 Epetra_Vector diag(A->RowMap(),false);
978 int err = A->ExtractDiagonalCopy(diag);
979
980 double average=0.0;
981 for (int i=0; i<diag.MyLength(); i++) average += diag[i];
982 average /= diag.MyLength();
983
984 for (int i=0; i<diag.MyLength(); i++)
985 {
986 // fix zero entries to be real dirichlet boundary constraints because they come from mesh tying
987 if (abs(diag[i])<1.0e-10)
988 {
989 if (OutLevel()>8)
990 printf("found zero diagonal entry %20.12e in row %d, fixing to be %e\n",diag[i],i,average);
991 //check whether there are nonzero off-diagonal entries in that row
992 int numentries;
993 double* values;
994 err = A->ExtractMyRowView(i,numentries,values);
995 if (err)
996 {
997 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::fix_MainDiagonal:\n"
998 << "**ERR**: A->ExtractMyRowView returned " << err << std::endl
999 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
1000 }
1001 double sum=0.0;
1002 for (int j=0; j<numentries; j++)
1003 sum += abs(values[j]);
1004
1005 if (sum>1.0e-9)
1006 continue;
1007
1008 //double small = 10.0;
1009 err = A->ReplaceMyValues(i,1,&average,&i);
1010 if (err)
1011 {
1012 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::fix_MainDiagonal:\n"
1013 << "**ERR**: A->ReplaceMyValues returned " << err << std::endl
1014 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
1015 }
1016 }
1017 // fix small values to be resonably sized because they come from frictionless contact
1018 else if (abs(diag[i])<1.0)
1019 {
1020 double small=10.0;
1021 if (abs(diag[i])>small) small = abs(diag[i]);
1022 if (OutLevel()>8)
1023 printf("found tiny diagonal value %20.12e in row %d, fixing to be %e\n",diag[i],i,small);
1024
1025 err = A->ReplaceMyValues(i,1,&small,&i);
1026 if (err)
1027 {
1028 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::fix_MainDiagonal:\n"
1029 << "**ERR**: A->ReplaceMyValues returned " << err << std::endl
1030 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
1031 }
1032 }
1033 if (diag[i]<0.0)
1034 {
1035 std::cout << "ML: ***WRN*** Found negative main diag entry! Fixing...\n"; fflush(stdout);
1036 double small=10.0;
1037 err = A->ReplaceMyValues(i,1,&small,&i);
1038 if (err)
1039 {
1040 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::fix_MainDiagonal:\n"
1041 << "**ERR**: A->ReplaceMyValues returned " << err << std::endl
1042 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
1043 }
1044 }
1045 }
1046 return;
1047 }
1048
1049
1050
1051
1052 /*----------------------------------------------------------------------*
1053 | compute Jacobian on fine grid m.gee 3/06|
1054 *----------------------------------------------------------------------*/
1055 RefCountPtr<Epetra_CrsMatrix> NLNML::NLNML_Preconditioner::ComputeFineLevelJacobian(const Epetra_Vector& x)
1056 {
1057 // get graph and constrained modified graph
1058 Epetra_CrsGraph* graph =
1059 const_cast<Epetra_CrsGraph*>(interface_->getGraph());
1060 Epetra_CrsGraph* cgraph =
1061 const_cast<Epetra_CrsGraph*>(interface_->getModifiedGraph());
1062
1063 // get the block size of the problem
1064 int bsize = getParameter("nlnML PDE equations",1);
1065
1066 double t0 = GetClock();
1067
1068 if (OutLevel()>0 && Comm().MyPID()==0)
1069 {
1070 std::cout << "nlnML (level 0): Entering Coloring on level 0\n";
1071 fflush(stdout);
1072 }
1073
1074 RefCountPtr<Epetra_MapColoring> colorMap =
1075 NLNML::Collapsedcoloring(cgraph,bsize,false,OutLevel());
1076 if (colorMap==null)
1077 colorMap = NLNML::Standardcoloring(cgraph,false);
1078
1079 RefCountPtr<EpetraExt::CrsGraph_MapColoringIndex> colorMapIndex =
1080 rcp(new EpetraExt::CrsGraph_MapColoringIndex(*colorMap));
1081
1082 RefCountPtr< vector<Epetra_IntVector> > colorcolumns =
1083 rcp(&(*colorMapIndex)(*graph));
1084
1085 double t1 = GetClock();
1086 if (OutLevel()>0 && Comm().MyPID()==0)
1087 {
1088 std::cout << "nlnML (level 0): Proc " << comm_.MyPID() <<" Coloring time is " << (t1-t0) << " sec\n";
1089 std::cout << "nlnML (level 0): Entering Construction FD-Operator on level 0\n";
1090 fflush(stdout);
1091 }
1092
1093 t0 = GetClock();
1094 int ncalls = interface_->getnumcallscomputeF();
1095 interface_->setnumcallscomputeF(0);
1096
1097 RefCountPtr<Teuchos::ParameterList> dummylist =
1098 rcp(new Teuchos::ParameterList());
1099
1100 NOX::Epetra::Vector nx(x);
1101
1102 RefCountPtr<Epetra_CrsGraph> rcpgraph = rcp(graph);
1103 rcpgraph.release();
1104
1105 double alpha = getParameter("nlnML finite difference alpha",1.0e-07);
1106 double beta = getParameter("nlnML finite difference beta",1.0e-06);
1107
1108 RefCountPtr<NOX::Epetra::FiniteDifferenceColoring> FD =
1109 rcp(new NOX::Epetra::FiniteDifferenceColoring(*dummylist,
1110 interface_,
1111 nx,
1112 rcpgraph,
1113 colorMap,
1114 colorcolumns,
1115 true,false,
1116 beta,alpha));
1117
1118 if (getParameter("nlnML finite difference centered",false)==true)
1119 FD->setDifferenceMethod(NOX::Epetra::FiniteDifferenceColoring::Centered);
1120 else
1121 FD->setDifferenceMethod(NOX::Epetra::FiniteDifferenceColoring::Forward);
1122
1123 bool err = FD->computeJacobian(x);
1124 if (err==false)
1125 {
1126 std::cout << "**ERR**: NLNML::NLNML_Preconditioner::ComputeFineLevelJacobian:\n"
1127 << "**ERR**: NOX::Epetra::FiniteDifferenceColoring returned an error on level 0"
1128 << "**ERR**: file/line: " << __FILE__ << "/" << __LINE__ << "\n"; throw -1;
1129 }
1130
1131 t1 = GetClock();
1132 if (OutLevel()>0 && Comm().MyPID()==0)
1133 {
1134 std::cout << "nlnML (level 0): colored Finite Differencing time :" << (t1-t0) << " sec\n";
1135 std::cout << "nlnML (level 0): colored Finite Differencing number of calls to computeF : "
1136 << interface_->getnumcallscomputeF() << std::endl;
1137 fflush(stdout);
1138 }
1139 interface_->setnumcallscomputeF(ncalls);
1140 Epetra_CrsMatrix& tmp = FD->getUnderlyingMatrix();
1141 RefCountPtr<Epetra_CrsMatrix> rcptmp = rcp(&tmp); rcptmp.release();
1142 RefCountPtr<Epetra_CrsMatrix> A = NLNML::StripZeros(rcptmp,1.0e-11);
1143 return A;
1144 }
1145
1146
1147
1148 /*----------------------------------------------------------------------*
1149 | FAS-preconditioner m.gee 3/06|
1150 *----------------------------------------------------------------------*/
1151 bool NLNML::NLNML_Preconditioner::FAS_cycle(Epetra_Vector* f,
1152 Epetra_Vector* x,
1153 int level,
1154 bool* converged,
1155 double* finenorm) const
1156 {
1157 int coarsegrid = getParameter("nlnML max levels",2)-1;
1158 double thisnorm = *finenorm/10000;
1159 double tolerance = getParameter("nlnML absolute residual tolerance",1.0e-06);
1160 if (thisnorm < tolerance) thisnorm = tolerance;
1161
1162 RefCountPtr<Epetra_Vector> fbar = null;
1163 RefCountPtr<Epetra_Vector> xbar = null;
1164 RefCountPtr<Epetra_Vector> fxbar = null;
1165
1166 //=====coarsest grid==================================================
1167 if (level==coarsegrid)
1168 {
1169 fbar = rcp(new Epetra_Vector(Copy,*f,0));
1170 xbar = rcp(new Epetra_Vector(Copy,*x,0));
1171 fxbar = rcp(new Epetra_Vector(xbar->Map(),false));
1172 (*nlnlevel_)[level]->setModifiedSystem(false,NULL,NULL);
1173 (*nlnlevel_)[level]->computeF(*xbar,*fxbar,NOX::Epetra::Interface::Required::Residual);
1174 (*nlnlevel_)[level]->setModifiedSystem(true,fbar.get(),fxbar.get());
1175 int nsmooth = getParameter("nlnML nonlinear smoothing sweeps coarse level",2);
1176 if (nsmooth)
1177 *converged = (*nlnlevel_)[level]->Iterate(f,x,nsmooth,&thisnorm);
1178 x->Update(-1.0,*xbar,1.0);
1179 (*nlnlevel_)[level]->setModifiedSystem(false,NULL,NULL);
1180 return true;
1181 }
1182
1183 //=====setup FAS on this level========================================
1184 fbar = rcp(new Epetra_Vector(Copy,*f,0));
1185 xbar = rcp(new Epetra_Vector(Copy,*x,0));
1186 fxbar = rcp(new Epetra_Vector(xbar->Map(),false));
1187 (*nlnlevel_)[level]->setModifiedSystem(false,NULL,NULL);
1188 (*nlnlevel_)[level]->computeF(*xbar,*fxbar,NOX::Epetra::Interface::Required::Residual);
1189 (*nlnlevel_)[level]->setModifiedSystem(true,fbar.get(),fxbar.get());
1190
1191 //=====presmoothing on the FAS system=================================
1192 double prenorm = thisnorm;
1193 int nsmooth;
1194 if (!level) nsmooth = getParameter("nlnML nonlinear presmoothing sweeps fine level",2);
1195 else nsmooth = getParameter("nlnML nonlinear presmoothing sweeps medium level",2);
1196 if (nsmooth)
1197 *converged = (*nlnlevel_)[level]->Iterate(f,x,nsmooth,&prenorm);
1198 if (*converged)
1199 {
1200 (*nlnlevel_)[level]->setModifiedSystem(false,NULL,NULL);
1201 x->Update(-1.0,*xbar,1.0);
1202 return true;
1203 }
1204
1205 //=====restrict to next coarser level=================================
1206 RefCountPtr<Epetra_Vector> xcoarse = rcp((*nlnlevel_)[level]->restrict_to_next_coarser_level(x,level,level+1));
1207 RefCountPtr<Epetra_Vector> fcoarse = rcp((*nlnlevel_)[level]->restrict_to_next_coarser_level(f,level,level+1));
1208
1209
1210 //======call cycle on coarser level===================================
1211 bool coarseconverged=false;
1212 FAS_cycle(fcoarse.get(),xcoarse.get(),level+1,&coarseconverged,&prenorm);
1213 fcoarse = null;
1214
1215 //=====prolongate correction to this level============================
1216 RefCountPtr<Epetra_Vector> xcorrect = rcp((*nlnlevel_)[level]->prolong_to_this_level(xcoarse.get(),level,level+1));
1217 xcoarse = null;
1218
1219 //=====apply correction===============================================
1220 x->Update(1.0,*xcorrect,1.0);
1221 xcorrect = null;
1222
1223 //=====postsmoothing on the FAS system================================
1224 double postnorm = thisnorm;
1225 if (!level) nsmooth = getParameter("nlnML nonlinear postsmoothing sweeps fine level",2);
1226 else nsmooth = getParameter("nlnML nonlinear postsmoothing sweeps medium level",2);
1227 if (nsmooth)
1228 *converged = (*nlnlevel_)[level]->Iterate(f,x,nsmooth,&postnorm);
1229 (*nlnlevel_)[level]->setModifiedSystem(false,NULL,NULL);
1230 x->Update(-1.0,*xbar,1.0);
1231
1232 return true;
1233 }
1234
1235
1236
1237 /*----------------------------------------------------------------------*
1238 | FAS-solver m.gee 3/06|
1239 *----------------------------------------------------------------------*/
1240 bool NLNML::NLNML_Preconditioner::FAS_cycle_solver() const
1241 {
1242 return true;
1243 }
1244
1245
1246
1247 /*----------------------------------------------------------------------*
1248 | adaptive setup m.gee 3/06|
1249 *----------------------------------------------------------------------*/
1250 bool NLNML::NLNML_Preconditioner::Adaptivesetup(double** oldns,
1251 Epetra_CrsMatrix* Jac,
1252 int oldnumpde,
1253 int olddimns)
1254 {
1255 #ifdef HAVE_ML_MLAPI
1256
1257 // init the mlapi
1258 MLAPI::Init();
1259 MLAPI::Space FineSpace(Jac->RowMap());
1260
1261 // fine grid operator
1262 MLAPI::Operator A(FineSpace,FineSpace,Jac,false);
1263
1264 // create the cycle options
1265 Teuchos::ParameterList List;
1266 List.set("PDE equations", oldnumpde);
1267 List.set("use default null space", false);
1268 List.set("smoother: type", "symmetric Gauss-Seidel");
1269 List.set("smoother: sweeps", 1);
1270 List.set("smoother: damping factor", 1.0);
1271 List.set("coarse: type", "Amesos-KLU");
1272 List.set("coarse: max size", getParameter("nlnML coarse: max size",128));
1273 List.set("max levels", getParameter("nlnML max levels",10));
1274 List.set("adapt: max reduction", 0.05);
1275 List.set("adapt: iters fine", 30); // 35
1276 List.set("adapt: iters coarse", 25); // 20
1277 List.set("aggregation: damping", 1.33);
1278 List.set("aggregation: type", "Uncoupled"); // or "METIS", not "VBMETIS"
1279
1280
1281 // create the adaptive class
1282 MLAPI::MultiLevelAdaptiveSA Prec(A,List,oldnumpde,getParameter("nlnML max levels",10));
1283
1284 // if there's no nullspace vector, create the default one
1285 if (!(*oldns))
1286 {
1287 if (olddimns<oldnumpde) olddimns = oldnumpde;
1288 int nmyrows = Jac->NumMyRows();
1289 (*oldns) = new double[olddimns*nmyrows];
1290 for (int v=0; v<olddimns; ++v)
1291 {
1292 for (int i=0; i<nmyrows; ++i) (*oldns)[i] = 0.0;
1293 int i=v;
1294 for (; i<nmyrows; )
1295 {
1296 (*oldns)[i] = 1.0;
1297 i += olddimns;
1298 }
1299 }
1300 }
1301
1302 // set the input nullspace
1303 MLAPI::MultiVector NSfine(FineSpace,olddimns);
1304 for (int v=0; v<olddimns; ++v)
1305 for (int i=0; i<NSfine.GetMyLength(); ++i)
1306 NSfine(i,v) = (*oldns)[v*(NSfine.GetMyLength())+i];
1307 Prec.SetNullSpace(NSfine);
1308
1309 // set input numpde
1310 Prec.SetInputNumPDEEqns(oldnumpde);
1311
1312 // run adatpive setup
1313 Prec.AdaptCompute(true,getParameter("nlnML additional adaptive nullspace",0));
1314
1315 // get the new nullspace
1316 MLAPI::MultiVector NSnew = Prec.GetNullSpace();
1317 int newdimns = NSnew.GetNumVectors();
1318
1319 // delete the old one and copy the new one
1320 delete [] (*oldns);
1321 (*oldns) = new double[newdimns*NSnew.GetMyLength()];
1322
1323 for (int v=0; v<newdimns; ++v)
1324 for (int i=0; i<NSnew.GetMyLength(); ++i)
1325 (*oldns)[v*(NSnew.GetMyLength())+i] = NSnew(i,v);
1326
1327 #if 1
1328 // scale new candidates to reasonible size
1329 int dimns = getParameter("nlnML null space: dimension2",1);
1330 for (int v=dimns; v<newdimns; ++v)
1331 {
1332 double length = 0.;
1333 for (int i=0; i<NSnew.GetMyLength(); ++i)
1334 length += (*oldns)[v*(NSnew.GetMyLength())+i]*(*oldns)[v*(NSnew.GetMyLength())+i];
1335 length = sqrt(length);
1336 length /= 10.;
1337 for (int i=0; i<NSnew.GetMyLength(); ++i)
1338 (*oldns)[v*(NSnew.GetMyLength())+i] /= length;
1339 }
1340 #endif
1341
1342 // change the dimension of the nullspace
1343 dimns = newdimns;
1344 setParameter("nlnML null space: dimension",dimns);
1345
1346 #endif
1347 return true;
1348 }
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365 #endif