MFEM  v3.2
Finite element discretization library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Pages
volta.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
2 // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
3 // reserved. See file COPYRIGHT for details.
4 //
5 // This file is part of the MFEM library. For more information and source code
6 // availability see http://mfem.org.
7 //
8 // MFEM is free software; you can redistribute it and/or modify it under the
9 // terms of the GNU Lesser General Public License (as published by the Free
10 // Software Foundation) version 2.1 dated February 1999.
11 //
12 // -----------------------------------------------------
13 // Volta Miniapp: Simple Electrostatics Simulation Code
14 // -----------------------------------------------------
15 //
16 // This miniapp solves a simple 2D or 3D electrostatic problem.
17 //
18 // Div eps Grad Phi = rho
19 //
20 // The permittivity function is that of the vacuum with an optional dielectric
21 // sphere. The charge density is either zero or a user defined sphere of charge.
22 //
23 // Boundary conditions for the electric potential consist of a user defined
24 // piecewise constant potential or a potential leading to a user selected
25 // uniform electric field.
26 //
27 // We discretize the electric potential with H1 finite elements. The electric
28 // field E is discretized with Nedelec finite elements.
29 //
30 // Compile with: make volta
31 //
32 // Sample runs:
33 //
34 // A cylinder at constant voltage in a square, grounded metal pipe:
35 // mpirun -np 4 volta -m ../../data/square-disc.mesh
36 // -dbcs '1 2 3 4 5 6 7 8' -dbcv '0 0 0 0 1 1 1 1'
37 //
38 // A cylinder with a constant surface charge density in a square,
39 // grounded metal pipe:
40 // mpirun -np 4 volta -m ../../data/square-disc.mesh
41 // -nbcs '5 6 7 8' -nbcv '5e-11 5e-11 5e-11 5e-11'
42 // -dbcs '1 2 3 4'
43 //
44 // A cylindrical voltaic pile within a grounded metal sphere:
45 // mpirun -np 4 volta -dbcs 1 -vp '0 -0.5 0 0 0.5 0 0.2 1'
46 //
47 // A charged sphere, off-center, within a grounded metal sphere:
48 // mpirun -np 4 volta -dbcs 1 -cs '0.0 0.5 0.0 0.2 2.0e-11'
49 //
50 // A dielectric sphere suspended in a uniform electric field:
51 // mpirun -np 4 volta -dbcs 1 -dbcg -ds '0.0 0.0 0.0 0.2 8.0'
52 //
53 // An example using piecewise constant permittivity values
54 // mpirun -np 4 volta -m llnl.mesh -dbcs '4' -dbcv '0'
55 // -cs '8.5 8.5 17 1.57' -pwe '1 1 1 0.001'
56 //
57 // By default the sources and fields are all zero:
58 // mpirun -np 4 volta
59 
60 #include "volta_solver.hpp"
61 #include <fstream>
62 #include <iostream>
63 
64 using namespace std;
65 using namespace mfem;
66 using namespace mfem::electromagnetics;
67 
68 // Physical Constants
69 // Permittivity of Free Space (units F/m)
70 static double epsilon0_ = 8.8541878176e-12;
71 
72 // Permittivity Functions
74 
75 static Vector pw_eps_(0); // Piecewise permittivity values
76 static Vector ds_params_(0); // Center, Radius, and Permittivity
77 // of dielectric sphere
78 double dielectric_sphere(const Vector &);
79 
80 // Charge Density Function
81 static Vector cs_params_(0); // Center, Radius, and Total Charge
82 // of charged sphere
83 double charged_sphere(const Vector &);
84 
85 // Polarization
86 static Vector vp_params_(0); // Axis Start, Axis End, Cylinder Radius,
87 // and Polarization Magnitude
88 void voltaic_pile(const Vector &, Vector &);
89 
90 // Phi Boundary Condition
91 static Vector e_uniform_(0);
92 double phi_bc_uniform(const Vector &);
93 
94 // Prints the program's logo to the given output stream
95 void display_banner(ostream & os);
96 
97 int main(int argc, char *argv[])
98 {
99  MPI_Session mpi(argc, argv);
100 
101  if ( mpi.Root() ) { display_banner(cout); }
102 
103  // Parse command-line options.
104  const char *mesh_file = "../../data/ball-nurbs.mesh";
105  int order = 1;
106  int maxit = 100;
107  int serial_ref_levels = 0;
108  int parallel_ref_levels = 0;
109  bool visualization = true;
110  bool visit = true;
111 
112  Array<int> dbcs;
113  Array<int> nbcs;
114 
115  Vector dbcv;
116  Vector nbcv;
117 
118  bool dbcg = false;
119 
120  OptionsParser args(argc, argv);
121  args.AddOption(&mesh_file, "-m", "--mesh",
122  "Mesh file to use.");
123  args.AddOption(&order, "-o", "--order",
124  "Finite element order (polynomial degree).");
125  args.AddOption(&serial_ref_levels, "-rs", "--serial-ref-levels",
126  "Number of serial refinement levels.");
127  args.AddOption(&parallel_ref_levels, "-rp", "--parallel-ref-levels",
128  "Number of parallel refinement levels.");
129  args.AddOption(&e_uniform_, "-uebc", "--uniform-e-bc",
130  "Specify if the three components of the constant electric field");
131  args.AddOption(&pw_eps_, "-pwe", "--piecewise-eps",
132  "Piecewise values of Permittivity");
133  args.AddOption(&ds_params_, "-ds", "--dielectric-sphere-params",
134  "Center, Radius, and Permittivity of Dielectric Sphere");
135  args.AddOption(&cs_params_, "-cs", "--charged-sphere-params",
136  "Center, Radius, and Total Charge of Charged Sphere");
137  args.AddOption(&vp_params_, "-vp", "--voltaic-pile-params",
138  "Axis End Points, Radius, and Polarization of Cylindrical Voltaic Pile");
139  args.AddOption(&dbcs, "-dbcs", "--dirichlet-bc-surf",
140  "Dirichlet Boundary Condition Surfaces");
141  args.AddOption(&dbcv, "-dbcv", "--dirichlet-bc-vals",
142  "Dirichlet Boundary Condition Values");
143  args.AddOption(&dbcg, "-dbcg", "--dirichlet-bc-gradient",
144  "-no-dbcg", "--no-dirichlet-bc-gradient",
145  "Dirichlet Boundary Condition Gradient (phi = -z)");
146  args.AddOption(&nbcs, "-nbcs", "--neumann-bc-surf",
147  "Neumann Boundary Condition Surfaces");
148  args.AddOption(&nbcv, "-nbcv", "--neumann-bc-vals",
149  "Neumann Boundary Condition Values");
150  args.AddOption(&maxit, "-maxit", "--max-amr-iterations",
151  "Max number of iterations in the main AMR loop.");
152  args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
153  "--no-visualization",
154  "Enable or disable GLVis visualization.");
155  args.AddOption(&visit, "-visit", "--visit", "-no-visit", "--no-visit",
156  "Enable or disable VisIt visualization.");
157  args.Parse();
158  if (!args.Good())
159  {
160  if (mpi.Root())
161  {
162  args.PrintUsage(cout);
163  }
164  return 1;
165  }
166  if (mpi.Root())
167  {
168  args.PrintOptions(cout);
169  }
170 
171  // Read the (serial) mesh from the given mesh file on all processors. We
172  // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
173  // and volume meshes with the same code.
174  Mesh *mesh = new Mesh(mesh_file, 1, 1);
175  int sdim = mesh->SpaceDimension();
176 
177  if (mpi.Root())
178  {
179  cout << "Starting initialization." << endl;
180  }
181 
182  // Project a NURBS mesh to a piecewise-quadratic curved mesh
183  if (mesh->NURBSext)
184  {
185  mesh->UniformRefinement();
186  if (serial_ref_levels > 0) { serial_ref_levels--; }
187 
188  mesh->SetCurvature(2);
189  }
190 
191  // Ensure that quad and hex meshes are treated as non-conforming.
192  mesh->EnsureNCMesh();
193 
194  // Refine the serial mesh on all processors to increase the resolution. In
195  // this example we do 'ref_levels' of uniform refinement. NURBS meshes are
196  // refined at least twice, as they are typically coarse.
197  for (int l = 0; l < serial_ref_levels; l++)
198  {
199  mesh->UniformRefinement();
200  }
201 
202  // Define a parallel mesh by a partitioning of the serial mesh. Refine
203  // this mesh further in parallel to increase the resolution. Once the
204  // parallel mesh is defined, the serial mesh can be deleted.
205  ParMesh pmesh(MPI_COMM_WORLD, *mesh);
206  delete mesh;
207 
208  // Refine this mesh in parallel to increase the resolution.
209  int par_ref_levels = parallel_ref_levels;
210  for (int l = 0; l < par_ref_levels; l++)
211  {
212  pmesh.UniformRefinement();
213  }
214 
215  // If the gradient bc was selected but the E field was not specified
216  // set a default vector value.
217  if ( dbcg && e_uniform_.Size() != sdim )
218  {
219  e_uniform_.SetSize(sdim);
220  e_uniform_ = 0.0;
221  e_uniform_(sdim-1) = 1.0;
222  }
223 
224  // If values for Dirichlet BCs were not set assume they are zero
225  if ( dbcv.Size() < dbcs.Size() && !dbcg )
226  {
227  dbcv.SetSize(dbcs.Size());
228  dbcv = 0.0;
229  }
230 
231  // If values for Neumann BCs were not set assume they are zero
232  if ( nbcv.Size() < nbcs.Size() )
233  {
234  nbcv.SetSize(nbcs.Size());
235  nbcv = 0.0;
236  }
237 
238  // Create a coefficient describing the dielectric permittivity
240 
241  // Create the Electrostatic solver
242  VoltaSolver Volta(pmesh, order, dbcs, dbcv, nbcs, nbcv, *epsCoef,
243  ( e_uniform_.Size() > 0 ) ? phi_bc_uniform : NULL,
244  ( cs_params_.Size() > 0 ) ? charged_sphere : NULL,
245  ( vp_params_.Size() > 0 ) ? voltaic_pile : NULL);
246 
247  // Initialize GLVis visualization
248  if (visualization)
249  {
250  Volta.InitializeGLVis();
251  }
252 
253  // Initialize VisIt visualization
254  VisItDataCollection visit_dc("Volta-AMR-Parallel", &pmesh);
255 
256  if ( visit )
257  {
258  Volta.RegisterVisItFields(visit_dc);
259  }
260  if (mpi.Root()) { cout << "Initialization done." << endl; }
261 
262  // The main AMR loop. In each iteration we solve the problem on the current
263  // mesh, visualize the solution, estimate the error on all elements, refine
264  // the worst elements and update all objects to work with the new mesh. We
265  // refine until the maximum number of dofs in the nodal finite element space
266  // reaches 10 million.
267  const int max_dofs = 10000000;
268  for (int it = 1; it <= maxit; it++)
269  {
270  if (mpi.Root())
271  {
272  cout << "\nAMR Iteration " << it << endl;
273  }
274 
275  // Display the current number of DoFs in each finite element space
276  Volta.PrintSizes();
277 
278  // Assemble all forms
279  Volta.Assemble();
280 
281  // Solve the system and compute any auxiliary fields
282  Volta.Solve();
283 
284  // Determine the current size of the linear system
285  int prob_size = Volta.GetProblemSize();
286 
287  // Write fields to disk for VisIt
288  if ( visit )
289  {
290  Volta.WriteVisItFields(it);
291  }
292 
293  // Send the solution by socket to a GLVis server.
294  if (visualization)
295  {
296  Volta.DisplayToGLVis();
297  }
298 
299  if (mpi.Root())
300  {
301  cout << "AMR iteration " << it << " complete." << endl;
302  }
303 
304  // Check stopping criteria
305  if (prob_size > max_dofs)
306  {
307  if (mpi.Root())
308  {
309  cout << "Reached maximum number of dofs, exiting..." << endl;
310  }
311  break;
312  }
313 
314  // Wait for user input. Ask every 10th iteration.
315  char c = 'c';
316  if (mpi.Root() && (it % 10 == 0))
317  {
318  cout << "press (q)uit or (c)ontinue --> " << flush;
319  cin >> c;
320  }
321  MPI_Bcast(&c, 1, MPI_CHAR, 0, MPI_COMM_WORLD);
322 
323  if (c != 'c')
324  {
325  break;
326  }
327 
328  // Estimate element errors using the Zienkiewicz-Zhu error estimator.
329  Vector errors(pmesh.GetNE());
330  Volta.GetErrorEstimates(errors);
331 
332  double local_max_err = errors.Max();
333  double global_max_err;
334  MPI_Allreduce(&local_max_err, &global_max_err, 1,
335  MPI_DOUBLE, MPI_MAX, pmesh.GetComm());
336 
337  // Refine the elements whose error is larger than a fraction of the
338  // maximum element error.
339  const double frac = 0.7;
340  double threshold = frac * global_max_err;
341  if (mpi.Root()) { cout << "Refining ..." << endl; }
342  pmesh.RefineByError(errors, threshold);
343 
344  // Update the electrostatic solver to reflect the new state of the mesh.
345  Volta.Update();
346 
347  if (pmesh.Nonconforming())
348  {
349  if (mpi.Root()) { cout << "Rebalancing ..." << endl; }
350  pmesh.Rebalance();
351 
352  // Update again after rebalancing
353  Volta.Update();
354  }
355  }
356 
357  delete epsCoef;
358 
359  return 0;
360 }
361 
362 // Print the Volta ascii logo to the given ostream
363 void display_banner(ostream & os)
364 {
365  os << " ____ ____ __ __ " << endl
366  << " \\ \\ / /___ | |_/ |______ " << endl
367  << " \\ Y / _ \\| |\\ __\\__ \\ " << endl
368  << " \\ ( <_> ) |_| | / __ \\_ " << endl
369  << " \\___/ \\____/|____/__| (____ / " << endl
370  << " \\/ " << endl << flush;
371 }
372 
373 // The Permittivity is a required coefficient which may be defined in
374 // various ways so we'll determine the appropriate coefficient type here.
375 Coefficient *
377 {
378  Coefficient * coef = NULL;
379 
380  if ( ds_params_.Size() > 0 )
381  {
383  }
384  else if ( pw_eps_.Size() > 0 )
385  {
386  coef = new PWConstCoefficient(pw_eps_);
387  }
388  else
389  {
390  coef = new ConstantCoefficient(epsilon0_);
391  }
392 
393  return coef;
394 }
395 
396 // A sphere with constant permittivity. The sphere has a radius,
397 // center, and permittivity specified on the command line and stored
398 // in ds_params_.
399 double dielectric_sphere(const Vector &x)
400 {
401  double r2 = 0.0;
402 
403  for (int i=0; i<x.Size(); i++)
404  {
405  r2 += (x(i)-ds_params_(i))*(x(i)-ds_params_(i));
406  }
407 
408  if ( sqrt(r2) <= ds_params_(x.Size()) )
409  {
410  return ds_params_(x.Size()+1) * epsilon0_;
411  }
412  return epsilon0_;
413 }
414 
415 // A sphere with constant charge density. The sphere has a radius,
416 // center, and total charge specified on the command line and stored
417 // in cs_params_.
418 double charged_sphere(const Vector &x)
419 {
420  double r2 = 0.0;
421  double rho = 0.0;
422 
423  if ( cs_params_(x.Size()) > 0.0 )
424  {
425  switch ( x.Size() )
426  {
427  case 2:
428  rho = cs_params_(x.Size()+1)/(M_PI*pow(cs_params_(x.Size()),2));
429  break;
430  case 3:
431  rho = 0.75*cs_params_(x.Size()+1)/(M_PI*pow(cs_params_(x.Size()),3));
432  break;
433  default:
434  rho = 0.0;
435  }
436  }
437 
438  for (int i=0; i<x.Size(); i++)
439  {
440  r2 += (x(i)-cs_params_(i))*(x(i)-cs_params_(i));
441  }
442 
443  if ( sqrt(r2) <= cs_params_(x.Size()) )
444  {
445  return rho;
446  }
447  return 0.0;
448 }
449 
450 // A Cylindrical Rod of constant polarization. The cylinder has two
451 // axis end points, a radius, and a constant electric polarization oriented
452 // along the axis.
453 void voltaic_pile(const Vector &x, Vector &p)
454 {
455  p.SetSize(x.Size());
456  p = 0.0;
457 
458  Vector a(x.Size()); // Normalized Axis vector
459  Vector xu(x.Size()); // x vector relative to the axis end-point
460 
461  xu = x;
462 
463  for (int i=0; i<x.Size(); i++)
464  {
465  xu[i] -= vp_params_[i];
466  a[i] = vp_params_[x.Size()+i] - vp_params_[i];
467  }
468 
469  double h = a.Norml2();
470 
471  if ( h == 0.0 )
472  {
473  return;
474  }
475 
476  double r = vp_params_[2*x.Size()];
477  double xa = xu*a;
478 
479  if ( h > 0.0 )
480  {
481  xu.Add(-xa/(h*h),a);
482  }
483 
484  double xp = xu.Norml2();
485 
486  if ( xa >= 0.0 && xa <= h*h && xp <= r )
487  {
488  p.Add(vp_params_[2*x.Size()+1]/h,a);
489  }
490 }
491 
492 // To produce a uniform electric field the potential can be set
493 // to (- Ex x - Ey y - Ez z).
494 double phi_bc_uniform(const Vector &x)
495 {
496  double phi = 0.0;
497 
498  for (int i=0; i<x.Size(); i++)
499  {
500  phi -= x(i) * e_uniform_(i);
501  }
502 
503  return phi;
504 }
double phi_bc_uniform(const Vector &)
Definition: volta.cpp:494
int Size() const
Logical size of the array.
Definition: array.hpp:109
Subclass constant coefficient.
Definition: coefficient.hpp:57
void SetSize(int s)
Resize the vector if the new size is different.
Definition: vector.hpp:263
double Norml2() const
Returns the l2 norm of the vector.
Definition: vector.cpp:644
int Size() const
Returns the size of the vector.
Definition: vector.hpp:86
int GetNE() const
Returns number of elements.
Definition: mesh.hpp:496
void RegisterVisItFields(VisItDataCollection &visit_dc)
int main(int argc, char *argv[])
void voltaic_pile(const Vector &, Vector &)
Definition: volta.cpp:453
void GetErrorEstimates(Vector &errors)
void Rebalance()
Load balance the mesh. NC meshes only.
Definition: pmesh.cpp:2255
bool Nonconforming() const
Definition: mesh.hpp:858
A simple convenience class that calls MPI_Init() at construction and MPI_Finalize() at destruction...
void UniformRefinement(int i, const DSTable &, int *, int *, int *)
Definition: mesh.cpp:6402
Data collection with VisIt I/O routines.
void SetCurvature(int order, bool discont=false, int space_dim=-1, int ordering=1)
Definition: mesh.cpp:3020
bool Root() const
Return true if WorldRank() == 0.
void PrintUsage(std::ostream &out) const
Definition: optparser.cpp:434
double charged_sphere(const Vector &)
Definition: volta.cpp:418
int SpaceDimension() const
Definition: mesh.hpp:524
MPI_Comm GetComm() const
Definition: pmesh.hpp:96
Base class Coefficient that may optionally depend on time.
Definition: coefficient.hpp:31
void AddOption(bool *var, const char *enable_short_name, const char *enable_long_name, const char *disable_short_name, const char *disable_long_name, const char *description, bool required=false)
Definition: optparser.hpp:74
bool RefineByError(const Array< double > &elem_error, double threshold, int nonconforming=-1, int nc_limit=0)
Definition: mesh.cpp:6130
NURBSExtension * NURBSext
Definition: mesh.hpp:143
class for piecewise constant coefficient
Definition: coefficient.hpp:72
Vector & Add(const double a, const Vector &Va)
(*this) += a * Va
Definition: vector.cpp:200
void PrintOptions(std::ostream &out) const
Definition: optparser.cpp:304
void display_banner(ostream &os)
Definition: tesla.cpp:357
void EnsureNCMesh(bool triangles_nonconforming=false)
Definition: mesh.cpp:6068
double dielectric_sphere(const Vector &)
Definition: volta.cpp:399
class for C-function coefficient
Vector data type.
Definition: vector.hpp:33
Coefficient * SetupPermittivityCoefficient()
Definition: volta.cpp:376
Class for parallel meshes.
Definition: pmesh.hpp:28
bool Good() const
Definition: optparser.hpp:120