Smith  0.1
Smith is an implicit thermal structural mechanics simulation code.
base_physics.hpp
Go to the documentation of this file.
1 // Copyright (c) Lawrence Livermore National Security, LLC and
2 // other Smith Project Developers. See the top-level LICENSE file for
3 // details.
4 //
5 // SPDX-License-Identifier: (BSD-3-Clause)
6 
13 #pragma once
14 
15 #include <functional>
16 #include <cstddef>
17 #include <format>
18 #include <memory>
19 #include <optional>
20 #include <string>
21 #include <unordered_map>
22 #include <vector>
23 
24 #include "mpi.h"
25 #include "mfem.hpp"
26 #include "axom/sidre.hpp"
27 #include "axom/slic.hpp"
28 
34 #include "smith/physics/common.hpp"
35 
36 namespace smith {
37 
38 class Mesh;
39 
40 namespace detail {
47 std::string addPrefix(const std::string& prefix, const std::string& target);
48 
54 std::string removePrefix(const std::string& prefix, const std::string& target);
55 
56 } // namespace detail
57 
61 class BasePhysics {
62  public:
72  BasePhysics(std::string physics_name, std::shared_ptr<smith::Mesh> mesh, int cycle = 0, double time = 0.0,
73  bool checkpoint_to_disk = false);
74 
80  BasePhysics(BasePhysics&& other) = default;
81 
87  virtual double time() const;
88 
94  virtual int cycle() const;
95 
101  virtual double maxTime() const;
102 
108  virtual double minTime() const;
109 
115  virtual int maxCycle() const;
116 
122  virtual int minCycle() const;
123 
129  bool isQuasistatic() const { return is_quasistatic_; }
130 
136  virtual const std::vector<double>& timesteps() const;
137 
144  virtual void resetStates(int cycle = 0, double time = 0.0) = 0;
145 
151  virtual void resetAdjointStates()
152  {
153  time_ = max_time_;
154  cycle_ = max_cycle_;
155  }
156 
163  virtual void completeSetup() = 0;
164 
171  virtual const FiniteElementState& state(const std::string& state_name) const = 0;
172 
176  virtual void setState(const std::string&, const FiniteElementState&) = 0;
177 
183  virtual std::vector<std::string> stateNames() const = 0;
184 
191  virtual const FiniteElementState& adjoint(const std::string& adjoint_name) const = 0;
192 
198  virtual std::vector<std::string> adjointNames() const { return {}; }
199 
205  virtual std::vector<std::string> dualNames() const { return {}; }
206 
213  virtual const FiniteElementDual& dual(const std::string& dual_name) const
214  {
215  SLIC_ERROR_ROOT(
216  std::format("dual '{}' requested from physics module '{}' which does not support duals", dual_name, name_));
217  return *duals_[0];
218  }
219 
227  virtual const FiniteElementState& dualAdjoint(const std::string& dual_name) const
228  {
229  SLIC_ERROR_ROOT(std::format("dualAdjoint '{}' requested from physics module '{}' which does not support duals",
230  dual_name, name_));
231  return *dual_adjoints_[0];
232  }
233 
239  virtual const FiniteElementState& shapeDisplacement() const;
240 
250  virtual const FiniteElementState& parameter(const std::string& parameter_name) const
251  {
252  std::string appended_name = detail::addPrefix(name_, parameter_name);
253 
254  for (auto& parameter : parameters_) {
255  if (appended_name == parameter.state->name()) {
256  return *parameter.state;
257  }
258  }
259 
260  SLIC_ERROR_ROOT(
261  std::format("Parameter {} requested from physics module {}, but it doesn't exist.", parameter_name, name_));
262 
263  return *states_[0];
264  }
265 
272  virtual const FiniteElementState& parameter(std::size_t parameter_index) const
273  {
274  SLIC_ERROR_ROOT_IF(parameter_index >= parameters_.size(),
275  std::format("Parameter index {} requested, but only {} parameters exist in physics module {}.",
276  parameter_index, parameters_.size(), name_));
277 
278  return *parameters_[parameter_index].state;
279  }
280 
286  virtual std::vector<std::string> parameterNames() const
287  {
288  std::vector<std::string> parameter_names;
289 
290  for (auto& parameter : parameters_) {
291  parameter_names.emplace_back(detail::removePrefix(name_, parameter.state->name()));
292  }
293 
294  return parameter_names;
295  }
296 
309  virtual void setParameter(const size_t parameter_index, const FiniteElementState& parameter_state);
310 
319  virtual void setShapeDisplacement(const FiniteElementState& shape_displacement);
320 
330  virtual FiniteElementDual computeTimestepSensitivity(size_t parameter_index);
331 
341 
350  virtual const std::unordered_map<std::string, const smith::FiniteElementDual&> computeInitialConditionSensitivity()
351  const
352  {
353  SLIC_WARNING_ROOT(std::format("Initial condition sensitivities not enabled in physics module {}", name_));
354  return {};
355  }
356 
364  virtual void advanceTimestep(double dt) = 0;
365 
371  virtual void setAdjointLoad(std::unordered_map<std::string, const smith::FiniteElementDual&> string_to_dual)
372  {
373  if (!string_to_dual.empty()) {
374  SLIC_ERROR_ROOT(
375  std::format("Failed to setAdjointLoad. Adjoint analysis not defined for physics module {}", name_));
376  }
377  }
378 
385  virtual void setDualAdjointBcs(std::unordered_map<std::string, const smith::FiniteElementState&> string_to_bc)
386  {
387  if (!string_to_bc.empty()) {
388  SLIC_ERROR_ROOT(
389  std::format("Failed to setDualAdjointBCs. Adjoint analysis not defined for physics module {}", name_));
390  }
391  }
392 
398  virtual void reverseAdjointTimestep()
399  {
400  SLIC_ERROR_ROOT(std::format("Adjoint analysis not defined for physics module {}", name_));
401  }
402 
409  virtual void outputStateToDisk(std::optional<std::string> paraview_output_dir = {}) const;
410 
417 
426  virtual FiniteElementState loadCheckpointedState(const std::string& state_name, int cycle);
427 
436  virtual FiniteElementDual loadCheckpointedDual([[maybe_unused]] const std::string& state_name,
437  [[maybe_unused]] int cycle)
438  {
439  SLIC_ERROR_ROOT(std::format("loadCheckpointedDual not enabled in physics module {}", name_));
440  return *duals_[0];
441  }
442 
448  virtual double getCheckpointedTimestep(int cycle) const;
449 
457  virtual void initializeSummary(axom::sidre::DataStore& datastore, const double t_final, const double dt) const;
458 
465  virtual void saveSummary(axom::sidre::DataStore& datastore, const double t) const;
466 
470  virtual ~BasePhysics() = default;
471 
475  const smith::Mesh& mesh() const;
476 
480  const mfem::ParMesh& mfemParMesh() const;
481 
485  mfem::ParMesh& mfemParMesh();
486 
490  std::string name() const { return name_; }
491 
492  protected:
499 
503  void CreateParaviewDataCollection() const;
504 
510  void UpdateParaviewDataCollection(const std::string& paraview_output_dir) const;
511 
519  void initializeBasePhysicsStates(int cycle, double time);
520 
528  std::unordered_map<std::string, FiniteElementState> getCheckpointedStates(int cycle);
529 
531  std::string name_ = {};
532 
536  std::shared_ptr<smith::Mesh> mesh_;
537 
541  MPI_Comm comm_;
542 
546  std::vector<const smith::FiniteElementState*> states_;
547 
551  std::vector<const smith::FiniteElementState*> adjoints_;
552 
556  std::vector<const smith::FiniteElementDual*> duals_;
557 
561  std::vector<const smith::FiniteElementState*> dual_adjoints_;
562 
564  struct ParameterInfo {
573  template <typename FunctionSpace>
574  ParameterInfo(mfem::ParMesh& mesh, FunctionSpace space, const std::string& name = "")
575  {
576  state = std::make_unique<FiniteElementState>(mesh, space, name);
577  previous_state = std::make_unique<FiniteElementState>(mesh, space, "previous_" + name);
578  sensitivity = std::make_unique<FiniteElementDual>(mesh, space, name + "_sensitivity");
581  }
582 
584  std::unique_ptr<smith::FiniteElementState> state;
585 
587  std::unique_ptr<smith::FiniteElementState> previous_state;
588 
594  std::unique_ptr<smith::FiniteElementDual> sensitivity;
595  };
596 
598  std::vector<ParameterInfo> parameters_;
599 
601  mutable std::unordered_map<std::string, std::vector<smith::FiniteElementState>> checkpoint_states_;
602 
610  mutable std::unordered_map<std::string, smith::FiniteElementState> cached_checkpoint_states_;
611 
613  mutable std::optional<int> cached_checkpoint_cycle_;
614 
618  bool is_quasistatic_ = true;
619 
623  static constexpr int FLOAT_PRECISION_ = 8;
624 
628  double time_;
629 
633  double dt_;
634 
638  double max_time_;
639 
643  double min_time_;
644 
648  std::vector<double> timesteps_;
649 
653  int cycle_;
654 
659 
664 
669 
674 
679 
683  mutable std::unique_ptr<mfem::ParaViewDataCollection> paraview_dc_;
684 
688  mutable std::unordered_map<std::string, std::unique_ptr<mfem::ParGridFunction>> paraview_dual_grid_functions_;
689 
693  mutable std::unique_ptr<mfem::ParGridFunction> shape_sensitivity_grid_function_;
694 
699 
704 
709 
712 };
713 
714 } // namespace smith
This file contains the declaration of the boundary condition manager class.
This is the abstract base class for a generic forward solver.
virtual const FiniteElementState & parameter(const std::string &parameter_name) const
Accessor for getting named finite element state parameter fields from the physics modules.
std::string name_
Name of the physics module.
virtual int maxCycle() const
The maximum cycle (timestep iteration number) reached by the forward solver.
virtual const std::vector< double > & timesteps() const
Get a vector of the timestep sizes (i.e. s) taken by the forward solver.
virtual void setParameter(const size_t parameter_index, const FiniteElementState &parameter_state)
Deep copy a parameter field into the internally-owned parameter used for simulations.
std::shared_ptr< smith::Mesh > mesh_
The primary mesh.
virtual ~BasePhysics()=default
Destroy the Base Solver object.
virtual FiniteElementDual loadCheckpointedDual([[maybe_unused]] const std::string &state_name, [[maybe_unused]] int cycle)
Accessor for getting a single named finite element dual solution from the physics modules at a given ...
void UpdateParaviewDataCollection(const std::string &paraview_output_dir) const
Update the paraview states, duals, parameters, and metadata (cycle, time) in preparation for output.
void CreateParaviewDataCollection() const
Create a paraview data collection for the physics package if requested.
virtual void setDualAdjointBcs(std::unordered_map< std::string, const smith::FiniteElementState & > string_to_bc)
Set the dual loads (dirichlet values) for the adjoint reverse timestep solve This must be called afte...
std::vector< const smith::FiniteElementState * > states_
List of finite element primal states associated with this physics module.
double min_time_
The time the forward solver was initialized to.
virtual void resetAdjointStates()
Base method to reset physics states back to the end of time to start adjoint calculations again....
int cycle_
Current cycle (forward pass time iteration count)
double ode_time_point_
The value of time at which the ODE solver wants to evaluate the residual.
virtual const FiniteElementState & adjoint(const std::string &adjoint_name) const =0
Accessor for getting named finite element state adjoint solution from the physics modules.
std::unordered_map< std::string, FiniteElementState > getCheckpointedStates(int cycle)
Accessor for getting all of the primal solutions from the physics modules at a given checkpointed cyc...
std::vector< const smith::FiniteElementDual * > duals_
List of finite element duals associated with this physics module.
virtual void initializeSummary(axom::sidre::DataStore &datastore, const double t_final, const double dt) const
Initializes the Sidre structure for simulation summary data.
std::string name() const
Return the name of the physics.
std::vector< double > timesteps_
A vector of the timestep sizes (i.e. ) taken by the forward solver.
std::vector< ParameterInfo > parameters_
A vector of the parameters associated with this physics module.
virtual void setShapeDisplacement(const FiniteElementState &shape_displacement)
Set the current shape displacement for the underlying mesh.
virtual double time() const
Get the current forward-solution time.
std::optional< int > cached_checkpoint_cycle_
An optional int for disk-based checkpointing containing the cycle number of the last retrieved checkp...
std::vector< const smith::FiniteElementState * > dual_adjoints_
List of adjoint finite element duals associated with this physics module.
int max_cycle_
The maximum cycle (forward pass iteration count) reached by the forward solver.
smith::FiniteElementDual shape_displacement_dual_
The shape displacement field sensitivity.
BasePhysics(std::string physics_name, std::shared_ptr< smith::Mesh > mesh, int cycle=0, double time=0.0, bool checkpoint_to_disk=false)
Empty constructor.
virtual void outputStateToDisk(std::optional< std::string > paraview_output_dir={}) const
Output the current state of the PDE fields in Sidre format and optionally in Paraview format if parav...
MPI_Comm comm_
The MPI communicator.
virtual double maxTime() const
Get the maximum time reached by the forward solver.
virtual void advanceTimestep(double dt)=0
Advance the state variables according to the chosen time integrator.
std::unordered_map< std::string, std::vector< smith::FiniteElementState > > checkpoint_states_
A map containing optionally in-memory checkpointed primal states for transient adjoint solvers.
virtual void completeSetup()=0
Complete the setup and allocate the necessary data structures.
virtual void setState(const std::string &, const FiniteElementState &)=0
Set the primal solution field values of the underlying physics solver.
static constexpr int FLOAT_PRECISION_
Number of significant figures to output for floating-point.
virtual std::vector< std::string > adjointNames() const
Get a vector of the finite element state adjoint solution names.
std::unique_ptr< mfem::ParaViewDataCollection > paraview_dc_
DataCollection pointer for optional paraview output.
virtual const FiniteElementState & shapeDisplacement() const
Accessor for getting the shape displacement field from the physics modules.
const smith::Mesh & mesh() const
Returns a reference to the mesh object.
virtual const FiniteElementState & parameter(std::size_t parameter_index) const
Accessor for getting indexed finite element state parameter fields from the physics modules.
double dt_
Current time step.
int mpi_rank_
MPI rank.
int mpi_size_
MPI size.
double time_
Current time for the forward pass.
virtual int cycle() const
Get the current forward-solution cycle iteration number.
virtual const FiniteElementDual & computeTimestepShapeSensitivity()
Compute the implicit sensitivity of the quantity of interest used in defining the adjoint load with r...
virtual void resetStates(int cycle=0, double time=0.0)=0
Base method to reset physics states to the initial time. This does not reset design parameters or sha...
BoundaryConditionManager bcs_
Boundary condition manager instance.
virtual void reverseAdjointTimestep()
Solve the adjoint reverse timestep problem.
bool is_quasistatic_
Whether the simulation is time-independent.
std::unique_ptr< mfem::ParGridFunction > shape_sensitivity_grid_function_
A optional view of the shape sensitivity in grid function form for paraview output.
bool isQuasistatic() const
Check if the physics is setup as quasistatic.
std::unordered_map< std::string, smith::FiniteElementState > cached_checkpoint_states_
A container relating a checkpointed cycle and the associated finite element state fields.
std::unordered_map< std::string, std::unique_ptr< mfem::ParGridFunction > > paraview_dual_grid_functions_
A optional map of the dual names and duals in grid function form for paraview output.
virtual int minCycle() const
Get the initial cycle (timestep iteration number) used by the forward solver.
virtual double getCheckpointedTimestep(int cycle) const
Get a timestep increment which has been previously checkpointed at the give cycle.
double max_time_
The maximum time reached for the forward solver.
virtual FiniteElementDual computeTimestepSensitivity(size_t parameter_index)
Compute the implicit sensitivity of the quantity of interest used in defining the adjoint load with r...
const FiniteElementDual & shapeDisplacementSensitivity() const
Internally used accessor for getting the shape displacement sensitivity from the physics modules.
virtual void saveSummary(axom::sidre::DataStore &datastore, const double t) const
Saves the summary data to the Sidre Datastore.
virtual const std::unordered_map< std::string, const smith::FiniteElementDual & > computeInitialConditionSensitivity() const
Compute the implicit sensitivity of the quantity of interest with respect to the initial condition fi...
virtual std::vector< std::string > dualNames() const
Get a vector of the finite element state dual (reaction) solution names.
bool checkpoint_to_disk_
A flag denoting whether to save the state to disk or memory as needed for dynamic adjoint solves.
std::vector< const smith::FiniteElementState * > adjoints_
List of finite element adjoint states associated with this physics module.
virtual const FiniteElementDual & dual(const std::string &dual_name) const
Accessor for getting named finite element state dual (reaction) solution from the physics modules.
virtual std::vector< std::string > parameterNames() const
Get a vector of the finite element state parameter names.
BasePhysics(BasePhysics &&other)=default
Construct a new Base Physics object (copy constructor)
virtual const FiniteElementState & state(const std::string &state_name) const =0
Accessor for getting named finite element state primal solution from the physics modules.
int min_cycle_
The cycle the forward solver was initialized to.
const mfem::ParMesh & mfemParMesh() const
Returns a reference to the mfem ParMesh object.
void initializeBasePhysicsStates(int cycle, double time)
Protected, non-virtual method to reset physics states to zero. This does not reset design parameters ...
void loadCheckpointedStatesFromDisk(int cycle)
load checkpointed states from disk into states array
virtual FiniteElementState loadCheckpointedState(const std::string &state_name, int cycle)
Accessor for getting a single named finite element state primal solution from the physics modules at ...
virtual double minTime() const
Get the initial time used by the forward solver.
smith::FiniteElementState shape_displacement_
The shape displacement field.
virtual std::vector< std::string > stateNames() const =0
Get a vector of the finite element state primal solution names.
virtual void setAdjointLoad(std::unordered_map< std::string, const smith::FiniteElementDual & > string_to_dual)
Set the loads for the adjoint reverse timestep solve.
virtual const FiniteElementState & dualAdjoint(const std::string &dual_name) const
Accessor for getting named finite element state dual adjoint (reaction adjoint load) from the physics...
A container for the boundary condition information relating to a specific physics module.
Class for encapsulating the dual vector space of a finite element space (i.e. the space of linear for...
Class for encapsulating the critical MFEM components of a primal finite element field.
std::string name() const
Returns the name of the FEState (field)
Helper class for constructing a mesh consistent with Smith.
Definition: mesh.hpp:37
static void storeState(FiniteElementState &state)
Store a pre-constructed finite element state in the state manager.
static void storeDual(FiniteElementDual &dual)
Store a pre-constructed finite element dual in the state manager.
A file defining some enums and structs that are used by the different physics modules.
This file contains the declaration of an equation solver wrapper.
This contains a class that represents the dual of a finite element vector space, i....
This file contains the declaration of structure that manages the MFEM objects that make up the state ...
Accelerator functionality.
Definition: smith.cpp:36
mfem::ParFiniteElementSpace & space(FieldState field)
Get the space from the primal field of a field states.
This file contains the declaration of the StateManager class.
The information needed for the physics parameters stored as Finite Element State fields.
std::unique_ptr< smith::FiniteElementState > previous_state
The finite element state representing the parameter at the previous evaluation.
std::unique_ptr< smith::FiniteElementDual > sensitivity
The sensitivities (dual vectors) of the QOI encoded in the adjoint load with respect to each of the i...
std::unique_ptr< smith::FiniteElementState > state
The finite element states representing user-defined and owned parameter fields.
ParameterInfo(mfem::ParMesh &mesh, FunctionSpace space, const std::string &name="")
Construct a new Parameter Info object.
a small POD class for tracking function space metadata