Debian Codegraph @

examples/step-97/step-97.cc

raw
1 /* ------------------------------------------------------------------------
2 *
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 * Copyright (C) 2024 - 2025 by the deal.II authors
5 *
6 * This file is part of the deal.II library.
7 *
8 * Part of the source code is dual licensed under Apache-2.0 WITH
9 * LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 * governing the source code and code contributions can be found in
11 * LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 *
13 * ------------------------------------------------------------------------
14 *
15 * This program was contributed by Siarhei Uzunbajakau, www.cembooks.nl, 2025.
16 */
17
18 #include <deal.II/base/tensor.h>
19 #include <deal.II/base/function.h>
20 #include <deal.II/base/convergence_table.h>
21 #include <deal.II/base/timer.h>
22 #include <deal.II/base/types.h>
23 #include <deal.II/base/work_stream.h>
24 #include <deal.II/base/multithread_info.h>
25
26 #include <deal.II/grid/tria.h>
27 #include <deal.II/grid/grid_in.h>
28 #include <deal.II/grid/grid_out.h>
29 #include <deal.II/grid/manifold_lib.h>
30
31 #include <deal.II/dofs/dof_handler.h>
32 #include <deal.II/dofs/dof_tools.h>
33
34 #include <deal.II/fe/fe_nedelec.h>
35 #include <deal.II/fe/fe_raviart_thomas.h>
36 #include <deal.II/fe/mapping_q.h>
37 #include <deal.II/fe/fe_values.h>
38
39 #include <deal.II/lac/vector.h>
40 #include <deal.II/lac/sparse_matrix.h>
41 #include <deal.II/lac/affine_constraints.h>
42 #include <deal.II/lac/sparsity_pattern.h>
43 #include <deal.II/lac/dynamic_sparsity_pattern.h>
44 #include <deal.II/lac/solver_control.h>
45 #include <deal.II/lac/vector_memory.h>
46 #include <deal.II/lac/solver_cg.h>
47 #include <deal.II/lac/precondition.h>
48
49 #include <deal.II/numerics/vector_tools.h>
50 #include <deal.II/numerics/data_component_interpretation.h>
51 #include <deal.II/numerics/data_out.h>
52
53 #include <string>
54 #include <ostream>
55
56 using namespace dealii;
57
58 // This enumeration is used to switch between boundary conditions when solving
59 // for the magnetic vector potential, $\vec{A}$. The boundary condition is fixed
60 // (Dirichlet) when solving for the current vector potential, $\vec{T}$.
61 enum BoundaryConditionType
62 {
63 Dirichlet,
64 Neumann,
65 Robin
66 };
67
68 // @sect3{Settings}
69
70 // The following is the control panel of the program. The scaling of the
71 // program can be changed by setting `mu_0 = 1.0`. Then the computed magnetic
72 // field, $\vec{B}$, will have to be multiplied by a factor of
73 // $\mu_0 = 1.25664 \cdot 10^{-6}$. The free-current density, $\vec{J}_f$, does
74 // not depend on scaling. The setting `boundary_condition_type_A` can be used
75 // to switch between Dirichlet, Neumann, and Robin (ABC) boundary conditions.
76 // This has an effect only on the solver that solves for the magnetic vector
77 // potential, $\vec{A}$. The solver that solves for the current vector
78 // potential,
79 // $\vec{T}$, applies the Dirichlet boundary condition. This cannot be changed.
80 // Recall, that forcing to zero the tangential component of $\vec{T}$ on the
81 // boundary allows us to skip the boundary integral $I_{b3-2}$. The boundary ID
82 // is set in the geo files that describe the mesh geometry. This is done by
83 // specifying the physical surface, i.e.,
84 // @code
85 // Physical Surface(2) = {115, 479, 665, 297, 847, 1029};
86 // @endcode
87 // The boundary ID in the geo file must match the boundary ID setting below.
88 // If `project_exact_solution = true`, the program projects the exact
89 // solutions for $\vec{J}_f$ and $\vec{B}$ onto $H(\text{div})$ function space
90 // and saves the results into corresponding vtu files next to the numerical
91 // solutions. If the projected exact solution and the numerical solution look
92 // alike, it is a good sign. In case of problems with the convergence of the
93 // CG solver the parameter $\eta^2$ must be increased just a bit.
94 namespace Settings
95 {
96 const double permeability_fs = 1.2566370614359172954e-6;
97 const double mu_0 = permeability_fs; // Permeability of free space.
98
99 const double mu_r = 4; // Relative permeability of the magnetic material.
100 const double mu_1 = mu_0 * mu_r; // Permeability of the magnetic material.
101 const double d1 = 0.1; // Half-side of the cube in the center of the mesh.
102 const double a1 = 0.3; // Inner radius of the magnetic core.
103 const double b1 = 0.6; // Outer radius of the magnetic core.
104 const double a2 = 0.9; // Inner radius of the free-current region.
105 const double b2 = 1.2; // Outer radius of the free-current region.
106 const double d2 = 2.0; // Error norms are computed if r < d2.
107 const double K0 = 1.0; // Magnitude of the free-current density.
108 const double H0 = // Magnitude of H-field inside the coil, core removed.
109 (1.0 / 3.0) * K0 * (std::pow(b2, 2) - std::pow(a2, 2));
110 const types::material_id material_id_free_space =
111 1; // Material ID of the free space.
112 const types::material_id material_id_core =
113 2; // Material ID of the magnetic core.
114 const types::material_id material_id_free_current =
115 3; // Material ID of the free-current region.
116 const types::boundary_id boundary_id_infinity =
117 2; // Boundary ID. Set in the geo file.
118
119 const unsigned int mapping_degree = 2; // Mapping degree used in all solvers.
120 const unsigned int fe_degree = 0; // Degree of the finite elements.
121 const BoundaryConditionType boundary_condition_type_A = Robin;
122
123 const double eta_squared_T = 0.0; // eta^2 when solving for T$.
124 const double eta_squared_A = 0.0; // eta^2 when solving for A$.
125
126 const unsigned int n_threads_max = 0; // If >0 limits the number of threads.
127 const double eps = 1e-12; // Two doubles are equal if their difference < eps.
128 const bool log_cg_convergence = false; // Save the CG convergence data.
129 const bool print_time_tables = false; // Print the time tables on the screen.
130 const bool project_exact_solution = false; // Save the exact solution.
131 } // namespace Settings
132
133 // Next comes the weight function used to limit the region in which the $L^2$
134 // error norms are computed. The error norms are computed if $r < d2$.
135 class Weight : public Function<3>
136 {
137 public:
138 virtual double value(const Point<3> &p,
139 const unsigned int) const override final
140 {
141 if (p.norm() > Settings::d2)
142 return 0.0;
143
144 return 1.0;
145 }
146 };
147
148 // This class describes a convergence table. The convergence tables are saved on
149 // disk in TeX format.
150 class MainOutputTable : public ConvergenceTable
151 {
152 public:
153 MainOutputTable() = delete;
154
155 MainOutputTable(const unsigned int dimensions)
156 : ConvergenceTable()
157 , dimensions(dimensions)
158 {}
159
160 void set_new_order(const std::vector<std::string> &new_order_in)
161 {
162 new_order = new_order_in;
163 }
164
165 void append_new_order(const std::string &new_column)
166 {
167 new_order.push_back(new_column);
168 }
169
170 void format()
171 {
172 set_precision("L2", 2);
173
174 set_scientific("L2", true);
175
176 evaluate_convergence_rates("L2",
177 "ncells",
178 ConvergenceTable::reduction_rate_log2,
179 dimensions);
180
181 set_tex_caption("p", "p");
182 set_tex_caption("r", "r");
183 set_tex_caption("ncells", "nr. cells");
184 set_tex_caption("ndofs", "nr. dofs");
185 set_tex_caption("L2", "L2 norm");
186
187 set_column_order(new_order);
188 }
189
190 void save(const std::string &fname)
191 {
192 format();
193
194 std::ofstream ofs(fname + ".tex");
195 write_tex(ofs);
196 }
197
198 private:
199 const unsigned int dimensions;
200 std::vector<std::string> new_order = {"p", "r", "ncells", "ndofs", "L2"};
201 };
202
203 // @sect3{Equations}
204
205 // This name space contains all closed-form analytical expressions mentioned in
206 // the introduction to this tutorial.
207 namespace ExactSolutions
208 {
209
210 // This function describes the free-current density, $\vec{J}_f$, inside the
211 // current region.
212 inline Tensor<1, 3> volume_free_current_density(const Point<3> &p,
213 const double K0)
214 {
215 return Tensor<1, 3>({-K0 * p[1], K0 * p[0], 0.0});
216 }
217
218 // This function computes the magnetic field induced by the free current in
219 // absence of the magnetic core, see the expression for $\vec{B}_J$ in the
220 // introduction.
221 inline Tensor<1, 3> magnetic_field_coil(const Point<3> &p,
222 const double K0,
223 const double mu_0,
224 const double a2,
225 const double b2)
226 {
227 const double r = p.norm();
228
229 const double cos_theta = p[2] / r;
230 const double sin_theta =
231 std::sqrt(std::pow(p[0], 2) + std::pow(p[1], 2)) / r;
232
233 const double cos_phi =
234 p[0] / std::sqrt(std::pow(p[0], 2) + std::pow(p[1], 2));
235 const double sin_phi =
236 p[1] / std::sqrt(std::pow(p[0], 2) + std::pow(p[1], 2));
237
238 const Tensor<1, 3> r_hat({p[0] / r, p[1] / r, p[2] / r});
239 const Tensor<1, 3> theta_hat(
240 {cos_theta * cos_phi, cos_theta * sin_phi, -sin_theta});
241
242 const Tensor<1, 3> F1 =
243 (2.0 / 3.0) * mu_0 * K0 * (cos_theta * r_hat - sin_theta * theta_hat);
244 const Tensor<1, 3> F2 = (2.0 / 3.0) * mu_0 * K0 *
245 (cos_theta * r_hat + 0.5 * sin_theta * theta_hat) /
246 std::pow(r, 3);
247
248 if (r <= a2)
249 {
250 return 0.5 * (std::pow(b2, 2) - std::pow(a2, 2)) * F1;
251 }
252 else if (r >= b2)
253 {
254 return 0.2 * (std::pow(b2, 5) - std::pow(a2, 5)) * F2;
255 }
256 else
257 {
258 return 0.5 * (std::pow(b2, 2) - std::pow(r, 2)) * F1 +
259 0.2 * (std::pow(r, 5) - std::pow(a2, 5)) * F2;
260 }
261
262 return Tensor<1, 3>({0.404, 0.404, 0.404});
263 }
264
265 // This function computes the magnetic field induced by the magnetic core, see
266 // the expression for $\vec{B}_{\mu}$ in the introduction.
267 inline Tensor<1, 3> magnetic_field_core(const Point<3> &p,
268 const double H0,
269 const double mur,
270 const double mu0,
271 const double a1,
272 const double b1)
273 {
274 const double a3 = std::pow(a1, 3);
275 const double b3 = std::pow(b1, 3);
276
277 const double OMEGA = ((mur - 1.0) / (mur + 2.0)) * (a3 / b3);
278 const double gamma_1 = (-3.0 * b3 * H0 * OMEGA) /
279 ((2.0 * mur + 1.0) - 2.0 * (mur - 1.0) * OMEGA);
280 const double beta_1 = ((2.0 * mur + 1.0) * gamma_1) / ((mur - 1.0) * a3);
281 const double alpha_1 =
282 (-b3 * H0 + 2.0 * mur * gamma_1 - mur * b3 * beta_1) / 2.0;
283 const double delta_1 = (mur * a3 * beta_1 - 2.0 * mur * gamma_1) / a3;
284
285 const double r = p.norm();
286 const double r3 = std::pow(r, 3);
287 const double r5 = std::pow(r, 5);
288
289 const double zz = -3.0 * p[2] * p[2] / r5;
290 const double xz = -3.0 * p[0] * p[2] / r5;
291 const double yz = -3.0 * p[1] * p[2] / r5;
292
293 if (r <= a1)
294 {
295 return -mu0 * (Tensor<1, 3>({0.0, 0.0, delta_1}) +
296 Tensor<1, 3>({0.0, 0.0, H0}));
297 }
298 else if (r >= b1)
299 {
300 return -mu0 * (Tensor<1, 3>({alpha_1 * xz,
301 alpha_1 * yz,
302 -H0 + alpha_1 / r3 + alpha_1 * zz}) +
303 Tensor<1, 3>({0.0, 0.0, H0}));
304 }
305 else
306 {
307 return -mu0 *
308 (mur * Tensor<1, 3>({gamma_1 * xz,
309 gamma_1 * yz,
310 beta_1 + gamma_1 / r3 + gamma_1 * zz}) +
311 Tensor<1, 3>({0.0, 0.0, H0}));
312 }
313
314 return Tensor<1, 3>({0.404, 0.404, 0.404});
315 }
316
317 // This class implements the closed-form analytical expression for the
318 // free-current density, $\vec{J}_f$, in the entire domain.
319 class FreeCurrentDensity : public Function<3>
320 {
321 public:
322 FreeCurrentDensity()
323 : Function<3>(3)
324 {}
325
326 virtual void
327 vector_value_list(const std::vector<Point<3>> &p,
328 std::vector<Vector<double>> &values) const override final
329 {
330 Assert(values.size() == p.size(),
331 ExcDimensionMismatch(values.size(), p.size()));
332
333 double r;
334
335 for (unsigned int i = 0; i < values.size(); i++)
336 {
337 r = p[i].norm();
338
339 if ((r >= Settings::a2) && (r <= Settings::b2))
340 {
341 const Tensor<1, 3> Jf =
342 volume_free_current_density(p[i], Settings::K0);
343
344 values[i][0] = Jf[0];
345 values[i][1] = Jf[1];
346 values[i][2] = Jf[2];
347 }
348 else
349 {
350 values[i][0] = 0.0;
351 values[i][1] = 0.0;
352 values[i][2] = 0.0;
353 }
354 }
355 }
356 };
357
358 // This class implements the closed-form analytical expression for the
359 // magnetic field induced by the coil, $\vec{B} = \vec{B}_J + \vec{B}_{\mu}$,
360 // see the introduction.
361 class MagneticField : public Function<3>
362 {
363 public:
364 MagneticField()
365 : Function<3>(3)
366 {}
367
368 virtual void
369 vector_value_list(const std::vector<Point<3>> &p,
370 std::vector<Vector<double>> &values) const override final
371 {
372 Assert(values.size() == p.size(),
373 ExcDimensionMismatch(values.size(), p.size()));
374
375 Tensor<1, 3> B;
376
377 for (unsigned int i = 0; i < values.size(); i++)
378 {
379 using namespace Settings;
380 B = magnetic_field_coil(p[i], K0, mu_0, a2, b2) +
381 magnetic_field_core(p[i], H0, mu_r, mu_0, a1, b1);
382
383 values[i][0] = B[0];
384 values[i][1] = B[1];
385 values[i][2] = B[2];
386 }
387 }
388 };
389
390 } // namespace ExactSolutions
391
392 // @sect3{Solver - T}
393
394 // This name space contains all the code related to the computation of the
395 // current vector potential, $\vec{T}$.
396 namespace SolverT
397 {
398 // This class describes the free-current density, $\vec{J}_f$, on the
399 // right-hand side of the curl-curl equation, see equation (i) in the
400 // boundary value problem for $\vec{T}$. The free-current density is given as
401 // a closed-form analytical expression by the definition of the problem.
402 class FreeCurrentDensity
403 {
404 public:
405 void value_list(const std::vector<Point<3>> &p, // Quadrature points.
406 const types::material_id mid, // Material ID of the cell.
407 std::vector<Tensor<1, 3>> &values) const
408 {
409 Assert(p.size() == values.size(),
410 ExcDimensionMismatch(p.size(), values.size()));
411
412 if ((mid == Settings::material_id_free_space) ||
413 (mid == Settings::material_id_core))
414 for (unsigned int i = 0; i < values.size(); i++)
415 values[i] = Tensor<1, 3>({0.0, 0.0, 0.0});
416
417 if (mid == Settings::material_id_free_current)
418 for (unsigned int i = 0; i < values.size(); i++)
419 values[i] =
420 ExactSolutions::volume_free_current_density(p[i], Settings::K0);
421 }
422 };
423
424 // This class implements the solver that minimizes the functional
425 // $F(\vec{T})$, see the introduction. The mesh is loaded in this class.
426 // All other solvers use a reference to this mesh.
427 class Solver
428 {
429 public:
430 Solver() = delete;
431 Solver(const unsigned int p, // Degree of the Nedelec finite elements.
432 const unsigned int r, // The mesh refinement parameter.
433 const unsigned int mapping_degree,
434 const double eta_squared = 0.0,
435 const std::string &fname = "data");
436
437 void make_mesh(); // Loads the mesh. Assigns mat. IDs. Attaches manifold.
438 void setup(); // Initializes dofs, vectors, matrices.
439 void assemble(); // Assembles the system of linear equations.
440 void solve(); // Solves the system of linear equations.
441 void save() const; // Saves computed T into a vtu file.
442 void clear()
443 { // Clears the memory for the next solver.
444 system_matrix.clear();
445 system_rhs.reinit(0);
446 }
447 void run(); /* Executes the last six functions in the proper order
448 and measures the execution time for each function. */
449
450 // These three get-functions are used to channel the mesh and the solution
451 // to the next solver.
452 const Triangulation<3> &get_tria() const
453 {
454 return triangulation;
455 }
456 const DoFHandler<3> &get_dof_handler() const
457 {
458 return dof_handler;
459 }
460 const Vector<double> &get_solution() const
461 {
462 return solution;
463 }
464
465 private:
466 // The following data members are typical for all deal.II simulations:
467 // triangulation, finite elements, dof handlers, etc. The constraints
468 // are used to enforce the Dirichlet boundary conditions. The names of the
469 // data members are self-explanatory.
470
471 Triangulation<3> triangulation;
472
473 const FE_Nedelec<3> fe;
474 DoFHandler<3> dof_handler;
475 Vector<double> solution;
476
477 SparseMatrix<double> system_matrix;
478 Vector<double> system_rhs;
479
480 AffineConstraints<double> constraints;
481 SparsityPattern sparsity_pattern;
482
483 SphericalManifold<3> sphere;
484
485 const unsigned int refinement_parameter;
486 const unsigned int mapping_degree;
487 const double eta_squared;
488 const std::string fname;
489 TimerOutput timer;
490
491 // The program utilizes the WorkStream technology. The Step-9 tutorial
492 // does a much better job of explaining the workings of WorkStream.
493 // Reading the "WorkStream paper", see the glossary, is recommended.
494 // The following structures and functions are related to WorkStream.
495 struct AssemblyScratchData
496 {
497 AssemblyScratchData(const FiniteElement<3> &fe,
498 const double eta_squared,
499 const unsigned int mapping_degree);
500
501 AssemblyScratchData(const AssemblyScratchData &scratch_data);
502
503 const FreeCurrentDensity Jf;
504
505 MappingQ<3> mapping;
506 FEValues<3> fe_values;
507
508 const unsigned int dofs_per_cell;
509 const unsigned int n_q_points;
510
511 std::vector<Tensor<1, 3>> Jf_list;
512
513 const double eta_squared;
514 const FEValuesExtractors::Vector ve;
515 };
516
517 struct AssemblyCopyData
518 {
519 FullMatrix<double> cell_matrix;
520 Vector<double> cell_rhs;
521 std::vector<types::global_dof_index> local_dof_indices;
522 };
523
524 void system_matrix_local(
525 const typename DoFHandler<3>::active_cell_iterator &cell,
526 AssemblyScratchData &scratch_data,
527 AssemblyCopyData &copy_data);
528
529 void copy_local_to_global(const AssemblyCopyData &copy_data);
530 };
531
532 Solver::Solver(const unsigned int p,
533 const unsigned int r,
534 const unsigned int mapping_degree,
535 const double eta_squared,
536 const std::string &fname)
537 : fe(p)
538 , refinement_parameter(r)
539 , mapping_degree(mapping_degree)
540 , eta_squared(eta_squared)
541 , fname(fname)
542 , timer(std::cout,
543 (Settings::print_time_tables) ? TimerOutput::summary :
544 TimerOutput::never,
545 TimerOutput::cpu_and_wall_times_grouped)
546 {}
547
548 // The following function loads the mesh, assigns material IDs to all cells,
549 // and attaches the spherical manifold to the mesh. The material IDs are
550 // assigned on the basis of the distance from the center of a cell to the
551 // origin. The spherical manifold is attached to a face if all vertices of
552 // the face are at the same distance from the origin provided the cell is
553 // outside the cube in the center of the mesh, see mesh description in the
554 // introduction.
555 void Solver::make_mesh()
556 {
557 GridIn<3> gridin;
558
559 gridin.attach_triangulation(triangulation);
560 std::ifstream ifs("sphere_r" + std::to_string(refinement_parameter) +
561 ".msh");
562 gridin.read_msh(ifs);
563
564 triangulation.reset_all_manifolds();
565
566 for (auto cell : triangulation.active_cell_iterators())
567 {
568 cell->set_material_id(
569 Settings::material_id_free_space); // The cell is in free space.
570
571 if ((cell->center().norm() > Settings::a1) &&
572 (cell->center().norm() < Settings::b1))
573 cell->set_material_id(
574 Settings::material_id_core); // The cell is inside the core.
575
576 if ((cell->center().norm() > Settings::a2) &&
577 (cell->center().norm() < Settings::b2))
578 cell->set_material_id(
579 Settings::material_id_free_current); /* The cell is inside the Jf
580 region. */
581
582 for (unsigned int f = 0; f < cell->n_faces(); f++)
583 {
584 double dif_norm = 0.0;
585 for (unsigned int v = 1; v < cell->face(f)->n_vertices(); v++)
586 dif_norm += std::abs(cell->face(f)->vertex(0).norm() -
587 cell->face(f)->vertex(v).norm());
588
589 if ((dif_norm < Settings::eps) &&
590 (cell->center().norm() > Settings::d1))
591 cell->face(f)->set_all_manifold_ids(1);
592 }
593 }
594
595 triangulation.set_manifold(1, sphere);
596 }
597
598 // This function initializes the dofs, applies the Dirichlet boundary
599 // condition, and initializes the vectors and matrices.
600 void Solver::setup()
601 {
602 dof_handler.reinit(triangulation);
603 dof_handler.distribute_dofs(fe);
604
605 // The following segment of the code applies the homogeneous Dirichlet
606 // boundary condition. As discussed in the introduction, the Dirichlet
607 // boundary condition is an essential condition and must be enforced
608 // by constraining the system matrix. This segment of the code does the
609 // constraining.
610 constraints.clear();
611
612 DoFTools::make_hanging_node_constraints(dof_handler, constraints);
613
614 VectorTools::project_boundary_values_curl_conforming_l2(
615 dof_handler,
616 0, // The first vector component.
617 Functions::ZeroFunction<3>(3),
618 Settings::boundary_id_infinity,
619 constraints,
620 MappingQ<3>(mapping_degree));
621
622 constraints.close();
623
624 // The rest of the function arranges the dofs in a sparsity pattern and
625 // initializes the system matrices and vectors.
626 DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());
627 DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false);
628 sparsity_pattern.copy_from(dsp);
629
630 system_matrix.reinit(sparsity_pattern);
631 solution.reinit(dof_handler.n_dofs());
632 system_rhs.reinit(dof_handler.n_dofs());
633 }
634
635 // Formally, the following function assembles the system of linear equations.
636 // In reality, however, it just spells all the magic words to get the
637 // WorkStream going. The interesting part, i.e., the actual assembling of the
638 // system matrix and the right-hand side, happens below in the function
639 // Solver::system_matrix_local().
640 void Solver::assemble()
641 {
642 WorkStream::run(dof_handler.begin_active(),
643 dof_handler.end(),
644 *this,
645 &Solver::system_matrix_local,
646 &Solver::copy_local_to_global,
647 AssemblyScratchData(fe, eta_squared, mapping_degree),
648 AssemblyCopyData());
649 }
650
651 // The following two constructors initialize scratch data from the input
652 // parameters and from another object of the same type, i.e., a copy
653 // constructor.
654 Solver::AssemblyScratchData::AssemblyScratchData(
655 const FiniteElement<3> &fe,
656 const double eta_squared,
657 const unsigned int mapping_degree)
658 : Jf()
659 , mapping(mapping_degree)
660 , fe_values(mapping,
661 fe,
662 QGauss<3>(fe.degree + 2),
663 update_gradients | update_values | update_quadrature_points |
664 update_JxW_values)
665 , dofs_per_cell(fe_values.dofs_per_cell)
666 , n_q_points(fe_values.get_quadrature().size())
667 , Jf_list(n_q_points, Tensor<1, 3>())
668 , eta_squared(eta_squared)
669 , ve(0)
670 {}
671
672 Solver::AssemblyScratchData::AssemblyScratchData(
673 const AssemblyScratchData &scratch_data)
674 : Jf()
675 , mapping(scratch_data.mapping.get_degree())
676 , fe_values(mapping,
677 scratch_data.fe_values.get_fe(),
678 scratch_data.fe_values.get_quadrature(),
679 update_gradients | update_values | update_quadrature_points |
680 update_JxW_values)
681 , dofs_per_cell(fe_values.dofs_per_cell)
682 , n_q_points(fe_values.get_quadrature().size())
683 , Jf_list(n_q_points, Tensor<1, 3>())
684 , eta_squared(scratch_data.eta_squared)
685 , ve(0)
686 {}
687
688 // This function assembles a fraction of the system matrix and the system
689 // right-hand side related to a single cell. These fractions are
690 // `copy_data.cell_matrix` and `copy_data.cell_rhs`. They are copied into
691 // the system matrix, $A_{ij}$, and the right-hand side, $b_i$, by the
692 // function `Solver::copy_local_to_global()`.
693 void Solver::system_matrix_local(
694 const typename DoFHandler<3>::active_cell_iterator &cell,
695 AssemblyScratchData &scratch_data,
696 AssemblyCopyData &copy_data)
697 {
698 // First, we reinitialize the matrices and vectors related to the current
699 // cell and compute the FE values.
700 copy_data.cell_matrix.reinit(scratch_data.dofs_per_cell,
701 scratch_data.dofs_per_cell);
702
703 copy_data.cell_rhs.reinit(scratch_data.dofs_per_cell);
704
705 copy_data.local_dof_indices.resize(scratch_data.dofs_per_cell);
706
707 scratch_data.fe_values.reinit(cell);
708
709 // Second, we compute the free-current density, $\vec{J}_f$, at the
710 // quadrature points.
711 scratch_data.Jf.value_list(scratch_data.fe_values.get_quadrature_points(),
712 cell->material_id(),
713 scratch_data.Jf_list);
714
715 // Third, we compute the components of the cell matrix and cell right-hand
716 // side. The labels of the integrals are the same as in the introduction to
717 // this tutorial.
718 for (unsigned int q_index = 0; q_index < scratch_data.n_q_points; ++q_index)
719 {
720 for (unsigned int i = 0; i < scratch_data.dofs_per_cell; ++i)
721 {
722 for (unsigned int j = 0; j < scratch_data.dofs_per_cell; ++j)
723 {
724 copy_data.cell_matrix(i, j) += // Integral I_a1+I_a3.
725 (scratch_data.fe_values[scratch_data.ve].curl(
726 i, q_index) * // curl N_i
727 scratch_data.fe_values[scratch_data.ve].curl(
728 j, q_index) // curl N_j
729 + scratch_data.eta_squared * // eta^2
730 scratch_data.fe_values[scratch_data.ve].value(
731 i, q_index) * // N_i
732 scratch_data.fe_values[scratch_data.ve].value(
733 j, q_index) // N_j
734 ) *
735 scratch_data.fe_values.JxW(q_index); // dV
736 }
737 copy_data.cell_rhs(i) += // Integral I_b3-1.
738 (scratch_data.Jf_list[q_index] *
739 scratch_data.fe_values[scratch_data.ve].curl(i, q_index)) *
740 scratch_data.fe_values.JxW(q_index); // J_f.(curl N_i)dV.
741 }
742 }
743
744 // Finally, we query the dof indices on the current cell and store them
745 // in the copy data structure, so we know to which locations of the system
746 // matrix and right-hand side the components of the cell matrix and
747 // cell right-hand side must be copied.
748 cell->get_dof_indices(copy_data.local_dof_indices);
749 }
750
751 // This function copies the components of a cell matrix and a cell right-hand
752 // side into the system matrix, $A_{i,j}$, and the system right-hand side,
753 // $b_i$.
754 void Solver::copy_local_to_global(const AssemblyCopyData &copy_data)
755 {
756 constraints.distribute_local_to_global(copy_data.cell_matrix,
757 copy_data.cell_rhs,
758 copy_data.local_dof_indices,
759 system_matrix,
760 system_rhs);
761 }
762
763 // This function solves the system of linear equations.
764 // If `Settings::log_cg_convergence == true`, the convergence data is saved
765 // into a file. In theory, a CG solver can solve an $m \times m$ system of
766 // linear equations in at most $m$ steps. In practice, it can take more steps
767 // to converge. The convergence of the algorithm depends on the spectral
768 // properties of the system matrix. The best case is if the eigenvalues form a
769 // compact cluster away from zero. In our case, however, the eigenvalues are
770 // spread in between zero and the maximal eigenvalue. Consequently, we expect
771 // a poor convergence and increase the maximal number of iteration steps by a
772 // factor of 10, i.e., `10*system_rhs.size()`. The stopping condition is \f[
773 // |\boldsymbol{b} - \boldsymbol{A}\boldsymbol{c}|
774 // < 10^{-6} |\boldsymbol{b}|.
775 // \f]
776 // As soon as we use constraints, we must not forget to distribute them.
777 void Solver::solve()
778 {
779 SolverControl control(10 * system_rhs.size(),
780 1.0e-6 * system_rhs.l2_norm(),
781 false,
782 false);
783
784 if (Settings::log_cg_convergence)
785 control.enable_history_data();
786
787 GrowingVectorMemory<Vector<double>> memory;
788 SolverCG<Vector<double>> cg(control, memory);
789
790 PreconditionSSOR<SparseMatrix<double>> preconditioner;
791 preconditioner.initialize(system_matrix, 1.2);
792
793 cg.solve(system_matrix, solution, system_rhs, preconditioner);
794
795 constraints.distribute(solution);
796
797 if (Settings::log_cg_convergence)
798 {
799 const std::vector<double> history_data = control.get_history_data();
800
801 std::ofstream ofs(fname + "_cg_convergence.csv");
802
803 for (unsigned int i = 1; i < history_data.size(); i++)
804 ofs << i << ", " << history_data[i] << "\n";
805 }
806 }
807
808 // This function saves the computed current vector potential into a vtu file.
809 void Solver::save() const
810 {
811 const std::vector<std::string> solution_names(3, "VectorField");
812 const std::vector<DataComponentInterpretation::DataComponentInterpretation>
813 interpretation(3,
814 DataComponentInterpretation::component_is_part_of_vector);
815
816 DataOut<3> data_out;
817
818 data_out.add_data_vector(dof_handler,
819 solution,
820 solution_names,
821 interpretation);
822
823 DataOutBase::VtkFlags flags;
824 flags.write_higher_order_cells = true;
825 data_out.set_flags(flags);
826
827 const MappingQ<3> mapping(mapping_degree);
828
829 data_out.build_patches(mapping,
830 fe.degree + 2,
831 DataOut<3>::CurvedCellRegion::curved_inner_cells);
832
833 std::ofstream ofs(fname + ".vtu");
834 data_out.write_vtu(ofs);
835 }
836
837 void Solver::run()
838 {
839 {
840 TimerOutput::Scope timer_section(timer, "Make mesh");
841 make_mesh();
842 }
843 {
844 TimerOutput::Scope timer_section(timer, "Setup");
845 setup();
846 }
847 {
848 TimerOutput::Scope timer_section(timer, "Assemble");
849 assemble();
850 }
851 {
852 TimerOutput::Scope timer_section(timer, "Solve");
853 solve();
854 }
855 {
856 TimerOutput::Scope timer_section(timer, "Save");
857 save();
858 }
859 {
860 TimerOutput::Scope timer_section(timer, "Clear");
861 clear();
862 }
863 }
864 } // namespace SolverT
865
866 // @sect3{Solver - A}
867
868 // This name space contains all the code related to the computation of the
869 // magnetic vector potential, $\vec{A}$. The main difference between this
870 // solver and the solver for the current vector potential, $\vec{T}$, is in how
871 // the information on the source is fed to respective solvers. The solver for
872 // $\vec{T}$ is fed data sampled from the analytical closed-form expression for
873 // $\vec{J}_f$. The solver for $\vec{A}$ is fed a field function, i.e., a
874 // numerically computed current vector potential, $\vec{T}$.
875 namespace SolverA
876 {
877 // This class describes the permeability in the entire problem domain. The
878 // permeability is given by the definition of the problem, see the
879 // introduction.
880 class Permeability
881 {
882 public:
883 void value_list(const types::material_id mid,
884 std::vector<double> &values) const
885 {
886 if ((mid == Settings::material_id_free_space) ||
887 (mid == Settings::material_id_free_current))
888 std::fill(values.begin(), values.end(), Settings::mu_0);
889
890 if (mid == Settings::material_id_core)
891 std::fill(values.begin(), values.end(), Settings::mu_1);
892 }
893 };
894
895 // This class describes the parameter $\gamma$ in the Robin boundary
896 // condition. As soon as it is evaluated on the boundary, the permeability
897 // equals to that of free space. Therefore, we evaluate the parameter gamma as
898 // \f[
899 // \gamma = \dfrac{1}{\mu_0 r}.
900 // \f]
901 class Gamma
902 {
903 public:
904 void value_list(const std::vector<Point<3>> &r,
905 std::vector<double> &values) const
906 {
907 Assert(r.size() == values.size(),
908 ExcDimensionMismatch(r.size(), values.size()));
909
910 for (unsigned int i = 0; i < values.size(); i++)
911 values[i] = 1.0 / (Settings::mu_0 * r[i].norm());
912 }
913 };
914
915 // This class implements the solver that minimizes the functional
916 // $F(\vec{A})$. The numerically computed current vector potential, $\vec{T}$,
917 // is fed to this solver by means of the input parameters `dof_handler_T` and
918 // `solution_T`. Moreover, this solver reuses the mesh on which $\vec{T}$ has
919 // been computed. The reference to the mesh is passed via the input parameter
920 // `triangulation_T`.
921 class Solver
922 {
923 public:
924 Solver() = delete;
925 Solver(const unsigned int p, // Degree of the Nedelec finite elements.
926 const unsigned int mapping_degree,
927 const Triangulation<3> &triangulation_T,
928 const DoFHandler<3> &dof_handler_T,
929 const Vector<double> &solution_T,
930 const double eta_squared = 0.0,
931 const std::string &fname = "data");
932
933 void setup(); // Initializes dofs, vectors, matrices.
934 void assemble(); // Assembles the system of linear equations.
935 void solve(); // Solves the system of linear equations.
936 void save() const; // Saves computed T into a vtu file.
937 void clear() // Clears the memory for the next solver.
938 {
939 system_matrix.clear();
940 system_rhs.reinit(0);
941 }
942 void run(); /* Executes the last five functions in the proper order
943 and measures the execution time for each function. */
944
945 const DoFHandler<3> &get_dof_handler() const
946 {
947 return dof_handler;
948 }
949 const Vector<double> &get_solution() const
950 {
951 return solution;
952 }
953
954 private:
955 const Triangulation<3> &triangulation_T;
956 const DoFHandler<3> &dof_handler_T;
957 const Vector<double> &solution_T;
958
959 // The following data members are typical for all deal.II simulations:
960 // triangulation, finite elements, dof handlers, etc. The constraints
961 // are used to enforce the Dirichlet boundary conditions. The names of the
962 // data members are self-explanatory.
963 const FE_Nedelec<3> fe;
964 DoFHandler<3> dof_handler;
965 Vector<double> solution;
966
967 SparseMatrix<double> system_matrix;
968 Vector<double> system_rhs;
969
970 AffineConstraints<double> constraints;
971 SparsityPattern sparsity_pattern;
972
973 const unsigned int mapping_degree;
974 const double eta_squared;
975 const std::string fname;
976 TimerOutput timer;
977
978 // This time we have two dof handlers, `dof_handler_T` for $\vec{T}$ and
979 // `dof_handler` for $\vec{A}$. The WorkStream needs to walk through
980 // the two dof handlers synchronously. For this purpose we will pair two
981 // active cell iterators (one from `dof_handler_T`, another from
982 // `dof_handler`). For that we need the `IteratorPair` type.
983 using IteratorTuple =
984 std::tuple<typename DoFHandler<3>::active_cell_iterator,
985 typename DoFHandler<3>::active_cell_iterator>;
986
987 using IteratorPair = SynchronousIterators<IteratorTuple>;
988
989 // The program utilizes the WorkStream technology. The Step-9 tutorial
990 // does a much better job of explaining the workings of WorkStream.
991 // Reading the "WorkStream paper", see the glossary, is recommended.
992 // The following structures and functions are related to WorkStream.
993 struct AssemblyScratchData
994 {
995 AssemblyScratchData(const FiniteElement<3> &fe,
996 const DoFHandler<3> &dof_hand_T,
997 const Vector<double> &dofs_T,
998 const unsigned int mapping_degree,
999 const double eta_squared,
1000 const BoundaryConditionType boundary_condition_type);
1001
1002 AssemblyScratchData(const AssemblyScratchData &scratch_data);
1003
1004 const Permeability permeability;
1005 const Gamma gamma;
1006
1007 MappingQ<3> mapping;
1008 FEValues<3> fe_values;
1009 FEFaceValues<3> fe_face_values;
1010
1011 FEValues<3> fe_values_T;
1012
1013 const unsigned int dofs_per_cell;
1014 const unsigned int n_q_points;
1015 const unsigned int n_q_points_face;
1016
1017 std::vector<double> permeability_list;
1018 std::vector<double> gamma_list;
1019 std::vector<Tensor<1, 3>> T_values;
1020
1021 const FEValuesExtractors::Vector ve;
1022
1023 const DoFHandler<3> &dof_hand_T;
1024 const Vector<double> &dofs_T;
1025
1026 const double eta_squared;
1027 const BoundaryConditionType boundary_condition_type;
1028 };
1029
1030 struct AssemblyCopyData
1031 {
1032 FullMatrix<double> cell_matrix;
1033 Vector<double> cell_rhs;
1034 std::vector<types::global_dof_index> local_dof_indices;
1035 };
1036
1037 void system_matrix_local(const IteratorPair &IP,
1038 AssemblyScratchData &scratch_data,
1039 AssemblyCopyData &copy_data);
1040
1041 void copy_local_to_global(const AssemblyCopyData &copy_data);
1042 };
1043
1044 Solver::Solver(const unsigned int p,
1045 const unsigned int mapping_degree,
1046 const Triangulation<3> &triangulation_T,
1047 const DoFHandler<3> &dof_handler_T,
1048 const Vector<double> &solution_T,
1049 const double eta_squared,
1050 const std::string &fname)
1051 : triangulation_T(triangulation_T)
1052 , dof_handler_T(dof_handler_T)
1053 , solution_T(solution_T)
1054 , fe(p)
1055 , mapping_degree(mapping_degree)
1056 , eta_squared(eta_squared)
1057 , fname(fname)
1058 , timer(std::cout,
1059 (Settings::print_time_tables) ? TimerOutput::summary :
1060 TimerOutput::never,
1061 TimerOutput::cpu_and_wall_times_grouped)
1062 {}
1063
1064 // This function initializes the dofs, applies the Dirichlet boundary
1065 // condition, and initializes the vectors and matrices.
1066 void Solver::setup()
1067 {
1068 dof_handler.reinit(triangulation_T);
1069 dof_handler.distribute_dofs(fe);
1070
1071 // The following segment of the code applies the homogeneous Dirichlet
1072 // boundary condition. As discussed in the introduction, the Dirichlet
1073 // boundary condition is an essential condition and must be enforced
1074 // by constraining the system matrix. This segment of code does the
1075 // constraining.
1076 constraints.clear();
1077
1078 DoFTools::make_hanging_node_constraints(dof_handler, constraints);
1079
1080 if (Settings::boundary_condition_type_A == Dirichlet)
1081 VectorTools::project_boundary_values_curl_conforming_l2(
1082 dof_handler,
1083 0, // The first vector component.
1084 Functions::ZeroFunction<3>(3),
1085 Settings::boundary_id_infinity,
1086 constraints,
1087 MappingQ<3>(mapping_degree));
1088
1089 constraints.close();
1090
1091 // The rest of the function arranges the dofs in a sparsity pattern and
1092 // initializes the system matrix and the system vectors.
1093 DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());
1094 DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false);
1095
1096 sparsity_pattern.copy_from(dsp);
1097 system_matrix.reinit(sparsity_pattern);
1098 solution.reinit(dof_handler.n_dofs());
1099 system_rhs.reinit(dof_handler.n_dofs());
1100 }
1101
1102 // Formally, this function assembles the system of linear equations. In
1103 // reality, however, it just spells all the magic words to get the WorkStream
1104 // going. The interesting part, i.e., the actual assembling of the system
1105 // matrix and the right-hand side happens below in the
1106 // Solver::system_matrix_local function. Note that this time the first two
1107 // input parameters to `WorkStream::run` are pairs of iterators, not
1108 // iterators themselves as per usual. Note also the order in which we package
1109 // the iterators: first the iterator of `dof_handler`, then the iterator of
1110 // the `dof_handler_T`. We will extract them in the same order.
1111 void Solver::assemble()
1112 {
1113 WorkStream::run(IteratorPair(IteratorTuple(dof_handler.begin_active(),
1114 dof_handler_T.begin_active())),
1115 IteratorPair(
1116 IteratorTuple(dof_handler.end(), dof_handler_T.end())),
1117 *this,
1118 &Solver::system_matrix_local,
1119 &Solver::copy_local_to_global,
1120 AssemblyScratchData(fe,
1121 dof_handler_T,
1122 solution_T,
1123 mapping_degree,
1124 eta_squared,
1125 Settings::boundary_condition_type_A),
1126 AssemblyCopyData());
1127 }
1128
1129 // The following two constructors initialize scratch data from the input
1130 // parameters and from another object of the same type, i.e., a copy
1131 // constructor.
1132 Solver::AssemblyScratchData::AssemblyScratchData(
1133 const FiniteElement<3> &fe,
1134 const DoFHandler<3> &dof_hand_T,
1135 const Vector<double> &dofs_T,
1136 const unsigned int mapping_degree,
1137 const double eta_squared,
1138 const BoundaryConditionType boundary_condition_type)
1139 : permeability()
1140 , gamma()
1141 , mapping(mapping_degree)
1142 , fe_values(mapping,
1143 fe,
1144 QGauss<3>(fe.degree + 2),
1145 update_gradients | update_values | update_JxW_values)
1146 , fe_face_values(mapping,
1147 fe,
1148 QGauss<2>(fe.degree + 2),
1149 update_values | update_normal_vectors |
1150 update_quadrature_points | update_JxW_values)
1151 , fe_values_T(mapping,
1152 dof_hand_T.get_fe(),
1153 QGauss<3>(fe.degree + 2),
1154 update_values | update_gradients)
1155 , dofs_per_cell(fe_values.dofs_per_cell)
1156 , n_q_points(fe_values.get_quadrature().size())
1157 , n_q_points_face(fe_face_values.get_quadrature().size())
1158 , permeability_list(n_q_points)
1159 , gamma_list(n_q_points_face)
1160 , T_values(n_q_points)
1161 , ve(0)
1162 , dof_hand_T(dof_hand_T)
1163 , dofs_T(dofs_T)
1164 , eta_squared(eta_squared)
1165 , boundary_condition_type(boundary_condition_type)
1166 {}
1167
1168 Solver::AssemblyScratchData::AssemblyScratchData(
1169 const AssemblyScratchData &scratch_data)
1170 : permeability()
1171 , gamma()
1172 , mapping(scratch_data.mapping.get_degree())
1173 , fe_values(mapping,
1174 scratch_data.fe_values.get_fe(),
1175 scratch_data.fe_values.get_quadrature(),
1176 update_gradients | update_values | update_JxW_values)
1177 , fe_face_values(mapping,
1178 scratch_data.fe_face_values.get_fe(),
1179 scratch_data.fe_face_values.get_quadrature(),
1180 update_values | update_normal_vectors |
1181 update_quadrature_points | update_JxW_values)
1182 , fe_values_T(mapping,
1183 scratch_data.fe_values_T.get_fe(),
1184 scratch_data.fe_values_T.get_quadrature(),
1185 update_values | update_gradients)
1186 , dofs_per_cell(fe_values.dofs_per_cell)
1187 , n_q_points(fe_values.get_quadrature().size())
1188 , n_q_points_face(fe_face_values.get_quadrature().size())
1189 , permeability_list(n_q_points)
1190 , gamma_list(n_q_points_face)
1191 , T_values(n_q_points)
1192 , ve(0)
1193 , dof_hand_T(scratch_data.dof_hand_T)
1194 , dofs_T(scratch_data.dofs_T)
1195 , eta_squared(scratch_data.eta_squared)
1196 , boundary_condition_type(scratch_data.boundary_condition_type)
1197 {}
1198
1199 // This function assembles a fraction of the system matrix and the system
1200 // right-hand side related to a single cell. These fractions are
1201 // `copy_data.cell_matrix` and `copy_data.cell_rhs`. They are copied into
1202 // to the system matrix, $A_{ij}$, and the right-hand side, $b_i$, by the
1203 // function `Solver::copy_local_to_global()`.
1204 void Solver::system_matrix_local(const IteratorPair &IP,
1205 AssemblyScratchData &scratch_data,
1206 AssemblyCopyData &copy_data)
1207 {
1208 // First we reinitialize the matrices and vectors related to the current
1209 // cell.
1210 copy_data.cell_matrix.reinit(scratch_data.dofs_per_cell,
1211 scratch_data.dofs_per_cell);
1212
1213 copy_data.cell_rhs.reinit(scratch_data.dofs_per_cell);
1214
1215 copy_data.local_dof_indices.resize(scratch_data.dofs_per_cell);
1216
1217 // Second, we extract the cells from the pair. We extract them in the
1218 // correct order, see above.
1219 auto cell = std::get<0>(*IP);
1220 auto cell_T = std::get<1>(*IP);
1221
1222 // Third, we compute the ordered FE values, the permeability, and the values
1223 // of the current vector potential, $\vec{T}$, on the cell.
1224 scratch_data.fe_values.reinit(cell);
1225 scratch_data.fe_values_T.reinit(cell_T);
1226
1227 scratch_data.permeability.value_list(cell->material_id(),
1228 scratch_data.permeability_list);
1229
1230 scratch_data.fe_values_T[scratch_data.ve].get_function_values(
1231 scratch_data.dofs_T, scratch_data.T_values);
1232
1233 // Fourth, we compute the components of the cell matrix and cell right-hand
1234 // side. The labels of the integrals are the same as in the introduction to
1235 // this tutorial.
1236 for (unsigned int q_index = 0; q_index < scratch_data.n_q_points; ++q_index)
1237 {
1238 for (unsigned int i = 0; i < scratch_data.dofs_per_cell; ++i)
1239 {
1240 for (unsigned int j = 0; j < scratch_data.dofs_per_cell; ++j)
1241 {
1242 copy_data.cell_matrix(i, j) += // Integral I_a1+I_a3.
1243 (1.0 / scratch_data.permeability_list[q_index]) * // 1 / mu
1244 (scratch_data.fe_values[scratch_data.ve].curl(
1245 i, q_index) * // curl N_i
1246 scratch_data.fe_values[scratch_data.ve].curl(
1247 j, q_index) // curl N_j
1248 + scratch_data.eta_squared * // eta^2
1249 scratch_data.fe_values[scratch_data.ve].value(
1250 i, q_index) * // N_i
1251 scratch_data.fe_values[scratch_data.ve].value(
1252 j, q_index) // N_j
1253 ) *
1254 scratch_data.fe_values.JxW(q_index); // dV
1255 }
1256 copy_data.cell_rhs(i) += // Integral I_b3-1.
1257 (scratch_data.T_values[q_index] *
1258 scratch_data.fe_values[scratch_data.ve].curl(i, q_index)) *
1259 scratch_data.fe_values.JxW(q_index); // T.(curl N_i)dV
1260 }
1261 }
1262
1263 // If the Robin boundary condition (first-order ABC) is ordered,
1264 // we compute an extra integral over the boundary.
1265 if (scratch_data.boundary_condition_type == BoundaryConditionType::Robin)
1266 {
1267 for (unsigned int f = 0; f < cell->n_faces(); ++f)
1268 {
1269 if (cell->face(f)->at_boundary())
1270 {
1271 scratch_data.fe_face_values.reinit(cell, f);
1272
1273 for (unsigned int q_index_face = 0;
1274 q_index_face < scratch_data.n_q_points_face;
1275 ++q_index_face)
1276 {
1277 for (unsigned int i = 0; i < scratch_data.dofs_per_cell;
1278 ++i)
1279 {
1280 scratch_data.gamma.value_list(
1281 scratch_data.fe_face_values.get_quadrature_points(),
1282 scratch_data.gamma_list);
1283
1284 for (unsigned int j = 0; j < scratch_data.dofs_per_cell;
1285 ++j)
1286 {
1287 copy_data.cell_matrix(i, j) += // Integral I_a2.
1288 scratch_data.gamma_list[q_index_face] * // gamma
1289 (cross_product_3d(
1290 scratch_data.fe_face_values.normal_vector(
1291 q_index_face),
1292 scratch_data.fe_face_values[scratch_data.ve]
1293 .value(i, q_index_face)) *
1294 cross_product_3d(
1295 scratch_data.fe_face_values.normal_vector(
1296 q_index_face),
1297 scratch_data.fe_face_values[scratch_data.ve]
1298 .value(j,
1299 q_index_face))) // (n x N_i).(n x N_j)
1300 * scratch_data.fe_face_values.JxW(
1301 q_index_face); // dS
1302 } // for j
1303 } // for i
1304 } // for q_index_face
1305 } // if (cell->face(f)->at_boundary())
1306 } // for f
1307 } /* if (scratch_data.boundary_condition_type ==
1308 BoundaryConditionType::Robin) */
1309
1310 // Finally, we query the dof indices on the current cell and store them
1311 // in the copy data structure, so we know to which locations of the system
1312 // matrix and right-hand side the components of the cell matrix and
1313 // cell right-hand side must be copied.
1314 cell->get_dof_indices(copy_data.local_dof_indices);
1315 }
1316
1317 // This function copies the components of a cell matrix and a cell right-hand
1318 // side into the system matrix, $A_{i,j}$, and the system right-hand side,
1319 // $b_i$.
1320 void Solver::copy_local_to_global(const AssemblyCopyData &copy_data)
1321 {
1322 constraints.distribute_local_to_global(copy_data.cell_matrix,
1323 copy_data.cell_rhs,
1324 copy_data.local_dof_indices,
1325 system_matrix,
1326 system_rhs);
1327 }
1328
1329 // This function solves the system of linear equations.
1330 // If `Settings::log_cg_convergence == true`, the convergence data is saved
1331 // into a file. In theory, a CG solver can solve an $m \times m$ system of
1332 // linear equations in at most $m$ steps. In practice, it can take more steps
1333 // to converge. The convergence of the algorithm depends on the spectral
1334 // properties of the system matrix. The best case is if the eigenvalues form a
1335 // compact cluster away from zero. In our case, however, the eigenvalues are
1336 // spread in between zero and the maximal eigenvalue. Consequently, we expect
1337 // a poor convergence and increase the maximal number of iteration steps by a
1338 // factor of 10, i.e., `10*system_rhs.size()`. The stopping condition is \f[
1339 // |\boldsymbol{b} - \boldsymbol{A}\boldsymbol{c}|
1340 // < 10^{-6} |\boldsymbol{b}|.
1341 // \f]
1342 // As soon as we use constraints, we must not forget to distribute them.
1343 void Solver::solve()
1344 {
1345 SolverControl control(10 * system_rhs.size(),
1346 1.0e-6 * system_rhs.l2_norm(),
1347 false,
1348 false);
1349
1350 if (Settings::log_cg_convergence)
1351 control.enable_history_data();
1352
1353 GrowingVectorMemory<Vector<double>> memory;
1354 SolverCG<Vector<double>> cg(control, memory);
1355
1356 PreconditionSSOR<SparseMatrix<double>> preconditioner;
1357 preconditioner.initialize(system_matrix, 1.2);
1358
1359 cg.solve(system_matrix, solution, system_rhs, preconditioner);
1360
1361 constraints.distribute(solution);
1362
1363 if (Settings::log_cg_convergence)
1364 {
1365 const std::vector<double> history_data = control.get_history_data();
1366
1367 std::ofstream ofs(fname + "_cg_convergence.csv");
1368
1369 for (unsigned int i = 1; i < history_data.size(); i++)
1370 ofs << i << ", " << history_data[i] << "\n";
1371 }
1372 }
1373
1374 // This function saves the computed magnetic vector potential into a vtu file.
1375 void Solver::save() const
1376 {
1377 std::vector<std::string> solution_names(3, "VectorField");
1378 std::vector<DataComponentInterpretation::DataComponentInterpretation>
1379 interpretation(3,
1380 DataComponentInterpretation::component_is_part_of_vector);
1381
1382 DataOut<3> data_out;
1383
1384 data_out.add_data_vector(dof_handler,
1385 solution,
1386 solution_names,
1387 interpretation);
1388
1389 DataOutBase::VtkFlags flags;
1390 flags.write_higher_order_cells = true;
1391 data_out.set_flags(flags);
1392
1393 const MappingQ<3> mapping(mapping_degree);
1394
1395 data_out.build_patches(mapping,
1396 fe.degree + 2,
1397 DataOut<3>::CurvedCellRegion::curved_inner_cells);
1398
1399 std::ofstream ofs(fname + ".vtu");
1400 data_out.write_vtu(ofs);
1401 }
1402
1403 void Solver::run()
1404 {
1405 {
1406 TimerOutput::Scope timer_section(timer, "Setup");
1407 setup();
1408 }
1409 {
1410 TimerOutput::Scope timer_section(timer, "Assemble");
1411 assemble();
1412 }
1413 {
1414 TimerOutput::Scope timer_section(timer, "Solve");
1415 solve();
1416 }
1417 {
1418 TimerOutput::Scope timer_section(timer, "Save");
1419 save();
1420 }
1421 {
1422 TimerOutput::Scope timer_section(timer, "Clear");
1423 clear();
1424 }
1425 }
1426 } // namespace SolverA
1427
1428
1429 // @sect3{Projector from H(curl) to H(div)}
1430 // This name space contains all the code related to the conversion of the
1431 // magnetic vector potential, $\vec{A}$, into magnetic field, $\vec{B}$.
1432 // The magnetic vector potential is modeled by the FE_Nedelec finite elements,
1433 // while the magnetic field is modeled by the FE_RaviartThomas finite elements.
1434 // This code is also used for converting the current vector potential,
1435 // $\vec{T}$ into the free-current density, $\vec{J}_f$.
1436 namespace ProjectorHcurlToHdiv
1437 {
1438
1439 // This class implements the solver that minimizes the functional $F(\vec{B})$
1440 // or $F(\vec{J}_f)$, see the introduction. The input vector field,
1441 // $\vec{A}$ or $\vec{T}$, is fed to the solver by means of the input
1442 // parameters `dof_handler_Hcurl` and `solution_Hcurl`. Moreover, this solver
1443 // reuses the mesh on which the input vector field has been computed. The
1444 // reference to the mesh is passed via the input parameter
1445 // `triangulation_Hcurl`. There are no constraints this time around as we are
1446 // not going to apply the Dirichlet boundary condition.
1447 class Solver
1448 {
1449 public:
1450 Solver() = delete;
1451 Solver(const unsigned int p, // Degree of the Raviart-Thomas finite elements
1452 const unsigned int mapping_degree,
1453 const Triangulation<3> &triangulation_Hcurl,
1454 const DoFHandler<3> &dof_handler_Hcurl,
1455 const Vector<double> &solution_Hcurl,
1456 const std::string &fname = "data",
1457 const Function<3> *exact_solution = nullptr);
1458
1459 double get_L2_norm()
1460 {
1461 return L2_norm;
1462 };
1463
1464 unsigned int get_n_cells() const
1465 {
1466 return triangulation_Hcurl.n_active_cells();
1467 }
1468
1469 types::global_dof_index get_n_dofs() const
1470 {
1471 return dof_handler_Hdiv.n_dofs();
1472 }
1473
1474 void setup(); // Initializes dofs, vectors, matrices.
1475 void assemble(); // Assembles the system of linear equations.
1476 void solve(); // Solves the system of linear equations.
1477 void save() const; // Saves computed T into a vtu file.
1478 void compute_error_norms(); // Computes L^2 error norm.
1479 void project_exact_solution_fcn(); // Projects exact solution.
1480 void clear()
1481 {
1482 system_matrix.clear();
1483 system_rhs.reinit(0);
1484 }
1485 void run(); /* Executes the last seven functions in the proper order
1486 and measures the execution time for each function. */
1487
1488 private:
1489 const Triangulation<3> &triangulation_Hcurl;
1490 const DoFHandler<3> &dof_handler_Hcurl;
1491 const Vector<double> &solution_Hcurl;
1492
1493 // The following data members are typical for all deal.II simulations:
1494 // triangulation, finite elements, dof handlers, etc. The constraints
1495 // are used to enforce the Dirichlet boundary conditions. The names of the
1496 // data members are self-explanatory.
1497 const FE_RaviartThomas<3> fe_Hdiv;
1498 DoFHandler<3> dof_handler_Hdiv;
1499
1500 SparsityPattern sparsity_pattern;
1501 SparseMatrix<double> system_matrix;
1502
1503 Vector<double> solution_Hdiv;
1504 Vector<double> system_rhs;
1505
1506 Vector<double> projected_exact_solution;
1507
1508 AffineConstraints<double> constraints;
1509
1510 const Function<3> *exact_solution;
1511
1512 const unsigned int mapping_degree;
1513
1514 Vector<double> L2_per_cell;
1515 double L2_norm;
1516
1517 const std::string fname;
1518 TimerOutput timer;
1519
1520 // This time we have two dof handlers, `dof_handler_Hcurl` for the input
1521 // vector field and `dof_handler_Hdiv` for the output vector field. The
1522 // WorkStream needs to walk through the two dof handlers synchronously.
1523 // For this purpose we will pair two active cells iterators (one from
1524 // `dof_handler_Hcurl`, another from `dof_handler_Hdiv`) to be walked
1525 // through synchronously. For that we need the `IteratorPair` type.
1526 using IteratorTuple =
1527 std::tuple<typename DoFHandler<3>::active_cell_iterator,
1528 typename DoFHandler<3>::active_cell_iterator>;
1529
1530 using IteratorPair = SynchronousIterators<IteratorTuple>;
1531
1532 // The program utilizes the WorkStream technology. The Step-9 tutorial
1533 // does a much better job of explaining the workings of WarkStream.
1534 // Reading the "WorkStream paper", see the glossary, is recommended.
1535 // The following structures and functions are related to WorkStream.
1536 struct AssemblyScratchData
1537 {
1538 AssemblyScratchData(const FiniteElement<3> &fe,
1539 const DoFHandler<3> &dof_handr_Hcurl,
1540 const Vector<double> &dofs_Hcurl,
1541 const unsigned int mapping_degree);
1542
1543 AssemblyScratchData(const AssemblyScratchData &scratch_data);
1544
1545 MappingQ<3> mapping;
1546 FEValues<3> fe_values_Hdiv;
1547 FEValues<3> fe_values_Hcurl;
1548
1549 const unsigned int dofs_per_cell;
1550 const unsigned int n_q_points;
1551
1552 std::vector<Tensor<1, 3>> curl_vec_in_Hcurl;
1553
1554 const FEValuesExtractors::Vector ve;
1555
1556 const DoFHandler<3> &dof_hand_Hcurl;
1557 const Vector<double> &dofs_Hcurl;
1558 };
1559
1560 struct AssemblyCopyData
1561 {
1562 FullMatrix<double> cell_matrix;
1563 Vector<double> cell_rhs;
1564 std::vector<types::global_dof_index> local_dof_indices;
1565 };
1566
1567 void system_matrix_local(const IteratorPair &IP,
1568 AssemblyScratchData &scratch_data,
1569 AssemblyCopyData &copy_data);
1570
1571 void copy_local_to_global(const AssemblyCopyData &copy_data);
1572 };
1573
1574 Solver::Solver(const unsigned int p,
1575 const unsigned int mapping_degree,
1576 const Triangulation<3> &triangulation_Hcurl,
1577 const DoFHandler<3> &dof_handler_Hcurl,
1578 const Vector<double> &solution_Hcurl,
1579 const std::string &fname,
1580 const Function<3> *exact_solution)
1581 : triangulation_Hcurl(triangulation_Hcurl)
1582 , dof_handler_Hcurl(dof_handler_Hcurl)
1583 , solution_Hcurl(solution_Hcurl)
1584 , fe_Hdiv(p)
1585 , exact_solution(exact_solution)
1586 , mapping_degree(mapping_degree)
1587 , fname(fname)
1588 , timer(std::cout,
1589 (Settings::print_time_tables) ? TimerOutput::summary :
1590 TimerOutput::never,
1591 TimerOutput::cpu_and_wall_times_grouped)
1592 {
1593 Assert(exact_solution != nullptr,
1594 ExcMessage("The exact solution is missing."));
1595 }
1596
1597 // This function initializes the dofs, vectors and matrices. This time there
1598 // are no constraints as we do not apply Dirichlet boundary condition.
1599 void Solver::setup()
1600 {
1601 constraints.close();
1602
1603 dof_handler_Hdiv.reinit(triangulation_Hcurl);
1604 dof_handler_Hdiv.distribute_dofs(fe_Hdiv);
1605
1606 DynamicSparsityPattern dsp(dof_handler_Hdiv.n_dofs(),
1607 dof_handler_Hdiv.n_dofs());
1608 DoFTools::make_sparsity_pattern(dof_handler_Hdiv, dsp, constraints, false);
1609
1610 sparsity_pattern.copy_from(dsp);
1611 system_matrix.reinit(sparsity_pattern);
1612 solution_Hdiv.reinit(dof_handler_Hdiv.n_dofs());
1613 system_rhs.reinit(dof_handler_Hdiv.n_dofs());
1614
1615 if (Settings::project_exact_solution && exact_solution)
1616 projected_exact_solution.reinit(dof_handler_Hdiv.n_dofs());
1617
1618 if (exact_solution)
1619 L2_per_cell.reinit(triangulation_Hcurl.n_active_cells());
1620 }
1621
1622 // Formally, this function assembles the system of linear equations. In
1623 // reality, however, it just spells all the magic words to get the WorkStream
1624 // going. The interesting part, i.e., the actual assembling of the system
1625 // matrix and the right-hand side happens below in the
1626 // Solver::system_matrix_local function.
1627 void Solver::assemble()
1628 {
1629 WorkStream::run(IteratorPair(
1630 IteratorTuple(dof_handler_Hdiv.begin_active(),
1631 dof_handler_Hcurl.begin_active())),
1632 IteratorPair(IteratorTuple(dof_handler_Hdiv.end(),
1633 dof_handler_Hcurl.end())),
1634 *this,
1635 &Solver::system_matrix_local,
1636 &Solver::copy_local_to_global,
1637 AssemblyScratchData(fe_Hdiv,
1638 dof_handler_Hcurl,
1639 solution_Hcurl,
1640 mapping_degree),
1641 AssemblyCopyData());
1642 }
1643
1644 // The following two constructors initialize scratch data from the input
1645 // parameters and from another object of the same type, i.e., a copy
1646 // constructor.
1647 Solver::AssemblyScratchData::AssemblyScratchData(
1648 const FiniteElement<3> &fe,
1649 const DoFHandler<3> &dof_hand_Hcurl,
1650 const Vector<double> &dofs_Hcurl,
1651 const unsigned int mapping_degree)
1652 : mapping(mapping_degree)
1653 , fe_values_Hdiv(mapping,
1654 fe,
1655 QGauss<3>(fe.degree + 2),
1656 update_values | update_JxW_values)
1657 , fe_values_Hcurl(mapping,
1658 dof_hand_Hcurl.get_fe(),
1659 QGauss<3>(fe.degree + 2),
1660 update_gradients)
1661 , dofs_per_cell(fe_values_Hdiv.dofs_per_cell)
1662 , n_q_points(fe_values_Hdiv.get_quadrature().size())
1663 , curl_vec_in_Hcurl(n_q_points)
1664 , ve(0)
1665 , dof_hand_Hcurl(dof_hand_Hcurl)
1666 , dofs_Hcurl(dofs_Hcurl)
1667 {}
1668
1669 Solver::AssemblyScratchData::AssemblyScratchData(
1670 const AssemblyScratchData &scratch_data)
1671 : mapping(scratch_data.mapping.get_degree())
1672 , fe_values_Hdiv(mapping,
1673 scratch_data.fe_values_Hdiv.get_fe(),
1674 scratch_data.fe_values_Hdiv.get_quadrature(),
1675 update_values | update_JxW_values)
1676 , fe_values_Hcurl(mapping,
1677 scratch_data.fe_values_Hcurl.get_fe(),
1678 scratch_data.fe_values_Hcurl.get_quadrature(),
1679 update_gradients)
1680 , dofs_per_cell(fe_values_Hdiv.dofs_per_cell)
1681 , n_q_points(fe_values_Hdiv.get_quadrature().size())
1682 , curl_vec_in_Hcurl(scratch_data.n_q_points)
1683 , ve(0)
1684 , dof_hand_Hcurl(scratch_data.dof_hand_Hcurl)
1685 , dofs_Hcurl(scratch_data.dofs_Hcurl)
1686 {}
1687
1688 // This function assembles a fraction of the system matrix and the system
1689 // right-hand side related to a single cell. These fractions are
1690 // `copy_data.cell_matrix` and `copy_data.cell_rhs`. They are copied into
1691 // to the system matrix, $A_{ij}$, and the right-hand side, $b_i$, by the
1692 // function `Solver::copy_local_to_global()`.
1693 void Solver::system_matrix_local(const IteratorPair &IP,
1694 AssemblyScratchData &scratch_data,
1695 AssemblyCopyData &copy_data)
1696 {
1697 // First we reinitialize the matrices and vectors related to the current
1698 // cell, update the FE values, and compute the curl of the input vector
1699 // field.
1700 copy_data.cell_matrix.reinit(scratch_data.dofs_per_cell,
1701 scratch_data.dofs_per_cell);
1702
1703 copy_data.cell_rhs.reinit(scratch_data.dofs_per_cell);
1704
1705 copy_data.local_dof_indices.resize(scratch_data.dofs_per_cell);
1706
1707 scratch_data.fe_values_Hdiv.reinit(std::get<0>(*IP));
1708 scratch_data.fe_values_Hcurl.reinit(std::get<1>(*IP));
1709
1710 // The variable `curl_vec_in_Hcurl` denotes the curl of the input vector
1711 // field, $\vec{\nabla} \times \vec{T}$ or $\vec{\nabla} \times \vec{A}$,
1712 // depending on the context.
1713 scratch_data.fe_values_Hcurl[scratch_data.ve].get_function_curls(
1714 scratch_data.dofs_Hcurl, scratch_data.curl_vec_in_Hcurl);
1715
1716 // Second, we compute the components of the cell matrix and cell right-hand
1717 // side. The labels of the integrals are the same as in the introduction to
1718 // this tutorial.
1719 for (unsigned int q_index = 0; q_index < scratch_data.n_q_points; ++q_index)
1720 {
1721 for (unsigned int i = 0; i < scratch_data.dofs_per_cell; ++i)
1722 {
1723 for (unsigned int j = 0; j < scratch_data.dofs_per_cell; ++j)
1724 {
1725 copy_data.cell_matrix(i, j) += // Integral I_a
1726 scratch_data.fe_values_Hdiv[scratch_data.ve].value(i,
1727 q_index) *
1728 scratch_data.fe_values_Hdiv[scratch_data.ve].value(j,
1729 q_index) *
1730 scratch_data.fe_values_Hdiv.JxW(q_index);
1731 }
1732
1733 copy_data.cell_rhs(i) += // Integral I_b
1734 scratch_data.curl_vec_in_Hcurl[q_index] *
1735 scratch_data.fe_values_Hdiv[scratch_data.ve].value(i, q_index) *
1736 scratch_data.fe_values_Hdiv.JxW(q_index);
1737 }
1738 }
1739
1740 // Finally, we query the dof indices on the current cell and store them
1741 // in the copy data structure, so we know to which locations of the system
1742 // matrix and right-hand side the components of the cell matrix and
1743 // cell right-hand side must be copied.
1744 std::get<0>(*IP)->get_dof_indices(copy_data.local_dof_indices);
1745 }
1746
1747 // This function copies the components of a cell matrix and a cell right-hand
1748 // side into the system matrix, $A_{i,j}$, and the system right-hand side,
1749 // $b_i$.
1750 void Solver::copy_local_to_global(const AssemblyCopyData &copy_data)
1751 {
1752 constraints.distribute_local_to_global(copy_data.cell_matrix,
1753 copy_data.cell_rhs,
1754 copy_data.local_dof_indices,
1755 system_matrix,
1756 system_rhs);
1757 }
1758
1759 // The following two functions compute the error norms and project the exact
1760 // solution.
1761 void Solver::compute_error_norms()
1762 {
1763 const Weight weight;
1764 const Function<3, double> *mask = &weight;
1765
1766 VectorTools::integrate_difference(MappingQ<3>(mapping_degree),
1767 dof_handler_Hdiv,
1768 solution_Hdiv,
1769 *exact_solution,
1770 L2_per_cell,
1771 QGauss<3>(fe_Hdiv.degree + 4),
1772 VectorTools::L2_norm,
1773 mask);
1774
1775 L2_norm = VectorTools::compute_global_error(triangulation_Hcurl,
1776 L2_per_cell,
1777 VectorTools::L2_norm);
1778 }
1779
1780 void Solver::project_exact_solution_fcn()
1781 {
1782 AffineConstraints<double> constraints_empty;
1783 constraints_empty.close();
1784
1785 VectorTools::project(MappingQ<3>(mapping_degree),
1786 dof_handler_Hdiv,
1787 constraints_empty,
1788 QGauss<3>(fe_Hdiv.degree + 2),
1789 *exact_solution,
1790 projected_exact_solution);
1791 }
1792
1793 // This function solves the system of linear equations. This time we are
1794 // dealing with a mass matrix. It has good spectral properties. Consequently,
1795 // we do not use the factor of 10 as in preceding two solvers.
1796 // The stopping condition is
1797 // \f[
1798 // |\boldsymbol{b} - \boldsymbol{A}\boldsymbol{c}|
1799 // < 10^{-6} |\boldsymbol{b}|.
1800 // \f]
1801 void Solver::solve()
1802 {
1803 SolverControl control(system_rhs.size(),
1804 1.0e-6 * system_rhs.l2_norm(),
1805 false,
1806 false);
1807
1808 if (Settings::log_cg_convergence)
1809 control.enable_history_data();
1810
1811 GrowingVectorMemory<Vector<double>> memory;
1812 SolverCG<Vector<double>> cg(control, memory);
1813
1814 PreconditionSSOR<SparseMatrix<double>> preconditioner;
1815 preconditioner.initialize(system_matrix, 1.2);
1816
1817 cg.solve(system_matrix, solution_Hdiv, system_rhs, preconditioner);
1818
1819 if (Settings::log_cg_convergence)
1820 {
1821 const std::vector<double> history_data = control.get_history_data();
1822
1823 std::ofstream ofs(fname + "_cg_convergence.csv");
1824
1825 for (unsigned int i = 1; i < history_data.size(); i++)
1826 ofs << i << ", " << history_data[i] << "\n";
1827 }
1828 }
1829
1830 // This function saves the computed fields into a vtu file. This time we also
1831 // save the projected exact solution and the $L^2$ error norm. The exact
1832 // solution is only saved if the `Settings::project_exact_solution = true`
1833 void Solver::save() const
1834 {
1835 std::vector<std::string> solution_names(3, "VectorField");
1836 std::vector<DataComponentInterpretation::DataComponentInterpretation>
1837 interpretation(3,
1838 DataComponentInterpretation::component_is_part_of_vector);
1839
1840 DataOut<3> data_out;
1841
1842 data_out.add_data_vector(dof_handler_Hdiv,
1843 solution_Hdiv,
1844 solution_names,
1845 interpretation);
1846
1847 if (Settings::project_exact_solution)
1848 {
1849 std::vector<std::string> solution_names_ex(3, "VectorFieldExact");
1850
1851 data_out.add_data_vector(dof_handler_Hdiv,
1852 projected_exact_solution,
1853 solution_names_ex,
1854 interpretation);
1855 }
1856
1857 if (exact_solution)
1858 {
1859 data_out.add_data_vector(L2_per_cell, "L2norm");
1860 }
1861
1862 DataOutBase::VtkFlags flags;
1863 flags.write_higher_order_cells = true;
1864 data_out.set_flags(flags);
1865
1866 const MappingQ<3> mapping(mapping_degree);
1867
1868 data_out.build_patches(mapping,
1869 fe_Hdiv.degree + 2,
1870 DataOut<3>::CurvedCellRegion::curved_inner_cells);
1871
1872 std::ofstream ofs(fname + ".vtu");
1873 data_out.write_vtu(ofs);
1874 }
1875
1876 void Solver::run()
1877 {
1878 {
1879 TimerOutput::Scope timer_section(timer, "Setup");
1880 setup();
1881 }
1882 {
1883 TimerOutput::Scope timer_section(timer, "Assemble");
1884 assemble();
1885 }
1886 {
1887 TimerOutput::Scope timer_section(timer, "Solve");
1888 solve();
1889 }
1890
1891 if (exact_solution)
1892 {
1893 {
1894 TimerOutput::Scope timer_section(timer, "Compute error norms");
1895 compute_error_norms();
1896 }
1897
1898 if (Settings::project_exact_solution)
1899 {
1900 {
1901 TimerOutput::Scope timer_section(timer, "Project exact solution");
1902 project_exact_solution_fcn();
1903 }
1904 }
1905 }
1906 {
1907 TimerOutput::Scope timer_section(timer, "Save");
1908 save();
1909 }
1910 {
1911 TimerOutput::Scope timer_section(timer, "Clear");
1912 clear();
1913 }
1914 }
1915 } // namespace ProjectorHcurlToHdiv
1916
1917
1918 // @sect3{The main loop}
1919
1920 // This class contains the main loop of the program.
1921 class MagneticProblem
1922 {
1923 public:
1924 void run()
1925 {
1926 if (Settings::n_threads_max)
1927 MultithreadInfo::set_thread_limit(Settings::n_threads_max);
1928
1929 MainOutputTable table_Jf(3);
1930 MainOutputTable table_B(3);
1931
1932 table_Jf.clear();
1933 table_B.clear();
1934
1935 std::cout << "Solving for (p = " << Settings::fe_degree
1936 << "): " << std::flush;
1937
1938 for (unsigned int r = 6; r < 10; r++) // Mesh refinement parameter.
1939 {
1940 table_Jf.add_value("r", r);
1941 table_Jf.add_value("p", Settings::fe_degree);
1942
1943 table_B.add_value("r", r);
1944 table_B.add_value("p", Settings::fe_degree);
1945
1946 // Stage 1. Computing $\vec{T}$.
1947
1948 std::cout << "T " << std::flush;
1949
1950 SolverT::Solver T(Settings::fe_degree,
1951 r,
1952 Settings::mapping_degree,
1953 Settings::eta_squared_T,
1954 "T_p" + std::to_string(Settings::fe_degree) + "_r" +
1955 std::to_string(r));
1956
1957 T.run();
1958
1959 // Stage 2. Computing $\vec{J}_f$.
1960
1961 std::cout << "Jf " << std::flush;
1962
1963 ExactSolutions::FreeCurrentDensity Jf_exact;
1964
1965 ProjectorHcurlToHdiv::Solver Jf(Settings::fe_degree,
1966 Settings::mapping_degree,
1967 T.get_tria(),
1968 T.get_dof_handler(),
1969 T.get_solution(),
1970 "Jf_p" +
1971 std::to_string(Settings::fe_degree) +
1972 "_r" + std::to_string(r),
1973 &Jf_exact);
1974
1975 Jf.run();
1976
1977 table_Jf.add_value("ndofs", Jf.get_n_dofs());
1978 table_Jf.add_value("ncells", Jf.get_n_cells());
1979 table_Jf.add_value("L2", Jf.get_L2_norm());
1980
1981 // Stage 3. Computing $\vec{A}$.
1982
1983 std::cout << "A " << std::flush;
1984
1985 SolverA::Solver A(Settings::fe_degree,
1986 Settings::mapping_degree,
1987 T.get_tria(),
1988 T.get_dof_handler(),
1989 T.get_solution(),
1990 Settings::eta_squared_A,
1991 "A_p" + std::to_string(Settings::fe_degree) + "_r" +
1992 std::to_string(r));
1993
1994 A.run();
1995
1996 // Stage 4. Computing $\vec{B}$.
1997
1998 std::cout << "B " << std::flush;
1999
2000 ExactSolutions::MagneticField B_exact;
2001
2002 ProjectorHcurlToHdiv::Solver B(Settings::fe_degree,
2003 Settings::mapping_degree,
2004 T.get_tria(),
2005 A.get_dof_handler(),
2006 A.get_solution(),
2007 "B_p" +
2008 std::to_string(Settings::fe_degree) +
2009 "_r" + std::to_string(r),
2010 &B_exact);
2011 B.run();
2012
2013 table_B.add_value("ndofs", B.get_n_dofs());
2014 table_B.add_value("ncells", B.get_n_cells());
2015 table_B.add_value("L2", B.get_L2_norm());
2016 // End stage 4.
2017
2018 table_Jf.save("table_Jf_p" + std::to_string(Settings::fe_degree));
2019 table_B.save("table_B_p" + std::to_string(Settings::fe_degree));
2020 }
2021 std::cout << std::endl;
2022 }
2023 };
2024
2025 int main()
2026 {
2027 try
2028 {
2029 MagneticProblem problem;
2030 problem.run();
2031 }
2032 catch (std::exception &exc)
2033 {
2034 std::cerr << std::endl
2035 << std::endl
2036 << "----------------------------------------------------"
2037 << std::endl;
2038 std::cerr << "Exception on processing: " << std::endl
2039 << exc.what() << std::endl
2040 << "Aborting!" << std::endl
2041 << "----------------------------------------------------"
2042 << std::endl;
2043
2044 return 1;
2045 }
2046 catch (...)
2047 {
2048 std::cerr << std::endl
2049 << std::endl
2050 << "----------------------------------------------------"
2051 << std::endl;
2052 std::cerr << "Unknown exception!" << std::endl
2053 << "Aborting!" << std::endl
2054 << "----------------------------------------------------"
2055 << std::endl;
2056 return 1;
2057 }
2058
2059 return 0;
2060 }