MFEM  v3.4
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
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 - 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:
35 // Blade shape:
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
37 // Blade limited shape:
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  {
125  add(x, -scale, c, x_out);
126  x_gf.SetFromTrueVector();
127 
128  energy_out = nlf->GetParGridFunctionEnergy(x_gf);
129  if (energy_out > 1.2*energy_in || 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  {
241  add(x, -scale, c, x_out);
242 
243  energy_out = nlf->GetEnergy(x_out);
244  if (energy_out > energy_in || 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;
285  int quad_type = 1;
286  int quad_order = 8;
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 visualization = true;
294  int verbosity_level = 0;
295 
296  // 2. Parse command-line options.
297  OptionsParser args(argc, argv);
298  args.AddOption(&mesh_file, "-m", "--mesh",
299  "Mesh file to use.");
300  args.AddOption(&mesh_poly_deg, "-o", "--order",
301  "Polynomial degree of mesh finite element space.");
302  args.AddOption(&rs_levels, "-rs", "--refine-serial",
303  "Number of times to refine the mesh uniformly in serial.");
304  args.AddOption(&rp_levels, "-rp", "--refine-parallel",
305  "Number of times to refine the mesh uniformly in parallel.");
306  args.AddOption(&jitter, "-ji", "--jitter",
307  "Random perturbation scaling factor.");
308  args.AddOption(&metric_id, "-mid", "--metric-id",
309  "Mesh optimization metric:\n\t"
310  "1 : |T|^2 -- 2D shape\n\t"
311  "2 : 0.5|T|^2/tau-1 -- 2D shape (condition number)\n\t"
312  "7 : |T-T^-t|^2 -- 2D shape+size\n\t"
313  "9 : tau*|T-T^-t|^2 -- 2D shape+size\n\t"
314  "22 : 0.5(|T|^2-2*tau)/(tau-tau_0) -- 2D untangling\n\t"
315  "50 : 0.5|T^tT|^2/tau^2-1 -- 2D shape\n\t"
316  "55 : (tau-1)^2 -- 2D size\n\t"
317  "56 : 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 2D size\n\t"
318  "58 : |T^tT|^2/(tau^2)-2*|T|^2/tau+2 -- 2D shape\n\t"
319  "77 : 0.5(tau-1/tau)^2 -- 2D size\n\t"
320  "211: (tau-1)^2-tau+sqrt(tau^2) -- 2D untangling\n\t"
321  "252: 0.5(tau-1)^2/(tau-tau_0) -- 2D untangling\n\t"
322  "301: (|T||T^-1|)/3-1 -- 3D shape\n\t"
323  "302: (|T|^2|T^-1|^2)/9-1 -- 3D shape\n\t"
324  "303: (|T|^2)/3*tau^(2/3)-1 -- 3D shape\n\t"
325  "315: (tau-1)^2 -- 3D size\n\t"
326  "316: 0.5(sqrt(tau)-1/sqrt(tau))^2 -- 3D size\n\t"
327  "321: |T-T^-t|^2 -- 3D shape+size\n\t"
328  "352: 0.5(tau-1)^2/(tau-tau_0) -- 3D untangling");
329  args.AddOption(&target_id, "-tid", "--target-id",
330  "Target (ideal element) type:\n\t"
331  "1: Ideal shape, unit size\n\t"
332  "2: Ideal shape, equal size\n\t"
333  "3: Ideal shape, initial size");
334  args.AddOption(&lim_const, "-lc", "--limit-const", "Limiting constant.");
335  args.AddOption(&quad_type, "-qt", "--quad-type",
336  "Quadrature rule type:\n\t"
337  "1: Gauss-Lobatto\n\t"
338  "2: Gauss-Legendre\n\t"
339  "3: Closed uniform points");
340  args.AddOption(&quad_order, "-qo", "--quad_order",
341  "Order of the quadrature rule.");
342  args.AddOption(&newton_iter, "-ni", "--newton-iters",
343  "Maximum number of Newton iterations.");
344  args.AddOption(&newton_rtol, "-rtol", "--newton-rel-tolerance",
345  "Relative tolerance for the Newton solver.");
346  args.AddOption(&lin_solver, "-ls", "--lin-solver",
347  "Linear solver: 0 - l1-Jacobi, 1 - CG, 2 - MINRES.");
348  args.AddOption(&max_lin_iter, "-li", "--lin-iter",
349  "Maximum number of iterations in the linear solve.");
350  args.AddOption(&move_bnd, "-bnd", "--move-boundary", "-fix-bnd",
351  "--fix-boundary",
352  "Enable motion along horizontal and vertical boundaries.");
353  args.AddOption(&combomet, "-cmb", "--combo-met", "-no-cmb", "--no-combo-met",
354  "Combination of metrics.");
355  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
356  "--no-visualization",
357  "Enable or disable GLVis visualization.");
358  args.AddOption(&verbosity_level, "-vl", "--verbosity-level",
359  "Set the verbosity level - 0, 1, or 2.");
360  args.Parse();
361  if (!args.Good())
362  {
363  if (myid == 0) { args.PrintUsage(cout); }
364  return 1;
365  }
366  if (myid == 0) { args.PrintOptions(cout); }
367 
368  // 3. Initialize and refine the starting mesh.
369  Mesh *mesh = new Mesh(mesh_file, 1, 1, false);
370  for (int lev = 0; lev < rs_levels; lev++) { mesh->UniformRefinement(); }
371  const int dim = mesh->Dimension();
372  if (myid == 0)
373  {
374  cout << "Mesh curvature: ";
375  if (mesh->GetNodes()) { cout << mesh->GetNodes()->OwnFEC()->Name(); }
376  else { cout << "(NONE)"; }
377  cout << endl;
378  }
379  ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
380  delete mesh;
381  for (int lev = 0; lev < rp_levels; lev++) { pmesh->UniformRefinement(); }
382 
383  // 4. Define a finite element space on the mesh. Here we use vector finite
384  // elements which are tensor products of quadratic finite elements. The
385  // number of components in the vector finite element space is specified by
386  // the last parameter of the FiniteElementSpace constructor.
388  if (mesh_poly_deg <= 0)
389  {
390  fec = new QuadraticPosFECollection;
391  mesh_poly_deg = 2;
392  }
393  else { fec = new H1_FECollection(mesh_poly_deg, dim); }
394  ParFiniteElementSpace *pfespace = new ParFiniteElementSpace(pmesh, fec, dim);
395 
396  // 5. Make the mesh curved based on the above finite element space. This
397  // means that we define the mesh elements through a fespace-based
398  // transformation of the reference element.
399  pmesh->SetNodalFESpace(pfespace);
400 
401  // 6. Set up an empty right-hand side vector b, which is equivalent to b=0.
402  Vector b(0);
403 
404  // 7. Get the mesh nodes (vertices and other degrees of freedom in the finite
405  // element space) as a finite element grid function in fespace. Note that
406  // changing x automatically changes the shapes of the mesh elements.
407  ParGridFunction x(pfespace);
408  pmesh->SetNodalGridFunction(&x);
409 
410  // 8. Define a vector representing the minimal local mesh size in the mesh
411  // nodes. We index the nodes using the scalar version of the degrees of
412  // freedom in pfespace.
413  Vector h0(pfespace->GetNDofs());
414  h0 = infinity();
415  Array<int> dofs;
416  for (int i = 0; i < pmesh->GetNE(); i++)
417  {
418  // Get the local scalar element degrees of freedom in dofs.
419  pfespace->GetElementDofs(i, dofs);
420  // Adjust the value of h0 in dofs based on the local mesh size.
421  for (int j = 0; j < dofs.Size(); j++)
422  {
423  h0(dofs[j]) = min(h0(dofs[j]), pmesh->GetElementSize(i));
424  }
425  }
426 
427  // 9. Add a random perturbation to the nodes in the interior of the domain.
428  // We define a random grid function of fespace and make sure that it is
429  // zero on the boundary and its values are locally of the order of h0.
430  // The latter is based on the DofToVDof() method which maps the scalar to
431  // the vector degrees of freedom in fespace.
432  ParGridFunction rdm(pfespace);
433  rdm.Randomize();
434  rdm -= 0.25; // Shift to random values in [-0.5,0.5].
435  rdm *= jitter;
436  // Scale the random values to be of order of the local mesh size.
437  for (int i = 0; i < pfespace->GetNDofs(); i++)
438  {
439  for (int d = 0; d < dim; d++)
440  {
441  rdm(pfespace->DofToVDof(i,d)) *= h0(i);
442  }
443  }
444  Array<int> vdofs;
445  for (int i = 0; i < pfespace->GetNBE(); i++)
446  {
447  // Get the vector degrees of freedom in the boundary element.
448  pfespace->GetBdrElementVDofs(i, vdofs);
449  // Set the boundary values to zero.
450  for (int j = 0; j < vdofs.Size(); j++) { rdm(vdofs[j]) = 0.0; }
451  }
452  x -= rdm;
453  // Set the perturbation of all nodes from the true nodes.
454  x.SetTrueVector();
455  x.SetFromTrueVector();
456 
457  // 10. Save the starting (prior to the optimization) mesh to a file. This
458  // output can be viewed later using GLVis: "glvis -m perturbed -np
459  // num_mpi_tasks".
460  {
461  ostringstream mesh_name;
462  mesh_name << "perturbed." << setfill('0') << setw(6) << myid;
463  ofstream mesh_ofs(mesh_name.str().c_str());
464  mesh_ofs.precision(8);
465  pmesh->Print(mesh_ofs);
466  }
467 
468  // 11. Store the starting (prior to the optimization) positions.
469  ParGridFunction x0(pfespace);
470  x0 = x;
471 
472  // 12. Form the integrator that uses the chosen metric and target.
473  double tauval = -0.1;
474  TMOP_QualityMetric *metric = NULL;
475  switch (metric_id)
476  {
477  case 1: metric = new TMOP_Metric_001; break;
478  case 2: metric = new TMOP_Metric_002; break;
479  case 7: metric = new TMOP_Metric_007; break;
480  case 9: metric = new TMOP_Metric_009; break;
481  case 22: metric = new TMOP_Metric_022(tauval); break;
482  case 50: metric = new TMOP_Metric_050; break;
483  case 55: metric = new TMOP_Metric_055; break;
484  case 56: metric = new TMOP_Metric_056; break;
485  case 58: metric = new TMOP_Metric_058; break;
486  case 77: metric = new TMOP_Metric_077; break;
487  case 211: metric = new TMOP_Metric_211; break;
488  case 252: metric = new TMOP_Metric_252(tauval); break;
489  case 301: metric = new TMOP_Metric_301; break;
490  case 302: metric = new TMOP_Metric_302; break;
491  case 303: metric = new TMOP_Metric_303; break;
492  case 315: metric = new TMOP_Metric_315; break;
493  case 316: metric = new TMOP_Metric_316; break;
494  case 321: metric = new TMOP_Metric_321; break;
495  case 352: metric = new TMOP_Metric_352(tauval); break;
496  default:
497  if (myid == 0) { cout << "Unknown metric_id: " << metric_id << endl; }
498  return 3;
499  }
501  switch (target_id)
502  {
503  case 1: target_t = TargetConstructor::IDEAL_SHAPE_UNIT_SIZE; break;
504  case 2: target_t = TargetConstructor::IDEAL_SHAPE_EQUAL_SIZE; break;
505  case 3: target_t = TargetConstructor::IDEAL_SHAPE_GIVEN_SIZE; break;
506  default:
507  if (myid == 0) { cout << "Unknown target_id: " << target_id << endl; }
508  return 3;
509  }
510  TargetConstructor *target_c;
511  target_c = new TargetConstructor(target_t, MPI_COMM_WORLD);
512  target_c->SetNodes(x0);
513  TMOP_Integrator *he_nlf_integ;
514  he_nlf_integ = new TMOP_Integrator(metric, target_c);
515 
516  // 13. Setup the quadrature rule for the non-linear form integrator.
517  const IntegrationRule *ir = NULL;
518  const int geom_type = pfespace->GetFE(0)->GetGeomType();
519  switch (quad_type)
520  {
521  case 1: ir = &IntRulesLo.Get(geom_type, quad_order); break;
522  case 2: ir = &IntRules.Get(geom_type, quad_order); break;
523  case 3: ir = &IntRulesCU.Get(geom_type, quad_order); break;
524  default:
525  if (myid == 0) { cout << "Unknown quad_type: " << quad_type << endl; }
526  return 3;
527  }
528  if (myid == 0)
529  { cout << "Quadrature points per cell: " << ir->GetNPoints() << endl; }
530  he_nlf_integ->SetIntegrationRule(*ir);
531 
532  // 14. Limit the node movement.
533  ConstantCoefficient lim_coeff(lim_const);
534  if (lim_const != 0.0) { he_nlf_integ->EnableLimiting(x0, lim_coeff); }
535 
536  // 15. Setup the final NonlinearForm (which defines the integral of interest,
537  // its first and second derivatives). Here we can use a combination of
538  // metrics, i.e., optimize the sum of two integrals, where both are
539  // scaled by used-defined space-dependent weights. Note that there are
540  // no command-line options for the weights and the type of the second
541  // metric; one should update those in the code.
542  ParNonlinearForm a(pfespace);
543  Coefficient *coeff1 = NULL;
544  TMOP_QualityMetric *metric2 = NULL;
545  TargetConstructor *target_c2 = NULL;
547 
548  if (combomet)
549  {
550  // Weight of the original metric.
551  coeff1 = new ConstantCoefficient(1.0);
552  he_nlf_integ->SetCoefficient(*coeff1);
553  a.AddDomainIntegrator(he_nlf_integ);
554 
555  metric2 = new TMOP_Metric_077;
556  target_c2 = new TargetConstructor(
558  target_c2->SetVolumeScale(0.01);
559  target_c2->SetNodes(x0);
560  TMOP_Integrator *he_nlf_integ2;
561  he_nlf_integ2 = new TMOP_Integrator(metric2, target_c2);
562  he_nlf_integ2->SetIntegrationRule(*ir);
563 
564  // Weight of metric2.
565  he_nlf_integ2->SetCoefficient(coeff2);
566  a.AddDomainIntegrator(he_nlf_integ2);
567  }
568  else { a.AddDomainIntegrator(he_nlf_integ); }
569  const double init_en = a.GetParGridFunctionEnergy(x);
570  if (myid == 0) { cout << "Initial strain energy: " << init_en << endl; }
571 
572  // 16. Visualize the starting mesh and metric values.
573  if (visualization)
574  {
575  char title[] = "Initial metric values";
576  vis_metric(mesh_poly_deg, *metric, *target_c, *pmesh, title, 0);
577  }
578 
579  // 17. Fix all boundary nodes, or fix only a given component depending on the
580  // boundary attributes of the given mesh. Attributes 1/2/3 correspond to
581  // fixed x/y/z components of the node. Attribute 4 corresponds to an
582  // entirely fixed node. Other boundary attributes do not affect the node
583  // movement boundary conditions.
584  if (move_bnd == false)
585  {
586  Array<int> ess_bdr(pmesh->bdr_attributes.Max());
587  ess_bdr = 1;
588  a.SetEssentialBC(ess_bdr);
589  }
590  else
591  {
592  const int nd = pfespace->GetBE(0)->GetDof();
593  int n = 0;
594  for (int i = 0; i < pmesh->GetNBE(); i++)
595  {
596  const int attr = pmesh->GetBdrElement(i)->GetAttribute();
597  MFEM_VERIFY(!(dim == 2 && attr == 3),
598  "Boundary attribute 3 must be used only for 3D meshes. "
599  "Adjust the attributes (1/2/3/4 for fixed x/y/z/all "
600  "components, rest for free nodes), or use -fix-bnd.");
601  if (attr == 1 || attr == 2 || attr == 3) { n += nd; }
602  if (attr == 4) { n += nd * dim; }
603  }
604  Array<int> ess_vdofs(n), vdofs;
605  n = 0;
606  for (int i = 0; i < pmesh->GetNBE(); i++)
607  {
608  const int attr = pmesh->GetBdrElement(i)->GetAttribute();
609  pfespace->GetBdrElementVDofs(i, vdofs);
610  if (attr == 1) // Fix x components.
611  {
612  for (int j = 0; j < nd; j++)
613  { ess_vdofs[n++] = vdofs[j]; }
614  }
615  else if (attr == 2) // Fix y components.
616  {
617  for (int j = 0; j < nd; j++)
618  { ess_vdofs[n++] = vdofs[j+nd]; }
619  }
620  else if (attr == 3) // Fix z components.
621  {
622  for (int j = 0; j < nd; j++)
623  { ess_vdofs[n++] = vdofs[j+2*nd]; }
624  }
625  else if (attr == 4) // Fix all components.
626  {
627  for (int j = 0; j < vdofs.Size(); j++)
628  { ess_vdofs[n++] = vdofs[j]; }
629  }
630  }
631  a.SetEssentialVDofs(ess_vdofs);
632  }
633 
634  // 18. As we use the Newton method to solve the resulting nonlinear system,
635  // here we setup the linear solver for the system's Jacobian.
636  Solver *S = NULL;
637  const double linsol_rtol = 1e-12;
638  if (lin_solver == 0)
639  {
640  S = new DSmoother(1, 1.0, max_lin_iter);
641  }
642  else if (lin_solver == 1)
643  {
644  CGSolver *cg = new CGSolver(MPI_COMM_WORLD);
645  cg->SetMaxIter(max_lin_iter);
646  cg->SetRelTol(linsol_rtol);
647  cg->SetAbsTol(0.0);
648  cg->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
649  S = cg;
650  }
651  else
652  {
653  MINRESSolver *minres = new MINRESSolver(MPI_COMM_WORLD);
654  minres->SetMaxIter(max_lin_iter);
655  minres->SetRelTol(linsol_rtol);
656  minres->SetAbsTol(0.0);
657  minres->SetPrintLevel(verbosity_level >= 2 ? 3 : -1);
658  S = minres;
659  }
660 
661  // 19. Compute the minimum det(J) of the starting mesh.
662  tauval = infinity();
663  const int NE = pmesh->GetNE();
664  for (int i = 0; i < NE; i++)
665  {
667  for (int j = 0; j < ir->GetNPoints(); j++)
668  {
669  transf->SetIntPoint(&ir->IntPoint(j));
670  tauval = min(tauval, transf->Jacobian().Det());
671  }
672  }
673  double minJ0;
674  MPI_Allreduce(&tauval, &minJ0, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
675  tauval = minJ0;
676  if (myid == 0)
677  { cout << "Minimum det(J) of the original mesh is " << tauval << endl; }
678 
679  // 20. Finally, perform the nonlinear optimization.
680  NewtonSolver *newton = NULL;
681  if (tauval > 0.0)
682  {
683  tauval = 0.0;
684  newton = new RelaxedNewtonSolver(*ir, pfespace);
685  if (myid == 0)
686  { cout << "RelaxedNewtonSolver is used (as all det(J) > 0)." << endl; }
687  }
688  else
689  {
690  if ( (dim == 2 && metric_id != 22 && metric_id != 252) ||
691  (dim == 3 && metric_id != 352) )
692  {
693  if (myid == 0)
694  { cout << "The mesh is inverted. Use an untangling metric." << endl; }
695  return 3;
696  }
697  double h0min = h0.Min(), h0min_all;
698  MPI_Allreduce(&h0min, &h0min_all, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
699  tauval -= 0.01 * h0min_all; // Slightly below minJ0 to avoid div by 0.
700  newton = new DescentNewtonSolver(*ir, pfespace);
701  if (myid == 0)
702  { cout << "DescentNewtonSolver is used (as some det(J) < 0)." << endl; }
703  }
704  newton->SetPreconditioner(*S);
705  newton->SetMaxIter(newton_iter);
706  newton->SetRelTol(newton_rtol);
707  newton->SetAbsTol(0.0);
708  newton->SetPrintLevel(verbosity_level >= 1 ? 1 : -1);
709  newton->SetOperator(a);
710  newton->Mult(b, x.GetTrueVector());
711  x.SetFromTrueVector();
712  if (myid == 0 && newton->GetConverged() == false)
713  {
714  cout << "NewtonIteration: rtol = " << newton_rtol << " not achieved."
715  << endl;
716  }
717  delete newton;
718 
719  // 21. Save the optimized mesh to a file. This output can be viewed later
720  // using GLVis: "glvis -m optimized -np num_mpi_tasks".
721  {
722  ostringstream mesh_name;
723  mesh_name << "optimized." << setfill('0') << setw(6) << myid;
724  ofstream mesh_ofs(mesh_name.str().c_str());
725  mesh_ofs.precision(8);
726  pmesh->Print(mesh_ofs);
727  }
728 
729  // 22. Compute the amount of energy decrease.
730  const double fin_en = a.GetParGridFunctionEnergy(x);
731  if (myid == 0)
732  {
733  cout << "Final strain energy : " << fin_en << endl;
734  cout << "The strain energy decreased by: " << setprecision(12)
735  << (init_en - fin_en) * 100.0 / init_en << " %." << endl;
736  }
737 
738  // 23. Visualize the final mesh and metric values.
739  if (visualization)
740  {
741  char title[] = "Final metric values";
742  vis_metric(mesh_poly_deg, *metric, *target_c, *pmesh, title, 600);
743  }
744 
745  // 23. Visualize the mesh displacement.
746  if (visualization)
747  {
748  x0 -= x;
749  socketstream sock;
750  if (myid == 0)
751  {
752  sock.open("localhost", 19916);
753  sock << "solution\n";
754  }
755  pmesh->PrintAsOne(sock);
756  x0.SaveAsOne(sock);
757  if (myid == 0)
758  {
759  sock << "window_title 'Displacements'\n"
760  << "window_geometry "
761  << 1200 << " " << 0 << " " << 600 << " " << 600 << "\n"
762  << "keys jRmclA" << endl;
763  }
764  }
765 
766  // 24. Free the used memory.
767  delete S;
768  delete target_c2;
769  delete metric2;
770  delete coeff1;
771  delete target_c;
772  delete metric;
773  delete pfespace;
774  delete fec;
775  delete pmesh;
776 
777  MPI_Finalize();
778  return 0;
779 }
780 
781 // Defined with respect to the icf mesh.
782 double weight_fun(const Vector &x)
783 {
784  const double r = sqrt(x(0)*x(0) + x(1)*x(1) + 1e-12);
785  const double den = 0.002;
786  double l2 = 0.2 + 0.5 * (std::tanh((r-0.16)/den) - std::tanh((r-0.17)/den)
787  + std::tanh((r-0.23)/den) - std::tanh((r-0.24)/den));
788  return l2;
789 }
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
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 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
void SaveAsOne(std::ostream &out=mfem::out)
Merge the local grid functions.
Definition: pgridfunc.cpp:413
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
Parallel non-linear operator on the true dofs.
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
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:361
bool Good() const
Definition: optparser.hpp:120
Abstract parallel finite element space.
Definition: pfespace.hpp:28
STL namespace.
void vis_metric(int order, TMOP_QualityMetric &qm, const TargetConstructor &tc, ParMesh &pmesh, char *title, int position)
MINRES method.
Definition: solvers.hpp:221
void Randomize(int seed=0)
Set random values in the vector.
Definition: vector.cpp:647
virtual void Print(std::ostream &out=mfem::out) const
Definition: pmesh.cpp:3427
Shape & area, ideal barrier metric, 2D.
Definition: tmop.hpp:108
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
double weight_fun(const Vector &x)
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 PrintAsOne(std::ostream &out=mfem::out)
Definition: pmesh.cpp:3555
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:6741
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
int main(int argc, char *argv[])
IntegrationRules IntRulesCU(0, Quadrature1D::ClosedUniform)
void SetNodalFESpace(FiniteElementSpace *nfes)
Definition: mesh.cpp:3338
double GetParGridFunctionEnergy(const Vector &x) const
Compute the energy 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
int GetMyRank() const
Definition: pmesh.hpp:126
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
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
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
IntegrationRules IntRulesLo(0, Quadrature1D::GaussLobatto)
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 open(const char hostname[], int port)
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
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
double GetEnergy(const ParGridFunction &x) const
Compute the energy of a ParGridFunction.
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
Class for parallel grid function.
Definition: pgridfunc.hpp:32
void SetNodalGridFunction(GridFunction *nodes, bool make_owner=false)
Definition: mesh.cpp:3344
Base class representing target-matrix construction algorithms for mesh optimization via the target-ma...
Definition: tmop.hpp:410
Class for parallel meshes.
Definition: pmesh.hpp:32
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