MFEM  v4.5.2
Finite element discretization library
pminimal-surface.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010-2023, Lawrence Livermore National Security, LLC. Produced
2 // at the Lawrence Livermore National Laboratory. All Rights reserved. See files
3 // LICENSE and NOTICE for details. LLNL-CODE-806117.
4 //
5 // This file is part of the MFEM library. For more information and source code
6 // availability visit https://mfem.org.
7 //
8 // MFEM is free software; you can redistribute it and/or modify it under the
9 // terms of the BSD-3 license. We welcome feedback and contributions, see file
10 // CONTRIBUTING.md for details.
11 //
12 // --------------------------------------------------------------------
13 // Minimal Surface Miniapp: Compute minimal surfaces - Parallel Version
14 // --------------------------------------------------------------------
15 //
16 // This miniapp solves Plateau's problem: the Dirichlet problem for the minimal
17 // surface equation.
18 //
19 // Two problems can be run:
20 //
21 // - Problem 0 solves the minimal surface equation of parametric surfaces.
22 // The surface (-s) option allow the selection of different
23 // parametrization:
24 // s=0: Uses the given mesh from command line options
25 // s=1: Catenoid
26 // s=2: Helicoid
27 // s=3: Enneper
28 // s=4: Hold
29 // s=5: Costa
30 // s=6: Shell
31 // s=7: Scherk
32 // s=8: FullPeach
33 // s=9: QuarterPeach
34 // s=10: SlottedSphere
35 //
36 // - Problem 1 solves the minimal surface equation of the form z=f(x,y),
37 // for the Dirichlet problem, using Picard iterations:
38 // -div( q grad u) = 0, with q(u) = (1 + |∇u|²)^{-1/2}
39 //
40 // Compile with: make pminimal-surface
41 //
42 // Sample runs: mpirun -np 4 pminimal-surface
43 // mpirun -np 4 pminimal-surface -a
44 // mpirun -np 4 pminimal-surface -c
45 // mpirun -np 4 pminimal-surface -c -a
46 // mpirun -np 4 pminimal-surface -no-pa
47 // mpirun -np 4 pminimal-surface -no-pa -a
48 // mpirun -np 4 pminimal-surface -no-pa -a -c
49 // mpirun -np 4 pminimal-surface -p 1
50 //
51 // Device sample runs:
52 // mpirun -np 4 pminimal-surface -d debug
53 // mpirun -np 4 pminimal-surface -d debug -a
54 // mpirun -np 4 pminimal-surface -d debug -c
55 // mpirun -np 4 pminimal-surface -d debug -c -a
56 // mpirun -np 4 pminimal-surface -d cuda
57 // mpirun -np 4 pminimal-surface -d cuda -a
58 // mpirun -np 4 pminimal-surface -d cuda -c
59 // mpirun -np 4 pminimal-surface -d cuda -c -a
60 // mpirun -np 4 pminimal-surface -d cuda -no-pa
61 // mpirun -np 4 pminimal-surface -d cuda -no-pa -a
62 // mpirun -np 4 pminimal-surface -d cuda -no-pa -c
63 // mpirun -np 4 pminimal-surface -d cuda -no-pa -c -a
64 
65 #include "mfem.hpp"
66 #include "../../general/forall.hpp"
67 
68 using namespace mfem;
69 
70 // Constant variables
71 constexpr int DIM = 2;
72 constexpr int SDIM = 3;
73 constexpr double PI = M_PI;
74 constexpr double NRM = 1.e-4;
75 constexpr double EPS = 1.e-14;
77 constexpr double NL_DMAX = std::numeric_limits<double>::max();
78 
79 // Static variables for GLVis
80 constexpr int GLVIZ_W = 1024;
81 constexpr int GLVIZ_H = 1024;
82 constexpr int visport = 19916;
83 constexpr char vishost[] = "localhost";
84 
85 // Context/Options for the solver
86 struct Opt
87 {
88  int sz, id;
89  int pb = 0;
90  int nx = 6;
91  int ny = 6;
92  int order = 3;
93  int refine = 2;
94  int niters = 8;
95  int surface = 5;
96  bool pa = true;
97  bool vis = true;
98  bool amr = false;
99  bool wait = false;
100  bool print = false;
101  bool radial = false;
102  bool by_vdim = false;
103  bool snapshot = false;
104  // bool vis_mesh = false; // Not supported by GLVis
105  double tau = 1.0;
106  double lambda = 0.1;
107  double amr_threshold = 0.6;
108  const char *keys = "gAm";
109  const char *device_config = "cpu";
110  const char *mesh_file = "../../data/mobius-strip.mesh";
111  void (*Tptr)(const Vector&, Vector&) = nullptr;
112 };
113 
114 class Surface: public Mesh
115 {
116 protected:
117  Opt &opt;
118  ParMesh *mesh;
119  Array<int> bc;
120  socketstream glvis;
121  H1_FECollection *fec;
123 public:
124  // Reading from mesh file
125  Surface(Opt &opt, const char *file): Mesh(file, true), opt(opt) { }
126 
127  // Generate 2D empty surface mesh
128  Surface(Opt &opt, bool): Mesh(), opt(opt) { }
129 
130  // Generate 2D quad surface mesh
131  Surface(Opt &opt)
132  : Mesh(Mesh::MakeCartesian2D(opt.nx, opt.ny, QUAD, true)), opt(opt) { }
133 
134  // Generate 2D generic surface mesh
135  Surface(Opt &opt, int nv, int ne, int nbe):
136  Mesh(DIM, nv, ne, nbe, SDIM), opt(opt) { }
137 
138  void Create()
139  {
140  if (opt.surface > 0)
141  {
142  Prefix();
143  Transform();
144  }
145  Postfix();
146  Refine();
147  Snap();
148  fec = new H1_FECollection(opt.order, DIM);
149  if (opt.amr) { EnsureNCMesh(); }
150  mesh = new ParMesh(MPI_COMM_WORLD, *this);
151  fes = new ParFiniteElementSpace(mesh, fec, opt.by_vdim ? 1 : SDIM);
152  BoundaryConditions();
153  }
154 
155  int Solve()
156  {
157  // Initialize GLVis server if 'visualization' is set
158  if (opt.vis) { opt.vis = glvis.open(vishost, visport) == 0; }
159  // Send to GLVis the first mesh
160  if (opt.vis) { Visualize(glvis, opt, mesh, GLVIZ_W, GLVIZ_H); }
161  // Create and launch the surface solver
162  if (opt.by_vdim)
163  {
164  ByVDim(*this, opt).Solve();
165  }
166  else
167  {
168  ByNodes(*this, opt).Solve();
169  }
170  if (opt.vis && opt.snapshot)
171  {
172  opt.keys = "Sq";
173  Visualize(glvis, opt, mesh, mesh->GetNodes());
174  }
175  return 0;
176  }
177 
178  ~Surface()
179  {
180  if (opt.vis) { glvis.close(); }
181  delete mesh; delete fec; delete fes;
182  }
183 
184  virtual void Prefix()
185  {
186  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
187  }
188 
189  virtual void Transform() { if (opt.Tptr) { Mesh::Transform(opt.Tptr); } }
190 
191  virtual void Postfix()
192  {
193  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
194  }
195 
196  virtual void Refine()
197  {
198  for (int l = 0; l < opt.refine; l++)
199  {
200  UniformRefinement();
201  }
202  }
203 
204  virtual void Snap()
205  {
206  GridFunction &nodes = *GetNodes();
207  for (int i = 0; i < nodes.Size(); i++)
208  {
209  if (std::abs(nodes(i)) < EPS)
210  {
211  nodes(i) = 0.0;
212  }
213  }
214  }
215 
216  void SnapNodesToUnitSphere()
217  {
218  Vector node(SDIM);
219  GridFunction &nodes = *GetNodes();
220  for (int i = 0; i < nodes.FESpace()->GetNDofs(); i++)
221  {
222  for (int d = 0; d < SDIM; d++)
223  {
224  node(d) = nodes(nodes.FESpace()->DofToVDof(i, d));
225  }
226  node /= node.Norml2();
227  for (int d = 0; d < SDIM; d++)
228  {
229  nodes(nodes.FESpace()->DofToVDof(i, d)) = node(d);
230  }
231  }
232  }
233 
234  virtual void BoundaryConditions()
235  {
236  if (bdr_attributes.Size())
237  {
238  Array<int> ess_bdr(bdr_attributes.Max());
239  ess_bdr = 1;
240  bc.HostReadWrite();
241  fes->GetEssentialTrueDofs(ess_bdr, bc);
242  }
243  }
244 
245  // Initialize visualization of some given mesh
246  static void Visualize(socketstream &glvis,
247  Opt &opt, const Mesh *mesh,
248  const int w, const int h,
249  const GridFunction *sol = nullptr)
250  {
251  const GridFunction &solution = sol ? *sol : *mesh->GetNodes();
252  glvis << "parallel " << opt.sz << " " << opt.id << "\n";
253  glvis << "solution\n" << *mesh << solution;
254  glvis.precision(8);
255  glvis << "window_size " << w << " " << h << "\n";
256  glvis << "keys " << opt.keys << "\n";
257  opt.keys = nullptr;
258  if (opt.wait) { glvis << "pause\n"; }
259  glvis << std::flush;
260  }
261 
262  // Visualize some solution on the given mesh
263  static void Visualize(socketstream &glvis,
264  const Opt &opt, const Mesh *mesh,
265  const GridFunction *sol = nullptr)
266  {
267  glvis << "parallel " << opt.sz << " " << opt.id << "\n";
268  const GridFunction &solution = sol ? *sol : *mesh->GetNodes();
269  glvis << "solution\n" << *mesh << solution;
270  if (opt.wait) { glvis << "pause\n"; }
271  if (opt.snapshot && opt.keys) { glvis << "keys " << opt.keys << "\n"; }
272  glvis << std::flush;
273  }
274 
275  using Mesh::Print;
276  static void Print(const Opt &opt, ParMesh *mesh, const GridFunction *sol)
277  {
278  const char *mesh_file = "surface.mesh";
279  const char *sol_file = "sol.gf";
280  if (!opt.id)
281  {
282  mfem::out << "Printing " << mesh_file << ", " << sol_file << std::endl;
283  }
284 
285  std::ostringstream mesh_name;
286  mesh_name << mesh_file << "." << std::setfill('0') << std::setw(6) << opt.id;
287  std::ofstream mesh_ofs(mesh_name.str().c_str());
288  mesh_ofs.precision(8);
289  mesh->Print(mesh_ofs);
290  mesh_ofs.close();
291 
292  std::ostringstream sol_name;
293  sol_name << sol_file << "." << std::setfill('0') << std::setw(6) << opt.id;
294  std::ofstream sol_ofs(sol_name.str().c_str());
295  sol_ofs.precision(8);
296  sol->Save(sol_ofs);
297  sol_ofs.close();
298  }
299 
300  // Surface Solver class
301  class Solver
302  {
303  protected:
304  Opt &opt;
305  Surface &S;
306  CGSolver cg;
307  OperatorPtr A;
309  ParGridFunction x, x0, b;
311  mfem::Solver *M = nullptr;
312  const int print_iter = -1, max_num_iter = 2000;
313  const double RTOLERANCE = EPS, ATOLERANCE = EPS*EPS;
314  public:
315  Solver(Surface &S, Opt &opt): opt(opt), S(S), cg(MPI_COMM_WORLD),
316  a(S.fes), x(S.fes), x0(S.fes), b(S.fes), one(1.0)
317  {
318  cg.SetRelTol(RTOLERANCE);
319  cg.SetAbsTol(ATOLERANCE);
320  cg.SetMaxIter(max_num_iter);
321  cg.SetPrintLevel(print_iter);
322  }
323 
324  ~Solver() { delete M; }
325 
326  void Solve()
327  {
328  constexpr bool converged = true;
329  if (opt.pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL);}
330  for (int i=0; i < opt.niters; ++i)
331  {
332  if (opt.amr) { Amr(); }
333  if (opt.vis) { Surface::Visualize(S.glvis, opt, S.mesh); }
334  if (!opt.id) { mfem::out << "Iteration " << i << ": "; }
335  S.mesh->NodesUpdated();
336  a.Update();
337  a.Assemble();
338  if (Step() == converged) { break; }
339  }
340  if (opt.print) { Surface::Print(opt, S.mesh, S.mesh->GetNodes()); }
341  }
342 
343  virtual bool Step() = 0;
344 
345  protected:
346  bool Converged(const double rnorm) { return rnorm < NRM; }
347 
348  bool ParAXeqB()
349  {
350  b = 0.0;
351  Vector X, B;
352  a.FormLinearSystem(S.bc, x, b, A, X, B);
353  if (!opt.pa) { M = new HypreBoomerAMG; }
354  if (M) { cg.SetPreconditioner(*M); }
355  cg.SetOperator(*A);
356  cg.Mult(B, X);
357  a.RecoverFEMSolution(X, b, x);
358  const bool by_vdim = opt.by_vdim;
359  GridFunction *nodes = by_vdim ? &x0 : S.fes->GetMesh()->GetNodes();
360  x.HostReadWrite();
361  nodes->HostRead();
362  double rnorm = nodes->DistanceTo(x) / nodes->Norml2();
363  double glob_norm;
364  MPI_Allreduce(&rnorm, &glob_norm, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
365  rnorm = glob_norm;
366  if (!opt.id) { mfem::out << "rnorm = " << rnorm << std::endl; }
367  const double lambda = opt.lambda;
368  if (by_vdim)
369  {
370  MFEM_VERIFY(!opt.radial,"'VDim solver can't use radial option!");
371  return Converged(rnorm);
372  }
373  if (opt.radial)
374  {
375  GridFunction delta(S.fes);
376  subtract(x, *nodes, delta); // delta = x - nodes
377  // position and Δ vectors at point i
378  Vector ni(SDIM), di(SDIM);
379  for (int i = 0; i < delta.Size()/SDIM; i++)
380  {
381  // extract local vectors
382  const int ndof = S.fes->GetNDofs();
383  for (int d = 0; d < SDIM; d++)
384  {
385  ni(d) = (*nodes)(d*ndof + i);
386  di(d) = delta(d*ndof + i);
387  }
388  // project the delta vector in radial direction
389  const double ndotd = (ni*di) / (ni*ni);
390  di.Set(ndotd,ni);
391  // set global vectors
392  for (int d = 0; d < SDIM; d++) { delta(d*ndof + i) = di(d); }
393  }
394  add(*nodes, delta, *nodes);
395  }
396  // x = lambda*nodes + (1-lambda)*x
397  add(lambda, *nodes, (1.0-lambda), x, x);
398  return Converged(rnorm);
399  }
400 
401  void Amr()
402  {
403  MFEM_VERIFY(opt.amr_threshold >= 0.0 && opt.amr_threshold <= 1.0, "");
404  Mesh *smesh = S.mesh;
405  Array<Refinement> amr;
406  const int NE = smesh->GetNE();
407  DenseMatrix Jadjt, Jadj(DIM, SDIM);
408  for (int e = 0; e < NE; e++)
409  {
410  double minW = +NL_DMAX;
411  double maxW = -NL_DMAX;
413  const Geometry::Type &type =
414  smesh->GetElement(e)->GetGeometryType();
415 
416  const IntegrationRule *ir = &IntRules.Get(type, opt.order);
417  const int NQ = ir->GetNPoints();
418  for (int q = 0; q < NQ; q++)
419  {
420  eTr->SetIntPoint(&ir->IntPoint(q));
421  const DenseMatrix &J = eTr->Jacobian();
422  CalcAdjugate(J, Jadj);
423  Jadjt = Jadj;
424  Jadjt.Transpose();
425  const double w = Jadjt.Weight();
426  minW = std::fmin(minW, w);
427  maxW = std::fmax(maxW, w);
428  }
429  if (std::fabs(maxW) != 0.0)
430  {
431  const double rho = minW / maxW;
432  MFEM_VERIFY(rho <= 1.0, "");
433  if (rho < opt.amr_threshold) { amr.Append(Refinement(e)); }
434  }
435  }
436  if (amr.Size()>0)
437  {
438  smesh->GetNodes()->HostReadWrite();
439  smesh->GeneralRefinement(amr);
440  S.fes->Update();
441  x.HostReadWrite();
442  x.Update();
443  a.Update();
444  b.HostReadWrite();
445  b.Update();
446  S.BoundaryConditions();
447  }
448  }
449  };
450 
451  // Surface solver 'by vector'
452  class ByNodes: public Solver
453  {
454  public:
455  ByNodes(Surface &S, Opt &opt): Solver(S, opt)
456  { a.AddDomainIntegrator(new VectorDiffusionIntegrator(one)); }
457 
458  bool Step()
459  {
460  x = *S.fes->GetMesh()->GetNodes();
461  bool converge = ParAXeqB();
462  S.mesh->SetNodes(x);
463  return converge ? true : false;
464  }
465  };
466 
467  // Surface solver 'by ByVDim'
468  class ByVDim: public Solver
469  {
470  public:
471  void SetNodes(const GridFunction &Xi, const int c)
472  {
473  auto d_Xi = Xi.Read();
474  auto d_nodes = S.fes->GetMesh()->GetNodes()->Write();
475  const int ndof = S.fes->GetNDofs();
476  MFEM_FORALL(i, ndof, d_nodes[c*ndof + i] = d_Xi[i]; );
477  }
478 
479  void GetNodes(GridFunction &Xi, const int c)
480  {
481  auto d_Xi = Xi.Write();
482  const int ndof = S.fes->GetNDofs();
483  auto d_nodes = S.fes->GetMesh()->GetNodes()->Read();
484  MFEM_FORALL(i, ndof, d_Xi[i] = d_nodes[c*ndof + i]; );
485  }
486 
487  ByVDim(Surface &S, Opt &opt): Solver(S, opt)
488  { a.AddDomainIntegrator(new DiffusionIntegrator(one)); }
489 
490  bool Step()
491  {
492  bool cvg[SDIM] {false};
493  for (int c=0; c < SDIM; ++c)
494  {
495  GetNodes(x, c);
496  x0 = x;
497  cvg[c] = ParAXeqB();
498  SetNodes(x, c);
499  }
500  const bool converged = cvg[0] && cvg[1] && cvg[2];
501  return converged ? true : false;
502  }
503  };
504 };
505 
506 // #0: Default surface mesh file
507 struct MeshFromFile: public Surface
508 {
509  MeshFromFile(Opt &opt): Surface(opt, opt.mesh_file) { }
510 };
511 
512 // #1: Catenoid surface
513 struct Catenoid: public Surface
514 {
515  Catenoid(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
516 
517  void Prefix()
518  {
519  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
520  Array<int> v2v(GetNV());
521  for (int i = 0; i < v2v.Size(); i++) { v2v[i] = i; }
522  // identify vertices on vertical lines
523  for (int j = 0; j <= opt.ny; j++)
524  {
525  const int v_old = opt.nx + j * (opt.nx + 1);
526  const int v_new = j * (opt.nx + 1);
527  v2v[v_old] = v_new;
528  }
529  // renumber elements
530  for (int i = 0; i < GetNE(); i++)
531  {
532  Element *el = GetElement(i);
533  int *v = el->GetVertices();
534  const int nv = el->GetNVertices();
535  for (int j = 0; j < nv; j++)
536  {
537  v[j] = v2v[v[j]];
538  }
539  }
540  // renumber boundary elements
541  for (int i = 0; i < GetNBE(); i++)
542  {
543  Element *el = GetBdrElement(i);
544  int *v = el->GetVertices();
545  const int nv = el->GetNVertices();
546  for (int j = 0; j < nv; j++)
547  {
548  v[j] = v2v[v[j]];
549  }
550  }
551  RemoveUnusedVertices();
552  RemoveInternalBoundaries();
553  }
554 
555  static void Parametrization(const Vector &x, Vector &p)
556  {
557  p.SetSize(SDIM);
558  // u in [0,2π] and v in [-π/6,π/6]
559  const double u = 2.0*PI*x[0];
560  const double v = PI*(x[1]-0.5)/3.;
561  p[0] = cos(u);
562  p[1] = sin(u);
563  p[2] = v;
564  }
565 };
566 
567 // #2: Helicoid surface
568 struct Helicoid: public Surface
569 {
570  Helicoid(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
571 
572  static void Parametrization(const Vector &x, Vector &p)
573  {
574  p.SetSize(SDIM);
575  // u in [0,2π] and v in [-2π/3,2π/3]
576  const double u = 2.0*PI*x[0];
577  const double v = 2.0*PI*(2.0*x[1]-1.0)/3.0;
578  p(0) = sin(u)*v;
579  p(1) = cos(u)*v;
580  p(2) = u;
581  }
582 };
583 
584 // #3: Enneper's surface
585 struct Enneper: public Surface
586 {
587  Enneper(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
588 
589  static void Parametrization(const Vector &x, Vector &p)
590  {
591  p.SetSize(SDIM);
592  // (u,v) in [-2, +2]
593  const double u = 4.0*(x[0]-0.5);
594  const double v = 4.0*(x[1]-0.5);
595  p[0] = +u - u*u*u/3.0 + u*v*v;
596  p[1] = -v - u*u*v + v*v*v/3.0;
597  p[2] = u*u - v*v;
598  }
599 };
600 
601 // #4: Hold surface
602 struct Hold: public Surface
603 {
604  Hold(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
605 
606  void Prefix()
607  {
608  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
609  Array<int> v2v(GetNV());
610  for (int i = 0; i < v2v.Size(); i++) { v2v[i] = i; }
611  // identify vertices on vertical lines
612  for (int j = 0; j <= opt.ny; j++)
613  {
614  const int v_old = opt.nx + j * (opt.nx + 1);
615  const int v_new = j * (opt.nx + 1);
616  v2v[v_old] = v_new;
617  }
618  // renumber elements
619  for (int i = 0; i < GetNE(); i++)
620  {
621  Element *el = GetElement(i);
622  int *v = el->GetVertices();
623  const int nv = el->GetNVertices();
624  for (int j = 0; j < nv; j++)
625  {
626  v[j] = v2v[v[j]];
627  }
628  }
629  // renumber boundary elements
630  for (int i = 0; i < GetNBE(); i++)
631  {
632  Element *el = GetBdrElement(i);
633  int *v = el->GetVertices();
634  const int nv = el->GetNVertices();
635  for (int j = 0; j < nv; j++)
636  {
637  v[j] = v2v[v[j]];
638  }
639  }
640  RemoveUnusedVertices();
641  RemoveInternalBoundaries();
642  }
643 
644  static void Parametrization(const Vector &x, Vector &p)
645  {
646  p.SetSize(SDIM);
647  // u in [0,2π] and v in [0,1]
648  const double u = 2.0*PI*x[0];
649  const double v = x[1];
650  p[0] = cos(u)*(1.0 + 0.3*sin(3.*u + PI*v));
651  p[1] = sin(u)*(1.0 + 0.3*sin(3.*u + PI*v));
652  p[2] = v;
653  }
654 };
655 
656 // #5: Costa minimal surface
657 #include <complex>
658 using cdouble = std::complex<double>;
659 #define I cdouble(0.0, 1.0)
660 
661 // https://dlmf.nist.gov/20.2
662 cdouble EllipticTheta(const int a, const cdouble u, const cdouble q)
663 {
664  cdouble J = 0.0;
665  double delta = std::numeric_limits<double>::max();
666  switch (a)
667  {
668  case 1:
669  for (int n=0; delta > EPS; n+=1)
670  {
671  const cdouble j = pow(-1,n)*pow(q,n*(n+1.0))*sin((2.0*n+1.0)*u);
672  delta = abs(j);
673  J += j;
674  }
675  return 2.0*pow(q,0.25)*J;
676 
677  case 2:
678  for (int n=0; delta > EPS; n+=1)
679  {
680  const cdouble j = pow(q,n*(n+1))*cos((2.0*n+1.0)*u);
681  delta = abs(j);
682  J += j;
683  }
684  return 2.0*pow(q,0.25)*J;
685  case 3:
686  for (int n=1; delta > EPS; n+=1)
687  {
688  const cdouble j = pow(q,n*n)*cos(2.0*n*u);
689  delta = abs(j);
690  J += j;
691  }
692  return 1.0 + 2.0*J;
693  case 4:
694  for (int n=1; delta > EPS; n+=1)
695  {
696  const cdouble j =pow(-1,n)*pow(q,n*n)*cos(2.0*n*u);
697  delta = abs(j);
698  J += j;
699  }
700  return 1.0 + 2.0*J;
701  }
702  return J;
703 }
704 
705 // https://dlmf.nist.gov/23.6#E5
707  const cdouble w1 = 0.5,
708  const cdouble w3 = 0.5*I)
709 {
710  const cdouble tau = w3/w1;
711  const cdouble q = exp(I*M_PI*tau);
712  const cdouble e1 = M_PI*M_PI/(12.0*w1*w1)*
713  (1.0*pow(EllipticTheta(2,0,q),4) +
714  2.0*pow(EllipticTheta(4,0,q),4));
715  const cdouble u = M_PI*z / (2.0*w1);
716  const cdouble P = M_PI * EllipticTheta(3,0,q)*EllipticTheta(4,0,q) *
717  EllipticTheta(2,u,q)/(2.0*w1*EllipticTheta(1,u,q));
718  return P*P + e1;
719 }
720 
721 cdouble EllipticTheta1Prime(const int k, const cdouble u, const cdouble q)
722 {
723  cdouble J = 0.0;
724  double delta = std::numeric_limits<double>::max();
725  for (int n=0; delta > EPS; n+=1)
726  {
727  const double alpha = 2.0*n+1.0;
728  const cdouble Dcosine = pow(alpha,k)*sin(k*M_PI/2.0 + alpha*u);
729  const cdouble j = pow(-1,n)*pow(q,n*(n+1.0))*Dcosine;
730  delta = abs(j);
731  J += j;
732  }
733  return 2.0*pow(q,0.25)*J;
734 }
735 
736 // Logarithmic Derivative of Theta Function 1
738 {
739  cdouble J = 0.0;
740  double delta = std::numeric_limits<double>::max();
741  for (int n=1; delta > EPS; n+=1)
742  {
743  cdouble q2n = pow(q, 2*n);
744  if (abs(q2n) < EPS) { q2n = 0.0; }
745  const cdouble j = q2n/(1.0-q2n)*sin(2.0*n*u);
746  delta = abs(j);
747  J += j;
748  }
749  return 1.0/tan(u) + 4.0*J;
750 }
751 
752 // https://dlmf.nist.gov/23.6#E13
754  const cdouble w1 = 0.5,
755  const cdouble w3 = 0.5*I)
756 {
757  const cdouble tau = w3/w1;
758  const cdouble q = exp(I*M_PI*tau);
759  const cdouble n1 = -M_PI*M_PI/(12.0*w1) *
760  (EllipticTheta1Prime(3,0,q)/
761  EllipticTheta1Prime(1,0,q));
762  const cdouble u = M_PI*z / (2.0*w1);
763  return z*n1/w1 + M_PI/(2.0*w1)*LogEllipticTheta1Prime(u,q);
764 }
765 
766 // https://www.mathcurve.com/surfaces.gb/costa/costa.shtml
767 static double ALPHA[4] {0.0};
768 struct Costa: public Surface
769 {
770  Costa(Opt &opt): Surface((opt.Tptr = Parametrization, opt), false) { }
771 
772  void Prefix()
773  {
774  ALPHA[3] = opt.tau;
775  const int nx = opt.nx, ny = opt.ny;
776  MFEM_VERIFY(nx>2 && ny>2, "");
777  const int nXhalf = (nx%2)==0 ? 4 : 2;
778  const int nYhalf = (ny%2)==0 ? 4 : 2;
779  const int nxh = nXhalf + nYhalf;
780  const int NVert = (nx+1) * (ny+1);
781  const int NElem = nx*ny - 4 - nxh;
782  const int NBdrElem = 0;
783  InitMesh(DIM, SDIM, NVert, NElem, NBdrElem);
784  // Sets vertices and the corresponding coordinates
785  for (int j = 0; j <= ny; j++)
786  {
787  const double cy = ((double) j / ny) ;
788  for (int i = 0; i <= nx; i++)
789  {
790  const double cx = ((double) i / nx);
791  const double coords[SDIM] = {cx, cy, 0.0};
792  AddVertex(coords);
793  }
794  }
795  // Sets elements and the corresponding indices of vertices
796  for (int j = 0; j < ny; j++)
797  {
798  for (int i = 0; i < nx; i++)
799  {
800  if (i == 0 && j == 0) { continue; }
801  if (i+1 == nx && j == 0) { continue; }
802  if (i == 0 && j+1 == ny) { continue; }
803  if (i+1 == nx && j+1 == ny) { continue; }
804  if ((j == 0 || j+1 == ny) && (abs(nx-(i<<1)-1)<=1)) { continue; }
805  if ((i == 0 || i+1 == nx) && (abs(ny-(j<<1)-1)<=1)) { continue; }
806  const int i0 = i + j*(nx+1);
807  const int i1 = i+1 + j*(nx+1);
808  const int i2 = i+1 + (j+1)*(nx+1);
809  const int i3 = i + (j+1)*(nx+1);
810  const int ind[4] = {i0, i1, i2, i3};
811  AddQuad(ind);
812  }
813  }
814  RemoveUnusedVertices();
815  FinalizeQuadMesh(false, 0, true);
816  FinalizeTopology();
817  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
818  }
819 
820  static void Parametrization(const Vector &X, Vector &p)
821  {
822  const double tau = ALPHA[3];
823  Vector x = X;
824  x -= +0.5;
825  x *= tau;
826  x -= -0.5;
827 
828  p.SetSize(3);
829  const bool y_top = x[1] > 0.5;
830  const bool x_top = x[0] > 0.5;
831  double u = x[0];
832  double v = x[1];
833  if (y_top) { v = 1.0 - x[1]; }
834  if (x_top) { u = 1.0 - x[0]; }
835  const cdouble w = u + I*v;
836  const cdouble w3 = I/2.;
837  const cdouble w1 = 1./2.;
838  const cdouble pw = WeierstrassP(w);
839  const cdouble e1 = WeierstrassP(0.5);
840  const cdouble zw = WeierstrassZeta(w);
841  const cdouble dw = WeierstrassZeta(w-w1) - WeierstrassZeta(w-w3);
842  p[0] = real(PI*(u+PI/(4.*e1))- zw +PI/(2.*e1)*(dw));
843  p[1] = real(PI*(v+PI/(4.*e1))-I*zw-PI*I/(2.*e1)*(dw));
844  p[2] = sqrt(PI/2.)*log(abs((pw-e1)/(pw+e1)));
845  if (y_top) { p[1] *= -1.0; }
846  if (x_top) { p[0] *= -1.0; }
847  const bool nan = std::isnan(p[0]) || std::isnan(p[1]) || std::isnan(p[2]);
848  MFEM_VERIFY(!nan, "nan");
849  ALPHA[0] = std::fmax(p[0], ALPHA[0]);
850  ALPHA[1] = std::fmax(p[1], ALPHA[1]);
851  ALPHA[2] = std::fmax(p[2], ALPHA[2]);
852  }
853 
854  void Snap()
855  {
856  Vector node(SDIM);
857  MFEM_VERIFY(ALPHA[0] > 0.0,"");
858  MFEM_VERIFY(ALPHA[1] > 0.0,"");
859  MFEM_VERIFY(ALPHA[2] > 0.0,"");
860  GridFunction &nodes = *GetNodes();
861  const double phi = (1.0 + sqrt(5.0)) / 2.0;
862  for (int i = 0; i < nodes.FESpace()->GetNDofs(); i++)
863  {
864  for (int d = 0; d < SDIM; d++)
865  {
866  const double alpha = d==2 ? phi : 1.0;
867  const int vdof = nodes.FESpace()->DofToVDof(i, d);
868  nodes(vdof) /= alpha * ALPHA[d];
869  }
870  }
871  }
872 };
873 
874 // #6: Shell surface model
875 struct Shell: public Surface
876 {
877  Shell(Opt &opt): Surface((opt.niters = 1, opt.Tptr = Parametrization, opt)) { }
878 
879  static void Parametrization(const Vector &x, Vector &p)
880  {
881  p.SetSize(3);
882  // u in [0,2π] and v in [-15, 6]
883  const double u = 2.0*PI*x[0];
884  const double v = 21.0*x[1]-15.0;
885  p[0] = +1.0*pow(1.16,v)*cos(v)*(1.0+cos(u));
886  p[1] = -1.0*pow(1.16,v)*sin(v)*(1.0+cos(u));
887  p[2] = -2.0*pow(1.16,v)*(1.0+sin(u));
888  }
889 };
890 
891 // #7: Scherk's doubly periodic surface
892 struct Scherk: public Surface
893 {
894  static void Parametrization(const Vector &x, Vector &p)
895  {
896  p.SetSize(SDIM);
897  const double alpha = 0.49;
898  // (u,v) in [-απ, +απ]
899  const double u = alpha*PI*(2.0*x[0]-1.0);
900  const double v = alpha*PI*(2.0*x[1]-1.0);
901  p[0] = u;
902  p[1] = v;
903  p[2] = log(cos(v)/cos(u));
904  }
905 
906  Scherk(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
907 };
908 
909 // #8: Full Peach street model
910 struct FullPeach: public Surface
911 {
912  static constexpr int NV = 8;
913  static constexpr int NE = 6;
914 
915  FullPeach(Opt &opt):
916  Surface((opt.niters = std::min(4, opt.niters), opt), NV, NE, 0) { }
917 
918  void Prefix()
919  {
920  const double quad_v[NV][SDIM] =
921  {
922  {-1, -1, -1}, {+1, -1, -1}, {+1, +1, -1}, {-1, +1, -1},
923  {-1, -1, +1}, {+1, -1, +1}, {+1, +1, +1}, {-1, +1, +1}
924  };
925  const int quad_e[NE][4] =
926  {
927  {3, 2, 1, 0}, {0, 1, 5, 4}, {1, 2, 6, 5},
928  {2, 3, 7, 6}, {3, 0, 4, 7}, {4, 5, 6, 7}
929 
930  };
931  for (int j = 0; j < NV; j++) { AddVertex(quad_v[j]); }
932  for (int j = 0; j < NE; j++) { AddQuad(quad_e[j], j+1); }
933 
934  FinalizeQuadMesh(false, 0, true);
935  FinalizeTopology(false);
936  UniformRefinement();
937  SetCurvature(opt.order, false, SDIM, Ordering::byNODES);
938  }
939 
940  void Snap() { SnapNodesToUnitSphere(); }
941 
942  void BoundaryConditions()
943  {
944  Vector X(SDIM);
945  Array<int> dofs;
946  Array<int> ess_vdofs, ess_tdofs;
947  ess_vdofs.SetSize(fes->GetVSize());
948  MFEM_VERIFY(fes->GetVSize() >= fes->GetTrueVSize(),"");
949  ess_vdofs = 0;
950  DenseMatrix PointMat;
951  mesh->GetNodes()->HostRead();
952  for (int e = 0; e < fes->GetNE(); e++)
953  {
954  fes->GetElementDofs(e, dofs);
955  const IntegrationRule &ir = fes->GetFE(e)->GetNodes();
957  eTr->Transform(ir, PointMat);
958  Vector one(dofs.Size());
959  for (int dof = 0; dof < dofs.Size(); dof++)
960  {
961  one = 0.0;
962  one[dof] = 1.0;
963  const int k = dofs[dof];
964  MFEM_ASSERT(k >= 0, "");
965  PointMat.Mult(one, X);
966  const bool halfX = std::fabs(X[0]) < EPS && X[1] <= 0.0;
967  const bool halfY = std::fabs(X[2]) < EPS && X[1] >= 0.0;
968  const bool is_on_bc = halfX || halfY;
969  for (int c = 0; c < SDIM; c++)
970  { ess_vdofs[fes->DofToVDof(k, c)] = is_on_bc; }
971  }
972  }
973  const SparseMatrix *R = fes->GetRestrictionMatrix();
974  if (!R)
975  {
976  ess_tdofs.MakeRef(ess_vdofs);
977  }
978  else
979  {
980  R->BooleanMult(ess_vdofs, ess_tdofs);
981  }
982  bc.HostReadWrite();
984  }
985 };
986 
987 // #9: 1/4th Peach street model
988 struct QuarterPeach: public Surface
989 {
990  QuarterPeach(Opt &opt): Surface((opt.Tptr = Parametrization, opt)) { }
991 
992  static void Parametrization(const Vector &X, Vector &p)
993  {
994  p = X;
995  const double x = 2.0*X[0]-1.0;
996  const double y = X[1];
997  const double r = sqrt(x*x + y*y);
998  const double t = (x==0.0) ? PI/2.0 :
999  (y==0.0 && x>0.0) ? 0. :
1000  (y==0.0 && x<0.0) ? PI : acos(x/r);
1001  const double sqrtx = sqrt(1.0 + x*x);
1002  const double sqrty = sqrt(1.0 + y*y);
1003  const bool yaxis = PI/4.0<t && t < 3.0*PI/4.0;
1004  const double R = yaxis?sqrtx:sqrty;
1005  const double gamma = r/R;
1006  p[0] = gamma * cos(t);
1007  p[1] = gamma * sin(t);
1008  p[2] = 1.0 - gamma;
1009  }
1010 
1011  void Postfix()
1012  {
1013  for (int i = 0; i < GetNBE(); i++)
1014  {
1015  Element *el = GetBdrElement(i);
1016  const int fn = GetBdrElementEdgeIndex(i);
1017  MFEM_VERIFY(!FaceIsTrueInterior(fn),"");
1018  Array<int> vertices;
1019  GetFaceVertices(fn, vertices);
1020  const GridFunction *nodes = GetNodes();
1021  Vector nval;
1022  double R[2], X[2][SDIM];
1023  for (int v = 0; v < 2; v++)
1024  {
1025  R[v] = 0.0;
1026  const int iv = vertices[v];
1027  for (int d = 0; d < SDIM; d++)
1028  {
1029  nodes->GetNodalValues(nval, d+1);
1030  const double x = X[v][d] = nval[iv];
1031  if (d < 2) { R[v] += x*x; }
1032  }
1033  }
1034  if (std::fabs(X[0][1])<=EPS && std::fabs(X[1][1])<=EPS &&
1035  (R[0]>0.1 || R[1]>0.1))
1036  { el->SetAttribute(1); }
1037  else { el->SetAttribute(2); }
1038  }
1039  }
1040 };
1041 
1042 // #10: Slotted sphere mesh
1043 struct SlottedSphere: public Surface
1044 {
1045  SlottedSphere(Opt &opt): Surface((opt.niters = 4, opt), 64, 40, 0) { }
1046 
1047  void Prefix()
1048  {
1049  constexpr double delta = 0.15;
1050  constexpr int NV1D = 4;
1051  constexpr int NV = NV1D*NV1D*NV1D;
1052  constexpr int NEPF = (NV1D-1)*(NV1D-1);
1053  constexpr int NE = NEPF*6;
1054  const double V1D[NV1D] = {-1.0, -delta, delta, 1.0};
1055  double QV[NV][3];
1056  for (int iv=0; iv<NV; ++iv)
1057  {
1058  int ix = iv % NV1D;
1059  int iy = (iv / NV1D) % NV1D;
1060  int iz = (iv / NV1D) / NV1D;
1061 
1062  QV[iv][0] = V1D[ix];
1063  QV[iv][1] = V1D[iy];
1064  QV[iv][2] = V1D[iz];
1065  }
1066  int QE[NE][4];
1067  for (int ix=0; ix<NV1D-1; ++ix)
1068  {
1069  for (int iy=0; iy<NV1D-1; ++iy)
1070  {
1071  int el_offset = ix + iy*(NV1D-1);
1072  // x = 0
1073  QE[0*NEPF + el_offset][0] = NV1D*ix + NV1D*NV1D*iy;
1074  QE[0*NEPF + el_offset][1] = NV1D*(ix+1) + NV1D*NV1D*iy;
1075  QE[0*NEPF + el_offset][2] = NV1D*(ix+1) + NV1D*NV1D*(iy+1);
1076  QE[0*NEPF + el_offset][3] = NV1D*ix + NV1D*NV1D*(iy+1);
1077  // x = 1
1078  int x_off = NV1D-1;
1079  QE[1*NEPF + el_offset][3] = x_off + NV1D*ix + NV1D*NV1D*iy;
1080  QE[1*NEPF + el_offset][2] = x_off + NV1D*(ix+1) + NV1D*NV1D*iy;
1081  QE[1*NEPF + el_offset][1] = x_off + NV1D*(ix+1) + NV1D*NV1D*(iy+1);
1082  QE[1*NEPF + el_offset][0] = x_off + NV1D*ix + NV1D*NV1D*(iy+1);
1083  // y = 0
1084  QE[2*NEPF + el_offset][0] = NV1D*NV1D*iy + ix;
1085  QE[2*NEPF + el_offset][1] = NV1D*NV1D*iy + ix + 1;
1086  QE[2*NEPF + el_offset][2] = NV1D*NV1D*(iy+1) + ix + 1;
1087  QE[2*NEPF + el_offset][3] = NV1D*NV1D*(iy+1) + ix;
1088  // y = 1
1089  int y_off = NV1D*(NV1D-1);
1090  QE[3*NEPF + el_offset][0] = y_off + NV1D*NV1D*iy + ix;
1091  QE[3*NEPF + el_offset][1] = y_off + NV1D*NV1D*iy + ix + 1;
1092  QE[3*NEPF + el_offset][2] = y_off + NV1D*NV1D*(iy+1) + ix + 1;
1093  QE[3*NEPF + el_offset][3] = y_off + NV1D*NV1D*(iy+1) + ix;
1094  // z = 0
1095  QE[4*NEPF + el_offset][0] = NV1D*iy + ix;
1096  QE[4*NEPF + el_offset][1] = NV1D*iy + ix + 1;
1097  QE[4*NEPF + el_offset][2] = NV1D*(iy+1) + ix + 1;
1098  QE[4*NEPF + el_offset][3] = NV1D*(iy+1) + ix;
1099  // z = 1
1100  int z_off = NV1D*NV1D*(NV1D-1);
1101  QE[5*NEPF + el_offset][0] = z_off + NV1D*iy + ix;
1102  QE[5*NEPF + el_offset][1] = z_off + NV1D*iy + ix + 1;
1103  QE[5*NEPF + el_offset][2] = z_off + NV1D*(iy+1) + ix + 1;
1104  QE[5*NEPF + el_offset][3] = z_off + NV1D*(iy+1) + ix;
1105  }
1106  }
1107  // Delete on x = 0 face
1108  QE[0*NEPF + 1 + 2*(NV1D-1)][0] = -1;
1109  QE[0*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1110  // Delete on x = 1 face
1111  QE[1*NEPF + 1 + 2*(NV1D-1)][0] = -1;
1112  QE[1*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1113  // Delete on y = 1 face
1114  QE[3*NEPF + 1 + 0*(NV1D-1)][0] = -1;
1115  QE[3*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1116  // Delete on z = 1 face
1117  QE[5*NEPF + 0 + 1*(NV1D-1)][0] = -1;
1118  QE[5*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1119  QE[5*NEPF + 2 + 1*(NV1D-1)][0] = -1;
1120  // Delete on z = 0 face
1121  QE[4*NEPF + 1 + 0*(NV1D-1)][0] = -1;
1122  QE[4*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1123  QE[4*NEPF + 1 + 2*(NV1D-1)][0] = -1;
1124  // Delete on y = 0 face
1125  QE[2*NEPF + 1 + 0*(NV1D-1)][0] = -1;
1126  QE[2*NEPF + 1 + 1*(NV1D-1)][0] = -1;
1127  for (int j = 0; j < NV; j++) { AddVertex(QV[j]); }
1128  for (int j = 0; j < NE; j++)
1129  {
1130  if (QE[j][0] < 0) { continue; }
1131  AddQuad(QE[j], j+1);
1132  }
1133  RemoveUnusedVertices();
1134  FinalizeQuadMesh(false, 0, true);
1135  EnsureNodes();
1136  FinalizeTopology();
1137  }
1138 
1139  void Snap() { SnapNodesToUnitSphere(); }
1140 };
1141 
1142 static int Problem0(Opt &opt)
1143 {
1144  // Create our surface mesh from command line options
1145  Surface *S = nullptr;
1146  switch (opt.surface)
1147  {
1148  case 0: S = new MeshFromFile(opt); break;
1149  case 1: S = new Catenoid(opt); break;
1150  case 2: S = new Helicoid(opt); break;
1151  case 3: S = new Enneper(opt); break;
1152  case 4: S = new Hold(opt); break;
1153  case 5: S = new Costa(opt); break;
1154  case 6: S = new Shell(opt); break;
1155  case 7: S = new Scherk(opt); break;
1156  case 8: S = new FullPeach(opt); break;
1157  case 9: S = new QuarterPeach(opt); break;
1158  case 10: S = new SlottedSphere(opt); break;
1159  default: MFEM_ABORT("Unknown surface (surface <= 10)!");
1160  }
1161  S->Create();
1162  S->Solve();
1163  delete S;
1164  return 0;
1165 }
1166 
1167 // Problem 1: solve the Dirichlet problem for the minimal surface equation
1168 // of the form z=f(x,y), using Picard iterations.
1169 static double u0(const Vector &x) { return sin(3.0 * PI * (x[1] + x[0])); }
1170 
1171 enum {NORM, AREA};
1172 
1173 static double qf(const int order, const int ker, Mesh &m,
1175 {
1176  const Geometry::Type type = m.GetElementBaseGeometry(0);
1177  const IntegrationRule &ir(IntRules.Get(type, order));
1179 
1180  const int NE(m.GetNE());
1181  const int ND(fes.GetFE(0)->GetDof());
1182  const int NQ(ir.GetNPoints());
1184  const GeometricFactors *geom = m.GetGeometricFactors(ir, flags);
1185 
1186  const int D1D = fes.GetFE(0)->GetOrder() + 1;
1187  const int Q1D = IntRules.Get(Geometry::SEGMENT, ir.GetOrder()).GetNPoints();
1188  MFEM_VERIFY(ND == D1D*D1D, "");
1189  MFEM_VERIFY(NQ == Q1D*Q1D, "");
1190 
1191  Vector Eu(ND*NE), grad_u(DIM*NQ*NE), sum(NE*NQ), one(NE*NQ);
1192  qi->SetOutputLayout(QVectorLayout::byVDIM);
1194  const Operator *G(fes.GetElementRestriction(e_ordering));
1195  G->Mult(u, Eu);
1196  qi->Derivatives(Eu, grad_u);
1197 
1198  auto W = Reshape(ir.GetWeights().Read(), Q1D, Q1D);
1199  auto J = Reshape(geom->J.Read(), Q1D, Q1D, DIM, DIM, NE);
1200  auto detJ = Reshape(geom->detJ.Read(), Q1D, Q1D, NE);
1201  auto grdU = Reshape(grad_u.Read(), DIM, Q1D, Q1D, NE);
1202  auto S = Reshape(sum.Write(), Q1D, Q1D, NE);
1203 
1204  MFEM_FORALL_2D(e, NE, Q1D, Q1D, 1,
1205  {
1206  MFEM_FOREACH_THREAD(qy,y,Q1D)
1207  {
1208  MFEM_FOREACH_THREAD(qx,x,Q1D)
1209  {
1210  const double w = W(qx, qy);
1211  const double J11 = J(qx, qy, 0, 0, e);
1212  const double J12 = J(qx, qy, 1, 0, e);
1213  const double J21 = J(qx, qy, 0, 1, e);
1214  const double J22 = J(qx, qy, 1, 1, e);
1215  const double det = detJ(qx, qy, e);
1216  const double area = w * det;
1217  const double gu0 = grdU(0, qx, qy, e);
1218  const double gu1 = grdU(1, qx, qy, e);
1219  const double tgu0 = (J22*gu0 - J12*gu1)/det;
1220  const double tgu1 = (J11*gu1 - J21*gu0)/det;
1221  const double ngu = tgu0*tgu0 + tgu1*tgu1;
1222  const double s = (ker == AREA) ? sqrt(1.0 + ngu) :
1223  (ker == NORM) ? ngu : 0.0;
1224  S(qx, qy, e) = area * s;
1225  }
1226  }
1227  });
1228  one = 1.0;
1229  return sum * one;
1230 }
1231 
1232 static int Problem1(Opt &opt)
1233 {
1234  const int order = opt.order;
1235  Mesh smesh = Mesh::MakeCartesian2D(opt.nx, opt.ny, QUAD);
1236  smesh.SetCurvature(opt.order, false, DIM, Ordering::byNODES);
1237  for (int l = 0; l < opt.refine; l++) { smesh.UniformRefinement(); }
1238  ParMesh mesh(MPI_COMM_WORLD, smesh);
1239  const H1_FECollection fec(order, DIM);
1240  ParFiniteElementSpace fes(&mesh, &fec);
1241  Array<int> ess_tdof_list;
1242  if (mesh.bdr_attributes.Size())
1243  {
1244  Array<int> ess_bdr(mesh.bdr_attributes.Max());
1245  ess_bdr = 1;
1246  fes.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
1247  }
1248  ParGridFunction uold(&fes), u(&fes), b(&fes);
1249  FunctionCoefficient u0_fc(u0);
1250  u.ProjectCoefficient(u0_fc);
1251  socketstream glvis;
1252  if (opt.vis) { opt.vis = glvis.open(vishost, visport) == 0; }
1253  if (opt.vis) { Surface::Visualize(glvis, opt, &mesh, GLVIZ_W, GLVIZ_H, &u); }
1254  Vector B, X;
1255  OperatorPtr A;
1256  CGSolver cg(MPI_COMM_WORLD);
1257  cg.SetRelTol(EPS);
1258  cg.SetAbsTol(EPS*EPS);
1259  cg.SetMaxIter(400);
1260  cg.SetPrintLevel(0);
1261  ParGridFunction eps(&fes);
1262  for (int i = 0; i < opt.niters; i++)
1263  {
1264  b = 0.0;
1265  uold = u;
1266  ParBilinearForm a(&fes);
1267  if (opt.pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
1268  const double q_uold = qf(order, AREA, mesh, fes, uold);
1269  MFEM_VERIFY(std::fabs(q_uold) > EPS,"");
1270  ConstantCoefficient q_uold_cc(1.0/sqrt(q_uold));
1271  a.AddDomainIntegrator(new DiffusionIntegrator(q_uold_cc));
1272  a.Assemble();
1273  a.FormLinearSystem(ess_tdof_list, u, b, A, X, B);
1274  cg.SetOperator(*A);
1275  cg.Mult(B, X);
1276  a.RecoverFEMSolution(X, b, u);
1277  subtract(u, uold, eps);
1278  const double norm = sqrt(std::fabs(qf(order, NORM, mesh, fes, eps)));
1279  const double area = qf(order, AREA, mesh, fes, u);
1280  if (!opt.id)
1281  {
1282  mfem::out << "Iteration " << i << ", norm: " << norm
1283  << ", area: " << area << std::endl;
1284  }
1285  if (opt.vis) { Surface::Visualize(glvis, opt, &mesh, &u); }
1286  if (opt.print) { Surface::Print(opt, &mesh, &u); }
1287  if (norm < NRM) { break; }
1288  }
1289  return 0;
1290 }
1291 
1292 int main(int argc, char *argv[])
1293 {
1294  Opt opt;
1295  Mpi::Init(argc, argv);
1296  opt.id = Mpi::WorldRank();
1297  opt.sz = Mpi::WorldSize();
1298  Hypre::Init();
1299 
1300  // Parse command-line options.
1301  OptionsParser args(argc, argv);
1302  args.AddOption(&opt.pb, "-p", "--problem", "Problem to solve.");
1303  args.AddOption(&opt.mesh_file, "-m", "--mesh", "Mesh file to use.");
1304  args.AddOption(&opt.wait, "-w", "--wait", "-no-w", "--no-wait",
1305  "Enable or disable a GLVis pause.");
1306  args.AddOption(&opt.radial, "-rad", "--radial", "-no-rad", "--no-radial",
1307  "Enable or disable radial constraints in solver.");
1308  args.AddOption(&opt.nx, "-x", "--num-elements-x",
1309  "Number of elements in x-direction.");
1310  args.AddOption(&opt.ny, "-y", "--num-elements-y",
1311  "Number of elements in y-direction.");
1312  args.AddOption(&opt.order, "-o", "--order", "Finite element order.");
1313  args.AddOption(&opt.refine, "-r", "--ref-levels", "Refinement");
1314  args.AddOption(&opt.niters, "-n", "--niter-max", "Max number of iterations");
1315  args.AddOption(&opt.surface, "-s", "--surface", "Choice of the surface.");
1316  args.AddOption(&opt.pa, "-pa", "--partial-assembly", "-no-pa",
1317  "--no-partial-assembly", "Enable Partial Assembly.");
1318  args.AddOption(&opt.tau, "-t", "--tau", "Costa scale factor.");
1319  args.AddOption(&opt.lambda, "-l", "--lambda", "Lambda step toward solution.");
1320  args.AddOption(&opt.amr, "-a", "--amr", "-no-a", "--no-amr", "Enable AMR.");
1321  args.AddOption(&opt.amr_threshold, "-at", "--amr-threshold", "AMR threshold.");
1322  args.AddOption(&opt.device_config, "-d", "--device",
1323  "Device configuration string, see Device::Configure().");
1324  args.AddOption(&opt.keys, "-k", "--keys", "GLVis configuration keys.");
1325  args.AddOption(&opt.vis, "-vis", "--visualization", "-no-vis",
1326  "--no-visualization", "Enable or disable visualization.");
1327  args.AddOption(&opt.by_vdim, "-c", "--solve-byvdim",
1328  "-no-c", "--solve-bynodes",
1329  "Enable or disable the 'ByVdim' solver");
1330  args.AddOption(&opt.print, "-print", "--print", "-no-print", "--no-print",
1331  "Enable or disable result output (files in mfem format).");
1332  args.AddOption(&opt.snapshot, "-ss", "--snapshot", "-no-ss", "--no-snapshot",
1333  "Enable or disable GLVis snapshot.");
1334  args.Parse();
1335  if (!args.Good()) { args.PrintUsage(mfem::out); return 1; }
1336  MFEM_VERIFY(opt.lambda >= 0.0 && opt.lambda <= 1.0,"");
1337  if (!opt.id) { args.PrintOptions(mfem::out); }
1338 
1339  // Initialize hardware devices
1340  Device device(opt.device_config);
1341  if (!opt.id) { device.Print(); }
1342 
1343  if (opt.pb == 0) { Problem0(opt); }
1344 
1345  if (opt.pb == 1) { Problem1(opt); }
1346 
1347  return 0;
1348 }
const T * Read(bool on_dev=true) const
Shortcut for mfem::Read(a.GetMemory(), a.Size(), on_dev).
Definition: array.hpp:307
const char vishost[]
T * HostReadWrite()
Shortcut for mfem::ReadWrite(a.GetMemory(), a.Size(), false).
Definition: array.hpp:327
static void Init()
Initialize hypre by calling HYPRE_Init() and set default options. After calling Hypre::Init(), hypre will be finalized automatically at program exit.
Definition: hypre.hpp:80
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1)
Definition: pfespace.cpp:1032
Conjugate gradient method.
Definition: solvers.hpp:493
int GetNPoints() const
Returns the number of the points in the integration rule.
Definition: intrules.hpp:247
Class for an integration rule - an Array of IntegrationPoint.
Definition: intrules.hpp:90
Class for grid function - Vector with associated FE space.
Definition: gridfunc.hpp:30
constexpr double NRM
const IntegrationRule & Get(int GeomType, int Order)
Returns an integration rule for given GeomType and Order.
Definition: intrules.cpp:923
A coefficient that is constant across space and time.
Definition: coefficient.hpp:84
const GeometricFactors * GetGeometricFactors(const IntegrationRule &ir, const int flags, MemoryType d_mt=MemoryType::DEFAULT)
Return the mesh geometric factors corresponding to the given integration rule.
Definition: mesh.cpp:840
virtual void GetVertices(Array< int > &v) const =0
Returns element&#39;s vertices.
void PrintOptions(std::ostream &out) const
Print the options.
Definition: optparser.cpp:324
Geometry::Type GetElementBaseGeometry(int i) const
Definition: mesh.hpp:1108
constexpr double PI
virtual const double * HostRead() const
Shortcut for mfem::Read(vec.GetMemory(), vec.Size(), false).
Definition: vector.hpp:452
void PrintUsage(std::ostream &out) const
Print the usage message.
Definition: optparser.cpp:454
Pointer to an Operator of a specified type.
Definition: handle.hpp:33
std::complex< double > cdouble
void SetIntPoint(const IntegrationPoint *ip)
Set the integration point ip that weights and Jacobians will be evaluated at.
Definition: eltrans.hpp:93
void CalcAdjugate(const DenseMatrix &a, DenseMatrix &adja)
Definition: densemat.cpp:2479
constexpr Element::Type QUAD
virtual void Mult(const Vector &b, Vector &x) const
Operator application: y=A(x).
Definition: solvers.cpp:712
int Size() const
Returns the size of the vector.
Definition: vector.hpp:199
T Max() const
Find the maximal element in the array, using the comparison operator < for class T.
Definition: array.cpp:68
Data type dense matrix using column-major storage.
Definition: densemat.hpp:23
void Transform(void(*f)(const Vector &, Vector &))
Definition: mesh.cpp:11691
int GetNDofs() const
Returns number of degrees of freedom.
Definition: fespace.hpp:584
virtual const double * Read(bool on_dev=true) const
Shortcut for mfem::Read(vec.GetMemory(), vec.Size(), on_dev).
Definition: vector.hpp:448
virtual void GetEssentialTrueDofs(const Array< int > &bdr_attr_is_ess, Array< int > &ess_tdof_list, int component=-1)
Get a list of essential true dofs, ess_tdof_list, corresponding to the boundary attributes marked in ...
Definition: fespace.cpp:564
virtual void Mult(const Vector &x, Vector &y) const =0
Operator application: y=A(x).
void Print(std::ostream &out=mfem::out)
Print the configuration of the MFEM virtual device object.
Definition: device.cpp:279
const Element * GetElement(int i) const
Definition: mesh.hpp:1081
cdouble LogEllipticTheta1Prime(const cdouble u, const cdouble q)
bool Good() const
Return true if the command line options were parsed successfully.
Definition: optparser.hpp:150
Abstract parallel finite element space.
Definition: pfespace.hpp:28
Structure for storing mesh geometric factors: coordinates, Jacobians, and determinants of the Jacobia...
Definition: mesh.hpp:1915
STL namespace.
static int WorldSize()
Return the size of MPI_COMM_WORLD.
double Weight() const
Definition: densemat.cpp:545
virtual const SparseMatrix * GetRestrictionMatrix() const
Get the R matrix which restricts a local dof vector to true dof vector.
Definition: pfespace.hpp:389
void add(const Vector &v1, const Vector &v2, Vector &v)
Definition: vector.cpp:314
virtual const FiniteElement * GetFE(int i) const
Returns pointer to the FiniteElement in the FiniteElementCollection associated with i&#39;th element in t...
Definition: fespace.cpp:2783
static void MarkerToList(const Array< int > &marker, Array< int > &list)
Convert a Boolean marker array to a list containing all marked indices.
Definition: fespace.cpp:598
IntegrationRules IntRules(0, Quadrature1D::GaussLegendre)
A global object with all integration rules (defined in intrules.cpp)
Definition: intrules.hpp:379
int close()
Close the socketstream.
const ElementRestrictionOperator * GetElementRestriction(ElementDofOrdering e_ordering) const
Return an Operator that converts L-vectors to E-vectors.
Definition: fespace.cpp:1259
constexpr int GLVIZ_W
The BoomerAMG solver in hypre.
Definition: hypre.hpp:1590
IntegrationPoint & IntPoint(int i)
Returns a reference to the i-th integration point.
Definition: intrules.hpp:250
Vector J
Jacobians of the element transformations at all quadrature points.
Definition: mesh.hpp:1956
const Array< double > & GetWeights() const
Return the quadrature weights in a contiguous array.
Definition: intrules.cpp:83
double DistanceTo(const double *p) const
Compute the Euclidean distance to another vector.
Definition: vector.hpp:664
virtual void SetPrintLevel(int print_lvl)
Legacy method to set the level of verbosity of the solver output.
Definition: solvers.cpp:71
constexpr int DIM
Geometry::Type GetGeometryType() const
Definition: element.hpp:52
void Parse()
Parse the command-line options. Note that this function expects all the options provided through the ...
Definition: optparser.cpp:151
Data type sparse matrix.
Definition: sparsemat.hpp:50
int Append(const T &el)
Append element &#39;el&#39; to array, resize if necessary.
Definition: array.hpp:756
virtual void Update()
Transform by the Space UpdateMatrix (e.g., on Mesh change).
Definition: pgridfunc.cpp:81
Vector detJ
Determinants of the Jacobians at all quadrature points.
Definition: mesh.hpp:1962
virtual double * Write(bool on_dev=true)
Shortcut for mfem::Write(vec.GetMemory(), vec.Size(), on_dev).
Definition: vector.hpp:456
A class that performs interpolation from an E-vector to quadrature point values and/or derivatives (Q...
double b
Definition: lissajous.cpp:42
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:9878
const DenseMatrix & Jacobian()
Return the Jacobian matrix of the transformation at the currently set IntegrationPoint, using the method SetIntPoint().
Definition: eltrans.hpp:119
int GetOrder() const
Returns the order of the integration rule.
Definition: intrules.hpp:240
int main(int argc, char *argv[])
void SetMaxIter(int max_it)
Definition: solvers.hpp:201
virtual void SetCurvature(int order, bool discont=false, int space_dim=-1, int ordering=1)
Set the curvature of the mesh nodes using the given polynomial degree.
Definition: mesh.cpp:5356
double delta
Definition: lissajous.cpp:43
Type
Constants for the classes derived from Element.
Definition: element.hpp:41
static void Init()
Singleton creation with Mpi::Init();.
const int visport
FiniteElementSpace * FESpace()
Definition: gridfunc.hpp:683
void Mult(const double *x, double *y) const
Matrix vector multiplication.
Definition: densemat.cpp:173
int GetNE() const
Returns number of elements in the mesh.
Definition: fespace.hpp:614
void GetNodalValues(int i, Array< double > &nval, int vdim=1) const
Returns the values in the vertices of i&#39;th element for dimension vdim.
Definition: gridfunc.cpp:396
virtual DofTransformation * GetElementDofs(int i, Array< int > &dofs) const
Returns indexes of degrees of freedom in array dofs for i&#39;th element.
Definition: pfespace.cpp:471
cdouble WeierstrassP(const cdouble z, const cdouble w1=0.5, const cdouble w3=0.5 *I)
void SetAbsTol(double atol)
Definition: solvers.hpp:200
Array< int > bdr_attributes
A list of all unique boundary attributes used by the Mesh.
Definition: mesh.hpp:275
void SetRelTol(double rtol)
Definition: solvers.hpp:199
void Transpose()
(*this) = (*this)^t
Definition: densemat.cpp:1420
virtual const FiniteElement * GetFE(int i) const
Definition: pfespace.cpp:535
Class FiniteElementSpace - responsible for providing FEM view of the mesh, mainly managing the set of...
Definition: fespace.hpp:96
cdouble EllipticTheta(const int a, const cdouble u, const cdouble q)
OutStream out(std::cout)
Global stream used by the library for standard output. Initially it uses the same std::streambuf as s...
Definition: globals.hpp:66
void subtract(const Vector &x, const Vector &y, Vector &z)
Definition: vector.cpp:461
constexpr double EPS
void AddOption(bool *var, const char *enable_short_name, const char *enable_long_name, const char *disable_short_name, const char *disable_long_name, const char *description, bool required=false)
Add a boolean option and set &#39;var&#39; to receive the value. Enable/disable tags are used to set the bool...
Definition: optparser.hpp:82
void SetSize(int nsize)
Change the logical size of the array, keep existing entries.
Definition: array.hpp:684
constexpr int SDIM
static Mesh MakeCartesian2D(int nx, int ny, Element::Type type, bool generate_edges=false, double sx=1.0, double sy=1.0, bool sfc_ordering=true)
Definition: mesh.cpp:3726
int GetDof() const
Returns the number of degrees of freedom in the finite element.
Definition: fe_base.hpp:322
void BooleanMult(const Array< int > &x, Array< int > &y) const
y = A * x, treating all entries as booleans (zero=false, nonzero=true).
Definition: sparsemat.cpp:1026
constexpr double NL_DMAX
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:936
virtual int GetTrueVSize() const
Return the number of local vector true dofs.
Definition: pfespace.hpp:289
double a
Definition: lissajous.cpp:41
const QuadratureInterpolator * GetQuadratureInterpolator(const IntegrationRule &ir) const
Return a QuadratureInterpolator that interpolates E-vectors to quadrature point values and/or derivat...
Definition: fespace.cpp:1327
void GetElementTransformation(int i, IsoparametricTransformation *ElTr)
Definition: mesh.cpp:348
ElementDofOrdering
Constants describing the possible orderings of the DOFs in one element.
Definition: fespace.hpp:74
int GetVSize() const
Return the number of vector dofs, i.e. GetNDofs() x GetVDim().
Definition: fespace.hpp:587
Lexicographic ordering for tensor-product FiniteElements.
virtual int GetNVertices() const =0
void SetAttribute(const int attr)
Set element&#39;s attribute.
Definition: element.hpp:58
Class for parallel bilinear form.
double Norml2() const
Returns the l2 norm of the vector.
Definition: vector.cpp:804
int open(const char hostname[], int port)
Open the socket stream on &#39;port&#39; at &#39;hostname&#39;.
static int WorldRank()
Return the MPI rank in MPI_COMM_WORLD.
int Size() const
Return the logical size of the array.
Definition: array.hpp:141
RefCoord t[3]
cdouble EllipticTheta1Prime(const int k, const cdouble u, const cdouble q)
void MakeRef(T *, int)
Make this Array a reference to a pointer.
Definition: array.hpp:869
virtual void SetOperator(const Operator &op)
Also calls SetOperator for the preconditioner if there is one.
Definition: solvers.hpp:507
const double alpha
Definition: ex15.cpp:369
A general function coefficient.
int DofToVDof(int dof, int vd, int ndofs=-1) const
Definition: fespace.cpp:251
Vector data type.
Definition: vector.hpp:60
virtual void Print(std::ostream &os=mfem::out) const
Definition: mesh.hpp:1749
virtual void Transform(const IntegrationPoint &, Vector &)=0
Transform integration point from reference coordinates to physical coordinates and store them in the ...
constexpr int GLVIZ_H
virtual void SetPreconditioner(Solver &pr)
This should be called before SetOperator.
Definition: solvers.cpp:173
Arbitrary order H1-conforming (continuous) finite elements.
Definition: fe_coll.hpp:252
void GetNodes(Vector &node_coord) const
Definition: mesh.cpp:7949
RefCoord s[3]
void Print(std::ostream &out=mfem::out) const override
Definition: pmesh.cpp:4839
double u(const Vector &xvec)
Definition: lor_mms.hpp:24
Base class for solvers.
Definition: operator.hpp:682
Class for parallel grid function.
Definition: pgridfunc.hpp:32
virtual void Save(std::ostream &out) const
Save the GridFunction to an output stream.
Definition: gridfunc.cpp:3673
The MFEM Device class abstracts hardware devices such as GPUs, as well as programming models such as ...
Definition: device.hpp:121
Abstract operator.
Definition: operator.hpp:24
MFEM_HOST_DEVICE DeviceTensor< sizeof...(Dims), T > Reshape(T *ptr, Dims... dims)
Wrap a pointer as a DeviceTensor with automatically deduced template parameters.
Definition: dtensor.hpp:131
const IntegrationRule & GetNodes() const
Get a const reference to the nodes of the element.
Definition: fe_base.hpp:388
void GeneralRefinement(const Array< Refinement > &refinements, int nonconforming=-1, int nc_limit=0)
Definition: mesh.cpp:9467
Class for parallel meshes.
Definition: pmesh.hpp:32
Abstract data type element.
Definition: element.hpp:28
cdouble WeierstrassZeta(const cdouble z, const cdouble w1=0.5, const cdouble w3=0.5 *I)
int GetOrder() const
Returns the order of the finite element. In the case of anisotropic orders, returns the maximum order...
Definition: fe_base.hpp:326
virtual double * HostReadWrite()
Shortcut for mfem::ReadWrite(vec.GetMemory(), vec.Size(), false).
Definition: vector.hpp:468
VDIM x NQPT x NE (values) / VDIM x DIM x NQPT x NE (grads)