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>
45 spdlog::level::level_enum,
46 {{spdlog::level::level_enum::trace,
"trace"},
47 {spdlog::level::level_enum::debug,
"debug"},
48 {spdlog::level::level_enum::info,
"info"},
49 {spdlog::level::level_enum::warn,
"warning"},
50 {spdlog::level::level_enum::err,
"error"},
51 {spdlog::level::level_enum::critical,
"critical"},
52 {spdlog::level::level_enum::off,
"off"},
53 {spdlog::level::level_enum::trace, 0},
54 {spdlog::level::level_enum::debug, 1},
55 {spdlog::level::level_enum::info, 2},
56 {spdlog::level::level_enum::warn, 3},
57 {spdlog::level::level_enum::err, 3},
58 {spdlog::level::level_enum::critical, 4},
59 {spdlog::level::level_enum::off, 5}})
65 using namespace utils;
69 std::string formulation_from_args(
const json &args)
71 if (!
args.contains(
"materials") || args[
"materials"].is_null())
74 if (args[
"materials"].is_array())
77 for (
const auto &m :
args[
"materials"])
79 const std::string
tmp = m[
"type"];
82 else if (current != tmp)
87 current =
"MultiModels";
99 return args[
"materials"].value(
"type",
"");
102 std::string resolve_output_path(
const std::string &output_dir,
const std::string &path)
104 if (output_dir.empty() ||
path.empty() || std::filesystem::path(path).is_absolute())
106 return std::filesystem::weakly_canonical(std::filesystem::path(output_dir) / path).string();
109 bool contact_enabled(
const json &args)
111 return args[
"contact"][
"enabled"];
114 void init_time(
json &args, Units &units)
119 const double t0 =
Units::convert(args[
"time"][
"t0"], units.time());
131 else if (num_valid == 2)
141 time_steps = int(std::ceil((tend - t0) / dt));
142 assert(time_steps > 0);
146 time_steps =
args[
"time"][
"time_steps"];
149 dt = (tend - t0) / time_steps;
154 throw std::runtime_error(
"This code should be unreachable!");
164 time_steps =
args[
"time"][
"time_steps"];
169 tend = t0 + time_steps * dt;
173 throw std::runtime_error(
"This code should be unreachable!");
176 else if (num_valid == 3)
180 time_steps =
args[
"time"][
"time_steps"];
182 if (std::abs(t0 + dt * time_steps - tend) > 1e-12)
186 args[
"time"][
"tend"] = tend;
187 args[
"time"][
"dt"] = dt;
188 args[
"time"][
"time_steps"] = time_steps;
190 units.characteristic_length() *= dt;
192 logger().info(
"t0={}, dt={}, tend={}", t0, dt, tend);
199 const std::string &log_file,
200 const spdlog::level::level_enum log_level,
201 const spdlog::level::level_enum file_log_level,
204 std::vector<spdlog::sink_ptr> sinks;
208 console_sink_ = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
212 if (!log_file.empty())
214 file_sink_ = std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file,
true);
220 spdlog::flush_every(std::chrono::seconds(3));
225 std::vector<spdlog::sink_ptr> sinks;
226 sinks.emplace_back(std::make_shared<spdlog::sinks::ostream_sink_mt>(os,
false));
231 const std::vector<spdlog::sink_ptr> &sinks,
232 const spdlog::level::level_enum log_level)
234 set_logger(std::make_shared<spdlog::logger>(
"polyfem", sinks.begin(), sinks.end()));
236 ipc::set_logger(std::make_shared<spdlog::logger>(
"ipctk", sinks.begin(), sinks.end()));
238 logger().set_level(spdlog::level::trace);
239 ipc::logger().set_level(spdlog::level::trace);
246 spdlog::set_level(log_level);
253 logger().set_level(log_level);
254 ipc::logger().set_level(log_level);
259 const json &p_args_in,
260 const bool strict_validation,
261 const bool is_adjoint_optimization)
264 init(p_args_in, resources, strict_validation, is_adjoint_optimization);
268 const json &p_args_in,
270 const bool strict_validation,
271 const bool is_adjoint_optimization)
274 json args_in = p_args_in;
276 ? args_in[
"root_path"].get<std::string>()
279 args_in.erase(
"root_path");
280 const bool contact_dhat_was_explicit = args_in.contains(
"/contact/dhat"_json_pointer);
288 jse.strict = strict_validation;
289 rules = jse::embed::polyfem_spec::polyfem::spec();
291 polysolve::linear::Solver::apply_default_solver(rules,
"/solver/linear");
292 polysolve::linear::Solver::apply_default_solver(rules,
"/solver/adjoint_linear");
295 polysolve::linear::Solver::select_valid_solver(args_in[
"solver"][
"linear"],
logger());
296 if (args_in[
"solver"][
"adjoint_linear"].is_null())
297 args_in[
"solver"][
"adjoint_linear"] = args_in[
"solver"][
"linear"];
299 polysolve::linear::Solver::select_valid_solver(args_in[
"solver"][
"adjoint_linear"],
logger());
301 if (args_in.contains(
"/solver/nonlinear"_json_pointer))
303 if (args_in.contains(
"/solver/augmented_lagrangian/nonlinear"_json_pointer))
305 assert(args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"].is_object());
306 json nonlinear = args_in[
"solver"][
"nonlinear"];
307 nonlinear.merge_patch(args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"]);
308 args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"] = nonlinear;
312 args_in[
"solver"][
"augmented_lagrangian"][
"nonlinear"] = args_in[
"solver"][
"nonlinear"];
316 const bool valid_input = jse.verify_json(args_in, rules);
319 logger().error(
"invalid input json:\n{}", jse.log2str());
320 throw std::runtime_error(
"Invalid input json file");
323 args = jse.inject_defaults(args_in, rules);
326 args, jse::embed::polyfem_dirichlet_spec::polyfem_dirichlet::spec(), *
resources_);
331 if (!args_in.contains(
"/space/advanced/bc_method"_json_pointer) &&
args[
"space"][
"basis_type"] !=
"Lagrange")
333 logger().warn(
"Setting bc method to lsq for non-Lagrange basis");
334 args[
"space"][
"advanced"][
"bc_method"] =
"lsq";
337 const std::string configured_output_dir =
args[
"output"][
"directory"].get<std::string>();
338 const std::string output_dir = configured_output_dir.empty()
340 : (std::filesystem::path(configured_output_dir).is_absolute()
341 ? std::filesystem::path(configured_output_dir)
342 :
resources_->host_directory() / configured_output_dir)
345 if (!output_dir.empty())
346 std::filesystem::create_directories(output_dir);
348 std::string out_path_log =
args[
"output"][
"log"][
"path"];
349 if (!out_path_log.empty())
350 out_path_log = resolve_output_path(output_dir, out_path_log);
354 args[
"output"][
"log"][
"level"],
355 args[
"output"][
"log"][
"file_level"],
356 args[
"output"][
"log"][
"quiet"]);
358 logger().info(
"Saving output to {}", output_dir);
362 init_time(
args, units);
364 if (contact_enabled(
args))
366 if (
args[
"solver"][
"contact"][
"friction_iterations"] == 0)
368 logger().info(
"specified friction_iterations is 0; disabling friction");
369 args[
"contact"][
"friction_coefficient"] = 0.0;
371 else if (
args[
"solver"][
"contact"][
"friction_iterations"] < 0)
373 args[
"solver"][
"contact"][
"friction_iterations"] = std::numeric_limits<int>::max();
375 if (
args[
"contact"][
"friction_coefficient"] == 0.0)
377 args[
"solver"][
"contact"][
"friction_iterations"] = 0;
382 args[
"solver"][
"contact"][
"friction_iterations"] = 0;
383 args[
"contact"][
"friction_coefficient"] = 0;
384 args[
"contact"][
"periodic"] =
false;
387 const std::string formulation = formulation_from_args(
args);
388 if (formulation.empty())
390 logger().error(
"specify some 'materials'");
391 throw std::runtime_error(
"invalid input");
396 throw std::runtime_error(
"Unsupported configuration for formulation " + formulation +
".");
399 args[
"contact"][
"_dhat_was_explicit"] = contact_dhat_was_explicit;
401 args[
"contact"].erase(
"_dhat_was_explicit");
408 init(checkpoint.
config(), checkpoint, strict_validation);
412 const json &continuation,
414 const bool strict_validation)
416 init(continuation, checkpoint.
resources(), strict_validation,
false);
421 "Checkpoint formulation '{}' is incompatible with configured formulation '{}'.",
423 if (std::abs(
args[
"time"][
"dt"].get<double>() -
checkpoint_->get().metadata().dt) > 1e-12)
425 if (std::abs(
args[
"time"][
"t0"].get<double>() -
checkpoint_->get().metadata().time) > 1e-12)
426 log_and_throw_error(
"Checkpoint time is incompatible with its continuation configuration.");
439 logger().info(
"Loading mesh ...");
449 loaded_geometry.
fem =
checkpoint_->get().read_mesh(
"/checkpoint/meshes/active", non_conforming);
451 args[
"geometry"], obstacle_displacements, dirichlet_conditions,
452 loaded_geometry.
fem->dimension(), non_conforming);
455 loaded_geometry = geometry_loader.
load(
456 args[
"geometry"], obstacle_displacements, dirichlet_conditions, non_conforming);
457 auto &mesh = loaded_geometry.
fem;
463 mesh->bounding_box(min, max);
465 logger().info(
"mesh bb min [{}], max [{}]", min, max);
468 logger().info(
" took {}s", timer.getElapsedTime());
470#ifdef POLYFEM_WITH_MISO
471 if (!mesh->is_simplicial())
476 args[
"space"][
"advanced"][
"count_flipped_els_continuous"] =
false;
477 args[
"output"][
"paraview"][
"options"][
"jacobian_validity"] =
false;
478 args[
"solver"][
"advanced"][
"check_inversion"] =
"Discrete";
480 else if (
args[
"solver"][
"advanced"][
"check_inversion"] !=
"Discrete")
482 args[
"space"][
"advanced"][
"use_corner_quadrature"] =
true;
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 solve(Eigen::MatrixXd &sol)
solves the problem, call other methods
void set_max_threads(const int max_threads=std::numeric_limits< int >::max())
void set_mesh(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, bool non_conforming=false)
loads the mesh from V and F,
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 load_mesh(bool non_conforming=false)
loads the mesh from the json arguments
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)
static bool is_elastic_material(const std::string &material)
utility to check if material is one of the elastic materials
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
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.
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)