Lethe Open-Source Library version 1.2.0
Developer Guide
Loading...
Searching...
No Matches
cahn_hilliard.cc
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) 2023-2026 The Lethe Authors
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
3
4#include <core/bdf.h>
6#include <core/utilities.h>
7
11
12#include <deal.II/base/work_stream.h>
13
14#include <deal.II/dofs/dof_renumbering.h>
15#include <deal.II/dofs/dof_tools.h>
16
17#include <deal.II/fe/mapping.h>
18#include <deal.II/fe/mapping_q.h>
19
20#include <deal.II/grid/grid_tools.h>
21
22#include <deal.II/lac/affine_constraints.h>
23#include <deal.II/lac/dynamic_sparsity_pattern.h>
24#include <deal.II/lac/solver_control.h>
25#include <deal.II/lac/sparsity_tools.h>
26#include <deal.II/lac/trilinos_precondition.h>
27#include <deal.II/lac/trilinos_solver.h>
28
29#include <deal.II/numerics/error_estimator.h>
30#include <deal.II/numerics/vector_tools.h>
31
32template <int dim>
33void
35{
36 AssertThrow(time_stepping_is_sdirk(
37 this->simulation_control->get_assembly_method()) == false,
38 ExcMessage(
39 "The SDIRK scheme is not yet supported for this physics"));
40
41 this->assemblers.clear();
42
43 // Time-stepping schemes
44 if (time_stepping_is_bdf(this->simulation_control->get_assembly_method()))
45 {
46 this->assemblers.emplace_back(
47 std::make_shared<CahnHilliardAssemblerBDF<dim>>(
48 this->simulation_control));
49 }
50
51 // For all the assemblers below, the parameter epsilon is passed to the
52 // constructor explicitly because it might be calculated directly using
53 // properties from the triangulation (e.g. minimal cell-size). Consequently,
54 // it cannot be used directly from the simulation parameters and it is passed
55 // to the constructor separately.
56
57 // Angle of contact boundary condition
58 this->assemblers.emplace_back(
61 this->simulation_parameters.multiphysics.cahn_hilliard_parameters,
62 (this->simulation_parameters.multiphysics.cahn_hilliard_parameters
63 .epsilon_set_method == Parameters::EpsilonSetMethod::manual) ?
64 this->simulation_parameters.multiphysics.cahn_hilliard_parameters
65 .epsilon :
66 GridTools::minimal_cell_diameter(*triangulation),
67 this->simulation_parameters.cahn_hilliard_boundary_conditions));
68
69 // Free angle of contact boundary condition
70 this->assemblers.emplace_back(
73 this->simulation_parameters.multiphysics.cahn_hilliard_parameters,
74 (this->simulation_parameters.multiphysics.cahn_hilliard_parameters
75 .epsilon_set_method == Parameters::EpsilonSetMethod::manual) ?
76 this->simulation_parameters.multiphysics.cahn_hilliard_parameters
77 .epsilon :
78 GridTools::minimal_cell_diameter(*triangulation),
79 this->simulation_parameters.cahn_hilliard_boundary_conditions));
80
81 // Core assembler
82 this->assemblers.emplace_back(
83 std::make_shared<CahnHilliardAssemblerCore<dim>>(
85 this->simulation_parameters.multiphysics.cahn_hilliard_parameters,
86 (this->simulation_parameters.multiphysics.cahn_hilliard_parameters
87 .epsilon_set_method == Parameters::EpsilonSetMethod::manual) ?
88 this->simulation_parameters.multiphysics.cahn_hilliard_parameters
89 .epsilon :
90 GridTools::minimal_cell_diameter(*triangulation)));
91}
92
93template <int dim>
94void
96{
97 TimerOutput::Scope t(this->computing_timer, "Assemble matrix");
98
99 this->system_matrix = 0;
101
102 const DoFHandler<dim> &dof_handler_fluid =
103 multiphysics->get_dof_handler(PhysicsID::fluid_dynamics);
104
105 auto scratch_data = CahnHilliardScratchData<dim>(
106 this->simulation_parameters.physical_properties_manager,
107 *this->fe,
108 *this->cell_quadrature,
109 *this->mapping,
110 dof_handler_fluid.get_fe(),
111 *this->face_quadrature);
112
113 WorkStream::run(this->dof_handler->begin_active(),
114 this->dof_handler->end(),
115 *this,
118 scratch_data,
119 StabilizedMethodsCopyData(this->fe->n_dofs_per_cell(),
120 this->cell_quadrature->size()));
121
122 system_matrix.compress(VectorOperation::add);
123}
124
125template <int dim>
126void
128 const typename DoFHandler<dim>::active_cell_iterator &cell,
129 CahnHilliardScratchData<dim> &scratch_data,
130 StabilizedMethodsCopyData &copy_data)
131{
132 copy_data.cell_is_local = cell->is_locally_owned();
133 if (!copy_data.cell_is_local)
134 return;
135
136 auto source_term = simulation_parameters.source_term.cahn_hilliard_source;
137 source_term->set_time(simulation_control->get_current_time());
138
139 scratch_data.reinit(cell,
140 this->evaluation_point,
141 *this->previous_solutions,
142 &(*source_term));
143
144 const DoFHandler<dim> &dof_handler_fluid =
145 multiphysics->get_dof_handler(PhysicsID::fluid_dynamics);
146
147 typename DoFHandler<dim>::active_cell_iterator velocity_cell(
148 &(*triangulation), cell->level(), cell->index(), &dof_handler_fluid);
149
150 if (multiphysics->fluid_dynamics_is_block())
151 {
152 scratch_data.reinit_velocity(velocity_cell,
153 multiphysics->get_block_solution(
155 this->simulation_parameters.ale);
156 }
157 else
158 {
159 scratch_data.reinit_velocity(velocity_cell,
160 multiphysics->get_solution(
162 this->simulation_parameters.ale);
163 }
164
165 scratch_data.calculate_physical_properties();
166 copy_data.reset();
167
168 for (auto &assembler : this->assemblers)
169 {
170 assembler->assemble_matrix(scratch_data, copy_data);
171 }
172
173 cell->get_dof_indices(copy_data.local_dof_indices);
174}
175
176template <int dim>
177void
179 const StabilizedMethodsCopyData &copy_data)
180{
181 if (!copy_data.cell_is_local)
182 return;
183
184 const AffineConstraints<double> &constraints_used = this->zero_constraints;
185 constraints_used.distribute_local_to_global(copy_data.local_matrix,
186 copy_data.local_dof_indices,
188}
189
190template <int dim>
191void
193{
194 TimerOutput::Scope t(this->computing_timer, "Assemble RHS");
195
196 this->system_rhs = 0;
198
199 const DoFHandler<dim> &dof_handler_fluid =
200 multiphysics->get_dof_handler(PhysicsID::fluid_dynamics);
201
202 auto scratch_data = CahnHilliardScratchData<dim>(
203 this->simulation_parameters.physical_properties_manager,
204 *this->fe,
205 *this->cell_quadrature,
206 *this->mapping,
207 dof_handler_fluid.get_fe(),
208 *this->face_quadrature);
209
210 WorkStream::run(this->dof_handler->begin_active(),
211 this->dof_handler->end(),
212 *this,
215 scratch_data,
216 StabilizedMethodsCopyData(this->fe->n_dofs_per_cell(),
217 this->cell_quadrature->size()));
218
219 this->system_rhs.compress(VectorOperation::add);
220}
221
222template <int dim>
223void
225 const typename DoFHandler<dim>::active_cell_iterator &cell,
226 CahnHilliardScratchData<dim> &scratch_data,
227 StabilizedMethodsCopyData &copy_data)
228{
229 copy_data.cell_is_local = cell->is_locally_owned();
230 if (!copy_data.cell_is_local)
231 return;
232
233 auto source_term = simulation_parameters.source_term.cahn_hilliard_source;
234 source_term->set_time(simulation_control->get_current_time());
235
236 scratch_data.reinit(cell,
237 this->evaluation_point,
238 *this->previous_solutions,
239 &(*source_term));
240
241 const DoFHandler<dim> &dof_handler_fluid =
242 multiphysics->get_dof_handler(PhysicsID::fluid_dynamics);
243
244 typename DoFHandler<dim>::active_cell_iterator velocity_cell(
245 &(*triangulation), cell->level(), cell->index(), &dof_handler_fluid);
246
247 if (multiphysics->fluid_dynamics_is_block())
248 {
249 scratch_data.reinit_velocity(velocity_cell,
250 multiphysics->get_block_solution(
252 this->simulation_parameters.ale);
253 }
254 else
255 {
256 scratch_data.reinit_velocity(velocity_cell,
257 multiphysics->get_solution(
259 this->simulation_parameters.ale);
260 }
261
262 scratch_data.calculate_physical_properties();
263 copy_data.reset();
264
265 for (auto &assembler : this->assemblers)
266 {
267 assembler->assemble_rhs(scratch_data, copy_data);
268 }
269
270 cell->get_dof_indices(copy_data.local_dof_indices);
271}
272
273template <int dim>
274void
276 const StabilizedMethodsCopyData &copy_data)
277{
278 if (!copy_data.cell_is_local)
279 return;
280
281 const AffineConstraints<double> &constraints_used = this->zero_constraints;
282 constraints_used.distribute_local_to_global(copy_data.local_rhs,
283 copy_data.local_dof_indices,
284 system_rhs);
285}
286
287template <int dim>
288std::vector<OutputStruct<dim, GlobalVectorType>>
290{
291 std::vector<OutputStruct<dim, GlobalVectorType>> solution_output_structs;
292 // Add the interpretation of the solution. The first component is the
293 // phase order (Phi) and the following one is the chemical potential (eta)
294 std::vector<std::string> solution_names;
295 solution_names.emplace_back("phase_order");
296 solution_names.emplace_back("chemical_potential");
297
298 std::vector<DataComponentInterpretation::DataComponentInterpretation>
299 data_component_interpretation(
300 2, DataComponentInterpretation::component_is_scalar);
301
302 solution_output_structs.emplace_back(
306 solution_names,
307 data_component_interpretation);
308
309 std::vector<std::string> solution_names_filtered;
310 solution_names_filtered.emplace_back("phase_order_filtered");
311 solution_names_filtered.emplace_back("chemical_potential_filtered");
312
313 // Filter phase fraction
314 solution_output_structs.emplace_back(
318 solution_names_filtered,
319 data_component_interpretation);
320
321 return solution_output_structs;
322}
323
324template <int dim>
325std::pair<double, double>
327{
328 auto mpi_communicator = triangulation->get_mpi_communicator();
329
330 FEValues<dim> fe_values(*this->mapping,
331 *fe,
332 *this->cell_quadrature,
333 update_values | update_gradients |
334 update_quadrature_points | update_JxW_values);
335
336 const FEValuesExtractors::Scalar phase_order(0);
337 const FEValuesExtractors::Scalar chemical_potential(1);
338 const unsigned int n_q_points = this->cell_quadrature->size();
339
340 std::vector<Vector<double>> q_exactSol(n_q_points, Vector<double>(2));
341
342 std::vector<double> local_phase_order_values(n_q_points);
343 std::vector<double> local_chemical_potential_values(n_q_points);
344
345 auto &exact_solution =
346 simulation_parameters.analytical_solution->cahn_hilliard;
347 exact_solution.set_time(simulation_control->get_current_time());
348
349 double l2_error_phase_order = 0.;
350 double l2_error_chemical_potential = 0.;
351
352 for (const auto &cell : dof_handler->active_cell_iterators())
353 {
354 if (cell->is_locally_owned())
355 {
356 fe_values.reinit(cell);
357 fe_values[phase_order].get_function_values(evaluation_point,
358 local_phase_order_values);
359 fe_values[chemical_potential].get_function_values(
360 evaluation_point, local_chemical_potential_values);
361
362 // Get the exact solution at all Gauss points
363 exact_solution.vector_value_list(fe_values.get_quadrature_points(),
364 q_exactSol);
365
366 for (unsigned int q = 0; q < n_q_points; q++)
367 {
368 // Find the values of x and u_h (the finite element solution) at
369 // the quadrature points
370 double phase_order_sim = local_phase_order_values[q];
371 double phase_order_exact = q_exactSol[q][0];
372
373 l2_error_phase_order += (phase_order_sim - phase_order_exact) *
374 (phase_order_sim - phase_order_exact) *
375 fe_values.JxW(q);
376
377 double chemical_potential_sim =
378 local_chemical_potential_values[q];
379 double chemical_potential_exact = q_exactSol[q][1];
380
381 l2_error_chemical_potential +=
382 (chemical_potential_sim - chemical_potential_exact) *
383 (chemical_potential_sim - chemical_potential_exact) *
384 fe_values.JxW(q);
385 }
386 }
387 }
388 l2_error_phase_order =
389 Utilities::MPI::sum(l2_error_phase_order, mpi_communicator);
390 l2_error_chemical_potential =
391 Utilities::MPI::sum(l2_error_chemical_potential, mpi_communicator);
392
393 return std::make_pair(std::sqrt(l2_error_phase_order),
394 std::sqrt(l2_error_chemical_potential));
395}
396
397
398template <int dim>
399void
401{
402 auto mpi_communicator = triangulation->get_mpi_communicator();
403
404 FEValues<dim> fe_values(*mapping,
405 *fe,
407 update_values | update_gradients |
408 update_quadrature_points | update_JxW_values);
409
410 const FEValuesExtractors::Scalar phase_order(0);
411
412 const unsigned int n_q_points = cell_quadrature->size();
413 std::vector<double> local_phase_order_values(n_q_points);
414 std::vector<Tensor<1, dim>> local_phase_order_gradients(n_q_points);
415
416 double integral(0.);
417 double max_phase_value(std::numeric_limits<double>::min());
418 double min_phase_value(std::numeric_limits<double>::max());
419 double volume_0(0.);
420 double volume_1(0.);
421
422
423 for (const auto &cell : dof_handler->active_cell_iterators())
424 {
425 if (cell->is_locally_owned())
426 {
427 fe_values.reinit(cell);
428 fe_values[phase_order].get_function_values(*present_solution,
429 local_phase_order_values);
430 fe_values[phase_order].get_function_gradients(
431 *present_solution, local_phase_order_gradients);
432 for (unsigned int q = 0; q < n_q_points; q++)
433 {
434 integral += local_phase_order_values[q] * fe_values.JxW(q);
435 max_phase_value =
436 std::max(local_phase_order_values[q], max_phase_value);
437 min_phase_value =
438 std::min(local_phase_order_values[q], min_phase_value);
439 volume_0 +=
440 (1 + local_phase_order_values[q]) * 0.5 * fe_values.JxW(q);
441 volume_1 +=
442 (1 - local_phase_order_values[q]) * 0.5 * fe_values.JxW(q);
443 }
444 }
445 }
446
447 min_phase_value = Utilities::MPI::min(min_phase_value, mpi_communicator);
448 max_phase_value = Utilities::MPI::max(max_phase_value, mpi_communicator);
449
450 integral = Utilities::MPI::sum(integral, mpi_communicator);
451 volume_0 = Utilities::MPI::sum(volume_0, mpi_communicator);
452 volume_1 = Utilities::MPI::sum(volume_1, mpi_communicator);
453
454 double global_volume = GridTools::volume(*triangulation, *mapping);
455 double phase_average = integral / global_volume;
456
457
458 // Console output
459 if (simulation_parameters.post_processing.verbosity ==
461 {
462 announce_string(this->pcout, "Phase statistics");
463 this->pcout << "Min: " << min_phase_value << std::endl;
464 this->pcout << "Max: " << max_phase_value << std::endl;
465 this->pcout << "Average: " << phase_average << std::endl;
466 this->pcout << "Integral: " << integral << std::endl;
467 this->pcout << "Volume phase 0: " << volume_0 << std::endl;
468 this->pcout << "Volume phase 1: " << volume_1 << std::endl;
469 }
470
471 statistics_table.add_value("time", simulation_control->get_current_time());
472 statistics_table.set_scientific("time", true);
473 statistics_table.add_value("min", min_phase_value);
474 statistics_table.set_scientific("min", true);
475 statistics_table.add_value("max", max_phase_value);
476 statistics_table.set_scientific("max", true);
477 statistics_table.add_value("average", phase_average);
478 statistics_table.set_scientific("average", true);
479 statistics_table.add_value("integral", integral);
480 statistics_table.set_scientific("integral", true);
481 statistics_table.add_value("volume_0", volume_0);
482 statistics_table.set_scientific("volume_0", true);
483 statistics_table.add_value("volume_1", volume_1);
484 statistics_table.set_scientific("volume_1", true);
485}
486
487template <int dim>
488void
490{
491 auto mpi_communicator = triangulation->get_mpi_communicator();
492
493 if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)
494 {
495 std::string filename =
496 simulation_parameters.simulation_control.output_folder +
497 simulation_parameters.post_processing.phase_output_name + ".dat";
498 std::ofstream output(filename.c_str());
499
500 statistics_table.write_text(output);
501 }
502}
503
504template <int dim>
505void
507{
508 auto mpi_communicator = triangulation->get_mpi_communicator();
509
510 FEValues<dim> fe_values(*mapping,
511 *fe,
513 update_values | update_gradients |
514 update_quadrature_points | update_JxW_values);
515
516 const FEValuesExtractors::Scalar phase_order(0);
517
518 const unsigned int n_q_points = cell_quadrature->size();
519 std::vector<double> local_phase_order_values(n_q_points);
520 std::vector<Tensor<1, dim>> local_phase_order_gradients(n_q_points);
521
522 double bulk_energy(0.);
523 double interface_energy(0.);
524 double total_energy(0.);
525
526 double epsilon =
527 (this->simulation_parameters.multiphysics.cahn_hilliard_parameters
528 .epsilon_set_method == Parameters::EpsilonSetMethod::manual) ?
529 this->simulation_parameters.multiphysics.cahn_hilliard_parameters
530 .epsilon :
531 GridTools::minimal_cell_diameter(*triangulation);
532
533 for (const auto &cell : dof_handler->active_cell_iterators())
534 {
535 if (cell->is_locally_owned())
536 {
537 fe_values.reinit(cell);
538 fe_values[phase_order].get_function_values(*present_solution,
539 local_phase_order_values);
540 fe_values[phase_order].get_function_gradients(
541 *present_solution, local_phase_order_gradients);
542 for (unsigned int q = 0; q < n_q_points; q++)
543 {
544 bulk_energy += (1 - local_phase_order_values[q] *
545 local_phase_order_values[q]) *
546 (1 - local_phase_order_values[q] *
547 local_phase_order_values[q]) *
548 fe_values.JxW(q);
549 interface_energy += epsilon * epsilon * 0.5 *
550 (local_phase_order_gradients[q] *
551 local_phase_order_gradients[q]) *
552 fe_values.JxW(q);
553 }
554 }
555 }
556
557 bulk_energy = Utilities::MPI::sum(bulk_energy, mpi_communicator);
558 interface_energy = Utilities::MPI::sum(interface_energy, mpi_communicator);
559 total_energy = bulk_energy + interface_energy;
560
561 phase_energy_table.add_value("time", simulation_control->get_current_time());
562 phase_energy_table.set_scientific("time", true);
563 phase_energy_table.add_value("bulk_energy", bulk_energy);
564 phase_energy_table.set_scientific("bulk_energy", true);
565 phase_energy_table.add_value("interface_energy", interface_energy);
566 phase_energy_table.set_scientific("interface_energy", true);
567 phase_energy_table.add_value("total_energy", total_energy);
568 phase_energy_table.set_scientific("total_energy", true);
569
570 // Console output
571 if (simulation_parameters.post_processing.verbosity ==
573 {
574 announce_string(this->pcout, "Phase energy");
575 this->pcout << "Bulk energy: " << bulk_energy << std::endl;
576 this->pcout << "Interface energy: " << interface_energy << std::endl;
577 this->pcout << "Total energy: " << total_energy << std::endl;
578 }
579}
580
581template <int dim>
582void
584{
585 auto mpi_communicator = triangulation->get_mpi_communicator();
586
587 if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)
588 {
589 std::string filename =
590 simulation_parameters.simulation_control.output_folder +
591 simulation_parameters.post_processing.phase_energy_output_name + ".dat";
592 std::ofstream output(filename.c_str());
593 phase_energy_table.set_precision("time", 12);
594 phase_energy_table.set_precision("bulk_energy", 12);
595 phase_energy_table.set_precision("interface_energy", 12);
596 phase_energy_table.set_precision("total_energy", 12);
597
598 phase_energy_table.write_text(output);
599 }
600}
601
602template <int dim>
603void
605{
606 auto mpi_communicator = triangulation->get_mpi_communicator();
607 unsigned int this_mpi_process(
608 Utilities::MPI::this_mpi_process(mpi_communicator));
609
610 if (this_mpi_process == 0 &&
611 simulation_parameters.analytical_solution->verbosity ==
613 {
614 error_table.omit_column_from_convergence_rate_evaluation("cells");
615
616 if (simulation_parameters.simulation_control.method ==
618 {
619 error_table.evaluate_all_convergence_rates(
620 ConvergenceTable::reduction_rate_log2);
621 }
622 error_table.set_scientific("error_phase_order", true);
623 error_table.set_precision("error_phase_order",
624 simulation_control->get_log_precision());
625 error_table.set_scientific("error_chemical_potential", true);
626 error_table.set_precision("error_chemical_potential",
627 simulation_control->get_log_precision());
628 error_table.write_text(std::cout);
629 }
630
632 {
633 announce_string(this->pcout, "Cahn-Hilliard");
634 this->pcout << std::defaultfloat;
635 this->computing_timer.print_summary();
636 this->pcout << std::scientific;
637 }
638}
639
640template <int dim>
641void
643{
644 for (unsigned int i = previous_solutions->size() - 1; i > 0; --i)
645 {
646 (*previous_solutions)[i] = (*previous_solutions)[i - 1];
647 }
648 (*previous_solutions)[0] = *this->present_solution;
649}
650
651template <int dim>
652void
654{
655 // Apply filter to phase order parameter
657}
658
659template <int dim>
660void
662{
663 auto mpi_communicator = this->triangulation->get_mpi_communicator();
664 unsigned int this_mpi_process(
665 Utilities::MPI::this_mpi_process(mpi_communicator));
666
667 if (simulation_parameters.analytical_solution->calculate_error() == true &&
668 !first_iteration)
669 {
670 double phase_order_error = calculate_L2_error().first;
671 double potential_error = calculate_L2_error().second;
672
673 error_table.add_value("cells",
674 this->triangulation->n_global_active_cells());
675 error_table.add_value("error_phase_order", phase_order_error);
676 error_table.add_value("error_chemical_potential", potential_error);
677
678 error_table.set_scientific("error_phase_order", true);
679 error_table.set_scientific("error_chemical_potential", true);
680
681 if (this_mpi_process == 0)
682 {
683 std::string filename =
684 simulation_parameters.simulation_control.output_folder +
685 simulation_parameters.analytical_solution->get_filename() +
686 "_cahn_hilliard.dat";
687 std::ofstream output(filename.c_str());
688 error_table.write_text(output);
689 }
690
691 if (simulation_parameters.analytical_solution->verbosity ==
693 {
694 this->pcout << "L2 error phase order: " << phase_order_error
695 << std::endl;
696 this->pcout << "L2 error chemical potential: " << potential_error
697 << std::endl;
698 }
699 }
700
701 if (simulation_parameters.multiphysics.cahn_hilliard_parameters
702 .epsilon_verbosity == Parameters::EpsilonVerbosity::verbose)
703 {
704 double epsilon = GridTools::minimal_cell_diameter(*triangulation);
705 announce_string(this->pcout, "Epsilon value");
706 this->pcout << "Epsilon value: " << epsilon << std::endl;
707 }
708
709 if (simulation_parameters.post_processing.calculate_phase_statistics)
710 {
712 if (simulation_control->get_iteration_number() %
713 this->simulation_parameters.post_processing.output_frequency ==
714 0)
716 }
717
718 if (this->simulation_parameters.post_processing.calculate_phase_energy)
719 {
721 // Output phase energies to a text file from processor 0
722 if (simulation_control->get_iteration_number() %
723 this->simulation_parameters.post_processing.output_frequency ==
724 0)
725 {
726 this->write_phase_energy();
727 }
728 }
729
730 if (this->simulation_parameters.post_processing.calculate_barycenter)
731 {
732 // Calculate volume and mass (this->mass_monitored)
733 std::pair<Tensor<1, dim>, Tensor<1, dim>> position_and_velocity;
734
735 if (multiphysics->fluid_dynamics_is_block())
736 {
737 // Check if the post processed variable needs to be calculated with
738 // the average velocity profile or the fluid solution.
739 if (this->simulation_parameters.initial_condition->type ==
741 average_velocity_profile &&
742 !this->simulation_parameters.multiphysics.fluid_dynamics &&
743 simulation_control->get_current_time() >
744 this->simulation_parameters.post_processing
745 .initial_time_for_average_velocities)
746 {
747 position_and_velocity = calculate_barycenter(
748 *this->present_solution,
749 multiphysics->get_block_time_average_solution(
751 }
752 else
753 {
754 position_and_velocity =
756 multiphysics->get_block_solution(
758 }
759 }
760 else
761 {
762 // Check if the post processed variable needs to be calculated with
763 // the average velocity profile or the fluid solution.
764 if (this->simulation_parameters.initial_condition->type ==
766 average_velocity_profile &&
767 !this->simulation_parameters.multiphysics.fluid_dynamics &&
768 simulation_control->get_current_time() >
769 this->simulation_parameters.post_processing
770 .initial_time_for_average_velocities)
771 {
772 position_and_velocity =
774 multiphysics->get_time_average_solution(
776 }
777 else
778 {
779 position_and_velocity =
781 multiphysics->get_solution(
783 }
784 }
785 if (this_mpi_process == 0)
786 {
787 if (simulation_parameters.post_processing.verbosity ==
789 {
790 std::cout << std::endl;
791 std::string independent_column_names = "time";
792
793 std::vector<std::string> dependent_column_names;
794 dependent_column_names.emplace_back("x_cahn_hilliard");
795 dependent_column_names.emplace_back("y_cahn_hilliard");
796 if constexpr (dim == 3)
797 dependent_column_names.emplace_back("z_cahn_hilliard");
798 dependent_column_names.emplace_back("vx_cahn_hilliard");
799 dependent_column_names.emplace_back("vy_cahn_hilliard");
800 if constexpr (dim == 3)
801 dependent_column_names.emplace_back("vz_cahn_hilliard");
802
803 std::vector<Tensor<1, dim>> position_vector{
804 position_and_velocity.first};
805 std::vector<Tensor<1, dim>> velocity_vector{
806 position_and_velocity.second};
807
808 std::vector<std::vector<Tensor<1, dim>>>
809 position_and_velocity_vectors{position_vector, velocity_vector};
810
811 std::vector<double> time = {
812 this->simulation_control->get_current_time()};
813
814 TableHandler table = make_table_scalars_tensors(
815 time,
816 independent_column_names,
817 position_and_velocity_vectors,
818 dependent_column_names,
819 this->simulation_parameters.simulation_control.log_precision,
820 true);
821
822 announce_string(this->pcout, "Cahn-Hilliard Barycenter");
823
824 table.write_text(std::cout);
825 }
826
827 this->barycenter_table.add_value(
828 "time", simulation_control->get_current_time());
829
830 this->barycenter_table.add_value("x_cahn_hilliard",
831 position_and_velocity.first[0]);
832 this->barycenter_table.add_value("y_cahn_hilliard",
833 position_and_velocity.first[1]);
834 if constexpr (dim == 3)
835 this->barycenter_table.add_value("z_cahn_hilliard",
836 position_and_velocity.first[2]);
837
838 this->barycenter_table.add_value("vx_cahn_hilliard",
839 position_and_velocity.second[0]);
840 this->barycenter_table.add_value("vy_cahn_hilliard",
841 position_and_velocity.second[1]);
842 if constexpr (dim == 3)
843 this->barycenter_table.add_value("vz_cahn_hilliard",
844 position_and_velocity.second[2]);
845
846
847 if (this->simulation_control->get_iteration_number() %
848 this->simulation_parameters.post_processing.output_frequency ==
849 0)
850 {
851 // Save table to .dat
852 std::string filename =
853 this->simulation_parameters.simulation_control.output_folder +
854 this->simulation_parameters.post_processing
855 .barycenter_output_name +
856 ".dat";
857 std::ofstream output(filename.c_str());
858 this->barycenter_table.write_text(output);
859 output.close();
860 }
861 }
862 }
863}
864
865template <int dim>
866void
868{
869 announce_string(this->pcout, "Cahn-Hilliard");
870 this->pcout << std::defaultfloat;
871 this->computing_timer.print_summary();
872 this->pcout << std::scientific;
873 this->computing_timer.reset();
874}
875
876template <int dim>
877void
879{
880 solution_transfer->prepare_for_coarsening_and_refinement(*present_solution);
881
882 for (unsigned int i = 0; i < previous_solutions->size(); ++i)
883 {
884 previous_solutions_transfer[i].prepare_for_coarsening_and_refinement(
885 (*previous_solutions)[i]);
886 }
887}
888
889template <int dim>
890void
892{
893 auto mpi_communicator = triangulation->get_mpi_communicator();
894
895 // Set up the vectors for the transfer
896 GlobalVectorType tmp(locally_owned_dofs, mpi_communicator);
897
898 // Interpolate the solution at time and previous time
899 solution_transfer->interpolate(tmp);
900
901 // Distribute constraints
902 nonzero_constraints.distribute(tmp);
903
904 // Fix on the new mesh
905 *present_solution = tmp;
906
907 // Transfer previous solutions
908 for (unsigned int i = 0; i < previous_solutions->size(); ++i)
909 {
910 GlobalVectorType tmp_previous_solution(locally_owned_dofs,
911 mpi_communicator);
912 previous_solutions_transfer[i].interpolate(tmp_previous_solution);
913 nonzero_constraints.distribute(tmp_previous_solution);
914 (*previous_solutions)[i] = tmp_previous_solution;
915 }
916}
917
918template <int dim>
919void
921 const std::pair<const Variable, Parameters::MultipleAdaptationParameters>
922 &ivar,
923 dealii::Vector<float> &estimated_error_per_cell)
924{
925 if (ivar.first == Variable::phase_cahn_hilliard)
926 {
927 AssertThrow(
928 ivar.second.error_estimator ==
930 ExcMessage(
931 "Only the Kelly error estimator is currently implemented for the "
932 "<phase_cahn-hilliard> field."));
933
934 ComponentMask phase_mask =
935 fe->component_mask(FEValuesExtractors::Scalar(0));
936 compute_kelly(estimated_error_per_cell, phase_mask);
937 }
938 else if (ivar.first == Variable::chemical_potential_cahn_hilliard)
939 {
940 AssertThrow(
941 ivar.second.error_estimator ==
943 ExcMessage(
944 "Only the Kelly error estimator is currently implemented for the "
945 "<chemical_potential_cahn-hilliard> field."));
946 ComponentMask chemical_potential_mask =
947 fe->component_mask(FEValuesExtractors::Scalar(1));
948 compute_kelly(estimated_error_per_cell, chemical_potential_mask);
949 }
950}
951
952
953template <int dim>
954void
956 dealii::Vector<float> &estimated_error_per_cell,
957 const ComponentMask &component_mask)
958{
959 KellyErrorEstimator<dim>::estimate(
960 *this->mapping,
961 *this->dof_handler,
962 *this->face_quadrature,
963 typename std::map<types::boundary_id, const Function<dim, double> *>(),
965 estimated_error_per_cell,
966 component_mask);
967}
968
969template <int dim>
970std::vector<OutputStructTableHandler>
972{
973 std::vector<OutputStructTableHandler> table_output_structs;
974
975 std::string prefix =
976 this->simulation_parameters.simulation_control.output_folder;
977 std::string suffix = ".checkpoint";
978
979 if (this->simulation_parameters.analytical_solution->calculate_error())
980 table_output_structs.emplace_back(
981 this->error_table,
982 prefix + this->simulation_parameters.analytical_solution->get_filename() +
983 "_CH" + suffix);
984
985 if (this->simulation_parameters.post_processing.calculate_phase_statistics)
986 table_output_structs.emplace_back(
987 this->statistics_table,
988 prefix + this->simulation_parameters.post_processing.phase_output_name +
989 suffix);
990
991 if (this->simulation_parameters.post_processing.calculate_barycenter)
992 table_output_structs.emplace_back(
993 this->barycenter_table,
994 prefix +
995 this->simulation_parameters.post_processing.barycenter_output_name +
996 suffix);
997
998 if (this->simulation_parameters.post_processing.calculate_phase_energy)
999 table_output_structs.emplace_back(
1000 this->phase_energy_table,
1001 prefix +
1002 this->simulation_parameters.post_processing.phase_energy_output_name +
1003 suffix);
1004
1005 return table_output_structs;
1006}
1007
1008template <int dim>
1009void
1011{
1012 auto mpi_communicator = this->triangulation->get_mpi_communicator();
1013 std::vector<const GlobalVectorType *> sol_set_transfer;
1014
1016 std::make_shared<SolutionTransfer<dim, GlobalVectorType>>(*dof_handler);
1017
1018 sol_set_transfer.emplace_back(&(*present_solution));
1019 for (const auto &previous_solution : *previous_solutions)
1020 {
1021 sol_set_transfer.emplace_back(&previous_solution);
1022 }
1023 solution_transfer->prepare_for_serialization(sol_set_transfer);
1024
1025 // Serialize all post-processing tables that are currently used with the Cahn-
1026 // Hilliard solver
1027 const std::vector<OutputStructTableHandler> &table_output_structs =
1028 this->gather_tables();
1029 serialize_tables_vector(table_output_structs, mpi_communicator);
1030}
1031
1032template <int dim>
1033void
1035{
1036 auto mpi_communicator = triangulation->get_mpi_communicator();
1037 this->pcout << "Reading Cahn Hilliard checkpoint" << std::endl;
1038
1039 std::vector<GlobalVectorType *> input_vectors(1 + previous_solutions->size());
1040 GlobalVectorType distributed_system(locally_owned_dofs, mpi_communicator);
1041 input_vectors[0] = &distributed_system;
1042
1043
1044 std::vector<GlobalVectorType> distributed_previous_solutions;
1045 distributed_previous_solutions.reserve(previous_solutions->size());
1046 for (unsigned int i = 0; i < previous_solutions->size(); ++i)
1047 {
1048 distributed_previous_solutions.emplace_back(
1049 GlobalVectorType(locally_owned_dofs, mpi_communicator));
1050 input_vectors[i + 1] = &distributed_previous_solutions[i];
1051 }
1052
1053 solution_transfer->deserialize(input_vectors);
1054
1055 *present_solution = distributed_system;
1056 for (unsigned int i = 0; i < previous_solutions->size(); ++i)
1057 {
1058 (*previous_solutions)[i] = distributed_previous_solutions[i];
1059 }
1060
1061 // Deserialize all post-processing tables that are currently used with the
1062 // Cahn-Hilliard solver
1063 std::vector<OutputStructTableHandler> table_output_structs =
1064 this->gather_tables();
1065 deserialize_tables_vector(table_output_structs, mpi_communicator);
1066}
1067
1068
1069template <int dim>
1070void
1072{
1074
1075 dof_handler->distribute_dofs(*fe);
1076 DoFRenumbering::Cuthill_McKee(*this->dof_handler);
1077
1078 auto mpi_communicator = triangulation->get_mpi_communicator();
1079
1080
1081 locally_owned_dofs = dof_handler->locally_owned_dofs();
1082 locally_relevant_dofs = DoFTools::extract_locally_relevant_dofs(*dof_handler);
1083
1086 mpi_communicator);
1087
1090 mpi_communicator);
1091
1092 // Previous solutions for transient schemes
1093 for (auto &solution : *this->previous_solutions)
1094 {
1095 solution.reinit(locally_owned_dofs,
1097 mpi_communicator);
1098 }
1099
1100 system_rhs.reinit(locally_owned_dofs, mpi_communicator);
1101
1102 newton_update.reinit(locally_owned_dofs, mpi_communicator);
1103
1104 local_evaluation_point.reinit(this->locally_owned_dofs, mpi_communicator);
1105
1106 {
1107 nonzero_constraints.clear();
1108 DoFTools::make_hanging_node_constraints(*this->dof_handler,
1110
1111 for (auto const &[id, type] :
1112 this->simulation_parameters.cahn_hilliard_boundary_conditions.type)
1113 {
1114 ComponentMask mask(2, true);
1115 mask.set(1, false);
1116
1117 // Dirichlet condition: imposed phase_order at i_bc
1118 // To impose the boundary condition only on the phase order, a component
1119 // mask is used at the end of the interpolate_boundary_values function
1121 {
1122 VectorTools::interpolate_boundary_values(
1123 *this->dof_handler,
1124 id,
1126 &this->simulation_parameters.cahn_hilliard_boundary_conditions
1127 .bcFunctions.at(id)
1128 ->phi),
1130 mask);
1131 }
1133 {
1134 const auto &periodic_boundary =
1135 this->simulation_parameters.cahn_hilliard_boundary_conditions
1136 .periodic_boundaries.at(id);
1137 DoFTools::make_periodicity_constraints(
1138 *this->dof_handler,
1139 id,
1140 periodic_boundary.neighbor_id,
1141 periodic_boundary.direction,
1143 }
1144 }
1145 }
1146 nonzero_constraints.close();
1147
1148 // Boundary conditions for Newton correction
1149 {
1150 zero_constraints.clear();
1151 DoFTools::make_hanging_node_constraints(*this->dof_handler,
1153
1154 for (auto const &[id, type] :
1155 this->simulation_parameters.cahn_hilliard_boundary_conditions.type)
1156 {
1158 {
1159 VectorTools::interpolate_boundary_values(
1160 *this->dof_handler,
1161 id,
1162 Functions::ZeroFunction<dim>(2),
1164 }
1166 {
1167 const auto &periodic_boundary =
1168 this->simulation_parameters.cahn_hilliard_boundary_conditions
1169 .periodic_boundaries.at(id);
1170 DoFTools::make_periodicity_constraints(
1171 *this->dof_handler,
1172 id,
1173 periodic_boundary.neighbor_id,
1174 periodic_boundary.direction,
1176 }
1177 }
1178 }
1179
1180 zero_constraints.close();
1181
1182 // Sparse matrices initialization
1183 DynamicSparsityPattern dsp(locally_relevant_dofs);
1184 DoFTools::make_sparsity_pattern(*this->dof_handler,
1185 dsp,
1187 /*keep_constrained_dofs = */ true);
1188
1189 SparsityTools::distribute_sparsity_pattern(dsp,
1191 mpi_communicator,
1195 dsp,
1196 mpi_communicator);
1197
1198 this->pcout << " Number of Cahn-Hilliard degrees of freedom: "
1199 << dof_handler->n_dofs() << std::endl;
1200
1201 // Provide the cahn_hilliard dof_handler and present solution pointers to the
1202 // multiphysics interface
1203 multiphysics->set_dof_handler(PhysicsID::cahn_hilliard, this->dof_handler);
1204 multiphysics->set_mapping(PhysicsID::cahn_hilliard, this->mapping);
1206 multiphysics->set_filtered_solution(PhysicsID::cahn_hilliard,
1207 this->filtered_solution);
1208 multiphysics->set_previous_solutions(PhysicsID::cahn_hilliard,
1209 this->previous_solutions);
1210}
1211
1212template <int dim>
1213void
1215{
1216 if (!this->simulation_parameters.cahn_hilliard_boundary_conditions
1217 .time_dependent)
1218 return;
1219
1220 double time = this->simulation_control->get_current_time();
1221 nonzero_constraints.clear();
1222 DoFTools::make_hanging_node_constraints(*this->dof_handler,
1224
1225 for (auto const &[id, type] :
1226 this->simulation_parameters.cahn_hilliard_boundary_conditions.type)
1227 {
1228 ComponentMask mask(2, true);
1229 mask.set(1, false);
1230
1231 // Dirichlet condition: imposed phase_order at i_bc
1232 // To impose the boundary condition only on the phase order, a component
1233 // mask is used at the end of the interpolate_boundary_values function
1235 {
1236 this->simulation_parameters.cahn_hilliard_boundary_conditions
1237 .bcFunctions.at(id)
1238 ->phi.set_time(time);
1239
1240 VectorTools::interpolate_boundary_values(
1241 *this->dof_handler,
1242 id,
1244 &this->simulation_parameters.cahn_hilliard_boundary_conditions
1245 .bcFunctions.at(id)
1246 ->phi),
1248 mask);
1249 }
1251 {
1252 const auto &periodic_boundary =
1253 this->simulation_parameters.cahn_hilliard_boundary_conditions
1254 .periodic_boundaries.at(id);
1255 DoFTools::make_periodicity_constraints(*this->dof_handler,
1256 id,
1257 periodic_boundary.neighbor_id,
1258 periodic_boundary.direction,
1260 }
1261 }
1262
1263 nonzero_constraints.close();
1267}
1268
1269template <int dim>
1270void
1272{
1273 const FEValuesExtractors::Scalar phase_order(0);
1274 const FEValuesExtractors::Scalar potential(1);
1275
1276 VectorTools::interpolate(
1277 *mapping,
1278 *dof_handler,
1279 simulation_parameters.initial_condition->cahn_hilliard,
1281 fe->component_mask(phase_order));
1282
1283 // Set the initial chemical potential to 0. (May be discussed or modified
1284 // later)
1285 VectorTools::interpolate(
1286 *mapping,
1287 *dof_handler,
1288 simulation_parameters.initial_condition->cahn_hilliard,
1290 fe->component_mask(potential));
1291
1296}
1297
1298template <int dim>
1299void
1301{
1302 TimerOutput::Scope t(this->computing_timer, "Setup ILU");
1303
1304 const unsigned int ilu_fill = static_cast<unsigned int>(
1306 .ilu_precond_fill);
1307 const double ilu_atol =
1309 .ilu_precond_atol;
1310 const double ilu_rtol =
1312 .ilu_precond_rtol;
1313 TrilinosWrappers::PreconditionILU::AdditionalData preconditionerOptions(
1314 ilu_fill, ilu_atol, ilu_rtol, 0);
1315
1316 ilu_preconditioner = std::make_shared<TrilinosWrappers::PreconditionILU>();
1317
1318 ilu_preconditioner->initialize(system_matrix, preconditionerOptions);
1319}
1320
1321template <int dim>
1322void
1324{
1325 TimerOutput::Scope t(this->computing_timer, "Setup AMG");
1326
1327 // Constant modes for the coupled (phase order + chemical potential) system.
1328 // The Cahn-Hilliard system is solved monolithically as a two-component
1329 // FESystem.
1330 std::vector<std::vector<bool>> constant_modes;
1331
1332 ComponentMask components(2, true);
1333 constant_modes =
1334 DoFTools::extract_constant_modes(*this->dof_handler, components);
1335
1336 // The Cahn-Hilliard operator is non-symmetric since the phase order parameter
1337 // is advected by the fluid velocity
1338 const bool elliptic = false;
1339 // The system mixes the phase order and chemical potential degrees, so the
1340 // largest of the two governs whether higher order elements are used
1341 const bool higher_order_elements =
1342 std::max(
1343 simulation_parameters.fem_parameters.phase_cahn_hilliard_degree,
1344 simulation_parameters.fem_parameters.potential_cahn_hilliard_degree) > 1;
1345 const unsigned int n_cycles =
1347 .amg_n_cycles;
1348 const bool w_cycle =
1350 .amg_w_cycles;
1351 const double aggregation_threshold =
1353 .amg_aggregation_threshold;
1354 const unsigned int smoother_sweeps =
1356 .amg_smoother_sweeps;
1357 const unsigned int smoother_overlap =
1359 .amg_smoother_overlap;
1360 const bool output_details = false;
1361 const char *smoother_type = "ILU";
1362 const char *coarse_type = "ILU";
1363 TrilinosWrappers::PreconditionAMG::AdditionalData preconditionerOptions(
1364 elliptic,
1365 higher_order_elements,
1366 n_cycles,
1367 w_cycle,
1368 aggregation_threshold,
1369 constant_modes,
1370 smoother_sweeps,
1371 smoother_overlap,
1372 output_details,
1373 smoother_type,
1374 coarse_type);
1375
1376 Teuchos::ParameterList parameter_ml;
1377 std::unique_ptr<Epetra_MultiVector> distributed_constant_modes;
1378 preconditionerOptions.set_parameters(parameter_ml,
1379 distributed_constant_modes,
1381 const double ilu_fill =
1383 .amg_precond_ilu_fill;
1384 const double ilu_atol =
1386 .amg_precond_ilu_atol;
1387 const double ilu_rtol =
1389 .amg_precond_ilu_rtol;
1390 parameter_ml.set("smoother: ifpack level-of-fill", ilu_fill);
1391 parameter_ml.set("smoother: ifpack absolute threshold", ilu_atol);
1392 parameter_ml.set("smoother: ifpack relative threshold", ilu_rtol);
1393
1394 parameter_ml.set("coarse: ifpack level-of-fill", ilu_fill);
1395 parameter_ml.set("coarse: ifpack absolute threshold", ilu_atol);
1396 parameter_ml.set("coarse: ifpack relative threshold", ilu_rtol);
1397
1398 amg_preconditioner = std::make_shared<TrilinosWrappers::PreconditionAMG>();
1399 amg_preconditioner->initialize(system_matrix, parameter_ml);
1400}
1401
1402template <int dim>
1403void
1405{
1406 TimerOutput::Scope t(this->computing_timer, "Solve linear system");
1407
1408 auto mpi_communicator = triangulation->get_mpi_communicator();
1409
1410 const AffineConstraints<double> &constraints_used = this->zero_constraints;
1411
1412 const double absolute_residual =
1414 .minimum_residual;
1415 const double relative_residual =
1417 .relative_residual;
1418
1419 const double rescale_metric = this->get_residual_rescale_metric();
1420 const double current_residual = system_rhs.l2_norm() / rescale_metric;
1421 const double linear_solver_tolerance =
1422 std::max(relative_residual * current_residual, absolute_residual);
1423 if (this->simulation_parameters.linear_solver.at(PhysicsID::cahn_hilliard)
1424 .verbosity != Parameters::Verbosity::quiet)
1425 {
1426 this->pcout << " -Tolerance of iterative solver is : "
1427 << linear_solver_tolerance << std::endl;
1428 }
1429 const double non_rescaled_linear_solver_tolerance =
1430 linear_solver_tolerance * rescale_metric;
1431
1432 GlobalVectorType completely_distributed_solution(locally_owned_dofs,
1433 mpi_communicator);
1434
1435 SolverControl solver_control(simulation_parameters.linear_solver
1437 .max_iterations,
1438 non_rescaled_linear_solver_tolerance,
1439 true,
1440 true);
1441
1442 TrilinosWrappers::SolverGMRES::AdditionalData solver_parameters(
1443 false,
1445 .max_krylov_vectors);
1446
1447
1448 TrilinosWrappers::SolverGMRES solver(solver_control, solver_parameters);
1449
1450 const auto preconditioner_type =
1452 .preconditioner;
1453
1454 if (preconditioner_type == Parameters::LinearSolver::PreconditionerType::ilu)
1455 {
1456 setup_ilu();
1457 solver.solve(system_matrix,
1458 completely_distributed_solution,
1459 system_rhs,
1461 }
1462 else if (preconditioner_type ==
1464 {
1465 setup_amg();
1466 solver.solve(system_matrix,
1467 completely_distributed_solution,
1468 system_rhs,
1470 }
1471 else
1472 AssertThrow(
1473 false,
1474 ExcMessage(
1475 "This linear solver does not support this preconditioner. Only <ilu> and <amg> preconditioners are supported."));
1476
1478 .verbosity != Parameters::Verbosity::quiet)
1479 {
1480 this->pcout << " -Iterative solver took : " << solver_control.last_step()
1481 << " steps to reach a residual norm of "
1482 << solver_control.last_value() / rescale_metric << std::endl;
1483 }
1484
1485 constraints_used.distribute(completely_distributed_solution);
1486 newton_update = completely_distributed_solution;
1487}
1488
1489template <int dim>
1490template <typename VectorType>
1491std::pair<Tensor<1, dim>, Tensor<1, dim>>
1493 const VectorType &solution_fd)
1494{
1495 const MPI_Comm mpi_communicator = this->triangulation->get_mpi_communicator();
1496
1497 FEValues<dim> fe_values_cahn_hilliard(*this->mapping,
1498 *this->fe,
1499 *this->cell_quadrature,
1500 update_values | update_gradients |
1501 update_quadrature_points |
1502 update_JxW_values);
1503 std::shared_ptr<CahnHilliardFilterBase> filter =
1505 this->simulation_parameters.multiphysics.cahn_hilliard_parameters);
1506
1507
1508 const DoFHandler<dim> &dof_handler_fd =
1509 multiphysics->get_dof_handler(PhysicsID::fluid_dynamics);
1510
1511 FEValues<dim> fe_values_fd(*this->mapping,
1512 dof_handler_fd.get_fe(),
1513 *this->cell_quadrature,
1514 update_values);
1515
1516 const unsigned int n_q_points = this->cell_quadrature->size();
1517 std::vector<double> phase_cahn_hilliard_values(n_q_points);
1518 std::vector<Tensor<1, dim>> phase_cahn_hilliard_gradients(n_q_points);
1519 std::vector<Tensor<1, dim>> velocity_values(n_q_points);
1520 std::vector<Point<dim>> quadrature_locations(n_q_points);
1521
1522 const FEValuesExtractors::Vector velocity(0);
1523 const FEValuesExtractors::Scalar phase_order(0);
1524
1525 Tensor<1, dim> barycenter_location;
1526 Tensor<1, dim> barycenter_velocity;
1527 double volume = 0;
1528
1529
1530 std::map<field, std::vector<double>> fields;
1531
1532 for (const auto &cell : this->dof_handler->active_cell_iterators())
1533 {
1534 if (cell->is_locally_owned())
1535 {
1536 fe_values_cahn_hilliard.reinit(cell);
1537 quadrature_locations =
1538 fe_values_cahn_hilliard.get_quadrature_points();
1539 fe_values_cahn_hilliard[phase_order].get_function_values(
1540 solution, phase_cahn_hilliard_values);
1541 fe_values_cahn_hilliard[phase_order].get_function_gradients(
1542 solution, phase_cahn_hilliard_gradients);
1543
1544 // Get fluid dynamics active cell iterator
1545 typename DoFHandler<dim>::active_cell_iterator cell_fd(
1546 &(*(this->triangulation)),
1547 cell->level(),
1548 cell->index(),
1549 &dof_handler_fd);
1550
1551 fe_values_fd.reinit(cell_fd);
1552 fe_values_fd[velocity].get_function_values(solution_fd,
1553 velocity_values);
1554
1555 for (unsigned int q = 0; q < n_q_points; q++)
1556 {
1557 const double JxW = fe_values_cahn_hilliard.JxW(q);
1558 const double phase_values = phase_cahn_hilliard_values[q];
1559
1560
1561
1562 volume += (1 - phase_values) * 0.5 * JxW;
1563 barycenter_location +=
1564 (1 - phase_values) * 0.5 * quadrature_locations[q] * JxW;
1565 barycenter_velocity +=
1566 (1 - phase_values) * 0.5 * velocity_values[q] * JxW;
1567 }
1568 }
1569 }
1570
1571 volume = Utilities::MPI::sum(volume, mpi_communicator);
1572 barycenter_location =
1573 Utilities::MPI::sum(barycenter_location, mpi_communicator) / volume;
1574 barycenter_velocity =
1575 Utilities::MPI::sum(barycenter_velocity, mpi_communicator) / volume;
1576
1577 return std::pair<Tensor<1, dim>, Tensor<1, dim>>(barycenter_location,
1578 barycenter_velocity);
1579}
1580
1581template <int dim>
1582void
1584{
1585 auto mpi_communicator = this->triangulation->get_mpi_communicator();
1586
1587 FEValues<dim> fe_values(*mapping,
1588 *fe,
1590 update_values | update_gradients |
1591 update_quadrature_points | update_JxW_values);
1592
1593 GlobalVectorType filtered_solution_owned(this->locally_owned_dofs,
1594 mpi_communicator);
1595 filtered_solution_owned = *this->present_solution;
1596
1597 filtered_solution->reinit(*this->present_solution);
1598
1599 // std::unordered_map<unsigned int, bool> filtered_cell_list;
1600 std::unordered_set<unsigned int> filtered_cell_list;
1601
1602 const unsigned int dofs_per_cell = this->fe->dofs_per_cell;
1603 std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);
1604
1605 // Create filter object
1607 this->simulation_parameters.multiphysics.cahn_hilliard_parameters);
1608
1609 // Apply filter to solution
1610 for (const auto &cell : this->dof_handler->active_cell_iterators())
1611 {
1612 if (cell->is_locally_owned())
1613 {
1614 cell->get_dof_indices(local_dof_indices);
1615
1616 for (unsigned int p = 0; p < local_dof_indices.size(); ++p)
1617 {
1618 if (this->locally_owned_dofs.is_element(local_dof_indices[p]))
1619 {
1620 // Allows to obtain the component corresponding to the degree
1621 // of freedom
1622 auto component_index = fe->system_to_component_index(p).first;
1623
1624 // Filter only the phase field
1625 if (component_index == 0)
1626 {
1627 auto iterator =
1628 filtered_cell_list.find(local_dof_indices[p]);
1629 if (iterator == filtered_cell_list.end())
1630 {
1631 filtered_cell_list.insert(local_dof_indices[p]);
1632 filtered_solution_owned[local_dof_indices[p]] =
1633 filter->filter_phase(
1634 filtered_solution_owned[local_dof_indices[p]]);
1635 }
1636 }
1637 }
1638 }
1639 }
1640 }
1641
1642 *filtered_solution = filtered_solution_owned;
1643
1644 if (this->simulation_parameters.multiphysics.cahn_hilliard_parameters
1645 .cahn_hilliard_phase_filter.verbosity == Parameters::Verbosity::verbose)
1646 {
1647 this->pcout << "Filtered phase values: " << std::endl;
1648 for (const double filtered_phase : *filtered_solution)
1649 {
1650 this->pcout << filtered_phase << std::endl;
1651 }
1652 }
1653}
1654
1655template <int dim>
1656void
1658{
1659 auto mpi_communicator = triangulation->get_mpi_communicator();
1660
1661 FEValuesExtractors::Scalar phase_order(0);
1662 FEValuesExtractors::Scalar chemical_potential(1);
1663
1664 ComponentMask phase_order_mask = fe->component_mask(phase_order);
1665 ComponentMask chemical_potential_mask =
1666 fe->component_mask(chemical_potential);
1667
1668 const std::vector<IndexSet> index_set_phase_order =
1669 DoFTools::locally_owned_dofs_per_component(*dof_handler, phase_order_mask);
1670 const std::vector<IndexSet> index_set_chemical_potential =
1671 DoFTools::locally_owned_dofs_per_component(*dof_handler,
1672 chemical_potential_mask);
1673
1674 double local_sum = 0.0;
1675 double local_max = std::numeric_limits<double>::lowest();
1676
1677
1678 for (const auto &j : index_set_phase_order[0])
1679 {
1680 double dof_newton_update = newton_update[j];
1681 local_sum += dof_newton_update * dof_newton_update;
1682 local_max = std::max(local_max, std::abs(dof_newton_update));
1683 }
1684
1685
1686 double global_phase_order_l2_norm =
1687 std::sqrt(Utilities::MPI::sum(local_sum, mpi_communicator));
1688 double global_phase_order_linfty_norm =
1689 Utilities::MPI::max(local_max, mpi_communicator);
1690
1691 local_sum = 0.0;
1692 local_max = std::numeric_limits<double>::lowest();
1693
1694 for (const auto &j : index_set_chemical_potential[0])
1695 {
1696 double dof_newton_update = newton_update[j];
1697 local_sum += dof_newton_update * dof_newton_update;
1698 local_max = std::max(local_max, std::abs(dof_newton_update));
1699 }
1700
1701 double global_chemical_potential_l2_norm =
1702 std::sqrt(Utilities::MPI::sum(local_sum, mpi_communicator));
1703 double global_chemical_potential_linfty_norm =
1704 Utilities::MPI::max(local_max, mpi_communicator);
1705
1706 this->pcout << "\n\t ||dphi||_L2 = " << std::setw(6)
1707 << global_phase_order_l2_norm << std::setw(6)
1708 << "\t ||dphi||_Linfty = " << global_phase_order_linfty_norm
1709 << std::endl;
1710 this->pcout << "\t ||deta||_L2 = " << std::setw(6)
1711 << global_chemical_potential_l2_norm << std::setw(6)
1712 << "\t ||deta||_Linfty = "
1713 << global_chemical_potential_linfty_norm << std::endl;
1714}
1715
1716template std::pair<Tensor<1, 2>, Tensor<1, 2>>
1718 const GlobalVectorType &solution,
1719 const GlobalVectorType &current_solution_fd);
1720
1721template std::pair<Tensor<1, 3>, Tensor<1, 3>>
1723 const GlobalVectorType &solution,
1724 const GlobalVectorType &current_solution_fd);
1725
1726template std::pair<Tensor<1, 2>, Tensor<1, 2>>
1728 const GlobalVectorType &solution,
1729 const GlobalBlockVectorType &current_solution_fd);
1730
1731
1732template std::pair<Tensor<1, 3>, Tensor<1, 3>>
1734 const GlobalVectorType &solution,
1735 const GlobalBlockVectorType &current_solution_fd);
1736
1737
1738template class CahnHilliard<2>;
1739template class CahnHilliard<3>;
Class that assembles the boundary condition on the angle of contact in the Cahn-Hilliard equations.
Class that assembles the transient time arising from BDF time integration for the Cahn-Hilliard equat...
Class that assembles the core of the Cahn-Hilliard equation : .
Class that assembles the boundary condition that allows a free angle of contact, thus adding a degree...
static std::shared_ptr< CahnHilliardFilterBase > model_cast(const Parameters::CahnHilliard &cahn_hilliard_parameters)
Instantiate and return a pointer to a CahnHilliardFilterBase object by casting it to the proper child...
Class that implements a boundary conditions for the Cahn-Hilliard equation where the phase and chemic...
Class that stores the information required by the assembly procedure for the Cahn-Hilliard equations....
void calculate_physical_properties()
Calculates the physical properties that may be required by the Cahn-Hilliard problem....
void reinit_velocity(const typename DoFHandler< dim >::active_cell_iterator &cell, const VectorType &current_solution, const Parameters::ALE< dim > &ale)
void reinit(const typename DoFHandler< dim >::active_cell_iterator &cell, const VectorType &current_solution, const std::vector< VectorType > &previous_solutions, Function< dim > *source_function)
Reinitializes the content of the scratch.
void apply_phase_filter()
Applies filter on phase fraction values.
std::vector< OutputStructTableHandler > gather_tables() override
Returns a vector of references to TableHandler objects that needs to be serialized/deserialized for t...
virtual void setup_assemblers()
sets up the vector of assembler functions
std::shared_ptr< TrilinosWrappers::PreconditionAMG > amg_preconditioner
AMG preconditioner used by the iterative linear solver.
void verify_consistency_of_boundary_conditions()
Verify consistency of the input parameters for boundary conditions to ensure that for every boundary ...
std::shared_ptr< DoFHandler< dim > > dof_handler
std::shared_ptr< TrilinosWrappers::PreconditionILU > ilu_preconditioner
ILU preconditioner used by the iterative linear solver.
TrilinosWrappers::SparseMatrix system_matrix
TableHandler barycenter_table
GlobalVectorType newton_update
void solve_linear_system() override
Call for the solution of the linear system of equation using a strategy appropriate to the auxiliary ...
TimerOutput computing_timer
std::shared_ptr< Quadrature< dim - 1 > > face_quadrature
std::shared_ptr< std::vector< GlobalVectorType > > previous_solutions
void finish_simulation() override
Carry out the operations required to finish a simulation correctly.
virtual void copy_local_matrix_to_global_matrix(const StabilizedMethodsCopyData &copy_data)
Copy local cell information to global matrix.
void compute_kelly(dealii::Vector< float > &estimated_error_per_cell, const ComponentMask &component_mask)
Compute the Kelly error estimator on the phase variable for mesh refinement. See : https://www....
IndexSet locally_relevant_dofs
std::vector< std::shared_ptr< CahnHilliardAssemblerBase< dim > > > assemblers
std::shared_ptr< parallel::DistributedTriangulationBase< dim > > triangulation
void setup_amg()
Set up the AMG preconditioner stored in amg_preconditioner.
IndexSet locally_owned_dofs
std::shared_ptr< GlobalVectorType > filtered_solution
std::shared_ptr< FESystem< dim > > fe
void setup_dofs() override
Sets-up the DofHandler and the degree of freedom associated with the physics.
void assemble_system_matrix() override
Assembles the matrix associated with the solver.
void modify_solution() override
Carry out modifications on the auxiliary physic solution.
void setup_ilu()
Set up the ILU preconditioner stored in ilu_preconditioner.
std::shared_ptr< SimulationControl > simulation_control
GlobalVectorType system_rhs
void write_phase_statistics()
Writes the phase statistics to an output file.
virtual void copy_local_rhs_to_global_rhs(const StabilizedMethodsCopyData &copy_data)
Copy local cell rhs information to global rhs.
TableHandler phase_energy_table
MultiphysicsInterface< dim > * multiphysics
GlobalVectorType local_evaluation_point
GlobalVectorType evaluation_point
std::pair< Tensor< 1, dim >, Tensor< 1, dim > > calculate_barycenter(const GlobalVectorType &solution, const VectorType &current_solution_fd)
Calculates the barycenter of fluid 1 and its velocity.
std::shared_ptr< CahnHilliardFilterBase > filter
AffineConstraints< double > nonzero_constraints
void post_mesh_adaptation() override
post_mesh_adaption Interpolates the auxiliary physics variables to the new mesh
std::shared_ptr< SolutionTransfer< dim, GlobalVectorType > > solution_transfer
void read_checkpoint() override
Allows Cahn-Hilliard physics to set-up solution vector from checkpoint file;.
void write_checkpoint() override
Prepares Cahn-Hilliard to write checkpoint.
void assemble_system_rhs() override
Assemble the rhs associated with the solver.
std::vector< SolutionTransfer< dim, GlobalVectorType > > previous_solutions_transfer
std::shared_ptr< Quadrature< dim > > cell_quadrature
std::shared_ptr< Mapping< dim > > mapping
AffineConstraints< double > zero_constraints
void write_phase_energy()
virtual void assemble_local_system_rhs(const typename DoFHandler< dim >::active_cell_iterator &cell, CahnHilliardScratchData< dim > &scratch_data, StabilizedMethodsCopyData &copy_data)
Assemble the local rhs for a given cell.
void percolate_time_vectors() override
Rearrange vector solution correctly for transient simulations.
void calculate_phase_statistics()
Calculate phase statistics for monitoring purposes.
ConvergenceTable error_table
double get_residual_rescale_metric() const override
Return the metric for residual rescaling. By default, should return 1. If the rescale_residual_by_vol...
std::shared_ptr< GlobalVectorType > present_solution
void set_initial_conditions() override
Sets-up the initial conditions associated with the physics. Generally, physics only support imposing ...
const SimulationParameters< dim > & simulation_parameters
void postprocess(bool first_iteration) override
Postprocess the auxiliary physics results. Post-processing this case implies the calculation of all d...
void calculate_phase_energy()
Calculate the phase energies : bulk energy, interface energy and total energy.
void output_per_iteration_timer() override
Output the per iteration wallclock times.
TableHandler statistics_table
virtual void assemble_local_system_matrix(const typename DoFHandler< dim >::active_cell_iterator &cell, CahnHilliardScratchData< dim > &scratch_data, StabilizedMethodsCopyData &copy_data)
Assemble the local matrix for a given cell.
std::pair< double, double > calculate_L2_error()
Calculates the L2 error of the solution.
void update_boundary_conditions() override
Update non zero constraints if the boundary is time-dependent.
void pre_mesh_adaptation() override
pre_mesh_adaption Prepares the auxiliary physics variables for a mesh refinement/coarsening
void compute_error_estimate(const std::pair< const Variable, Parameters::MultipleAdaptationParameters > &ivar, dealii::Vector< float > &estimated_error_per_cell) override
Compute the error estimator for mesh refinement.
std::vector< OutputStruct< dim, GlobalVectorType > > gather_output_hook() override
Gather and return vector of output structs that are particular to some applications.
void output_newton_update_norms() override
Output the L2 and Linfty norms of the correction vector.
Class responsible for storing the information calculated using the assembly of stabilized scalar equa...
Definition copy_data.h:67
Vector< double > local_rhs
Definition copy_data.h:105
FullMatrix< double > local_matrix
Definition copy_data.h:104
void reset()
Resets the cell_matrix, cell_rhs, strong_residual and strong_jacobian to zero.
Definition copy_data.h:92
std::vector< types::global_dof_index > local_dof_indices
Definition copy_data.h:106
TableHandler make_table_scalars_tensors(const std::vector< T > &independent_values, const std::string &independent_column_name, const std::vector< Tensor< 1, dim > > &dependent_vector, const std::vector< std::string > &dependent_column_names, const unsigned int display_precision, const bool display_scientific_notation=false)
Generate a table from a vector of scalars (independent variable) and a vector of Tensor<1,...
Definition utilities.cc:59
void serialize_tables_vector(const std::vector< OutputStructTableHandler > &table_output_structs, const MPI_Comm mpi_communicator)
Serializes all the TableHandler objects in table_output_structs.
Definition utilities.h:602
void announce_string(const ConditionalOStream &pcout, const std::string &expression, const char delimiter='-')
Prints a string and then adds a line above and below made with dashes containing as many dashes as th...
Definition utilities.h:500
void deserialize_tables_vector(std::vector< OutputStructTableHandler > &table_output_structs, const MPI_Comm mpi_communicator)
Deserializes all the TableHandler objects in table_output_structs.
Definition utilities.h:624
@ chemical_potential_cahn_hilliard
Chemical potential scalar field from Cahn Hilliard.
@ phase_cahn_hilliard
Phase order scalar field from Cahn Hilliard.
@ velocity
Velocity vector field from fluid dynamics.
@ fluid_dynamics
Fluid Dynamics (Velocity,Pressure).
@ cahn_hilliard
Cahn-Hilliard (Phase indicator, Potential).
std::pair< double, double > calculate_L2_error(const DoFHandler< dim > &dof_handler, const VectorType &evaluation_point, const Function< dim > *exact_solution, const Quadrature< dim > &quadrature_formula, const Mapping< dim > &mapping)
Calculates the L2 norm of the error on velocity and pressure.
Struct containing information about the solution output. It is used to pass all the information requi...
@ ilu
Incomplete LU Factorization.
GlobalVectorType VectorType
bool time_stepping_is_bdf(const Parameters::SimulationControl::TimeSteppingMethod method)
Determines if the time integration method is within the bdf family.
bool time_stepping_is_sdirk(const Parameters::SimulationControl::TimeSteppingMethod method)
Determines if the time integration method is within the sdirk family.
dealii::TrilinosWrappers::MPI::Vector GlobalVectorType
Definition vector.h:17
dealii::TrilinosWrappers::MPI::BlockVector GlobalBlockVectorType
Definition vector.h:18