MFEM  v3.4
Finite element discretization library
mesh-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
9 // terms of the GNU Lesser General Public License (as published by the Free
10 // Software Foundation) version 2.1 dated February 1999.
11 //
12 // --------------------------------------------------
13 // Mesh Optimizer Miniapp: Optimize high-order meshes
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 mesh-optimizer
33 //
34 // Sample runs:
35 // Blade shape:
36 // mesh-optimizer -m blade.mesh -o 4 -rs 0 -mid 2 -tid 1 -ni 200 -ls 2 -li 100 -bnd -qt 1 -qo 8
37 // Blade limited shape:
38 // mesh-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 // mesh-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 // mesh-optimizer -o 3 -rs 0 -mid 9 -tid 3 -ni 100 -ls 2 -li 100 -bnd -qt 1 -qo 8
43 // ICF shape:
44 // mesh-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 // mesh-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 // mesh-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 // * mesh-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  Mesh &mesh, char *title, int position)
65 {
67  FiniteElementSpace fes(&mesh, &fec, 1);
68  GridFunction metric(&fes);
69  InterpolateTMOP_QualityMetric(qm, tc, mesh, metric);
70  osockstream sock(19916, "localhost");
71  sock << "solution\n";
72  mesh.Print(sock);
73  metric.Save(sock);
74  sock.send();
75  sock << "window_title '"<< title << "'\n"
76  << "window_geometry "
77  << position << " " << 0 << " " << 600 << " " << 600 << "\n"
78  << "keys jRmclA" << endl;
79 }
80 
81 class RelaxedNewtonSolver : public NewtonSolver
82 {
83 private:
84  // Quadrature points that are checked for negative Jacobians etc.
85  const IntegrationRule &ir;
86  FiniteElementSpace *fes;
87  mutable GridFunction x_gf;
88 
89 public:
90  RelaxedNewtonSolver(const IntegrationRule &irule, FiniteElementSpace *f)
91  : ir(irule), fes(f) { }
92 
93  virtual double ComputeScalingFactor(const Vector &x, const Vector &b) const;
94 };
95 
96 double RelaxedNewtonSolver::ComputeScalingFactor(const Vector &x,
97  const Vector &b) const
98 {
99  const NonlinearForm *nlf = dynamic_cast<const NonlinearForm *>(oper);
100  MFEM_VERIFY(nlf != NULL, "invalid Operator subclass");
101  const bool have_b = (b.Size() == Height());
102 
103  const int NE = fes->GetMesh()->GetNE(), dim = fes->GetFE(0)->GetDim(),
104  dof = fes->GetFE(0)->GetDof(), nsp = ir.GetNPoints();
105  Array<int> xdofs(dof * dim);
106  DenseMatrix Jpr(dim), dshape(dof, dim), pos(dof, dim);
107  Vector posV(pos.Data(), dof * dim);
108 
109  Vector x_out(x.Size());
110  bool x_out_ok = false;
111  const double energy_in = nlf->GetEnergy(x);
112  double scale = 1.0, energy_out;
113  double norm0 = Norm(r);
114  x_gf.MakeTRef(fes, x_out, 0);
115 
116  // Decreases the scaling of the update until the new mesh is valid.
117  for (int i = 0; i < 12; i++)
118  {
119  add(x, -scale, c, x_out);
120  x_gf.SetFromTrueVector();
121 
122  energy_out = nlf->GetGridFunctionEnergy(x_gf);
123  if (energy_out > 1.2*energy_in || isnan(energy_out) != 0)
124  {
125  if (print_level >= 0)
126  { cout << "Scale = " << scale << " Increasing energy." << endl; }
127  scale *= 0.5; continue;
128  }
129 
130  int jac_ok = 1;
131  for (int i = 0; i < NE; i++)
132  {
133  fes->GetElementVDofs(i, xdofs);
134  x_gf.GetSubVector(xdofs, posV);
135  for (int j = 0; j < nsp; j++)
136  {
137  fes->GetFE(i)->CalcDShape(ir.IntPoint(j), dshape);
138  MultAtB(pos, dshape, Jpr);
139  if (Jpr.Det() <= 0.0) { jac_ok = 0; goto break2; }
140  }
141  }
142  break2:
143  if (jac_ok == 0)
144  {
145  if (print_level >= 0)
146  { cout << "Scale = " << scale << " Neg det(J) found." << endl; }
147  scale *= 0.5; continue;
148  }
149 
150  oper->Mult(x_out, r);
151  if (have_b) { r -= b; }
152  double norm = Norm(r);
153 
154  if (norm > 1.2*norm0)
155  {
156  if (print_level >= 0)
157  { cout << "Scale = " << scale << " Norm increased." << endl; }
158  scale *= 0.5; continue;
159  }
160  else { x_out_ok = true; break; }
161  }
162 
163  if (print_level >= 0)
164  {
165  cout << "Energy decrease: "
166  << (energy_in - energy_out) / energy_in * 100.0
167  << "% with " << scale << " scaling." << endl;
168  }
169 
170  if (x_out_ok == false) { scale = 0.0; }
171 
172  return scale;
173 }
174 
175 // Allows negative Jacobians. Used in untangling metrics.
176 class DescentNewtonSolver : public NewtonSolver
177 {
178 private:
179  // Quadrature points that are checked for negative Jacobians etc.
180  const IntegrationRule &ir;
181  FiniteElementSpace *fes;
182  mutable GridFunction x_gf;
183 
184 public:
185  DescentNewtonSolver(const IntegrationRule &irule, FiniteElementSpace *f)
186  : ir(irule), fes(f) { }
187 
188  virtual double ComputeScalingFactor(const Vector &x, const Vector &b) const;
189 };
190 
191 double DescentNewtonSolver::ComputeScalingFactor(const Vector &x,
192  const Vector &b) const
193 {
194  const NonlinearForm *nlf = dynamic_cast<const NonlinearForm *>(oper);
195  MFEM_VERIFY(nlf != NULL, "invalid Operator subclass");
196 
197  const int NE = fes->GetMesh()->GetNE(), dim = fes->GetFE(0)->GetDim(),
198  dof = fes->GetFE(0)->GetDof(), nsp = ir.GetNPoints();
199  Array<int> xdofs(dof * dim);
200  DenseMatrix Jpr(dim), dshape(dof, dim), pos(dof, dim);
201  Vector posV(pos.Data(), dof * dim);
202 
203  x_gf.MakeTRef(fes, x.GetData());
204  x_gf.SetFromTrueVector();
205 
206  double min_detJ = infinity();
207  for (int i = 0; i < NE; i++)
208  {
209  fes->GetElementVDofs(i, xdofs);
210  x_gf.GetSubVector(xdofs, posV);
211  for (int j = 0; j < nsp; j++)
212  {
213  fes->GetFE(i)->CalcDShape(ir.IntPoint(j), dshape);
214  MultAtB(pos, dshape, Jpr);
215  min_detJ = min(min_detJ, Jpr.Det());
216  }
217  }
218  cout << "Minimum det(J) = " << min_detJ << endl;
219 
220  Vector x_out(x.Size());
221  bool x_out_ok = false;
222  const double energy_in = nlf->GetGridFunctionEnergy(x_gf);
223  double scale = 1.0, energy_out;
224 
225  for (int i = 0; i < 7; i++)
226  {
227  add(x, -scale, c, x_out);
228 
229  energy_out = nlf->GetEnergy(x_out);
230  if (energy_out > energy_in || isnan(energy_out) != 0)
231  {
232  scale *= 0.5;
233  }
234  else { x_out_ok = true; break; }
235  }
236 
237  cout << "Energy decrease: " << (energy_in - energy_out) / energy_in * 100.0
238  << "% with " << scale << " scaling." << endl;
239 
240  if (x_out_ok == false) { return 0.0;}
241 
242  return scale;
243 }
244 
245 // Additional IntegrationRules that can be used with the --quad-type option.
248 
249 
250 int main (int argc, char *argv[])
251 {
252  // 0. Set the method's default parameters.
253  const char *mesh_file = "icf.mesh";
254  int mesh_poly_deg = 1;
255  int rs_levels = 0;
256  double jitter = 0.0;
257  int metric_id = 1;
258  int target_id = 1;
259  double lim_const = 0.0;
260  int quad_type = 1;
261  int quad_order = 8;
262  int newton_iter = 10;
263  double newton_rtol = 1e-12;
264  int lin_solver = 2;
265  int max_lin_iter = 100;
266  bool move_bnd = true;
267  bool combomet = 0;
268  bool visualization = true;
269  int verbosity_level = 0;
270 
271  // 1. Parse command-line options.
272  OptionsParser args(argc, argv);
273  args.AddOption(&mesh_file, "-m", "--mesh",
274  "Mesh file to use.");
275  args.AddOption(&mesh_poly_deg, "-o", "--order",
276  "Polynomial degree of mesh finite element space.");
277  args.AddOption(&rs_levels, "-rs", "--refine-serial",
278  "Number of times to refine the mesh uniformly in serial.");
279  args.AddOption(&jitter, "-ji", "--jitter",
280  "Random perturbation scaling factor.");
281  args.AddOption(&metric_id, "-mid", "--metric-id",
282  "Mesh optimization metric:\n\t"
283  "1 : |T|^2 -- 2D shape\n\t"
284  "2 : 0.5|T|^2/tau-1 -- 2D shape (condition number)\n\t"
285  "7 : |T-T^-t|^2 -- 2D shape+size\n\t"
286  "9 : tau*|T-T^-t|^2 -- 2D shape+size\n\t"
287  "22 : 0.5(|T|^2-2*tau)/(tau-tau_0) -- 2D untangling\n\t"
288  "50 : 0.5|T^tT|^2/tau^2-1 -- 2D shape\n\t"
289  "55 : (tau-1)^2 -- 2D size\n\t"
290  "56 : 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 2D size\n\t"
291  "58 : |T^tT|^2/(tau^2)-2*|T|^2/tau+2 -- 2D shape\n\t"
292  "77 : 0.5(tau-1/tau)^2 -- 2D size\n\t"
293  "211: (tau-1)^2-tau+sqrt(tau^2) -- 2D untangling\n\t"
294  "252: 0.5(tau-1)^2/(tau-tau_0) -- 2D untangling\n\t"
295  "301: (|T||T^-1|)/3-1 -- 3D shape\n\t"
296  "302: (|T|^2|T^-1|^2)/9-1 -- 3D shape\n\t"
297  "303: (|T|^2)/3*tau^(2/3)-1 -- 3D shape\n\t"
298  "315: (tau-1)^2 -- 3D size\n\t"
299  "316: 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 3D size\n\t"
300  "321: |T-T^-t|^2 -- 3D shape+size\n\t"
301  "352: 0.5(tau-1)^2/(tau-tau_0) -- 3D untangling");
302  args.AddOption(&target_id, "-tid", "--target-id",
303  "Target (ideal element) type:\n\t"
304  "1: Ideal shape, unit size\n\t"
305  "2: Ideal shape, equal size\n\t"
306  "3: Ideal shape, initial size");
307  args.AddOption(&lim_const, "-lc", "--limit-const", "Limiting constant.");
308  args.AddOption(&quad_type, "-qt", "--quad-type",
309  "Quadrature rule type:\n\t"
310  "1: Gauss-Lobatto\n\t"
311  "2: Gauss-Legendre\n\t"
312  "3: Closed uniform points");
313  args.AddOption(&quad_order, "-qo", "--quad_order",
314  "Order of the quadrature rule.");
315  args.AddOption(&newton_iter, "-ni", "--newton-iters",
316  "Maximum number of Newton iterations.");
317  args.AddOption(&newton_rtol, "-rtol", "--newton-rel-tolerance",
318  "Relative tolerance for the Newton solver.");
319  args.AddOption(&lin_solver, "-ls", "--lin-solver",
320  "Linear solver: 0 - l1-Jacobi, 1 - CG, 2 - MINRES.");
321  args.AddOption(&max_lin_iter, "-li", "--lin-iter",
322  "Maximum number of iterations in the linear solve.");
323  args.AddOption(&move_bnd, "-bnd", "--move-boundary", "-fix-bnd",
324  "--fix-boundary",
325  "Enable motion along horizontal and vertical boundaries.");
326  args.AddOption(&combomet, "-cmb", "--combo-met", "-no-cmb", "--no-combo-met",
327  "Combination of metrics.");
328  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
329  "--no-visualization",
330  "Enable or disable GLVis visualization.");
331  args.AddOption(&verbosity_level, "-vl", "--verbosity-level",
332  "Set the verbosity level - 0, 1, or 2.");
333  args.Parse();
334  if (!args.Good())
335  {
336  args.PrintUsage(cout);
337  return 1;
338  }
339  args.PrintOptions(cout);
340 
341  // 2. Initialize and refine the starting mesh.
342  Mesh *mesh = new Mesh(mesh_file, 1, 1, false);
343  for (int lev = 0; lev < rs_levels; lev++) { mesh->UniformRefinement(); }
344  const int dim = mesh->Dimension();
345  cout << "Mesh curvature: ";
346  if (mesh->GetNodes()) { cout << mesh->GetNodes()->OwnFEC()->Name(); }
347  else { cout << "(NONE)"; }
348  cout << endl;
349 
350  // 3. Define a finite element space on the mesh. Here we use vector finite
351  // elements which are tensor products of quadratic finite elements. The
352  // number of components in the vector finite element space is specified by
353  // the last parameter of the FiniteElementSpace constructor.
355  if (mesh_poly_deg <= 0)
356  {
357  fec = new QuadraticPosFECollection;
358  mesh_poly_deg = 2;
359  }
360  else { fec = new H1_FECollection(mesh_poly_deg, dim); }
361  FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec, dim);
362 
363  // 4. Make the mesh curved based on the above finite element space. This
364  // means that we define the mesh elements through a fespace-based
365  // transformation of the reference element.
366  mesh->SetNodalFESpace(fespace);
367 
368  // 5. Set up an empty right-hand side vector b, which is equivalent to b=0.
369  Vector b(0);
370 
371  // 6. Get the mesh nodes (vertices and other degrees of freedom in the finite
372  // element space) as a finite element grid function in fespace. Note that
373  // changing x automatically changes the shapes of the mesh elements.
374  GridFunction *x = mesh->GetNodes();
375 
376  // 7. Define a vector representing the minimal local mesh size in the mesh
377  // nodes. We index the nodes using the scalar version of the degrees of
378  // freedom in fespace.
379  Vector h0(fespace->GetNDofs());
380  h0 = infinity();
381  Array<int> dofs;
382  for (int i = 0; i < mesh->GetNE(); i++)
383  {
384  // Get the local scalar element degrees of freedom in dofs.
385  fespace->GetElementDofs(i, dofs);
386  // Adjust the value of h0 in dofs based on the local mesh size.
387  for (int j = 0; j < dofs.Size(); j++)
388  {
389  h0(dofs[j]) = min(h0(dofs[j]), mesh->GetElementSize(i));
390  }
391  }
392 
393  // 8. Add a random perturbation to the nodes in the interior of the domain.
394  // We define a random grid function of fespace and make sure that it is
395  // zero on the boundary and its values are locally of the order of h0.
396  // The latter is based on the DofToVDof() method which maps the scalar to
397  // the vector degrees of freedom in fespace.
398  GridFunction rdm(fespace);
399  rdm.Randomize();
400  rdm -= 0.25; // Shift to random values in [-0.5,0.5].
401  rdm *= jitter;
402  // Scale the random values to be of order of the local mesh size.
403  for (int i = 0; i < fespace->GetNDofs(); i++)
404  {
405  for (int d = 0; d < dim; d++)
406  {
407  rdm(fespace->DofToVDof(i,d)) *= h0(i);
408  }
409  }
410  Array<int> vdofs;
411  for (int i = 0; i < fespace->GetNBE(); i++)
412  {
413  // Get the vector degrees of freedom in the boundary element.
414  fespace->GetBdrElementVDofs(i, vdofs);
415  // Set the boundary values to zero.
416  for (int j = 0; j < vdofs.Size(); j++) { rdm(vdofs[j]) = 0.0; }
417  }
418  *x -= rdm;
419  // Set the perturbation of all nodes from the true nodes.
420  x->SetTrueVector();
421  x->SetFromTrueVector();
422 
423  // 9. Save the starting (prior to the optimization) mesh to a file. This
424  // output can be viewed later using GLVis: "glvis -m perturbed.mesh".
425  {
426  ofstream mesh_ofs("perturbed.mesh");
427  mesh->Print(mesh_ofs);
428  }
429 
430  // 10. Store the starting (prior to the optimization) positions.
431  GridFunction x0(fespace);
432  x0 = *x;
433 
434  // 11. Form the integrator that uses the chosen metric and target.
435  double tauval = -0.1;
436  TMOP_QualityMetric *metric = NULL;
437  switch (metric_id)
438  {
439  case 1: metric = new TMOP_Metric_001; break;
440  case 2: metric = new TMOP_Metric_002; break;
441  case 7: metric = new TMOP_Metric_007; break;
442  case 9: metric = new TMOP_Metric_009; break;
443  case 22: metric = new TMOP_Metric_022(tauval); break;
444  case 50: metric = new TMOP_Metric_050; break;
445  case 55: metric = new TMOP_Metric_055; break;
446  case 56: metric = new TMOP_Metric_056; break;
447  case 58: metric = new TMOP_Metric_058; break;
448  case 77: metric = new TMOP_Metric_077; break;
449  case 211: metric = new TMOP_Metric_211; break;
450  case 252: metric = new TMOP_Metric_252(tauval); break;
451  case 301: metric = new TMOP_Metric_301; break;
452  case 302: metric = new TMOP_Metric_302; break;
453  case 303: metric = new TMOP_Metric_303; break;
454  case 315: metric = new TMOP_Metric_315; break;
455  case 316: metric = new TMOP_Metric_316; break;
456  case 321: metric = new TMOP_Metric_321; break;
457  case 352: metric = new TMOP_Metric_352(tauval); break;
458  default: cout << "Unknown metric_id: " << metric_id << endl; return 3;
459  }
461  switch (target_id)
462  {
463  case 1: target_t = TargetConstructor::IDEAL_SHAPE_UNIT_SIZE; break;
464  case 2: target_t = TargetConstructor::IDEAL_SHAPE_EQUAL_SIZE; break;
465  case 3: target_t = TargetConstructor::IDEAL_SHAPE_GIVEN_SIZE; break;
466  default: cout << "Unknown target_id: " << target_id << endl;
467  delete metric; return 3;
468  }
469  TargetConstructor *target_c = new TargetConstructor(target_t);
470  target_c->SetNodes(x0);
471  TMOP_Integrator *he_nlf_integ = new TMOP_Integrator(metric, target_c);
472 
473  // 12. Setup the quadrature rule for the non-linear form integrator.
474  const IntegrationRule *ir = NULL;
475  const int geom_type = fespace->GetFE(0)->GetGeomType();
476  switch (quad_type)
477  {
478  case 1: ir = &IntRulesLo.Get(geom_type, quad_order); break;
479  case 2: ir = &IntRules.Get(geom_type, quad_order); break;
480  case 3: ir = &IntRulesCU.Get(geom_type, quad_order); break;
481  default: cout << "Unknown quad_type: " << quad_type << endl;
482  delete he_nlf_integ; return 3;
483  }
484  cout << "Quadrature points per cell: " << ir->GetNPoints() << endl;
485  he_nlf_integ->SetIntegrationRule(*ir);
486 
487  // 13. Limit the node movement.
488  ConstantCoefficient lim_coeff(lim_const);
489  if (lim_const != 0.0) { he_nlf_integ->EnableLimiting(x0, lim_coeff); }
490 
491  // 14. Setup the final NonlinearForm (which defines the integral of interest,
492  // its first and second derivatives). Here we can use a combination of
493  // metrics, i.e., optimize the sum of two integrals, where both are
494  // scaled by used-defined space-dependent weights. Note that there are no
495  // command-line options for the weights and the type of the second
496  // metric; one should update those in the code.
497  NonlinearForm a(fespace);
498  Coefficient *coeff1 = NULL;
499  TMOP_QualityMetric *metric2 = NULL;
500  TargetConstructor *target_c2 = NULL;
502  if (combomet == 1)
503  {
504  // Weight of the original metric.
505  coeff1 = new ConstantCoefficient(1.25);
506  he_nlf_integ->SetCoefficient(*coeff1);
507  a.AddDomainIntegrator(he_nlf_integ);
508 
509  metric2 = new TMOP_Metric_077;
510  target_c2 = new TargetConstructor(
512  target_c2->SetVolumeScale(0.01);
513  target_c2->SetNodes(x0);
514  TMOP_Integrator *he_nlf_integ2 = new TMOP_Integrator(metric2, target_c2);
515  he_nlf_integ2->SetIntegrationRule(*ir);
516 
517  // Weight of metric2.
518  he_nlf_integ2->SetCoefficient(coeff2);
519  a.AddDomainIntegrator(he_nlf_integ2);
520  }
521  else { a.AddDomainIntegrator(he_nlf_integ); }
522  const double init_en = a.GetGridFunctionEnergy(*x);
523  cout << "Initial strain energy: " << init_en << endl;
524 
525  // 15. Visualize the starting mesh and metric values.
526  if (visualization)
527  {
528  char title[] = "Initial metric values";
529  vis_metric(mesh_poly_deg, *metric, *target_c, *mesh, title, 0);
530  }
531 
532  // 16. Fix all boundary nodes, or fix only a given component depending on the
533  // boundary attributes of the given mesh. Attributes 1/2/3 correspond to
534  // fixed x/y/z components of the node. Attribute 4 corresponds to an
535  // entirely fixed node. Other boundary attributes do not affect the node
536  // movement boundary conditions.
537  if (move_bnd == false)
538  {
539  Array<int> ess_bdr(mesh->bdr_attributes.Max());
540  ess_bdr = 1;
541  a.SetEssentialBC(ess_bdr);
542  }
543  else
544  {
545  const int nd = fespace->GetBE(0)->GetDof();
546  int n = 0;
547  for (int i = 0; i < mesh->GetNBE(); i++)
548  {
549  const int attr = mesh->GetBdrElement(i)->GetAttribute();
550  MFEM_VERIFY(!(dim == 2 && attr == 3),
551  "Boundary attribute 3 must be used only for 3D meshes. "
552  "Adjust the attributes (1/2/3/4 for fixed x/y/z/all "
553  "components, rest for free nodes), or use -fix-bnd.");
554  if (attr == 1 || attr == 2 || attr == 3) { n += nd; }
555  if (attr == 4) { n += nd * dim; }
556  }
557  Array<int> ess_vdofs(n), vdofs;
558  n = 0;
559  for (int i = 0; i < mesh->GetNBE(); i++)
560  {
561  const int attr = mesh->GetBdrElement(i)->GetAttribute();
562  fespace->GetBdrElementVDofs(i, vdofs);
563  if (attr == 1) // Fix x components.
564  {
565  for (int j = 0; j < nd; j++)
566  { ess_vdofs[n++] = vdofs[j]; }
567  }
568  else if (attr == 2) // Fix y components.
569  {
570  for (int j = 0; j < nd; j++)
571  { ess_vdofs[n++] = vdofs[j+nd]; }
572  }
573  else if (attr == 3) // Fix z components.
574  {
575  for (int j = 0; j < nd; j++)
576  { ess_vdofs[n++] = vdofs[j+2*nd]; }
577  }
578  else if (attr == 4) // Fix all components.
579  {
580  for (int j = 0; j < vdofs.Size(); j++)
581  { ess_vdofs[n++] = vdofs[j]; }
582  }
583  }
584  a.SetEssentialVDofs(ess_vdofs);
585  }
586 
587  // 17. As we use the Newton method to solve the resulting nonlinear system,
588  // here we setup the linear solver for the system's Jacobian.
589  Solver *S = NULL;
590  const double linsol_rtol = 1e-12;
591  if (lin_solver == 0)
592  {
593  S = new DSmoother(1, 1.0, max_lin_iter);
594  }
595  else if (lin_solver == 1)
596  {
597  CGSolver *cg = new CGSolver;
598  cg->SetMaxIter(max_lin_iter);
599  cg->SetRelTol(linsol_rtol);
600  cg->SetAbsTol(0.0);
601  cg->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
602  S = cg;
603  }
604  else
605  {
606  MINRESSolver *minres = new MINRESSolver;
607  minres->SetMaxIter(max_lin_iter);
608  minres->SetRelTol(linsol_rtol);
609  minres->SetAbsTol(0.0);
610  minres->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
611  S = minres;
612  }
613 
614  // 18. Compute the minimum det(J) of the starting mesh.
615  tauval = infinity();
616  const int NE = mesh->GetNE();
617  for (int i = 0; i < NE; i++)
618  {
620  for (int j = 0; j < ir->GetNPoints(); j++)
621  {
622  transf->SetIntPoint(&ir->IntPoint(j));
623  tauval = min(tauval, transf->Jacobian().Det());
624  }
625  }
626  cout << "Minimum det(J) of the original mesh is " << tauval << endl;
627 
628  // 19. Finally, perform the nonlinear optimization.
629  NewtonSolver *newton = NULL;
630  if (tauval > 0.0)
631  {
632  tauval = 0.0;
633  newton = new RelaxedNewtonSolver(*ir, fespace);
634  cout << "The RelaxedNewtonSolver is used (as all det(J)>0)." << endl;
635  }
636  else
637  {
638  if ( (dim == 2 && metric_id != 22 && metric_id != 252) ||
639  (dim == 3 && metric_id != 352) )
640  {
641  cout << "The mesh is inverted. Use an untangling metric." << endl;
642  return 3;
643  }
644  tauval -= 0.01 * h0.Min(); // Slightly below minJ0 to avoid div by 0.
645  newton = new DescentNewtonSolver(*ir, fespace);
646  cout << "The DescentNewtonSolver is used (as some det(J)<0)." << endl;
647  }
648  newton->SetPreconditioner(*S);
649  newton->SetMaxIter(newton_iter);
650  newton->SetRelTol(newton_rtol);
651  newton->SetAbsTol(0.0);
652  newton->SetPrintLevel(verbosity_level >= 1 ? 1 : -1);
653  newton->SetOperator(a);
654  newton->Mult(b, x->GetTrueVector());
655  x->SetFromTrueVector();
656  if (newton->GetConverged() == false)
657  {
658  cout << "NewtonIteration: rtol = " << newton_rtol << " not achieved."
659  << endl;
660  }
661  delete newton;
662 
663  // 20. Save the optimized mesh to a file. This output can be viewed later
664  // using GLVis: "glvis -m optimized.mesh".
665  {
666  ofstream mesh_ofs("optimized.mesh");
667  mesh_ofs.precision(14);
668  mesh->Print(mesh_ofs);
669  }
670 
671  // 21. Compute the amount of energy decrease.
672  const double fin_en = a.GetGridFunctionEnergy(*x);
673  cout << "Final strain energy : " << fin_en << endl;
674  cout << "The strain energy decreased by: " << setprecision(12)
675  << (init_en - fin_en) * 100.0 / init_en << " %." << endl;
676 
677  // 22. Visualize the final mesh and metric values.
678  if (visualization)
679  {
680  char title[] = "Final metric values";
681  vis_metric(mesh_poly_deg, *metric, *target_c, *mesh, title, 600);
682  }
683 
684  // 23. Visualize the mesh displacement.
685  if (visualization)
686  {
687  x0 -= *x;
688  osockstream sock(19916, "localhost");
689  sock << "solution\n";
690  mesh->Print(sock);
691  x0.Save(sock);
692  sock.send();
693  sock << "window_title 'Displacements'\n"
694  << "window_geometry "
695  << 1200 << " " << 0 << " " << 600 << " " << 600 << "\n"
696  << "keys jRmclA" << endl;
697  }
698 
699  // 24. Free the used memory.
700  delete S;
701  delete target_c2;
702  delete metric2;
703  delete coeff1;
704  delete target_c;
705  delete metric;
706  delete fespace;
707  delete fec;
708  delete mesh;
709 
710  return 0;
711 }
712 
713 // Defined with respect to the icf mesh.
714 double weight_fun(const Vector &x)
715 {
716  const double r = sqrt(x(0)*x(0) + x(1)*x(1) + 1e-12);
717  const double den = 0.002;
718  double l2 = 0.2 + 0.5*std::tanh((r-0.16)/den) - 0.5*std::tanh((r-0.17)/den)
719  + 0.5*std::tanh((r-0.23)/den) - 0.5*std::tanh((r-0.24)/den);
720  return l2;
721 }
Shifted barrier form of metric 56 (area, ideal barrier metric), 2D.
Definition: tmop.hpp:265
Shifted barrier form of 3D metric 16 (volume, ideal barrier metric), 3D.
Definition: tmop.hpp:383
Conjugate gradient method.
Definition: solvers.hpp:111
int GetNPoints() const
Returns the number of the points in the integration rule.
Definition: intrules.hpp:232
Class for an integration rule - an Array of IntegrationPoint.
Definition: intrules.hpp:83
void GetBdrElementVDofs(int i, Array< int > &vdofs) const
Returns indexes of degrees of freedom for i&#39;th boundary element.
Definition: fespace.cpp:177
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:27
Shape & volume, ideal barrier metric, 3D.
Definition: tmop.hpp:367
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:861
void SetFromTrueVector()
Shortcut for calling SetFromTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:122
Subclass constant coefficient.
Definition: coefficient.hpp:57
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
int main(int argc, char *argv[])
int Dimension() const
Definition: mesh.hpp:645
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:987
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:317
void PrintUsage(std::ostream &out) const
Definition: optparser.cpp:434
void AddDomainIntegrator(NonlinearFormIntegrator *nlfi)
Adds new Domain Integrator.
void SetIntPoint(const IntegrationPoint *ip)
Definition: eltrans.hpp:52
int GetAttribute() const
Return element&#39;s attribute.
Definition: element.hpp:50
double Det() const
Definition: densemat.cpp:460
int Size() const
Returns the size of the vector.
Definition: vector.hpp:120
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition: array.cpp:109
Container class for integration rules.
Definition: intrules.hpp:289
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:301
void SetVolumeScale(double vol_scale)
Used by target type IDEAL_SHAPE_EQUAL_SIZE. The default volume scale is 1.
Definition: tmop.hpp:473
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:92
int GetNDofs() const
Returns number of degrees of freedom.
Definition: fespace.hpp:250
Volume metric, 3D.
Definition: tmop.hpp:333
Area, ideal barrier metric, 2D.
Definition: tmop.hpp:229
bool Good() const
Definition: optparser.hpp:120
STL namespace.
MINRES method.
Definition: solvers.hpp:221
void Randomize(int seed=0)
Set random values in the vector.
Definition: vector.cpp:647
double weight_fun(const Vector &x)
Shape & area, ideal barrier metric, 2D.
Definition: tmop.hpp:108
void vis_metric(int order, TMOP_QualityMetric &qm, const TargetConstructor &tc, Mesh &mesh, char *title, int position)
int GetNBE() const
Returns number of boundary elements.
Definition: mesh.hpp:621
Shifted barrier form of metric 2 (shape, ideal barrier metric), 2D.
Definition: tmop.hpp:140
int GetGeomType() const
Returns the Geometry::Type of the reference element.
Definition: fe.hpp:214
void add(const Vector &v1, const Vector &v2, Vector &v)
Definition: vector.cpp:260
const FiniteElement * GetFE(int i) const
Returns pointer to the FiniteElement associated with i&#39;th element.
Definition: fespace.cpp:1335
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:211
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:235
void SetTrueVector()
Shortcut for calling GetTrueDofs() with GetTrueVector() as argument.
Definition: gridfunc.hpp:116
int dim
Definition: ex3.cpp:47
void SetPrintLevel(int print_lvl)
Definition: solvers.cpp:72
void SetCoefficient(Coefficient &w1)
Sets a scaling Coefficient for the quality metric term of the integrator.
Definition: tmop.hpp:528
Area metric, 2D.
Definition: tmop.hpp:175
Volume, ideal barrier metric, 3D.
Definition: tmop.hpp:349
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:6741
IntegrationRules IntRulesLo(0, Quadrature1D::GaussLobatto)
const DenseMatrix & Jacobian()
Return the Jacobian matrix of the transformation at the currently set IntegrationPoint, using the method SetIntPoint().
Definition: eltrans.hpp:67
void SetNodes(const GridFunction &n)
Set the nodes to be used in the target-matrix construction.
Definition: tmop.hpp:470
void SetMaxIter(int max_it)
Definition: solvers.hpp:63
Newton&#39;s method for solving F(x)=b for a given operator F.
Definition: solvers.hpp:259
Version of QuadraticFECollection with positive basis functions.
Definition: fe_coll.hpp:366
virtual double GetEnergy(const Vector &x) const
Compute the enery corresponding to the state x.
void SetNodalFESpace(FiniteElementSpace *nfes)
Definition: mesh.cpp:3338
double GetGridFunctionEnergy(const Vector &x) const
Compute the enery corresponding to the state x.
double * GetData() const
Return a pointer to the beginning of the Vector data.
Definition: vector.hpp:129
double GetElementSize(int i, int type=0)
Definition: mesh.cpp:64
virtual void Print(std::ostream &out=mfem::out) const
Definition: mesh.hpp:1034
virtual void Mult(const Vector &b, Vector &x) const
Solve the nonlinear system with right-hand side b.
Definition: solvers.cpp:1241
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:174
void SetRelTol(double rtol)
Definition: solvers.hpp:61
Shape, ideal barrier metric, 2D.
Definition: tmop.hpp:159
Untangling metric, 2D.
Definition: tmop.hpp:246
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition: fespace.hpp:66
Area, ideal barrier metric, 2D.
Definition: tmop.hpp:192
Base class Coefficient that may optionally depend on time.
Definition: coefficient.hpp:31
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:74
void EnableLimiting(const GridFunction &n0, Coefficient &w0)
Adds a limiting term to the integrator.
Definition: tmop.hpp:537
int GetDof() const
Returns the number of degrees of freedom in the finite element.
Definition: fe.hpp:217
const Vector & GetTrueVector() const
Read only access to the (optional) internal true-dof Vector.
Definition: gridfunc.hpp:105
virtual void GetElementDofs(int i, Array< int > &dofs) const
Returns indexes of degrees of freedom in array dofs for i&#39;th element.
Definition: fespace.cpp:1233
Shape & area metric, 2D.
Definition: tmop.hpp:124
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:618
void GetElementTransformation(int i, IsoparametricTransformation *ElTr)
Definition: mesh.cpp:279
void SetIntegrationRule(const IntegrationRule &irule)
Prescribe a fixed IntegrationRule to use.
Definition: nonlininteg.hpp:40
int GetNBE() const
Returns number of boundary elements in the mesh.
Definition: fespace.hpp:286
double infinity()
Define a shortcut for std::numeric_limits<double>::infinity()
Definition: vector.hpp:42
void SetEssentialBC(const Array< int > &bdr_attr_is_ess, Vector *rhs=NULL)
Specify essential boundary conditions.
int Size() const
Logical size of the array.
Definition: array.hpp:133
class for C-function coefficient
int DofToVDof(int dof, int vd, int ndofs=-1) const
Definition: fespace.cpp:142
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:3631
Vector data type.
Definition: vector.hpp:48
IntegrationRules IntRulesCU(0, Quadrature1D::ClosedUniform)
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:93
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:79
TargetType
Target-matrix construction algorithms supported by this class.
Definition: tmop.hpp:414
void GetNodes(Vector &node_coord) const
Definition: mesh.cpp:5422
void SetEssentialVDofs(const Array< int > &ess_vdofs_list)
(DEPRECATED) Specify essential boundary conditions.
const Element * GetBdrElement(int i) const
Definition: mesh.hpp:680
Base class for solvers.
Definition: operator.hpp:268
Base class representing target-matrix construction algorithms for mesh optimization via the target-ma...
Definition: tmop.hpp:410
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Definition: gridfunc.cpp:2349
IntegrationRules IntRules(0, Quadrature1D::GaussLegendre)
A global object with all integration rules (defined in intrules.cpp)
Definition: intrules.hpp:353
const FiniteElement * GetBE(int i) const
Returns pointer to the FiniteElement for the i&#39;th boundary element.
Definition: fespace.cpp:1571
aka closed Newton-Cotes
Definition: intrules.hpp:277
Shape, ideal barrier metric, 3D.
Definition: tmop.hpp:285
int GetConverged() const
Definition: solvers.hpp:67
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:1230
Arbitrary order "L2-conforming" discontinuous finite elements.
Definition: fe_coll.hpp:128
A TMOP integrator class based on any given TMOP_QualityMetric and TargetConstructor.
Definition: tmop.hpp:490