PolyFEM
Loading...
Searching...
No Matches
OptState.cpp
Go to the documentation of this file.
1#include "OptState.hpp"
2
3#include <polyfem/Common.hpp>
4
8
16
19
20#include <polysolve/nonlinear/Solver.hpp>
21
22#include <spdlog/sinks/stdout_color_sinks.h>
23#include <spdlog/sinks/basic_file_sink.h>
24#include <spdlog/sinks/ostream_sink.h>
25
26#include <Eigen/Core>
27
28#include <algorithm>
29#include <filesystem>
30#include <fstream>
31#include <functional>
32#include <limits>
33#include <memory>
34#include <optional>
35#include <string>
36#include <vector>
37
38namespace spdlog::level
39{
41 spdlog::level::level_enum,
42 {{spdlog::level::level_enum::trace, "trace"},
43 {spdlog::level::level_enum::debug, "debug"},
44 {spdlog::level::level_enum::info, "info"},
45 {spdlog::level::level_enum::warn, "warning"},
46 {spdlog::level::level_enum::err, "error"},
47 {spdlog::level::level_enum::critical, "critical"},
48 {spdlog::level::level_enum::off, "off"},
49 {spdlog::level::level_enum::trace, 0},
50 {spdlog::level::level_enum::debug, 1},
51 {spdlog::level::level_enum::info, 2},
52 {spdlog::level::level_enum::warn, 3},
53 {spdlog::level::level_enum::err, 3},
54 {spdlog::level::level_enum::critical, 4},
55 {spdlog::level::level_enum::off, 5}})
56}
57
58namespace polyfem
59{
60 namespace
61 {
62 bool is_failed_status(const polysolve::nonlinear::Status status)
63 {
64 using Status = polysolve::nonlinear::Status;
65 return status == Status::NanEncountered
66 || status == Status::NotDescentDirection
67 || status == Status::LineSearchFailed
68 || status == Status::UpdateDirectionFailed
69 || status == Status::NotStarted
70 || status == Status::Continue;
71 }
72
73 std::string parse_remeshing_trigger(const json &args)
74 {
75 const json &remeshing = args["remeshing"];
76 if (remeshing.is_null())
77 return "none";
78
79 const json &trigger = remeshing["trigger"];
80 if (trigger.is_null())
81 return "none";
82
83 const bool periodic = trigger.contains("periodic") && trigger["periodic"].is_object();
84 const bool scaled_jacobian = trigger.contains("scaled_jacobian") && trigger["scaled_jacobian"].is_object();
85 if (periodic && scaled_jacobian)
86 return "multiple";
87 if (periodic)
88 return "periodic";
89 if (scaled_jacobian)
90 return "scaled_jacobian";
91 return "none";
92 }
93
94 std::vector<json> load_state_jsons(
95 const io::ResourceIO &resources,
96 const json &args,
97 std::vector<std::unique_ptr<const io::ResourceIO>> &state_resources)
98 {
99 std::vector<json> result;
100 state_resources.clear();
101 for (int i = 0; i < args.size(); ++i)
102 {
103 const std::string path = args[i]["path"].get<std::string>();
104 if (!resources.exists(path))
105 log_and_throw_adjoint_error("Can't find json for varform::DifferentiableVarForm {}", i);
106 result.push_back(json::parse(resources.read_string(path)));
107 const std::string parent = std::filesystem::path(path).parent_path().generic_string();
108 state_resources.push_back(resources.with_root(parent));
109 }
110 return result;
111 }
112
113 void validate_remeshing_json(const json &args)
114 {
115 const std::string trigger = parse_remeshing_trigger(args);
116 if (trigger == "multiple")
117 log_and_throw_error("Optimization remeshing requires exactly one trigger: periodic or scaled_jacobian.");
118 const json &remeshing = args["remeshing"];
119 const int state = remeshing["state"];
120 if (state >= args["states"].size())
121 log_and_throw_error("Optimization remeshing state index {} is out of range.", state);
122
123 for (const auto &variable : args["variable_to_simulation"])
124 {
125 if (variable["type"] != "shape")
126 continue;
127
128 const json &variable_state = variable["state"];
129 const bool targets_state = variable_state.is_array()
130 ? std::find(variable_state.begin(), variable_state.end(), state) != variable_state.end()
131 : variable_state.get<int>() == state;
132 if (!targets_state)
133 continue;
134
135 const json &selection = variable["active_geometry_nodes"];
136 const bool selects_all_nodes = selection.is_array() && selection.empty();
137 if (selects_all_nodes || selection.is_object())
138 continue;
139
141 "Optimization remeshing changes mesh vertex numbering. "
142 "Shape variable {} targeting state {} must use a geometry-based "
143 "active_geometry_nodes selector (interior, boundary, or "
144 "boundary_excluding_surface), or an empty selector for all nodes.",
145 variable.value("name", "shape"), state);
146 }
147 }
148
149 void validate_remeshing_geometry(const json &state_args, const int geometry)
150 {
151 if (geometry < 0 || geometry >= state_args["geometry"].size())
152 log_and_throw_error("Optimization remeshing geometry index {} is out of range.", geometry);
153 if (state_args["geometry"][geometry].value("is_obstacle", false))
154 log_and_throw_error("Optimization remeshing geometry {} is an obstacle.", geometry);
155 }
156
158 double minimum_scaled_jacobian(
159 const Eigen::MatrixXd &vertices,
160 const Eigen::MatrixXi &elements)
161 {
162 Eigen::VectorXd quality;
163 solver::AdjointTools::scaled_jacobian(vertices, elements, quality);
164 return quality.minCoeff();
165 }
166
168 double minimum_scaled_jacobian(const varform::DifferentiableVarForm &varform)
169 {
170 Eigen::MatrixXd vertices;
171 Eigen::MatrixXi elements;
172 varform.get_vertices(vertices);
173 varform.get_elements(elements);
174 return minimum_scaled_jacobian(vertices, elements);
175 }
176
183 bool remesh_and_write(
184 const OptState &opt_state,
185 const int state,
186 const int body_id,
187 const std::filesystem::path &path,
188 const std::optional<double> quality_threshold)
189 {
190 mesh::MmgOptions options;
191 options.optim = true;
192
193 Eigen::MatrixXd vertices;
194 Eigen::MatrixXi elements;
195 opt_state.varforms[state]->get_vertices(vertices);
196 opt_state.varforms[state]->get_elements(elements);
197
198 Eigen::MatrixXd remeshed_vertices;
199 Eigen::MatrixXi remeshed_boundary;
200 Eigen::MatrixXi remeshed_elements;
201 bool has_shape_variable = false;
202 for (const auto &var2sim : opt_state.variable_to_simulations.data)
203 {
204 const auto shape_v2s = std::dynamic_pointer_cast<solver::ShapeVariableToSimulation>(var2sim);
205 if (!shape_v2s || !shape_v2s->affects_varform(*opt_state.varforms[state]))
206 continue;
207 has_shape_variable = true;
208
209 for (int other_state = 0; other_state < opt_state.varforms.size(); ++other_state)
210 {
211 if (other_state != state
212 && shape_v2s->affects_varform(*opt_state.varforms[other_state]))
213 {
215 "Optimization remeshing cannot remesh state {} while its shape variable also affects state {}. This is not supported currently.",
216 state, other_state);
217 }
218 }
219 }
220 if (!has_shape_variable)
221 {
222 logger().error("Can not remesh state {} because it's not affected by shape variables. No reason to remesh if you are not doing shape optimization.", state);
223 return false;
224 }
225
226 const mesh::Mesh &mesh = opt_state.varforms[state]->get_mesh();
227 bool success = false;
228 if (mesh.dimension() == 2)
229 {
230 success = mesh::remesh_2d(
231 vertices, elements, remeshed_vertices, remeshed_elements,
232 options);
233 }
234 else
235 {
236 success = mesh::remesh_3d(
237 vertices, elements, remeshed_vertices, remeshed_boundary,
238 remeshed_elements, options);
239 }
240 if (!success)
241 {
242 return false;
243 }
244
245 const double input_quality = minimum_scaled_jacobian(vertices, elements);
246 const double output_quality = minimum_scaled_jacobian(remeshed_vertices, remeshed_elements);
247 logger().info(
248 "Optimization remeshing minimum scaled Jacobian: {} -> {}.",
249 input_quality, output_quality);
250 // If trigger mode is scaled jacobian, check quality immediately after remeshing.
251 if (quality_threshold.has_value() && output_quality <= *quality_threshold)
252 {
254 "MMG remeshing failed to satisfy minimum scaled Jacobian threshold: "
255 "input={}, output={}, required > {}. This is because MMG use a different convergence criteria, please switch remeshing trigger to periodic.",
256 input_quality, output_quality, *quality_threshold);
257 }
258
260 path.string(), remeshed_vertices, remeshed_elements,
261 std::vector<int>(remeshed_elements.rows(), body_id),
262 opt_state.varforms[state]->get_mesh().is_volume(), false);
263 return true;
264 }
265 } // namespace
266
268 {
269 }
270
271 OptState::OptState() = default;
272
273 int OptState::run(json input_args, const bool strict_validation)
274 {
275 std::filesystem::path root = std::filesystem::current_path();
276 if (utils::is_param_valid(input_args, "root_path"))
277 root = input_args["root_path"].get<std::string>();
278 resources_ = std::make_unique<io::FileSystemIO>(root);
279 return run(std::move(input_args), *resources_, strict_validation);
280 }
281
283 json input_args,
284 const io::ResourceIO &resources,
285 const bool strict_validation)
286 {
287 resources_ = resources.with_root("");
288 input_args = solver::AdjointOptUtils::apply_opt_json_spec(input_args, strict_validation);
289
290 std::string mode = parse_remeshing_trigger(input_args);
291 bool remeshing_enabled = mode != "none";
292 if (remeshing_enabled)
293 validate_remeshing_json(input_args);
294
295 std::filesystem::path output_root = input_args["output"]["directory"].get<std::string>();
296 if (!output_root.is_absolute())
297 output_root = resources_->host_directory() / output_root;
298 int max_restarts = remeshing_enabled
299 ? input_args["remeshing"]["max_restarts"].get<int>()
300 : 0;
301 state_args = load_state_jsons(*resources_, input_args["states"], state_resources);
302
303 int state = 0;
304 int geometry = 0;
305 int body_id = 0;
306 if (remeshing_enabled)
307 {
308 state = input_args["remeshing"]["state"].get<int>();
309 geometry = input_args["remeshing"]["geometry"].get<int>();
310 validate_remeshing_geometry(state_args[state], geometry);
311 body_id = state_args[state]["geometry"][geometry].value("volume_selection", 0);
312 }
313
314 int remesh_count = 0;
315 while (true)
316 {
317 remeshing_requested_ = false;
318
319 // Each remeshing round use a unique output directory.
320 json round_args = input_args;
321 if (remeshing_enabled)
322 {
323 const std::filesystem::path round_dir = output_root / fmt::format("remesh_round_{:d}", remesh_count);
324 round_args["output"]["directory"] = round_dir.string();
325 state_args[state]["output"]["directory"] = round_dir.string();
326 }
327
328 init(round_args, *resources_, strict_validation);
329 create_varforms(args["solver"]["max_threads"].get<int>());
332
333 Eigen::VectorXd x;
335 // Dry run mode. Compute objective and exit immediately.
336 if (args["compute_objective"].get<bool>())
337 {
338 logger().info("Objective is {}", eval(x));
339 return EXIT_SUCCESS;
340 }
341
342 const polysolve::nonlinear::Status status = solve(x);
343 if (is_failed_status(status))
344 {
345 logger().error("Optimization failed: {}.", polysolve::nonlinear::status_message(status));
346 return EXIT_FAILURE;
347 }
349 {
350 return EXIT_SUCCESS;
351 }
352 if (remesh_count >= max_restarts)
353 {
354 logger().info("Reached the optimization remeshing limit of {} restart(s).", max_restarts);
355 return EXIT_SUCCESS;
356 }
357
358 const std::filesystem::path round_dir = output_root / fmt::format("remesh_round_{:d}", remesh_count);
359 const std::filesystem::path remeshed_path = std::filesystem::absolute(round_dir / "remeshed.msh");
360 const std::optional<double> quality_threshold = mode == "scaled_jacobian"
361 ? std::optional<double>(args["remeshing"]["trigger"]["scaled_jacobian"]["quality_threshold"].get<double>())
362 : std::nullopt;
363 if (!remesh_and_write(
364 *this, state, body_id,
365 remeshed_path, quality_threshold))
366 {
367 logger().error("MMG failed to produce a valid optimization restart mesh.");
368 return EXIT_FAILURE;
369 }
370
371 state_args[state]["geometry"][geometry]["mesh"] = remeshed_path.string();
372 logger().info("Restarting optimization from remeshed mesh {}.", remeshed_path.string());
373 ++remesh_count;
374 }
375 }
376
378 const std::string &log_file,
379 const spdlog::level::level_enum log_level,
380 const spdlog::level::level_enum file_log_level,
381 const bool is_quiet)
382 {
383 std::vector<spdlog::sink_ptr> sinks;
384
385 if (!is_quiet)
386 {
387 console_sink_ = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
388 sinks.emplace_back(console_sink_);
389 }
390
391 if (!log_file.empty())
392 {
393 file_sink_ = std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file, /*truncate=*/true);
394 // Set the file sink separately from the console so it can save all messages
395 file_sink_->set_level(file_log_level);
396 sinks.push_back(file_sink_);
397 }
398
399 init_logger(sinks, log_level);
400 spdlog::flush_every(std::chrono::seconds(3));
401 }
402
403 void OptState::init_logger(std::ostream &os, const spdlog::level::level_enum log_level)
404 {
405 std::vector<spdlog::sink_ptr> sinks;
406 sinks.emplace_back(std::make_shared<spdlog::sinks::ostream_sink_mt>(os, false));
407 init_logger(sinks, log_level);
408 }
409
411 const std::vector<spdlog::sink_ptr> &sinks,
412 const spdlog::level::level_enum log_level)
413 {
414 set_adjoint_logger(std::make_shared<spdlog::logger>("adjoint-polyfem", sinks.begin(), sinks.end()));
415
416 // Set the logger at the lowest level, so all messages are passed to the sinks
417 adjoint_logger().set_level(spdlog::level::trace);
418 set_log_level(log_level);
419 }
420
421 void OptState::set_log_level(const spdlog::level::level_enum log_level)
422 {
423 adjoint_logger().set_level(log_level);
424 if (console_sink_)
425 console_sink_->set_level(log_level); // Shared by all loggers
426 }
427
428 void OptState::init(const json &p_args_in, const bool strict_validation)
429 {
430 std::filesystem::path root = std::filesystem::current_path();
431 if (utils::is_param_valid(p_args_in, "root_path"))
432 root = p_args_in["root_path"].get<std::string>();
433 resources_ = std::make_unique<io::FileSystemIO>(root);
434 init(p_args_in, *resources_, strict_validation);
435 }
436
438 const json &p_args_in,
439 const io::ResourceIO &resources,
440 const bool strict_validation)
441 {
442 resources_ = resources.with_root("");
443 strict_validation_ = strict_validation;
444 json args_in = p_args_in; // mutable copy
445 args = solver::AdjointOptUtils::apply_opt_json_spec(args_in, strict_validation);
446
447 // Save output directory and resolve output paths dynamically
448 std::filesystem::path output_path = args["output"]["directory"].get<std::string>();
449 if (!output_path.is_absolute())
450 output_path = resources_->host_directory() / output_path;
451 const std::string output_dir = output_path.lexically_normal().string();
452 if (!output_dir.empty())
453 {
454 std::filesystem::create_directories(output_dir);
455 }
456 this->output_dir = output_dir;
457
458 std::string out_path_log = args["output"]["log"]["path"];
459 if (!out_path_log.empty())
460 {
461 out_path_log = (std::filesystem::path(out_path_log).is_absolute()
462 ? std::filesystem::path(out_path_log)
463 : std::filesystem::path(output_dir) / out_path_log)
464 .lexically_normal()
465 .string();
466 }
467
469 out_path_log,
470 args["output"]["log"]["level"],
471 args["output"]["log"]["file_level"],
472 args["output"]["log"]["quiet"]);
473
474 adjoint_logger().info("Saving adjoint output to {}", output_dir);
475
476 const int thread_in = args["solver"]["max_threads"];
478 }
479
480 void OptState::create_varforms(const int max_threads)
481 {
482 if (state_args.empty())
483 state_args = load_state_jsons(*resources_, args["states"], state_resources);
484
485 size_t threads = max_threads <= 0
486 ? std::numeric_limits<unsigned int>::max()
487 : max_threads;
488 varforms.clear();
489 for (int i = 0; i < state_args.size(); ++i)
490 {
491 json cur_args = state_args[i];
492 if (!args["output"]["log"].empty())
493 cur_args["output"]["log"].merge_patch(args["output"]["log"]);
494 varforms.push_back(from_json::build_differentiable_varform(cur_args, *state_resources.at(i), threads));
495 }
496
497 diff_caches.resize(varforms.size());
498 for (auto &diff_cache : diff_caches)
499 {
500 diff_cache = std::make_shared<DiffCache>();
501 }
502
504 }
505
507 {
508 for (int i = 0; i < varforms.size(); ++i)
509 {
510 const varform::DifferentiableVarForm &varform = *varforms[i];
511 if (!varform.solve_data())
512 {
514 "varform::DifferentiableVarForm {} ({}) does not expose solve data required by optimization.",
515 i, varform.name());
516 }
517
518 // No transient linear support.
519 if (varform.get_problem().is_time_dependent() && varform.is_problem_linear())
520 {
522 "varform::DifferentiableVarForm {}: transient linear problem is not supported in optimization.", i);
523 }
524
525 if (varform.is_contact_enabled())
526 {
527 // No non-convergent contact formulation support.
528 if (!varform.get_args()["contact"]["use_gcp_formulation"].get<bool>()
529 && !varform.get_args()["contact"]["use_convergent_formulation"].get<bool>())
530 {
532 "varform::DifferentiableVarForm {}: non-convergent contact formulation is not supported in optimization.", i);
533 }
534
535 // No non-const barrier stiffness support.
536 if (varform.get_args()["/solver/contact/barrier_stiffness"_json_pointer].is_string())
537 {
539 "varform::DifferentiableVarForm {}: only constant barrier stiffness is supported in optimization.", i);
540 }
541 }
542
543 // No non-const boundary support.
544 if (varform.get_args().contains("boundary_conditions") && varform.get_args()["boundary_conditions"].contains("rhs"))
545 {
546 const json &rhs = varform.get_args()["boundary_conditions"]["rhs"];
547 if (rhs.is_string() || (rhs.is_array() && rhs.size() > 0 && rhs[0].is_string()))
548 {
550 "varform::DifferentiableVarForm {}: only constant rhs over space is supported in optimization.", i);
551 }
552 }
553
554 // No high order geometric basis support.
555 for (const auto &element_bases : varform.primary_space().geometry_basis_list())
556 {
557 for (const auto &basis : element_bases.bases)
558 {
559 if (basis.order() > 1)
560 {
562 "varform::DifferentiableVarForm {}: high-order geometry basis is not supported in optimization.", i);
563 }
564 }
565 }
566 }
567 }
568
570 {
571 std::vector<std::reference_wrapper<const io::ResourceIO>> resource_refs;
572 resource_refs.reserve(state_resources.size());
573 for (const auto &resources : state_resources)
574 resource_refs.emplace_back(*resources);
575
576 const json &parameters = args["parameters"];
577 bool is_auto = parameters.is_string() && parameters.get<std::string>() == "auto";
578
579 // Auto mode.
580 // In auto mode optimization parameters dof is inferred. No need to parse json.
581 if (is_auto)
582 {
583 if (args["variable_to_simulation"].size() != 1)
584 {
586 "Auto parameters are only supported with a single variable to simulation.");
587 }
588
589 for (auto &composition : utils::json_as_array(args["variable_to_simulation"][0]["composition"]))
590 {
591 if (composition["type"].get<std::string>() == "slice")
592 {
593 log_and_throw_adjoint_error("Auto parameters do not support slice maps in composition.");
594 }
595 }
596
598
599 ndof = variable_to_simulations.data[0]->inverse_dof();
601
602 return;
603 }
604
605 // Manual mode.
606 // We need to parse optimization parameter blocks to load dof first.
607 variable_sizes.clear();
608 ndof = 0;
609 for (const auto &arg : args["parameters"])
610 {
612 ndof += size;
613 variable_sizes.push_back(size);
614 }
615
616 /* variable to simulations */
618 args["variable_to_simulation"], varforms, diff_caches, variable_sizes, resource_refs);
619
620 // Verify varaible dof.
621 for (int i = 0; i < variable_to_simulations.data.size(); ++i)
622 {
623 auto &var2sim = variable_to_simulations.data[i];
624 int inv_dof = var2sim->inverse_dof();
625 if (inv_dof != ndof)
626 {
628 "VariableToSimulation {} (type {}) expects {} DOF, but parameters define {} DOF.",
629 i, var2sim->name(), inv_dof, ndof);
630 }
631 }
632 }
633
635 {
636 std::vector<std::reference_wrapper<const io::ResourceIO>> resource_refs;
637 resource_refs.reserve(state_resources.size());
638 for (const auto &resources : state_resources)
639 resource_refs.emplace_back(*resources);
640
641 /* forms */
642 std::shared_ptr<solver::AdjointForm> obj = from_json::build_form(
643 args["functionals"], variable_to_simulations, varforms, diff_caches, resource_refs);
644
645 /* stopping conditions */
646 std::vector<std::shared_ptr<solver::AdjointForm>> stopping_conditions;
647 for (const auto &arg : args["stopping_conditions"])
648 stopping_conditions.push_back(
650
651 std::function<bool()> remeshing_trigger;
652 const std::string mode = parse_remeshing_trigger(args);
653 if (mode == "periodic")
654 {
655 int period = args["remeshing"]["trigger"]["periodic"]["period"];
656 // this capture is for remeshing_requested_ specifically.
657 remeshing_trigger = [this, period, iter = 0]() mutable {
658 remeshing_requested_ = (iter % period) == 0;
659 ++iter;
661 adjoint_logger().debug(
662 "Periodic optimization remeshing triggered after {} accepted iteration(s).", iter);
664 };
665 }
666 else if (mode == "scaled_jacobian")
667 {
668 int state = args["remeshing"]["state"];
669 double threshold = args["remeshing"]["trigger"]["scaled_jacobian"]["quality_threshold"];
670 auto varform = varforms[state];
671 // this capture is for remeshing_requested_ specifically.
672 remeshing_trigger = [this, varform, threshold]() {
673 double quality = minimum_scaled_jacobian(*varform);
674 adjoint_logger().debug(
675 "Minimum scaled Jacobian: {} (remesh threshold: {}).",
676 quality, threshold);
677 remeshing_requested_ = quality <= threshold;
679 };
680 }
681
682 nl_problem = std::make_unique<solver::AdjointNLProblem>(
683 obj, stopping_conditions, variable_to_simulations, varforms, diff_caches,
684 args, std::move(remeshing_trigger));
685 }
686
693
694 double OptState::eval(Eigen::VectorXd &x) const
695 {
696 nl_problem->solution_changed(x);
697 return nl_problem->value(x);
698 }
699
700 polysolve::nonlinear::Status OptState::solve(Eigen::VectorXd &x)
701 {
703 args["solver"]["nonlinear"],
704 args["solver"]["linear"],
705 args["solver"]["advanced"]["characteristic_length"],
707 nl_problem->normalize_forms();
708 nl_solver->minimize(*nl_problem, x);
709 return nl_solver->status();
710 }
711} // namespace polyfem
int x
void initial_guess(Eigen::VectorXd &x)
Definition OptState.cpp:687
void set_log_level(const spdlog::level::level_enum log_level)
change log level
Definition OptState.cpp:421
json args
main input arguments containing all defaults
Definition OptState.hpp:51
std::vector< std::shared_ptr< varform::DifferentiableVarForm > > varforms
Variational formulations used by the optimization.
Definition OptState.hpp:92
void init(const json &args, const bool strict_validation)
initialize the polyfem solver with a json settings
Definition OptState.cpp:428
int run(json args, const bool strict_validation)
Run optimization, including remeshing restarts when the selected trigger requests them.
Definition OptState.cpp:273
std::vector< std::shared_ptr< DiffCache > > diff_caches
Definition OptState.hpp:95
spdlog::sink_ptr file_sink_
Definition OptState.hpp:114
void check_unsupported() const
Check and throw if any forward simulation varform::DifferentiableVarForm is not supported.
Definition OptState.cpp:506
double eval(Eigen::VectorXd &x) const
Definition OptState.cpp:694
std::vector< std::unique_ptr< const io::ResourceIO > > state_resources
Definition OptState.hpp:94
std::vector< int > variable_sizes
variables
Definition OptState.hpp:98
std::unique_ptr< solver::AdjointNLProblem > nl_problem
Definition OptState.hpp:103
std::string output_dir
Directory for output files.
Definition OptState.hpp:126
std::vector< json > state_args
Definition OptState.hpp:93
spdlog::sink_ptr console_sink_
logger sink to stdout
Definition OptState.hpp:113
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
Definition OptState.cpp:377
std::unique_ptr< const io::ResourceIO > resources_
Definition OptState.hpp:118
solver::VariableToSimulationGroup variable_to_simulations
Definition OptState.hpp:101
void create_varforms(const int max_threads=-1)
Create the optimization variational formulations.
Definition OptState.cpp:480
polysolve::nonlinear::Status solve(Eigen::VectorXd &x)
Definition OptState.cpp:700
void init_variables()
init variables
Definition OptState.cpp:569
OptState()
Constructor.
virtual bool is_time_dependent() const
Definition Problem.hpp:68
static void write(const std::string &path, const mesh::Mesh &mesh, const bool binary)
saves the mesh
Definition MshWriter.cpp:7
Read-only interface to a hierarchical collection of simulation resources.
virtual std::unique_ptr< const ResourceIO > with_root(const std::string &root) const =0
std::vector< std::shared_ptr< VariableToSimulation > > data
static NThread & get()
Definition par_for.hpp:39
void set_num_threads(const int max_threads)
Definition par_for.hpp:47
Optimization-facing interface implemented by differentiated VarForm adapters.
virtual std::string name() const =0
virtual solver::SolveData * solve_data()=0
virtual assembler::Problem & get_problem()=0
virtual bool is_contact_enabled() const =0
virtual const FESpace & primary_space() const =0
const std::vector< basis::ElementBases > & geometry_basis_list() const
Definition FESpace.hpp:119
list vertices
Definition p_bases.py:238
std::shared_ptr< varform::DifferentiableVarForm > build_differentiable_varform(const json &args, const io::ResourceIO &resources, const size_t max_threads)
solver::VariableToSimulationGroup build_variable_to_simulation_group(const json &args, const std::vector< std::shared_ptr< varform::DifferentiableVarForm > > &varforms, const std::vector< std::shared_ptr< DiffCache > > &diff_caches, const std::vector< int > &variable_sizes, const std::vector< std::reference_wrapper< const io::ResourceIO > > &resources)
std::shared_ptr< solver::AdjointForm > build_form(const json &args, const solver::VariableToSimulationGroup &var2sim, const std::vector< std::shared_ptr< varform::DifferentiableVarForm > > &varforms, const std::vector< std::shared_ptr< DiffCache > > &diff_caches, const std::vector< std::reference_wrapper< const io::ResourceIO > > &resources)
NLOHMANN_JSON_SERIALIZE_ENUM(CollisionProxyTessellation, {{CollisionProxyTessellation::REGULAR, "regular"}, {CollisionProxyTessellation::IRREGULAR, "irregular"}})
void scaled_jacobian(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, Eigen::VectorXd &quality)
std::vector< T > json_as_array(const json &j)
Return the value of a json object as an array.
Definition JSONUtils.hpp:49
bool is_param_valid(const json &params, const std::string &key)
Determine if a key exists and is non-null in a json object.
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:44
spdlog::logger & adjoint_logger()
Retrieves the current logger for adjoint.
Definition Logger.cpp:30
nlohmann::json json
Definition Common.hpp:9
void set_adjoint_logger(std::shared_ptr< spdlog::logger > p_logger)
Setup a logger object to be used by adjoint Polyfem.
Definition Logger.cpp:68
void log_and_throw_adjoint_error(const std::string &msg)
Definition Logger.cpp:79
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73
static int compute_variable_size(const json &args, const std::vector< std::shared_ptr< varform::DifferentiableVarForm > > &varforms)
static json apply_opt_json_spec(const json &input_args, bool strict_validation)
static Eigen::VectorXd inverse_evaluation(const json &args, const int ndof, const std::vector< int > &variable_sizes, VariableToSimulationGroup &var2sim)
static std::shared_ptr< polysolve::nonlinear::Solver > make_nl_solver(const json &solver_params, const json &linear_solver_params, const double characteristic_length, const bool strict_validation=true)