MFEM  v4.0 Finite element discretization library
pmesh-optimizer.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
2 // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
3 // reserved. See file COPYRIGHT for details.
4 //
5 // This file is part of the MFEM library. For more information and source code
6 // availability see http://mfem.org.
7 //
8 // MFEM is free software; you can redistribute it and/or modify it under the
10 // Software Foundation) version 2.1 dated February 1999.
11 //
12 // ---------------------------------------------------------------------
13 // Mesh Optimizer Miniapp: Optimize high-order meshes - Parallel Version
14 // ---------------------------------------------------------------------
15 //
16 // This miniapp performs mesh optimization using the Target-Matrix Optimization
17 // Paradigm (TMOP) by P.Knupp et al., and a global variational minimization
18 // approach. It minimizes the quantity sum_T int_T mu(J(x)), where T are the
19 // target (ideal) elements, J is the Jacobian of the transformation from the
20 // target to the physical element, and mu is the mesh quality metric. This
21 // metric can measure shape, size or alignment of the region around each
22 // quadrature point. The combination of targets & quality metrics is used to
23 // optimize the physical node positions, i.e., they must be as close as possible
24 // to the shape / size / alignment of their targets. This code also demonstrates
25 // a possible use of nonlinear operators (the class TMOP_QualityMetric, defining
26 // mu(J), and the class TMOP_Integrator, defining int mu(J)), as well as their
27 // coupling to Newton methods for solving minimization problems. Note that the
28 // utilized Newton methods are oriented towards avoiding invalid meshes with
29 // negative Jacobian determinants. Each Newton step requires the inversion of a
30 // Jacobian matrix, which is done through an inner linear solver.
31 //
32 // Compile with: make pmesh-optimizer
33 //
34 // Sample runs:
36 // mpirun -np 4 pmesh-optimizer -m blade.mesh -o 4 -rs 0 -mid 2 -tid 1 -ni 200 -ls 2 -li 100 -bnd -qt 1 -qo 8
38 // mpirun -np 4 pmesh-optimizer -m blade.mesh -o 4 -rs 0 -mid 2 -tid 1 -ni 200 -ls 2 -li 100 -bnd -qt 1 -qo 8 -lc 5000
39 // ICF shape and equal size:
40 // mpirun -np 4 pmesh-optimizer -o 3 -rs 0 -mid 9 -tid 2 -ni 200 -ls 2 -li 100 -bnd -qt 1 -qo 8
41 // ICF shape and initial size:
42 // mpirun -np 4 pmesh-optimizer -o 3 -rs 0 -mid 9 -tid 3 -ni 100 -ls 2 -li 100 -bnd -qt 1 -qo 8
43 // ICF shape:
44 // mpirun -np 4 pmesh-optimizer -o 3 -rs 0 -mid 1 -tid 1 -ni 100 -ls 2 -li 100 -bnd -qt 1 -qo 8
45 // ICF limited shape:
46 // mpirun -np 4 pmesh-optimizer -o 3 -rs 0 -mid 1 -tid 1 -ni 100 -ls 2 -li 100 -bnd -qt 1 -qo 8 -lc 10
47 // ICF combo shape + size (rings, slow convergence):
48 // mpirun -np 4 pmesh-optimizer -o 3 -rs 0 -mid 1 -tid 1 -ni 1000 -ls 2 -li 100 -bnd -qt 1 -qo 8 -cmb
49 // 3D pinched sphere shape (the mesh is in the mfem/data GitHub repository):
50 // * mpirun -np 4 pmesh-optimizer -m ../../../mfem_data/ball-pert.mesh -o 4 -rs 0 -mid 303 -tid 1 -ni 20 -ls 2 -li 500 -fix-bnd
51
52 #include "mfem.hpp"
53 #include <fstream>
54 #include <iostream>
55
56 using namespace mfem;
57 using namespace std;
58
59 double weight_fun(const Vector &x);
60
61 // Metric values are visualized by creating an L2 finite element functions and
62 // computing the metric values at the nodes.
63 void vis_metric(int order, TMOP_QualityMetric &qm, const TargetConstructor &tc,
64  ParMesh &pmesh, char *title, int position)
65 {
67  ParFiniteElementSpace fes(&pmesh, &fec, 1);
68  ParGridFunction metric(&fes);
69  InterpolateTMOP_QualityMetric(qm, tc, pmesh, metric);
70  socketstream sock;
71  if (pmesh.GetMyRank() == 0)
72  {
73  sock.open("localhost", 19916);
74  sock << "solution\n";
75  }
76  pmesh.PrintAsOne(sock);
77  metric.SaveAsOne(sock);
78  if (pmesh.GetMyRank() == 0)
79  {
80  sock << "window_title '"<< title << "'\n"
81  << "window_geometry "
82  << position << " " << 0 << " " << 600 << " " << 600 << "\n"
83  << "keys jRmclA" << endl;
84  }
85 }
86
87 class RelaxedNewtonSolver : public NewtonSolver
88 {
89 private:
90  // Quadrature points that are checked for negative Jacobians etc.
91  const IntegrationRule &ir;
93  mutable ParGridFunction x_gf;
94
95 public:
96  RelaxedNewtonSolver(const IntegrationRule &irule, ParFiniteElementSpace *pf)
97  : NewtonSolver(pf->GetComm()), ir(irule), pfes(pf) { }
98
99  virtual double ComputeScalingFactor(const Vector &x, const Vector &b) const;
100 };
101
102 double RelaxedNewtonSolver::ComputeScalingFactor(const Vector &x,
103  const Vector &b) const
104 {
105  const ParNonlinearForm *nlf = dynamic_cast<const ParNonlinearForm *>(oper);
106  MFEM_VERIFY(nlf != NULL, "invalid Operator subclass");
107  const bool have_b = (b.Size() == Height());
108
109  const int NE = pfes->GetParMesh()->GetNE(), dim = pfes->GetFE(0)->GetDim(),
110  dof = pfes->GetFE(0)->GetDof(), nsp = ir.GetNPoints();
111  Array<int> xdofs(dof * dim);
112  DenseMatrix Jpr(dim), dshape(dof, dim), pos(dof, dim);
113  Vector posV(pos.Data(), dof * dim);
114
115  Vector x_out(x.Size());
116  bool x_out_ok = false;
117  const double energy_in = nlf->GetEnergy(x);
118  double scale = 1.0, energy_out;
119  double norm0 = Norm(r);
120  x_gf.MakeTRef(pfes, x_out, 0);
121
122  // Decreases the scaling of the update until the new mesh is valid.
123  for (int i = 0; i < 12; i++)
124  {
126  x_gf.SetFromTrueVector();
127
128  energy_out = nlf->GetParGridFunctionEnergy(x_gf);
129  if (energy_out > 1.2*energy_in || std::isnan(energy_out) != 0)
130  {
131  if (print_level >= 0)
132  { cout << "Scale = " << scale << " Increasing energy." << endl; }
133  scale *= 0.5; continue;
134  }
135
136  int jac_ok = 1;
137  for (int i = 0; i < NE; i++)
138  {
139  pfes->GetElementVDofs(i, xdofs);
140  x_gf.GetSubVector(xdofs, posV);
141  for (int j = 0; j < nsp; j++)
142  {
143  pfes->GetFE(i)->CalcDShape(ir.IntPoint(j), dshape);
144  MultAtB(pos, dshape, Jpr);
145  if (Jpr.Det() <= 0.0) { jac_ok = 0; goto break2; }
146  }
147  }
148  break2:
149  int jac_ok_all;
150  MPI_Allreduce(&jac_ok, &jac_ok_all, 1, MPI_INT, MPI_LAND,
151  pfes->GetComm());
152
153  if (jac_ok_all == 0)
154  {
155  if (print_level >= 0)
156  { cout << "Scale = " << scale << " Neg det(J) found." << endl; }
157  scale *= 0.5; continue;
158  }
159
160  oper->Mult(x_out, r);
161  if (have_b) { r -= b; }
162  double norm = Norm(r);
163
164  if (norm > 1.2*norm0)
165  {
166  if (print_level >= 0)
167  { cout << "Scale = " << scale << " Norm increased." << endl; }
168  scale *= 0.5; continue;
169  }
170  else { x_out_ok = true; break; }
171  }
172
173  if (print_level >= 0)
174  {
175  cout << "Energy decrease: "
176  << (energy_in - energy_out) / energy_in * 100.0
177  << "% with " << scale << " scaling." << endl;
178  }
179
180  if (x_out_ok == false) { scale = 0.0; }
181
182  return scale;
183 }
184
185 // Allows negative Jacobians. Used in untangling metrics.
186 class DescentNewtonSolver : public NewtonSolver
187 {
188 private:
189  // Quadrature points that are checked for negative Jacobians etc.
190  const IntegrationRule &ir;
191  ParFiniteElementSpace *pfes;
192  mutable ParGridFunction x_gf;
193
194 public:
195  DescentNewtonSolver(const IntegrationRule &irule, ParFiniteElementSpace *pf)
196  : NewtonSolver(pf->GetComm()), ir(irule), pfes(pf) { }
197
198  virtual double ComputeScalingFactor(const Vector &x, const Vector &b) const;
199 };
200
201 double DescentNewtonSolver::ComputeScalingFactor(const Vector &x,
202  const Vector &b) const
203 {
204  const ParNonlinearForm *nlf = dynamic_cast<const ParNonlinearForm *>(oper);
205  MFEM_VERIFY(nlf != NULL, "invalid Operator subclass");
206
207  const int NE = pfes->GetParMesh()->GetNE(), dim = pfes->GetFE(0)->GetDim(),
208  dof = pfes->GetFE(0)->GetDof(), nsp = ir.GetNPoints();
209  Array<int> xdofs(dof * dim);
210  DenseMatrix Jpr(dim), dshape(dof, dim), pos(dof, dim);
211  Vector posV(pos.Data(), dof * dim);
212
213  x_gf.MakeTRef(pfes, x.GetData());
214  x_gf.SetFromTrueVector();
215
216  double min_detJ = infinity();
217  for (int i = 0; i < NE; i++)
218  {
219  pfes->GetElementVDofs(i, xdofs);
220  x_gf.GetSubVector(xdofs, posV);
221  for (int j = 0; j < nsp; j++)
222  {
223  pfes->GetFE(i)->CalcDShape(ir.IntPoint(j), dshape);
224  MultAtB(pos, dshape, Jpr);
225  min_detJ = min(min_detJ, Jpr.Det());
226  }
227  }
228  double min_detJ_all;
229  MPI_Allreduce(&min_detJ, &min_detJ_all, 1, MPI_DOUBLE, MPI_MIN,
230  pfes->GetComm());
231  if (print_level >= 0)
232  { cout << "Minimum det(J) = " << min_detJ_all << endl; }
233
234  Vector x_out(x.Size());
235  bool x_out_ok = false;
236  const double energy_in = nlf->GetParGridFunctionEnergy(x_gf);
237  double scale = 1.0, energy_out;
238
239  for (int i = 0; i < 7; i++)
240  {
242
243  energy_out = nlf->GetEnergy(x_out);
244  if (energy_out > energy_in || std::isnan(energy_out) != 0)
245  {
246  scale *= 0.5;
247  }
248  else { x_out_ok = true; break; }
249  }
250
251  if (print_level >= 0)
252  {
253  cout << "Energy decrease: "
254  << (energy_in - energy_out) / energy_in * 100.0
255  << "% with " << scale << " scaling." << endl;
256  }
257
258  if (x_out_ok == false) { return 0.0; }
259
260  return scale;
261 }
262
263 // Additional IntegrationRules that can be used with the --quad-type option.
266
267
268 int main (int argc, char *argv[])
269 {
270  // 0. Initialize MPI.
271  int num_procs, myid;
272  MPI_Init(&argc, &argv);
273  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
274  MPI_Comm_rank(MPI_COMM_WORLD, &myid);
275
276  // 1. Set the method's default parameters.
277  const char *mesh_file = "icf.mesh";
278  int mesh_poly_deg = 1;
279  int rs_levels = 0;
280  int rp_levels = 0;
281  double jitter = 0.0;
282  int metric_id = 1;
283  int target_id = 1;
284  double lim_const = 0.0;
287  int newton_iter = 10;
288  double newton_rtol = 1e-12;
289  int lin_solver = 2;
290  int max_lin_iter = 100;
291  bool move_bnd = true;
292  bool combomet = 0;
293  bool normalization = false;
294  bool visualization = true;
295  int verbosity_level = 0;
296
297  // 2. Parse command-line options.
298  OptionsParser args(argc, argv);
300  "Mesh file to use.");
302  "Polynomial degree of mesh finite element space.");
304  "Number of times to refine the mesh uniformly in serial.");
306  "Number of times to refine the mesh uniformly in parallel.");
308  "Random perturbation scaling factor.");
310  "Mesh optimization metric:\n\t"
311  "1 : |T|^2 -- 2D shape\n\t"
312  "2 : 0.5|T|^2/tau-1 -- 2D shape (condition number)\n\t"
313  "7 : |T-T^-t|^2 -- 2D shape+size\n\t"
314  "9 : tau*|T-T^-t|^2 -- 2D shape+size\n\t"
315  "22 : 0.5(|T|^2-2*tau)/(tau-tau_0) -- 2D untangling\n\t"
316  "50 : 0.5|T^tT|^2/tau^2-1 -- 2D shape\n\t"
317  "55 : (tau-1)^2 -- 2D size\n\t"
318  "56 : 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 2D size\n\t"
319  "58 : |T^tT|^2/(tau^2)-2*|T|^2/tau+2 -- 2D shape\n\t"
320  "77 : 0.5(tau-1/tau)^2 -- 2D size\n\t"
321  "211: (tau-1)^2-tau+sqrt(tau^2) -- 2D untangling\n\t"
322  "252: 0.5(tau-1)^2/(tau-tau_0) -- 2D untangling\n\t"
323  "301: (|T||T^-1|)/3-1 -- 3D shape\n\t"
324  "302: (|T|^2|T^-1|^2)/9-1 -- 3D shape\n\t"
325  "303: (|T|^2)/3*tau^(2/3)-1 -- 3D shape\n\t"
326  "315: (tau-1)^2 -- 3D size\n\t"
327  "316: 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 3D size\n\t"
328  "321: |T-T^-t|^2 -- 3D shape+size\n\t"
329  "352: 0.5(tau-1)^2/(tau-tau_0) -- 3D untangling");
331  "Target (ideal element) type:\n\t"
332  "1: Ideal shape, unit size\n\t"
333  "2: Ideal shape, equal size\n\t"
334  "3: Ideal shape, initial size");
335  args.AddOption(&lim_const, "-lc", "--limit-const", "Limiting constant.");
338  "1: Gauss-Lobatto\n\t"
339  "2: Gauss-Legendre\n\t"
340  "3: Closed uniform points");
342  "Order of the quadrature rule.");
344  "Maximum number of Newton iterations.");
346  "Relative tolerance for the Newton solver.");
348  "Linear solver: 0 - l1-Jacobi, 1 - CG, 2 - MINRES.");
350  "Maximum number of iterations in the linear solve.");
352  "--fix-boundary",
353  "Enable motion along horizontal and vertical boundaries.");
354  args.AddOption(&combomet, "-cmb", "--combo-met", "-no-cmb", "--no-combo-met",
355  "Combination of metrics.");
357  "--no-normalization",
358  "Make all terms in the optimization functional unitless.");
360  "--no-visualization",
361  "Enable or disable GLVis visualization.");
363  "Set the verbosity level - 0, 1, or 2.");
364  args.Parse();
365  if (!args.Good())
366  {
367  if (myid == 0) { args.PrintUsage(cout); }
368  return 1;
369  }
370  if (myid == 0) { args.PrintOptions(cout); }
371
372  // 3. Initialize and refine the starting mesh.
373  Mesh *mesh = new Mesh(mesh_file, 1, 1, false);
374  for (int lev = 0; lev < rs_levels; lev++) { mesh->UniformRefinement(); }
375  const int dim = mesh->Dimension();
376  if (myid == 0)
377  {
378  cout << "Mesh curvature: ";
379  if (mesh->GetNodes()) { cout << mesh->GetNodes()->OwnFEC()->Name(); }
380  else { cout << "(NONE)"; }
381  cout << endl;
382  }
383  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
384  delete mesh;
385  for (int lev = 0; lev < rp_levels; lev++) { pmesh->UniformRefinement(); }
386
387  // 4. Define a finite element space on the mesh. Here we use vector finite
388  // elements which are tensor products of quadratic finite elements. The
389  // number of components in the vector finite element space is specified by
390  // the last parameter of the FiniteElementSpace constructor.
392  if (mesh_poly_deg <= 0)
393  {
395  mesh_poly_deg = 2;
396  }
397  else { fec = new H1_FECollection(mesh_poly_deg, dim); }
398  ParFiniteElementSpace *pfespace = new ParFiniteElementSpace(pmesh, fec, dim);
399
400  // 5. Make the mesh curved based on the above finite element space. This
401  // means that we define the mesh elements through a fespace-based
402  // transformation of the reference element.
403  pmesh->SetNodalFESpace(pfespace);
404
405  // 6. Set up an empty right-hand side vector b, which is equivalent to b=0.
406  Vector b(0);
407
408  // 7. Get the mesh nodes (vertices and other degrees of freedom in the finite
409  // element space) as a finite element grid function in fespace. Note that
410  // changing x automatically changes the shapes of the mesh elements.
411  ParGridFunction x(pfespace);
412  pmesh->SetNodalGridFunction(&x);
413
414  // 8. Define a vector representing the minimal local mesh size in the mesh
415  // nodes. We index the nodes using the scalar version of the degrees of
416  // freedom in pfespace. Note: this is partition-dependent.
417  //
418  // In addition, compute average mesh size and total volume.
419  Vector h0(pfespace->GetNDofs());
420  h0 = infinity();
421  double vol_loc = 0.0;
422  Array<int> dofs;
423  for (int i = 0; i < pmesh->GetNE(); i++)
424  {
425  // Get the local scalar element degrees of freedom in dofs.
426  pfespace->GetElementDofs(i, dofs);
427  // Adjust the value of h0 in dofs based on the local mesh size.
428  const double hi = pmesh->GetElementSize(i);
429  for (int j = 0; j < dofs.Size(); j++)
430  {
431  h0(dofs[j]) = min(h0(dofs[j]), hi);
432  }
433  vol_loc += pmesh->GetElementVolume(i);
434  }
435  double volume;
436  MPI_Allreduce(&vol_loc, &volume, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
437  const double small_phys_size = pow(volume, 1.0 / dim) / 100.0;
438
439  // 9. Add a random perturbation to the nodes in the interior of the domain.
440  // We define a random grid function of fespace and make sure that it is
441  // zero on the boundary and its values are locally of the order of h0.
442  // The latter is based on the DofToVDof() method which maps the scalar to
443  // the vector degrees of freedom in fespace.
444  ParGridFunction rdm(pfespace);
445  rdm.Randomize();
446  rdm -= 0.25; // Shift to random values in [-0.5,0.5].
447  rdm *= jitter;
448  // Scale the random values to be of order of the local mesh size.
449  for (int i = 0; i < pfespace->GetNDofs(); i++)
450  {
451  for (int d = 0; d < dim; d++)
452  {
453  rdm(pfespace->DofToVDof(i,d)) *= h0(i);
454  }
455  }
456  Array<int> vdofs;
457  for (int i = 0; i < pfespace->GetNBE(); i++)
458  {
459  // Get the vector degrees of freedom in the boundary element.
460  pfespace->GetBdrElementVDofs(i, vdofs);
461  // Set the boundary values to zero.
462  for (int j = 0; j < vdofs.Size(); j++) { rdm(vdofs[j]) = 0.0; }
463  }
464  x -= rdm;
465  // Set the perturbation of all nodes from the true nodes.
466  x.SetTrueVector();
467  x.SetFromTrueVector();
468
469  // 10. Save the starting (prior to the optimization) mesh to a file. This
470  // output can be viewed later using GLVis: "glvis -m perturbed -np
472  {
473  ostringstream mesh_name;
474  mesh_name << "perturbed." << setfill('0') << setw(6) << myid;
475  ofstream mesh_ofs(mesh_name.str().c_str());
476  mesh_ofs.precision(8);
477  pmesh->Print(mesh_ofs);
478  }
479
480  // 11. Store the starting (prior to the optimization) positions.
481  ParGridFunction x0(pfespace);
482  x0 = x;
483
484  // 12. Form the integrator that uses the chosen metric and target.
485  double tauval = -0.1;
486  TMOP_QualityMetric *metric = NULL;
487  switch (metric_id)
488  {
489  case 1: metric = new TMOP_Metric_001; break;
490  case 2: metric = new TMOP_Metric_002; break;
491  case 7: metric = new TMOP_Metric_007; break;
492  case 9: metric = new TMOP_Metric_009; break;
493  case 22: metric = new TMOP_Metric_022(tauval); break;
494  case 50: metric = new TMOP_Metric_050; break;
495  case 55: metric = new TMOP_Metric_055; break;
496  case 56: metric = new TMOP_Metric_056; break;
497  case 58: metric = new TMOP_Metric_058; break;
498  case 77: metric = new TMOP_Metric_077; break;
499  case 211: metric = new TMOP_Metric_211; break;
500  case 252: metric = new TMOP_Metric_252(tauval); break;
501  case 301: metric = new TMOP_Metric_301; break;
502  case 302: metric = new TMOP_Metric_302; break;
503  case 303: metric = new TMOP_Metric_303; break;
504  case 315: metric = new TMOP_Metric_315; break;
505  case 316: metric = new TMOP_Metric_316; break;
506  case 321: metric = new TMOP_Metric_321; break;
507  case 352: metric = new TMOP_Metric_352(tauval); break;
508  default:
509  if (myid == 0) { cout << "Unknown metric_id: " << metric_id << endl; }
510  return 3;
511  }
513  switch (target_id)
514  {
515  case 1: target_t = TargetConstructor::IDEAL_SHAPE_UNIT_SIZE; break;
516  case 2: target_t = TargetConstructor::IDEAL_SHAPE_EQUAL_SIZE; break;
517  case 3: target_t = TargetConstructor::IDEAL_SHAPE_GIVEN_SIZE; break;
518  default:
519  if (myid == 0) { cout << "Unknown target_id: " << target_id << endl; }
520  return 3;
521  }
522  TargetConstructor *target_c;
523  target_c = new TargetConstructor(target_t, MPI_COMM_WORLD);
524  target_c->SetNodes(x0);
525  TMOP_Integrator *he_nlf_integ;
526  he_nlf_integ = new TMOP_Integrator(metric, target_c);
527
528  // 13. Setup the quadrature rule for the non-linear form integrator.
529  const IntegrationRule *ir = NULL;
530  const int geom_type = pfespace->GetFE(0)->GetGeomType();
532  {
533  case 1: ir = &IntRulesLo.Get(geom_type, quad_order); break;
534  case 2: ir = &IntRules.Get(geom_type, quad_order); break;
535  case 3: ir = &IntRulesCU.Get(geom_type, quad_order); break;
536  default:
537  if (myid == 0) { cout << "Unknown quad_type: " << quad_type << endl; }
538  return 3;
539  }
540  if (myid == 0)
541  { cout << "Quadrature points per cell: " << ir->GetNPoints() << endl; }
542  he_nlf_integ->SetIntegrationRule(*ir);
543
544  if (normalization) { he_nlf_integ->ParEnableNormalization(x0); }
545
546  // 14. Limit the node movement.
547  // The limiting distances can be given by a general function of space.
548  ParGridFunction dist(pfespace);
549  dist = 1.0;
550  // The small_phys_size is relevant only with proper normalization.
551  if (normalization) { dist = small_phys_size; }
552  ConstantCoefficient lim_coeff(lim_const);
553  if (lim_const != 0.0) { he_nlf_integ->EnableLimiting(x0, dist, lim_coeff); }
554
555  // 15. Setup the final NonlinearForm (which defines the integral of interest,
556  // its first and second derivatives). Here we can use a combination of
557  // metrics, i.e., optimize the sum of two integrals, where both are
558  // scaled by used-defined space-dependent weights. Note that there are
559  // no command-line options for the weights and the type of the second
560  // metric; one should update those in the code.
561  ParNonlinearForm a(pfespace);
562  ConstantCoefficient *coeff1 = NULL;
563  TMOP_QualityMetric *metric2 = NULL;
564  TargetConstructor *target_c2 = NULL;
566
567  if (combomet == 1)
568  {
569  // TODO normalization of combinations.
570  // We will probably drop this example and replace it with adaptivity.
571  if (normalization) { MFEM_ABORT("Not implemented."); }
572
573  // First metric.
574  coeff1 = new ConstantCoefficient(1.0);
575  he_nlf_integ->SetCoefficient(*coeff1);
577
578  // Second metric.
579  metric2 = new TMOP_Metric_077;
580  target_c2 = new TargetConstructor(
582  target_c2->SetVolumeScale(0.01);
583  target_c2->SetNodes(x0);
584  TMOP_Integrator *he_nlf_integ2;
585  he_nlf_integ2 = new TMOP_Integrator(metric2, target_c2);
586  he_nlf_integ2->SetIntegrationRule(*ir);
587
588  // Weight of metric2.
589  he_nlf_integ2->SetCoefficient(coeff2);
591  }
593
594  const double init_energy = a.GetParGridFunctionEnergy(x);
595
596  // 16. Visualize the starting mesh and metric values.
597  if (visualization)
598  {
599  char title[] = "Initial metric values";
600  vis_metric(mesh_poly_deg, *metric, *target_c, *pmesh, title, 0);
601  }
602
603  // 17. Fix all boundary nodes, or fix only a given component depending on the
604  // boundary attributes of the given mesh. Attributes 1/2/3 correspond to
605  // fixed x/y/z components of the node. Attribute 4 corresponds to an
606  // entirely fixed node. Other boundary attributes do not affect the node
607  // movement boundary conditions.
608  if (move_bnd == false)
609  {
610  Array<int> ess_bdr(pmesh->bdr_attributes.Max());
611  ess_bdr = 1;
612  a.SetEssentialBC(ess_bdr);
613  }
614  else
615  {
616  const int nd = pfespace->GetBE(0)->GetDof();
617  int n = 0;
618  for (int i = 0; i < pmesh->GetNBE(); i++)
619  {
620  const int attr = pmesh->GetBdrElement(i)->GetAttribute();
621  MFEM_VERIFY(!(dim == 2 && attr == 3),
622  "Boundary attribute 3 must be used only for 3D meshes. "
623  "Adjust the attributes (1/2/3/4 for fixed x/y/z/all "
625  if (attr == 1 || attr == 2 || attr == 3) { n += nd; }
626  if (attr == 4) { n += nd * dim; }
627  }
628  Array<int> ess_vdofs(n), vdofs;
629  n = 0;
630  for (int i = 0; i < pmesh->GetNBE(); i++)
631  {
632  const int attr = pmesh->GetBdrElement(i)->GetAttribute();
633  pfespace->GetBdrElementVDofs(i, vdofs);
634  if (attr == 1) // Fix x components.
635  {
636  for (int j = 0; j < nd; j++)
637  { ess_vdofs[n++] = vdofs[j]; }
638  }
639  else if (attr == 2) // Fix y components.
640  {
641  for (int j = 0; j < nd; j++)
642  { ess_vdofs[n++] = vdofs[j+nd]; }
643  }
644  else if (attr == 3) // Fix z components.
645  {
646  for (int j = 0; j < nd; j++)
647  { ess_vdofs[n++] = vdofs[j+2*nd]; }
648  }
649  else if (attr == 4) // Fix all components.
650  {
651  for (int j = 0; j < vdofs.Size(); j++)
652  { ess_vdofs[n++] = vdofs[j]; }
653  }
654  }
655  a.SetEssentialVDofs(ess_vdofs);
656  }
657
658  // 18. As we use the Newton method to solve the resulting nonlinear system,
659  // here we setup the linear solver for the system's Jacobian.
660  Solver *S = NULL;
661  const double linsol_rtol = 1e-12;
662  if (lin_solver == 0)
663  {
664  S = new DSmoother(1, 1.0, max_lin_iter);
665  }
666  else if (lin_solver == 1)
667  {
668  CGSolver *cg = new CGSolver(MPI_COMM_WORLD);
669  cg->SetMaxIter(max_lin_iter);
670  cg->SetRelTol(linsol_rtol);
671  cg->SetAbsTol(0.0);
672  cg->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
673  S = cg;
674  }
675  else
676  {
677  MINRESSolver *minres = new MINRESSolver(MPI_COMM_WORLD);
678  minres->SetMaxIter(max_lin_iter);
679  minres->SetRelTol(linsol_rtol);
680  minres->SetAbsTol(0.0);
681  minres->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
682  S = minres;
683  }
684
685  // 19. Compute the minimum det(J) of the starting mesh.
686  tauval = infinity();
687  const int NE = pmesh->GetNE();
688  for (int i = 0; i < NE; i++)
689  {
691  for (int j = 0; j < ir->GetNPoints(); j++)
692  {
693  transf->SetIntPoint(&ir->IntPoint(j));
694  tauval = min(tauval, transf->Jacobian().Det());
695  }
696  }
697  double minJ0;
698  MPI_Allreduce(&tauval, &minJ0, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
699  tauval = minJ0;
700  if (myid == 0)
701  { cout << "Minimum det(J) of the original mesh is " << tauval << endl; }
702
703  // 20. Finally, perform the nonlinear optimization.
704  NewtonSolver *newton = NULL;
705  if (tauval > 0.0)
706  {
707  tauval = 0.0;
708  newton = new RelaxedNewtonSolver(*ir, pfespace);
709  if (myid == 0)
710  { cout << "RelaxedNewtonSolver is used (as all det(J) > 0)." << endl; }
711  }
712  else
713  {
714  if ( (dim == 2 && metric_id != 22 && metric_id != 252) ||
715  (dim == 3 && metric_id != 352) )
716  {
717  if (myid == 0)
718  { cout << "The mesh is inverted. Use an untangling metric." << endl; }
719  return 3;
720  }
721  double h0min = h0.Min(), h0min_all;
722  MPI_Allreduce(&h0min, &h0min_all, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
723  tauval -= 0.01 * h0min_all; // Slightly below minJ0 to avoid div by 0.
724  newton = new DescentNewtonSolver(*ir, pfespace);
725  if (myid == 0)
726  { cout << "DescentNewtonSolver is used (as some det(J) < 0)." << endl; }
727  }
728  newton->SetPreconditioner(*S);
729  newton->SetMaxIter(newton_iter);
730  newton->SetRelTol(newton_rtol);
731  newton->SetAbsTol(0.0);
732  newton->SetPrintLevel(verbosity_level >= 1 ? 1 : -1);
733  newton->SetOperator(a);
734  newton->Mult(b, x.GetTrueVector());
735  x.SetFromTrueVector();
736  if (myid == 0 && newton->GetConverged() == false)
737  {
738  cout << "NewtonIteration: rtol = " << newton_rtol << " not achieved."
739  << endl;
740  }
741  delete newton;
742
743  // 21. Save the optimized mesh to a file. This output can be viewed later
744  // using GLVis: "glvis -m optimized -np num_mpi_tasks".
745  {
746  ostringstream mesh_name;
747  mesh_name << "optimized." << setfill('0') << setw(6) << myid;
748  ofstream mesh_ofs(mesh_name.str().c_str());
749  mesh_ofs.precision(8);
750  pmesh->Print(mesh_ofs);
751  }
752
753  // 22. Compute the amount of energy decrease.
754  const double fin_energy = a.GetParGridFunctionEnergy(x);
755  double metric_part = fin_energy;
756  if (lim_const != 0.0)
757  {
758  lim_coeff.constant = 0.0;
759  metric_part = a.GetParGridFunctionEnergy(x);
760  lim_coeff.constant = lim_const;
761  }
762  if (myid == 0)
763  {
764  cout << "Initial strain energy: " << init_energy
765  << " = metrics: " << init_energy
766  << " + limiting term: " << 0.0 << endl;
767  cout << " Final strain energy: " << fin_energy
768  << " = metrics: " << metric_part
769  << " + limiting term: " << fin_energy - metric_part << endl;
770  cout << "The strain energy decreased by: " << setprecision(12)
771  << (init_energy - fin_energy) * 100.0 / init_energy << " %." << endl;
772  }
773
774  // 23. Visualize the final mesh and metric values.
775  if (visualization)
776  {
777  char title[] = "Final metric values";
778  vis_metric(mesh_poly_deg, *metric, *target_c, *pmesh, title, 600);
779  }
780
781  // 23. Visualize the mesh displacement.
782  if (visualization)
783  {
784  x0 -= x;
785  socketstream sock;
786  if (myid == 0)
787  {
788  sock.open("localhost", 19916);
789  sock << "solution\n";
790  }
791  pmesh->PrintAsOne(sock);
792  x0.SaveAsOne(sock);
793  if (myid == 0)
794  {
795  sock << "window_title 'Displacements'\n"
796  << "window_geometry "
797  << 1200 << " " << 0 << " " << 600 << " " << 600 << "\n"
798  << "keys jRmclA" << endl;
799  }
800  }
801
802  // 24. Free the used memory.
803  delete S;
804  delete target_c2;
805  delete metric2;
806  delete coeff1;
807  delete target_c;
808  delete metric;
809  delete pfespace;
810  delete fec;
811  delete pmesh;
812
813  MPI_Finalize();
814  return 0;
815 }
816
817 // Defined with respect to the icf mesh.
818 double weight_fun(const Vector &x)
819 {
820  const double r = sqrt(x(0)*x(0) + x(1)*x(1) + 1e-12);
821  const double den = 0.002;
822  double l2 = 0.2 + 0.5 * (std::tanh((r-0.16)/den) - std::tanh((r-0.17)/den)
823  + std::tanh((r-0.23)/den) - std::tanh((r-0.24)/den));
824  return l2;
825 }
int GetNPoints() const
Returns the number of the points in the integration rule.
Definition: intrules.hpp:237
int Size() const
Logical size of the array.
Definition: array.hpp:118
Shifted barrier form of metric 56 (area, ideal barrier metric), 2D.
Definition: tmop.hpp:325
Shifted barrier form of 3D metric 16 (volume, ideal barrier metric), 3D.
Definition: tmop.hpp:443
Definition: solvers.hpp:111
int GetNDofs() const
Returns number of degrees of freedom.
Definition: fespace.hpp:344
Class for an integration rule - an Array of IntegrationPoint.
Definition: intrules.hpp:85
int DofToVDof(int dof, int vd, int ndofs=-1) const
Definition: fespace.cpp:143
Shape &amp; volume, ideal barrier metric, 3D.
Definition: tmop.hpp:427
Data type for scaled Jacobi-type smoother of sparse matrix.
const IntegrationRule & Get(int GeomType, int Order)
Returns an integration rule for given GeomType and Order.
Definition: intrules.cpp:877
void SetFromTrueVector()
Shortcut for calling SetFromTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:139
Subclass constant coefficient.
Definition: coefficient.hpp:67
int GetNBE() const
Returns number of boundary elements.
Definition: mesh.hpp:679
void InterpolateTMOP_QualityMetric(TMOP_QualityMetric &metric, const TargetConstructor &tc, const Mesh &mesh, GridFunction &metric_gf)
Interpolates the metric&#39;s values at the nodes of metric_gf.
Definition: tmop.cpp:1259
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:377
double Det() const
Definition: densemat.cpp:472
void SetIntPoint(const IntegrationPoint *ip)
Definition: eltrans.hpp:53
aka closed Newton-Cotes
Definition: intrules.hpp:287
void SaveAsOne(std::ostream &out=mfem::out)
Merge the local grid functions.
Definition: pgridfunc.cpp:504
Container class for integration rules.
Definition: intrules.hpp:299
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:361
int Size() const
Returns the size of the vector.
Definition: vector.hpp:150
void SetVolumeScale(double vol_scale)
Used by target type IDEAL_SHAPE_EQUAL_SIZE. The default volume scale is 1.
Definition: tmop.hpp:589
Parallel non-linear operator on the true dofs.
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:152
Volume metric, 3D.
Definition: tmop.hpp:393
Area, ideal barrier metric, 2D.
Definition: tmop.hpp:289
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:676
Abstract parallel finite element space.
Definition: pfespace.hpp:28
MINRES method.
Definition: solvers.hpp:221
void Randomize(int seed=0)
Set random values in the vector.
Definition: vector.cpp:690
int main(int argc, char *argv[])
Definition: ex1.cpp:58
double * GetData() const
Return a pointer to the beginning of the Vector data.
Definition: vector.hpp:159
double weight_fun(const Vector &x)
Shape &amp; area, ideal barrier metric, 2D.
Definition: tmop.hpp:168
void vis_metric(int order, TMOP_QualityMetric &qm, const TargetConstructor &tc, Mesh &mesh, char *title, int position)
Shifted barrier form of metric 2 (shape, ideal barrier metric), 2D.
Definition: tmop.hpp:200
void add(const Vector &v1, const Vector &v2, Vector &v)
Definition: vector.cpp:238
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:271
double GetEnergy(const ParGridFunction &x) const
Compute the energy of a ParGridFunction.
Geometry::Type GetGeomType() const
Returns the Geometry::Type of the reference element.
Definition: fe.hpp:308
Abstract class for local mesh quality metrics in the target-matrix optimization paradigm (TMOP) by P...
Definition: tmop.hpp:24
IntegrationPoint & IntPoint(int i)
Returns a reference to the i-th integration point.
Definition: intrules.hpp:240
void SetTrueVector()
Shortcut for calling GetTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:133
int dim
Definition: ex3.cpp:48
void SetPrintLevel(int print_lvl)
Definition: solvers.cpp:67
void EnableLimiting(const GridFunction &n0, const GridFunction &dist, Coefficient &w0, TMOP_LimiterFunction *lfunc=NULL)
Adds a limiting term to the integrator (general version).
Definition: tmop.cpp:867
int GetNBE() const
Returns number of boundary elements in the mesh.
Definition: fespace.hpp:383
void SetCoefficient(Coefficient &w1)
Sets a scaling Coefficient for the quality metric term of the integrator.
Definition: tmop.hpp:663
Area metric, 2D.
Definition: tmop.hpp:235
Volume, ideal barrier metric, 3D.
Definition: tmop.hpp:409
void PrintAsOne(std::ostream &out=mfem::out)
Definition: pmesh.cpp:3992
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:7591
const DenseMatrix & Jacobian()
Return the Jacobian matrix of the transformation at the currently set IntegrationPoint, using the method SetIntPoint().
Definition: eltrans.hpp:68
void SetNodes(const GridFunction &n)
Set the nodes to be used in the target-matrix construction.
Definition: tmop.hpp:586
void SetMaxIter(int max_it)
Definition: solvers.hpp:63
T Max() const
Find the maximal element in the array, using the comparison operator &lt; for class T.
Definition: array.cpp:68
Newton&#39;s method for solving F(x)=b for a given operator F.
Definition: solvers.hpp:259
virtual void Print(std::ostream &out=mfem::out) const
Definition: pmesh.cpp:3863
Version of QuadraticFECollection with positive basis functions.
Definition: fe_coll.hpp:383
int GetAttribute() const
Return element&#39;s attribute.
Definition: element.hpp:55
void SetNodalFESpace(FiniteElementSpace *nfes)
Definition: mesh.cpp:3621
int GetConverged() const
Definition: solvers.hpp:67
int Dimension() const
Definition: mesh.hpp:713
void PrintUsage(std::ostream &out) const
Definition: optparser.cpp:434
virtual void Mult(const Vector &b, Vector &x) const
Solve the nonlinear system with right-hand side b.
Definition: solvers.cpp:1250
double GetParGridFunctionEnergy(const Vector &x) const
Compute the energy corresponding to the state x.
const Vector & GetTrueVector() const
Definition: gridfunc.hpp:121
double GetElementSize(int i, int type=0)
Get the size of the i-th element relative to the perfect reference element.
Definition: mesh.cpp:74
void SetAbsTol(double atol)
Definition: solvers.hpp:62
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:179
int GetMyRank() const
Definition: pmesh.hpp:225
void SetRelTol(double rtol)
Definition: solvers.hpp:61
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:219
Untangling metric, 2D.
Definition: tmop.hpp:306
int GetDof() const
Returns the number of degrees of freedom in the finite element.
Definition: fe.hpp:311
Area, ideal barrier metric, 2D.
Definition: tmop.hpp:252
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)
Definition: optparser.hpp:76
Shape &amp; area metric, 2D.
Definition: tmop.hpp:184
virtual void GetElementDofs(int i, Array< int > &dofs) const
Returns indexes of degrees of freedom in array dofs for i&#39;th element.
Definition: pfespace.cpp:456
void GetElementTransformation(int i, IsoparametricTransformation *ElTr)
Definition: mesh.cpp:336
void SetIntegrationRule(const IntegrationRule &irule)
Prescribe a fixed IntegrationRule to use.
Definition: nonlininteg.hpp:40
const FiniteElement * GetFE(int i) const
Returns pointer to the FiniteElement associated with i&#39;th element.
Definition: fespace.cpp:1541
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
double infinity()
Define a shortcut for std::numeric_limits&lt;double&gt;::infinity()
Definition: vector.hpp:42
void SetEssentialBC(const Array< int > &bdr_attr_is_ess, Vector *rhs=NULL)
Specify essential boundary conditions.
int open(const char hostname[], int port)
class for C-function coefficient
void MultAtB(const DenseMatrix &A, const DenseMatrix &B, DenseMatrix &AtB)
Multiply the transpose of a matrix A with a matrix B: At*B.
Definition: densemat.cpp:3725
Vector data type.
Definition: vector.hpp:48
void GetNodes(Vector &node_coord) const
Definition: mesh.cpp:5837
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:88
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:83
TargetType
Target-matrix construction algorithms supported by this class.
Definition: tmop.hpp:530
void SetEssentialVDofs(const Array< int > &ess_vdofs_list)
(DEPRECATED) Specify essential boundary conditions.
Base class for solvers.
Definition: operator.hpp:279
Class for parallel grid function.
Definition: pgridfunc.hpp:32
const FiniteElement * GetBE(int i) const
Returns pointer to the FiniteElement for the i&#39;th boundary element.
Definition: fespace.cpp:1781
void GetBdrElementVDofs(int i, Array< int > &vdofs) const
Returns indexes of degrees of freedom for i&#39;th boundary element.
Definition: fespace.cpp:178
void SetNodalGridFunction(GridFunction *nodes, bool make_owner=false)
Definition: mesh.cpp:3633
Base class representing target-matrix construction algorithms for mesh optimization via the target-ma...
Definition: tmop.hpp:526
Class for parallel meshes.
Definition: pmesh.hpp:32
A global object with all integration rules (defined in intrules.cpp)
Definition: intrules.hpp:368
void ParEnableNormalization(const ParGridFunction &x)
Definition: tmop.cpp:1198
double GetElementVolume(int i)
Definition: mesh.cpp:101
const Element * GetBdrElement(int i) const
Definition: mesh.hpp:748
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:345
Metric without a type, 2D.
Definition: tmop.hpp:76
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.cpp:1239
Arbitrary order &quot;L2-conforming&quot; discontinuous finite elements.
Definition: fe_coll.hpp:134
bool Good() const
Definition: optparser.hpp:122
A TMOP integrator class based on any given TMOP_QualityMetric and TargetConstructor.
Definition: tmop.hpp:607