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