Debian Codegraph @

packages/nox/test/epetra/1Dfem/1DfemTransient.C

raw
1 // @HEADER
2 // *****************************************************************************
3 // NOX: An Object-Oriented Nonlinear Solver Package
4 //
5 // Copyright 2002 NTESS and the NOX contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 // 1D Transient Finite Element Test Problem
11 /* Solves the nonlinear PDE for u(x,t):
12 *
13 * du d2u 8
14 * --- = --- + --- u**2( 1 - u )
15 * dt dx2 k*k
16 *
17 * subject to u(-infinity,t) = 1
18 * u(-infinity,t) = 0
19 * and
20 * u(x,0) = 0.5 * ( 1 - tanh(x/k) )
21 *
22 * with d representing partial differentiation.
23 *
24 * An exact closed solution is the following:
25 *
26 * x - 2t/k
27 * u(x,t) = 0.5 * ( 1 - tanh(--------- ) )
28 * k
29 *
30 * This problem is examined with a variety of time integration schemes in:
31 * "Studies on the Convergence of Various Time-Integration Schemes for the
32 * Radiation-Diffusion Problem," Curtis C. Ober & John N. Shadid, in prep.
33 *
34 * In this example, only a 1st-order fully implicit (backward Euler)
35 * time integration scheme is considered currently.
36 *
37 * Values for k, time step size, and finite spatial extent are specified in
38 * the constructor initialization list in FiniteElementProblem.C using
39 * variables factor, dt and xmin,xmax, respectively.
40 * The number of time steps to be taken is specified by variable
41 * maxTimeSteps below.
42 */
43
44 #undef PRINT_RESULTS_TO_FILES
45
46 // NOX Objects
47 #include "NOX.H"
48 #include "NOX_Epetra.H"
49
50 // Trilinos Objects
51 #ifdef HAVE_MPI
52 #include "Epetra_MpiComm.h"
53 #else
54 #include "Epetra_SerialComm.h"
55 #endif
56 #include "Epetra_Map.h"
57 #include "Epetra_Vector.h"
58 #include "Epetra_RowMatrix.h"
59 #include "Epetra_CrsMatrix.h"
60 #include "Epetra_Map.h"
61 #include "Epetra_LinearProblem.h"
62 #include "AztecOO.h"
63 #include "Teuchos_StandardCatchMacros.hpp"
64
65 // User's application specific files
66 #include "1DfemInterface.H"
67
68 using namespace std;
69
70 // ------------------------------------------------------------------------
71 // ------------------ Declaration with definition ------------------------
72 // ------------------------------------------------------------------------
73 class TransientInterface : public Interface
74 {
75 public:
76 // ---------------------------
77 // -------- Constructor ------
78 // ---------------------------
79 TransientInterface(int NumGlobalElements, Epetra_Comm& Comm,
80 double xmin = 0.0, double xmax = 1.0) :
81 Interface(NumGlobalElements, Comm, xmin, xmax),
82 dt(0.0),
83 oldSolution(0),
84 exactSolution(0)
85 {
86 // Must reinitialize the solution now that the inherited class exists
87 initializeSoln();
88
89 oldSolution = new Epetra_Vector(*initialSolution);
90 };
91
92 // ---------------------------
93 // --------- Destructor ------
94 // ---------------------------
95 virtual ~TransientInterface()
96 {
97 delete oldSolution;
98 if (exactSolution) delete exactSolution;
99 };
100
101 // ---------------------------
102 // - Matrix and Residual Fills
103 // ---------------------------
104 bool evaluate(NOX::Epetra::Interface::Required::FillType flag,
105 const Epetra_Vector* soln,
106 Epetra_Vector* tmp_rhs,
107 Epetra_RowMatrix* tmp_matrix)
108 {
109
110 //Determine what to fill (F or Jacobian)
111 bool fillF = false;
112 bool fillMatrix = false;
113 if (tmp_rhs != 0) {
114 fillF = true;
115 rhs = tmp_rhs;
116 }
117 else {
118 fillMatrix = true;
119 }
120
121 // "flag" can be used to determine how accurate your fill of F should be
122 // depending on why we are calling evaluate (Could be using computeF to
123 // populate a Jacobian or Preconditioner).
124 if (flag == NOX::Epetra::Interface::Required::Residual) {
125 // Do nothing for now
126 }
127 else if (flag == NOX::Epetra::Interface::Required::Jac) {
128 // Do nothing for now
129 }
130 else if (flag == NOX::Epetra::Interface::Required::Prec) {
131 // Do nothing for now
132 }
133 else if (flag == NOX::Epetra::Interface::Required::User) {
134 // Do nothing for now
135 }
136
137 // Create the overlapped solution and position vectors
138 Epetra_Vector u(*OverlapMap);
139 Epetra_Vector uold(*OverlapMap);
140 Epetra_Vector xvec(*OverlapMap);
141
142 // Export Solution to Overlap vector
143 u.Import(*soln, *Importer, Insert);
144 uold.Import(*oldSolution, *Importer, Insert);
145 xvec.Import(*xptr, *Importer, Insert);
146
147 // Declare required variables
148 int OverlapNumMyElements = OverlapMap->NumMyElements();
149
150 int row, column;
151 double jac;
152 double xx[2];
153 double uu[2];
154 double uuold[2];
155 Basis basis;
156
157 // Zero out the objects that will be filled
158 if (fillF)
159 rhs->PutScalar(0.0);
160 if (fillMatrix)
161 jacobian->PutScalar(0.0);
162
163 // Loop Over # of Finite Elements on Processor
164 for (int ne=0; ne < OverlapNumMyElements-1; ne++) {
165
166 // Loop Over Gauss Points
167 for(int gp=0; gp < 2; gp++) {
168 // Get the solution and coordinates at the nodes
169 xx[0]=xvec[ne];
170 xx[1]=xvec[ne+1];
171 uu[0]=u[ne];
172 uu[1]=u[ne+1];
173 uuold[0]=uold[ne];
174 uuold[1]=uold[ne+1];
175 // Calculate the basis function at the gauss point
176 basis.computeBasis(gp, xx, uu, uuold);
177
178 // Loop over Nodes in Element
179 for (int i=0; i< 2; i++) {
180 row=OverlapMap->GID(ne+i);
181 //printf("Proc=%d GlobalRow=%d LocalRow=%d Owned=%d\n",
182 // MyPID, row, ne+i,StandardMap.MyGID(row));
183 if (StandardMap->MyGID(row)) {
184 if (fillF) {
185 (*rhs)[StandardMap->LID(OverlapMap->GID(ne+i))]+=
186 +basis.wt*basis.dx*(
187 (basis.uu-basis.uuold)/dt*basis.phi[i] +
188 (1.0/(basis.dx*basis.dx))*basis.duu*basis.dphide[i] -
189 8.0/factor/factor*basis.uu*basis.uu*
190 (1.0-basis.uu)*basis.phi[i]);
191 }
192 }
193 // Loop over Trial Functions
194 if (fillMatrix) {
195 for(int j=0;j < 2; j++) {
196 if (StandardMap->MyGID(row)) {
197 column=OverlapMap->GID(ne+j);
198 jac=basis.wt*basis.dx*(
199 basis.phi[j]/dt*basis.phi[i] +
200 (1.0/(basis.dx*basis.dx))*
201 basis.dphide[j]*basis.dphide[i] -
202 8.0/factor/factor*
203 (2.0*basis.uu-3.0*basis.uu*basis.uu)*
204 basis.phi[j]*basis.phi[i]);
205 jacobian->SumIntoGlobalValues(row, 1, &jac, &column);
206 }
207 }
208 }
209 }
210 }
211 }
212
213 // Insert Boundary Conditions and modify Jacobian and function (F)
214 // U(0)=1
215 if (MyPID==0) {
216 if (fillF)
217 (*rhs)[0]= (*soln)[0] - 1.0;
218 if (fillMatrix) {
219 column=0;
220 jac=1.0;
221 jacobian->ReplaceGlobalValues(0, 1, &jac, &column);
222 column=1;
223 jac=0.0;
224 jacobian->ReplaceGlobalValues(0, 1, &jac, &column);
225 }
226 }
227
228 // Insert Boundary Conditions and modify Jacobian and function (F)
229 // U(xmax)=0
230 if (MyPID==NumProc-1) {
231 if (fillF)
232 (*rhs)[NumMyElements-1]= (*soln)[NumMyElements-1] - 0.0;
233 if (fillMatrix) {
234 row=NumGlobalElements-1;
235 column=row;
236 jac=1.0;
237 jacobian->ReplaceGlobalValues(row, 1, &jac, &column);
238 column--;
239 jac=0.0;
240 jacobian->ReplaceGlobalValues(row, 1, &jac, &column);
241 }
242 }
243
244 // Sync up processors to be safe
245 Comm->Barrier();
246
247 jacobian->FillComplete();
248
249 return true;
250 }
251
252 // ---------------------------
253 // --------------- Set desired initial condition / initial guess
254 // ---------------------------
255 bool initializeSoln()
256 {
257 Epetra_Vector& x = *xptr;
258
259 double arg;
260 for(int i=0; i<NumMyElements; i++) {
261 arg = x[i]/factor;
262 (*initialSolution)[i] = (1.0 - ( exp(arg) - exp(-arg) ) /
263 ( exp(arg) + exp(-arg) )) / 2.0;
264 }
265 return true;
266 }
267
268 // Reset problem for next parameter (time) step.
269 // For now, this simply updates oldsoln with the given Epetra_Vector
270 bool reset(const Epetra_Vector& x)
271 { *oldSolution = x; return true; };
272
273 // Return a reference to the Epetra_Vector with the old solution
274 Epetra_Vector& getOldSoln()
275 { return *oldSolution; };
276
277 // ---------------------------
278 // --------------- Return a reference to the Epetra_Vector
279 // --------------- with the exact analytic solution
280 // ---------------------------
281 Epetra_Vector& getExactSoln(double time)
282 {
283 // Create the exact solution vector only if needed and if not already
284 // created.
285 if( !exactSolution )
286 exactSolution = new Epetra_Vector(*xptr);
287
288 Epetra_Vector& x = *xptr;
289
290 for(int i=0; i<NumMyElements; i++)
291 (*exactSolution)[i] =
292 (1.0 - tanh( (x[i]-2.0*time/factor)/factor )) / 2.0;
293
294 return *exactSolution;
295 }
296
297 // Accesor function for setting time step
298 void setdt( double dt_ ) { dt = dt_; }
299
300 // Accesor function for time obtaining step
301 double getdt() { return dt; }
302
303 private:
304
305 double dt; // Time step size
306
307 Epetra_Vector *oldSolution;
308 Epetra_Vector *exactSolution;
309
310 };
311
312
313 // ------------------------------------------------------------------------
314 // --------------------------- Main Program -----------------------------
315 // ------------------------------------------------------------------------
316 int main(int argc, char *argv[])
317 {
318 // Initialize MPI
319 #ifdef HAVE_MPI
320 MPI_Init(&argc,&argv);
321 #endif
322
323 // Create a communicator for Epetra objects
324 #ifdef HAVE_MPI
325 Epetra_MpiComm Comm( MPI_COMM_WORLD );
326 #else
327 Epetra_SerialComm Comm;
328 #endif
329
330 // Get the process ID and the total number of processors
331 int MyPID = Comm.MyPID();
332 int NumProc = Comm.NumProc();
333
334 bool verbose = false;
335 // Check for verbose output
336 if (argc>1)
337 if (argv[1][0]=='-' && argv[1][1]=='v')
338 verbose = true;
339
340 // Get the number of elements from the command line
341 int NumGlobalElements = 0;
342 if ((argc > 2) && (verbose))
343 NumGlobalElements = atoi(argv[2]) + 1;
344 else if ((argc > 1) && (!verbose))
345 NumGlobalElements = atoi(argv[1]) + 1;
346 else
347 NumGlobalElements = 101;
348
349 bool success = false;
350 try {
351 // The number of unknowns must be at least equal to the
352 // number of processors.
353 if (NumGlobalElements < NumProc) {
354 std::cout << "numGlobalBlocks = " << NumGlobalElements
355 << " cannot be < number of processors = " << NumProc << std::endl;
356 throw std::runtime_error("NOX Error");
357 }
358
359 // Create the interface between NOX and the application
360 // This object is derived from NOX::Epetra::Interface
361 Teuchos::RCP<TransientInterface> interface =
362 Teuchos::rcp(new TransientInterface(NumGlobalElements, Comm, -20.0, 20.0));
363 double dt = 0.10;
364 interface->setdt(dt);
365
366 // Set the PDE nonlinear coefficient for this problem
367 interface->setPDEfactor(1.0);
368
369 // Get the vector from the Problem
370 Teuchos::RCP<Epetra_Vector> soln = interface->getSolution();
371 NOX::Epetra::Vector noxSoln(soln, NOX::Epetra::Vector::CreateView);
372
373 // Begin Nonlinear Solver ************************************
374
375 // Create the top level parameter list
376 Teuchos::RCP<Teuchos::ParameterList> nlParamsPtr =
377 Teuchos::rcp(new Teuchos::ParameterList);
378 Teuchos::ParameterList& nlParams = *(nlParamsPtr.get());
379
380 // Set the nonlinear solver method
381 nlParams.set("Nonlinear Solver", "Line Search Based");
382
383 // Set the printing parameters in the "Printing" sublist
384 Teuchos::ParameterList& printParams = nlParams.sublist("Printing");
385 printParams.set("MyPID", MyPID);
386 printParams.set("Output Precision", 3);
387 printParams.set("Output Processor", 0);
388 if (verbose)
389 printParams.set("Output Information",
390 NOX::Utils::OuterIteration +
391 NOX::Utils::OuterIterationStatusTest +
392 NOX::Utils::InnerIteration +
393 NOX::Utils::LinearSolverDetails +
394 NOX::Utils::Parameters +
395 NOX::Utils::Details +
396 NOX::Utils::Warning +
397 NOX::Utils::Debug +
398 NOX::Utils::Error);
399 else
400 printParams.set("Output Information", NOX::Utils::Error);
401
402 // Create a print class for controlling output below
403 NOX::Utils utils(printParams);
404
405 // Sublist for line search
406 Teuchos::ParameterList& searchParams = nlParams.sublist("Line Search");
407 searchParams.set("Method", "Full Step");
408
409 // Sublist for direction
410 Teuchos::ParameterList& dirParams = nlParams.sublist("Direction");
411 dirParams.set("Method", "Newton");
412 Teuchos::ParameterList& newtonParams = dirParams.sublist("Newton");
413 newtonParams.set("Forcing Term Method", "Constant");
414
415 // Sublist for linear solver for the Newton method
416 Teuchos::ParameterList& lsParams = newtonParams.sublist("Linear Solver");
417 lsParams.set("Aztec Solver", "GMRES");
418 lsParams.set("Max Iterations", 800);
419 lsParams.set("Tolerance", 1e-4);
420 lsParams.set("Preconditioner", "AztecOO");
421
422 // Create all possible Epetra_Operators.
423 // 1. User supplied (Epetra_RowMatrix)
424 Teuchos::RCP<Epetra_RowMatrix> Analytic = interface->getJacobian();
425 // 2. Matrix-Free (Epetra_Operator)
426
427 // Four constructors to create the Linear System
428 Teuchos::RCP<NOX::Epetra::Interface::Required> iReq = interface;
429 Teuchos::RCP<NOX::Epetra::Interface::Jacobian> iJac = interface;
430 Teuchos::RCP<NOX::Epetra::LinearSystemAztecOO> linSys =
431 Teuchos::rcp(new NOX::Epetra::LinearSystemAztecOO(printParams, lsParams,
432 iReq, iJac, Analytic,
433 noxSoln));
434
435 // Create the Group
436 Teuchos::RCP<NOX::Epetra::Group> grpPtr =
437 Teuchos::rcp(new NOX::Epetra::Group(printParams,
438 iReq,
439 noxSoln,
440 linSys));
441 NOX::Epetra::Group& grp = *(grpPtr.get());
442
443 // Create the convergence tests
444 Teuchos::RCP<NOX::StatusTest::NormF> absresid =
445 Teuchos::rcp(new NOX::StatusTest::NormF(1.0e-8));
446 Teuchos::RCP<NOX::StatusTest::NormF> relresid =
447 Teuchos::rcp(new NOX::StatusTest::NormF(grp, 1.0e-2));
448 Teuchos::RCP<NOX::StatusTest::NormUpdate> update =
449 Teuchos::rcp(new NOX::StatusTest::NormUpdate(1.0e-5));
450 Teuchos::RCP<NOX::StatusTest::NormWRMS> wrms =
451 Teuchos::rcp(new NOX::StatusTest::NormWRMS(1.0e-2, 1.0e-8));
452 Teuchos::RCP<NOX::StatusTest::Combo> converged =
453 Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::AND));
454 converged->addStatusTest(absresid);
455 converged->addStatusTest(relresid);
456 converged->addStatusTest(wrms);
457 converged->addStatusTest(update);
458 Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters =
459 Teuchos::rcp(new NOX::StatusTest::MaxIters(20));
460 Teuchos::RCP<NOX::StatusTest::FiniteValue> fv =
461 Teuchos::rcp(new NOX::StatusTest::FiniteValue);
462 Teuchos::RCP<NOX::StatusTest::Combo> combo =
463 Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR));
464 combo->addStatusTest(fv);
465 combo->addStatusTest(converged);
466 combo->addStatusTest(maxiters);
467
468 // Initialize time integration parameters
469 int maxTimeSteps = 10;
470 int timeStep = 0;
471 double time = 0.0;
472
473 #ifdef PRINT_RESULTS_TO_FILES
474 // Print initial solution
475 char file_name[25];
476 FILE *ifp;
477 int NumMyElements = soln.Map().NumMyElements();
478 (void) sprintf(file_name, "output.%d_%d",MyPID,timeStep);
479 ifp = fopen(file_name, "w");
480 for (int i=0; i<NumMyElements; i++)
481 fprintf(ifp, "%d %E %E\n", soln.Map().MinMyGID()+i,
482 interface->getMesh()[i], soln[i]);
483 fclose(ifp);
484 #endif
485
486 // Create the solver
487 Teuchos::RCP<NOX::Solver::Generic> solver =
488 NOX::Solver::buildSolver(grpPtr, combo, nlParamsPtr);
489
490 // Overall status flag
491 int ierr = 0;
492
493 // Time integration loop
494 while(timeStep < maxTimeSteps) {
495 timeStep++;
496 time += dt;
497
498 utils.out() << "Time Step: " << timeStep << ",\tTime: " << time << std::endl;
499
500 NOX::StatusTest::StatusType status = solver->solve();
501
502 // Check for convergence
503 if (status != NOX::StatusTest::Converged) {
504 ierr++;
505 if (utils.isPrintType(NOX::Utils::Error))
506 utils.out() << "Nonlinear solver failed to converge!" << std::endl;
507 }
508
509
510 // Get the Epetra_Vector with the final solution from the solver
511 const NOX::Epetra::Group& finalGroup = dynamic_cast<const NOX::Epetra::Group&>(solver->getSolutionGroup());
512 const Epetra_Vector& finalSolution = (dynamic_cast<const NOX::Epetra::Vector&>(finalGroup.getX())).getEpetraVector();
513 //Epetra_Vector& exactSolution = interface->getExactSoln(time);
514
515
516 // End Nonlinear Solver **************************************
517
518 #ifdef PRINT_RESULTS_TO_FILES
519 // Print solution
520 (void) sprintf(file_name, "output.%d_%d",MyPID,timeStep);
521 ifp = fopen(file_name, "w");
522 for (int i=0; i<NumMyElements; i++)
523 fprintf(ifp, "%d %E %E %E\n", soln.Map().MinMyGID()+i,
524 interface->getMesh()[i], finalSolution[i],exactSolution[i]);
525 fclose(ifp);
526 #endif
527
528 interface->reset(finalSolution);
529 grp.setX(finalSolution);
530 solver->reset(grp.getX(), combo);
531 grp.computeF();
532
533 } // end time step while loop
534
535 // Output the parameter list
536 if (utils.isPrintType(NOX::Utils::Parameters)) {
537 utils.out() << std::endl << "Final Parameters" << std::endl
538 << "****************" << std::endl;
539 solver->getList().print(utils.out());
540 utils.out() << std::endl;
541 }
542
543 // Test for convergence
544
545 #ifndef HAVE_MPI
546 // 1. Linear solve iterations on final time step (30)- SERIAL TEST ONLY!
547 // The number of linear iterations changes with # of procs.
548 if (const_cast<Teuchos::ParameterList&>(solver->getList()).sublist("Direction").sublist("Newton").sublist("Linear Solver").sublist("Output").get("Total Number of Linear Iterations",0) != 30) {
549 ierr = 1;
550 }
551 #endif
552 // 2. Nonlinear solve iterations on final time step (3)
553 if (const_cast<Teuchos::ParameterList&>(solver->getList()).sublist("Output").get("Nonlinear Iterations", 0) != 3)
554 ierr = 2;
555
556 success = ierr==0;
557 // Summarize test results
558 if (success)
559 utils.out() << "Test passed!" << std::endl;
560 else
561 utils.out() << "Test failed!" << std::endl;
562 }
563 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
564
565 #ifdef HAVE_MPI
566 MPI_Finalize();
567 #endif
568
569 return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
570 }