diff --git a/CHANGELOG.md b/CHANGELOG.md index f7c8f3c..0dff913 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,394 +1,395 @@ # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) for final versions and [PEP440](https://www.python.org/dev/peps/pep-0440/) in case intermediate versions need to be released (e.g. development version `2.2.3.dev1` or release candidates `2.2.3rc1`), or individual commits are packaged. ## Unreleased ### Added - Added a `Material` class tree to decouple material behavior from residuals. The `Material` class can be derived in Python for custom material laws. - `Model` can set the integration method for volume operators with the `setIntegrationMethod` method. +- `EPICSolver` can be used in `utils.load_path` ### Changed - Removed `model_type` template for `Residual`: they are only defined on the `model_type::volume_2d` type. - Simplified interface for `Residual`: it now takes a `Material` object at construction which handles the computation of eigenstresses involved in the residual equation ### Deprecated - `getStress()`, `setIntegrationMethod()` and `getVector()` in `Residual` are deprecated, use `model["stress"]`, `model.setIntegrationMethod()` and `residual.vector` respectively instead. - `ModelFactor.createResidual` is deprecated. Instead, instanciate a `Material` object and use the `Residual` constructor to create the residual object. ## v2.6.0 -- 2022-12-23 ### Added - Added `matvec` interface for the following operators: - `Hooke` - `Kelvin` - `Westergaard` - Documented error handling with MPI - Added `span` class - `FieldContainer` class that defines an interface to access fields registered with an object - Operators now expose their fields, which can be modified from Python - Added `HookeField` operator for heterogeneous elastic properties - Documented proper unit choice - Added `Statistics::computeFDRMSSlope()`, finite difference approximation of RMS of surface slopes - Kato saturated uses L2 norm on residual displacement instead of L∞ - Request system to avoid erasing model data on restart - Boundary field names are dumped ### Changed - Resizing a grid no longer sets values to zero - Wheels built for `manylinux2014` instead of `manylinux2010` - Cleaned up `Array` interface - Shared-memory compile options disabled by default - Unknown build variables raise a warning - Removed conditional branches from PKR - NetCDF dumps in `NETCDF4` format instead of `NETCDF4_CLASSIC` - VTK no longer writes FieldData, this was causing issues reading converted files ### Fixed - Fixed flood fill algorithm to properly account for PBCs ## v2.5.0 -- 2022-07-05 ### Added - Added `tamaas.utils.publications` to print a list of publications relevant to the parts of Tamaas used in a script. Call at the end of a script for an exhaustive list. - Added `tamaas.mpi.gather` and `tamaas.mpi.scatter` to help handling of 2D data in MPI contexts. - Added `getBoundaryFields()/boundary_fields` function/property to `Model`. - Added Python constructor to `Model`, which is an alias to `ModelFactory.createModel`. - Added convenience `tamaas.dumpers._helper.netCDFtoParaview` function to convert model sequence to Paraview data file. - Added dump of surface fields as `FieldData` in VTK files - Added `scipy.sparse.linalg.LinearOperator` interface to `Westergaard`. A `LinearOperator` can be created by calling `scipy.sparse.linalg.aslinearoperator` on the operator object. - Allowed sub-classing of `ContactSolver` in Python. - Exposed elastic contact functionals in Python to help with custom solver implementation. - Added an example of custom solver with penalty method using Scipy. - Added `graphArea` function in statistics to compute area of function graph - Added `tamaas.utils.radial_average` to radialy average a 2D field - Added option to not make a dump directory (e.g. `netcdf`, `hdf5` directories for dump files). This allows to specify an absolute path for dump files, and is useful if simulation workflow is managed with file targets, as do systems like GNU Make and Snakemake. ### Changed - Filter for boundary fields in dumper should be smarter. - `read` functions in dumpers are now `@classmethod` - Changed sign of plastic correction in KatoSaturated solver to match the EPICSolver sign. - Plastic correction of KatoSaturated is registered in the model as `KatoSaturated::residual_displacement`. - Changed to modern Python packaging (PEP517) with `setup.cfg` and `pyproject.toml`. A `setup.py` script is still provided for editable installations, see [gh#7953](https://github.com/pypa/pip/issues/7953). Once setuptools has stable support for [PEP621](https://peps.python.org/pep-0621/), `setup.cfg` will be merged into `pyproject.toml`. Note that source distributions that can be built with [`build`](https://pypi.org/project/build/) are not true source distributions, since they contain the compiled Python module of Tamaas. - Updated copyright to reflect Tamaas' development history since leaving EPFL ### Fixed - Fixed `tamaas.dumpers.NetCDFDumper` to dump in MPI context. ### Deprecated - SCons versions < 3 and Python < 3.6 are explicitely no longer supported. ## v2.4.0 -- 2022-03-22 ### Added - Added a `tamaas.utils` module. - Added `tamaas.utils.load_path` generator, which yields model objects for a sequence of applied loads. - Added `tamaas.utils.seeded_surfaces` generator, which yields surfaces for a sequence of random seeds. - Added `tamaas.utils.hertz_surface` which generates a parabolic (Hertzian) surface. - Added `tamaas.utils.log_context` context manager which locally sets the log level for Tamaas' logger. - Added `tamaas.compute.from_voigt` to convert Voigt/Mendel fields to dense tensor fields. - Added a deep-copy function to `ModelFactory` to copy `Model` objects. Use `model_copy = copy.deepcopy(model)` in Python to make a copy. Currently only copies registered fields, same as dumpers/readers. - Added a `read_sequence` method for dumpers to read model frames. - Automatic draft release on Zenodo. ### Changed - `*_ROOT` variables for vendored dependencies GoogleTest and pybind11 now default to empty strings, so that the vendored trees in `third-party/` are not selected by default. This is so system packages are given priority. Vendored dependency submodules will eventually be deprecated. ### Fixed - Fixed an issue with `scons -c` when GTest was missing. ## v2.3.1 -- 2021-11-08 ### Added - Now using `clang-format`, `clang-tidy` and `flake8` for linting - Pre-built Tamaas images can be pulled with `docker pull registry.gitlab.com/tamaas/tamaas` - Added a `--version` flag to the `tamaas` command ### Changed - The root `Dockerfile` now compiles Tamaas, so using Tamaas in Docker is easier. - The model attributes dumped to Numpy files are now written in a JSON-formatted string to avoid unsafe loading/unpickling of objects. - Removed the `build_doc` build option: now the doc targets are automatically added if the dependencies are met, and built if `scons doc` is called. - Removed the `use_googletest` build option: if tests are built and gtest is present, the corresponding tests will be built ### Fixed - The command `tamaas plot` gracefully fails if Matplotlib is missing - Better heuristic to guess which fields are defined on boundary in dumpers (still not perfect and may give false negatives) ## v2.3.0 -- 2021-06-15 ### Added - Added `read()` method to dumpers to create a model from a dump file - `getClusters()` can be called in MPI contact with partial contact maps - Added a JSON encoder class for models and a JSON dumper - CUDA compatibility is re-established, but has not been tested - Docstrings in the Python bindings for many classes/methods ### Changed - Tamaas version numbers are now managed by [versioneer](https://github.com/python-versioneer/python-versioneer). This means that Git tags prefixed with `v` (e.g. `v2.2.3`) carry meaning and determine the version. When no tag is set, versioneer uses the last tag, specifies the commit short hash and the distance to the last tag (e.g. `2.2.2+33.ge314b0e`). This version string is used in the compiled library, the `setup.py` script and the `__version__` variable in the python module. - Tamaas migrated to [GitLab](https://gitlab.com/tamaas/tamaas) - Continuous delivery has been implemented: - the `master` branch will now automatically build and publish Python wheels to `https://gitlab.com/api/v4/projects/19913787/packages/pypi/simple`. These "nightly" builds can be installed with: pip install \ --extra-index-url https://gitlab.com/api/v4/projects/19913787/packages/pypi/simple \ tamaas - version tags pushed to `master` will automatically publish the wheels to [PyPI](https://pypi.org/project/tamaas/) ### Deprecated - The `finalize()` function is now deprecated, since it is automatically called when the process terminates - Python versions 3.5 and below are not supported anymore ### Fixed - Fixed a host of dump read/write issues when model type was not `volume_*d`. Dumper tests are now streamlined and systematic. - Fixed a bug where `Model::solveDirichlet` would not compute correctly - Fixed a bug where `Statistics::contact` would not normalize by the global number of surface points ## v2.2.2 -- 2021-04-02 ### Added - Entry-point `tamaas` defines a grouped CLI for `examples/pipe_tools`. Try executing `tamaas surface -h` from the command-line! ### Changed - `CXXFLAGS` are now passed to the linker - Added this changelog - Using absolute paths for environmental variables when running `scons test` - Reorganized documentation layout - Gave the build system a facelift (docs are now generated directly with SCons instead of a Makefile) ### Deprecated - Python 2 support is discontinued. Version `v2.2.1` is the last PyPi build with a Python 2 wheel. - The scripts in `examples/pipe_tools` have been replaced by the `tamaas` command ### Fixed - `UVWDumper` no longer imports `mpi4py` in sequential - Compiling with different Thrust/FFTW backends ## v2.2.1 -- 2021-03-02 ### Added - Output registered fields and dumpers in `print(model)` - Added `operator[]` to the C++ model class (for fields) - Added `traction` and `displacement` properties to Python model bindings - Added `operators` property to Python model bindings, which provides a dict-like access to registered operators - Added `shape` and `spectrum` to properties to Python surface generator bindings - Surface generator constructor accepts surface global shape as argument - Choice of FFTW thread model ### Changed - Tests use `/tmp` for temporary files - Updated dependency versions (Thrust, Pybind11) ### Deprecated - Most `get___()` and `set___()` in Python bindings have been deprecated. They will generate a `DeprecationWarning`. ### Removed - All legacy code ## v2.2.0 -- 2020-12-31 ### Added - More accurate function for computation of contact area - Function to compute deviatoric of tensor fields - MPI implementation - Convenience `hdf5toVTK` function - Readonly properties `shape`, `global_shape`, `boundary_shape` on model to give shape information ### Changed - Preprocessor defined macros are prefixed with `TAMAAS_` - Moved `tamaas.to_voigt` to `tamaas.compute.to_voigt` ### Fixed - Warning about deprecated constructors with recent GCC versions - Wrong computation of grid strides - Wrong computation of grid sizes in views ## v2.1.4 -- 2020-08-07 ### Added - Possibility to generate a static `libTamaas` - C++ implementation of DFSANE solver - Allowing compilation without OpenMP ### Changed - NetCDF dumper writes frames to a single file ### Fixed - Compatibility with SCons+Python 3 ## v2.1.3 -- 2020-07-27 ### Added - Version number to `TamaasInfo` ### Changed - Prepending root directory when generating archive ## v2.1.2 -- 2020-07-24 This release changes some core internals related to discrete Fourier transforms for future MPI support. ### Added - Caching `CXXFLAGS` in SCons build - SCons shortcut to create code archive - Test of the elastic-plastic contact solver - Paraview data dumper (`.pvd` files) - Compression for UVW dumper - `__contains__` and `__iter__` Python bindings of model - Warning message of possible overflow in Kelvin ### Changed - Simplified `tamaas_info.cpp`, particularly the diff part - Using a new class `FFTEngine` to manage discrete Fourier transforms. Plans are re-used as much as possible with different data with the same shape. This is in view of future MPI developments - Redirecting I/O streams in solve functions so they can be used from Python (e.g. in Jupyter notebooks) - Calling `initialize()` and `finalize()` is no longer necessary ### Fixed - Convergence issue with non-linear solvers - Memory error in volume potentials ## v2.1.1 -- 2020-04-22 ### Added - SCons shortcut to run tests ### Fixed - Correct `RPATH` for shared libraries - Issues with SCons commands introduced in v2.1.0 - Tests with Python 2.7 ## v2.1.0 -- 2020-04-17 ### Added - SCons shortcuts to build/install Tamaas and its components - Selection of integration method for Kelvin operator - Compilation option to remove the legacy part of Tamaas - NetCDF dumper ### Fixed - Link bug with clang - NaNs in Kato saturated solver ## v2.0.0 -- 2019-11-11 First public release. Contains relatively mature elastic-plastic contact code. diff --git a/python/wrap/solvers.cpp b/python/wrap/solvers.cpp index 0fc3f06..bd55d92 100644 --- a/python/wrap/solvers.cpp +++ b/python/wrap/solvers.cpp @@ -1,239 +1,244 @@ /* * SPDX-License-Indentifier: AGPL-3.0-or-later * * Copyright (©) 2016-2023 EPFL (École Polytechnique Fédérale de Lausanne), * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * Copyright (©) 2020-2023 Lucas Frérot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * */ /* -------------------------------------------------------------------------- */ #include "beck_teboulle.hh" #include "condat.hh" #include "contact_solver.hh" #include "dfsane_solver.hh" #include "ep_solver.hh" #include "epic.hh" #include "kato.hh" #include "kato_saturated.hh" #include "polonsky_keer_rey.hh" #include "polonsky_keer_tan.hh" #include "wrap.hh" #include /* -------------------------------------------------------------------------- */ namespace tamaas { namespace wrap { /* -------------------------------------------------------------------------- */ using namespace py::literals; class PyEPSolver : public EPSolver { public: using EPSolver::EPSolver; // NOLINTNEXTLINE(readability-else-after-return) void solve() override { PYBIND11_OVERLOAD_PURE(void, EPSolver, solve); } void updateState() override { // NOLINTNEXTLINE(readability-else-after-return) PYBIND11_OVERLOAD(void, EPSolver, updateState); } }; class PyContactSolver : public ContactSolver { public: using ContactSolver::ContactSolver; Real solve(std::vector load) override { PYBIND11_OVERLOAD(Real, ContactSolver, solve, load); } Real solve(Real load) override { PYBIND11_OVERLOAD(Real, ContactSolver, solve, load); } }; /* -------------------------------------------------------------------------- */ void wrapSolvers(py::module& mod) { py::class_(mod, "ContactSolver") .def(py::init&, Real>(), py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def( "setMaxIterations", [](ContactSolver& m, UInt iter) { TAMAAS_DEPRECATE("setMaxIterations()", "the max_iter property"); m.setMaxIterations(iter); }, "max_iter"_a) .def( "setDumpFrequency", [](ContactSolver& m, UInt freq) { TAMAAS_DEPRECATE("setDumpFrequency()", "the dump_freq property"); m.setDumpFrequency(freq); }, "dump_freq"_a) .def_property("tolerance", &ContactSolver::getTolerance, &ContactSolver::setTolerance, "Solver tolerance") .def_property("max_iter", &ContactSolver::getMaxIterations, &ContactSolver::setMaxIterations, "Maximum number of iterations") .def_property("dump_freq", &ContactSolver::getDumpFrequency, &ContactSolver::setDumpFrequency, "Frequency of displaying solver info") .def_property_readonly("model", &ContactSolver::getModel) .def_property_readonly("surface", &ContactSolver::getSurface) .def_property_readonly("functional", &ContactSolver::getFunctional) .def("addFunctionalTerm", &ContactSolver::addFunctionalTerm, "Add a term to the contact functional to minimize") .def("solve", py::overload_cast>(&ContactSolver::solve), "target_force"_a, py::call_guard(), "Solve the contact for a mean traction/gap vector") .def("solve", py::overload_cast(&ContactSolver::solve), "target_normal_pressure"_a, py::call_guard(), "Solve the contact for a mean normal pressure/gap"); py::class_ pkr( mod, "PolonskyKeerRey", "Main solver class for normal elastic contact problems. Its functional " "can be customized to add an adhesion term, and its primal variable can " "be set to either the gap or the pressure."); // Need to export enum values before defining PKR constructor py::enum_(pkr, "type") .value("gap", PolonskyKeerRey::gap) .value("pressure", PolonskyKeerRey::pressure) .export_values(); pkr.def(py::init&, Real, PolonskyKeerRey::type, PolonskyKeerRey::type>(), "model"_a, "surface"_a, "tolerance"_a, "primal_type"_a = PolonskyKeerRey::type::pressure, "constraint_type"_a = PolonskyKeerRey::type::pressure, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def("computeError", &PolonskyKeerRey::computeError); py::class_( mod, "KatoSaturated", "Solver for pseudo-plasticity problems where the normal pressure is " "constrained above by a saturation pressure \"pmax\"") .def(py::init&, Real, Real>(), "model"_a, "surface"_a, "tolerance"_a, "pmax"_a, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def_property("pmax", &KatoSaturated::getPMax, &KatoSaturated::setPMax, "Saturation normal pressure"); py::class_ kato(mod, "Kato"); kato.def(py::init&, Real, Real>(), "model"_a, "surface"_a, "tolerance"_a, "mu"_a, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def("solve", &Kato::solve, "p0"_a, "proj_iter"_a = 50) .def("solveRelaxed", &Kato::solveRelaxed, "g0"_a) .def("solveRegularized", &Kato::solveRegularized, "p0"_a, "r"_a = 0.01) .def("computeCost", &Kato::computeCost, "use_tresca"_a = false); py::class_ bt(mod, "BeckTeboulle"); bt.def(py::init&, Real, Real>(), "model"_a, "surface"_a, "tolerance"_a, "mu"_a, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def("solve", &BeckTeboulle::solve, "p0"_a) .def("computeCost", &BeckTeboulle::computeCost); py::class_ cd( mod, "Condat", "Main solver for frictional contact problems. It has no restraint on the " "material properties or friction coefficient values, but solves an " "associated version of the Coulomb friction law, which differs from the " "traditional Coulomb friction in that the normal and tangential slip " "components are coupled."); cd.def(py::init&, Real, Real>(), "model"_a, "surface"_a, "tolerance"_a, "mu"_a, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def("solve", &Condat::solve, "p0"_a, "grad_step"_a = 0.9) .def("computeCost", &Condat::computeCost); py::class_ pkt(mod, "PolonskyKeerTan"); pkt.def(py::init&, Real, Real>(), "model"_a, "surface"_a, "tolerance"_a, "mu"_a, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def("solve", &PolonskyKeerTan::solve, "p0"_a) .def("solveTresca", &PolonskyKeerTan::solveTresca, "p0"_a) .def("computeCost", &PolonskyKeerTan::computeCost, "use_tresca"_a = false); py::class_( mod, "_tolerance_manager", "Manager object for the tolereance of nonlinear plasticity solvers. " "Decreases the solver tolerance by geometric progression.") .def(py::init(), "start_tol"_a, "end_tol"_a, "rate"_a); py::class_( mod, "EPSolver", "Mother class for nonlinear plasticity solvers") .def(py::init(), "residual"_a, py::keep_alive<1, 2>()) .def("solve", &EPSolver::solve) .def("getStrainIncrement", &EPSolver::getStrainIncrement, py::return_value_policy::reference_internal) .def("getResidual", &EPSolver::getResidual, py::return_value_policy::reference_internal) .def("updateState", &EPSolver::updateState) .def_property("tolerance", &EPSolver::getTolerance, &EPSolver::setTolerance) .def("setToleranceManager", &EPSolver::setToleranceManager) .def("beforeSolve", &EPSolver::beforeSolve); py::class_(mod, "_DFSANESolver") .def(py::init(), "residual"_a, py::keep_alive<1, 2>()) .def(py::init([](Residual& res, Model&) { TAMAAS_DEPRECATE("Solver(residual, model)", "Solver(residual)"); return std::make_unique(res); }), "residual"_a, "model"_a, py::keep_alive<1, 2>()); py::class_( mod, "EPICSolver", "Main solver class for elastic-plastic contact problems") .def(py::init(), "contact_solver"_a, "elasto_plastic_solver"_a, "tolerance"_a = 1e-10, "relaxation"_a = 0.3, py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) .def( "solve", [](EPICSolver& solver, Real pressure) { return solver.solve(std::vector{pressure}); }, "normal_pressure"_a, py::call_guard(), "Solves the EP contact with a relaxed fixed-point scheme. Adjust " "the relaxation parameter to help convergence.") .def( "acceleratedSolve", [](EPICSolver& solver, Real pressure) { return solver.acceleratedSolve(std::vector{pressure}); }, "normal_pressure"_a, py::call_guard(), "Solves the EP contact with an accelerated fixed-point scheme. May " - "not converge!"); + "not converge!") + .def_property("tolerance", &EPICSolver::getTolerance, + &EPICSolver::setTolerance) + .def_property("relaxation", &EPICSolver::getRelaxation, + &EPICSolver::setRelaxation) + .def_property_readonly("model", &EPICSolver::getModel); } } // namespace wrap } // namespace tamaas diff --git a/src/model/model.cpp b/src/model/model.cpp index 26de840..1941f94 100644 --- a/src/model/model.cpp +++ b/src/model/model.cpp @@ -1,169 +1,168 @@ /* * SPDX-License-Indentifier: AGPL-3.0-or-later * * Copyright (©) 2016-2023 EPFL (École Polytechnique Fédérale de Lausanne), * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * Copyright (©) 2020-2023 Lucas Frérot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * */ /* -------------------------------------------------------------------------- */ #include "model.hh" #include "be_engine.hh" #include "logger.hh" /* -------------------------------------------------------------------------- */ namespace tamaas { /* -------------------------------------------------------------------------- */ void Model::setElasticity(Real E_, Real nu_) { setYoungModulus(E_); setPoissonRatio(nu_); - updateOperators(); } /* -------------------------------------------------------------------------- */ void Model::applyElasticity(GridBase& stress, const GridBase& strain) const { operators.at("hooke")->apply(const_cast&>(strain), stress); } /* -------------------------------------------------------------------------- */ GridBase& Model::getTraction() { return this->field("traction"); } const GridBase& Model::getTraction() const { return this->field("traction"); } /* -------------------------------------------------------------------------- */ GridBase& Model::getDisplacement() { return this->field("displacement"); } const GridBase& Model::getDisplacement() const { return this->field("displacement"); } /* -------------------------------------------------------------------------- */ const std::vector& Model::getSystemSize() const { return system_size; } /* -------------------------------------------------------------------------- */ const std::vector& Model::getDiscretization() const { return discretization; } /* -------------------------------------------------------------------------- */ void Model::solveNeumann() { engine->registerNeumann(); engine->solveNeumann(getTraction(), getDisplacement()); } void Model::solveDirichlet() { engine->registerDirichlet(); engine->solveDirichlet(getDisplacement(), getTraction()); } /* -------------------------------------------------------------------------- */ IntegralOperator* Model::getIntegralOperator(const std::string& name) const { return operators.at(name).get(); } /* -------------------------------------------------------------------------- */ std::vector Model::getIntegralOperators() const { std::vector keys; keys.reserve(operators.size()); std::transform(operators.begin(), operators.end(), std::back_inserter(keys), [](auto&& pair) { return pair.first; }); return keys; } /* -------------------------------------------------------------------------- */ void Model::updateOperators() { for (auto& op : operators) op.second->updateFromModel(); } /* -------------------------------------------------------------------------- */ void Model::addDumper(std::shared_ptr dumper) { this->dumpers.push_back(std::move(dumper)); } void Model::dump() const { if (dumpers.empty()) Logger().get(LogLevel::warning) << "dumper list is empty\n"; for (const auto& dumper : dumpers) if (dumper) dumper->dump(*this); } /* -------------------------------------------------------------------------- */ std::vector Model::getBoundaryFields() const { std::vector boundary_fields; for (auto&& pair : this->fields_map()) { const auto boundary = boost::apply_visitor( [&](auto&& grid_ptr) { return this->isBoundaryField(*grid_ptr); }, pair.second); if (boundary) boundary_fields.push_back(pair.first); } return boundary_fields; } /* -------------------------------------------------------------------------- */ std::ostream& operator<<(std::ostream& o, const Model& _this) { o << "Model<" << _this.getType() << "> (E = " << _this.getYoungModulus() << ", nu = " << _this.getPoissonRatio() << ")\n"; auto out_collec = [&o](auto&& collec) { std::for_each(collec.begin(), collec.end() - 1, [&o](const auto& x) { o << x << ", "; }); o << collec.back(); }; // Printing domain size o << " - domain = ["; out_collec(_this.getSystemSize()); o << "]\n"; // Printing discretization o << " - discretization = ["; out_collec(_this.getDiscretization()); o << "]\n"; if (mpi::size() > 1) { o << " - global discretization = ["; out_collec(_this.getGlobalDiscretization()); o << "]\n"; } // Print fields o << " - registered fields = ["; out_collec(_this.fields()); o << "]\n"; o << " - registered operators = ["; out_collec(_this.getIntegralOperators()); o << "]"; if (not _this.dumpers.empty()) o << "\n - " << _this.dumpers.size() << " registered dumpers"; return o; } /* -------------------------------------------------------------------------- */ } // namespace tamaas diff --git a/src/solvers/epic.cpp b/src/solvers/epic.cpp index 995bf9a..4b41056 100644 --- a/src/solvers/epic.cpp +++ b/src/solvers/epic.cpp @@ -1,142 +1,144 @@ /* * SPDX-License-Indentifier: AGPL-3.0-or-later * * Copyright (©) 2016-2023 EPFL (École Polytechnique Fédérale de Lausanne), * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * Copyright (©) 2020-2023 Lucas Frérot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * */ /* -------------------------------------------------------------------------- */ #include "epic.hh" #include "logger.hh" /* -------------------------------------------------------------------------- */ namespace tamaas { /* -------------------------------------------------------------------------- */ EPICSolver::EPICSolver(ContactSolver& csolver, EPSolver& epsolver, Real tolerance, Real relaxation) : csolver(csolver), epsolver(epsolver), tolerance(tolerance), relaxation(relaxation) { auto& model = csolver.getModel(); surface.wrap(csolver.getSurface()); pressure.resize(model.getTraction().getNbPoints()); model_type_dispatch( [this](auto&& _) { constexpr auto type = std::decay_t::value; setViews(); }, model.getType()); } /* -------------------------------------------------------------------------- */ -void EPICSolver::solve(const std::vector& load) { +Real EPICSolver::solve(const std::vector& load) { UInt n = 0, nmax = 1000; Real error = 0.; const GridBase initial_surface(surface); Real normalizing_factor = std::sqrt(initial_surface.var()); GridBase previous_residual(*residual_disp); GridBase relaxation_direction(*residual_disp); previous_residual = 0; pressure = *pressure_inc; // set previous pressure to current model pressure do { fixedPoint(relaxation_direction, previous_residual, initial_surface, load); relaxation_direction -= previous_residual; relaxation_direction *= relaxation; error = computeError(*residual_disp, previous_residual, normalizing_factor); previous_residual += relaxation_direction; Logger().get(LogLevel::info) << "[EPIC] error = " << std::scientific << error << std::fixed << std::endl; } while (error > tolerance && n++ < nmax); // computing full pressure pressure += *pressure_inc; // setting the model pressure to full converged pressure *pressure_inc = pressure; // updating plastic state epsolver.updateState(); + return error; } /* -------------------------------------------------------------------------- */ -void EPICSolver::acceleratedSolve(const std::vector& load) { +Real EPICSolver::acceleratedSolve(const std::vector& load) { UInt n = 0, nmax = 1000; Real error = 0.; const GridBase initial_surface(surface); Real normalizing_factor = std::sqrt(initial_surface.var()); GridBase doubleg(*residual_disp), dg(*residual_disp), d2x(*residual_disp), x(*residual_disp), x_prev(*residual_disp); do { // First compute g(x) and g(g(x)) fixedPoint(dg, x, initial_surface, load); fixedPoint(doubleg, dg, initial_surface, load); // dg contains g(x): compute delta x d2x = dg; d2x -= x; // compute delta g(x) dg *= -1; dg += doubleg; // now we have delta g(x) and delta x, compute delta^2 x d2x *= -1; d2x += dg; // Apply Irons & Truck iteration auto f = dg.dot(d2x) / d2x.dot(d2x); dg *= -f; x = doubleg; x += dg; error = computeError(x, x_prev, normalizing_factor); x_prev = x; Logger().get(LogLevel::info) << "[EPIC] error = " << std::scientific << error << std::fixed << std::endl; } while (error > tolerance && n++ < nmax); // computing full pressure pressure += *pressure_inc; // setting the model pressure to full converged pressure *pressure_inc = pressure; // updating plastic state epsolver.updateState(); + return error; } /* -------------------------------------------------------------------------- */ void EPICSolver::fixedPoint(GridBase& result, const GridBase& x, const GridBase& initial_surface, std::vector load) { surface = initial_surface; surface -= x; csolver.solve(std::move(load)); *pressure_inc -= pressure; epsolver.solve(); result = *residual_disp; } /* -------------------------------------------------------------------------- */ Real EPICSolver::computeError(const GridBase& current, const GridBase& prev, Real factor) const { GridBase error(current); error -= prev; return std::sqrt(error.dot(error)) / factor; } /* -------------------------------------------------------------------------- */ } // namespace tamaas diff --git a/src/solvers/epic.hh b/src/solvers/epic.hh index 5e04a18..4b6f9c4 100644 --- a/src/solvers/epic.hh +++ b/src/solvers/epic.hh @@ -1,84 +1,88 @@ /* * SPDX-License-Indentifier: AGPL-3.0-or-later * * Copyright (©) 2016-2023 EPFL (École Polytechnique Fédérale de Lausanne), * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * Copyright (©) 2020-2023 Lucas Frérot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * */ /* -------------------------------------------------------------------------- */ #ifndef EPIC_HH #define EPIC_HH /* -------------------------------------------------------------------------- */ #include "contact_solver.hh" #include "ep_solver.hh" #include "model.hh" /* -------------------------------------------------------------------------- */ namespace tamaas { /* -------------------------------------------------------------------------- */ class EPICSolver { public: /// Constructor EPICSolver(ContactSolver& csolver, EPSolver& epsolver, Real tolerance = 1e-10, Real relaxation = 0.3); - void solve(const std::vector& load); - void acceleratedSolve(const std::vector& load); + Real solve(const std::vector& load); + Real acceleratedSolve(const std::vector& load); Real computeError(const GridBase& current, const GridBase& prev, Real factor) const; void fixedPoint(GridBase& result, const GridBase& x, const GridBase& initial_surface, std::vector load); template void setViews(); + TAMAAS_ACCESSOR(tolerance, Real, Tolerance); + TAMAAS_ACCESSOR(relaxation, Real, Relaxation); + const Model& getModel() const { return csolver.getModel(); } + protected: GridBase surface; ///< corrected surface GridBase pressure; ///< current pressure std::unique_ptr> residual_disp; ///< plastic residual disp std::unique_ptr> pressure_inc; ///< pressure increment ContactSolver& csolver; EPSolver& epsolver; Real tolerance, relaxation; }; /* -------------------------------------------------------------------------- */ /* Template impl. */ /* -------------------------------------------------------------------------- */ template void EPICSolver::setViews() { constexpr UInt dim = model_type_traits::dimension; constexpr UInt bdim = model_type_traits::boundary_dimension; constexpr UInt comp = model_type_traits::components; pressure_inc = std::unique_ptr>{new GridView( csolver.getModel().getTraction(), {}, comp - 1)}; residual_disp = std::unique_ptr>{new GridView( csolver.getModel().getDisplacement(), model_type_traits::indices, comp - 1)}; } /* -------------------------------------------------------------------------- */ } // namespace tamaas #endif // EPIC_HH