MFEM  v4.3.0
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
ex9p.cpp
Go to the documentation of this file.
1 // MFEM Example 9 - Parallel Version
2 // Nonlinear Constrained Optimization Modification
3 //
4 // Compile with: make ex9p
5 //
6 // Sample runs:
7 // mpirun -np 4 ex9p -m ../../data/periodic-segment.mesh -rs 3 -p 0 -o 2 -dt 0.002 -opt 1
8 // mpirun -np 4 ex9p -m ../../data/periodic-segment.mesh -rs 3 -p 0 -o 2 -dt 0.002 -opt 2
9 //
10 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 0 -rs 2 -dt 0.01 -tf 10 -opt 1
11 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 0 -rs 2 -dt 0.01 -tf 10 -opt 2
12 //
13 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 1 -rs 2 -dt 0.005 -tf 9 -opt 1
14 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 1 -rs 2 -dt 0.005 -tf 9 -opt 2
15 //
16 // mpirun -np 4 ex9p -m ../../data/amr-quad.mesh -p 1 -rs 1 -dt 0.002 -tf 9 -opt 1
17 // mpirun -np 4 ex9p -m ../../data/amr-quad.mesh -p 1 -rs 1 -dt 0.002 -tf 9 -opt 2
18 //
19 // mpirun -np 4 ex9p -m ../../data/disc-nurbs.mesh -p 1 -rs 2 -dt 0.005 -tf 9 -opt 1
20 // mpirun -np 4 ex9p -m ../../data/disc-nurbs.mesh -p 1 -rs 2 -dt 0.005 -tf 9 -opt 2
21 //
22 // mpirun -np 4 ex9p -m ../../data/disc-nurbs.mesh -p 2 -rs 2 -dt 0.01 -tf 9 -opt 1
23 // mpirun -np 4 ex9p -m ../../data/disc-nurbs.mesh -p 2 -rs 2 -dt 0.01 -tf 9 -opt 2
24 //
25 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 3 -rs 3 -dt 0.0025 -tf 9 -opt 1
26 // mpirun -np 4 ex9p -m ../../data/periodic-square.mesh -p 3 -rs 3 -dt 0.0025 -tf 9 -opt 2
27 //
28 // mpirun -np 4 ex9p -m ../../data/periodic-cube.mesh -p 0 -rs 2 -o 2 -dt 0.02 -tf 8 -opt 1
29 // mpirun -np 4 ex9p -m ../../data/periodic-cube.mesh -p 0 -rs 2 -o 2 -dt 0.02 -tf 8 -opt 2
30 
31 // Description: This example modifies the standard MFEM ex9 by adding nonlinear
32 // constrained optimization capabilities through the SLBQP and
33 // HIOP solvers. It demonstrates how a user can define a custom
34 // class OptimizationProblem that includes linear/nonlinear
35 // equality/inequality constraints. This optimization is applied
36 // as post-processing to the solution of the transport equation.
37 //
38 // Description of ex9:
39 // This example code solves the time-dependent advection equation
40 // du/dt + v.grad(u) = 0, where v is a given fluid velocity, and
41 // u0(x)=u(0,x) is a given initial condition.
42 //
43 // The example demonstrates the use of Discontinuous Galerkin (DG)
44 // bilinear forms in MFEM (face integrators), the use of explicit
45 // ODE time integrators, the definition of periodic boundary
46 // conditions through periodic meshes, as well as the use of GLVis
47 // for persistent visualization of a time-evolving solution. The
48 // saving of time-dependent data files for external visualization
49 // with VisIt (visit.llnl.gov) is also illustrated.
50 
51 #include "mfem.hpp"
52 #include <fstream>
53 #include <iostream>
54 
55 #ifndef MFEM_USE_HIOP
56 #error This example requires that MFEM is built with MFEM_USE_HIOP=YES
57 #endif
58 
59 using namespace std;
60 using namespace mfem;
61 
62 // Choice for the problem setup. The fluid velocity, initial condition and
63 // inflow boundary condition are chosen based on this parameter.
64 int problem;
65 
66 // Nonlinear optimizer.
68 
69 // Velocity coefficient
70 bool invert_velocity = false;
71 void velocity_function(const Vector &x, Vector &v);
72 
73 // Initial condition
74 double u0_function(const Vector &x);
75 
76 // Inflow boundary condition
77 double inflow_function(const Vector &x);
78 
79 // Mesh bounding box
81 
82 /// Computes C(x) = sum w_i x_i, where w is a given Vector.
83 class LinearScaleOperator : public Operator
84 {
85 private:
87  // Local weights.
88  const Vector &w;
89  // Gradient for the tdofs.
90  mutable DenseMatrix grad;
91 
92 public:
93  LinearScaleOperator(ParFiniteElementSpace &space, const Vector &weight)
94  : Operator(1, space.TrueVSize()),
95  pfes(space), w(weight), grad(1, width)
96  {
97  Vector w_glob(width);
98  pfes.Dof_TrueDof_Matrix()->MultTranspose(w, w_glob);
99  for (int i = 0; i < width; i++) { grad(0, i) = w_glob(i); }
100  }
101 
102  virtual void Mult(const Vector &x, Vector &y) const
103  {
104  Vector x_loc(w.Size());
105  pfes.GetProlongationMatrix()->Mult(x, x_loc);
106  const double loc_res = w * x_loc;
107  MPI_Allreduce(&loc_res, &y(0), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
108  }
109 
110  virtual Operator &GetGradient(const Vector &x) const
111  {
112  return grad;
113  }
114 };
115 
116 /// Nonlinear monotone bounded operator to test nonlinear inequality constraints
117 /// Computes D(x) = tanh(sum(x_i)).
118 class TanhSumOperator : public Operator
119 {
120 private:
121  // Gradient for the tdofs.
122  mutable DenseMatrix grad;
123 
124 public:
125  TanhSumOperator(ParFiniteElementSpace &space)
126  : Operator(1, space.TrueVSize()), grad(1, width) { }
127 
128  virtual void Mult(const Vector &x, Vector &y) const
129  {
130  double sum_loc = x.Sum();
131  MPI_Allreduce(&sum_loc, &y(0), 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
132  y(0) = std::tanh(y(0));
133  }
134 
135  virtual Operator &GetGradient(const Vector &x) const
136  {
137  double sum_loc = x.Sum();
138  double dtanh;
139  MPI_Allreduce(&sum_loc, &dtanh, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
140  dtanh = 1.0 - pow(std::tanh(dtanh), 2);
141 
142  for (int i = 0; i < width; i++) { grad(0, i) = dtanh; }
143  return grad;
144  }
145 };
146 
147 
148 /** Monotone and conservative a posteriori correction for transport solutions:
149  * Find x that minimizes 0.5 || x - x_HO ||^2, subject to
150  * sum w_i x_i = mass,
151  * tanh(sum(x_i_min)) <= tanh(sum(x_i)) <= tanh(sum(x_i_max)),
152  * x_i_min <= x_i <= x_i_max,
153  */
154 class OptimizedTransportProblem : public OptimizationProblem
155 {
156 private:
157  const Vector &x_HO;
158  Vector massvec, d_lo, d_hi;
159  const LinearScaleOperator LSoper;
160  const TanhSumOperator TSoper;
161 
162 public:
163  OptimizedTransportProblem(ParFiniteElementSpace &space,
164  const Vector &xho, const Vector &w, double mass,
165  const Vector &xmin, const Vector &xmax)
166  : OptimizationProblem(xho.Size(), NULL, NULL),
167  x_HO(xho), massvec(1), d_lo(1), d_hi(1),
168  LSoper(space, w), TSoper(space)
169  {
170  C = &LSoper;
171  massvec(0) = mass;
172  SetEqualityConstraint(massvec);
173 
174  D = &TSoper;
175  double lsums[2], gsums[2];
176  lsums[0] = xmin.Sum();
177  lsums[1] = xmax.Sum();
178  MPI_Allreduce(lsums, gsums, 2, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
179  d_lo(0) = std::tanh(gsums[0]);
180  d_hi(0) = std::tanh(gsums[1]);
181  MFEM_ASSERT(d_lo(0) < d_hi(0),
182  "The bounds produce an infeasible optimization problem");
183  SetInequalityConstraint(d_lo, d_hi);
184 
185  SetSolutionBounds(xmin, xmax);
186  }
187 
188  virtual double CalcObjective(const Vector &x) const
189  {
190  double loc_res = 0.0;
191  for (int i = 0; i < input_size; i++)
192  {
193  const double d = x(i) - x_HO(i);
194  loc_res += d * d;
195  }
196  loc_res *= 0.5;
197  double res;
198  MPI_Allreduce(&loc_res, &res, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
199  return res;
200  }
201 
202  virtual void CalcObjectiveGrad(const Vector &x, Vector &grad) const
203  {
204  for (int i = 0; i < input_size; i++) { grad(i) = x(i) - x_HO(i); }
205  }
206 };
207 
208 
209 /** A time-dependent operator for the right-hand side of the ODE. The DG weak
210  form of du/dt = -v.grad(u) is M du/dt = K u + b, where M and K are the mass
211  and advection matrices, and b describes the flow on the boundary. This can
212  be written as a general ODE, du/dt = M^{-1} (K u + b), and this class is
213  used to evaluate the right-hand side. */
214 class FE_Evolution : public TimeDependentOperator
215 {
216 private:
217  HypreParMatrix &M, &K;
218  const Vector &b;
219  HypreSmoother M_prec;
220  CGSolver M_solver;
221 
222  mutable Vector z;
223 
224  double dt;
225  ParBilinearForm &pbf;
226  Vector &M_rowsums;
227 
228 public:
230  const Vector &b_, ParBilinearForm &pbf_, Vector &M_rs);
231 
232  void SetTimeStep(double dt_) { dt = dt_; }
233  void SetK(HypreParMatrix &K_) { K = K_; }
234  virtual void Mult(const Vector &x, Vector &y) const;
235 
236  virtual ~FE_Evolution() { }
237 };
238 
239 
240 int main(int argc, char *argv[])
241 {
242  // 1. Initialize MPI.
243  int num_procs, myid;
244  MPI_Init(&argc, &argv);
245  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
246  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
247 
248  // 2. Parse command-line options.
249  problem = 0;
250  optimizer_type = 2;
251  const char *mesh_file = "../../data/periodic-hexagon.mesh";
252  int ser_ref_levels = 2;
253  int par_ref_levels = 0;
254  int order = 3;
255  int ode_solver_type = 3;
256  double t_final = 1.0;
257  double dt = 0.01;
258  bool visualization = true;
259  bool visit = false;
260  bool binary = false;
261  int vis_steps = 5;
262 
263  int precision = 8;
264  cout.precision(precision);
265 
266  OptionsParser args(argc, argv);
267  args.AddOption(&mesh_file, "-m", "--mesh",
268  "Mesh file to use.");
269  args.AddOption(&problem, "-p", "--problem",
270  "Problem setup to use. See options in velocity_function().");
271  args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
272  "Number of times to refine the mesh uniformly in serial.");
273  args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
274  "Number of times to refine the mesh uniformly in parallel.");
275  args.AddOption(&order, "-o", "--order",
276  "Order (degree) of the finite elements.");
277  args.AddOption(&optimizer_type, "-opt", "--optimizer",
278  "Nonlinear optimizer: 1 - SLBQP,\n\t"
279  " 2 - HIOP.");
280  args.AddOption(&ode_solver_type, "-s", "--ode-solver",
281  "ODE solver: 1 - Forward Euler,\n\t"
282  " 2 - RK2 SSP, 3 - RK3 SSP.");
283  args.AddOption(&t_final, "-tf", "--t-final",
284  "Final time; start time is 0.");
285  args.AddOption(&dt, "-dt", "--time-step",
286  "Time step.");
287  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
288  "--no-visualization",
289  "Enable or disable GLVis visualization.");
290  args.AddOption(&visit, "-visit", "--visit-datafiles", "-no-visit",
291  "--no-visit-datafiles",
292  "Save data files for VisIt (visit.llnl.gov) visualization.");
293  args.AddOption(&binary, "-binary", "--binary-datafiles", "-ascii",
294  "--ascii-datafiles",
295  "Use binary (Sidre) or ascii format for VisIt data files.");
296  args.AddOption(&vis_steps, "-vs", "--visualization-steps",
297  "Visualize every n-th timestep.");
298  args.Parse();
299  if (!args.Good())
300  {
301  if (myid == 0) { args.PrintUsage(cout); }
302  MPI_Finalize();
303  return 1;
304  }
305  if (myid == 0) { args.PrintOptions(cout); }
306 
307  // 3. Read the serial mesh from the given mesh file on all processors. We can
308  // handle geometrically periodic meshes in this code.
309  Mesh *mesh = new Mesh(mesh_file, 1, 1);
310  int dim = mesh->Dimension();
311 
312  // 4. Define the ODE solver used for time integration. Several explicit
313  // Runge-Kutta methods are available.
314  ODESolver *ode_solver = NULL;
315  switch (ode_solver_type)
316  {
317  case 1: ode_solver = new ForwardEulerSolver; break;
318  case 2: ode_solver = new RK2Solver(1.0); break;
319  case 3: ode_solver = new RK3SSPSolver; break;
320  case 4: ode_solver = new RK4Solver; break;
321  case 6: ode_solver = new RK6Solver; break;
322  default:
323  if (myid == 0)
324  {
325  cout << "Unknown ODE solver type: " << ode_solver_type << '\n';
326  }
327  delete mesh;
328  MPI_Finalize();
329  return 3;
330  }
331 
332  // 5. Refine the mesh in serial to increase the resolution. In this example
333  // we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
334  // a command-line parameter. If the mesh is of NURBS type, we convert it
335  // to a (piecewise-polynomial) high-order mesh.
336  for (int lev = 0; lev < ser_ref_levels; lev++)
337  {
338  mesh->UniformRefinement();
339  }
340  if (mesh->NURBSext)
341  {
342  mesh->SetCurvature(max(order, 1));
343  }
344  mesh->GetBoundingBox(bb_min, bb_max, max(order, 1));
345 
346  // 6. Define the parallel mesh by a partitioning of the serial mesh. Refine
347  // this mesh further in parallel to increase the resolution. Once the
348  // parallel mesh is defined, the serial mesh can be deleted.
349  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
350  delete mesh;
351  for (int lev = 0; lev < par_ref_levels; lev++)
352  {
353  pmesh->UniformRefinement();
354  }
355 
356  // 7. Define the parallel discontinuous DG finite element space on the
357  // parallel refined mesh of the given polynomial order.
358  DG_FECollection fec(order, dim, BasisType::Positive);
359  ParFiniteElementSpace *fes = new ParFiniteElementSpace(pmesh, &fec);
360 
361  HYPRE_BigInt global_vSize = fes->GlobalTrueVSize();
362  if (myid == 0)
363  {
364  cout << "Number of unknowns: " << global_vSize << endl;
365  }
366 
367  // 8. Set up and assemble the parallel bilinear and linear forms (and the
368  // parallel hypre matrices) corresponding to the DG discretization. The
369  // DGTraceIntegrator involves integrals over mesh interior faces.
373 
374  ParBilinearForm *m = new ParBilinearForm(fes);
376  ParBilinearForm *k = new ParBilinearForm(fes);
377  k->AddDomainIntegrator(new ConvectionIntegrator(velocity, -1.0));
379  new TransposeIntegrator(new DGTraceIntegrator(velocity, 1.0, -0.5)));
381  new TransposeIntegrator(new DGTraceIntegrator(velocity, 1.0, -0.5)));
382 
383  ParLinearForm *b = new ParLinearForm(fes);
385  new BoundaryFlowIntegrator(inflow, velocity, -1.0, -0.5));
386 
387  m->Assemble();
388  m->Finalize();
389  int skip_zeros = 0;
390  k->Assemble(skip_zeros);
391  k->Finalize(skip_zeros);
392  b->Assemble();
393 
397 
398  // 9. Define the initial conditions, save the corresponding grid function to
399  // a file and (optionally) save data in the VisIt format and initialize
400  // GLVis visualization.
401  ParGridFunction *u = new ParGridFunction(fes);
402  u->ProjectCoefficient(u0);
403  HypreParVector *U = u->GetTrueDofs();
404 
405  {
406  ostringstream mesh_name, sol_name;
407  mesh_name << "ex9-mesh." << setfill('0') << setw(6) << myid;
408  sol_name << "ex9-init." << setfill('0') << setw(6) << myid;
409  ofstream omesh(mesh_name.str().c_str());
410  omesh.precision(precision);
411  pmesh->Print(omesh);
412  ofstream osol(sol_name.str().c_str());
413  osol.precision(precision);
414  u->Save(osol);
415  }
416 
417  // Create data collection for solution output: either VisItDataCollection for
418  // ascii data files, or SidreDataCollection for binary data files.
419  DataCollection *dc = NULL;
420  if (visit)
421  {
422  if (binary)
423  {
424 #ifdef MFEM_USE_SIDRE
425  dc = new SidreDataCollection("Example9-Parallel", pmesh);
426 #else
427  MFEM_ABORT("Must build with MFEM_USE_SIDRE=YES for binary output.");
428 #endif
429  }
430  else
431  {
432  dc = new VisItDataCollection("Example9-Parallel", pmesh);
433  dc->SetPrecision(precision);
434  // To save the mesh using MFEM's parallel mesh format:
435  // dc->SetFormat(DataCollection::PARALLEL_FORMAT);
436  }
437  dc->RegisterField("solution", u);
438  dc->SetCycle(0);
439  dc->SetTime(0.0);
440  dc->Save();
441  }
442 
443  socketstream sout;
444  if (visualization)
445  {
446  char vishost[] = "localhost";
447  int visport = 19916;
448  sout.open(vishost, visport);
449  if (!sout)
450  {
451  if (myid == 0)
452  cout << "Unable to connect to GLVis server at "
453  << vishost << ':' << visport << endl;
454  visualization = false;
455  if (myid == 0)
456  {
457  cout << "GLVis visualization disabled.\n";
458  }
459  }
460  else
461  {
462  sout << "parallel " << num_procs << " " << myid << "\n";
463  sout.precision(precision);
464  sout << "solution\n" << *pmesh << *u;
465  sout << "pause\n";
466  sout << flush;
467  if (myid == 0)
468  cout << "GLVis visualization paused."
469  << " Press space (in the GLVis window) to resume it.\n";
470  }
471  }
472 
473  Vector M_rowsums(m->Size());
474  m->SpMat().GetRowSums(M_rowsums);
475 
476  // 10. Define the time-dependent evolution operator describing the ODE
477  // right-hand side, and perform time-integration (looping over the time
478  // iterations, ti, with a time-step dt).
479  FE_Evolution adv(*M, *K, *B, *k, M_rowsums);
480 
481  double t = 0.0;
482  adv.SetTime(t);
483  ode_solver->Init(adv);
484 
485  *u = *U;
486 
487  // Compute initial volume.
488  const double vol0_loc = M_rowsums * (*u);
489  double vol0;
490  MPI_Allreduce(&vol0_loc, &vol0, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
491 
492  bool done = false;
493  for (int ti = 0; !done; )
494  {
495  double dt_real = min(dt, t_final - t);
496  adv.SetTimeStep(dt_real);
497  ode_solver->Step(*U, t, dt_real);
498  ti++;
499 
500  done = (t >= t_final - 1e-8*dt);
501 
502  if (done || ti % vis_steps == 0)
503  {
504  if (myid == 0)
505  {
506  cout << "time step: " << ti << ", time: " << t << endl;
507  }
508 
509  // 11. Extract the parallel grid function corresponding to the finite
510  // element approximation U (the local solution on each processor).
511  *u = *U;
512 
513  if (visualization)
514  {
515  sout << "parallel " << num_procs << " " << myid << "\n";
516  sout << "solution\n" << *pmesh << *u << flush;
517  }
518 
519  if (visit)
520  {
521  dc->SetCycle(ti);
522  dc->SetTime(t);
523  dc->Save();
524  }
525  }
526  }
527 
528  // Print the error vs exact solution.
529  const double max_error = u->ComputeMaxError(u0),
530  l1_error = u->ComputeL1Error(u0),
531  l2_error = u->ComputeL2Error(u0);
532  if (myid == 0)
533  {
534  std::cout << "Linf error = " << max_error << endl
535  << "L1 error = " << l1_error << endl
536  << "L2 error = " << l2_error << endl;
537  }
538 
539  // Print error in volume.
540  const double vol_loc = M_rowsums * (*u);
541  double vol;
542  MPI_Allreduce(&vol_loc, &vol, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
543  if (myid == 0)
544  {
545  std::cout << "Vol error = " << vol - vol0 << endl;
546  }
547 
548  // 12. Save the final solution in parallel. This output can be viewed later
549  // using GLVis: "glvis -np <np> -m ex9-mesh -g ex9-final".
550  {
551  *u = *U;
552  ostringstream sol_name;
553  sol_name << "ex9-final." << setfill('0') << setw(6) << myid;
554  ofstream osol(sol_name.str().c_str());
555  osol.precision(precision);
556  u->Save(osol);
557  }
558 
559  // 13. Free the used memory.
560  delete U;
561  delete u;
562  delete B;
563  delete b;
564  delete K;
565  delete k;
566  delete M;
567  delete m;
568  delete fes;
569  delete pmesh;
570  delete ode_solver;
571  delete dc;
572 
573  MPI_Finalize();
574  return 0;
575 }
576 
577 
578 // Implementation of class FE_Evolution
580  const Vector &b_, ParBilinearForm &pbf_,
581  Vector &M_rs)
582  : TimeDependentOperator(M_.Height()),
583  M(M_), K(K_), b(b_), M_solver(M.GetComm()), z(M_.Height()),
584  pbf(pbf_), M_rowsums(M_rs)
585 {
586  M_prec.SetType(HypreSmoother::Jacobi);
587  M_solver.SetPreconditioner(M_prec);
588  M_solver.SetOperator(M);
589 
590  M_solver.iterative_mode = false;
591  M_solver.SetRelTol(1e-9);
592  M_solver.SetAbsTol(0.0);
593  M_solver.SetMaxIter(100);
594  M_solver.SetPrintLevel(0);
595 }
596 
597 void FE_Evolution::Mult(const Vector &x, Vector &y) const
598 {
599  // Get values on the ldofs.
600  ParFiniteElementSpace *pfes = pbf.ParFESpace();
601  ParGridFunction x_gf(pfes);
602  pfes->GetProlongationMatrix()->Mult(x, x_gf);
603 
604  // Compute bounds y_min, y_max for y from from x on the ldofs.
605  const int ldofs = x_gf.Size();
606  Vector y_min(ldofs), y_max(ldofs);
607  x_gf.ExchangeFaceNbrData();
608  Vector &x_nd = x_gf.FaceNbrData();
609  const int *In = pbf.SpMat().GetI(), *Jn = pbf.SpMat().GetJ();
610  for (int i = 0, k = 0; i < ldofs; i++)
611  {
612  double x_i_min = +std::numeric_limits<double>::infinity();
613  double x_i_max = -std::numeric_limits<double>::infinity();
614  for (int end = In[i+1]; k < end; k++)
615  {
616  const int j = Jn[k];
617  const double x_j = (j < ldofs) ? x(j): x_nd(j-ldofs);
618 
619  if (x_j > x_i_max) { x_i_max = x_j; }
620  if (x_j < x_i_min) { x_i_min = x_j; }
621  }
622  y_min(i) = x_i_min;
623  y_max(i) = x_i_max;
624  }
625  for (int i = 0; i < ldofs; i++)
626  {
627  y_min(i) = (y_min(i) - x_gf(i) ) / dt;
628  y_max(i) = (y_max(i) - x_gf(i) ) / dt;
629  }
630  Vector y_min_tdofs(y.Size()), y_max_tdofs(y.Size());
631  // Move the bounds to the tdofs.
632  pfes->GetRestrictionMatrix()->Mult(y_min, y_min_tdofs);
633  pfes->GetRestrictionMatrix()->Mult(y_max, y_max_tdofs);
634 
635  // Compute the high-order solution y = M^{-1} (K x + b) on the tdofs.
636  K.Mult(x, z);
637  z += b;
638  M_solver.Mult(z, y);
639 
640  // The solution y is an increment; it should not introduce new mass.
641  const double mass_y = 0.0;
642 
643  // Perform optimization on the tdofs.
644  Vector y_out(y.Size());
645  const int max_iter = 500;
646  const double rtol = 1.e-7;
647  double atol = 1.e-7;
648 
649  OptimizationSolver* optsolver = NULL;
650  if (optimizer_type == 2)
651  {
652 #ifdef MFEM_USE_HIOP
653  HiopNlpOptimizer *tmp_opt_ptr = new HiopNlpOptimizer(MPI_COMM_WORLD);
654  optsolver = tmp_opt_ptr;
655 #else
656  MFEM_ABORT("MFEM is not built with HiOp support!");
657 #endif
658  }
659  else
660  {
661  SLBQPOptimizer *slbqp = new SLBQPOptimizer(MPI_COMM_WORLD);
662  slbqp->SetBounds(y_min_tdofs, y_max_tdofs);
663  slbqp->SetLinearConstraint(M_rowsums, mass_y);
664  atol = 1.e-15;
665  optsolver = slbqp;
666  }
667 
668  OptimizedTransportProblem ot_prob(*pfes, y, M_rowsums, mass_y,
669  y_min_tdofs, y_max_tdofs);
670  optsolver->SetOptimizationProblem(ot_prob);
671 
672  optsolver->SetMaxIter(max_iter);
673  optsolver->SetAbsTol(atol);
674  optsolver->SetRelTol(rtol);
675  optsolver->SetPrintLevel(0);
676  optsolver->Mult(y, y_out);
677 
678  y = y_out;
679 
680  delete optsolver;
681 }
682 
683 
684 // Velocity coefficient
685 void velocity_function(const Vector &x, Vector &v)
686 {
687  int dim = x.Size();
688 
689  // map to the reference [-1,1] domain
690  Vector X(dim);
691  for (int i = 0; i < dim; i++)
692  {
693  double center = (bb_min[i] + bb_max[i]) * 0.5;
694  X(i) = 2 * (x(i) - center) / (bb_max[i] - bb_min[i]);
695  }
696 
697  switch (problem)
698  {
699  case 0:
700  {
701  // Translations in 1D, 2D, and 3D
702  switch (dim)
703  {
704  case 1: v(0) = (invert_velocity) ? -1.0 : 1.0; break;
705  case 2: v(0) = sqrt(2./3.); v(1) = sqrt(1./3.); break;
706  case 3: v(0) = sqrt(3./6.); v(1) = sqrt(2./6.); v(2) = sqrt(1./6.);
707  break;
708  }
709  break;
710  }
711  case 1:
712  case 2:
713  {
714  // Clockwise rotation in 2D around the origin
715  const double w = M_PI/2;
716  switch (dim)
717  {
718  case 1: v(0) = 1.0; break;
719  case 2: v(0) = w*X(1); v(1) = -w*X(0); break;
720  case 3: v(0) = w*X(1); v(1) = -w*X(0); v(2) = 0.0; break;
721  }
722  break;
723  }
724  case 3:
725  {
726  // Clockwise twisting rotation in 2D around the origin
727  const double w = M_PI/2;
728  double d = max((X(0)+1.)*(1.-X(0)),0.) * max((X(1)+1.)*(1.-X(1)),0.);
729  d = d*d;
730  switch (dim)
731  {
732  case 1: v(0) = 1.0; break;
733  case 2: v(0) = d*w*X(1); v(1) = -d*w*X(0); break;
734  case 3: v(0) = d*w*X(1); v(1) = -d*w*X(0); v(2) = 0.0; break;
735  }
736  break;
737  }
738  }
739 }
740 
741 // Initial condition
742 double u0_function(const Vector &x)
743 {
744  int dim = x.Size();
745 
746  // map to the reference [-1,1] domain
747  Vector X(dim);
748  for (int i = 0; i < dim; i++)
749  {
750  double center = (bb_min[i] + bb_max[i]) * 0.5;
751  X(i) = 2 * (x(i) - center) / (bb_max[i] - bb_min[i]);
752  }
753 
754  switch (problem)
755  {
756  case 0:
757  case 1:
758  {
759  switch (dim)
760  {
761  case 1:
762  return (X(0) > -0.15 && X(0) < 0.15) ? 1.0 : 0.0;
763  //return exp(-40.*pow(X(0)-0.0,2));
764  case 2:
765  case 3:
766  {
767  double rx = 0.45, ry = 0.25, cx = 0., cy = -0.2, w = 10.;
768  if (dim == 3)
769  {
770  const double s = (1. + 0.25*cos(2*M_PI*X(2)));
771  rx *= s;
772  ry *= s;
773  }
774  return ( erfc(w*(X(0)-cx-rx))*erfc(-w*(X(0)-cx+rx)) *
775  erfc(w*(X(1)-cy-ry))*erfc(-w*(X(1)-cy+ry)) )/16;
776  }
777  }
778  }
779  case 2:
780  {
781  double x_ = X(0), y_ = X(1), rho, phi;
782  rho = hypot(x_, y_);
783  phi = atan2(y_, x_);
784  return pow(sin(M_PI*rho),2)*sin(3*phi);
785  }
786  case 3:
787  {
788  const double f = M_PI;
789  return sin(f*X(0))*sin(f*X(1));
790  }
791  }
792  return 0.0;
793 }
794 
795 // Inflow boundary condition (zero for the problems considered in this example)
796 double inflow_function(const Vector &x)
797 {
798  switch (problem)
799  {
800  case 0:
801  case 1:
802  case 2:
803  case 3: return 0.0;
804  }
805  return 0.0;
806 }
Vector bb_max
Definition: ex9.cpp:66
void SetPrecision(int prec)
Set the precision (number of digits) used for the text output of doubles.
Conjugate gradient method.
Definition: solvers.hpp:316
virtual void Mult(const Vector &x, Vector &y) const
Matrix vector multiplication: .
void SetCycle(int c)
Set time cycle (for time-dependent simulations)
virtual void Mult(const Vector &b, Vector &x) const
Operator application: y=A(x).
Definition: solvers.cpp:616
virtual const Operator * GetProlongationMatrix() const
The returned Operator is owned by the FiniteElementSpace.
Definition: pfespace.cpp:910
int TrueVSize() const
Obsolete, kept for backward compatibility.
Definition: pfespace.hpp:422
Base abstract class for first order time dependent operators.
Definition: operator.hpp:282
void Mult(const Table &A, const Table &B, Table &C)
C = A * B (as boolean matrices)
Definition: table.cpp:476
void GetBoundingBox(Vector &min, Vector &max, int ref=2)
Returns the minimum and maximum corners of the mesh bounding box.
Definition: mesh.cpp:129
int * GetJ()
Return the array J.
Definition: sparsemat.hpp:185
virtual void Step(Vector &x, double &t, double &dt)=0
Perform a time step from time t [in] to time t [out] based on the requested step size dt [in]...
HYPRE_BigInt GlobalTrueVSize() const
Definition: pfespace.hpp:275
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
int Size() const
Returns the size of the vector.
Definition: vector.hpp:190
Abstract class for solving systems of ODEs: dx/dt = f(x,t)
Definition: ode.hpp:22
int * GetI()
Return the array I.
Definition: sparsemat.hpp:180
virtual void Save(std::ostream &out) const
Definition: pgridfunc.cpp:841
virtual void Mult(const Vector &x, Vector &y) const =0
Operator application: y=A(x).
virtual void SetTime(const double t_)
Set the current time.
Definition: operator.hpp:326
Abstract parallel finite element space.
Definition: pfespace.hpp:28
virtual void ProjectCoefficient(Coefficient &coeff)
Project coeff Coefficient to this GridFunction. The projection computation depends on the choice of t...
Definition: pgridfunc.cpp:493
bool iterative_mode
If true, use the second argument of Mult() as an initial guess.
Definition: operator.hpp:652
HypreParMatrix * ParallelAssemble()
Returns the matrix assembled on the true dofs, i.e. P^t A P.
Data collection with Sidre routines following the Conduit mesh blueprint specification.
int optimizer_type
Definition: ex9.cpp:67
Class for parallel linear form.
Definition: plinearform.hpp:26
virtual void RegisterField(const std::string &field_name, GridFunction *gf)
Add a grid function to the collection.
void SetPrintLevel(int print_lvl)
Definition: solvers.cpp:71
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
Definition: optparser.cpp:150
constexpr char vishost[]
ParFiniteElementSpace * ParFESpace() const
Return the parallel FE space associated with the ParBilinearForm.
virtual void Save()
Save the collection to disk.
double b
Definition: lissajous.cpp:42
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:9143
constexpr int visport
int Size() const
Get the size of the BilinearForm as a square matrix.
Data collection with VisIt I/O routines.
void SetMaxIter(int max_it)
Definition: solvers.hpp:100
virtual void SetCurvature(int order, bool discont=false, int space_dim=-1, int ordering=1)
Definition: mesh.cpp:4882
void SetTimeStep(double dt_)
Definition: ex9p.cpp:232
void SetLinearConstraint(const Vector &w_, double a_)
Definition: solvers.cpp:2174
void Assemble(int skip_zeros=1)
Assemble the local matrix.
void SetK(HypreParMatrix &K_)
Definition: ex9p.cpp:233
virtual void Print(std::ostream &out=mfem::out) const
Definition: pmesh.cpp:4382
Parallel smoothers in hypre.
Definition: hypre.hpp:840
void AddBdrFaceIntegrator(LinearFormIntegrator *lfi)
Adds new Boundary Face Integrator. Assumes ownership of lfi.
Definition: linearform.cpp:83
int Dimension() const
Definition: mesh.hpp:911
void PrintUsage(std::ostream &out) const
Print the usage message.
Definition: optparser.cpp:457
void SetTime(double t)
Set physical time (for time-dependent simulations)
Vector bb_min
Definition: ex9.cpp:66
A general vector function coefficient.
Wrapper for hypre&#39;s parallel vector class.
Definition: hypre.hpp:99
The classical explicit forth-order Runge-Kutta method, RK4.
Definition: ode.hpp:162
void SetAbsTol(double atol)
Definition: solvers.hpp:99
void SetRelTol(double rtol)
Definition: solvers.hpp:98
void velocity_function(const Vector &x, Vector &v)
Definition: ex9.cpp:500
virtual void Mult(const Vector &x, Vector &y) const
Matrix vector multiplication.
Definition: sparsemat.cpp:613
void AddOption(bool *var, const char *enable_short_name, const char *enable_long_name, const char *disable_short_name, const char *disable_long_name, const char *description, bool required=false)
Add a boolean option and set &#39;var&#39; to receive the value. Enable/disable tags are used to set the bool...
Definition: optparser.hpp:82
int problem
Definition: ex15.cpp:62
string space
Third-order, strong stability preserving (SSP) Runge-Kutta method.
Definition: ode.hpp:149
HYPRE_Int HYPRE_BigInt
virtual ~FE_Evolution()
Definition: ex9p.cpp:236
Adapts the HiOp functionality to the MFEM OptimizationSolver interface.
Definition: hiop.hpp:173
virtual void Mult(const Vector &x, Vector &y) const
Perform the action of the operator: y = k = f(x, t), where k solves the algebraic equation F(x...
Definition: ex18.hpp:128
FE_Evolution(FiniteElementSpace &vfes_, Operator &A_, SparseMatrix &Aflux_)
Definition: ex18.hpp:102
NURBSExtension * NURBSext
Optional NURBS mesh extension.
Definition: mesh.hpp:206
Abstract solver for OptimizationProblems.
Definition: solvers.hpp:634
bool invert_velocity
Definition: ex9.cpp:70
virtual void Finalize(int skip_zeros=1)
Finalizes the matrix initialization.
virtual const SparseMatrix * GetRestrictionMatrix() const
Get the R matrix which restricts a local dof vector to true dof vector.
Definition: pfespace.hpp:379
virtual void Mult(const Vector &xt, Vector &x) const =0
Operator application: y=A(x).
int dim
Definition: ex24.cpp:53
void AddInteriorFaceIntegrator(BilinearFormIntegrator *bfi)
Adds new interior Face Integrator. Assumes ownership of bfi.
void AddDomainIntegrator(BilinearFormIntegrator *bfi)
Adds new Domain Integrator. Assumes ownership of bfi.
void PrintOptions(std::ostream &out) const
Print the options.
Definition: optparser.cpp:327
HypreParVector * GetTrueDofs() const
Returns the true dofs in a new HypreParVector.
Definition: pgridfunc.cpp:143
double infinity()
Define a shortcut for std::numeric_limits&lt;double&gt;::infinity()
Definition: vector.hpp:46
Class for parallel bilinear form.
int open(const char hostname[], int port)
Open the socket stream on &#39;port&#39; at &#39;hostname&#39;.
double u0_function(const Vector &x)
Definition: ex9.cpp:557
RefCoord t[3]
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.hpp:330
A general function coefficient.
Vector data type.
Definition: vector.hpp:60
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:92
RefCoord s[3]
const SparseMatrix & SpMat() const
Returns a const reference to the sparse matrix.
double u(const Vector &xvec)
Definition: lor_mms.hpp:24
Class for parallel grid function.
Definition: pgridfunc.hpp:32
The classical forward Euler method.
Definition: ode.hpp:116
Abstract operator.
Definition: operator.hpp:24
Wrapper for hypre&#39;s ParCSR matrix class.
Definition: hypre.hpp:277
void SetBounds(const Vector &lo_, const Vector &hi_)
Definition: solvers.cpp:2168
virtual void SetOptimizationProblem(const OptimizationProblem &prob)
Definition: solvers.hpp:648
Class for parallel meshes.
Definition: pmesh.hpp:32
double Sum() const
Return the sum of the vector entries.
Definition: vector.cpp:891
void ParallelAssemble(Vector &tv)
Assemble the vector on the true dofs, i.e. P^t v.
Definition: plinearform.cpp:87
virtual void Init(TimeDependentOperator &f_)
Associate a TimeDependentOperator with the ODE solver.
Definition: ode.cpp:18
int main()
double inflow_function(const Vector &x)
Definition: ex9.cpp:610
void AddBdrFaceIntegrator(BilinearFormIntegrator *bfi)
Adds new boundary Face Integrator. Assumes ownership of bfi.
void GetRowSums(Vector &x) const
For all i compute .
Definition: sparsemat.cpp:1069
Arbitrary order &quot;L2-conforming&quot; discontinuous finite elements.
Definition: fe_coll.hpp:285
double f(const Vector &p)
bool Good() const
Return true if the command line options were parsed successfully.
Definition: optparser.hpp:150
alpha (q . grad u, v)