23#include <polyfem/embedded_spec/polyfem.hpp>
24#include <polyfem/embedded_spec/polyfem_dirichlet.hpp>
26#include <polysolve/linear/Solver.hpp>
28#include <spdlog/sinks/basic_file_sink.h>
29#include <spdlog/sinks/ostream_sink.h>
30#include <spdlog/sinks/stdout_color_sinks.h>
32#include <ipc/utils/logger.hpp>
33#ifdef POLYFEM_WITH_ITR
34#include <wmtk/utils/Logger.hpp>
48 spdlog::level::level_enum,
49 {{spdlog::level::level_enum::trace,
"trace"},
50 {spdlog::level::level_enum::debug,
"debug"},
51 {spdlog::level::level_enum::info,
"info"},
52 {spdlog::level::level_enum::warn,
"warning"},
53 {spdlog::level::level_enum::err,
"error"},
54 {spdlog::level::level_enum::critical,
"critical"},
55 {spdlog::level::level_enum::off,
"off"},
56 {spdlog::level::level_enum::trace, 0},
57 {spdlog::level::level_enum::debug, 1},
58 {spdlog::level::level_enum::info, 2},
59 {spdlog::level::level_enum::warn, 3},
60 {spdlog::level::level_enum::err, 3},
61 {spdlog::level::level_enum::critical, 4},
62 {spdlog::level::level_enum::off, 5}})
68 using namespace utils;
72 std::string resolve_output_path(
const std::string &output_dir,
const std::string &path)
74 if (output_dir.empty() ||
path.empty() || std::filesystem::path(path).is_absolute())
76 return std::filesystem::weakly_canonical(std::filesystem::path(output_dir) / path).string();
79 bool contact_enabled(
const json &args)
81 return args[
"contact"][
"enabled"];
84 void init_time(
json &args, Units &units)
89 const double t0 =
Units::convert(args[
"time"][
"t0"], units.time());
101 else if (num_valid == 2)
111 time_steps = int(std::ceil((tend - t0) / dt));
112 assert(time_steps > 0);
116 time_steps =
args[
"time"][
"time_steps"];
119 dt = (tend - t0) / time_steps;
124 throw std::runtime_error(
"This code should be unreachable!");
134 time_steps =
args[
"time"][
"time_steps"];
139 tend = t0 + time_steps * dt;
143 throw std::runtime_error(
"This code should be unreachable!");
146 else if (num_valid == 3)
150 time_steps =
args[
"time"][
"time_steps"];
152 if (std::abs(t0 + dt * time_steps - tend) > 1e-12)
156 args[
"time"][
"tend"] = tend;
157 args[
"time"][
"dt"] = dt;
158 args[
"time"][
"time_steps"] = time_steps;
160 units.characteristic_length() *= dt;
162 logger().info(
"t0={}, dt={}, tend={}", t0, dt, tend);
172 const std::string &log_file,
173 const spdlog::level::level_enum log_level,
174 const spdlog::level::level_enum file_log_level,
177 std::vector<spdlog::sink_ptr> sinks;
181 console_sink_ = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
185 if (!log_file.empty())
187 file_sink_ = std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file,
true);
193 spdlog::flush_every(std::chrono::seconds(3));
198 std::vector<spdlog::sink_ptr> sinks;
199 sinks.emplace_back(std::make_shared<spdlog::sinks::ostream_sink_mt>(os,
false));
204 const std::vector<spdlog::sink_ptr> &sinks,
205 const spdlog::level::level_enum log_level)
207 set_logger(std::make_shared<spdlog::logger>(
"polyfem", sinks.begin(), sinks.end()));
210 ipc::set_logger(std::make_shared<spdlog::logger>(
"ipctk", sinks.begin(), sinks.end()));
212#ifdef POLYFEM_WITH_ITR
213 wmtk::set_logger(std::make_shared<spdlog::logger>(
"wmtk", sinks.begin(), sinks.end()));
216 logger().set_level(spdlog::level::trace);
217 ipc::logger().set_level(spdlog::level::trace);
218#ifdef POLYFEM_WITH_ITR
219 wmtk::logger().set_level(spdlog::level::trace);
227 spdlog::set_level(log_level);
234 logger().set_level(log_level);
235 ipc::logger().set_level(log_level);
240 const json &p_args_in,
241 const bool strict_validation,
242 const bool is_adjoint_optimization)
245 init(p_args_in, resources, strict_validation, is_adjoint_optimization);
249 const json &p_args_in,
251 const bool strict_validation,
252 const bool is_adjoint_optimization)
255 json args_in = p_args_in;
257 ? args_in[
"root_path"].get<std::string>()
260 args_in.erase(
"root_path");
261 const bool contact_dhat_was_explicit = args_in.contains(
"/contact/dhat"_json_pointer);
269 jse.strict = strict_validation;
270 rules = jse::embed::polyfem_spec::polyfem::spec();
272 polysolve::linear::Solver::apply_default_solver(rules,
"/solver/linear");
273 polysolve::linear::Solver::apply_default_solver(rules,
"/solver/adjoint_linear");
276 polysolve::linear::Solver::select_valid_solver(args_in[
"solver"][
"linear"],
logger());
277 if (args_in[
"solver"][
"adjoint_linear"].is_null())
278 args_in[
"solver"][
"adjoint_linear"] = args_in[
"solver"][
"linear"];
280 polysolve::linear::Solver::select_valid_solver(args_in[
"solver"][
"adjoint_linear"],
logger());
282 if (args_in.contains(
"/solver/nonlinear"_json_pointer))
284 if (args_in.contains(
"/solver/augmented_lagrangian/nonlinear"_json_pointer))
286 assert(args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"].is_object());
287 json nonlinear = args_in[
"solver"][
"nonlinear"];
288 nonlinear.merge_patch(args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"]);
289 args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"] = nonlinear;
293 args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"] = args_in[
"solver"][
"nonlinear"];
297 const bool valid_input = jse.verify_json(args_in, rules);
300 logger().error(
"invalid input json:\n{}", jse.log2str());
301 throw std::runtime_error(
"Invalid input json file");
304 args = jse.inject_defaults(args_in, rules);
307 args, jse::embed::polyfem_dirichlet_spec::polyfem_dirichlet::spec(), *
resources_);
312 if (!args_in.contains(
"/space/advanced/bc_method"_json_pointer) &&
args[
"space"][
"basis_type"] !=
"Lagrange")
314 logger().warn(
"Setting bc method to lsq for non-Lagrange basis");
315 args[
"space"][
"advanced"][
"bc_method"] =
"lsq";
318 const std::string configured_output_dir =
args[
"output"][
"directory"].get<std::string>();
319 const std::string output_dir = configured_output_dir.empty()
321 : (std::filesystem::path(configured_output_dir).is_absolute()
322 ? std::filesystem::path(configured_output_dir)
323 :
resources_->host_directory() / configured_output_dir)
326 if (!output_dir.empty())
327 std::filesystem::create_directories(output_dir);
329 std::string out_path_log =
args[
"output"][
"log"][
"path"];
330 if (!out_path_log.empty())
331 out_path_log = resolve_output_path(output_dir, out_path_log);
335 args[
"output"][
"log"][
"level"],
336 args[
"output"][
"log"][
"file_level"],
337 args[
"output"][
"log"][
"quiet"]);
339 logger().info(
"Saving output to {}", output_dir);
343 init_time(
args, units);
345 if (contact_enabled(
args))
347 if (
args[
"solver"][
"contact"][
"friction_iterations"] == 0)
349 logger().info(
"specified friction_iterations is 0; disabling friction");
350 args[
"contact"][
"friction_coefficient"] = 0.0;
352 else if (
args[
"solver"][
"contact"][
"friction_iterations"] < 0)
354 args[
"solver"][
"contact"][
"friction_iterations"] = std::numeric_limits<int>::max();
356 if (
args[
"contact"][
"friction_coefficient"] == 0.0)
358 args[
"solver"][
"contact"][
"friction_iterations"] = 0;
363 args[
"solver"][
"contact"][
"friction_iterations"] = 0;
364 args[
"contact"][
"friction_coefficient"] = 0;
365 args[
"contact"][
"periodic"] =
false;
369 if (formulation.empty())
371 logger().error(
"specify some 'materials'");
372 throw std::runtime_error(
"invalid input");
377 throw std::runtime_error(
"polyfem::State is varform-only; use polyfem::legacy::State for " + formulation +
".");
380 args[
"contact"][
"_dhat_was_explicit"] = contact_dhat_was_explicit;
382 args[
"contact"].erase(
"_dhat_was_explicit");
387 init(checkpoint.
config(), checkpoint, strict_validation);
391 const json &continuation,
393 const bool strict_validation)
395 init(continuation, checkpoint.
resources(), strict_validation,
false);
400 "Checkpoint formulation '{}' is incompatible with configured formulation '{}'.",
402 if (std::abs(
args[
"time"][
"dt"].get<double>() -
checkpoint_->get().metadata().dt) > 1e-12)
404 if (std::abs(
args[
"time"][
"t0"].get<double>() -
checkpoint_->get().metadata().time) > 1e-12)
405 log_and_throw_error(
"Checkpoint time is incompatible with its continuation configuration.");
413 void State::set_mesh(
415 const std::function<
int(
const size_t,
const std::vector<int> &,
const RowVectorNd &,
bool)> &boundary_marker,
417 bool skip_boundary_sideset)
421 logger().info(
"Loading mesh...");
427 logger().error(
"Unable to load the mesh");
432 mesh->bounding_box(min, max);
434 logger().info(
"mesh bb min [{}], max [{}]", min, max);
436 if (!skip_boundary_sideset)
437 mesh->compute_boundary_ids(boundary_marker);
440 logger().info(
" took {}s", timer.getElapsedTime());
451 logger().info(
"Loading mesh ...");
461 loaded_geometry.
fem =
checkpoint_->get().read_mesh(
"/checkpoint/meshes/active", non_conforming);
463 args[
"geometry"], obstacle_displacements, dirichlet_conditions,
464 loaded_geometry.
fem->dimension(), non_conforming);
467 loaded_geometry = geometry_loader.
load(
468 args[
"geometry"], obstacle_displacements, dirichlet_conditions, non_conforming);
469 auto &mesh = loaded_geometry.
fem;
475 mesh->bounding_box(min, max);
477 logger().info(
"mesh bb min [{}], max [{}]", min, max);
480 logger().info(
" took {}s", timer.getElapsedTime());
482#ifdef POLYFEM_WITH_MISO
483 if (!mesh->is_simplicial())
488 args[
"space"][
"advanced"][
"count_flipped_els_continuous"] =
false;
489 args[
"output"][
"paraview"][
"options"][
"jacobian_validity"] =
false;
490 args[
"solver"][
"advanced"][
"check_inversion"] =
"Discrete";
492 else if (
args[
"solver"][
"advanced"][
"check_inversion"] !=
"Discrete")
494 args[
"space"][
"advanced"][
"use_corner_quadrature"] =
true;
509 void State::set_mesh(
const Eigen::MatrixXd &
V,
const Eigen::MatrixXi &
F,
bool non_conforming)
std::shared_ptr< varform::VarForm > variational_formulation
active variational formulation
void init(const json &args, bool strict_validation, bool is_adjoint_optimization=false)
initialize the polyfem solver with a json settings
void set_max_threads(const int max_threads=std::numeric_limits< int >::max())
std::optional< std::reference_wrapper< const io::CheckpointReader > > checkpoint_
spdlog::sink_ptr file_sink_
spdlog::sink_ptr console_sink_
logger sink to stdout
json args
main input arguments containing all defaults
void set_log_level(const spdlog::level::level_enum log_level)
change log level
std::unique_ptr< const io::ResourceIO > resources_
std::function< void(int, int, double, double)> time_callback
Optional UI progress callback.
void init_logger(const std::string &log_file, const spdlog::level::level_enum log_level, const spdlog::level::level_enum file_log_level, const bool is_quiet)
initializing the logger
void init(const json &json)
static double convert(const json &val, const std::string &unit_type)
const ResourceIO & resources() const
const json & config() const
Read-only interface to a hierarchical collection of simulation resources.
virtual std::unique_ptr< const ResourceIO > with_root(const std::string &root) const =0
void init(const json &args, const bool strict_validation)
initialize the polyfem solver with a json settings
void load_mesh(bool non_conforming=false, const std::vector< std::string > &names=std::vector< std::string >(), const std::vector< Eigen::MatrixXi > &cells=std::vector< Eigen::MatrixXi >(), const std::vector< Eigen::MatrixXd > &vertices=std::vector< Eigen::MatrixXd >())
loads the mesh from the json arguments
void set_max_threads(const int max_threads=std::numeric_limits< int >::max())
void set_log_level(const spdlog::level::level_enum log_level)
change log level
void init_logger(const std::string &log_file, const spdlog::level::level_enum log_level, const spdlog::level::level_enum file_log_level, const bool is_quiet)
initializing the logger
void solve(Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure, UserPostStepCallback user_post_step={}, const InitialConditionOverride *ic_override=nullptr)
solves the problem, call other methods
Applies geometry JSON semantics while delegating all decoding to MeshLoader.
Obstacle load_obstacles(const json &geometry, const std::vector< json > &obstacle_displacements, const std::vector< json > &dirichlet_conditions, int dimension, bool non_conforming=false) const
LoadedGeometry load(const json &geometry, const std::vector< json > &obstacle_displacements, const std::vector< json > &dirichlet_conditions, bool non_conforming=false) const
std::unique_ptr< Mesh > fem
Format-independent input used to construct a runtime Mesh.
static std::unique_ptr< Mesh > create(MeshData data, bool non_conforming=false)
Construct a runtime mesh from format-independent decoded data.
static MeshData from_geogram(GEO::Mesh &mesh)
void set_logger(spdlog::logger &logger)
static GeogramUtils & instance()
void set_num_threads(const int max_threads)
NLOHMANN_JSON_SERIALIZE_ENUM(CollisionProxyTessellation, {{CollisionProxyTessellation::REGULAR, "regular"}, {CollisionProxyTessellation::IRREGULAR, "irregular"}})
std::unique_ptr< const io::ResourceIO > apply_common_params(json &args, const io::ResourceIO &resources)
void expand_bc_sidecars(json &args, const json &rules)
Expand string entries in dirichlet_boundary that point to .json files.
std::vector< T > json_as_array(const json &j)
Return the value of a json object as an array.
bool is_param_valid(const json ¶ms, const std::string &key)
Determine if a key exists and is non-null in a json object.
spdlog::logger & logger()
Retrieves the current logger.
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
void set_logger(std::shared_ptr< spdlog::logger > p_logger)
Setup a logger object to be used by Polyfem.
void log_and_throw_error(const std::string &msg)