diff --git a/.gitattributes b/.gitattributes index 702e9768..b9076a03 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ cmake/* linguist-vendored +*.msh -whitespace diff --git a/.github/workflows/continuous.yml b/.github/workflows/continuous.yml index 3e9c1dff..85ee7192 100644 --- a/.github/workflows/continuous.yml +++ b/.github/workflows/continuous.yml @@ -1,70 +1,42 @@ -name: Build +name: CI -on: [push, pull_request] +on: [push, pull_request, workflow_dispatch] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: - Build: - name: ${{ matrix.name }} Python ${{ matrix.python-version }} (${{ matrix.config }}) + test: + name: ${{ matrix.os }} (${{ matrix.python }}) runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - python-version: [3.7, 3.8] - config: [Debug, Release] - include: - - os: ubuntu-latest - name: Linux - - os: windows-latest - name: Windows - - os: macOS-latest - name: MacOS - env: - if: runner.os == 'Windows' - USE_CHOLMOD: 0 + os: [ubuntu-latest, macos-latest, windows-latest] + python: ["3.10", 3.11, 3.12] steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v7 with: - fetch-depth: 10 + submodules: recursive - - name: Setup NMake (Windows) - if: runner.os == 'Windows' - uses: ilammy/msvc-dev-cmd@v1 - - - name: Stetup Conda - uses: s-weigand/setup-conda@v1 + - name: Set up Python + uses: actions/setup-python@v7 with: - update-conda: true - python-version: ${{ matrix.python-version }} - conda-channels: anaconda, conda-forge - - - name: Install Dependencies - run: | - conda install numpy libblas libcblas suitesparse plotly -y + python-version: ${{ matrix.python }} - - name: Envs (Windows) - if: runner.os == 'Windows' - run: | - echo "CMAKE_GENERATOR=NMake Makefiles" >> $GITHUB_ENV - echo "CXX=cl.exe" >> $GITHUB_ENV - echo "CC=cl.exe" >> $GITHUB_ENV - echo "USE_CHOLMOD=0" >> $GITHUB_ENV - conda init powershell + - name: Install package + run: python -m pip install ".[dev]" - - name: Build (Debug) - if: matrix.config == 'Debug' - run: | - python setup.py build --debug install + - name: Run ruff + run: python -m ruff check python tools tests - # windows has problem with memory and 2 passes... - - name: Build (Release) - if: matrix.config == 'Release' && runner.os != 'Windows' - run: | - python setup.py build install + - name: Run pytest + run: python -m pytest tests -q - # macos segfaults??? - - name: Tests - if: matrix.name == 'Linux' || matrix.name == 'MacOS' || (matrix.config == 'Debug' && runner.os == 'Windows') - run: | - python test/test_bending.py + - name: Check installed package + run: python tools/check_installed_package.py diff --git a/.github/workflows/release-packages.yml b/.github/workflows/release-packages.yml new file mode 100644 index 00000000..79a8b07c --- /dev/null +++ b/.github/workflows/release-packages.yml @@ -0,0 +1,93 @@ +name: Release Packages + +on: + workflow_dispatch: + +concurrency: + group: release-packages-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + source: + runs-on: ubuntu-latest + outputs: + filename: ${{ steps.archive.outputs.filename }} + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + - name: Prepare source archive + run: | + python -m pip install build numpy + python -m build --sdist + python tools/check_distribution.py "dist/*.tar.gz" + - name: Locate source archive + id: archive + shell: python + run: | + import os + from pathlib import Path + archives = list(Path("dist").glob("*.tar.gz")) + if len(archives) != 1: + raise RuntimeError(f"Expected one source archive, found {archives}") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"filename={archives[0].name}\n") + - uses: actions/upload-artifact@v7 + with: + name: polyfempy-source + path: dist/*.tar.gz + if-no-files-found: error + + wheels: + needs: source + runs-on: ${{ matrix.target.os }} + name: Wheel / ${{ matrix.target.name }} / CPython ${{ matrix.python }} + timeout-minutes: 360 + strategy: + fail-fast: false + matrix: + python: ["311"] + target: + - { name: windows-x64, os: windows-2022, arch: AMD64 } + - { name: linux-x64, os: ubuntu-latest, arch: x86_64 } + - { name: macos-intel, os: macos-15-intel, arch: x86_64 } + - { name: macos-arm64, os: macos-15, arch: arm64 } + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.13" + - uses: actions/download-artifact@v8 + with: + name: polyfempy-source + path: dist + - name: Use short Windows build paths + if: runner.os == 'Windows' + shell: pwsh + run: | + New-Item -ItemType Directory -Force C:/pf-tmp | Out-Null + "TEMP=C:/pf-tmp" >> $env:GITHUB_ENV + "TMP=C:/pf-tmp" >> $env:GITHUB_ENV + "CPM_SOURCE_CACHE=C:/pf-cpm" >> $env:GITHUB_ENV + - name: Build and test installed wheels + uses: pypa/cibuildwheel@v4.3.5 + with: + package-dir: dist/${{ needs.source.outputs.filename }} + config-file: cibuildwheel.toml + output-dir: wheelhouse + env: + CIBW_BUILD: cp${{ matrix.python }}-* + CIBW_ARCHS: ${{ matrix.target.arch }} + - name: Check wheel contents + run: python tools/check_distribution.py "wheelhouse/*.whl" + - uses: actions/upload-artifact@v7 + with: + name: wheels-${{ matrix.target.name }}-cp${{ matrix.python }} + path: wheelhouse/*.whl + if-no-files-found: error diff --git a/.gitignore b/.gitignore index a6cc73b0..95f0fbdd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,113 @@ +# Build directories build/ +build_debug/ build.nosync/ bin/ bin_rel/ -.vscode +lib/ +out/ dist/ -3rdparty* +/wheelhouse/ +/conda-out/ +CMakeFiles/ +CPM_modules/ +_deps/ +msvc_*/ +x64/ +*.dir/ +Release/ +Debug/ + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +*.egg +*.egg-info/ +.eggs/ +.pytest_cache/ +.ruff_cache/ +.venv/ +.coverage +htmlcov/ + +# Generated Python API artifacts +/python/polyfempy/generated_api/ +/python-from-jse/generated/ + +# Local architecture/discussion notes +/doc/ +/python/polyfempy/runtime/README.md + +# Local agent/build scratch +.codex +.codex_tmp/ +/Class-Generation-From-Json-main/ +/build_log.txt +/FORWARD_REVIEW.md + +# Simulation output directories. Meshes and reference data may be tracked elsewhere. +/results/ +/runs/ +/outputs/ +/sim.json +/impact_stats.json + +# Slurm batch logs written at the repo root. +/slurm_logs/ + +# IDE +.vscode/* +.idea/ *.sublime-workspace -copy_lib *.sublime-project *.code-workspace -__pycache__ -*.obj -*.pyc -*.vtu -*.pvd -*.egg-info -*.so -temp-plot.html -data* +.vs/ +*.swp +*.swo +*~ + +# Dependencies (repo-root dirs only — avoids ignoring names like data_loader.py) +/3rdparty/ +/data/ *libTracyClient.* + +# Compiled binaries (Windows) +*.dll +*.pyd +*.exe +*.pdb +*.ilk +*.exp +*.lib +*.a +# Note: nanobind.dll and TracyClient.dll in python/polyfempy/ are build artifacts + +# Cache .cache/ +.env +env/ +venv/ +ENV/ + +# Temporary files +*.log +*.tmp +*.bak +temp-plot.html +copy_lib +build_verbose.txt + +# OS metadata +.DS_Store +Thumbs.db + +# Local experiments +/experiment/ +*.pvd +*.obj +*.vtu + +# Former backend checkout; backend sources are now fetched by CPM. +/polyfem/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..fedacb2b --- /dev/null +++ b/.gitmodules @@ -0,0 +1,10 @@ +# Use the submodule commits recorded by the parent repository. +[submodule "examples"] + path = examples + url = https://github.com/polyfem/python_data.git +[submodule "polyfem-data"] + path = polyfem-data + url = https://github.com/polyfem/polyfem-data.git +[submodule "python-from-jse"] + path = python-from-jse + url = https://github.com/polyfem/python-from-jse.git diff --git a/API.md b/API.md new file mode 100644 index 00000000..ff14faf1 --- /dev/null +++ b/API.md @@ -0,0 +1,225 @@ +# Forward API + +Both `import polyfempy` and `import polyfem` expose this API. + +For a complete example, see the [README](README.md#run-a-simulation). +This guide shows API patterns. Supply your own mesh paths; `part.msh` below +must be a 2D mesh. Later snippets are alternatives, not one script to run in +sequence. They assume `import polyfempy as polyfem` and a fresh `model` with the named bodies. + +```python +import polyfempy as polyfem +from polyfempy import solve + +model = polyfem.model() +body = model.mesh(mesh="part.msh") +body.material(polyfem.neo_hookean(E=1000, nu=0.3)) +body.dirichlet(value=[0, 0]) + +model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) +config = model.config(rhs=[0, -1]) +result = solve(cfg=config) +``` + +Use vectors with two components for 2D and three for 3D. Choose values consistent with the model's units. + +## Run an existing configuration + +`solve(cfg=...)` accepts `model.config()`, a configuration dictionary, or a JSON +file path. For an existing JSON file: + +```python +from polyfempy import solve + +result = solve(cfg="simulation.json") +``` + +By default, relative mesh paths in that file are resolved from the JSON file's +directory. Relative paths in a model or dictionary use the working directory +unless you set `root_path`. + +## Geometry + +| Method | Purpose | +| --- | --- | +| `model.mesh(mesh=...)` | Add a mesh | +| `model.mesh_array(mesh=..., array=...)` | Repeat a mesh in an array | +| `model.mesh_sequence(mesh_sequence=..., fps=...)` | Add a sequence of meshes | + +Set `is_obstacle=True` for an obstacle. Geometry methods use the names and parameters generated from the spec. + +```python +obstacles = model.mesh_array( + mesh="edge.obj", + array=polyfem.array(offset=1, size=[21, 1]), + is_obstacle=True, +) +obstacles.dirichlet(value=[0, 0]) +``` + +Use these geometry methods for both deformable meshes and obstacles. + +## Materials and body settings + +```python +body.material(polyfem.neo_hookean(E=1000, nu=0.3, rho=1000)) +body.velocity(value=[0, 0]) +body.discr_order(order=1) +``` + +The returned body connects these settings to its mesh. The builder writes the volume ID when a body-level setting needs it. Creating a mesh alone preserves its existing volume tags. + +## All or part of a boundary + +Apply a condition directly to the body to select its entire outer boundary. + +```python +body.dirichlet(value=[0, 0]) +``` + +Alternatively, select part of the boundary before applying the condition: + +```python +# Select the left side of the mesh bounding box. +boundary = body.surface_axis(axis="-x", position=0.0, relative=True) +boundary.dirichlet(value=[0, 0]) +``` + +With `relative=True`, position 0 is the minimum and position 1 is the maximum +of the bounding box along that axis. `"-x"` selects the side at or below the +chosen x position. With `relative=False`, position uses mesh coordinates. +The selection parameters follow the PolyFEM spec. The API assigns the boundary ID and connects the condition to it. The same binding mechanism supports `neumann`, `normal_aligned_neumann` and `pressure`. + +A direct whole-boundary condition and a partial or file-based surface selection on the same body are rejected when they would overwrite each other's selection. Apply conditions to explicit selections when a body has multiple boundary regions. + +For an existing sideset file: + +```python +boundary = body.surface_from_file("surface_sidesets.txt") +boundary.dirichlet(value=[0, 0]) +``` + +If the file contains several groups, supply `tag=...` to identify the intended group. + +Use `surface_all()` when you need an explicit whole-boundary object. It also supports shared labels: + +```python +first_surface = first.surface_all() +second_surface = second.surface_all(same_as=first_surface) +first_surface.dirichlet(value=[0, 0]) +``` + +Here `first` and `second` are bodies in the same model. Both surfaces share +one boundary ID, so the condition applies to both. + +## Body loads + +For a uniform load across the model: + +```python +config = model.config(rhs=[0, -1]) +``` + +For two bodies named `first` and `second` in the same model: + +```python +first.rhs(value=[0, -1]) +second.rhs(value=[0, 0]) +config = model.config() +``` + +Choose one of these load scopes per model. Supplying both a global RHS and body-specific RHS raises an error. + +## Time, contact and output + +Add these settings to a model with geometry, materials, loads, and constraints +already configured. A transient elastic model also needs material density. +For a complete transient example, use the +[transient square](https://github.com/polyfem/python_data/blob/ffd670690bf20021e1c380d68b0afe845fb275fd/quickstart/transient_elasticity.py). + +```python +config = model.config( + time=polyfem.time(dt=0.01, tend=0.5, integrator="BDF"), + contact=polyfem.contact(enabled=True, dhat=0.001), + output=polyfem.output( + directory="results/example", + json="sim.json", + paraview=polyfem.output_paraview(file_name="sim.pvd"), + ), +) +result = solve(cfg=config) +``` + +A relative output directory is resolved from the working directory. `result.sol` +is the raw finite-element solution array; its rows are not necessarily mesh +vertices. Open the saved `.pvd` file in ParaView to view the result on the mesh. + +`result.sol` is a NumPy array. For a transient simulation, it contains the final +state; use the saved output files for earlier time steps. `result.meta` starts +as an empty dictionary. + +## Model settings + +Section methods save their settings for the next `model.config()` call: + +```python +model = polyfem.model() +body = model.mesh(mesh="part.msh") +body.dirichlet(value=[0, 0]) +model.materials(polyfem.neo_hookean(E=1000, nu=0.3)) +model.space(discr_order=2) +model.boundary_conditions(rhs=[0, -1]) +model.output(directory="results/example") +config = model.config() +``` + +This is a configuration example; supply a 2D mesh at `part.msh` before solving. +`model.materials(...)` accepts one material or a list. Use `body.material(...)` +for different materials on different bodies; the builder assigns their IDs. +Similarly, use `body.velocity(...)`, `body.solution(...)`, and +`body.acceleration(...)` for body-specific initial conditions. + +- `model.space(...)`, `model.initial_conditions(...)`, and `model.materials(...)` + save settings and return the model, like `model.time(...)` and `model.output(...)`. +- Calling `model.space()`, `model.initial_conditions()`, or `model.materials()` + without arguments still returns the current configuration for that section. +- `model.boundary_conditions(...)` now saves its keyword settings. It still + returns a dictionary for compatibility. With no arguments, it only reads the + current boundary configuration. +- Calling a section setter again replaces its explicit settings, not the values + attached to bodies. Supply all explicit fields you want to keep on that call. +- Explicit lists are combined with body and boundary lists. Other fields are + kept together when their names differ. Conflicting global and body-specific + values raise an error; for example, choose either `model.space(discr_order=2)` + or per-body `body.discr_order(...)`. Global and body-specific RHS also cannot + be mixed. + +The existing `model.config(space=polyfem.space(...), ...)` style remains available. +These arguments apply to that export only; they do not save settings on the model. +Use one configuration style per section. Passing a section to `model.config(...)` +after setting it on the model raises an error. For compatibility, the unchanged +dictionary returned by `model.boundary_conditions(...)` can still be passed as +`model.config(boundary_conditions=...)`; its boundary entries are not added twice. + +`model.geometry()` remains a read method. Add geometry with `model.mesh(...)` +and the other geometry methods. + +To show only errors in the terminal, set +`model.output(log=polyfem.output_log(level="error"))`. For a dictionary, use +`config["output"] = {"log": {"level": "error"}}`. Log levels apply to both +file meshes and array meshes. Add the log settings to the existing output +section if you also want to save results. + +## Input errors + +`solve` checks array meshes before calling the native solver. Vertex coordinates +must be finite, and cell indices must be integers starting at zero and smaller +than the number of vertices. JSON configuration errors include the file path +and line number. If the backend rejects an incomplete `LinearElasticity` or +`NeoHookean` material, the exception identifies the required parameter pairs. + +## Generation and maintenance + +Configuration factories and geometry entry points are generated from the pinned specs. Shared builder code manages scene objects and IDs. `generator-config/id_relationships.json` defines how bodies and selections connect to materials, loads and boundary conditions. + +PolySolve specs are cached by the revision selected by the pinned PolyFEM source. After updating the source or generator, regenerate and test using [BUILD.md](BUILD.md) and [TESTING.md](TESTING.md). diff --git a/BUILD.md b/BUILD.md new file mode 100644 index 00000000..cfed6e41 --- /dev/null +++ b/BUILD.md @@ -0,0 +1,54 @@ +# Build the Python bindings + +Clone this repository with its pinned submodules: + +```sh +git clone --recurse-submodules https://github.com/polyfem/polyfem-python.git +cd polyfem-python +``` + +Install with the Python interpreter you want to use: + +```sh +python -m pip install . +``` + +For development: + +```sh +python -m pip install -e ".[dev]" +``` + +Pip installs the build requirements declared in `pyproject.toml`. The build +backend runs CMake, generates the Python API, builds the native extension, and +installs it alongside the Python package. No separate generation or dependency +installation command is needed. A source build requires a C++17 compiler and +network access for dependencies that have not been cached. + +An existing conda environment works too; activate it before running pip. +Python 3.10 or later is required. On Windows, use an x64 Visual Studio developer +shell and a short checkout path. + +## Wheels and source archives + +```sh +python -m build +python tools/check_distribution.py "dist/*.tar.gz" "dist/*.whl" +``` + +The `build` frontend is included in the development extra. Source archives +contain the generator and generated API; CPM fetches the pinned PolyFEM sources. CMake installs +only the extension and the builder runtime into wheels; build-time schema tools +stay in the build directory. Nanobind supplies NumPy/Eigen conversion and the +platform-specific extension suffix. + +The three recipes load CPM and fetch nanobind and PolyFEM sources. PolyFEM pins +a commit from upstream `main` without local patches; nanobind uses a pinned release. +Build defaults are declared in `pyproject.toml`. +Reference data is used by tests and needs no CMake setup. The backend submodule +is no longer required. + +The native build uses `build//`. Override CMake options through pip, +for example `python -m pip install . -Ccmake.define.POLYFEM_WITH_TRIANGLE=ON`. +The default build uses two compiler workers. Override that with +`-Cbuild.tool-args=-j1` when memory is limited. diff --git a/CMakeLists.txt b/CMakeLists.txt index 509e07bc..99a8889a 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,61 +1,40 @@ -################################################################################ -# Check required CMake version -set(REQUIRED_CMAKE_VERSION "3.14.0") -cmake_minimum_required(VERSION ${REQUIRED_CMAKE_VERSION}) +cmake_minimum_required(VERSION 3.25) +project(polyfempy LANGUAGES CXX) -if(INPUT_POLYFEMPY_DATA_ROOT) - set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/${INPUT_POLYFEMPY_DATA_ROOT}/") -else() - set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/data/") -endif() -if(NOT EXISTS ${POLYFEMPY_DATA_ROOT}) - file(MAKE_DIRECTORY ${POLYFEMPY_DATA_ROOT}) -endif() - -project(polyfempy) -################################################################################ - -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") -list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/recipes/") - -# Color output -include(UseColors) - -# Prepend function -include(PrependCurrentPath) - -# Extra warnings -include(Warnings) - -# Use C++11/14 -include(CXXFeatures) - -# Sort projects inside the solution -set_property(GLOBAL PROPERTY USE_FOLDERS ON) - -# Generate position independent code by default +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_POSITION_INDEPENDENT_CODE ON) +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/recipes") -################################################################################ -# Polyfem library -################################################################################ - -# dependencies +find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED) +if(NOT SKBUILD_STATE STREQUAL "sdist") + include(nanobind) +endif() include(polyfem) -include(pybind11) -include(pybind11_json) - -#for testing purpose -include(polyfem_data) - -################################################################################ -# Subdirectories -################################################################################ -add_library(polyfempy MODULE src/binding.cpp src/raster.cpp) -target_link_libraries(polyfempy PRIVATE polyfem::polyfem pybind11::module pybind11::json) - -set_target_properties(polyfempy PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}" SUFFIX "${PYTHON_MODULE_EXTENSION}") - - - +if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/python-from-jse/tools/generate_with_overrides.py") + execute_process( + COMMAND "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/generate_polyfem_api.py" + --polyfem-source-dir "${polyfem_SOURCE_DIR}" + COMMAND_ERROR_IS_FATAL ANY) +elseif(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/python/polyfempy/generated_api/generated_api.py") + message(FATAL_ERROR "Initialize the generator submodule: git submodule update --init --recursive") +endif() +if(SKBUILD_STATE STREQUAL "sdist") + return() +endif() +nanobind_add_module(polyfempy NB_STATIC src/binding.cpp) +target_link_libraries(polyfempy PRIVATE polyfem::polyfem) +install(TARGETS polyfempy LIBRARY DESTINATION polyfempy COMPONENT python + RUNTIME DESTINATION polyfempy COMPONENT python) +install(FILES + python-from-jse/generator/__init__.py + python-from-jse/generator/model_builder.py + python-from-jse/generator/id_relationships.py + python-from-jse/generator/selection_refs.py + DESTINATION polyfempy/generated_api/generator COMPONENT python) +install(FILES "${polyfem_SOURCE_DIR}/LICENSE" DESTINATION polyfempy/licenses + RENAME PolyFEM.LICENSE COMPONENT python) +install(FILES "${nanobind_SOURCE_DIR}/LICENSE" DESTINATION polyfempy/licenses + RENAME nanobind.LICENSE COMPONENT python) diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..c4963c61 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,33 @@ +# Installation + +For this branch, install from a checkout with its submodules initialized: + +```sh +python -m pip install . +``` + +Pip obtains Python and build dependencies from `pyproject.toml` and runs the +build automatically. See [BUILD.md](BUILD.md) for cloning and compiler details. + +To install a wheel supplied by a maintainer: + +```sh +python -m pip install ./polyfempy----.whl +``` + +Choose a wheel matching your Python version, operating system, and CPU +architecture. Wheels include the generated API and native extension. No +compiler or generator is needed to install one. + +A conda environment can be used by activating it before running pip. This +repository does not maintain a separate native conda recipe. + +## Check the installation + +```sh +python -c "import polyfempy; from polyfempy.polyfempy import Solver; print(polyfempy.model())" +python tools/check_installed_package.py +``` + +The second command runs small file and NumPy-array simulations using the +installed package in an isolated process outside the checkout. diff --git a/README.md b/README.md index ef00ea4c..a36ec415 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,48 @@ -# polyfem-python -![Build](https://github.com/polyfem/polyfem-python/workflows/Build/badge.svg) +# PolyFEM for Python +`polyfempy` provides model builders and Python bindings to the PolyFEM solver. +`import polyfem` is an alias with the same public API. -[![Anaconda-Server Badge](https://anaconda.org/conda-forge/polyfempy/badges/latest_release_date.svg)](https://anaconda.org/conda-forge/polyfempy) -[![Anaconda-Server Badge](https://anaconda.org/conda-forge/polyfempy/badges/downloads.svg)](https://anaconda.org/conda-forge/polyfempy) -[![Anaconda-Server Badge](https://anaconda.org/conda-forge/polyfempy/badges/platforms.svg)](https://anaconda.org/conda-forge/polyfempy) -[![Anaconda-Server Badge](https://anaconda.org/conda-forge/polyfempy/badges/installer/conda.svg)](https://conda.anaconda.org/conda-forge) +## Install +From a checkout with its submodules initialized: +```sh +python -m pip install . +``` +Pip handles dependencies, API generation, and compilation. For development, +use `python -m pip install -e ".[dev]"`. See [BUILD.md](BUILD.md) for source-build +requirements and [INSTALL.md](INSTALL.md) for wheel installation. -The python bindings are in alpha. Expect a lot of API changes and possible bugs. Use at your own peril! - -
-I am making efforts to provide a simple python interface to Polyfem. - -For doing so I am maintaining a *conda* package which can be easily installed [https://anaconda.org/conda-forge/polyfempy](https://anaconda.org/conda-forge/polyfempy). +## Run a simulation -Note that the conda deployment is slow and this tutorial will follow the deployment version. +```python +import polyfempy as pf -If you hare in a hurry for the juicy latest feature you can clone the repository [Polyfem-python](https://github.com/polyfem/polyfem-python) and use `pip` to install: -``` -python setup.py install +model = pf.model() +body = model.mesh(mesh="part.msh") +body.material(pf.neo_hookean(E=1000, nu=.3)) +body.surface_axis(axis="-x", position=0, relative=True).dirichlet(value=[0, 0]) +model.solver(linear=pf.linear(solver="Eigen::SimplicialLDLT")) +result = pf.solve(model.config(rhs=[0, -1])) +print(result.sol) ``` -and -``` -python setup.py test -``` -for testing. -For python documentation [https://polyfem.github.io/python/](https://polyfem.github.io/python/). +Supply a 2D mesh file at `part.msh`, or pass another path to `model.mesh()`. +`result.sol` contains the raw finite-element solution; rows are not necessarily +mesh vertices. + +See [API.md](API.md) for materials, selections, loads, and time settings, and +[TESTING.md](TESTING.md) for validation commands. -For python jupyter notebook [https://polyfem.github.io/python_examples/](https://polyfem.github.io/python_examples/). +## Source layout -For full documentation see [https://polyfem.github.io/](https://polyfem.github.io/). +- `python/polyfempy/solve.py`: configuration preparation, solving, and results. +- `python/polyfempy/generated_api/`: generated model builders. +- `python/polyfem/`: automatic alias for `polyfempy`. +- `src/`: nanobind bindings to the native solver. +- `cmake/recipes/`: CPM, nanobind, and PolyFEM integration. +- `python-from-jse/`: pinned generator used during builds. +- `polyfem-data/`: reference data; CPM fetches a pinned PolyFEM commit and nanobind release. +- `tools/`: API generation and release checks. diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 00000000..c982f012 --- /dev/null +++ b/TESTING.md @@ -0,0 +1,45 @@ +# Testing + +Install development dependencies through the project: + +```sh +python -m pip install -e ".[dev]" +python -m pytest tests -q +python -m ruff check python tools tests +``` + +The normal installation generates the configuration API automatically. After +changing schemas or generator configuration, regenerate it by +reinstalling the project. + +Python tests cover configuration loading, model selection IDs, and solver +dispatch. Native file-mesh tests run when the extension is available. Reference examples require the pinned `examples` and +`polyfem-data` submodules. Both `polyfempy` and its `polyfem` alias are installed +and expose the same public API. + +To test an installed wheel outside the source directory: + +```sh +python tools/check_installed_package.py +``` + +This checks both public imports and runs file-mesh solves with constant and +Python-function loads, including material and boundary selections. + +For a selected existing native build and its reference data: + +```sh +python -m pytest tests/test_backend_smoke.py --backend-package-dir /path/to/site-packages -s +``` + +Full contact regressions are an explicit test run: + +```sh +python -m pytest tests/test_contact_regressions.py -m contact -q +``` + +CI has one workflow that installs the project and runs Python tests, lint, and +installed native checks on Ubuntu, macOS, and Windows. +The separate Release Packages workflow builds a source archive and platform +wheels with cibuildwheel. It checks archive contents and each installed wheel +without publishing them. diff --git a/cibuildwheel.toml b/cibuildwheel.toml new file mode 100644 index 00000000..d82a22c7 --- /dev/null +++ b/cibuildwheel.toml @@ -0,0 +1,14 @@ +[tool.cibuildwheel] +build = "cp311-*" +skip = "*-musllinux_*" +build-frontend = "build" +test-command = 'python "{package}/tools/check_installed_package.py"' + +[tool.cibuildwheel.linux] +manylinux-x86_64-image = "manylinux_2_28" + +[tool.cibuildwheel.macos] +environment = { MACOSX_DEPLOYMENT_TARGET = "11.0" } + +[tool.cibuildwheel.config-settings] +"build.tool-args" = ["-j1"] diff --git a/cmake/CXXFeatures.cmake b/cmake/CXXFeatures.cmake deleted file mode 100644 index 476cbd13..00000000 --- a/cmake/CXXFeatures.cmake +++ /dev/null @@ -1,85 +0,0 @@ -################################################################################ - -if(NOT (${CMAKE_VERSION} VERSION_LESS "3.8.0")) - # For CMake 3.8 and above, we can use meta features directly provided by CMake itself - set(CXX11_FEATURES cxx_std_11) - set(CXX14_FEATURES cxx_std_14) - set(CXX17_FEATURES cxx_std_17) - return() -endif() - -################################################################################ - -set(CXX11_FEATURES - cxx_auto_type - cxx_constexpr -) - -set(CXX14_FEATURES - cxx_generic_lambdas -) - -set(CXX17_FEATURES - cxx_generic_lambdas -) - -################################################################################ - -# https://cmake.org/cmake/help/v3.1/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html -# cxx_aggregate_default_initializers Aggregate default initializers, as defined in N3605. -# cxx_alias_templates Template aliases, as defined in N2258. -# cxx_alignas Alignment control alignas, as defined in N2341. -# cxx_alignof Alignment control alignof, as defined in N2341. -# cxx_attributes Generic attributes, as defined in N2761. -# cxx_attribute_deprecated deprecated]] attribute, as defined in N3760. -# cxx_auto_type Automatic type deduction, as defined in N1984. -# cxx_binary_literals Binary literals, as defined in N3472. -# cxx_constexpr Constant expressions, as defined in N2235. -# cxx_contextual_conversions Contextual conversions, as defined in N3323. -# cxx_decltype_incomplete_return_types Decltype on incomplete return types, as defined in N3276. -# cxx_decltype Decltype, as defined in N2343. -# cxx_decltype_auto decltype(auto) semantics, as defined in N3638. -# cxx_default_function_template_args Default template arguments for function templates, as defined in DR226 -# cxx_defaulted_functions Defaulted functions, as defined in N2346. -# cxx_defaulted_move_initializers Defaulted move initializers, as defined in N3053. -# cxx_delegating_constructors Delegating constructors, as defined in N1986. -# cxx_deleted_functions Deleted functions, as defined in N2346. -# cxx_digit_separators Digit separators, as defined in N3781. -# cxx_enum_forward_declarations Enum forward declarations, as defined in N2764. -# cxx_explicit_conversions Explicit conversion operators, as defined in N2437. -# cxx_extended_friend_declarations Extended friend declarations, as defined in N1791. -# cxx_extern_templates Extern templates, as defined in N1987. -# cxx_final Override control final keyword, as defined in N2928, N3206 and N3272. -# cxx_func_identifier Predefined __func__ identifier, as defined in N2340. -# cxx_generalized_initializers Initializer lists, as defined in N2672. -# cxx_generic_lambdas Generic lambdas, as defined in N3649. -# cxx_inheriting_constructors Inheriting constructors, as defined in N2540. -# cxx_inline_namespaces Inline namespaces, as defined in N2535. -# cxx_lambdas Lambda functions, as defined in N2927. -# cxx_lambda_init_captures Initialized lambda captures, as defined in N3648. -# cxx_local_type_template_args Local and unnamed types as template arguments, as defined in N2657. -# cxx_long_long_type long long type, as defined in N1811. -# cxx_noexcept Exception specifications, as defined in N3050. -# cxx_nonstatic_member_init Non-static data member initialization, as defined in N2756. -# cxx_nullptr Null pointer, as defined in N2431. -# cxx_override Override control override keyword, as defined in N2928, N3206 and N3272. -# cxx_range_for Range-based for, as defined in N2930. -# cxx_raw_string_literals Raw string literals, as defined in N2442. -# cxx_reference_qualified_functions Reference qualified functions, as defined in N2439. -# cxx_relaxed_constexpr Relaxed constexpr, as defined in N3652. -# cxx_return_type_deduction Return type deduction on normal functions, as defined in N3386. -# cxx_right_angle_brackets Right angle bracket parsing, as defined in N1757. -# cxx_rvalue_references R-value references, as defined in N2118. -# cxx_sizeof_member Size of non-static data members, as defined in N2253. -# cxx_static_assert Static assert, as defined in N1720. -# cxx_strong_enums Strongly typed enums, as defined in N2347. -# cxx_thread_local Thread-local variables, as defined in N2659. -# cxx_trailing_return_types Automatic function return type, as defined in N2541. -# cxx_unicode_literals Unicode string literals, as defined in N2442. -# cxx_uniform_initialization Uniform intialization, as defined in N2640. -# cxx_unrestricted_unions Unrestricted unions, as defined in N2544. -# cxx_user_literals User-defined literals, as defined in N2765. -# cxx_variable_templates Variable templates, as defined in N3651. -# cxx_variadic_macros Variadic macros, as defined in N1653. -# cxx_variadic_templates Variadic templates, as defined in N2242. -# cxx_template_template_parameters Template template parameters, as defined in ISO/IEC 14882:1998. diff --git a/cmake/PrependCurrentPath.cmake b/cmake/PrependCurrentPath.cmake deleted file mode 100644 index 334637ce..00000000 --- a/cmake/PrependCurrentPath.cmake +++ /dev/null @@ -1,8 +0,0 @@ -function(prepend_current_path SOURCE_FILES) - # Use recursive substitution to expand SOURCE_FILES - unset(MODIFIED) - foreach(SOURCE_FILE IN ITEMS ${${SOURCE_FILES}}) - list(APPEND MODIFIED "${CMAKE_CURRENT_SOURCE_DIR}/${SOURCE_FILE}") - endforeach() - set(${SOURCE_FILES} ${MODIFIED} PARENT_SCOPE) -endfunction() diff --git a/cmake/UseColors.cmake b/cmake/UseColors.cmake deleted file mode 100644 index 78017566..00000000 --- a/cmake/UseColors.cmake +++ /dev/null @@ -1,47 +0,0 @@ -################################################################################ -# When using Clang, there is nothing to do: colors are enabled by default -# When using GCC >= 4.9, colored diagnostics can be enabled natively -# When using an older version, one can use gccfilter (a perl script) -# -# I do not recommend using gccfilter as of now (May 2014), because it seems to -# be bugged. But if you still want to try, here is how to install it on Ubuntu: -# -# -# 1) Download the perl script and add it to you $PATH -# mkdir -p ~/.local/bin -# wget -P ~/.local/bin http://www.mixtion.org/gccfilter/gccfilter -# chmod +x ~/local/bin/gccfilter -# echo 'PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -# -# 2) Install the dependencies -# * Term::ANSIColor -# sudo cpan -# cpan> install Term::ANSIColor -# * The module "Getopt::Long" is included in "perl-base" -# * For Getopt::ArgvFile and Regexp::Common ... -# sudo apt-get install libgetopt-argvfile-perl libregexp-common-perl -# -################################################################################ - -if(CMAKE_COMPILER_IS_GNUCXX) - # If GCC >= 4.9, just activate the right option - # We enable colorized diagnostics always instead of using "auto" so that - # they're still colored when using Ninja. - if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) - message(STATUS "GCC >= 4.9 detected, enabling colored diagnostics") - add_definitions(-fdiagnostics-color=always) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color=always") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fdiagnostics-color=always") - return() - endif() - # If GCC < 4.9, maybe we can use gccfilter - find_program(GCC_FILTER gccfilter) - if(GCC_FILTER) - option(COLOR_GCC "Use GCCFilter to color compiler output messages" OFF) - set(COLOR_GCC_OPTIONS "-c -r -w" CACHE STRING "Arguments that are passed to gccfilter when output coloring is switchend on. Defaults to -c -r -w.") - if(COLOR_GCC) - set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${GCC_FILTER} ${COLOR_GCC_OPTIONS}") - message(STATUS "Using gccfilter for colored diagnostics") - endif() - endif() -endif() diff --git a/cmake/Warnings.cmake b/cmake/Warnings.cmake deleted file mode 100644 index d4b711db..00000000 --- a/cmake/Warnings.cmake +++ /dev/null @@ -1,158 +0,0 @@ -################################################################################ -# See comments and discussions here: -# http://stackoverflow.com/questions/5088460/flags-to-enable-thorough-and-verbose-g-warnings -################################################################################ - -if(TARGET warnings::all) - return() -endif() - -set(MY_FLAGS - -Wall - -Wextra - -pedantic - - # -Wconversion - #-Wunsafe-loop-optimizations # broken with C++11 loops - -Wunused - - -Wno-long-long - -Wpointer-arith - -Wformat=2 - -Wuninitialized - -Wcast-qual - -Wmissing-noreturn - -Wmissing-format-attribute - -Wredundant-decls - - -Werror=implicit - -Werror=nonnull - -Werror=init-self - -Werror=main - -Werror=missing-braces - -Werror=sequence-point - -Werror=return-type - -Werror=trigraphs - -Werror=array-bounds - -Werror=write-strings - -Werror=address - -Werror=int-to-pointer-cast - -Werror=pointer-to-int-cast - - -Wno-unused-variable - -Wunused-but-set-variable - -Wno-unused-parameter - - #-Weffc++ - -Wno-old-style-cast - # -Wno-sign-conversion - #-Wsign-conversion - - -Wshadow - - -Wstrict-null-sentinel - -Woverloaded-virtual - -Wsign-promo - -Wstack-protector - -Wstrict-aliasing - -Wstrict-aliasing=2 - -Wswitch-default - -Wswitch-enum - -Wswitch-unreachable - - -Wcast-align - -Wdisabled-optimization - #-Winline # produces warning on default implicit destructor - -Winvalid-pch - # -Wmissing-include-dirs - -Wpacked - -Wno-padded - -Wstrict-overflow - -Wstrict-overflow=2 - - -Wctor-dtor-privacy - -Wlogical-op - -Wnoexcept - -Woverloaded-virtual - # -Wundef - - -Wnon-virtual-dtor - -Wdelete-non-virtual-dtor - -Werror=non-virtual-dtor - -Werror=delete-non-virtual-dtor - - -Wno-sign-compare - - ########### - # GCC 6.1 # - ########### - - -Wnull-dereference - -fdelete-null-pointer-checks - -Wduplicated-cond - -Wmisleading-indentation - - #-Weverything - - ########################### - # Enabled by -Weverything # - ########################### - - #-Wdocumentation - #-Wdocumentation-unknown-command - #-Wfloat-equal - #-Wcovered-switch-default - - #-Wglobal-constructors - #-Wexit-time-destructors - #-Wmissing-variable-declarations - #-Wextra-semi - #-Wweak-vtables - #-Wno-source-uses-openmp - #-Wdeprecated - #-Wnewline-eof - #-Wmissing-prototypes - - #-Wno-c++98-compat - #-Wno-c++98-compat-pedantic - - ########################### - # Need to check if those are still valid today - ########################### - - #-Wimplicit-atomic-properties - #-Wmissing-declarations - #-Wmissing-prototypes - #-Wstrict-selector-match - #-Wundeclared-selector - #-Wunreachable-code - - # Not a warning, but enable link-time-optimization - # TODO: Check out modern CMake version of setting this flag - # https://cmake.org/cmake/help/latest/module/CheckIPOSupported.html - #-flto - - # Gives meaningful stack traces - -fno-omit-frame-pointer - -fno-optimize-sibling-calls -) - -# Flags above don't make sense for MSVC -if(MSVC) - set(MY_FLAGS) -endif() - -include(CheckCXXCompilerFlag) - -add_library(warnings_all INTERFACE) -add_library(warnings::all ALIAS warnings_all) - -foreach(FLAG IN ITEMS ${MY_FLAGS}) - string(REPLACE "=" "-" FLAG_VAR "${FLAG}") - if(NOT DEFINED IS_SUPPORTED_${FLAG_VAR}) - check_cxx_compiler_flag("${FLAG}" IS_SUPPORTED_${FLAG_VAR}) - endif() - if(IS_SUPPORTED_${FLAG_VAR}) - target_compile_options(warnings_all INTERFACE ${FLAG}) - endif() -endforeach() diff --git a/cmake/recipes/CPM.cmake b/cmake/recipes/CPM.cmake new file mode 100644 index 00000000..8ae7eab7 --- /dev/null +++ b/cmake/recipes/CPM.cmake @@ -0,0 +1,8 @@ +include_guard(GLOBAL) +set(CPM_DOWNLOAD_VERSION 0.42.0) +set(CPM_DOWNLOAD_LOCATION "${CMAKE_BINARY_DIR}/cmake/CPM_${CPM_DOWNLOAD_VERSION}.cmake") +file(DOWNLOAD + "https://github.com/cpm-cmake/CPM.cmake/releases/download/v${CPM_DOWNLOAD_VERSION}/CPM.cmake" + "${CPM_DOWNLOAD_LOCATION}" + EXPECTED_HASH SHA256=2020b4fc42dba44817983e06342e682ecfc3d2f484a581f11cc5731fbe4dce8a) +include("${CPM_DOWNLOAD_LOCATION}") diff --git a/cmake/recipes/nanobind.cmake b/cmake/recipes/nanobind.cmake new file mode 100644 index 00000000..9b9be440 --- /dev/null +++ b/cmake/recipes/nanobind.cmake @@ -0,0 +1,3 @@ +include_guard(GLOBAL) +include(CPM) +CPMAddPackage("gh:wjakob/nanobind@3.1.0") diff --git a/cmake/recipes/polyfem.cmake b/cmake/recipes/polyfem.cmake index a1471835..a4a8c126 100644 --- a/cmake/recipes/polyfem.cmake +++ b/cmake/recipes/polyfem.cmake @@ -1,19 +1,8 @@ -# Polyfem -# License: MIT - -if(TARGET polyfem::polyfem) - return() -endif() - -message(STATUS "Third-party: creating target 'polyfem::polyfem'") - -include(FetchContent) -FetchContent_Declare( - polyfem - GIT_REPOSITORY https://github.com/polyfem/polyfem.git - GIT_TAG 12ac634833f91a3946cff26db01972fdb2ec3214 - GIT_SHALLOW FALSE -) -FetchContent_MakeAvailable(polyfem) - - +include_guard(GLOBAL) +include(CPM) +string(COMPARE EQUAL "${SKBUILD_STATE}" "sdist" download_only) +CPMAddPackage( + NAME polyfem + GITHUB_REPOSITORY polyfem/polyfem + GIT_TAG 76205bfd1247570abbb9e552347b8b44cc62b0b2 + DOWNLOAD_ONLY "${download_only}") diff --git a/cmake/recipes/polyfem_data.cmake b/cmake/recipes/polyfem_data.cmake deleted file mode 100644 index 95aa1849..00000000 --- a/cmake/recipes/polyfem_data.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# data -# License: MIT - -message(STATUS "Third-party: fetching 'polyfem data'") - -include(FetchContent) -FetchContent_Declare( - polyfem_data - GIT_REPOSITORY https://github.com/polyfem/polyfem-data - GIT_TAG 29a46df1fd90c237a82c219f346a956e72bd17d3 - GIT_SHALLOW FALSE - SOURCE_DIR ${POLYFEMPY_DATA_ROOT} -) -FetchContent_GetProperties(polyfem_data) -if(NOT polyfem_data_POPULATED) - FetchContent_Populate(polyfem_data) - # SET(POLYFEM_DATA_DIR ${polyfem_data_SOURCE_DIR}) -endif() \ No newline at end of file diff --git a/cmake/recipes/pybind11.cmake b/cmake/recipes/pybind11.cmake deleted file mode 100644 index a170372c..00000000 --- a/cmake/recipes/pybind11.cmake +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright 2020 Adobe. All rights reserved. -# This file is licensed to you under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. You may obtain a copy -# of the License at http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software distributed under -# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS -# OF ANY KIND, either express or implied. See the License for the specific language -# governing permissions and limitations under the License. -# -if(TARGET pybind11::pybind11) - return() -endif() - -message(STATUS "Third-party: creating target 'pybind11::pybind11'") - -include(FetchContent) -FetchContent_Declare( - pybind11 - GIT_REPOSITORY https://github.com/pybind/pybind11.git - GIT_TAG v2.9.2 - GIT_SHALLOW FALSE -) - -if (POLICY CMP0094) # https://cmake.org/cmake/help/latest/policy/CMP0094.html - cmake_policy(SET CMP0094 NEW) # FindPython should return the first matching Python -endif () - -# needed on GitHub Actions CI: actions/setup-python does not touch registry/frameworks on Windows/macOS -# this mirrors PythonInterp behavior which did not consult registry/frameworks first -if (NOT DEFINED Python_FIND_REGISTRY) - set(Python_FIND_REGISTRY "LAST") -endif () -if (NOT DEFINED Python_FIND_FRAMEWORK) - set(Python_FIND_FRAMEWORK "LAST") -endif () - -# Pybind11 still uses the deprecated FindPythonInterp. So let's call CMake's -# new FindPython module and set PYTHON_EXECUTABLE for Pybind11 to pick up. -# This works well with conda environments. -find_package(Python REQUIRED COMPONENTS Interpreter Development) -set(PYTHON_EXECUTABLE ${Python_EXECUTABLE}) - -FetchContent_MakeAvailable(pybind11) \ No newline at end of file diff --git a/cmake/recipes/pybind11_json.cmake b/cmake/recipes/pybind11_json.cmake deleted file mode 100644 index 54bddd69..00000000 --- a/cmake/recipes/pybind11_json.cmake +++ /dev/null @@ -1,22 +0,0 @@ -# pybind11_json -# License: MIT - -if(TARGET pybind11::json) - return() -endif() - -message(STATUS "Third-party: creating target 'pybind11::json'") - -set(BUILD_TESTS OFF CACHE BOOL "" FORCE) -set(DOWNLOAD_GTEST OFF CACHE BOOL "" FORCE) - -include(FetchContent) -FetchContent_Declare( - pybind11_json - GIT_REPOSITORY https://github.com/pybind/pybind11_json.git - GIT_TAG 0.2.11 - GIT_SHALLOW FALSE -) -FetchContent_MakeAvailable(pybind11_json) - -add_library(pybind11::json ALIAS pybind11_json) diff --git a/examples b/examples new file mode 160000 index 00000000..ffd67069 --- /dev/null +++ b/examples @@ -0,0 +1 @@ +Subproject commit ffd670690bf20021e1c380d68b0afe845fb275fd diff --git a/generator-config/README.md b/generator-config/README.md new file mode 100644 index 00000000..b3a7c32f --- /dev/null +++ b/generator-config/README.md @@ -0,0 +1,65 @@ +# PolyFEM generator configuration + +The API generator reads two files in this directory: + +- `api_aliases.json` defines public factory names and aliases. +- `id_relationships.json` connects geometry IDs to materials, boundary conditions and contact settings. + +The generic generator lives in the `python-from-jse/` submodule. + +## Generated global configuration helpers + +The generic generator accepts keyword arguments directly on polymorphic +factories, for example `polyfem.time(dt=0.01, tend=0.5, integrator="BDF")`. +It selects a schema branch using its required fields; explicit variant objects +remain supported for compatibility. + +Root configuration sections also generate methods on the model builder: + +```python +import polyfempy as polyfem + +model = polyfem.model() +model.time(dt=0.01, tend=0.5, integrator="BDF") +model.units(length="cm", mass="g", time="s") +model.output(directory="runs/example") +config = model.config() +``` + +These setters return the model and replace the same section when called again. +Passing that section again to `model.config(...)` raises an error instead of +silently overriding it. Shared builder methods also support setting `space`, +`materials`, and `initial_conditions`, while preserving their no-argument reads. +`boundary_conditions(...)` saves keyword settings but keeps its dictionary return +value for existing callers. Passing that unchanged dictionary to `model.config(...)` +is supported without duplicating boundary entries. + +Explicit section settings are combined with body settings when exporting the +model. Lists are appended; conflicting non-list fields raise an error. Repeating +a setter replaces only its explicit settings. ID assignment remains in the +shared builder and relationship rules, so users can work with body and selection +objects. See [Model settings](../API.md#model-settings) for examples and merge rules. + +Maintain this behavior in `python-from-jse/generator/JsonToTreeClass.py` and +`python-from-jse/generator/model_builder.py`, not the generated output. From the +repository root, regenerate with: + +```powershell +python -m pip install -e . +``` + +## Geometry and ID binding + +Geometry factories also generate model methods such as `model.mesh(...)`, +`model.mesh_array(...)` and `model.mesh_sequence(...)`. Use +`is_obstacle=True` to mark an obstacle. + +Shared builder logic registers geometry and binds IDs. Body-level consumers +such as `body.material(...)` use volume relationships. Direct boundary +conditions such as `body.dirichlet(...)` use the configured surface +relationships and select the whole boundary. Partial selections retain their +own handles. + +See [API.md](../API.md) for user-facing examples. New geometry types use the +same generated dispatch. New relationships must be described in +`id_relationships.json` and tested against the backend configuration. diff --git a/generator-config/api_aliases.json b/generator-config/api_aliases.json new file mode 100644 index 00000000..bde254ed --- /dev/null +++ b/generator-config/api_aliases.json @@ -0,0 +1,294 @@ +{ + "api_aliases": [ + { + "main_api_name": "material_models", + "main_class_path": "Root.Materials.MaterialSum.Models", + "api_generated_name": "models", + "kind": "custom_api_name", + "aliases": [ + { + "alias_name": "models", + "alias_class_path": "Root.Materials.MaterialSum.Models", + "hide": true, + "reason": "The generated name is too generic; material_models explains that this is the model list used by MaterialSum." + } + ] + }, + { + "main_api_name": "neo_hookean", + "main_class_path": "Root.Materials.NeoHookean", + "aliases": [ + { + "alias_name": "models_neo_hookean", + "alias_class_path": "Root.Materials.MaterialSum.Models.NeoHookean", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call neo_hookean(...)." + } + ] + }, + { + "main_api_name": "isochoric_neo_hookean", + "main_class_path": "Root.Materials.IsochoricNeoHookean", + "aliases": [ + { + "alias_name": "models_isochoric_neo_hookean", + "alias_class_path": "Root.Materials.MaterialSum.Models.IsochoricNeoHookean", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call isochoric_neo_hookean(...)." + } + ] + }, + { + "main_api_name": "mooney_rivlin", + "main_class_path": "Root.Materials.MooneyRivlin", + "aliases": [ + { + "alias_name": "models_mooney_rivlin", + "alias_class_path": "Root.Materials.MaterialSum.Models.MooneyRivlin", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call mooney_rivlin(...)." + } + ] + }, + { + "main_api_name": "mooney_rivlin3_param", + "main_class_path": "Root.Materials.MooneyRivlin3Param", + "aliases": [ + { + "alias_name": "models_mooney_rivlin3_param", + "alias_class_path": "Root.Materials.MaterialSum.Models.MooneyRivlin3Param", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call mooney_rivlin3_param(...)." + } + ] + }, + { + "main_api_name": "mooney_rivlin3_param_symbolic", + "main_class_path": "Root.Materials.MooneyRivlin3ParamSymbolic", + "aliases": [ + { + "alias_name": "models_mooney_rivlin3_param_symbolic", + "alias_class_path": "Root.Materials.MaterialSum.Models.MooneyRivlin3ParamSymbolic", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call mooney_rivlin3_param_symbolic(...)." + } + ] + }, + { + "main_api_name": "unconstrained_ogden", + "main_class_path": "Root.Materials.UnconstrainedOgden", + "aliases": [ + { + "alias_name": "models_unconstrained_ogden", + "alias_class_path": "Root.Materials.MaterialSum.Models.UnconstrainedOgden", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call unconstrained_ogden(...)." + } + ] + }, + { + "main_api_name": "incompressible_ogden", + "main_class_path": "Root.Materials.IncompressibleOgden", + "aliases": [ + { + "alias_name": "models_incompressible_ogden", + "alias_class_path": "Root.Materials.MaterialSum.Models.IncompressibleOgden", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call incompressible_ogden(...)." + } + ] + }, + { + "main_api_name": "linear_elasticity", + "main_class_path": "Root.Materials.LinearElasticity", + "aliases": [ + { + "alias_name": "models_linear_elasticity", + "alias_class_path": "Root.Materials.MaterialSum.Models.LinearElasticity", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call linear_elasticity(...)." + } + ] + }, + { + "main_api_name": "hooke_linear_elasticity", + "main_class_path": "Root.Materials.HookeLinearElasticity", + "aliases": [ + { + "alias_name": "models_hooke_linear_elasticity", + "alias_class_path": "Root.Materials.MaterialSum.Models.HookeLinearElasticity", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call hooke_linear_elasticity(...)." + } + ] + }, + { + "main_api_name": "saint_venant", + "main_class_path": "Root.Materials.SaintVenant", + "aliases": [ + { + "alias_name": "models_saint_venant", + "alias_class_path": "Root.Materials.MaterialSum.Models.SaintVenant", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call saint_venant(...)." + } + ] + }, + { + "main_api_name": "stokes", + "main_class_path": "Root.Materials.Stokes", + "aliases": [ + { + "alias_name": "models_stokes", + "alias_class_path": "Root.Materials.MaterialSum.Models.Stokes", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call stokes(...)." + } + ] + }, + { + "main_api_name": "navier_stokes", + "main_class_path": "Root.Materials.NavierStokes", + "aliases": [ + { + "alias_name": "models_navier_stokes", + "alias_class_path": "Root.Materials.MaterialSum.Models.NavierStokes", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call navier_stokes(...)." + } + ] + }, + { + "main_api_name": "operator_splitting", + "main_class_path": "Root.Materials.OperatorSplitting", + "aliases": [ + { + "alias_name": "models_operator_splitting", + "alias_class_path": "Root.Materials.MaterialSum.Models.OperatorSplitting", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call operator_splitting(...)." + } + ] + }, + { + "main_api_name": "electrostatics", + "main_class_path": "Root.Materials.Electrostatics", + "aliases": [ + { + "alias_name": "models_electrostatics", + "alias_class_path": "Root.Materials.MaterialSum.Models.Electrostatics", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call electrostatics(...)." + } + ] + }, + { + "main_api_name": "incompressible_linear_elasticity", + "main_class_path": "Root.Materials.IncompressibleLinearElasticity", + "aliases": [ + { + "alias_name": "models_incompressible_linear_elasticity", + "alias_class_path": "Root.Materials.MaterialSum.Models.IncompressibleLinearElasticity", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call incompressible_linear_elasticity(...)." + } + ] + }, + { + "main_api_name": "material_sum", + "main_class_path": "Root.Materials.MaterialSum", + "aliases": [ + { + "alias_name": "models_material_sum", + "alias_class_path": "Root.Materials.MaterialSum.Models.MaterialSum", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call material_sum(...)." + } + ] + }, + { + "main_api_name": "laplacian", + "main_class_path": "Root.Materials.Laplacian", + "aliases": [ + { + "alias_name": "models_laplacian", + "alias_class_path": "Root.Materials.MaterialSum.Models.Laplacian", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call laplacian(...)." + } + ] + }, + { + "main_api_name": "helmholtz", + "main_class_path": "Root.Materials.Helmholtz", + "aliases": [ + { + "alias_name": "models_helmholtz", + "alias_class_path": "Root.Materials.MaterialSum.Models.Helmholtz", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call helmholtz(...)." + } + ] + }, + { + "main_api_name": "bilaplacian", + "main_class_path": "Root.Materials.Bilaplacian", + "aliases": [ + { + "alias_name": "models_bilaplacian", + "alias_class_path": "Root.Materials.MaterialSum.Models.Bilaplacian", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call bilaplacian(...)." + } + ] + }, + { + "main_api_name": "amips", + "main_class_path": "Root.Materials.AMIPS", + "aliases": [ + { + "alias_name": "models_amips", + "alias_class_path": "Root.Materials.MaterialSum.Models.AMIPS", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call amips(...)." + } + ] + }, + { + "main_api_name": "fixed_corotational", + "main_class_path": "Root.Materials.FixedCorotational", + "aliases": [ + { + "alias_name": "models_fixed_corotational", + "alias_class_path": "Root.Materials.MaterialSum.Models.FixedCorotational", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call fixed_corotational(...)." + } + ] + }, + { + "main_api_name": "volume_penalty", + "main_class_path": "Root.Materials.VolumePenalty", + "aliases": [ + { + "alias_name": "models_volume_penalty", + "alias_class_path": "Root.Materials.MaterialSum.Models.VolumePenalty", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call volume_penalty(...)." + } + ] + }, + { + "main_api_name": "hgo_fiber", + "main_class_path": "Root.Materials.HGOFiber", + "aliases": [ + { + "alias_name": "models_hgo_fiber", + "alias_class_path": "Root.Materials.MaterialSum.Models.HGOFiber", + "hide": true, + "reason": "Nested MaterialSum.Models helper is an internal placement of the same material concept; users should call hgo_fiber(...)." + } + ] + } + ] +} diff --git a/generator-config/id_relationships.json b/generator-config/id_relationships.json new file mode 100644 index 00000000..1974f2a7 --- /dev/null +++ b/generator-config/id_relationships.json @@ -0,0 +1,128 @@ +[ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "boundary_conditions.rhs[*].id", + "builder_api": "body.rhs", + "status": "required" + }, + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "materials[*].id", + "builder_api": "body.material", + "status": "required" + }, + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "initial_conditions.velocity[*].id", + "builder_api": "body.velocity", + "status": "required" + }, + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "initial_conditions.solution[*].id", + "builder_api": "body.solution", + "status": "required" + }, + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "initial_conditions.acceleration[*].id", + "builder_api": "body.acceleration", + "status": "required" + }, + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "space.discr_order[*].id", + "builder_api": "body.discr_order", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.dirichlet_boundary[*].id", + "builder_api": "surface.dirichlet", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.neumann_boundary[*].id", + "builder_api": "surface.neumann", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.normal_aligned_neumann_boundary[*].id", + "builder_api": "surface.normal_aligned_neumann", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.pressure_boundary[*].id", + "builder_api": "surface.pressure", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.pressure_cavity[*].id", + "builder_api": "surface.pressure_cavity", + "status": "required" + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.obstacle_displacements[*].id", + "builder_api": "surface.obstacle_displacement", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.dirichlet_boundary[*].id", + "builder_api": "point.dirichlet", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.neumann_boundary[*].id", + "builder_api": "point.neumann", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.normal_aligned_neumann_boundary[*].id", + "builder_api": "point.normal_aligned_neumann", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.pressure_boundary[*].id", + "builder_api": "point.pressure", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.pressure_cavity[*].id", + "builder_api": "point.pressure_cavity", + "status": "required" + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.obstacle_displacements[*].id", + "builder_api": "point.obstacle_displacement", + "status": "required" + } +] diff --git a/polyfem-data b/polyfem-data new file mode 160000 index 00000000..b65a2cb0 --- /dev/null +++ b/polyfem-data @@ -0,0 +1 @@ +Subproject commit b65a2cb0c06ea39a06bf15ab8e673b9a72887f4d diff --git a/polyfempy/Problem.py b/polyfempy/Problem.py deleted file mode 100644 index 8124458d..00000000 --- a/polyfempy/Problem.py +++ /dev/null @@ -1,151 +0,0 @@ -import json -import types - - -class Problem: - """Generic problem problem, scalar or tensor depending on the pde. Warning, this problem needs to be used with the `set_pde` function in settings""" - - def __init__(self, rhs=None, exact=None, is_time_dependent=False): - self.rhs = rhs - self.is_time_dependent = is_time_dependent - self.exact = exact - self.dirichlet_boundary = [] - self.neumann_boundary = [] - self.pressure_boundary = [] - - self.initial_solution = None - self.initial_velocity = None - self.initial_acceleration = None - - # self.dirichlet_boundary_lambda = [] - # self.neumann_boundary_lambda = [] - # self.pressure_boundary_lambda = [] - - def set_dirichlet_value(self, id, value, is_dirichlet_dim=None, linear_ramp_to=None): - """set the Dirichlet value value for the sideset id. Note the value must be a scalar, vector in 2D, or 3D depending on the problem. is_dirichlet_dim is a vector of boolean specifying which dimentions are fixed, only for vector-based problems.""" - self.add_dirichlet_value(id, value, is_dirichlet_dim, linear_ramp_to) - - def set_neumann_value(self, id, value, linear_ramp_to=None): - """set the Neumann value value for the sideset id. Note the value must be a scalar, vector in 2D, or 3D depending on the problem""" - self.add_neumann_value(id, value, linear_ramp_to) - - def set_pressure_value(self, id, value, linear_ramp_to=None): - """set the Pressure value value for the sideset id. Note the value must be a scalar""" - self.add_pressure_value(id, value, linear_ramp_to) - - def add_dirichlet_value(self, id, value, is_dirichlet_dim=None, linear_ramp_to=None): - """set the Dirichlet value value for the sideset id. Note the value must be a scalar, vector in 2D, or 3D depending on the problem. is_dirichlet_dim is a vector of boolean specifying which dimentions are fixed, only for vector-based problems.""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - if is_dirichlet_dim is not None: - assert(len(is_dirichlet_dim) == 3 or len(is_dirichlet_dim) == 2) - assert(len(value) == len(is_dirichlet_dim)) - tmp["dimension"] = is_dirichlet_dim - - if linear_ramp_to is not None: - tmp["linear_ramp"] = {"to": linear_ramp_to} - - if isinstance(value, types.LambdaType) or isinstance(value, types.FunctionType): - pass - # self.dirichlet_boundary_lambda.append(tmp) - else: - self.dirichlet_boundary.append(tmp) - - def add_neumann_value(self, id, value, linear_ramp_to=None): - """set the Neumann value value for the sideset id. Note the value must be a scalar, vector in 2D, or 3D depending on the problem""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - - if linear_ramp_to is not None: - tmp["linear_ramp"] = {"to": linear_ramp_to} - - if isinstance(value, types.LambdaType) or isinstance(value, types.FunctionType): - pass - # self.neumann_boundary_lambda.append(tmp) - else: - self.neumann_boundary.append(tmp) - - def add_pressure_value(self, id, value, linear_ramp_to=None): - """set the Pressure value value for the sideset id. Note the value must be a scalar""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - - if linear_ramp_to is not None: - tmp["linear_ramp"] = {"to": linear_ramp_to} - - if isinstance(value, types.LambdaType) or isinstance(value, types.FunctionType): - pass - # self.pressure_boundary_lambda.append(tmp) - else: - self.pressure_boundary.append(tmp) - - def set_initial_solution(self, value): - """set the initial solution for time dependent problems""" - self.initial_solution = value - - def set_initial_velocity(self, value): - """set the initial velocity for time dependent problems""" - self.initial_velocity = value - - def set_initial_acceleration(self, value): - """set the initial acceleration for time dependent problems""" - self.initial_acceleration = value - - def set_velocity(self, id, value, is_dim_fixed=None, linear_ramp_to=None): - """set the velocity value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_dirichlet_value(id, value, is_dim_fixed, linear_ramp_to) - - def set_displacement(self, id, value, is_dim_fixed=None, linear_ramp_to=None): - """set the displacement value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_dirichlet_value(id, value, is_dim_fixed, linear_ramp_to) - - def set_force(self, id, value, linear_ramp_to=None): - """set the force value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_neumann_value(id, value, linear_ramp_to) - - def set_x_symmetric(self, id): - """x coorinate is fixed, y is allowed to move (Neumann)""" - self.add_dirichlet_value(id, [0, 0], [True, False]) - - def set_y_symmetric(self, id): - """y coorinate is fixed, x is allowed to move (Neumann)""" - self.add_dirichlet_value(id, [0, 0], [False, True]) - - def set_xy_symmetric(self, id): - """xy coorinates are fixed, z is allowed to move (Neumann)""" - self.add_dirichlet_value(id, [0, 0, 0], [True, True, False]) - - def set_xz_symmetric(self, id): - """xz coorinates are fixed, y is allowed to move (Neumann)""" - self.add_dirichlet_value(id, [0, 0, 0], [True, False, True]) - - def set_yz_symmetric(self, id): - """yz coorinates are fixed, x is allowed to move (Neumann)""" - self.add_dirichlet_value(id, [0, 0, 0], [False, True, True]) - - def params(self): - """return a dictionary representation of the problem""" - tmp = dict( - (key, value) - for (key, value) in self.__dict__.items()) - - if self.initial_solution is None: - tmp.pop('initial_solution', None) - - if self.initial_velocity is None: - tmp.pop('initial_velocity', None) - - if self.initial_acceleration is None: - tmp.pop('initial_acceleration', None) - - # tmp.pop('dirichlet_boundary_lambda', None) - # tmp.pop('neumann_boundary_lambda', None) - # tmp.pop('pressure_boundary_lambda', None) - - return tmp diff --git a/polyfempy/Problems.py b/polyfempy/Problems.py deleted file mode 100644 index 33c0006e..00000000 --- a/polyfempy/Problems.py +++ /dev/null @@ -1,170 +0,0 @@ - - -################################################# -############Scalar############################### -class Franke: - """Franke problem with exact solution https://polyfem.github.io/documentation/#franke""" - - def name(self): - return "Franke" - - def params(self): - return {} - - -class GenericScalar: - """Generic scalar problem https://polyfem.github.io/documentation/#genericscalar""" - - def __init__(self): - self.rhs = 0 - self.exact = None - self.dirichlet_boundary = [] - self.neumann_boundary = [] - - def add_dirichlet_value(self, id, value): - """add the Dirichlet value value for the sideset id""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - self.dirichlet_boundary.append(tmp) - - def add_neumann_value(self, id, value): - """add the Neumann value value for the sideset id""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - self.neumann_boundary.append(tmp) - - def name(self): - return "GenericScalar" - - def params(self): - return self.__dict__ - - -################################################# -############Elasticity########################### -class Gravity: - """time dependent gravity problem https://polyfem.github.io/documentation/#gravity""" - - def __init__(self, force=0.1): - self.force = force - - def name(self): - return "Gravity" - - def params(self): - return self.__dict__ - - -class Torsion: - """3D torsion problem, specify which sideset to fix (fixed_boundary) and which one turns turning_boundary https://polyfem.github.io/documentation/#torsionelastic""" - - def __init__(self, axis_coordiante=None, axis_coordinate=2, n_turns=0.5, fixed_boundary=5, turning_boundary=6): - if axis_coordiante: - self.axis_coordiante = axis_coordiante - else: - self.axis_coordiante = axis_coordinate - self.n_turns = n_turns - self.fixed_boundary = fixed_boundary - self.turning_boundary = turning_boundary - - def name(self): - return "TorsionElastic" - - def params(self): - return self.__dict__ - - -class GenericTensor: - """Generic tensor problem https://polyfem.github.io/documentation/#generictensor""" - - def __init__(self): - self.rhs = [0, 0, 0] - self.exact = None - self.dirichlet_boundary = [] - self.neumann_boundary = [] - - def set_velocity(self, id, value, is_dim_fixed=None): - """set the velocity value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_dirichlet_value(id, value, is_dim_fixed) - - def set_displacement(self, id, value, is_dim_fixed=None): - """set the displacement value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_dirichlet_value(id, value, is_dim_fixed) - - def set_force(self, id, value): - """set the force value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - self.add_neumann_value(id, value) - - def add_dirichlet_value(self, id, value, is_dirichlet_dim=None): - """add the Dirichlet value value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem. is_dirichlet_dim is a vector of boolean specifying which dimentions are fixed.""" - assert(len(value) == 3 or len(value) == 2) - tmp = {} - tmp["id"] = id - tmp["value"] = value - if is_dirichlet_dim is not None: - assert(len(is_dirichlet_dim) == 3 or len(is_dirichlet_dim) == 2) - tmp["dimension"] = is_dirichlet_dim - - self.dirichlet_boundary.append(tmp) - - def add_neumann_value(self, id, value): - """add the Neumann value value for the sideset id. Note the value must be a vector in 2D or 3D depending on the problem""" - - tmp = {} - tmp["id"] = id - tmp["value"] = value - self.neumann_boundary.append(tmp) - - def name(self): - return "GenericTensor" - - def params(self): - return self.__dict__ - - -################################################# -############Stokes############################### -class Flow: - """Inflow/outflow problem for fluids. You can specify the sideset for the moving fluxes, the axial direction of the flow, and the list of obstacle sidesets. https://polyfem.github.io/documentation/#flow""" - - def __init__(self, inflow=1, outflow=3, inflow_amout=0.25, outflow_amout=0.25, direction=0, obstacle=[7]): - self.inflow = inflow - self.outflow = outflow - self.inflow_amout = inflow_amout - self.outflow_amout = outflow_amout - self.direction = direction - self.obstacle = obstacle - - def name(self): - return "Flow" - - def params(self): - return self.__dict__ - - -class DrivenCavity: - """Classical driven cavity problem in fluid simulation""" - - def name(self): - return "DrivenCavity" - - def params(self): - return {} - - -class FlowWithObstacle: - """FLuid Obstacle problem""" - - def __init__(self, U=1.5, time_dependent=True): - self.U = U - self.time_dependent = time_dependent - - def name(self): - return "FlowWithObstacle" - - def params(self): - return self.__dict__ diff --git a/polyfempy/Selection.py b/polyfempy/Selection.py deleted file mode 100644 index bb5f910c..00000000 --- a/polyfempy/Selection.py +++ /dev/null @@ -1,53 +0,0 @@ -import json - - -class Selection: - """Object used to select sideset and bodies""" - - def __init__(self): - self.body_ids = [] - self.boundary_sidesets = [] - - def select_body_with_sphere(self, id, center, radius): - """Select a body using a sphere""" - self.body_ids.append({"id": id, "center": center, "radius": radius}) - - def select_body_with_box(self, id, box_min, box_max): - """Select a body using an axis-aligned box""" - self.body_ids.append({"id": id, "box": [box_min, box_max]}) - - def select_body_with_axis_plane(self, id, axis, position): - """Select a body using an axis-aligned plane at position position, axis 1, 2, 3 is x, y, and z respectively. Use negative to flip axis (e.g., -1 is negative x axis)""" - self.body_ids.append({"id": id, "position": position, "axis": axis}) - - def select_body_with_plane(self, id, normal, offset): - """Select a body using a generic plane with normal normal, the point on the plane is defined by normal*offset""" - self.body_ids.append({"id": id, "normal": normal, "offset": offset}) - - def select_sideset_with_sphere(self, id, center, radius): - """Select a boundary sideset using a sphere""" - self.boundary_sidesets.append( - {"id": id, "center": center, "radius": radius}) - - def select_sideset_with_box(self, id, box_min, box_max): - """Select a boundary sideset using an axis-aligned box""" - self.boundary_sidesets.append({"id": id, "box": [box_min, box_max]}) - - def select_sideset_with_axis_plane(self, id, axis, position): - """Select a boundary sideset using an axis-aligned plane at position position, axis 1, 2, 3 is x, y, and z respectively. Use negative to flip axis (e.g., -1 is negative x axis)""" - self.boundary_sidesets.append( - {"id": id, "position": position, "axis": axis}) - - def select_sideset_with_plane(self, id, normal, offset): - """Select a boundary sideset using a generic plane with normal normal, the point on the plane is defined by normal*offset""" - self.boundary_sidesets.append( - {"id": id, "normal": normal, "offset": offset}) - - def __str__(self): - """stringygied json description of this class, used to run the solver""" - - tmp = dict( - (key, value) - for (key, value) in self.__dict__.items()) - - return json.dumps(tmp, sort_keys=True, indent=4) diff --git a/polyfempy/Settings.py b/polyfempy/Settings.py deleted file mode 100644 index 745a30a1..00000000 --- a/polyfempy/Settings.py +++ /dev/null @@ -1,156 +0,0 @@ -import json -from logging import raiseExceptions -import polyfempy -import sys - -class Settings: - """Class that encodes the settings of the solver, it models the input json file""" - - def __init__(self, discr_order=1, pressure_discr_order=1, pde=polyfempy.PDEs.Laplacian, contact_problem=False, BDF_order=1, nl_solver_rhs_steps=-1, tend=1, time_steps=10, dhat=0.03): - self.discr_order = discr_order - self.pressure_discr_order = pressure_discr_order - self._is_scalar = True - self.dhat = dhat - - self.BDF_order = 1 - - self.scalar_formulation = "Laplacian" - self.tensor_formulation = "LinearElasticity" - self.has_collision = contact_problem - self.BDF_order = BDF_order - - self.nl_solver_rhs_steps = nl_solver_rhs_steps - - self._problem = "Franke" - self._python_problem = None - - self.tend = tend - self.time_steps = time_steps - - self.quadrature_order = 4 - - self.params = {} - self.body_params = [] - self.export = {} - self.advanced_options = {} - - self.problem_params = {} - - self.pde = pde - - self.selection = None - raise RuntimeError("Old Version Deprecated. Use version <0.5.2 on conda for the old interface") - - def get_problem(self): - """Get the problem""" - return self._problem - - def set_problem(self, problem): - """Sets the problem, use any of the problems in Problems or the Problem""" - if isinstance(problem, str): - self._problem = problem - return - - if isinstance(problem, polyfempy.Problem): - self._problem = "GenericScalar" if self._is_scalar else "GenericTensor" - if problem.rhs is None: - problem.rhs = 0 if self._is_scalar else [0, 0, 0] - else: - self._problem = problem.name() - self.problem_params = problem.params() - self._python_problem = problem - - def get_pde(self, pde): - """Get the PDE""" - if self._is_scalar: - return self.scalar_formulation - else: - self.tensor_formulation - - def set_pde(self, pde): - """Sets the PDE to solve, use any of the polyfempy.PDEs""" - - if pde == "NonLinearElasticity": - pde = "NeoHookean" - - self._is_scalar = not polyfempy.polyfempy.is_tensor(pde) - - if self._is_scalar: - self.scalar_formulation = pde - else: - self.tensor_formulation = pde - - def set_material_params(self, name, value): - """set the material parameters, for instance set_material_params("E", 200) sets the Young's modulus E to 200. See https://polyfem.github.io/documentation/#formulations for full list""" - - self.params[name] = value - - def set_body_params(self, id, **kwargs): - """set the material parameters, for a body id. For instance set_body_params(1, E=200, nu=0.3, rho=1000) sets the Young's modulus E to 200, nu=0.3 and density=100 body body 1. See https://polyfem.github.io/documentation/#formulations for full list""" - - tmp = {} - tmp["id"] = id - for key, value in kwargs.items(): - tmp[key] = value - - self.body_params.append(tmp) - - def set_vtu_export_path(self, path, boundary_only=False): - """Sets the path to export a vtu file with the results, use boundary_only to export only one layer of the mesh in 3d""" - - self.export["vis_mesh"] = path - self.export["vis_boundary_only"] = boundary_only - - def set_wireframe_export_path(self, path): - """Sets the path to export a wireframe of the mesh""" - - self.export["wire_mesh"] = path - - def set_isolines_export_path(self, path): - """Sets the path to export the isolines of the solution""" - - self.export["iso_mesh"] = path - - def set_solution_export_path(self, path): - """Sets the path to save the solution""" - - self.export["solution"] = path - - def set_advanced_option(self, key, value): - """Used to set any advanced option not present in this class, for instance set_advanced_option("use_spline",True), see https://polyfem.github.io/documentation/ for full list""" - - self.advanced_options[key] = value - - def __str__(self): - """stringygied json description of this class, used to run the solver""" - - tmp = dict( - (key, value) - for (key, value) in self.__dict__.items()) - tmp.pop('advanced_options', None) - tmp.pop('_problem', None) - tmp.pop('_Settings_is_scalar', None) - tmp.pop('_python_problem', None) - tmp.pop('selection', None) - - if self.selection is not None: - tmp["body_ids"] = self.selection.body_ids - tmp["boundary_sidesets"] = self.selection.boundary_sidesets - - if len(self.body_params) <= 0: - tmp.pop("body_params", None) - - tmp["problem"] = self.problem - tmp.update(self.advanced_options) - - json_str = json.dumps(tmp, sort_keys=True, indent=4) - - return json_str - - def serialize(self): - """stringyfied json description of this class, used to run the solver""" - - return str(self) - - problem = property(get_problem, set_problem) - pde = property(get_pde, set_pde) diff --git a/polyfempy/__init__.py b/polyfempy/__init__.py deleted file mode 100644 index 0c575718..00000000 --- a/polyfempy/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from .polyfempy import Solver -from .polyfempy import PDEs -from .polyfempy import ScalarFormulations -from .polyfempy import TensorFormulations -from .polyfempy import solve_febio -from .polyfempy import solve - -from .Settings import Settings -from .Selection import Selection - -from .Problem import Problem - -from .Problems import Franke -from .Problems import GenericScalar -from .Problems import Gravity -from .Problems import Torsion -from .Problems import GenericTensor -from .Problems import Flow -from .Problems import DrivenCavity -from .Problems import FlowWithObstacle diff --git a/polyfempy/autoclass.py b/polyfempy/autoclass.py deleted file mode 100644 index f22e927a..00000000 --- a/polyfempy/autoclass.py +++ /dev/null @@ -1,122 +0,0 @@ -from dataclasses import make_dataclass -import typing -import dataclasses -import json -import polyfempy - -def getter(contain, key): - if key not in contain: - return [] - return contain[key] - -def parse_tree(rules, mark_required = False): - tree = dict() - for r in rules: - pt = r['pointer'] - pt = pt.replace('/*','') - - path = pt.split('/') - if pt == '/': - path = [''] - - subtree = tree - for k in path: - if k not in subtree: - subtree[k] = dict() - subtree = subtree[k] - req, opt = (getter(r,'required'), getter(r, 'optional')) - for k in req: - if k not in subtree: - subtree[k] = {} - if mark_required: - subtree[k]['R'] = '0' - for k in opt: - if k not in subtree: - subtree[k] = {} - return tree - - -def snake_to_camel(name): - if name == '': - return 'PolyFEM' - return ''.join([n.capitalize() for n in name.split('_')]) - -def print_script(): - # deprecated to the make_dataclasses interface - key = '' - node = tree[key] - indent = 4 - repre = 'from dataclasses import dataclass\nimport typing\n' - - def rec(key, val, h): - global repre - if key == 'lambda': - return - if key !='': - repre += (' '*h*indent + f'{key} : typing.Any = None\n') - - if len(val) == 0: - return - classname = snake_to_camel(key) - repre += (' '*h*indent + f'@dataclass\n') - repre += (' '*h*indent + f'class {classname}:\n') - for k,v in (val.items()): - rec(k,v, h+1) - - rec(key, node, 0) - - repre += """ - if __name__ == '__main__': - print(PolyFEM(geometry='mesh.obj')) - """ - - with open('test.py', 'w') as fp: - fp.write(repre) - - - -def recursive_data_class_builder(node, name): - fields = [] - namespace = dict() - for k, v in node.items(): - if k == 'lambda': - continue - fields.append((k,typing.Any,None)) - if isinstance(v, dict) and len(v) != 0: - name0 = snake_to_camel(k) - namespace[name0] = recursive_data_class_builder(v, name0) - return make_dataclass(name, fields=fields, namespace = namespace) - - -def prune_none_entry(node): - if not isinstance(node, dict): - if isinstance(node, list): - for v in node: - prune_none_entry(v) - else: - for k, v in list(node.items()): - prune_none_entry(v) - if v is None or (hasattr(v, '__len__') and len(v) == 0): - node.pop(k) - -def generate_input_dict(config): - output = dataclasses.asdict(config) - prune_none_entry(output) - return output - - -with open('data/default_rules.json')as fp: - rules = json.load(fp) - -tree = parse_tree(rules) -pf = recursive_data_class_builder(tree[''], '') - -geometry = pf.Geometry(mesh='import.obj') -matnu = pf.Materials(id = 0, nu=0.1) -matE = pf.Materials(id = 1,E=10) - -config = pf(geometry = geometry, materials = [matnu, matE]) - -def solve(**kwargs): - d = generate_input_dict(config) - polyfempy.solve(**d) diff --git a/polyfempy/command.py b/polyfempy/command.py deleted file mode 100644 index fed18e1c..00000000 --- a/polyfempy/command.py +++ /dev/null @@ -1,85 +0,0 @@ -from .polyfempy import polyfem_command -import argparse - - -def polyfem(): - parser = argparse.ArgumentParser() - - parser.add_argument("-j", "--json", type=str, - default="", help="Simulation json file") - parser.add_argument("-m", "--mesh", type=str, default="", help="Mesh path") - parser.add_argument("-b", "--febio", type=str, - default="", help="FEBio file path") - - parser.add_argument("--n_refs", type=int, default=0, - help="Number of refinements") - parser.add_argument("--not_norm", type=bool, default=True, - help="Skips mesh normalization") - - parser.add_argument("--problem", type=str, - default="", help="Problem name") - parser.add_argument("--sform", type=str, - default="", help="Scalar formulation") - parser.add_argument("--tform", type=str, - default="", help="Tensor formulation") - - parser.add_argument("--solver", type=str, default="", help="Solver to use") - - parser.add_argument("-q", "-p", type=int, default=1, - help="Discretization order") - parser.add_argument("--p_ref", type=bool, - default=False, help="Use p refimenet") - # parser.add_argument("--spline", use_splines, "Use spline for quad/hex meshes"); - parser.add_argument("--count_flipped_els", type=bool, - default=False, help="Count flippsed elements") - parser.add_argument("--lin_geom", type=bool, default=False, - help="Force use linear geometric mapping") - # parser.add_argument("--isoparametric", isoparametric, "Force use isoparametric basis"); - # parser.add_argument("--serendipity", serendipity, "Use of serendipity elements, only for Q2"); - # parser.add_argument("--stop_after_build_basis", stop_after_build_basis, "Stop after build bases"); - parser.add_argument("--vis_mesh_res", type=float, - default=-1.0, help="Vis mesh resolution") - parser.add_argument("--project_to_psd", type=bool, - default=False, help="Project local matrices to psd") - parser.add_argument("--n_incr_load", type=int, default=- - 1, help="Number of incremeltal load") - - parser.add_argument("--output", type=str, default="", - help="Output json file") - parser.add_argument("--vtu", type=str, default="", help="Vtu output file") - - parser.add_argument("--quiet", type=bool, default=False, - help="Disable cout for logging") - parser.add_argument("--log_file", type=str, - default="", help="Log to a file") - parser.add_argument("--log_level", type=int, default=1, - help="Log level 1 debug 2 info") - - parser.add_argument("--export_material_params", type=bool, - default=False, help="Export material parameters") - - args = parser.parse_args() - - polyfem_command( - args.json, - args.febio, - args.mesh, - args.problem, - args.sform, - args.tform, - args.n_refs, - args.not_norm, - args.solver, - args.q, - args.p_ref, - args.count_flipped_els, - args.lin_geom, - args.vis_mesh_res, - args.project_to_psd, - args.n_incr_load, - args.output, - args.vtu, - args.log_level, - args.log_file, - args.quiet, - args.export_material_params) diff --git a/polyfempy/test/__init__.py b/polyfempy/test/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/polyfempy/test/test_pythonic.py b/polyfempy/test/test_pythonic.py deleted file mode 100644 index a4bb0964..00000000 --- a/polyfempy/test/test_pythonic.py +++ /dev/null @@ -1,55 +0,0 @@ -import unittest - -import numpy as np -import polyfempy as pf - - -class PythonicTest(unittest.TestCase): - def test_run(self): - n_pts = 3 - - extend = np.linspace(0, 1, n_pts) - x, y = np.meshgrid(extend, extend, sparse=False, indexing='xy') - pts = np.column_stack((x.ravel(), y.ravel())) - - # Create connectivity - faces = np.ndarray([(n_pts-1)**2, 4], dtype=np.int32) - - index = 0 - for i in range(n_pts-1): - for j in range(n_pts-1): - faces[index, :] = np.array([ - j + i * n_pts, - j+1 + i * n_pts, - j+1 + (i+1) * n_pts, - j + (i+1) * n_pts - ]) - index = index + 1 - - def sideset(p): - if p[0] <= 0.001: - return 4 - return 1 - - solver = pf.solve( - vertices=pts, - cells=faces, - sidesets_func=sideset, - boundary_conditions=dict( - dirichlet_boundary=[dict(id=4, value=[0, 0])], - rhs=[0, 0.1], - ), - geometry="", - materials=[dict(type="NeoHookean", id=0, E=2100, nu=0.3)], - space=dict(discr_order=1), - ) - - log = solver.get_log() - - # Get the solution - pts, tris, el_id, bid, fun = solver.get_sampled_solution() - assert(abs(np.linalg.norm(fun) - 0.03) < 1e-3) - - -if __name__ == '__main__': - unittest.main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..5d5c3031 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,79 @@ +[build-system] +requires = ["scikit-build-core>=0.12"] +build-backend = "scikit_build_core.build" + +[project] +name = "polyfempy" +version = "0.8" +description = "PolyFEM Python bindings" +readme = "README.md" +license = "MIT" +license-files = ["LICENSE", "python-from-jse/LICENSE"] +authors = [ + { name = "Teseo Schneider" }, +] +requires-python = ">=3.10" +dependencies = [ + "numpy>=1.23", +] +classifiers = [ + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.0", + "build>=1", + "scikit-build-core>=0.12", + "ruff>=0.17.5,<0.18", +] +test = [ + "pytest>=7.0", +] +[project.urls] +Homepage = "https://polyfem.github.io/" +Source = "https://github.com/polyfem/polyfem-python" +Issues = "https://github.com/polyfem/polyfem-python/issues" + +[tool.scikit-build] +minimum-version = "build-system.requires" +cmake.version = ">=3.25" +build-dir = "build/{wheel_tag}" +build.targets = ["polyfempy"] +build.tool-args = ["-j2"] +install.components = ["python"] +wheel.packages = ["python/polyfempy", "python/polyfem"] +sdist.cmake = true +sdist.include = ["python/polyfempy/generated_api/*.py", "python/polyfempy/generated_api/*_manifest.json"] +sdist.exclude = [ + ".github/**", "tests/**", "doc/**", "polyfem/**", "polyfem-data/**", "data*/**", + "examples/**", "python-from-jse/tests/**", "python-from-jse/generated/**", + "python-from-jse/examples/**", + "**/__pycache__/**", "**/*.pyc", + "sim.pvd", "step*.obj", "step*.vtu", "test.obj", "test*.vtu", "*.code-workspace", +] + +[tool.scikit-build.cmake.define] +CMAKE_POLICY_VERSION_MINIMUM = "3.5" +POLYFEM_WITH_TESTS = false +POLYFEM_WITH_MISO = false +POLYFEM_PORTABLE_BUILD = true +POLYSOLVE_WITH_SPECTRA = false +POLYSOLVE_WITH_AMGCL = false +POLYSOLVE_WITH_UMFPACK = false +POLYSOLVE_WITH_MPI = false +POLYSOLVE_WITH_HYPRE = false + +[[tool.scikit-build.overrides]] +if.platform-system = "darwin" +inherit.cmake.define = "append" +cmake.define.POLYSOLVE_WITH_MKL = false +cmake.define.POLYSOLVE_WITH_ACCELERATE = true + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-m 'not contact'" +markers = ["contact: full native contact regression sweep (opt in with -m contact)"] diff --git a/python-from-jse b/python-from-jse new file mode 160000 index 00000000..9d0a9b98 --- /dev/null +++ b/python-from-jse @@ -0,0 +1 @@ +Subproject commit 9d0a9b98ed0ce428242e5d2ebc57813cc9703ae7 diff --git a/python/polyfem/__init__.py b/python/polyfem/__init__.py new file mode 100644 index 00000000..4c88daa0 --- /dev/null +++ b/python/polyfem/__init__.py @@ -0,0 +1,4 @@ +"""Alias for the polyfempy public API.""" + +from polyfempy import * # noqa: F403 +from polyfempy import __all__ as __all__ diff --git a/python/polyfempy/__init__.py b/python/polyfempy/__init__.py new file mode 100644 index 00000000..4a52abeb --- /dev/null +++ b/python/polyfempy/__init__.py @@ -0,0 +1,7 @@ +"""PolyFEM model builders and forward simulations.""" + +from .generated_api.generated_api import * # noqa: F403 +from .generated_api.generated_api import __all__ as _generated_exports +from .solve import Result, solve + +__all__ = [*_generated_exports, "Result", "solve"] diff --git a/python/polyfempy/solve.py b/python/polyfempy/solve.py new file mode 100644 index 00000000..dddab96a --- /dev/null +++ b/python/polyfempy/solve.py @@ -0,0 +1,40 @@ +"""Forward solves from model configurations, dictionaries, or JSON files.""" + +import json +from pathlib import Path + +import numpy as np + +__all__ = ["Result", "solve"] + + +class Result: + """Raw finite-element solution coefficients and optional metadata.""" + + def __init__(self, sol, *, meta=None): + self.sol = np.ascontiguousarray(sol) + self.meta = {} if meta is None else dict(meta) + + +def _config(cfg): + if isinstance(cfg, (str, Path)): + path = Path(cfg).resolve() + cfg = json.loads(path.read_text(encoding="utf-8")) + if isinstance(cfg, dict): + cfg = dict(cfg, root_path=cfg.get("root_path", str(path))) + elif callable(getattr(cfg, "as_dict", None)): + cfg = cfg.as_dict() + if not isinstance(cfg, dict): + raise TypeError("cfg must be a model configuration, dictionary, or JSON path") + return cfg + + +def solve(cfg): + """Solve a model configuration, dictionary, or JSON file using PolyFEM.""" + settings = _config(cfg) + from .polyfempy import Solver + + solver = Solver() + solver.set_settings(json.dumps(settings), strict_validation=True) + solver.load_mesh_from_settings() + return Result(solver.solve()) diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 00000000..3b058a5b --- /dev/null +++ b/ruff.toml @@ -0,0 +1,13 @@ +# Ruff configuration for PolyFEM Python API + +line-length = 88 +target-version = "py310" +extend-exclude = ["python/polyfempy/generated_api", "python-from-jse", "examples"] + +[lint] +# Catch syntax errors, undefined names, and unused imports. +select = ["E4", "E7", "E9", "F"] + +[lint.isort] +known-first-party = ["polyfempy"] + diff --git a/setup.py b/setup.py deleted file mode 100644 index 5982caf9..00000000 --- a/setup.py +++ /dev/null @@ -1,123 +0,0 @@ -import os -import re -import sys -# import sysconfig -import platform -import subprocess - -from distutils.version import LooseVersion -from setuptools import setup, Extension, find_packages -from setuptools.command.build_ext import build_ext - -from distutils.sysconfig import get_python_inc - - -class CMakeExtension(Extension): - def __init__(self, name, sourcedir=''): - Extension.__init__(self, name, sources=[]) - self.sourcedir = os.path.abspath(sourcedir) - - -class CMakeBuild(build_ext): - def run(self): - try: - out = subprocess.check_output(['cmake', '--version']) - except OSError: - raise RuntimeError( - "CMake must be installed to build the following extensions: , ".join(e.name for e in self.extensions)) - - # self.debug = True - - cmake_version = LooseVersion( - re.search(r'version\s*([\d.]+)', out.decode()).group(1)) - if cmake_version < '3.1.0': - raise RuntimeError("CMake >= 3.1.0 is required") - - for ext in self.extensions: - self.build_extension(ext) - - def build_extension(self, ext): - use_cholmod = os.environ.get( "USE_CHOLMOD", "1" ) - n_threads_str = os.environ.get( "N_THREADS", "1" ) - n_threads = int(n_threads_str) - - cholmod_str = "-DPOLYSOLVE_WITH_CHOLMOD=OFF" if use_cholmod == "0" else "-DPOLYSOLVE_WITH_CHOLMOD=ON" - - - extdir = os.path.join(os.path.abspath(os.path.dirname( - self.get_ext_fullpath(ext.name))), "polyfempy") - - python_include_directory = str(get_python_inc()) - - cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir, - '-DPYTHON_EXECUTABLE=' + sys.executable, - '-DPYTHON_INCLUDE_DIR=' + python_include_directory, - '-DPOLYSOLVE_WITH_PARDISO=OFF', - cholmod_str, - # '-DPOLYFEM_THREADING=NONE', - '-DPOLYFEM_NO_UI=ON', - '-DPOLYSOLVE_WITH_AMGCL=OFF', - '-DPOLYSOLVE_WITH_MKL=OFF', - '-DPOLYSOLVE_WITH_SPECTRA=OFF'] - - cfg = 'Debug' if self.debug else 'Release' - build_args = ['--config', cfg] - cmake_args += ['-DCMAKE_BUILD_TYPE=' + cfg] - - if platform.system() == "Windows": - cmake_args += [ - '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{}={}'.format(cfg.upper(), extdir)] - if os.environ.get('CMAKE_GENERATOR') != "NMake Makefiles": - if sys.maxsize > 2**32: - cmake_args += ['-A', 'x64'] - # build_args += ['--', '/m'] - else: - build_args += ['--', '-j{}'.format(n_threads)] - - env = os.environ.copy() - # env['CXXFLAGS'] = '{} -DVERSION_INFO=\"{}\"'.format( - # env.get('CXXFLAGS', ''), self.distribution.get_version()) - # print(env['CXXFLAGS']) - - if not os.path.exists(self.build_temp): - os.makedirs(self.build_temp) - subprocess.check_call(['cmake', ext.sourcedir] + - cmake_args, cwd=self.build_temp, env=env) - - subprocess.check_call(['cmake', '--build', '.'] + - build_args, cwd=self.build_temp) - - print() # Add an empty line for cleaner output - - -with open("README.md", "r") as fh: - long_description = fh.read() - - -setup( - name="polyfempy", - version="0.7", - author="Teseo Schneider", - author_email="", - description="Polyfem Python Bindings", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://polyfem.github.io/", - ext_modules=[CMakeExtension('polyfempy')], - cmdclass=dict(build_ext=CMakeBuild), - packages=find_packages(), - classifiers=[ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: MIT License" - ], - python_requires='>=3.6', - install_requires=[ - 'numpy', - 'argparse'], - entry_points={ - 'console_scripts': [ - 'polyfem = polyfempy.command:polyfem' - ] - }, - test_suite="test" -) diff --git a/src/binding.cpp b/src/binding.cpp index 892143e5..9c6b2678 100644 --- a/src/binding.cpp +++ b/src/binding.cpp @@ -1,1073 +1,35 @@ -#include +#include #include -#include -#include -#include -#include +#include -#include "polyfem/State.hpp" -#include "polyfem/solver/ALNLProblem.hpp" -#include "polyfem/solver/NLProblem.hpp" -#include "raster.hpp" +#include +#include +#include -#include -#include +namespace py = nanobind; +using namespace polyfem; +using namespace py::literals; -#include -#include -#include -#include - -#ifdef USE_TBB -#include -#include -#endif - -#include - -#include -#include -#include -#include -#include - -namespace py = pybind11; - -typedef std::function BCFuncV; -typedef std::function BCFuncS; - -class ScalarAssemblers -{ -}; -class TensorAssemblers -{ -}; - -class PDEs -{ -}; - -// TODO add save_time_sequence - -namespace -{ - void init_globals(polyfem::State &state) - { - static bool initialized = false; - - if (!initialized) - { -#ifndef WIN32 - setenv("GEO_NO_SIGNAL_HANDLER", "1", 1); -#endif - - GEO::initialize(); - -#ifdef USE_TBB - const size_t MB = 1024 * 1024; - const size_t stack_size = 64 * MB; - unsigned int num_threads = - std::max(1u, std::thread::hardware_concurrency()); - tbb::task_scheduler_init scheduler(num_threads, stack_size); -#endif - - // Import standard command line arguments, and custom ones - GEO::CmdLine::import_arg_group("standard"); - GEO::CmdLine::import_arg_group("pre"); - GEO::CmdLine::import_arg_group("algo"); - - state.init_logger(std::cout, 2); - - initialized = true; - } - } - -} // namespace - -const auto rendering_lambda = - [](const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &faces, int width, - int height, const Eigen::MatrixXd &camera_positionm, - const double camera_fov, const double camera_near, - const double camera_far, const bool is_perspective, - const Eigen::MatrixXd &lookatm, const Eigen::MatrixXd &upm, - const Eigen::MatrixXd &ambient_lightm, - const std::vector> &lights, - const Eigen::MatrixXd &diffuse_colorm, - const Eigen::MatrixXd &specular_colorm, const double specular_exponent) { - using namespace renderer; - using namespace Eigen; - - Eigen::Vector3d camera_position(0, 0, 1); - Eigen::Vector3d lookat(0, 0, 0); - Eigen::Vector3d up(0, 0, 1); - Eigen::Vector3d ambient_light(0.1, 0.1, 0.1); - Eigen::Vector3d diffuse_color(1, 0, 0); - Eigen::Vector3d specular_color(1, 0, 0); - - if (camera_positionm.size() > 0 && camera_positionm.size() != 3) - throw pybind11::value_error("camera_position have size 3"); - if (camera_positionm.size() == 3) - camera_position << camera_positionm(0), camera_positionm(1), - camera_positionm(2); - if (lookatm.size() > 0 && lookatm.size() != 3) - throw pybind11::value_error("lookat have size 3"); - if (lookatm.size() == 3) - lookat << lookatm(0), lookatm(1), lookatm(2); - if (upm.size() > 0 && upm.size() != 3) - throw pybind11::value_error("up have size 3"); - if (upm.size() == 3) - up << upm(0), upm(1), upm(2); - if (ambient_lightm.size() > 0 && ambient_lightm.size() != 3) - throw pybind11::value_error("ambient_light have size 3"); - if (ambient_lightm.size() == 3) - ambient_light << ambient_lightm(0), ambient_lightm(1), - ambient_lightm(2); - if (diffuse_colorm.size() > 0 && diffuse_colorm.size() != 3) - throw pybind11::value_error("diffuse_color have size 3"); - if (diffuse_colorm.size() == 3) - diffuse_color << diffuse_colorm(0), diffuse_colorm(1), - diffuse_colorm(2); - if (specular_colorm.size() > 0 && specular_colorm.size() != 3) - throw pybind11::value_error("specular_color have size 3"); - if (specular_colorm.size() == 3) - specular_color << specular_colorm(0), specular_colorm(1), - specular_colorm(2); - - Material material; - material.diffuse_color = diffuse_color; - material.specular_color = specular_color; - material.specular_exponent = specular_exponent; - - Eigen::Matrix - frameBuffer(width, height); - UniformAttributes uniform; - - const Vector3d gaze = lookat - camera_position; - const Vector3d w = -gaze.normalized(); - const Vector3d u = up.cross(w).normalized(); - const Vector3d v = w.cross(u); - - Matrix4d M_cam_inv; - M_cam_inv << u(0), v(0), w(0), camera_position(0), u(1), v(1), w(1), - camera_position(1), u(2), v(2), w(2), camera_position(2), 0, 0, 0, 1; - - uniform.M_cam = M_cam_inv.inverse(); - - { - const double camera_ar = double(width) / height; - const double tan_angle = tan(camera_fov / 2); - const double n = -camera_near; - const double f = -camera_far; - const double t = tan_angle * n; - const double b = -t; - const double r = t * camera_ar; - const double l = -r; - - uniform.M_orth << 2 / (r - l), 0, 0, -(r + l) / (r - l), 0, 2 / (t - b), - 0, -(t + b) / (t - b), 0, 0, 2 / (n - f), -(n + f) / (n - f), 0, 0, - 0, 1; - Matrix4d P; - if (is_perspective) - { - P << n, 0, 0, 0, 0, n, 0, 0, 0, 0, n + f, -f * n, 0, 0, 1, 0; - } - else - { - P << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1; - } - - uniform.M = uniform.M_orth * P * uniform.M_cam; - } - - Program program; - program.VertexShader = [&](const VertexAttributes &va, - const UniformAttributes &uniform) { - VertexAttributes out; - out.position = uniform.M * va.position; - Vector3d color = ambient_light; - - Vector3d hit(va.position(0), va.position(1), va.position(2)); - for (const auto &l : lights) - { - Vector3d Li = (l.first - hit).normalized(); - Vector3d N = va.normal; - Vector3d diffuse = - va.material.diffuse_color * std::max(Li.dot(N), 0.0); - Vector3d H; - if (is_perspective) - { - H = (Li + (camera_position - hit).normalized()).normalized(); - } - else - { - H = (Li - gaze.normalized()).normalized(); - } - const Vector3d specular = va.material.specular_color - * std::pow(std::max(N.dot(H), 0.0), - va.material.specular_exponent); - const Vector3d D = l.first - hit; - color += - (diffuse + specular).cwiseProduct(l.second) / D.squaredNorm(); - } - out.color = color; - return out; - }; - - program.FragmentShader = [](const VertexAttributes &va, - const UniformAttributes &uniform) { - FragmentAttributes out(va.color(0), va.color(1), va.color(2)); - out.depth = -va.position(2); - return out; - }; - - program.BlendingShader = [](const FragmentAttributes &fa, - const FrameBufferAttributes &previous) { - if (fa.depth < previous.depth) - { - FrameBufferAttributes out(fa.color[0] * 255, fa.color[1] * 255, - fa.color[2] * 255, fa.color[3] * 255); - out.depth = fa.depth; - return out; - } - else - { - return previous; - } - }; - - Eigen::MatrixXd vnormals(vertices.rows(), 3); - // Eigen::MatrixXd areas(tmp.rows(), 1); - vnormals.setZero(); - // areas.setZero(); - Eigen::MatrixXd fnormals(faces.rows(), 3); - - for (int i = 0; i < faces.rows(); ++i) - { - const Vector3d l1 = - vertices.row(faces(i, 1)) - vertices.row(faces(i, 0)); - const Vector3d l2 = - vertices.row(faces(i, 2)) - vertices.row(faces(i, 0)); - const auto nn = l1.cross(l2); - const double area = nn.norm(); - fnormals.row(i) = nn / area; - - for (int j = 0; j < 3; j++) - { - int vid = faces(i, j); - vnormals.row(vid) += nn; - // areas(vid) += area; - } - } - - std::vector vertex_attributes; - for (int i = 0; i < faces.rows(); ++i) - { - for (int j = 0; j < 3; j++) - { - int vid = faces(i, j); - VertexAttributes va(vertices(vid, 0), vertices(vid, 1), - vertices(vid, 2)); - va.material = material; - va.normal = vnormals.row(vid).normalized(); - vertex_attributes.push_back(va); - } - } - - rasterize_triangles(program, uniform, vertex_attributes, frameBuffer); - - std::vector image; - framebuffer_to_uint8(frameBuffer, image); - - return image; - }; - -PYBIND11_MODULE(polyfempy, m) +NB_MODULE(polyfempy, m) { - const auto &pdes = py::class_(m, "PDEs"); - - const auto &sa = py::class_(m, "ScalarFormulations"); - for (auto &a : polyfem::assembler::AssemblerUtils::scalar_assemblers()) - { - sa.attr(a.c_str()) = a; - pdes.attr(a.c_str()) = a; - } - - const auto &ta = py::class_(m, "TensorFormulations"); - for (auto &a : polyfem::assembler::AssemblerUtils::tensor_assemblers()) - { - ta.attr(a.c_str()) = a; - pdes.attr(a.c_str()) = a; - } - - ta.attr("NonLinearElasticity") = "NonLinearElasticity"; - pdes.attr("NonLinearElasticity") = "NonLinearElasticity"; - - pdes.doc() = "List of supported partial differential equations"; - - m.def( - "is_tensor", - [](const std::string &pde) { - return polyfem::assembler::AssemblerUtils::is_tensor(pde); - }, - "returns true if the pde is tensorial", py::arg("pde")); - - const auto setting_lambda = [](polyfem::State &self, - const py::object &settings) { - using namespace polyfem; - - init_globals(self); - // py::scoped_ostream_redirect output; - const std::string json_string = py::str(settings); - self.init(json::parse(json_string)); - }; - - auto &solver = py::class_(m, "Solver") - .def(py::init<>()) - - .def("settings", setting_lambda, - "load PDE and problem parameters from the settings", py::arg("json")) - - .def("set_settings", setting_lambda, - "load PDE and problem parameters from the settings", py::arg("json")) - - .def( - "set_log_level", [](polyfem::State &s, int log_level) { - init_globals(s); - // py::scoped_ostream_redirect output; - log_level = std::max(0, std::min(6, log_level)); - spdlog::set_level(static_cast(log_level)); }, - "sets polyfem log level, valid value between 0 (all logs) and 6 (no logs)", py::arg("log_level")) - - .def( - "load_mesh_from_settings", [](polyfem::State &s, const bool normalize_mesh, const double vismesh_rel_area, const int n_refs, const double boundary_id_threshold) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.args["geometry"][0]["advanced"]["normalize_mesh"] = normalize_mesh; - s.args["output"]["paraview"]["vismesh_rel_area"] = vismesh_rel_area; - s.load_mesh(); }, - "Loads a mesh from the 'mesh' field of the json and 'bc_tag' if any bc tags", py::arg("normalize_mesh") = bool(false), py::arg("vismesh_rel_area") = double(0.00001), py::arg("n_refs") = int(0), py::arg("boundary_id_threshold") = double(-1)) - - .def( - "load_mesh_from_path", [](polyfem::State &s, const std::string &path, const bool normalize_mesh, const double vismesh_rel_area, const int n_refs, const double boundary_id_threshold) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.args["geometry"][0]["mesh"] = path; - s.args["geometry"][0]["advanced"]["normalize_mesh"] = normalize_mesh; - s.args["output"]["paraview"]["vismesh_rel_area"] = vismesh_rel_area; - s.load_mesh(); }, - "Loads a mesh from the path and 'bc_tag' from the json if any bc tags", py::arg("path"), py::arg("normalize_mesh") = bool(false), py::arg("vismesh_rel_area") = double(0.00001), py::arg("n_refs") = int(0), py::arg("boundary_id_threshold") = double(-1)) - - .def( - "load_mesh_from_path_and_tags", [](polyfem::State &s, const std::string &path, const std::string &bc_tag, const bool normalize_mesh, const double vismesh_rel_area, const int n_refs, const double boundary_id_threshold) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.args["geometry"][0]["mesh"] = path; - s.args["bc_tag"] = bc_tag; - s.args["geometry"][0]["advanced"]["normalize_mesh"] = normalize_mesh; - s.args["n_refs"] = n_refs; - s.args["output"]["paraview"]["vismesh_rel_area"] = vismesh_rel_area; - s.load_mesh(); }, - "Loads a mesh and bc_tags from path", py::arg("path"), py::arg("bc_tag_path"), py::arg("normalize_mesh") = bool(false), py::arg("vismesh_rel_area") = double(0.00001), py::arg("n_refs") = int(0), py::arg("boundary_id_threshold") = double(-1)) - - .def( - "set_mesh", [](polyfem::State &s, const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const bool normalize_mesh, const double vismesh_rel_area, const int n_refs, const double boundary_id_threshold) { - init_globals(s); - // py::scoped_ostream_redirect output; - - if (V.cols() == 2) - s.mesh = std::make_unique(); - else - s.mesh = std::make_unique(); - s.mesh->build_from_matrices(V, F); - - s.args["geometry"][0]["advanced"]["normalize_mesh"] = normalize_mesh; - s.args["geometry"][0]["n_refs"] = n_refs; - s.args["boundary_id_threshold"] = boundary_id_threshold; - s.args["output"]["paraview"]["vismesh_rel_area"] = vismesh_rel_area; - - s.load_mesh(); }, - "Loads a mesh from vertices and connectivity", py::arg("vertices"), py::arg("connectivity"), py::arg("normalize_mesh") = bool(false), py::arg("vismesh_rel_area") = double(0.00001), py::arg("n_refs") = int(0), py::arg("boundary_id_threshold") = double(-1)) - - .def( - "set_high_order_mesh", [](polyfem::State &s, const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, const Eigen::MatrixXd &nodes_pos, const std::vector> &nodes_indices, const bool normalize_mesh, const double vismesh_rel_area, const int n_refs, const double boundary_id_threshold) { - init_globals(s); - // py::scoped_ostream_redirect output; - - if (V.cols() == 2) - s.mesh = std::make_unique(); - else - s.mesh = std::make_unique(); - s.mesh->build_from_matrices(V, F); - s.mesh->attach_higher_order_nodes(nodes_pos, nodes_indices); - - s.args["geometry"][0]["advanced"]["normalize_mesh"] = normalize_mesh; - s.args["geometry"][0]["n_refs"] = n_refs; - s.args["boundary_id_threshold"] = boundary_id_threshold; - s.args["output"]["paraview"]["vismesh_rel_area"] = vismesh_rel_area; - - s.load_mesh(); }, - "Loads an high order mesh from vertices, connectivity, nodes, and node indices mapping element to nodes", py::arg("vertices"), py::arg("connectivity"), py::arg("nodes_pos"), py::arg("nodes_indices"), py::arg("normalize_mesh") = bool(false), py::arg("vismesh_rel_area") = double(0.00001), py::arg("n_refs") = int(0), py::arg("boundary_id_threshold") = double(-1)) - - .def( - "set_boundary_side_set_from_bary", [](polyfem::State &s, const std::function &boundary_marker) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.mesh->compute_boundary_ids(boundary_marker); }, - "Sets the side set for the boundary conditions, the functions takes the barycenter of the boundary (edge or face)", py::arg("boundary_marker")) - .def( - "set_boundary_side_set_from_bary_and_boundary", [](polyfem::State &s, const std::function &boundary_marker) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.mesh->compute_boundary_ids(boundary_marker); }, - "Sets the side set for the boundary conditions, the functions takes the barycenter of the boundary (edge or face) and a flag that says if the element is boundary", py::arg("boundary_marker")) - .def( - "set_boundary_side_set_from_v_ids", [](polyfem::State &s, const std::function &, bool)> &boundary_marker) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.mesh->compute_boundary_ids(boundary_marker); }, - "Sets the side set for the boundary conditions, the functions takes the sorted list of vertex id and a flag that says if the element is boundary", py::arg("boundary_marker")) - - .def( - "set_rhs_from_path", [](polyfem::State &s, std::string &path) { - init_globals(s); - // py::scoped_ostream_redirect output; - throw std::runtime_error("No RHS path"); }, - "Loads the rhs from a file", py::arg("path")) - .def( - "set_rhs", [](polyfem::State &s, const Eigen::MatrixXd &rhs) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.rhs_in = rhs; }, - "Sets the rhs", py::arg("matrix")) - - .def( - "solve", [](polyfem::State &s) { - init_globals(s); - // py::scoped_ostream_redirect output; - s.compute_mesh_stats(); - - s.build_basis(); - - s.assemble_rhs(); - s.assemble_stiffness_mat(); - - s.solve_export_to_file = false; - s.solution_frames.clear(); - s.solve_problem(); - s.solve_export_to_file = true; }, - "solve the pde") - .def( - "init_timestepping", [](polyfem::State &s, const double t0, const double dt) { - init_globals(s); - s.compute_mesh_stats(); - - s.build_basis(); - - s.assemble_rhs(); - s.assemble_stiffness_mat(); - - s.solution_frames.clear(); - Eigen::VectorXd _; - s.init_transient(_); - const polyfem::assembler::RhsAssembler &rhs_assembler = *s.step_data.rhs_assembler; - s.solve_transient_tensor_non_linear_init(t0, dt, rhs_assembler); }, - "initialize timestepping", py::arg("t0"), py::arg("dt")) - .def( - "step_in_time", [](polyfem::State &s, const double t0, const double dt, const int t) { - json solver_info; - s.step_data.nl_problem->substepping(t0 + t * dt); - s.step_data.alnl_problem->update_target(t0 + t * dt); - s.solve_transient_tensor_non_linear_step(t0, dt, t, solver_info); - return solver_info; }, - "step in time", py::arg("t0"), py::arg("dt"), py::arg("t")) - - .def( - "compute_errors", [](polyfem::State &s) { - init_globals(s); - // py::scoped_ostream_redirect output; - - s.compute_errors(); }, - "compute the error") - - .def( - "get_log", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - json out; - s.save_json(out); - return out; }, - "gets the log") - - // .def("export_data", [](polyfem::State &s) { py::scoped_ostream_redirect output; s.export_data(); }, "exports all data specified in the settings") - .def( - "export_vtu", [](polyfem::State &s, std::string &path, bool boundary_only) { - // py::scoped_ostream_redirect output; - auto& vis_bnd = s.args["output"]["advanced"]["vis_boundary_only"]; - const bool tmp = vis_bnd; - vis_bnd = boundary_only; - s.save_vtu(path, 0); - vis_bnd = tmp;}, - "exports the solution as vtu", py::arg("path"), py::arg("boundary_only") = bool(false)) - // .def("export_wire", [](polyfem::State &s, std::string &path, bool isolines) { py::scoped_ostream_redirect output; s.save_wire(path, isolines); }, "exports wireframe of the mesh", py::arg("path"), py::arg("isolines") = false) - - .def( - "get_solution", [](const polyfem::State &s) { return s.sol; }, - "returns the solution") - .def( - "get_pressure", [](const polyfem::State &s) { return s.pressure; }, - "returns the pressure") - .def( - "get_sampled_solution", [](polyfem::State &s, bool boundary_only) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi tets; - Eigen::MatrixXi el_id; - Eigen::MatrixXd discr; - Eigen::MatrixXd fun; - - auto& vis_bnd = s.args["output"]["advanced"]["vis_boundary_only"]; - const bool tmp = vis_bnd; - vis_bnd = boundary_only; - - s.build_vis_mesh(points, tets, el_id, discr); - - Eigen::MatrixXd ids(points.rows(), 1); - for (int i = 0; i < points.rows(); ++i) - { - ids(i) = s.mesh->get_body_id(el_id(i)); - } - const bool use_sampler = true; - s.interpolate_function(points.rows(), s.sol, fun, use_sampler, boundary_only); - - vis_bnd = tmp; - - return py::make_tuple(points, tets, el_id, ids, fun); }, - "returns the solution on a densly sampled mesh, use 'vismesh_rel_area' to control density", py::arg("boundary_only") = bool(false)) - - .def( - "get_stresses", [](polyfem::State &s, bool boundary_only) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi tets; - Eigen::MatrixXi el_id; - Eigen::MatrixXd discr; - Eigen::MatrixXd fun; - auto& vis_bnd = s.args["output"]["advanced"]["vis_boundary_only"]; - const bool tmp = vis_bnd; - vis_bnd = boundary_only; - - s.build_vis_mesh(points, tets, el_id, discr); - const bool use_sampler = true; - s.compute_tensor_value(points.rows(), s.sol, fun, use_sampler, boundary_only); - - vis_bnd = tmp; - - return fun; }, - "returns the stress tensor on a densly sampled mesh, use 'vismesh_rel_area' to control density", py::arg("boundary_only") = bool(false)) - - .def( - "get_sampled_mises", [](polyfem::State &s, bool boundary_only) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi tets; - Eigen::MatrixXi el_id; - Eigen::MatrixXd discr; - Eigen::MatrixXd fun; - - auto& vis_bnd = s.args["output"]["advanced"]["vis_boundary_only"]; - const bool tmp = vis_bnd; - vis_bnd = boundary_only; - - s.build_vis_mesh(points, tets, el_id, discr); - const bool use_sampler = true; - s.compute_scalar_value(points.rows(), s.sol, fun, use_sampler, boundary_only); - - vis_bnd = tmp; - - return fun; }, - "returns the von mises stresses on a densly sampled mesh, use 'vismesh_rel_area' to control density", py::arg("boundary_only") = bool(false)) - - .def( - "get_sampled_mises_avg", [](polyfem::State &s, bool boundary_only) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi tets; - Eigen::MatrixXi el_id; - Eigen::MatrixXd discr; - Eigen::MatrixXd fun, tfun; - - auto& vis_bnd = s.args["output"]["advanced"]["vis_boundary_only"]; - const bool tmp = vis_bnd; - vis_bnd = boundary_only; - - s.build_vis_mesh(points, tets, el_id, discr); - const bool use_sampler = true; - s.average_grad_based_function(points.rows(), s.sol, fun, tfun, use_sampler, boundary_only); - - vis_bnd = tmp; - - return py::make_tuple(fun, tfun); }, - "returns the von mises stresses and stress tensor averaged around a vertex on a densly sampled mesh, use 'vismesh_rel_area' to control density", py::arg("boundary_only") = bool(false)) - - .def( - "get_sampled_traction_forces", [](polyfem::State &s, const bool apply_displacement, const bool compute_avg) { - // py::scoped_ostream_redirect output; - - if (!s.mesh) - throw pybind11::value_error("Load the mesh first!"); - if (!s.mesh->is_volume()) - throw pybind11::value_error("This function works only on volumetric meshes!"); - if (s.problem->is_scalar()) - throw pybind11::value_error("Define a tensor problem!"); - - Eigen::MatrixXd result, stresses, mises; - - Eigen::MatrixXd v_surf; - Eigen::MatrixXi f_surf; - const double epsilon = 1e-10; - - { - const polyfem::mesh::CMesh3D &mesh3d = *dynamic_cast(s.mesh.get()); - Eigen::MatrixXd points(mesh3d.n_vertices(), 3); - Eigen::MatrixXi tets(mesh3d.n_cells(), 4); - - for (int t = 0; t < mesh3d.n_cells(); ++t) - { - if (mesh3d.n_cell_vertices(t) != 4) - throw pybind11::value_error("Works only with tet meshes!"); - - for (int i = 0; i < 4; ++i) - tets(t, i) = mesh3d.cell_vertex(t, i); - } - - for (int p = 0; p < mesh3d.n_vertices(); ++p) - points.row(p) << mesh3d.point(p); - - Eigen::MatrixXi f_surf_tmp, _; - igl::boundary_facets(tets, f_surf_tmp); - igl::remove_unreferenced(points, f_surf_tmp, v_surf, f_surf, _); - } - - if (apply_displacement) - s.interpolate_boundary_tensor_function(v_surf, f_surf, s.sol, s.sol, compute_avg, result, stresses, mises, true); - else - s.interpolate_boundary_tensor_function(v_surf, f_surf, s.sol, compute_avg, result, stresses, mises, true); - - return py::make_tuple(v_surf, f_surf, result, stresses, mises); }, - "returns the traction forces, stresses, and von mises computed on the surface", py::arg("apply_displacement") = bool(false), py::arg("compute_avg") = bool(true)) - - //////////////////////////////////////////////////////////////////////////////////////////// - .def( - "get_sampled_points_frames", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - assert(!s.solution_frames.empty()); - - std::vector pts; - - for (const auto &sol : s.solution_frames) - { - pts.push_back(sol.points); - } - - return pts; }, - "returns the points frames for a time dependent problem on a densly sampled mesh, use 'vismesh_rel_area' to control density") - - .def( - "get_sampled_connectivity_frames", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - assert(!s.solution_frames.empty()); - - std::vector tets; - - for (const auto &sol : s.solution_frames) - tets.push_back(sol.connectivity); - - return tets; }, - "returns the connectivity frames for a time dependent problem on a densly sampled mesh, use 'vismesh_rel_area' to control density") - - .def( - "get_sampled_solution_frames", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - assert(!s.solution_frames.empty()); - - std::vector fun; - - for (const auto &sol : s.solution_frames) - { - fun.push_back(sol.solution); - } - - return fun; }, - "returns the solution frames for a time dependent problem on a densly sampled mesh, use 'vismesh_rel_area' to control density") - - .def( - "get_sampled_mises_frames", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - assert(!s.solution_frames.empty()); - - std::vector mises; - - for (const auto &sol : s.solution_frames) - mises.push_back(sol.scalar_value); - - return mises; }, - "returns the von mises stresses frames on a densly sampled mesh, use 'vismesh_rel_area' to control density") - - .def( - "get_sampled_mises_avg_frames", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - assert(!s.solution_frames.empty()); - - std::vector mises; - - for (const auto &sol : s.solution_frames) - mises.push_back(sol.scalar_value_avg); - - return mises; }, - "returns the von mises stresses per frame averaged around a vertex on a densly sampled mesh, use 'vismesh_rel_area' to control density") - - .def( - "get_boundary_sidesets", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi faces; - Eigen::MatrixXd sidesets; - - s.get_sidesets(points, faces, sidesets); - - return py::make_tuple(points, faces, sidesets); }, - "exports get the boundary sideset, edges in 2d or trangles in 3d") - .def( - "get_body_ids", [](polyfem::State &s) { - // py::scoped_ostream_redirect output; - Eigen::MatrixXd points; - Eigen::MatrixXi tets; - Eigen::MatrixXi el_id; - Eigen::MatrixXd discr; - - s.build_vis_mesh(points, tets, el_id, discr); - - Eigen::MatrixXd ids(points.rows(), 1); - - for (int i = 0; i < points.rows(); ++i) - { - ids(i) = s.mesh->get_body_id(el_id(i)); - } - - return py::make_tuple(points, tets, el_id, ids); }, - "exports get the body ids") - .def( - "update_dirichlet_boundary", [](polyfem::State &self, const int id, const py::object &val, const bool isx, const bool isy, const bool isz, const std::string &interp) { - using namespace polyfem; - // py::scoped_ostream_redirect output; - const json json_val = val; - if (polyfem::assembler::GenericTensorProblem *prob = dynamic_cast(self.problem.get())) - { - prob->update_dirichlet_boundary(id, json_val, isx, isy, isz, interp); - } - else if (polyfem::assembler::GenericScalarProblem *prob = dynamic_cast(self.problem.get())) - { - prob->update_dirichlet_boundary(id, json_val, interp); - } - else - { - throw "Updating BC works only for GenericProblems"; - } }, - "updates dirichlet boundary", py::arg("id"), py::arg("val"), py::arg("isx") = bool(true), py::arg("isy") = bool(true), py::arg("isz") = bool(true), py::arg("interp") = std::string("")) - .def( - "update_neumann_boundary", [](polyfem::State &self, const int id, const py::object &val, const std::string &interp) { - using namespace polyfem; - // py::scoped_ostream_redirect output; - const json json_val = val; - - if (auto prob = dynamic_cast(self.problem.get())) - { - prob->update_neumann_boundary(id, json_val, interp); - } - else if (auto prob = dynamic_cast(self.problem.get())) - { - prob->update_neumann_boundary(id, json_val, interp); - } - else - { - throw "Updating BC works only for GenericProblems"; - } }, - "updates neumann boundary", py::arg("id"), py::arg("val"), py::arg("interp") = std::string("")) - .def( - "update_pressure_boundary", [](polyfem::State &self, const int id, const py::object &val, const std::string &interp) { - using namespace polyfem; - // py::scoped_ostream_redirect output; - const json json_val = val; - - if (auto prob = dynamic_cast(self.problem.get())) - { - prob->update_pressure_boundary(id, json_val, interp); - } - else - { - throw "Updating BC works only for Tensor GenericProblems"; - } }, - "updates pressure boundary", py::arg("id"), py::arg("val"), py::arg("interp") = std::string("")) - .def( - "update_obstacle_displacement", [](polyfem::State &self, const int oid, const py::object &val, const std::string &interp) { - using namespace polyfem; - // py::scoped_ostream_redirect output; - const json json_val = val; - self.obstacle.change_displacement(oid, json_val, interp); }, - "updates obstacle displacement", py::arg("oid"), py::arg("val"), py::arg("interp") = std::string("")) - .def( - "render", [](polyfem::State &self, int width, int height, const Eigen::MatrixXd &camera_positionm, const double camera_fov, const double camera_near, const double camera_far, const bool is_perspective, const Eigen::MatrixXd &lookatm, const Eigen::MatrixXd &upm, const Eigen::MatrixXd &ambient_lightm, const std::vector> &lights, const Eigen::MatrixXd &diffuse_colorm, const Eigen::MatrixXd &specular_colorm, const double specular_exponent) { - using namespace Eigen; - - const int problem_dim = self.problem->is_scalar() ? 1 : self.mesh->dimension(); - - Eigen::MatrixXd tmp = self.boundary_nodes_pos; - assert(tmp.rows() * problem_dim == self.sol.size()); - for (int i = 0; i < self.sol.size(); i += problem_dim) - { - for (int d = 0; d < problem_dim; ++d) - { - tmp(i / problem_dim, d) += self.sol(i + d); - } - } - - return rendering_lambda(tmp, self.boundary_triangles, width, height, camera_positionm, camera_fov, camera_near, camera_far, is_perspective, lookatm, upm, ambient_lightm, lights, diffuse_colorm, specular_colorm, specular_exponent); }, - "renders the scene", py::kw_only(), py::arg("width"), py::arg("height"), py::arg("camera_position") = Eigen::MatrixXd(), py::arg("camera_fov") = double(0.8), py::arg("camera_near") = double(1), py::arg("camera_far") = double(10), py::arg("is_perspective") = bool(true), py::arg("lookat") = Eigen::MatrixXd(), py::arg("up") = Eigen::MatrixXd(), py::arg("ambient_light") = Eigen::MatrixXd(), py::arg("lights") = std::vector>(), py::arg("diffuse_color") = Eigen::MatrixXd(), py::arg("specular_color") = Eigen::MatrixXd(), py::arg("specular_exponent") = double(1)) - .def( - "render_extrinsic", [](polyfem::State &self, const std::vector> &vertex_face, int width, int height, const Eigen::MatrixXd &camera_positionm, const double camera_fov, const double camera_near, const double camera_far, const bool is_perspective, const Eigen::MatrixXd &lookatm, const Eigen::MatrixXd &upm, const Eigen::MatrixXd &ambient_lightm, const std::vector> &lights, const Eigen::MatrixXd &diffuse_colorm, const Eigen::MatrixXd &specular_colorm, const double specular_exponent) { - int v_count = 0; - int f_count = 0; - for (const auto& vf_pair : vertex_face) { - v_count += vf_pair.first.rows(); - f_count += vf_pair.second.rows(); - } - Eigen::MatrixXd vertices(v_count, 3); - Eigen::MatrixXi faces(f_count, 3); - v_count = 0; - f_count = 0; - for (const auto& vf_pair : vertex_face) { - vertices.block(v_count, 0, vf_pair.first.rows(), 3) = vf_pair.first; - faces.block(f_count, 0, vf_pair.second.rows(), 3) = (vf_pair.second.array() + v_count).matrix(); - v_count += vf_pair.first.rows(); - f_count += vf_pair.second.rows(); - } - return rendering_lambda(vertices, faces, width, height, camera_positionm, camera_fov, camera_near, camera_far, is_perspective, lookatm, upm, ambient_lightm, lights, diffuse_colorm, specular_colorm, specular_exponent); }, - "renders the extrinsic scene", py::kw_only(), py::arg("vertex_face") = std::vector>(), py::arg("width"), py::arg("height"), py::arg("camera_position") = Eigen::MatrixXd(), py::arg("camera_fov") = double(0.8), py::arg("camera_near") = double(1), py::arg("camera_far") = double(10), py::arg("is_perspective") = bool(true), py::arg("lookat") = Eigen::MatrixXd(), py::arg("up") = Eigen::MatrixXd(), py::arg("ambient_light") = Eigen::MatrixXd(), py::arg("lights") = std::vector>(), py::arg("diffuse_color") = Eigen::MatrixXd(), py::arg("specular_color") = Eigen::MatrixXd(), py::arg("specular_exponent") = double(1)); - - solver.doc() = "Polyfem solver"; - - m.def( - "polyfem_command", - [](const std::string &json_file, const std::string &febio_file, - const std::string &mesh, const std::string &problem_name, - const std::string &scalar_formulation, - const std::string &tensor_formulation, const int n_refs, - const bool skip_normalization, const std::string &solver, - const int discr_order, const bool p_ref, const bool count_flipped_els, - const bool force_linear_geom, const double vis_mesh_res, - const bool project_to_psd, const int nl_solver_rhs_steps, - const std::string &output, const std::string &vtu, const int log_level, - const std::string &log_file, const bool is_quiet, - const bool export_material_params) { - json in_args = json({}); - - if (!json_file.empty()) - { - std::ifstream file(json_file); - - if (file.is_open()) - file >> in_args; - else - throw "unable to open " + json_file + " file"; - file.close(); - } - else - { - in_args["geometry"][0]["mesh"] = mesh; - in_args["force_linear_geometry"] = force_linear_geom; - in_args["n_refs"] = n_refs; - if (!problem_name.empty()) - in_args["problem"] = problem_name; - in_args["geometry"][0]["advanced"]["normalize_mesh"] = - !skip_normalization; - in_args["project_to_psd"] = project_to_psd; - - if (!scalar_formulation.empty()) - in_args["scalar_formulation"] = scalar_formulation; - if (!tensor_formulation.empty()) - in_args["tensor_formulation"] = tensor_formulation; - // in_args["mixed_formulation"] = mixed_formulation; - - in_args["discr_order"] = discr_order; - // in_args["use_spline"] = use_splines; - in_args["count_flipped_els"] = count_flipped_els; - in_args["output"] = output; - in_args["use_p_ref"] = p_ref; - // in_args["iso_parametric"] = isoparametric; - // in_args["serendipity"] = serendipity; - - in_args["nl_solver_rhs_steps"] = nl_solver_rhs_steps; - - if (!vtu.empty()) - { - in_args["export"]["vis_mesh"] = vtu; - in_args["export"]["wire_mesh"] = - polyfem::utils::StringUtils::replace_ext(vtu, "obj"); - } - if (!solver.empty()) - in_args["solver_type"] = solver; - - if (vis_mesh_res > 0) - in_args["output"]["paraview"]["vismesh_rel_area"] = vis_mesh_res; - - if (export_material_params) - in_args["export"]["material_params"] = true; - } - - polyfem::State state; - state.init_logger(log_file, log_level, is_quiet); - state.init(in_args); - - if (!febio_file.empty()) - state.load_febio(febio_file, in_args); - else - state.load_mesh(); - state.compute_mesh_stats(); - - state.build_basis(); - - state.assemble_rhs(); - state.assemble_stiffness_mat(); - - state.solve_problem(); - - state.compute_errors(); - - state.save_json(); - state.export_data(); - }, - "runs the polyfem command, internal usage"); - - m.def( - "solve_febio", - [](const std::string &febio_file, const std::string &output_path, - const int log_level, const py::kwargs &kwargs) { - if (febio_file.empty()) - throw pybind11::value_error("Specify a febio file!"); - - // json in_args = opts.is_none() ? json({}) : json(opts); - json in_args = json(static_cast(kwargs)); - - if (!output_path.empty()) - { - in_args["export"]["paraview"] = output_path; - in_args["export"]["wire_mesh"] = - polyfem::utils::StringUtils::replace_ext(output_path, "obj"); - in_args["export"]["material_params"] = true; - in_args["export"]["body_ids"] = true; - in_args["export"]["contact_forces"] = true; - in_args["export"]["surface"] = true; - } - - const int discr_order = - in_args.contains("discr_order") ? int(in_args["discr_order"]) : 1; - - if (discr_order == 1 && !in_args.contains("vismesh_rel_area")) - in_args["output"]["paraview"]["vismesh_rel_area"] = 1e10; - - polyfem::State state; - state.init_logger("", log_level, false); - state.init(in_args); - state.load_febio(febio_file, in_args); - state.compute_mesh_stats(); - - state.build_basis(); - - state.assemble_rhs(); - state.assemble_stiffness_mat(); - - state.solve_problem(); - - // state.compute_errors(); - - state.save_json(); - state.export_data(); - }, - "runs FEBio", py::arg("febio_file"), - py::arg("output_path") = std::string(""), py::arg("log_level") = 2); - - m.def( - "solve", - [](const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &cells, - const py::object &sidesets_func, const int log_level, - const py::kwargs &kwargs) { - std::string log_file = ""; - - std::unique_ptr res = - std::make_unique(); - polyfem::State &state = *res; - state.init_logger(log_file, log_level, false); - - json in_args = json(static_cast(kwargs)); - - state.init(in_args); - - state.load_mesh(vertices, cells); - - [&]() { - if (!sidesets_func.is_none()) - { - try - { - const auto fun = - sidesets_func - .cast>(); - state.mesh->compute_boundary_ids(fun); - return true; - } - catch (...) + py::class_(m, "Solver") + .def(py::init<>()) + .def("set_settings", [](State &state, const std::string &settings, bool strict) { + state.init(json::parse(settings), strict); + }, "json"_a, "strict_validation"_a = false) + .def("load_mesh_from_settings", [](State &state) { state.load_mesh(); }) + .def("solve", [](State &state) { + Eigen::MatrixXd sol; { - { - } + // Python expressions may run on worker threads. + py::gil_scoped_release release; + state.solve(sol); + state.variational_formulation->compute_errors(sol); + const auto timings = state.variational_formulation->output_timings(); + logger().info("total time: {}s", timings.total_time()); + state.variational_formulation->save_json(sol); + state.variational_formulation->export_data(sol); } - try - { - const auto fun = sidesets_func.cast< - std::function>(); - state.mesh->compute_boundary_ids(fun); - return true; - } - catch (...) - { - } - - try - { - const auto fun = sidesets_func.cast< - std::function &, bool)>>(); - state.mesh->compute_boundary_ids(fun); - return true; - } - catch (...) - { - } - - throw pybind11::value_error( - "sidesets_func has invalid type, should be a function (p)->int, (p, bool)->int, ([], bool)->int"); - } - }(); - - state.compute_mesh_stats(); - - state.build_basis(); - - state.assemble_rhs(); - state.assemble_stiffness_mat(); - state.solve_problem(); - - return res; - }, - "single solve function", py::kw_only(), - py::arg("vertices") = Eigen::MatrixXd(), - py::arg("cells") = Eigen::MatrixXi(), - py::arg("sidesets_func") = py::none(), py::arg("log_level") = 2); + return sol; + }); } diff --git a/src/raster.cpp b/src/raster.cpp deleted file mode 100755 index 5b73708a..00000000 --- a/src/raster.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include "raster.hpp" - - - -#include - -namespace renderer -{ - void rasterize_triangle(const Program &program, const UniformAttributes &uniform, const VertexAttributes &v1, const VertexAttributes &v2, const VertexAttributes &v3, Eigen::Matrix &frameBuffer) - { - Eigen::Matrix p; - p.row(0) = v1.position.array() / v1.position[3]; - p.row(1) = v2.position.array() / v2.position[3]; - p.row(2) = v3.position.array() / v3.position[3]; - - p.col(0) = ((p.col(0).array() + 1.0) / 2.0) * frameBuffer.rows(); - p.col(1) = ((p.col(1).array() + 1.0) / 2.0) * frameBuffer.cols(); - - int lx = std::floor(p.col(0).minCoeff()); - int ly = std::floor(p.col(1).minCoeff()); - int ux = std::ceil(p.col(0).maxCoeff()); - int uy = std::ceil(p.col(1).maxCoeff()); - - lx = std::min(std::max(lx, int(0)), int(frameBuffer.rows() - 1)); - ly = std::min(std::max(ly, int(0)), int(frameBuffer.cols() - 1)); - ux = std::max(std::min(ux, int(frameBuffer.rows() - 1)), int(0)); - uy = std::max(std::min(uy, int(frameBuffer.cols() - 1)), int(0)); - - Eigen::Matrix3d A; - A.col(0) = p.row(0).segment(0, 3); - A.col(1) = p.row(1).segment(0, 3); - A.col(2) = p.row(2).segment(0, 3); - A.row(2) << 1.0, 1.0, 1.0; - - Eigen::Matrix3d Ai = A.inverse(); - - for (unsigned i = lx; i <= ux; i++) - { - for (unsigned j = ly; j <= uy; j++) - { - - Eigen::Vector3d pixel(i + 0.5, j + 0.5, 1); - Eigen::Vector3d b = Ai * pixel; - if (b.minCoeff() >= 0) - { - VertexAttributes va = VertexAttributes::interpolate(v1, v2, v3, b[0], b[1], b[2]); - - if (va.position[2] >= -1 && va.position[2] <= 1) - { - FragmentAttributes frag = program.FragmentShader(va, uniform); - frameBuffer(i, j) = program.BlendingShader(frag, frameBuffer(i, j)); - } - } - } - } - } - - void rasterize_triangles(const Program &program, const UniformAttributes &uniform, const std::vector &vertices, Eigen::Matrix &frameBuffer) - { - std::vector v(vertices.size()); - for (unsigned i = 0; i < vertices.size(); i++) - v[i] = program.VertexShader(vertices[i], uniform); - - for (unsigned i = 0; i < vertices.size() / 3; i++) - rasterize_triangle(program, uniform, v[i * 3 + 0], v[i * 3 + 1], v[i * 3 + 2], frameBuffer); - } - - void rasterize_line(const Program &program, const UniformAttributes &uniform, const VertexAttributes &v1, const VertexAttributes &v2, double line_thickness, Eigen::Matrix &frameBuffer) - { - Eigen::Matrix p; - p.row(0) = v1.position.array() / v1.position[3]; - p.row(1) = v2.position.array() / v2.position[3]; - - p.col(0) = ((p.col(0).array() + 1.0) / 2.0) * frameBuffer.rows(); - p.col(1) = ((p.col(1).array() + 1.0) / 2.0) * frameBuffer.cols(); - - int lx = std::floor(p.col(0).minCoeff() - line_thickness); - int ly = std::floor(p.col(1).minCoeff() - line_thickness); - int ux = std::ceil(p.col(0).maxCoeff() + line_thickness); - int uy = std::ceil(p.col(1).maxCoeff() + line_thickness); - - lx = std::min(std::max(lx, int(0)), int(frameBuffer.rows() - 1)); - ly = std::min(std::max(ly, int(0)), int(frameBuffer.cols() - 1)); - ux = std::max(std::min(ux, int(frameBuffer.rows() - 1)), int(0)); - uy = std::max(std::min(uy, int(frameBuffer.cols() - 1)), int(0)); - - Eigen::Vector2f l1(p(0, 0), p(0, 1)); - Eigen::Vector2f l2(p(1, 0), p(1, 1)); - - double t = -1; - double ll = (l1 - l2).squaredNorm(); - - for (unsigned i = lx; i <= ux; i++) - { - for (unsigned j = ly; j <= uy; j++) - { - - Eigen::Vector2f pixel(i + 0.5, j + 0.5); - - if (ll == 0.0) - t = 0; - else - { - t = (pixel - l1).dot(l2 - l1) / ll; - t = std::fmax(0, std::fmin(1, t)); - } - - Eigen::Vector2f pixel_p = l1 + t * (l2 - l1); - - if ((pixel - pixel_p).squaredNorm() < (line_thickness * line_thickness)) - { - VertexAttributes va = VertexAttributes::interpolate(v1, v2, v1, 1 - t, t, 0); - FragmentAttributes frag = program.FragmentShader(va, uniform); - frameBuffer(i, j) = program.BlendingShader(frag, frameBuffer(i, j)); - } - } - } - } - - void rasterize_lines(const Program &program, const UniformAttributes &uniform, const std::vector &vertices, double line_thickness, Eigen::Matrix &frameBuffer) - { - std::vector v(vertices.size()); - for (unsigned i = 0; i < vertices.size(); i++) - v[i] = program.VertexShader(vertices[i], uniform); - - for (unsigned i = 0; i < vertices.size() / 2; i++) - rasterize_line(program, uniform, v[i * 2 + 0], v[i * 2 + 1], line_thickness, frameBuffer); - } - - void framebuffer_to_uint8(const Eigen::Matrix &frameBuffer, std::vector &image) - { - const int w = frameBuffer.rows(); - const int h = frameBuffer.cols(); - const int comp = 4; - const int stride_in_bytes = w * comp; - image.resize(w * h * comp, 0); - - for (unsigned wi = 0; wi < w; ++wi) - { - for (unsigned hi = 0; hi < h; ++hi) - { - unsigned hif = h - 1 - hi; - image[(hi * w * 4) + (wi * 4) + 0] = frameBuffer(wi, hif).color[0]; - image[(hi * w * 4) + (wi * 4) + 1] = frameBuffer(wi, hif).color[1]; - image[(hi * w * 4) + (wi * 4) + 2] = frameBuffer(wi, hif).color[2]; - image[(hi * w * 4) + (wi * 4) + 3] = frameBuffer(wi, hif).color[3]; - } - } - } -} \ No newline at end of file diff --git a/src/raster.hpp b/src/raster.hpp deleted file mode 100755 index 46edce1a..00000000 --- a/src/raster.hpp +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once - -#include -#include - -#include -#include - -namespace renderer -{ - struct Material - { - Eigen::Vector3d diffuse_color; - Eigen::Vector3d specular_color; - double specular_exponent; - }; - class VertexAttributes - { - public: - VertexAttributes(double x = 0, double y = 0, double z = 0, double w = 1) - { - position << x, y, z, w; - } - - static VertexAttributes interpolate( - const VertexAttributes &a, - const VertexAttributes &b, - const VertexAttributes &c, - const double alpha, - const double beta, - const double gamma) - { - VertexAttributes r; - r.position = alpha * (a.position / a.position(3)) + beta * (b.position / b.position(3)) + gamma * (c.position / c.position(3)); - r.color = alpha * a.color + beta * b.color + gamma * c.color; - return r; - } - - Eigen::Vector4d position; - Eigen::Vector3d normal; - Eigen::Vector3d color; - Material material; - }; - - class FragmentAttributes - { - public: - FragmentAttributes(double r = 0, double g = 0, double b = 0, double a = 1) - { - color << r, g, b, a; - } - double depth; - Eigen::Vector4d color; - }; - - class FrameBufferAttributes - { - public: - FrameBufferAttributes(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255) - { - color << r, g, b, a; - depth = 2; - } - double depth; - Eigen::Matrix color; - }; - - class UniformAttributes - { - public: - Eigen::Matrix4d M_cam; - - Eigen::Matrix4d M_orth; - Eigen::Matrix4d M; - }; - - class Program - { - public: - std::function VertexShader; - std::function FragmentShader; - std::function BlendingShader; - }; - - void rasterize_triangle(const Program &program, const UniformAttributes &uniform, const VertexAttributes &v1, const VertexAttributes &v2, const VertexAttributes &v3, Eigen::Matrix &frameBuffer); - void rasterize_triangles(const Program &program, const UniformAttributes &uniform, const std::vector &vertices, Eigen::Matrix &frameBuffer); - - void rasterize_line(const Program &program, const UniformAttributes &uniform, const VertexAttributes &v1, const VertexAttributes &v2, double line_thickness, Eigen::Matrix &frameBuffer); - void rasterize_lines(const Program &program, const UniformAttributes &uniform, const std::vector &vertices, double line_thickness, Eigen::Matrix &frameBuffer); - - void framebuffer_to_uint8(const Eigen::Matrix &frameBuffer, std::vector &image); -} diff --git a/test.py b/test.py deleted file mode 100644 index 748a7411..00000000 --- a/test.py +++ /dev/null @@ -1,45 +0,0 @@ -import polyfempy as pf -import json -import numpy as np - - -root = "/Users/teseo/Downloads" -with open(root + "/pushbox.json", "r") as f: - config = json.load(f) - -config["root_path"] = root + "/pushbox.json" - -dt = config["dt"] -t0 = config["t0"] - - -solver = pf.Solver() -solver.set_settings(json.dumps(config)) -solver.load_mesh_from_settings() - -# inits stuff -solver.init_timestepping(t0, dt) - -for i in range(1, 6): - # substepping - for t in range(1): - solver.step_in_time(t0, dt, t+1) - solver.update_dirichlet_boundary(1, [ - "0.5*t", - "0", - "0" - ]) - pixles = solver.render(width=84, - height=84, - camera_position=np.array([[0., 0., 0.]]), - camera_fov=90, - ambient_light=np.array([[0., 0., 0.]]), - diffuse_color=np.array([[1., 0., 0.]]), - specular_color=np.array([[1., 0., 0.]])) - break - - print(pixles) - t0 += dt - - -solver.export_vtu("xxx.vtu") diff --git a/test/__init__.py b/test/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/test/test_bending.py b/test/test_bending.py deleted file mode 100644 index 414a773d..00000000 --- a/test/test_bending.py +++ /dev/null @@ -1,57 +0,0 @@ -import unittest - -import platform -import polyfempy as pf -# from .utils import plot -import os - - -class BendingTest(unittest.TestCase): - def test_run(self): - return - root_folder = os.path.join("..", "data", "data") - - dir_path = os.path.dirname(os.path.realpath(__file__)) - mesh_path = os.path.join(dir_path, root_folder, "square_beam.mesh") - tag_path = os.path.join(dir_path, root_folder, "square_beam.txt") - - settings = pf.Settings(discr_order=1, pde=pf.PDEs.LinearElasticity) - - settings.set_material_params("E", 200000) - settings.set_material_params("nu", 0.35) - - settings.pde = pf.PDEs.LinearElasticity - - problem = pf.Problem() - problem.add_dirichlet_value(2, [0, 0, 0]) - problem.add_neumann_value(1, [0, -100, 0]) - - settings.problem = problem - - solver = pf.Solver() - - solver.settings(settings) - solver.load_mesh_from_path_and_tags( - mesh_path, tag_path, normalize_mesh=False, vismesh_rel_area=0.1) - - solver.solve() - - pts, tets, el_id, bid, disp = solver.get_sampled_solution() - vertices = pts + disp - mises, _ = solver.get_sampled_mises_avg() - - vs, fs, tr, stress, mises = solver.get_sampled_traction_forces() - assert(vs.shape[0] > 0) - assert(vs.shape[1] == 3) - - assert(fs.shape[0] > 0) - assert(fs.shape[1] == 3) - - assert(tr.shape[0] == fs.shape[0]) - assert(tr.shape[1] == 3) - - # plot(vertices, tets, mises) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_febio.py b/test/test_febio.py deleted file mode 100644 index 7e94d317..00000000 --- a/test/test_febio.py +++ /dev/null @@ -1,32 +0,0 @@ -import unittest - -import platform -import polyfempy as pf -# from .utils import plot -import os - - -class FeBioTest(unittest.TestCase): - def test_run(self): - root_folder = os.path.join("..", "data", "data") - - dir_path = os.path.dirname(os.path.realpath(__file__)) - febio_file = os.path.join(dir_path, root_folder, "test.feb") - - opts = { - "solver_type": "Eigen::SparseLU", - "solver_params": { - "gradNorm": 1e-1, - "nl_iterations": 10 - } - } - - pf.solve_febio( - febio_file, - output_path="test.vtu", - log_level=1, - **opts) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_gravity.py b/test/test_gravity.py deleted file mode 100644 index 2bb97b04..00000000 --- a/test/test_gravity.py +++ /dev/null @@ -1,68 +0,0 @@ -import unittest - -import numpy as np -import polyfempy as pf -# from .utils import plot - - -class Gravity(unittest.TestCase): - def test_run(self): - n_pts = 3 - - extend = np.linspace(0, 1, n_pts) - x, y = np.meshgrid(extend, extend, sparse=False, indexing='xy') - pts = np.column_stack((x.ravel(), y.ravel())) - - # Create connectivity - faces = np.ndarray([(n_pts-1)**2, 4],dtype=np.int32) - - index = 0 - for i in range(n_pts-1): - for j in range(n_pts-1): - faces[index, :] = np.array([ - j + i * n_pts, - j+1 + i * n_pts, - j+1 + (i+1) * n_pts, - j + (i+1) * n_pts - ]) - index = index + 1 - - # create settings - # We use a linear material model and linear elments - settings = pf.Settings(discr_order=1, pde=pf.PDEs.LinearElasticity) - - settings.set_material_params("E", 2100) - settings.set_material_params("nu", 0.3) - - problem = pf.Gravity(force=0.1) - settings.problem = problem - - solver = pf.Solver() - solver.settings(settings) - - # This time we are using pts and faces instead of loading from the disk - solver.set_mesh(pts, faces) - - solver.solve() - - #Animation frame, last one - frame = -1 - - # Get the solution - pts = solver.get_sampled_points_frames() - tets = solver.get_sampled_connectivity_frames() - disp = solver.get_sampled_solution_frames() - - - # diplace the mesh - vertices = pts[frame] + disp[frame] - - # and get the stresses - mises = solver.get_sampled_mises_avg_frames() - - # finally plot - # plot(vertices, tets[frame], mises[frame]) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_inflation.py b/test/test_inflation.py deleted file mode 100644 index ecbfcdc8..00000000 --- a/test/test_inflation.py +++ /dev/null @@ -1,85 +0,0 @@ -import unittest - -import polyfempy as pf -import numpy as np -import platform - -# from .utils import plot - -import os - - -class InflationTest(unittest.TestCase): - def test_run(self): - root_folder = os.path.join("..", "data", "data") - - solver = pf.Solver() - - # some setup - dir_path = os.path.dirname(os.path.realpath(__file__)) - mesh_path = os.path.join(dir_path, root_folder, "circle2.msh") - - settings = pf.Settings(discr_order=2, pde=pf.PDEs.Laplacian) - - problem = pf.Problem(rhs=0) - problem.add_dirichlet_value("all", 10) - settings.set_problem(problem) - - solver.settings(settings) - solver.load_mesh_from_path( - mesh_path, normalize_mesh=True, vismesh_rel_area=0.00001) - - solver.solve() - sol = solver.get_solution() - ########################################################################## - - # now we got the solution of the first laplacian, we use it as rhs for the second one - # setup zero bc and use sol as rhs - problem = pf.Problem(rhs=0) - problem.add_dirichlet_value("all", 0) - settings.problem = problem - - # reload the parameters and mesh - solver.settings(settings) - solver.load_mesh_from_path( - mesh_path, normalize_mesh=True, vismesh_rel_area=0.00001) - - # set the rhs as prev sol - solver.set_rhs(sol) - - solver.solve() - - # get the solution on a densly sampled mesh - vertices, tris, el_id, bid, sol = solver.get_sampled_solution() - - # the dense mesh is disconnected, so we need to connecit it back - _, res = np.unique(vertices, axis=0, return_inverse=True) - vertices, resi = np.unique(vertices, axis=0, return_index=True) - - faces = np.ndarray([len(tris), 3], dtype=np.int64) - vv = np.ndarray([len(vertices), 3], dtype=np.float64) - - for i in range(len(tris)): - faces[i] = np.array( - [res[tris[i][0]], res[tris[i][1]], res[tris[i][2]]]) - - for i in range(len(vv)): - vv[i] = np.array([vertices[i][0], vertices[i][1], sol[resi[i]][0]]) - - # plot(vv, faces, None) - - # #save obj - # with open(output, "w") as file: - # # use sol as z - # for i in range(len(vertices)): - # file.write("v {} {} {}\n".format()) - - # for i in range(len(tris)): - # i0 = res[tris[i][0]] - # i1 = res[tris[i][1]] - # i2 = res[tris[i][2]] - # file.write("f {} {} {}\n".format(i0+1, i1+1, i2+1)) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_plane_hole.py b/test/test_plane_hole.py deleted file mode 100644 index 83d7b579..00000000 --- a/test/test_plane_hole.py +++ /dev/null @@ -1,53 +0,0 @@ -import unittest - -import polyfempy as pf -# from .utils import plot -import os -import platform - - -class BendingTest(unittest.TestCase): - def test_run(self): - # self.run_one(1) - # self.run_one(2) - - # def run_one(self, discr_order): - discr_order = 2 - root_folder = os.path.join("..", "data", "data") - - dir_path = os.path.dirname(os.path.realpath(__file__)) - mesh_path = os.path.join(dir_path, root_folder, "plane_hole.obj") - - settings = pf.Settings(discr_order=discr_order, - pde=pf.PDEs.LinearElasticity) - - settings.set_material_params("E", 210000) - settings.set_material_params("nu", 0.3) - - problem = pf.Problem() - problem.set_x_symmetric(1) - problem.set_y_symmetric(4) - - problem.add_neumann_value(3, [100, 0]) - # problem.add_neumann_value(3, lambda x,y,z: [100, 0, 0]) - - settings.problem = problem - - solver = pf.Solver() - - solver.settings(settings) - solver.load_mesh_from_path(mesh_path, normalize_mesh=True) - - solver.solve() - - pts, tets, el_id, bid, disp = solver.get_sampled_solution() - vertices = pts + disp - mises, _ = solver.get_sampled_mises_avg() - - solver.compute_errors() - - # plot(vertices, tets, mises) - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_pythonic.py b/test/test_pythonic.py deleted file mode 100644 index 27c2db35..00000000 --- a/test/test_pythonic.py +++ /dev/null @@ -1,54 +0,0 @@ -import unittest - -import numpy as np -import polyfempy as pf -# from .utils import plot - - -class PythonicTest(unittest.TestCase): - def test_run(self): - n_pts = 3 - - extend = np.linspace(0, 1, n_pts) - x, y = np.meshgrid(extend, extend, sparse=False, indexing='xy') - pts = np.column_stack((x.ravel(), y.ravel())) - - # Create connectivity - faces = np.ndarray([(n_pts-1)**2, 4], dtype=np.int32) - - index = 0 - for i in range(n_pts-1): - for j in range(n_pts-1): - faces[index, :] = np.array([ - j + i * n_pts, - j+1 + i * n_pts, - j+1 + (i+1) * n_pts, - j + (i+1) * n_pts - ]) - index = index + 1 - - def sideset(p): - if p[0] <= 0.001: - return 4 - return 1 - - solver = pf.solve( - vertices=pts, - cells=faces, - sidesets_func=sideset, - diriclet_bc=[{"id": 4, "value": [0, 0]}], - materials=[{"id": 0, "E": 2100, "nu": 0.3}], - rhs=[0, 0.1], - pde=pf.PDEs.LinearElasticity, - discr_order=1 - ) - - log = solver.get_log() - print(log["time_solving"]) - - # Get the solution - pts, tris, el_id, bid, fun = solver.get_sampled_solution() - - -if __name__ == '__main__': - unittest.main() diff --git a/test/test_torsion.py b/test/test_torsion.py deleted file mode 100644 index 29977523..00000000 --- a/test/test_torsion.py +++ /dev/null @@ -1,41 +0,0 @@ -import unittest - -import polyfempy as pf -# from .utils import plot - -import os -import platform - - -class TorsionTest(unittest.TestCase): - def test_run(self): - root_folder = os.path.join("..", "data", "data") - dir_path = os.path.dirname(os.path.realpath(__file__)) - mesh_path = os.path.join(dir_path, root_folder, "square_beam_h.HYBRID") - - settings = pf.Settings( - discr_order=1, pde=pf.PDEs.NonLinearElasticity, nl_solver_rhs_steps=5) - - settings.set_material_params("E", 200) - settings.set_material_params("nu", 0.35) - - problem = pf.Torsion( - fixed_boundary=5, turning_boundary=6, axis_coordiante=2, n_turns=0.5) - settings.problem = problem - - solver = pf.Solver() - solver.settings(settings) - solver.load_mesh_from_path( - mesh_path, normalize_mesh=False, vismesh_rel_area=0.001) - - solver.solve() - - pts, tets, el_id, bid, disp = solver.get_sampled_solution() - vertices = pts + disp - mises, _ = solver.get_sampled_mises_avg() - - # plot(vertices, tets, mises) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..882564b9 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,8 @@ +"""Options for tests that use an existing native build.""" + + +def pytest_addoption(parser): + parser.addoption( + "--backend-package-dir", + help="Package root containing polyfempy and the native backend to test.", + ) diff --git a/tests/test_api_errors.py b/tests/test_api_errors.py new file mode 100644 index 00000000..5e9eda34 --- /dev/null +++ b/tests/test_api_errors.py @@ -0,0 +1,17 @@ +"""Invalid user inputs should produce useful errors without a native solve.""" + + +import pytest + +from polyfempy import solve + + +def test_config_path_errors_name_the_file(tmp_path): + missing = tmp_path / "missing.json" + with pytest.raises(FileNotFoundError) as error: + solve(cfg=missing) + assert str(missing) in str(error.value) + bad = tmp_path / "bad.json" + bad.write_text('{"geometry": }', encoding="utf-8") + with pytest.raises(ValueError, match="line 1 column") as error: + solve(cfg=bad) diff --git a/tests/test_backend_smoke.py b/tests/test_backend_smoke.py new file mode 100644 index 00000000..b2cab597 --- /dev/null +++ b/tests/test_backend_smoke.py @@ -0,0 +1,144 @@ +from pathlib import Path +import json +import subprocess +import sys + +import pytest + + +_BACKEND_RUNNER = """ +import hashlib +import importlib +import json +from importlib.machinery import EXTENSION_SUFFIXES +from pathlib import Path +import sys + +package_dir = Path(sys.argv[1]).resolve() +expected_package = package_dir / "polyfempy" / "__init__.py" +if not expected_package.is_file(): + raise RuntimeError(f"Selected package is missing: {expected_package}") +sys.path.insert(0, str(package_dir)) +import polyfempy as pf + +package_path = Path(pf.__file__).resolve() +if package_path != expected_package.resolve(): + raise RuntimeError(f"Loaded package {package_path}; expected {expected_package}") +try: + native = importlib.import_module("polyfempy.polyfempy") +except ImportError as exc: + raise RuntimeError(f"Native backend is unavailable: {exc}") from exc +native_path = Path(native.__file__).resolve() +if native_path.parent != expected_package.parent.resolve(): + raise RuntimeError(f"Loaded backend outside selected package: {native_path}") +if not any(native_path.name.endswith(suffix) for suffix in EXTENSION_SUFFIXES): + raise RuntimeError(f"Expected a compiled native extension: {native_path}") + +digest = hashlib.sha256() +with native_path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) +info = {"package": str(package_path), "native": str(native_path), "sha256": digest.hexdigest()} +expected = json.loads(sys.argv[2]) +if expected is not None and info != expected: + raise RuntimeError(f"Native backend changed between probe and solve: expected {expected}, got {info}") +print(json.dumps(info), flush=True) + +if len(sys.argv) > 3: + # Reference JSON goes directly to the native solver, independently of builders. + values = sys.argv[3:] + config = Path(values[1]).resolve() + payload = json.loads(config.read_text()) + payload["root_path"] = str(config) + payload.setdefault("output", {})["directory"] = values[values.index("--output-dir") + 1] if "--output-dir" in values else "." + solver = native.Solver() + solver.set_settings(json.dumps(payload), strict_validation=True) + solver.load_mesh_from_settings() + solver.solve() +""" + + +def _run_backend(package_dir, args, *, cwd, expected_backend=None): + # -I ignores PYTHONPATH, the working directory, and user site-packages. + return subprocess.run( + [ + sys.executable, "-I", "-c", _BACKEND_RUNNER, + str(Path(package_dir).resolve()), json.dumps(expected_backend), *args, + ], + cwd=cwd, + capture_output=True, + text=True, + check=False, + ) + + +def _load_expected_error_metrics(config_path: Path) -> tuple[dict[str, float], float]: + payload = json.loads(config_path.read_text(encoding="utf-8")) + tests = payload.get("tests") + if not isinstance(tests, dict): + raise AssertionError(f"backend smoke config has no tests block: {config_path}") + + margin = float(tests.get("margin", 1e-8)) + expected = { + key: float(value) + for key, value in tests.items() + if key.startswith("err_") and isinstance(value, (int, float)) + } + if not expected: + raise AssertionError(f"backend smoke config has no err_* test metrics: {config_path}") + return expected, margin + + +def _load_actual_error_metrics(output_dir: Path) -> dict[str, float]: + stats_path = output_dir / "sim.json" + if not stats_path.exists(): + raise AssertionError(f"backend did not write expected stats file: {stats_path}") + + payload = json.loads(stats_path.read_text(encoding="utf-8")) + return { + key: float(value) + for key, value in payload.items() + if key.startswith("err_") and isinstance(value, (int, float)) + } + + +def test_backend_forward_solve_smoke(tmp_path, pytestconfig): + package_dir = pytestconfig.getoption("backend_package_dir") + if package_dir is None: + pytest.skip("Select the build to test with --backend-package-dir; no backend is chosen automatically.") + root = Path(__file__).resolve().parents[1] + backend_info = _run_backend(package_dir, [], cwd=tmp_path) + assert backend_info.returncode == 0, backend_info.stdout + backend_info.stderr + selected_backend = json.loads(backend_info.stdout) + print(f"Native backend: {selected_backend['native']}") + print(f"SHA-256: {selected_backend['sha256']}") + + config_path = root / "polyfem-data" / "units" / "neohookean.json" + assert config_path.is_file(), f"Backend smoke config is missing: {config_path}. Initialize polyfem-data." + expected_metrics, margin = _load_expected_error_metrics(config_path) + + output_dir = tmp_path / "backend_smoke" + result = _run_backend( + package_dir, + [ + "solve", + str(config_path), + "--output-dir", + str(output_dir), + "--log-level", + "2", + "--max-threads", + "1", + ], + cwd=tmp_path, + expected_backend=selected_backend, + ) + + assert result.returncode == 0, result.stdout + result.stderr + assert output_dir.exists() + assert any(output_dir.iterdir()) + + actual_metrics = _load_actual_error_metrics(output_dir) + for key, expected_value in expected_metrics.items(): + assert key in actual_metrics + assert abs(actual_metrics[key] - expected_value) <= margin diff --git a/tests/test_backend_smoke_selection.py b/tests/test_backend_smoke_selection.py new file mode 100644 index 00000000..e5c9cf21 --- /dev/null +++ b/tests/test_backend_smoke_selection.py @@ -0,0 +1,114 @@ +"""Check smoke-test backend selection without compiling native code.""" + +import hashlib +import importlib.util +from importlib.machinery import EXTENSION_SUFFIXES +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + + +@pytest.fixture +def smoke(): + path = Path(__file__).with_name("test_backend_smoke.py") + spec = importlib.util.spec_from_file_location("backend_smoke_for_test", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _fake_package(root, marker="selected", *, native_path=None, available=True): + package = root / "polyfempy" + package.mkdir(parents=True) + native = native_path or package / ("polyfempy" + EXTENSION_SUFFIXES[0]) + native.write_bytes(b"native test fixture") + (package / "__init__.py").write_text( + "import sys\nfrom types import SimpleNamespace\n" + + (f"sys.modules[__name__ + '.polyfempy'] = SimpleNamespace(__file__={str(native)!r})\n" if available else ""), + encoding="utf-8", + ) + return native + + +def test_selected_build_wins_over_pythonpath_and_working_directory(smoke, tmp_path, monkeypatch): + selected = tmp_path / "current build" + native = _fake_package(selected) + old_env = tmp_path / "old-env" + old_cwd = tmp_path / "old-cwd" + _fake_package(old_env, "OLD_ENV_USED") + _fake_package(old_cwd, "OLD_CWD_USED") + monkeypatch.setenv("PYTHONPATH", str(old_env)) + + probe = smoke._run_backend(selected, [], cwd=old_cwd) + assert probe.returncode == 0, probe.stderr + info = json.loads(probe.stdout) + assert Path(info["native"]) == native.resolve() + assert info["sha256"] == hashlib.sha256(native.read_bytes()).hexdigest() + + + +def test_missing_selection_skips_without_probing_a_backend(smoke, tmp_path, monkeypatch): + def unexpected_probe(*args, **kwargs): + raise AssertionError("A backend must not be selected automatically.") + + monkeypatch.setattr(smoke, "_run_backend", unexpected_probe) + config = SimpleNamespace(getoption=lambda name: None) + with pytest.raises(pytest.skip.Exception, match="--backend-package-dir"): + smoke.test_backend_forward_solve_smoke(tmp_path, config) + + +def test_missing_selected_package_fails_instead_of_falling_back(smoke, tmp_path, monkeypatch): + _fake_package(tmp_path / "old") + monkeypatch.setenv("PYTHONPATH", str(tmp_path / "old")) + config = SimpleNamespace(getoption=lambda name: str(tmp_path / "missing")) + + with pytest.raises(AssertionError, match="Selected package is missing"): + smoke.test_backend_forward_solve_smoke(tmp_path, config) + + +def test_unavailable_selected_backend_fails_instead_of_skipping(smoke, tmp_path): + selected = tmp_path / "selected" + _fake_package(selected, available=False) + config = SimpleNamespace(getoption=lambda name: str(selected)) + + with pytest.raises(AssertionError, match="Native backend is unavailable"): + smoke.test_backend_forward_solve_smoke(tmp_path, config) + + +def test_backend_outside_selected_package_is_rejected(smoke, tmp_path): + selected = tmp_path / "selected" + old_native = tmp_path / ("old" + EXTENSION_SUFFIXES[0]) + _fake_package(selected, native_path=old_native) + + result = smoke._run_backend(selected, [], cwd=tmp_path) + + assert result.returncode != 0 + assert "Loaded backend outside selected package" in result.stderr + + +def test_python_module_cannot_stand_in_for_native_backend(smoke, tmp_path): + selected = tmp_path / "selected" + _fake_package(selected, native_path=selected / "polyfempy" / "polyfempy.py") + + result = smoke._run_backend(selected, [], cwd=tmp_path) + + assert result.returncode != 0 + assert "Expected a compiled native extension" in result.stderr + + +def test_changed_binary_is_rejected_before_solve(smoke, tmp_path): + selected = tmp_path / "selected" + native = _fake_package(selected, "SOLVE_MUST_NOT_RUN") + probe = smoke._run_backend(selected, [], cwd=tmp_path) + assert probe.returncode == 0, probe.stderr + info = json.loads(probe.stdout) + native.write_bytes(b"a different native build") + + result = smoke._run_backend(selected, ["solve"], cwd=tmp_path, expected_backend=info) + + assert result.returncode != 0 + assert "Native backend changed between probe and solve" in result.stderr + assert "SOLVE_MUST_NOT_RUN" not in result.stdout diff --git a/tests/test_config_resource_paths.py b/tests/test_config_resource_paths.py new file mode 100644 index 00000000..f3413ecc --- /dev/null +++ b/tests/test_config_resource_paths.py @@ -0,0 +1,33 @@ +"""PolyFEM resolves mesh and selection resources from the JSON file's directory.""" + +import json + +import numpy as np +import pytest + +from polyfempy import solve + + +@pytest.mark.parametrize("geometry_list", [False, True]) +def test_backend_resolves_config_resources(tmp_path, monkeypatch, geometry_list): + pytest.importorskip("polyfempy.polyfempy") + config_dir = tmp_path / "inputs" + config_dir.mkdir() + (config_dir / "square.obj").write_text( + "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv .5 .5 0\n" + "f 1 2 5\nf 2 3 5\nf 3 4 5\nf 4 1 5\n") + (config_dir / "volume.txt").write_text("1\n1\n1\n1\n") + geometry = {"mesh": "square.obj", "volume_selection": "volume.txt"} + cfg = { + "geometry": [geometry] if geometry_list else geometry, + "materials": [{"id": 1, "type": "NeoHookean", "E": 1000, "nu": 0.3}], + "boundary_conditions": {"dirichlet_boundary": [{"id": "all", "value": [0, 0]}], "rhs": [0, -1]}, + "solver": {"linear": {"solver": "Eigen::SimplicialLDLT"}}, + "output": {"log": {"level": "off", "path": ""}}, + } + path = config_dir / "simulation.json" + path.write_text(json.dumps(cfg)) + monkeypatch.chdir(tmp_path) + result = solve(cfg=path) + assert np.isfinite(result.sol).all() + assert abs(result.sol).max() > 1e-6 diff --git a/tests/test_contact_regressions.py b/tests/test_contact_regressions.py new file mode 100644 index 00000000..ca75ff94 --- /dev/null +++ b/tests/test_contact_regressions.py @@ -0,0 +1,85 @@ +"""Opt-in native parity checks for the backend's active contact cases.""" + +from functools import lru_cache +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +from polyfempy.solve import _config +from test_generated_api_example import _all_example_cases, _import_example, _load_source_config + +ROOT = Path(__file__).resolve().parents[1] +BACKEND = None +for cache in sorted((ROOT / "build").glob("*/CMakeCache.txt"), key=lambda p: p.stat().st_mtime, reverse=True): + for line in cache.read_text().splitlines(): + if line.startswith("CPM_PACKAGE_polyfem_SOURCE_DIR:INTERNAL="): + BACKEND = Path(line.partition("=")[2]) + break + if BACKEND is not None: + break +CASES = [] +for name in ("contact_2d.txt", "contact_3d.txt"): + listing = BACKEND / "tests" / name if BACKEND else ROOT / "missing-backend" + if listing.exists(): + CASES.extend(line.strip() for line in listing.read_text().splitlines() + if line.strip().startswith("contact/examples/")) + + +@lru_cache(maxsize=1) +def example_map(): + return {source: example for example, source in _all_example_cases()} + + +RUN = """ +import json, sys +from pathlib import Path +from polyfempy import solve +from polyfempy.polyfempy import Solver +workspace = Path(sys.argv[1]) +for label in ('generated', 'source'): + payload = json.loads((workspace / (label + '.json')).read_text()) + if label == 'generated': + solve(cfg=payload) + else: + solver = Solver() + solver.set_settings(json.dumps(payload), strict_validation=True) + solver.load_mesh_from_settings() + solver.solve() +""" + + +@pytest.mark.contact +@pytest.mark.parametrize("case", CASES, ids=lambda case: case.removeprefix("contact/examples/")) +def test_contact_api_matches_source_json(case, tmp_path): + source = (ROOT / "polyfem-data" / case).resolve() + if not source.exists(): + pytest.skip("Initialize polyfem-data for native contact regressions") + probe = subprocess.run([sys.executable, "-I", "-c", "from polyfempy.polyfempy import Solver"], + capture_output=True, text=True) + assert probe.returncode == 0, "Install the native package before running contact regressions: " + probe.stderr + generated = _import_example(example_map()[source]).polyfem_config.as_dict() + reference = _load_source_config(source) + steps = json.loads(source.read_text()).get("tests", {}).get("time_steps", 1) + for label, payload in (("generated", generated), ("source", reference)): + payload = _config(dict(payload, root_path=str(source))) + time = payload.get("time") + if time: + dt = time.get("dt") + if dt is None: + dt = (time["tend"] - time.get("t0", 0)) / time["time_steps"] + time.update(dt=dt, time_steps=steps, tend=time.get("t0", 0) + steps * dt) + payload.setdefault("solver", {}).update(linear={"solver": "Eigen::SimplicialLDLT"}, max_threads=1) + payload["output"] = {"directory": str(tmp_path / label), "json": "sim.json"} + (tmp_path / (label + ".json")).write_text(json.dumps(payload)) + result = subprocess.run([sys.executable, "-I", "-c", RUN, str(tmp_path)], + capture_output=True, text=True, timeout=360, cwd=tmp_path) + assert result.returncode == 0, result.stdout + result.stderr + generated_metrics = json.loads((tmp_path / "generated/sim.json").read_text()) + source_metrics = json.loads((tmp_path / "source/sim.json").read_text()) + keys = [key for key in source_metrics if key.startswith("err_")] + assert keys, "Native solver did not report error metrics" + for key in keys: + assert generated_metrics[key] == pytest.approx(source_metrics[key], rel=1e-5, abs=1e-12) diff --git a/tests/test_examples_public_surface.py b/tests/test_examples_public_surface.py new file mode 100644 index 00000000..26894744 --- /dev/null +++ b/tests/test_examples_public_surface.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLES = ROOT / "examples" +CLASSIC_EXAMPLES = EXAMPLES / "classic_example" + + +def _require_examples_submodule() -> None: + if not CLASSIC_EXAMPLES.exists(): + pytest.skip( + "examples submodule is not initialized; run " + "`git submodule update --init examples`" + ) + + +def _example_source_files() -> list[Path]: + _require_examples_submodule() + return sorted(path for path in EXAMPLES.rglob("*.py") if path.is_file()) + + +def test_examples_do_not_reintroduce_removed_impact_template_name(): + offenders = [] + for path in _example_source_files(): + text = path.read_text(encoding="utf-8") + if "make_impact_template" in text: + offenders.append(path.relative_to(ROOT).as_posix()) + + assert offenders == [] + + +def test_classic_examples_use_generated_api_helpers_only(): + expected = { + "examples/classic_example/2D/_contact_2d_common.py", + "examples/classic_example/2D/contact_2d_friction_circle_rollers_generated_api.py", + "examples/classic_example/2D/contact_2d_golf_ball_deformable_wall_generated_api.py", + "examples/classic_example/2D/contact_2d_golf_ball_generated_api.py", + "examples/classic_example/3D/_contact_3d_common.py", + "examples/classic_example/3D/contact_3d_friction_high_school_slopetest_generated_api.py", + "examples/classic_example/3D/contact_3d_golf_ball_generated_api.py", + "examples/classic_example/3D/contact_3d_large_ratios_sphere_mat_generated_api.py", + } + actual = {path.relative_to(ROOT).as_posix() for path in _example_source_files()} + assert expected <= actual + + +def test_classic_examples_do_not_import_legacy_api_package(): + offenders = [] + for path in _example_source_files(): + text = path.read_text(encoding="utf-8") + if "polyfempy.api" in text: + offenders.append(path.relative_to(ROOT).as_posix()) + + assert offenders == [] + + +def test_classic_examples_import_public_polyfem(): + _require_examples_submodule() + for example in CLASSIC_EXAMPLES.glob("[23]D/*_generated_api.py"): + lines = example.read_text(encoding="utf-8").splitlines() + assert "import polyfem" in lines + + +def test_classic_examples_keep_solver_and_output_explicit(): + offenders = [] + for path in _example_source_files(): + text = path.read_text(encoding="utf-8") + if "common_solver" in text or "common_output" in text: + offenders.append(path.relative_to(ROOT).as_posix()) + + assert offenders == [] diff --git a/tests/test_generate_polyfem_api.py b/tests/test_generate_polyfem_api.py new file mode 100644 index 00000000..f4999489 --- /dev/null +++ b/tests/test_generate_polyfem_api.py @@ -0,0 +1,42 @@ +"""Keep generated exports deterministic and linked schemas pinned.""" + +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def workflow(): + spec = importlib.util.spec_from_file_location("generate_api", ROOT / "tools/generate_polyfem_api.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_schema_cache_tracks_backend_revision(tmp_path, monkeypatch): + module = workflow() + monkeypatch.setattr(module, "POLYSOLVE_SPEC_CACHE_DIR", tmp_path / "cache") + recipe = tmp_path / "polyfem/cmake/recipes/polysolve.cmake" + recipe.parent.mkdir(parents=True) + downloads = [] + def download(url, target): + downloads.append(url) + Path(target).write_text("{}") + monkeypatch.setattr(module.urllib.request, "urlretrieve", download) + for revision in ("abc123", "def456", "abc123"): + recipe.write_text(f'CPMAddPackage("gh:polyfem/polysolve#{revision}")') + assert module._cache_polysolve_solver_specs(tmp_path / "polyfem") == tmp_path / "cache" / revision + assert len(downloads) == 4 + assert all("/abc123/" in url or "/def456/" in url for url in downloads) + + +def test_generated_exports_hide_implementation_imports_and_are_idempotent(tmp_path, monkeypatch): + module = workflow() + monkeypatch.setattr(module, "GENERATED_DIR", tmp_path) + api = tmp_path / "generated_api.py" + api.write_text("from pathlib import Path\nfrom .generated_class import Root\ndef model(): pass\ndef _private(): pass\n") + module.write_public_exports() + first = api.read_text() + module.write_public_exports() + assert api.read_text() == first + assert "__all__ = ['Root', 'model']" in first diff --git a/tests/test_generated_api_example.py b/tests/test_generated_api_example.py new file mode 100644 index 00000000..e43b04dd --- /dev/null +++ b/tests/test_generated_api_example.py @@ -0,0 +1,1140 @@ +"""Smoke and source-parity tests for classic generated API examples.""" + +from __future__ import annotations + +import copy +import importlib.util +import json +import py_compile +import sys +from pathlib import Path +from typing import Any + +import pytest + +from polyfempy.solve import _config +from polyfempy.generated_api import generated_api as polyfem + + +ROOT = Path(__file__).resolve().parents[1] +CLASSIC_EXAMPLES = ROOT / "examples" / "classic_example" +POLYFEM_DATA_CONTACT = ROOT / "polyfem-data" / "contact" +POLYFEM_DATA_EXAMPLES = POLYFEM_DATA_CONTACT / "examples" + +EXAMPLE_CASES = [ + ( + CLASSIC_EXAMPLES / "2D" / "contact_2d_golf_ball_generated_api.py", + POLYFEM_DATA_EXAMPLES / "2D" / "golf-ball.json", + ), + ( + CLASSIC_EXAMPLES + / "2D" + / "contact_2d_golf_ball_deformable_wall_generated_api.py", + POLYFEM_DATA_EXAMPLES / "2D" / "golf-ball-doformable-wall.json", + ), + ( + CLASSIC_EXAMPLES / "2D" / "contact_2d_friction_circle_rollers_generated_api.py", + POLYFEM_DATA_EXAMPLES / "2D" / "friction" / "circle-rollers.json", + ), + ( + CLASSIC_EXAMPLES / "3D" / "contact_3d_golf_ball_generated_api.py", + POLYFEM_DATA_EXAMPLES / "3D" / "golf-ball.json", + ), + ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_friction_high_school_slopetest_generated_api.py", + POLYFEM_DATA_EXAMPLES + / "3D" + / "friction" + / "high-school-physics-slopetest-mu=0.50.json", + ), + ( + CLASSIC_EXAMPLES / "3D" / "contact_3d_large_ratios_sphere_mat_generated_api.py", + POLYFEM_DATA_EXAMPLES / "3D" / "large-ratios" / "sphere-mat.json", + ), +] + +DOLPHIN_MATERIAL_SHAPE_CASES = [ + ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_stress_tests_dolphin_funnel_generated_api.py", + POLYFEM_DATA_EXAMPLES / "3D" / "stress-tests" / "dolphin-funnel.json", + ), + ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_stress_tests_dolphin_funnel_linf_generated_api.py", + POLYFEM_DATA_EXAMPLES / "3D" / "stress-tests" / "dolphin-funnel-Linf.json", + ), +] + +EXPECTED_GENERATED_API_FALLBACK_SOURCES: set[str] = set() + + +def _ordinary_contact_source_paths() -> set[Path]: + sources: set[Path] = set() + for dim in ("2D", "3D"): + for path in (POLYFEM_DATA_EXAMPLES / dim).rglob("*.json"): + if _is_auxiliary_contact_json(path): + continue + sources.add(path.resolve()) + return sources + + +def _is_auxiliary_contact_json(path: Path) -> bool: + return ( + path.name == "common.json" + or path.name.endswith("-common.json") + ) + + +def _generated_example_files() -> list[Path]: + return sorted(CLASSIC_EXAMPLES.glob("[23]D/contact_*_generated_api.py")) + + +def _declared_source_paths() -> set[Path]: + return { + Path(_import_example(path).SOURCE_JSON).resolve() + for path in _generated_example_files() + } + + +def _all_example_cases() -> list[tuple[Path, Path]]: + cases = [] + for example_path in _generated_example_files(): + example = _import_example(example_path) + cases.append((example_path, Path(example.SOURCE_JSON).resolve())) + return cases + + +def _builder_safe_source_paths() -> set[Path]: + safe = set() + for source_path in _ordinary_contact_source_paths(): + config = _load_source_config(source_path) + try: + polyfem.config(**copy.deepcopy(config)) + except TypeError: + continue + if _is_builder_safe_config(config): + safe.add(source_path) + return safe + + +def _is_builder_safe_config(config: dict[str, Any]) -> bool: + geometry = config.get("geometry") + if not isinstance(geometry, list): + return False + if any( + not isinstance(item, dict) + or item.get("type") not in ("mesh", "mesh_array", "mesh_sequence") + for item in geometry + ): + return False + + normal_geometry = [item for item in geometry if not item.get("is_obstacle")] + if any( + "volume_selection" in item + and ( + not isinstance(item.get("volume_selection"), int) + or item.get("volume_selection") <= 0 + ) + for item in normal_geometry + ): + return False + volume_geometry = [ + item for item in normal_geometry + if isinstance(item.get("volume_selection"), int) + and item.get("volume_selection") > 0 + ] + obstacle_surface_ids = { + item.get("surface_selection") + for item in geometry + if item.get("is_obstacle") + and isinstance(item.get("surface_selection"), int) + and item.get("surface_selection") > 0 + } + if any( + item.get("is_obstacle") + and item.get("point_selection") not in (None, 0) + for item in geometry + ): + return False + + volume_ids = { + item.get("volume_selection") + for item in volume_geometry + if isinstance(item.get("volume_selection"), int) + and item.get("volume_selection") > 0 + } + if not all(item.get("volume_selection") in volume_ids for item in volume_geometry): + return False + + materials = _optional_items(config.get("materials")) + if any(not isinstance(item, dict) for item in materials): + return False + id_materials = [item for item in materials if "id" in item] + if any(item.get("id") not in volume_ids for item in id_materials): + return False + + selection_ids = _builder_selection_ids(geometry) + if selection_ids is None: + return False + if not _builder_safe_boundary_conditions( + config.get("boundary_conditions"), + selection_ids, + obstacle_surface_ids, + ): + return False + return _builder_safe_initial_conditions( + config.get("initial_conditions"), + volume_ids, + ) + + +def _builder_selection_ids(geometry: list[dict[str, Any]]) -> set[int] | None: + selection_ids = set() + for item in geometry: + for field in ("surface_selection", "point_selection"): + value = item.get(field) + if value is None: + continue + if isinstance(value, int): + if value > 0: + selection_ids.add(value) + continue + if isinstance(value, dict): + items = [value] + elif isinstance(value, list): + items = value + else: + return None + for selection in items: + if not isinstance(selection, dict): + return None + selection_id = selection.get("id") + if not isinstance(selection_id, int) or selection_id <= 0: + return None + selection_ids.add(selection_id) + return selection_ids + + +def _builder_safe_boundary_conditions( + boundary_conditions: Any, + selection_ids: set[int], + obstacle_surface_ids: set[int], +) -> bool: + if boundary_conditions is None: + return True + if not isinstance(boundary_conditions, dict): + return False + + bindable = { + "dirichlet_boundary", + "neumann_boundary", + "normal_aligned_neumann_boundary", + "pressure_boundary", + "pressure_cavity", + "obstacle_displacements", + } + if any(key not in {"rhs", *bindable} for key in boundary_conditions): + return False + + for section in bindable: + for item in _optional_items(boundary_conditions.get(section)): + if not isinstance(item, dict): + return False + expected_ids = ( + obstacle_surface_ids + if section == "obstacle_displacements" + else selection_ids + ) + if item.get("id") not in expected_ids: + return False + return True + + +def _builder_safe_initial_conditions( + initial_conditions: Any, + volume_ids: set[int], +) -> bool: + if initial_conditions is None: + return True + if not isinstance(initial_conditions, dict): + return False + + bindable = {"velocity", "solution", "acceleration"} + if any(key not in bindable for key in initial_conditions): + return False + + for section in bindable: + for item in _optional_items(initial_conditions.get(section)): + if not isinstance(item, dict) or item.get("id") not in volume_ids: + return False + return True + + +def _optional_items(value: Any) -> list[Any]: + if value is None: + return [] + return value if isinstance(value, list) else [value] + + +def _case_id(case: tuple[Path, Path]) -> str: + example_path, _source_path = case + return example_path.stem + + +def _require_examples_submodule() -> None: + if not CLASSIC_EXAMPLES.exists(): + pytest.skip( + "examples submodule is not initialized; run " + "`git submodule update --init examples`" + ) + + +def _require_polyfem_data_submodule() -> None: + if not POLYFEM_DATA_EXAMPLES.exists(): + pytest.skip( + "polyfem-data submodule is not initialized; run " + "`git submodule update --init polyfem-data`" + ) + + +@pytest.fixture(autouse=True) +def _skip_without_required_submodules(): + _require_examples_submodule() + _require_polyfem_data_submodule() + + +def test_classic_generated_examples_cover_all_contact_source_jsons(): + assert _declared_source_paths() == _ordinary_contact_source_paths() + + +def test_classic_generated_examples_show_api_configuration(): + offenders = [] + fallback_sources = { + (POLYFEM_DATA_EXAMPLES / source).resolve() + for source in EXPECTED_GENERATED_API_FALLBACK_SOURCES + } + for example_path, source_path in _all_example_cases(): + text = example_path.read_text(encoding="utf-8") + has_constructor_config = ( + "polyfem.config(" in text or "model.config(" in text + ) + has_known_fallback = ( + source_path in fallback_sources and "SourcePayloadConfig(" in text + ) + if "load_polyfem_config(SOURCE_JSON)" in text: + offenders.append(example_path.relative_to(ROOT).as_posix()) + elif not has_constructor_config and not has_known_fallback: + offenders.append(example_path.relative_to(ROOT).as_posix()) + + assert offenders == [] + + +def test_builder_safe_classic_examples_use_model_builder(): + offenders = [] + builder_safe_sources = _builder_safe_source_paths() + for example_path, source_path in _all_example_cases(): + if source_path not in builder_safe_sources: + continue + text = example_path.read_text(encoding="utf-8") + if "model = polyfem.model()" not in text or "polyfem_config = model.config(" not in text: + offenders.append(example_path.relative_to(ROOT).as_posix()) + + assert offenders == [] + + +def test_obstacle_mesh_classic_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "2D" + / "contact_2d_unit_tests_erleben_spikes_generated_api.py" + ) + source_path = ( + POLYFEM_DATA_EXAMPLES + / "2D" + / "unit-tests" + / "erleben" + / "spikes.json" + ) + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert "polyfem_config = model.config(" in text + + +def test_model_builder_obstacle_mesh_does_not_create_volume_selection(): + model = polyfem.model() + + obstacle = model.mesh(is_obstacle=True, + mesh="obstacle.obj", + surface_selection=0, + ) + config = model.config() + + assert obstacle is None + assert config.as_dict()["geometry"] == [ + { + "mesh": "obstacle.obj", + "surface_selection": 0, + "is_obstacle": True, + "type": "mesh", + } + ] + + +@pytest.mark.parametrize("factory", ["mesh", "mesh_array"]) +def test_unified_geometry_can_bind_material_and_obstacle_motion(factory): + model = polyfem.model() + kwargs = {"mesh": "part.msh"} + if factory == "mesh_array": + kwargs["array"] = polyfem.array(size=[2, 1], offset=1) + body = getattr(model, factory)(**kwargs) + obstacle = getattr(model, factory)(**kwargs, is_obstacle=True) + assert "volume_selection" not in model.config().as_dict()["geometry"][0] + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + obstacle.dirichlet(value=[1, 0]) + cfg = model.config().as_dict() + assert cfg["materials"][0]["id"] == cfg["geometry"][0]["volume_selection"] + assert "volume_selection" not in cfg["geometry"][1] + assert cfg["boundary_conditions"]["dirichlet_boundary"][0]["id"] == cfg["geometry"][1]["surface_selection"] + + +def test_unified_geometry_can_share_a_volume_without_explicit_ids(): + model = polyfem.model() + first = model.mesh(mesh="first.msh") + second = model.mesh_array( + mesh="second.msh", array=polyfem.array(size=[2, 1], offset=1), + same_volume_as=first, + ) + second.material(polyfem.neo_hookean(E=1000, nu=0.3)) + cfg = model.config().as_dict() + assert cfg["geometry"][0]["volume_selection"] == cfg["geometry"][1]["volume_selection"] + assert cfg["materials"][0]["id"] == cfg["geometry"][0]["volume_selection"] + + +@pytest.mark.parametrize( + "method,value", + [("dirichlet", [0, 0]), ("neumann", [1, 0]), ("pressure", 2.0)], +) +def test_body_boundary_shortcut_matches_explicit_whole_surface(method, value): + direct = polyfem.model() + body = direct.mesh(mesh="part.msh") + getattr(body, method)(value=value) + getattr(body, method)(value=value) + explicit = polyfem.model() + surface = explicit.mesh(mesh="part.msh").surface_all() + getattr(surface, method)(value=value) + assert direct.config().as_dict() == explicit.config().as_dict() + + +def test_body_boundary_shortcut_keeps_bodies_and_volume_loads_separate(): + model = polyfem.model() + first = model.mesh(mesh="first.msh") + second = model.mesh(mesh="second.msh", surface_selection=1) + first.rhs(value=[0, 1]) + first.dirichlet(value=[0, 0]) + second.dirichlet(value=[1, 0]) + cfg = model.config().as_dict() + first_id, second_id = [g["surface_selection"] for g in cfg["geometry"]] + assert first_id != second_id + assert second_id == 1 + assert cfg["boundary_conditions"]["dirichlet_boundary"] == [ + {"id": first_id, "value": [0, 0]}, + {"id": second_id, "value": [1, 0]}, + ] + assert cfg["boundary_conditions"]["rhs"] == [ + {"id": cfg["geometry"][0]["volume_selection"], "value": [0, 1]} + ] + + +@pytest.mark.parametrize("whole_first", [True, False]) +def test_body_boundary_shortcut_rejects_overwriting_partial_selections(whole_first): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + if whole_first: + body.dirichlet(value=[0, 0]) + else: + bottom = body.surface_axis(axis=-1, position=-1) + bottom.dirichlet(value=[0, 0]) + before = model.config().as_dict() + with pytest.raises(ValueError, match="surface|boundary"): + if whole_first: + body.surface_axis(axis=1, position=1) + else: + body.dirichlet(value=[1, 0]) + assert model.config().as_dict() == before + + +def test_body_boundary_shortcut_requires_mesh_and_preserves_file_selection(): + model = polyfem.model() + with pytest.raises(ValueError, match="body.mesh"): + model.body().dirichlet(value=[0, 0]) + body = model.mesh( + mesh="part.msh", + surface_selection=polyfem.surface_selection_file(file="sidesets.txt"), + ) + before = model.config().as_dict() + with pytest.raises(ValueError, match="file-based"): + body.dirichlet(value=[0, 0]) + assert model.config().as_dict() == before + + +def test_top_level_config_with_model_delegates_to_model_builder(): + model = polyfem.model() + + material = polyfem.neo_hookean(E=100000.0, nu=0.3) + body = model.mesh(mesh="beam.msh") + body.material(material) + body.surface_all(id=1).dirichlet(value=[0.0, 0.0, 0.0]) + + solver = polyfem.solver(max_threads=1) + output = polyfem.output(directory="out") + config_kwargs = { + "rhs": [10, 100, 0], + "space": polyfem.space( + discr_order=1, + advanced=polyfem.space_advanced(quadrature_order=4), + ), + "solver": solver, + "output": output, + } + + builder_config = model.config(**config_kwargs) + top_level_config = polyfem.config(model=model, **config_kwargs) + + assert top_level_config.as_dict() == builder_config.as_dict() + + builder_canonical = _config(builder_config) + top_level_canonical = _config(top_level_config) + assert top_level_canonical == builder_canonical + + +def test_top_level_body_mesh_and_model_rhs_match_legacy_builder_payload(): + legacy_model = polyfem.model() + legacy_body = legacy_model.mesh(mesh="beam.msh") + legacy_body.material(polyfem.neo_hookean(E=100000.0, nu=0.3)) + legacy_body.surface_all(id=1).dirichlet(value=[0.0, 0.0, 0.0]) + legacy_config = polyfem.config(model=legacy_model, rhs=[10, 100, 0]) + + model = polyfem.model() + mesh_descriptor = polyfem.mesh(mesh="beam.msh") + mesh_payload_before_attach = mesh_descriptor.as_dict() + body = polyfem.body(model=model) + body.mesh(mesh_descriptor) + body.material(polyfem.neo_hookean(E=100000.0, nu=0.3)) + body.surface_all(id=1).dirichlet(value=[0.0, 0.0, 0.0]) + model.rhs([10, 100, 0]) + config = polyfem.config(model=model) + + assert config.as_dict() == legacy_config.as_dict() + assert mesh_descriptor.as_dict() == mesh_payload_before_attach + + legacy_canonical = _config(legacy_config) + canonical = _config(config) + assert canonical == legacy_canonical + + +def test_model_rhs_rejects_duplicate_rhs_sources(): + model = polyfem.model() + model.rhs([10, 100, 0]) + + with pytest.raises(TypeError, match="rhs"): + polyfem.config(model=model, rhs=[0, 0, 0]) + with pytest.raises(TypeError, match="rhs"): + polyfem.config( + model=model, + boundary_conditions=polyfem.boundary_conditions(rhs=[0, 0, 0]), + ) + + +def test_body_rhs_preserves_each_body_selection_and_rejects_conflicts(): + model = polyfem.model() + first = model.mesh(mesh="first.obj") + second = model.mesh(mesh="second.obj") + first.material(polyfem.neo_hookean(E=1000, nu=0.3)) + second.material(polyfem.neo_hookean(E=2000, nu=0.3)) + first.rhs(value=[1, 0]) + second.rhs(value=[0, 2]) + payload = polyfem.config(model=model).as_dict() + ids = [item["volume_selection"] for item in payload["geometry"]] + assert ids[0] != ids[1] + assert payload["boundary_conditions"]["rhs"] == [ + {"id": ids[0], "value": [1, 0]}, + {"id": ids[1], "value": [0, 2]}, + ] + assert [item["id"] for item in payload["materials"]] == ids + with pytest.raises(TypeError, match="rhs"): + first.rhs(value=[3, 4]) + with pytest.raises(TypeError, match="rhs"): + model.rhs([1, 1]) + with pytest.raises(TypeError, match="rhs"): + polyfem.config(model=model, rhs=[1, 1]) + with pytest.raises(TypeError, match="rhs"): + polyfem.config(model=model, boundary_conditions={"rhs": [1, 1]}) + + global_model = polyfem.model() + global_model.rhs([1, 1]) + global_body = global_model.mesh(mesh="first.obj") + with pytest.raises(TypeError, match="rhs"): + global_body.rhs(value=[1, 0]) + unbound = polyfem.body(model=polyfem.model()) + with pytest.raises(ValueError, match="body.mesh"): + unbound.rhs(value=[1, 0]) + + +def test_global_material_geometry_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "2D" + / "contact_2d_static_friction_slope_generated_api.py" + ) + source_path = POLYFEM_DATA_EXAMPLES / "2D" / "static" / "friction-slope.json" + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert "model.mesh(" in text + assert "polyfem_config = model.config(" in text + + +def test_model_builder_geometry_mesh_does_not_create_volume_selection(): + model = polyfem.model() + + geometry = model.mesh( + mesh="static-wall.obj", + ) + surface = geometry.surface_all(id=1) + surface.dirichlet(value=[0, 0]) + config = model.config() + + assert config.as_dict()["geometry"] == [ + { + "mesh": "static-wall.obj", + "surface_selection": 1, + "type": "mesh", + } + ] + assert config.as_dict()["boundary_conditions"]["dirichlet_boundary"] == [ + { + "id": 1, + "value": [0, 0], + } + ] + + +def test_single_dict_selection_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_unit_tests_2_cubes_generated_api.py" + ) + source_path = POLYFEM_DATA_EXAMPLES / "3D" / "unit-tests" / "2-cubes.json" + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert ".surface_axis(" in text + assert "polyfem_config = model.config(" in text + + +def test_mesh_sequence_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_mesh_sequence_kick_generated_api.py" + ) + source_path = POLYFEM_DATA_EXAMPLES / "3D" / "mesh-sequence" / "kick.json" + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert "model.mesh_sequence(" in text + assert "polyfem_config = model.config(" in text + + +def test_model_builder_mesh_sequence_preserves_payload(): + model = polyfem.model() + + obstacle = model.mesh_sequence(is_obstacle=True, + mesh_sequence="kick-sequence/", + fps=24, + ) + config = model.config() + + assert obstacle is None + assert config.as_dict()["geometry"] == [ + { + "mesh_sequence": "kick-sequence/", + "fps": 24, + "is_obstacle": True, + "type": "mesh_sequence", + } + ] + + + +def test_implicit_obstacle_motion_targets_only_the_bound_obstacle(): + model = polyfem.model() + model.mesh(is_obstacle=True, mesh="lower.obj") + obstacle = model.mesh(is_obstacle=True, mesh="upper.obj") + obstacle.dirichlet(value=[1, 0, 0]) + moved = model.config().as_dict() + assert "surface_selection" not in moved["geometry"][0] + surface_id = moved["geometry"][1]["surface_selection"] + assert moved["boundary_conditions"]["dirichlet_boundary"] == [ + {"id": surface_id, "value": [1, 0, 0]} + ] + + +def test_mesh_array_pile_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_pile_cubes_generated_api.py" + ) + source_path = POLYFEM_DATA_EXAMPLES / "3D" / "pile" / "cubes.json" + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert "model.mesh_array(" in text + assert "polyfem_config = model.config(" in text + + +def test_model_builder_mesh_array_without_volume_selection_preserves_payload(): + model = polyfem.model() + + mesh_array = model.mesh_array( + mesh="cube.msh", + array=polyfem.array( + size=[2, 3, 4], + offset=1.25, + ), + ) + config = model.config() + + assert callable(mesh_array.material) + assert config.as_dict()["geometry"] == [ + { + "mesh": "cube.msh", + "array": { + "size": [2, 3, 4], + "offset": 1.25, + }, + "type": "mesh_array", + } + ] + + +def test_obstacle_displacement_example_uses_model_builder(): + example_path = ( + CLASSIC_EXAMPLES + / "3D" + / "contact_3d_friction_ball_rollers_generated_api.py" + ) + source_path = ( + POLYFEM_DATA_EXAMPLES + / "3D" + / "friction" + / "ball-rollers.json" + ) + + assert source_path.resolve() in _builder_safe_source_paths() + + text = example_path.read_text(encoding="utf-8") + assert "model = polyfem.model()" in text + assert ".obstacle_displacement(" in text + + +def test_model_builder_can_bind_obstacle_surface_displacement(): + model = polyfem.model() + + surface = model.mesh(is_obstacle=True, + mesh="roller.obj", + surface_selection=1000, + ) + surface.obstacle_displacement(value=[1, 0, 0]) + config = model.config() + + assert config.as_dict()["geometry"] == [ + { + "mesh": "roller.obj", + "surface_selection": 1000, + "is_obstacle": True, + "type": "mesh", + } + ] + assert config.as_dict()["boundary_conditions"]["obstacle_displacements"] == [ + { + "id": 1000, + "value": [1, 0, 0], + } + ] + + +def _import_example(example_path: Path) -> Any: + spec = importlib.util.spec_from_file_location(example_path.stem, example_path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + # Adapt the import in the pinned external fixtures to the current public API. + source = example_path.read_text().replace("from polyfempy.runtime import solve", "from polyfempy import solve") + exec(compile(source, str(example_path), "exec"), module.__dict__) + return module + + +def _import_module(module_path: Path, module_name: str) -> Any: + spec = importlib.util.spec_from_file_location(module_name, module_path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + try: + spec.loader.exec_module(module) + finally: + sys.modules.pop(module_name, None) + return module + + +def _deep_merge(base: Any, override: Any) -> Any: + if isinstance(base, dict) and isinstance(override, dict): + merged = copy.deepcopy(base) + for key, value in override.items(): + merged[key] = ( + _deep_merge(merged[key], value) + if key in merged + else copy.deepcopy(value) + ) + return merged + return copy.deepcopy(override) + + +def _load_source_config(source_path: Path) -> dict[str, Any]: + source_path = source_path.resolve() + with source_path.open(encoding="utf-8") as f: + source = json.load(f) + + common_ref = source.pop("common", None) + source.pop("tests", None) + source.pop("default_params", None) + patch = source.pop("patch", None) + + if common_ref is None: + merged = source + else: + common_path = (source_path.parent / common_ref).resolve() + merged = _deep_merge(_load_source_config(common_path), source) + + if patch: + merged = _apply_json_patch(merged, patch) + + _resolve_mesh_paths(merged, source_path.parent) + _normalize_solver_fallbacks(merged) + _normalize_generated_mesh_payloads(merged, source_path.parent) + return merged + + +def _expected_config_from_source(source_path: Path) -> dict[str, Any]: + config = _load_source_config(source_path) + output = config.setdefault("output", {}) + case = source_path.relative_to(POLYFEM_DATA_EXAMPLES).with_suffix("") + output.setdefault("directory", f"results/{case.as_posix()}") + # The generated configuration represents these singleton entries as lists. + if isinstance(config.get("materials"), dict): + config["materials"] = [config["materials"]] + boundary = config.get("boundary_conditions", {}) + if isinstance(boundary.get("dirichlet_boundary"), dict): + boundary["dirichlet_boundary"] = [boundary["dirichlet_boundary"]] + return config + + +def _apply_json_patch(config: dict[str, Any], patch: list[dict[str, Any]]) -> dict[str, Any]: + patched = copy.deepcopy(config) + for item in patch: + assert item.get("op") == "replace" + _replace_json_pointer(patched, item["path"], item.get("value")) + return patched + + +def _replace_json_pointer(config: Any, pointer: str, value: Any) -> None: + target = config + tokens = _json_pointer_tokens(pointer) + for token in tokens[:-1]: + target = target[int(token)] if isinstance(target, list) else target[token] + + last = tokens[-1] + if isinstance(target, list): + target[int(last)] = copy.deepcopy(value) + else: + target[last] = copy.deepcopy(value) + + +def _json_pointer_tokens(pointer: str) -> list[str]: + assert pointer.startswith("/") + return [ + token.replace("~1", "/").replace("~0", "~") + for token in pointer[1:].split("/") + ] + + +def _resolve_mesh_paths(value: Any, source_dir: Path) -> None: + if isinstance(value, list): + for item in value: + _resolve_mesh_paths(item, source_dir) + elif isinstance(value, dict): + for key in ("mesh", "linear_map"): + path_value = value.get(key) + if isinstance(path_value, str): + value[key] = str((source_dir / path_value).resolve()) + for child in value.values(): + _resolve_mesh_paths(child, source_dir) + + +def _normalize_solver_fallbacks(config: dict[str, Any]) -> None: + solver = config.get("solver") + if not isinstance(solver, dict): + return + linear = solver.get("linear") + if not isinstance(linear, dict): + return + solver_name = linear.get("solver") + if isinstance(solver_name, list): + linear["solver"] = solver_name[0] + + +def _normalize_generated_mesh_payloads(config: dict[str, Any], source_dir: Path) -> None: + geometry = config.get("geometry") + if not isinstance(geometry, list): + return + + for item in geometry: + if not isinstance(item, dict) or "mesh" not in item: + continue + item.setdefault("type", "mesh") + _normalize_file_selection(item, "volume_selection", source_dir) + _normalize_file_selection(item, "surface_selection", source_dir) + + transformation = item.get("transformation") + if not isinstance(transformation, dict): + continue + for field in ("rotation", "scale"): + if isinstance(transformation.get(field), (int, float)): + transformation[field] = [float(transformation[field])] + + +def _normalize_file_selection(item: dict[str, Any], field: str, source_dir: Path) -> None: + selection = item.get(field) + if isinstance(selection, str): + item[field] = {"file": _resolve_source_file_path(selection, source_dir)} + elif isinstance(selection, dict): + file_path = selection.get("file") + if isinstance(file_path, str): + selection["file"] = _resolve_source_file_path(file_path, source_dir) + + +def _resolve_source_file_path(path_value: str, source_dir: Path) -> str: + path = Path(path_value) + if path.is_absolute(): + return path_value + return str((source_dir / path).resolve()) + + +@pytest.mark.parametrize("case", EXAMPLE_CASES, ids=_case_id) +def test_classic_generated_example_compiles(case: tuple[Path, Path]): + example_path, _source_path = case + py_compile.compile(str(example_path), doraise=True) + + +@pytest.mark.parametrize("case", EXAMPLE_CASES, ids=_case_id) +def test_classic_generated_example_declares_polyfem_data_source(case: tuple[Path, Path]): + example_path, source_path = case + example = _import_example(example_path) + + assert Path(example.SOURCE_JSON).resolve() == source_path.resolve() + assert POLYFEM_DATA_CONTACT in Path(example.SOURCE_JSON).resolve().parents + + +def test_classic_common_helpers_support_polyfem_data_root_env(monkeypatch, tmp_path): + data_root = tmp_path / "polyfem-data-alt" + monkeypatch.setenv("POLYFEM_DATA_ROOT", str(data_root)) + + common_2d = _import_module( + CLASSIC_EXAMPLES / "2D" / "_contact_2d_common.py", + "contact_2d_common_env_test", + ) + common_3d = _import_module( + CLASSIC_EXAMPLES / "3D" / "_contact_3d_common.py", + "contact_3d_common_env_test", + ) + + assert common_2d.POLYFEM_DATA_ROOT == data_root.resolve() + assert common_2d.POLYFEM_DATA_CONTACT == data_root.resolve() / "contact" + assert common_2d.CONTACT_EXAMPLES_DIR == data_root.resolve() / "contact" / "examples" + assert common_2d.MESHES_DIR == data_root.resolve() / "contact" / "meshes" + assert common_3d.POLYFEM_DATA_ROOT == data_root.resolve() + assert common_3d.POLYFEM_DATA_CONTACT == data_root.resolve() / "contact" + + +def test_contact_source_loader_resolves_file_selection_paths(): + source_path = POLYFEM_DATA_EXAMPLES / "3D" / "hex_tet" / "params.json" + loader = _import_module( + CLASSIC_EXAMPLES / "_contact_source_loader.py", + "contact_source_loader_file_selection_test", + ) + + payload = loader.load_contact_source_payload(source_path) + + assert payload["geometry"][0]["surface_selection"] == { + "file": str((source_path.parent / "surface_sidesets11.txt").resolve()) + } + + +def _assert_source_parity(actual, expected): + """Compare geometry labels and their consumers under a one-to-one renumbering.""" + actual = copy.deepcopy(actual) + maps = {"volume": {}, "boundary": {}} + + def match(label, source_label, group): + if not isinstance(label, int) or not isinstance(source_label, int) or min(label, source_label) <= 0: + assert label == source_label + return label + mapping = maps[group] + assert mapping.setdefault(label, source_label) == source_label + return source_label + + def align(value, source, group): + if isinstance(value, list): + assert len(value) == len(source) + return [align(v, s, group) for v, s in zip(value, source)] + if isinstance(value, dict): + if "id" in value: + value["id"] = match(value["id"], source["id"], group) + return value + return match(value, source, group) + + expected = copy.deepcopy(expected) + conditions = expected.get("boundary_conditions", {}) + for geometry, source in zip(actual["geometry"], expected["geometry"]): + if (source.get("is_obstacle") and source.get("type", "mesh") in ("mesh", "mesh_array") + and source.get("surface_selection") == 0 and "surface_selection" not in geometry): + # GeometryLoader only consults an obstacle tag when choosing its displacement. + for key in ("dirichlet_boundary", "obstacle_displacements"): + entries = conditions.get(key, []) + for entry in entries if isinstance(entries, list) else [entries]: + target = entry["id"] + assert target not in (0, "all") + assert not isinstance(target, list) or 0 not in target + del source["surface_selection"] + for field, group in (("volume_selection", "volume"), ("surface_selection", "boundary"), ("point_selection", "boundary")): + if field in geometry: + if (field == "surface_selection" and not source.get("is_obstacle") + and source[field] == 0 and isinstance(geometry[field], int) and geometry[field] > 0): + label = geometry[field] + assert maps[group].setdefault(label, 0) == 0 + geometry[field] = 0 + else: + geometry[field] = align(geometry[field], source[field], group) + for mapping in maps.values(): + assert len(set(mapping.values())) == len(mapping) + + def translate(items, group): + for item in items if isinstance(items, list) else [items]: + if isinstance(item, dict) and isinstance(item.get("id"), int): + label = item["id"] + mapping = maps[group] + if label in mapping: + item["id"] = mapping[label] + else: + # An external mesh tag can stay literal. An old, reassigned ID cannot. + assert label not in mapping.values(), f"Stale {group} ID {label}" + + translate(actual.get("materials"), "volume") + translate(actual.get("space", {}).get("discr_order"), "volume") + for items in actual.get("initial_conditions", {}).values(): + translate(items, "volume") + for items in actual.get("boundary_conditions", {}).values(): + translate(items, "boundary") + assert actual == expected + + +def test_source_parity_rejects_stale_boundary_id(): + source = { + "geometry": [{"surface_selection": 1000}], + "boundary_conditions": {"dirichlet_boundary": [{"id": 1000, "value": [1, 0]}]}, + } + actual = copy.deepcopy(source) + actual["geometry"][0]["surface_selection"] = 1 + with pytest.raises(AssertionError, match="Stale boundary ID 1000"): + _assert_source_parity(actual, source) + + +@pytest.mark.parametrize("case", EXAMPLE_CASES, ids=_case_id) +def test_classic_generated_example_matches_polyfem_data_source(case: tuple[Path, Path]): + example_path, source_path = case + example = _import_example(example_path) + + _assert_source_parity(example.polyfem_config.as_dict(), _expected_config_from_source(source_path)) + + +def test_all_classic_generated_examples_match_polyfem_data_sources(): + for example_path, source_path in _all_example_cases(): + example = _import_example(example_path) + try: + _assert_source_parity(example.polyfem_config.as_dict(), _expected_config_from_source(source_path)) + except AssertionError as error: + raise AssertionError(str(source_path)) from error + + + +@pytest.mark.parametrize("case", DOLPHIN_MATERIAL_SHAPE_CASES, ids=_case_id) +def test_dolphin_generated_backend_payload_keeps_source_materials_shape( + case: tuple[Path, Path], +): + example_path, source_path = case + source_config = _load_source_config(source_path) + example = _import_example(example_path) + + canonical = _config(example.polyfem_config) + + assert isinstance(source_config["materials"], dict) + assert canonical["materials"] == source_config["materials"] + + +def test_classic_generated_api_fallbacks_are_limited_to_known_schema_gaps(): + actual = set() + for _example_path, source_path in _all_example_cases(): + example = _import_example(_example_path) + fallback_reason = getattr(example.polyfem_config, "fallback_reason", None) + if fallback_reason: + actual.add(source_path.relative_to(POLYFEM_DATA_EXAMPLES).as_posix()) + + assert actual == EXPECTED_GENERATED_API_FALLBACK_SOURCES + + +@pytest.mark.parametrize("case", EXAMPLE_CASES, ids=_case_id) +def test_classic_generated_example_uses_generated_solve_path(case: tuple[Path, Path]): + example_path, _source_path = case + example = _import_example(example_path) + + canonical = _config(example.polyfem_config) + + assert "geometry" in canonical + + +def test_all_classic_generated_examples_use_generated_solve_path(): + failures = [] + for example_path, _source_path in _all_example_cases(): + example = _import_example(example_path) + canonical = _config(example.polyfem_config) + if not canonical.get("geometry"): + failures.append(example_path.relative_to(ROOT).as_posix()) + + assert failures == [] diff --git a/tests/test_generated_payload.py b/tests/test_generated_payload.py new file mode 100644 index 00000000..84f91906 --- /dev/null +++ b/tests/test_generated_payload.py @@ -0,0 +1,39 @@ +"""Generated configurations reach PolyFEM with their chosen values intact.""" + +import copy + +import polyfempy as pf + +from polyfempy.solve import _config + + +def test_generated_material_union_is_not_rewritten(): + cfg = pf.config(materials=[pf.neo_hookean(E=1000, nu=0.3)]) + assert _config(cfg) == cfg.as_dict() + + +def test_tagged_materials_remain_a_list(): + cfg = pf.config(materials=[pf.neo_hookean(E=1000, nu=0.3, id=7)]) + assert _config(cfg)["materials"] == [{"id": 7, "type": "NeoHookean", "E": 1000, "nu": 0.3}] + + +def test_explicit_solver_values_pass_through_unchanged(): + cfg = pf.config(solver=pf.solver( + advanced=pf.solver_advanced(cache_size=900000, lump_mass_matrix=False), + nonlinear=pf.nonlinear(max_iterations=500, advanced=pf.nonlinear_advanced(f_delta_tol=0.0)), + )) + before = cfg.as_dict() + assert _config(cfg) == before + + +def test_unset_solver_options_stay_unset(): + cfg = pf.config(solver=pf.solver(advanced=pf.solver_advanced(), nonlinear=pf.nonlinear())) + assert _config(cfg)["solver"] == {"advanced": {}, "nonlinear": {}} + + +def test_backend_options_and_paths_are_not_rewritten(): + cfg = {"geometry": [{"mesh": "relative.msh"}], "root_path": "/tmp/config.json", + "output": {"future_option": {"enabled": False}}, "common": "parameters.json"} + original = copy.deepcopy(cfg) + assert _config(cfg) == original + assert cfg == original diff --git a/tests/test_generated_time_api.py b/tests/test_generated_time_api.py new file mode 100644 index 00000000..a2a383df --- /dev/null +++ b/tests/test_generated_time_api.py @@ -0,0 +1,45 @@ +"""Schema-generated time factories and builder payload compatibility.""" + +import pytest + +from polyfempy.generated_api import generated_api as pf + + +@pytest.mark.parametrize("fields", [ + {"dt": 0.01, "tend": 0.5}, + {"dt": 0.01, "time_steps": 50}, + {"tend": 0.5, "time_steps": 50}, +]) +def test_time_factory_and_builder_match_schema(fields): + fields = dict(fields, t0=0, integrator="BDF") + expected = pf.config(time=fields).as_dict()["time"] + assert pf.time(**fields).as_dict() == expected + model = pf.model() + assert model.time(**fields) is model + assert model.config().as_dict()["time"] == expected + + +@pytest.mark.parametrize("fields", [ + {"dt": 0.01}, + {"dt": 0.01, "tend": 0.5, "typo": True}, +]) +def test_invalid_time_parameters_fail(fields): + with pytest.raises(TypeError): + pf.time(**fields) + with pytest.raises(TypeError): + pf.model().time(**fields) + + +def test_existing_time_wrapper_and_model_configuration(): + old = pf.time(pf.object1(t0=0, dt=0.01, tend=0.5, integrator="BDF")) + model = pf.model() + model.time(t0=0, dt=0.01, tend=0.5, integrator="BDF") + model.units(length="cm", mass="g", time="s") + model.output(directory="runs/example") + config = model.config().as_dict() + assert config["time"] == old.as_dict() + assert config["units"] == {"length": "cm", "mass": "g", "time": "s"} + assert config["output"]["directory"] == "runs/example" + assert "time" not in pf.model().config().as_dict() + with pytest.raises(TypeError, match="already set"): + model.config(time=old) diff --git a/tests/test_import_public_api.py b/tests/test_import_public_api.py new file mode 100644 index 00000000..0c63c20d --- /dev/null +++ b/tests/test_import_public_api.py @@ -0,0 +1,102 @@ +"""Smoke tests for the current public import surface.""" + +import os +from pathlib import Path +import subprocess +import sys + + +def test_import_does_not_change_host_streams_or_environment(): + root = Path(__file__).resolve().parents[1] + env = os.environ.copy() + env["PYTHONPATH"] = str(root / "python") + env.pop("POLYFEMPY_WINDOWS_AUTOCONFIG", None) + env.pop("POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG", None) + env.pop("KMP_DUPLICATE_LIB_OK", None) + env["PYTHONIOENCODING"] = "cp1252" + code = ''' +import os, sys +from unittest.mock import patch +before = (sys.stdout, sys.stderr) +with patch("os.system") as shell: + import polyfempy +assert sys.stdout is before[0] +assert sys.stderr is before[1] +assert "KMP_DUPLICATE_LIB_OK" not in os.environ +shell.assert_not_called() +''' + subprocess.run([sys.executable, "-c", code], cwd=root, env=env, check=True) + + +def test_unsupported_callback_fails_before_loading_backend(): + import pytest + from polyfempy import solve + + with pytest.raises(TypeError, match="sidesets_func"): + solve(sidesets_func=lambda *_: 1) + + +def test_public_api_imports(): + from polyfempy import Result, solve + + assert solve is not None + assert Result is not None + + +def test_polyfem_is_an_automatic_alias(): + import polyfem + import polyfempy + + assert polyfem.__all__ == polyfempy.__all__ + for name in polyfempy.__all__: + assert getattr(polyfem, name) is getattr(polyfempy, name) + + +def test_generated_api_package_is_the_preferred_generated_surface(): + from polyfempy.generated_api import generated_api as polyfem + from polyfempy.generated_api import generated_class + + assert polyfem.Root is generated_class.Root + + +def test_legacy_api_and_generated_packages_are_removed(): + from pathlib import Path + + package_dir = Path(__file__).resolve().parents[1] / "python" / "polyfempy" + + assert not (package_dir / "api").exists() + assert not (package_dir / "generated").exists() + assert not (package_dir / "runtime" / "_solve_pipeline.py").exists() + assert not (package_dir / "runtime" / "_solve_outputs.py").exists() + + +def test_solve_module_all_only_recommends_solve(): + import importlib + import inspect + + solve_module = importlib.import_module("polyfempy.solve") + + assert solve_module.__all__ == ["Result", "solve"] + assert "sampled_vtu_fallback" not in inspect.signature(solve_module.solve).parameters + assert not hasattr(solve_module, "populate_sampled_history") + + +def test_import_does_not_load_native_extension(): + root = Path(__file__).resolve().parents[1] + env = os.environ.copy() + env["PYTHONPATH"] = str(root / "python") + code = """ +import importlib.abc +import sys +class RejectNative(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == 'polyfempy.polyfempy': + raise AssertionError('Import eagerly loaded native bindings') +sys.meta_path.insert(0, RejectNative()) +import polyfempy +assert callable(polyfempy.model) +assert callable(polyfempy.solve) +assert 'Path' not in polyfempy.__all__ +assert 'builtins' not in polyfempy.__all__ +""" + subprocess.run([sys.executable, "-c", code], cwd=root, env=env, check=True) diff --git a/tests/test_model_selection_ids.py b/tests/test_model_selection_ids.py new file mode 100644 index 00000000..55af5c2f --- /dev/null +++ b/tests/test_model_selection_ids.py @@ -0,0 +1,174 @@ +"""Check model associations without loading meshes or running the native solver.""" + +import pytest + +import polyfempy as polyfem + + +def select_left(body): + return body.surface_axis(axis="-x", position=0.0, relative=True) + + +def test_repeated_partial_selection_keeps_one_geometry_rule(): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + first = select_left(body) + first.dirichlet(value=[0, 0]) + second = select_left(body) + second.neumann(value=[1, 0]) + cfg = model.config().as_dict() + selections = cfg["geometry"][0]["surface_selection"] + assert len(selections) == 1 + for key in ("dirichlet_boundary", "neumann_boundary"): + assert cfg["boundary_conditions"][key][0]["id"] == selections[0]["id"] + + +@pytest.mark.parametrize("direct_first", [False, True]) +def test_repeated_whole_surface_reuses_its_id(direct_first): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + if direct_first: + first = body.dirichlet(value=[0, 0]) + else: + first = body.surface_all().dirichlet(value=[0, 0]) + second = body.surface_all().neumann(value=[1, 0]) + assert first.selection_ref.backend_id == second.selection_ref.backend_id + cfg = model.config().as_dict() + assert cfg["geometry"][0]["surface_selection"] == first.selection_ref.backend_id + assert cfg["boundary_conditions"]["neumann_boundary"][0]["id"] == first.selection_ref.backend_id + + +@pytest.mark.parametrize("field", ["point_selection", "surface_selection", "volume_selection"]) +def test_existing_selection_rules_reserve_ids_before_auto_allocation(field): + model = polyfem.model() + model.mesh(mesh="tagged.msh", **{field: [{"id": 1, "axis": "-x", "position": 0.0}]}) + body = model.mesh(mesh="automatic.msh") + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + body.dirichlet(value=[0, 0]) + cfg = model.config().as_dict() + produced_field = "volume_selection" if field == "volume_selection" else "surface_selection" + assert cfg["geometry"][1][produced_field] != 1 + assert cfg["geometry"][0][field][0]["id"] == 1 + + +def test_bind_rejects_a_foreign_ref_even_when_backend_ids_match(): + first_model = polyfem.model() + foreign = first_model.mesh(mesh="first.msh").surface_all() + second_model = polyfem.model() + local = second_model.mesh(mesh="second.msh").surface_all() + assert foreign.selection_ref.backend_id == local.selection_ref.backend_id + before = second_model.config().as_dict() + with pytest.raises(ValueError, match="this model"): + second_model.bind("surface.dirichlet", foreign.selection_ref, {"value": [9, 9]}) + assert second_model.config().as_dict() == before + second_model.bind("surface.dirichlet", local.selection_ref, {"value": [0, 0]}) + assert second_model.config().as_dict()["boundary_conditions"]["dirichlet_boundary"] == [ + {"id": local.selection_ref.backend_id, "value": [0, 0]}, + ] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_multiple_bodies_keep_their_own_material_and_boundary_ids(reverse): + model = polyfem.model() + bodies = [model.mesh(mesh="first.msh"), model.mesh(mesh="second.msh")] + indices = [1, 0] if reverse else [0, 1] + for index in indices: + body = bodies[index] + body.material(polyfem.neo_hookean(E=1000 * (index + 1), nu=0.3)) + body.velocity(value=[index, 0]) + select_left(body).dirichlet(value=[index, 0]) + body.point_axis(axis="-y", position=0.0, relative=True).neumann(value=[index + 1, 0]) + cfg = model.config().as_dict() + boundary_ids = [] + for index, geometry in enumerate(cfg["geometry"]): + material = next(item for item in cfg["materials"] if item["id"] == geometry["volume_selection"]) + assert material["E"] == 1000 * (index + 1) + for field, consumer, value in ( + ("surface_selection", "dirichlet_boundary", [index, 0]), + ("point_selection", "neumann_boundary", [index + 1, 0]), + ): + tag = geometry[field][0]["id"] + boundary_ids.append(tag) + assert next(item for item in cfg["boundary_conditions"][consumer] if item["id"] == tag)["value"] == value + assert len(set(boundary_ids)) == 4 + assert len({g["volume_selection"] for g in cfg["geometry"]}) == 2 + + +def test_shared_surfaces_and_volumes_work_without_explicit_ids(): + model = polyfem.model() + first = model.mesh(mesh="first.msh") + second = model.mesh(mesh="second.msh", same_volume_as=first) + first.material(polyfem.neo_hookean(E=1000, nu=0.3)) + second.material(polyfem.neo_hookean(E=1000, nu=0.3)) + surface = first.surface_all() + second.surface_all(same_as=surface).dirichlet(value=[0, 0]) + surface.dirichlet(value=[0, 0]) + cfg = model.config().as_dict() + assert cfg["geometry"][0]["volume_selection"] == cfg["geometry"][1]["volume_selection"] + assert cfg["geometry"][0]["surface_selection"] == cfg["geometry"][1]["surface_selection"] + assert len(cfg["materials"]) == 1 + assert len(cfg["boundary_conditions"]["dirichlet_boundary"]) == 1 + + +def test_cross_model_sharing_is_rejected_without_changing_the_model(): + first = polyfem.model().mesh(mesh="first.msh") + surface = first.surface_all() + model = polyfem.model() + local = model.mesh(mesh="local.msh") + before = model.config().as_dict() + with pytest.raises(ValueError, match="this model"): + model.mesh(mesh="second.msh", same_volume_as=first) + with pytest.raises(ValueError, match="this model"): + local.surface_all(same_as=surface) + assert model.config().as_dict() == before + + +def test_point_reference_cannot_be_used_as_a_surface_reference(): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + point = body.point_axis(axis="-x", position=0.0, relative=True) + before = model.config().as_dict() + with pytest.raises(ValueError): + body.surface_all(same_as=point) + with pytest.raises(ValueError, match="expects surface"): + model.bind("surface.dirichlet", point.selection_ref, {"value": [0, 0]}) + assert model.config().as_dict() == before + + +def test_explicit_shared_ids_remain_supported(): + model = polyfem.model() + for mesh in ("first.msh", "second.msh"): + body = model.mesh(mesh=mesh, volume_selection=7) + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + body.surface_all(id=9).dirichlet(value=[0, 0]) + cfg = model.config().as_dict() + assert [g["volume_selection"] for g in cfg["geometry"]] == [7, 7] + assert [g["surface_selection"] for g in cfg["geometry"]] == [9, 9] + assert len(cfg["materials"]) == 1 + assert len(cfg["boundary_conditions"]["dirichlet_boundary"]) == 1 + + +def test_file_surface_refs_belong_to_the_model_and_reserve_all_tags(tmp_path): + sideset = tmp_path / "boundary.txt" + sideset.write_text("1 0\n5 1\n", encoding="utf-8") + model = polyfem.model() + tagged = model.mesh(mesh="tagged.msh") + tagged.surface_from_file(sideset, tag=1).dirichlet(value=[0, 0]) + tagged.surface_from_file(sideset, tag=5).neumann(value=[1, 0]) + other = model.mesh(mesh="other.msh").surface_all() + other.dirichlet(value=[1, 0]) + assert other.selection_ref.backend_id > 5 + boundary = model.config().as_dict()["boundary_conditions"] + assert boundary["dirichlet_boundary"][0]["id"] == 1 + assert boundary["neumann_boundary"][0]["id"] == 5 + + +def test_obstacle_and_body_surface_refs_have_distinct_ids(): + model = polyfem.model() + obstacle = model.mesh(mesh="wall.obj", is_obstacle=True) + first = obstacle.dirichlet(value=[0, 0]) + obstacle.surface_all().dirichlet(value=[0, 0]) + second = model.mesh(mesh="part.msh").surface_all().dirichlet(value=[1, 0]) + assert first.selection_ref.backend_id != second.selection_ref.backend_id + cfg = model.config().as_dict() + assert len(cfg["boundary_conditions"]["dirichlet_boundary"]) == 2 diff --git a/tests/test_model_settings.py b/tests/test_model_settings.py new file mode 100644 index 00000000..4d07a4d9 --- /dev/null +++ b/tests/test_model_settings.py @@ -0,0 +1,179 @@ +"""Model settings must survive export without changing existing config calls.""" + +import pytest + +import polyfempy as polyfem + + +@pytest.mark.parametrize( + "section, fields", + [ + ("space", {"discr_order": 2}), + ("initial_conditions", {"velocity": [{"id": 7, "value": [1, 0]}]}), + ("boundary_conditions", {"rhs": [0, -1]}), + ("time", {"dt": 0.01, "tend": 0.1}), + ("output", {"directory": "results"}), + ], +) +def test_model_settings_match_explicit_config(section, fields): + model = polyfem.model() + returned = getattr(model, section)(**fields) + if section == "boundary_conditions": + assert isinstance(returned, dict) + else: + assert returned is model + expected = polyfem.model().config(**{section: getattr(polyfem, section)(**fields)}) + assert model.config().as_dict() == expected.as_dict() + assert model.config().as_dict() == expected.as_dict() + + +@pytest.mark.parametrize("as_list", [False, True]) +def test_material_setting_accepts_one_material_or_a_list(as_list): + material = polyfem.neo_hookean(E=1000, nu=0.3) + value = [material] if as_list else material + model = polyfem.model() + assert model.materials(value) is model + assert model.config().as_dict() == polyfem.model().config(materials=value).as_dict() + + +@pytest.mark.parametrize("settings_first", [False, True]) +def test_global_fields_and_body_lists_survive_in_either_order(settings_first): + model = polyfem.model() + body = model.mesh(mesh="part.msh", volume_selection=7) + + def settings(): + model.space(discr_orderq=4) + model.initial_conditions(velocity=[{"id": 8, "value": [1, 0]}]) + model.materials(polyfem.neo_hookean(id=8, E=2000, nu=0.3)) + model.boundary_conditions(rhs=[0, -1]) + + if settings_first: + settings() + body.discr_order(order=2) + body.velocity(value=[0, 0]) + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + body.dirichlet(value=[0, 0]) + if not settings_first: + settings() + + config = model.config().as_dict() + assert config["space"] == {"discr_orderq": 4, "discr_order": [{"id": 7, "order": 2}]} + assert [entry["id"] for entry in config["materials"]] == [8, 7] + assert [entry["id"] for entry in config["initial_conditions"]["velocity"]] == [8, 7] + assert config["boundary_conditions"]["rhs"] == [0, -1] + assert len(config["boundary_conditions"]["dirichlet_boundary"]) == 1 + for section in ("space", "materials", "initial_conditions", "boundary_conditions"): + assert getattr(model, section)() == config[section] + + +def test_replacing_settings_preserves_body_values_without_duplicates(): + model = polyfem.model() + body = model.mesh(mesh="part.msh", volume_selection=7) + body.velocity(value=[0, 0]) + body.dirichlet(value=[0, 0]) + model.initial_conditions(velocity=[{"id": 8, "value": [1, 0]}]) + model.initial_conditions(velocity=[{"id": 9, "value": [2, 0]}]) + model.space(discr_order=1) + model.space(discr_order=2) + model.boundary_conditions(rhs=[0, -1]) + model.boundary_conditions(rhs=[0, -2]) + first = model.config().as_dict() + assert first == model.config().as_dict() + assert first["space"] == {"discr_order": 2} + assert [entry["id"] for entry in first["initial_conditions"]["velocity"]] == [9, 7] + assert first["boundary_conditions"]["rhs"] == [0, -2] + assert len(first["boundary_conditions"]["dirichlet_boundary"]) == 1 + + +def test_boundary_dictionary_can_still_be_passed_to_config(): + model = polyfem.model() + model.mesh(mesh="part.msh").dirichlet(value=[0, 0]) + boundary = model.boundary_conditions(rhs=[0, -1]) + assert isinstance(boundary, dict) + expected = model.config().as_dict() + assert model.config(boundary_conditions=boundary).as_dict() == expected + assert len(expected["boundary_conditions"]["dirichlet_boundary"]) == 1 + + +def test_explicit_boundary_list_and_body_conditions_are_merged_once(): + model = polyfem.model() + model.mesh(mesh="part.msh").dirichlet(value=[0, 0]) + boundary = model.boundary_conditions( + dirichlet_boundary=[{"id": 9, "value": [1, 0]}], + ) + assert len(boundary["dirichlet_boundary"]) == 2 + assert model.config(boundary_conditions=boundary).as_dict()["boundary_conditions"] == boundary + assert model.config().as_dict()["boundary_conditions"] == boundary + + +def test_body_and_selection_ids_stay_automatic_with_model_settings(): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + body.velocity(value=[0, 0]) + body.surface_axis(axis="-x", position=0.0, relative=True).dirichlet(value=[0, 0]) + model.space(discr_order=2) + model.boundary_conditions(rhs=[0, -1]) + config = model.config().as_dict() + geometry = config["geometry"][0] + assert config["materials"][0]["id"] == geometry["volume_selection"] + assert config["initial_conditions"]["velocity"][0]["id"] == geometry["volume_selection"] + assert config["boundary_conditions"]["dirichlet_boundary"][0]["id"] == geometry["surface_selection"][0]["id"] + + +@pytest.mark.parametrize("section", ["space", "materials", "initial_conditions", "boundary_conditions"]) +def test_conflicting_config_argument_is_not_silently_ignored(section): + model = polyfem.model() + if section == "materials": + model.materials(polyfem.neo_hookean(E=1000, nu=0.3)) + elif section == "space": + model.space(discr_order=2) + elif section == "initial_conditions": + model.initial_conditions(velocity=[{"id": 7, "value": [0, 0]}]) + else: + model.boundary_conditions(rhs=[0, -1]) + with pytest.raises(TypeError, match="already set"): + model.config(**{section: {}}) + + +@pytest.mark.parametrize("settings_first", [False, True]) +@pytest.mark.parametrize("section", ["space", "boundary_conditions"]) +def test_global_and_body_values_cannot_replace_each_other(section, settings_first): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + fields = {"discr_order": 2} if section == "space" else {"rhs": [0, -1]} + if settings_first: + getattr(model, section)(**fields) + if section == "space": + body.discr_order(order=1) + else: + body.rhs(value=[0, -2]) + if settings_first: + with pytest.raises((TypeError, ValueError)): + model.config() + else: + before = model.config().as_dict() + with pytest.raises((TypeError, ValueError)): + getattr(model, section)(**fields) + assert model.config().as_dict() == before + + +def test_reading_or_exporting_does_not_change_settings(): + model = polyfem.model() + fields = {"velocity": [{"id": 7, "value": [1, 0]}]} + model.initial_conditions(**fields) + expected = model.config().as_dict() + fields["velocity"][0]["value"][0] = 99 + model.initial_conditions()["velocity"][0]["value"][0] = 88 + assert model.config().as_dict() == expected + + +def test_explicit_config_is_still_a_one_time_override(): + model = polyfem.model() + body = model.mesh(mesh="part.msh") + body.discr_order(order=1) + before = model.config().as_dict() + assert model.config(space=polyfem.space(discr_order=2)).as_dict()["space"] == {"discr_order": 2} + assert model.config().as_dict() == before + model.config(rhs=[0, -1]) + assert model.config().as_dict() == before diff --git a/tests/test_pipeline_backend.py b/tests/test_pipeline_backend.py new file mode 100644 index 00000000..e9509700 --- /dev/null +++ b/tests/test_pipeline_backend.py @@ -0,0 +1,36 @@ +"""Public solves configure the native solver once and retain its outputs.""" + +import sys +from types import SimpleNamespace +import json + +import numpy as np +import pytest + +from polyfempy import solve + + +@pytest.mark.parametrize("log_level", [4, "off", "debug"]) +def test_solve_preserves_logging_and_runs_native_pipeline(monkeypatch, log_level): + calls = [] + sol = np.arange(6.) + + class FakeSolver: + def set_settings(self, settings, strict_validation): + assert strict_validation is True + assert json.loads(settings)["output"]["log"]["level"] == log_level + calls.append("settings") + + def load_mesh_from_settings(self): + calls.append("file") + + def solve(self): + calls.append("solve") + return sol + + monkeypatch.setitem(sys.modules, "polyfempy.polyfempy", SimpleNamespace(Solver=FakeSolver)) + cfg = {"geometry": [{"mesh": "triangle.obj"}], "output": {"log": {"level": log_level}}} + result = solve(cfg=cfg) + assert calls == ["settings", "file", "solve"] + np.testing.assert_array_equal(result.sol, sol) + assert result.meta == {} diff --git a/tests/test_pipeline_normalize.py b/tests/test_pipeline_normalize.py new file mode 100644 index 00000000..545d2f19 --- /dev/null +++ b/tests/test_pipeline_normalize.py @@ -0,0 +1,49 @@ +"""Configuration loading passes dictionaries and generated payloads through.""" + +import json + +import pytest + +from polyfempy.solve import _config + +CONFIG = {"geometry": [{"mesh": "beam.msh"}], + "materials": {"type": "LinearElasticity", "E": 20, "nu": 0.3}} + + +def test_generated_configuration_is_not_rewritten(): + class Config: + def as_dict(self): + return CONFIG + + assert _config(Config()) == CONFIG + + +def test_dictionary_is_not_rewritten(): + assert _config(CONFIG) == CONFIG + + +def test_json_path_sets_resource_root(tmp_path): + path = tmp_path / "config.json" + path.write_text(json.dumps(CONFIG)) + assert _config(path) == dict(CONFIG, root_path=str(path.resolve())) + + +def test_explicit_resource_root_is_preserved(tmp_path): + path = tmp_path / "config.json" + path.write_text(json.dumps(dict(CONFIG, root_path="other-inputs"))) + assert _config(path)["root_path"] == "other-inputs" + + +@pytest.mark.parametrize("cfg", [None, 123, 1.5, ["a"], object()]) +def test_unsupported_configurations_fail(cfg): + with pytest.raises(TypeError, match="cfg"): + _config(cfg) + + +def test_configuration_errors_propagate(): + class Config: + def as_dict(self): + raise RuntimeError("boom") + + with pytest.raises(RuntimeError, match="boom"): + _config(Config()) diff --git a/tests/test_release_checks.py b/tests/test_release_checks.py new file mode 100644 index 00000000..34d4bc80 --- /dev/null +++ b/tests/test_release_checks.py @@ -0,0 +1,39 @@ +"""Protect against broken GitHub links and incomplete release archives.""" + +import pytest + +from tools.check_distribution import BUILDER_FILES, PACKAGE_FILES, SOURCE_FILES, check_files + + +def source_files(): + return {f"python/{name}" for name in PACKAGE_FILES} | SOURCE_FILES | {f"python-from-jse/generator/{n}" for n in BUILDER_FILES} + + +def test_source_archive_requires_generator_config_and_builder(): + names = source_files() + check_files(names, wheel=False) + for name in ["generator-config/api_aliases.json", "python-from-jse/generator/model_builder.py"]: + with pytest.raises(ValueError, match="Missing distribution files"): + check_files(names - {name}, wheel=False) + + +@pytest.mark.parametrize("path", ["tests/test_cli.py", "build/native.obj", "polyfempy/__pycache__/a.pyc"]) +def test_source_archive_rejects_development_files(path): + with pytest.raises(ValueError, match="distribution"): + check_files(source_files() | {path}, wheel=False) + + +def test_wheel_must_include_native_extension(): + names = PACKAGE_FILES | {"polyfempy-0.8.dist-info/licenses/LICENSE"} + names |= {f"polyfempy/generated_api/generator/{n}" for n in BUILDER_FILES} + with pytest.raises(ValueError, match="native"): + check_files(names, wheel=True) + check_files(names | {"polyfempy/polyfempy.cp311-win_amd64.pyd"}, wheel=True) + + +def test_source_archive_requires_python_source_layout(): + names = source_files() + names.difference_update(f"python/{name}" for name in PACKAGE_FILES) + names.update(PACKAGE_FILES) + with pytest.raises(ValueError, match="Missing distribution files"): + check_files(names, wheel=False) diff --git a/tests/test_result_container.py b/tests/test_result_container.py new file mode 100644 index 00000000..862b5f10 --- /dev/null +++ b/tests/test_result_container.py @@ -0,0 +1,78 @@ +"""Tests for the minimal runtime ``Result`` container.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +_REPO = Path(__file__).resolve().parents[1] + +from polyfempy import Result # noqa: E402 + + +def test_result_stores_raw_backend_solution_and_meta(): + sol = np.array([[0.0, 0.0], [0.1, 0.0], [0.0, 0.1]]) + + result = Result(sol, meta={"case": "example"}) + + np.testing.assert_array_equal(result.sol, sol) + assert result.meta == {"case": "example"} + assert not hasattr(result, "vertices") + assert not hasattr(result, "cells") + assert not hasattr(result, "p") + assert not hasattr(result, "u") + + +def test_result_keeps_raw_backend_solution_shape(): + result = Result(np.arange(6)) + + np.testing.assert_array_equal(result.sol, np.arange(6)) + + +def test_removed_runtime_output_and_convenience_helpers_are_absent(): + result = Result(np.zeros((3, 2))) + + for name in ( + "backend", + "vertices", + "cells", + "V", + "p", + "u", + "fields", + "point_data", + "cell_data", + "history", + "sampled_data", + "body_ids", + "von_mises", + "stress", + "strain", + "has_field", + "require_field", + "point_field", + "cell_field", + "set_field", + "remove_field", + "field_names", + "field", + "n_vertices", + "n_cells", + "available_fields", + "summary", + "as_numpy", + "to_backend", + "to_torch", + "set_sampled_field", + "sampled_field", + "field_by_body", + "to_meshio", + "from_meshio", + "read", + "write", + "to_vtk", + "get_percentile_from_von_mises", + ): + assert not hasattr(result, name) + assert not hasattr(Result, name) diff --git a/tools/check_distribution.py b/tools/check_distribution.py new file mode 100644 index 00000000..c35b7ede --- /dev/null +++ b/tools/check_distribution.py @@ -0,0 +1,87 @@ +"""Check the contents of a source archive or wheel without extracting it.""" + +from __future__ import annotations + +import argparse +import glob +from pathlib import Path, PurePosixPath +import tarfile +import zipfile + + +PACKAGE_FILES = { + "polyfem/__init__.py", "polyfempy/__init__.py", "polyfempy/solve.py", + "polyfempy/generated_api/__init__.py", + "polyfempy/generated_api/generated_api.py", + "polyfempy/generated_api/generated_class.py", + "polyfempy/generated_api/builder_api_manifest.json", + "polyfempy/generated_api/class_tree_manifest.json", + "polyfempy/generated_api/generated_api_manifest.json", +} +BUILDER_FILES = {"__init__.py", "model_builder.py", "id_relationships.py", "selection_refs.py"} +SOURCE_FILES = { + "pyproject.toml", "CMakeLists.txt", "LICENSE", "README.md", "INSTALL.md", "API.md", + "src/binding.cpp", + "python-from-jse/LICENSE", + "tools/check_installed_package.py", + "cmake/recipes/CPM.cmake", + "cmake/recipes/nanobind.cmake", + "cmake/recipes/polyfem.cmake", + "tools/generate_polyfem_api.py", "generator-config/api_aliases.json", + "generator-config/id_relationships.json", +} + + +def check_files(names: set[str], *, wheel: bool) -> None: + for name in names: + path = PurePosixPath(name) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"Unsafe archive path: {name}") + if set(path.parts) & {"__pycache__", ".git", ".pytest_cache", ".ruff_cache"}: + raise ValueError(f"Cache or repository file in distribution: {name}") + if path.parts[0] in {"tests", "build", "dist", "results"}: + raise ValueError(f"Development or output file in distribution: {name}") + builder = "polyfempy/generated_api/generator" if wheel else "python-from-jse/generator" + package_files = PACKAGE_FILES if wheel else {f"python/{name}" for name in PACKAGE_FILES} + required = package_files | {f"{builder}/{name}" for name in BUILDER_FILES} + if not wheel: + required |= SOURCE_FILES + missing = required - names + if missing: + raise ValueError("Missing distribution files: " + ", ".join(sorted(missing))) + if wheel: + if not any(n.startswith("polyfempy/polyfempy") and n.endswith((".so", ".pyd")) for n in names): + raise ValueError("Wheel has no native polyfempy extension.") + if not any(".dist-info/licenses/" in n and n.endswith("LICENSE") for n in names): + raise ValueError("Wheel has no license files.") + + +def check_archive(path: Path) -> None: + wheel = path.suffix == ".whl" + if wheel: + with zipfile.ZipFile(path) as archive: + names = {m.filename for m in archive.infolist() if not m.is_dir()} + else: + with tarfile.open(path) as archive: + members = archive.getmembers() + roots = {PurePosixPath(m.name).parts[0] for m in members} + if len(roots) != 1: + raise ValueError("Source archive must have one top-level directory.") + names = {m.name.split("/", 1)[1] for m in members if m.isfile()} + check_files(names, wheel=wheel) + print(f"Distribution files passed: {path.name}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("archives", nargs="+", help="Archive paths or glob patterns") + for pattern in parser.parse_args().archives: + matches = glob.glob(pattern) + if not matches: + parser.error(f"No archives match {pattern}") + for path in matches: + check_archive(Path(path)) + + +if __name__ == "__main__": + main() diff --git a/tools/check_installed_package.py b/tools/check_installed_package.py new file mode 100644 index 00000000..602010cf --- /dev/null +++ b/tools/check_installed_package.py @@ -0,0 +1,45 @@ +"""Smoke-test an installed wheel outside the source checkout.""" + +import subprocess +import sys +from tempfile import TemporaryDirectory + + +CHECK = r""" +from pathlib import Path +from importlib.util import find_spec +import sys +import numpy as np +import polyfempy as pf +import polyfem + +assert Path(pf.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()) +assert find_spec("polyfempy.runtime") is None +assert polyfem.__all__ == pf.__all__ +assert polyfem.model is pf.model and polyfem.solve is pf.solve and polyfem.Result is pf.Result +mesh = Path("square.obj") +mesh.write_text("v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv .5 .5 0\nf 1 2 5\nf 2 3 5\nf 3 4 5\nf 4 1 5\n") +model = pf.model() +body = model.mesh(mesh=str(mesh.resolve())) +body.material(pf.neo_hookean(E=1000, nu=.3)) +body.surface_axis(axis="-x", position=0, relative=True).dirichlet(value=[0, 0]) +model.solver(linear=pf.linear(solver="Eigen::SimplicialLDLT")) +config = model.config(rhs=[0, -1]) +file_result = pf.solve(cfg=config) +assert np.isfinite(file_result.sol).all() +assert abs(file_result.sol).max() > 1e-6 +load = Path("body_load.py").resolve() +load.write_text("def value(x, y, z, t, index):\n return -1.0\n") +function_result = pf.solve(cfg=model.config(rhs=[0, {"file_name": str(load), "function_name": "value"}])) +np.testing.assert_allclose(function_result.sol, file_result.sol, rtol=1e-6, atol=1e-9) +print("Installed package: alias, file mesh, and Python load-function solves passed.") +""" + + +def main(): + with TemporaryDirectory(prefix="polyfem-installed-") as folder: + subprocess.run([sys.executable, "-I", "-c", CHECK], cwd=folder, check=True, timeout=300) + + +if __name__ == "__main__": + main() diff --git a/tools/generate_polyfem_api.py b/tools/generate_polyfem_api.py new file mode 100644 index 00000000..ee366b80 --- /dev/null +++ b/tools/generate_polyfem_api.py @@ -0,0 +1,118 @@ +"""Generate the packaged configuration API; CMake runs this during installation.""" + +from __future__ import annotations + +import argparse +import ast +from pathlib import Path +import re +import subprocess +import sys +import urllib.request + +REPO_ROOT = Path(__file__).resolve().parents[1] +GENERATOR_ROOT = REPO_ROOT / "python-from-jse" +GENERATOR_CONFIG_DIR = REPO_ROOT / "generator-config" +GENERATED_DIR = REPO_ROOT / "python/polyfempy/generated_api" +POLYSOLVE_SPEC_CACHE_DIR = REPO_ROOT / "build/polysolve-json-specs" +LINKED_SOLVER_SPEC_FILES = ("linear-solver-spec.json", "nonlinear-solver-spec.json") + + +def _polysolve_revision_from_recipe(polyfem_source_dir: Path) -> str | None: + recipe = polyfem_source_dir / "cmake" / "recipes" / "polysolve.cmake" + if not recipe.exists(): + return None + + match = re.search( + r"polyfem/polysolve#([A-Za-z0-9_.-]+)", + recipe.read_text(encoding="utf-8"), + ) + if match is None: + return None + return match.group(1) + + +def _cache_polysolve_solver_specs(polyfem_source_dir: Path) -> Path | None: + revision = _polysolve_revision_from_recipe(polyfem_source_dir) + if revision in (None, '.', '..'): + return None + + cache_dir = POLYSOLVE_SPEC_CACHE_DIR / revision + cache_dir.mkdir(parents=True, exist_ok=True) + for spec_file in LINKED_SOLVER_SPEC_FILES: + target = cache_dir / spec_file + if target.exists(): + continue + + url = ( + "https://raw.githubusercontent.com/polyfem/polysolve/" + f"{revision}/{spec_file}" + ) + try: + urllib.request.urlretrieve(url, target) + except Exception as exc: + target.unlink(missing_ok=True) + print( + f"Warning: could not download {spec_file} from polysolve " + f"revision {revision}: {exc}", + file=sys.stderr, + ) + return None + + return cache_dir + + +def write_public_exports() -> None: + api_file = GENERATED_DIR / "generated_api.py" + source = api_file.read_text(encoding="utf-8").split("\n__all__ = ", 1)[0] + exports = ["Root", *( + node.name for node in ast.parse(source).body + if isinstance(node, (ast.FunctionDef, ast.ClassDef)) + and not node.name.startswith("_") + )] + api_file.write_text(source + "\n__all__ = " + repr(exports) + "\n", encoding="utf-8") + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--polyfem-source-dir", type=Path) + parser.add_argument("--resolved-schema-file", type=Path) + parser.add_argument("--include-spec-dir", type=Path, action="append", default=[]) + parser.add_argument("--check", action="store_true", help="Run example parity tests after generation") + args = parser.parse_args(argv) + if args.resolved_schema_file is None and args.polyfem_source_dir is None: + parser.error("Install with pip to generate automatically, or pass --polyfem-source-dir") + schema = args.resolved_schema_file or args.polyfem_source_dir / "json-specs/input-spec.json" + generator = GENERATOR_ROOT / "tools/generate_with_overrides.py" + for path in (schema, generator): + if not path.is_file(): + parser.error(f"Missing {path}; initialize the pinned submodules with git submodule update --init --recursive") + includes = list(args.include_spec_dir) + search = [schema.parent, *includes] + if args.resolved_schema_file is None and not all( + any((folder / name).is_file() for folder in search) + for name in LINKED_SOLVER_SPEC_FILES + ): + cache = _cache_polysolve_solver_specs(args.polyfem_source_dir) + if cache is None: + parser.error("Linked solver schemas are missing; pass --include-spec-dir with their directory") + includes.append(cache) + command = [sys.executable, str(generator), "--schema-file", str(schema), + "--output-file", str(GENERATED_DIR / "generated_class.py"), + "--api-output-file", str(GENERATED_DIR / "generated_api.py"), + "--manifest-dir", str(GENERATED_DIR), + "--relationships", str(GENERATOR_CONFIG_DIR / "id_relationships.json"), + "--api-aliases", str(GENERATOR_CONFIG_DIR / "api_aliases.json"), + "--model-entry", "polyfempy.model"] + for include in includes: + command.extend(["--include-spec-dir", str(include)]) + subprocess.run(command, cwd=REPO_ROOT, check=True) + write_public_exports() + if args.check: + subprocess.run([sys.executable, "-m", "pytest", "tests/test_generated_api_example.py"], + cwd=REPO_ROOT, check=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())