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 deleted file mode 100644 index 3e9c1dff..00000000 --- a/.github/workflows/continuous.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: Build - -on: [push, pull_request] - -jobs: - Build: - name: ${{ matrix.name }} Python ${{ matrix.python-version }} (${{ matrix.config }}) - 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 - steps: - - name: Checkout repository - uses: actions/checkout@v2 - with: - fetch-depth: 10 - - - name: Setup NMake (Windows) - if: runner.os == 'Windows' - uses: ilammy/msvc-dev-cmd@v1 - - - name: Stetup Conda - uses: s-weigand/setup-conda@v1 - 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 - - - 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: Build (Debug) - if: matrix.config == 'Debug' - run: | - python setup.py build --debug install - - # windows has problem with memory and 2 passes... - - name: Build (Release) - if: matrix.config == 'Release' && runner.os != 'Windows' - run: | - python setup.py build install - - # macos segfaults??? - - name: Tests - if: matrix.name == 'Linux' || matrix.name == 'MacOS' || (matrix.config == 'Debug' && runner.os == 'Windows') - run: | - python test/test_bending.py diff --git a/.github/workflows/generated-contact-backend.yml b/.github/workflows/generated-contact-backend.yml new file mode 100644 index 00000000..592f1164 --- /dev/null +++ b/.github/workflows/generated-contact-backend.yml @@ -0,0 +1,107 @@ +name: Generated Contact Backend + +on: + pull_request: + branches: [main] + types: [opened, synchronize, reopened, ready_for_review, edited] + push: + branches: + - main + workflow_dispatch: + inputs: + generated_source_tolerance: + description: Numeric tolerance for generated vs source JSON metric comparison + required: false + default: "1e-5" + type: string + max_threads: + description: Max backend threads per case + required: false + default: "1" + type: string + +env: + GENERATED_SOURCE_TOLERANCE: ${{ github.event.inputs.generated_source_tolerance || '1e-5' }} + MAX_THREADS: ${{ github.event.inputs.max_threads || '1' }} + +jobs: + generated-contact-backend: + runs-on: ubuntu-latest + if: >- + github.event_name != 'pull_request' || + (github.event.pull_request.draft == false && + (github.event.action != 'edited' || github.event.changes.base != null)) + concurrency: + group: forward-solver-${{ github.ref }} + cancel-in-progress: true + name: Forward solver checks (Ubuntu, Python 3.11) + timeout-minutes: 360 + + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: "3.11" + + - name: Install build and test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install "setuptools>=77" wheel build cmake nanobind numpy pytest + + - name: Generate packaged API + run: python tools/generate_polyfem_api.py + + - name: Build source archive and wheel + # The default build creates the wheel from the unpacked source archive. + run: python -m build --no-isolation + + - name: Check distribution contents + run: python tools/check_distribution.py "dist/*.tar.gz" "dist/*.whl" + + - name: Install wheel in a clean environment + run: | + python -m venv "$RUNNER_TEMP/wheel-test" + "$RUNNER_TEMP/wheel-test/bin/python" -m pip install dist/*.whl + "$RUNNER_TEMP/wheel-test/bin/python" tools/check_installed_package.py \ + --readme README.md --reference polyfem-data/units/neohookean.json \ + --example examples/quickstart/beam.py \ + --example examples/quickstart/static_elasticity.py \ + --example examples/quickstart/transient_elasticity.py + + - name: Install wheel for the full example sweep + run: python -m pip install --force-reinstall --no-deps dist/*.whl + + - name: Upload checked distributions + uses: actions/upload-artifact@v7 + with: + name: polyfempy-ubuntu-py311 + retention-days: 14 + path: dist/* + + - name: Check compiled backend + run: python -I -m polyfempy backend-info --require + + - name: Run active generated contact backend sweep + run: | + python tools/run_generated_contact_backend_checks.py \ + --output-root build/generated-contact-backend-check-release-candidate \ + --generated-source-tolerance "$GENERATED_SOURCE_TOLERANCE" \ + --max-threads "$MAX_THREADS" \ + --require-tests-match + + - name: Upload generated contact backend results + if: always() + uses: actions/upload-artifact@v7 + with: + name: generated-contact-backend-results + if-no-files-found: warn + retention-days: 14 + path: | + build/generated-contact-backend-check-release-candidate/summary.txt + build/generated-contact-backend-check-release-candidate/summary.json + build/generated-contact-backend-check-release-candidate/logs + tools/generated_contact_expected_failures.json diff --git a/.github/workflows/release-packages.yml b/.github/workflows/release-packages.yml new file mode 100644 index 00000000..bbd5d5e5 --- /dev/null +++ b/.github/workflows/release-packages.yml @@ -0,0 +1,164 @@ +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 tools/generate_polyfem_api.py + 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 + + conda: + needs: source + runs-on: ${{ matrix.target.os }} + name: Conda / ${{ matrix.target.name }} / Python ${{ matrix.python }} + timeout-minutes: 360 + strategy: + fail-fast: false + matrix: + python: ["3.11"] + target: + - { name: win-64, os: windows-2022 } + - { name: linux-64, os: ubuntu-latest } + - { name: osx-64, os: macos-15-intel } + - { name: osx-arm64, os: macos-15 } + defaults: + run: + shell: bash -el {0} + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + name: polyfempy-source + path: dist + - uses: conda-incubator/setup-miniconda@v4 + with: + miniforge-version: latest + activate-environment: package-build + python-version: "3.13" + channels: conda-forge + conda-remove-defaults: "true" + channel-priority: strict + - name: Install conda build tools + run: conda install --yes --override-channels --channel conda-forge conda-build + - name: Select the source archive + run: | + python - <<'PY' + import hashlib + 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}") + archive = archives[0].resolve() + with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as output: + output.write(f"POLYFEMPY_SDIST_URL={archive.as_uri()}\n") + output.write(f"POLYFEMPY_SDIST_SHA256={hashlib.sha256(archive.read_bytes()).hexdigest()}\n") + output.write(f"CPM_SOURCE_CACHE={Path(os.environ['RUNNER_TEMP']) / 'pf-cpm'}\n") + PY + - 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 + "CONDA_BLD_PATH=C:/pf-cb" >> $env:GITHUB_ENV + "CPM_SOURCE_CACHE=C:/pf-cpm" >> $env:GITHUB_ENV + - name: Build and test the native conda package + run: >- + conda-build conda/recipe --python "${{ matrix.python }}" + --no-anaconda-upload --override-channels --channel conda-forge + --output-folder conda-out + - uses: actions/upload-artifact@v7 + with: + name: conda-${{ matrix.target.name }}-py${{ matrix.python }} + path: | + conda-out/**/*.conda + conda-out/**/*.tar.bz2 + if-no-files-found: error diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..e52df463 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,71 @@ +name: Test + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + release-files: + name: Documentation and source archive + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - uses: actions/setup-python@v7 + with: + python-version: "3.11" + - name: Check documentation + run: python tools/check_docs.py --online + - name: Build and inspect source archive + run: | + python -m pip install build numpy + python tools/generate_polyfem_api.py + python -m build --sdist + python tools/check_distribution.py "dist/*.tar.gz" + + test: + runs-on: ${{ matrix.os }} + name: ${{ matrix.os }} (py${{ matrix.python-version }}) + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, macos-15-intel, windows-latest] + python-version: ["3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: ${{ matrix.python-version }} + + - name: Install test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install numpy pytest "setuptools>=77" "ruff>=0.17.5,<0.18" + + - name: Check handwritten Python code + run: python -m ruff check python setup.py tools tests + + # python/polyfempy/generated_api is intentionally ignored in git, so CI must + # regenerate it before importing the public generated API. + - name: Generate packaged API + run: python tools/generate_polyfem_api.py + + # Do not run `pip install -e .` here: it compiles the C++ backend. + # This workflow is the backend-free Python/generator test gate. + - name: Run tests + env: + PYTHONPATH: ${{ github.workspace }}/python + run: python -m pytest tests -q + + # Generator tests need their own generic artifacts, separate from the packaged API. + - name: Test the API generator + working-directory: python-from-jse + run: python tools/regenerate_and_test.py diff --git a/.gitignore b/.gitignore index a6cc73b0..995b2882 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,107 @@ +# 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/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..3f1b6311 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,13 @@ +# Use the submodule commits recorded by the parent repository. +[submodule "polyfem"] + path = polyfem + url = https://github.com/polyfem/polyfem.git +[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..3822617c --- /dev/null +++ b/API.md @@ -0,0 +1,263 @@ +# Forward API + +For a complete example with a supplied mesh, use the [README beam](README.md#run-a-forward-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 polyfem` and a fresh `model` with the named bodies. + +```python +import 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]) +body.rhs(value=[0, -1]) + +model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) +config = model.config() +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`. + +## Use an array mesh + +Pass vertex coordinates and zero-based cell indices directly to `solve` when +the mesh is already in Python. This complete example needs no mesh file: + +```python +import numpy as np +import polyfem +from polyfempy import solve + +vertices = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]]) +cells = np.array([[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]]) +model = polyfem.model() +square = model.mesh(mesh="array.msh") +square.material(polyfem.neo_hookean(E=1000, nu=0.3)) +square.dirichlet(value=[0, 0]) +square.rhs(value=[0, -1]) +model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) + +result = solve(vertices, cells, cfg=model.config()) +print(f"Largest displacement component: {abs(result.sol).max():.8g}") +``` + +The result is about `0.00011234568`. Each vertex row contains two coordinates +for 2D or three for 3D; each cell row contains its vertex indices. Supply both +arrays together. They take precedence over mesh files in `cfg`. + +For model selections, configure one deformable mesh with +`model.mesh(mesh="array.msh")`, then pass the arrays to `solve`. The mesh path +is replaced internally; no `array.msh` file is needed. Material and boundary +IDs assigned by the model are preserved. Geometry transformations, refinement, +and selections use the backend's existing geometry loader. Obstacles still +read their configured resources. Multiple enabled deformable entries are +rejected because one pair of arrays cannot identify their bodies. + +This requires a Python extension built with `set_settings_with_mesh` support. +An older extension reports an error rather than ignoring the selections. + +## 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 + +Set the force on each body. Two beams can have different loads: + +```python +beam.rhs(value=[0, -1000]) +another_beam.rhs(value=[200, 0]) +config = model.config() +``` + +For equal loads on two independent beams, call `.rhs(value=[0, -1000])` on both. +One call on a `mesh_array` applies to every copy. Meshes that share a volume +with `same_volume_as` also share its load. + +If both beams receive `[0, -1000]` and they are the only deformable bodies, +`model.config()` exports `"rhs": [0, -1000]` and preserves the mesh volume +tags. When only some bodies have a load, or their loads differ, the JSON +identifies each loaded volume by ID. You can also use `model.rhs([0, -1000])` +to set a uniform load in one call. Choose one RHS style per model. + +## 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/8fe9d8b9a1935231d1005f4121cf7866131b4497/quickstart/transient_elasticity.py). + +```python +model.time(dt=0.01, tend=0.5, integrator="BDF") +model.contact(enabled=True, dhat=0.001) +model.output( + directory="results/example", + json="sim.json", + paraview=polyfem.output_paraview(file_name="sim.pvd"), +) +config = model.config() +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` contains +backend metadata, whose keys may depend on the solve. + +## 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) +body.rhs(value=[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..84a9c18c --- /dev/null +++ b/BUILD.md @@ -0,0 +1,151 @@ +# Build the Python bindings + +For an installed binary package, start with [INSTALL.md](INSTALL.md). +This guide covers building and changing the library. + +Use a Git checkout of the intended release branch. GitHub's **Download ZIP** does +not include submodule contents. Keep the recorded submodule revisions together; +updating each dependency to its latest branch is not the same configuration. + +Clone the forward branch (use a short parent directory on Windows): + +```sh +git clone --branch jingyaoyu_forward --recurse-submodules https://github.com/peteryu0131/polyfem-python.git +cd polyfem-python +``` + +For an existing checkout, select the intended revision first, then run +`git submodule update --init --recursive` from its root. This checks out the +commits recorded by the parent repository. Do not add `--remote` when reproducing +a release: it follows remote branches instead of the recorded commits. +Maintainers should review dependency updates and commit the new submodule +pointers explicitly. + +Use an environment with Python 3.10 or later, CMake 3.25 or later, and a C++ compiler. On Windows, use an x64 Visual Studio development environment. To use an existing conda environment named `polyfem`, activate it with `conda activate polyfem` first. + +On Windows, use a short checkout path such as `C:\src\polyfem-python`. Some +third-party MSBuild projects still fail when generated paths exceed 260 characters. + +## Development install + +```sh +python -m pip install "setuptools>=77" wheel build "cmake>=3.25" "nanobind>=2" numpy pytest +python tools/generate_polyfem_api.py +python -m pip install -e . --no-build-isolation +python -m polyfempy backend-info --require +``` + +Both Python packages live under `python/`. After moving from an older checkout +layout, repeat the development install above to refresh editable-install paths. + +Regenerate the API after updating the schemas, generator or generator configuration. Generation writes to `python/polyfempy/generated_api/` and may download the linked solver schemas. PolySolve schemas are cached under `build/polysolve-json-specs//`, using the revision in the pinned PolyFEM source. Switching that revision selects a separate cache. The first native build also needs access to the pinned third-party dependencies. + +Generation is currently an explicit prerequisite, not an automatic installation +step. Run it before building or installing from source. Installed wheel users +receive the generated API and its small builder runtime inside the wheel. +They do not need a separate generator checkout. A build fails early if these +files are missing. + +The distribution is named `polyfempy`. Check its public model-building import +with the same interpreter used for installation: + +```sh +python -c "import polyfem; print(type(polyfem.model()).__name__)" +``` + +## Build and check a wheel + +From a fresh checkout with the development dependencies and generated API in place, run: + +```sh +python -m build --no-isolation +``` + +This creates a source archive, then builds the wheel from the extracted archive. +Set `N_THREADS` to a positive integer to limit parallel compilation. The default +is at most two workers. Visual Studio builds one project at a time and assigns +the worker limit to its compiler, so parallel settings do not multiply. Release builds enable +PolyFEM's portable CPU settings. + +macOS builds use Apple Accelerate and Eigen solvers on both Intel and Apple +Silicon. MKL is disabled on macOS. The examples select +`Eigen::SimplicialLDLT`, which is available on all supported platforms. + +In a separate environment with a compatible Python version and architecture, +install the resulting wheel by its full path. Run the installed-package check +from the checkout: + +```sh +python tools/check_installed_package.py --readme README.md --reference polyfem-data/units/neohookean.json +``` + +The check starts isolated Python processes in a temporary directory. It verifies +the import location, native backend, README beam, installation self-check, Python +load function, and six cube error metrics. Run from the checkout root so the +check can find `INSTALL.md`, `examples/quickstart/beam.obj`, and the cube reference +in `polyfem-data`. +The cube data is not included in the source archive; omit `--reference` there +to check the beam, installation self-check, and Python load function. +For the full example sweep, see [TESTING.md](TESTING.md). + +Check both `import polyfem` and `python -I -m polyfempy backend-info --require` there. +An editable install or a wheel assembled with an existing local binary does not +verify a fresh native build of the release revision. + +## Build adapters + +The parent repository owns the Python extension build adapters in +`cmake/recipes/polyfem.cmake` and `cmake/recipes/libigl.cmake`. They do not edit +the PolyFEM submodule. + +The Python adapter disables the backend's interpreter-embedding setup, then +links its target with `pybind11::module` and enables Python expressions. +`POLYFEM_WITH_PYTHON=OFF` still disables Python expressions. Nanobind remains +the binding library for the public extension. + +The libigl adapter uses the pinned dependency version and the patches shipped +with PolyFEM. It applies them with `git apply`, without shell redirection or a +separate `patch` program. Review this adapter when upgrading the PolyFEM pin. + +The adapter tests configure small CMake fixtures without downloading dependencies +or compiling C++. They do not replace native build and installed-package checks. + +## Source archives + +The source archive includes the binding sources, pinned PolyFEM sources, +generated API, and builder runtime. It does not need Git submodules after +extraction. A compiler and network access for pinned native dependencies are +still required. Mesh data and the full example collection are not build inputs. + +Use a Git checkout when changing schemas or regenerating the API. The archive +contains the generated package, not the complete generator development tools +or the repository test suite. Run development tests from a Git checkout. +The archive retains `tools/check_installed_package.py` and the quick-start +scripts for checking an installed build. + +## Windows compatibility settings + +Importing `polyfempy` leaves Python's output streams and OpenMP environment +settings unchanged by default. If an existing application needs the previous +console and OpenMP workarounds, set `POLYFEMPY_WINDOWS_AUTOCONFIG=1` before +importing. `POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG=1` always disables automatic changes. +Use this option only for an application that needs those settings. + +## What the build tools do + +| Component | Role | +| --- | --- | +| `python-from-jse` | Generates Python configuration classes and model-building helpers from schemas. | +| `python/polyfempy/runtime/` | Prepares solve inputs and wraps the native result as `Result`. | +| nanobind | Exposes the C++ solver and its methods to Python and converts supported argument and result types. | +| CMake and a C++ compiler | Build PolyFEM and the Python extension. | +| pip and conda | Install packages into the selected Python environment. | + +The call path is `model.config()` -> Python `solve()` -> the bound C++ `Solver` +-> PolyFEM -> `Result`. The bindings are declared in `src/binding.cpp` and +`src/state/state.cpp`. They are compiled, not generated by `python-from-jse`. + +The build uses nanobind's shared runtime. On Windows, the reviewed wheel contains +`polyfempy.pyd` and `nanobind.dll`. Release packaging must include and check the +corresponding native libraries on each platform. End users should not have to +install the binding toolchain to use a binary package. diff --git a/CMakeLists.txt b/CMakeLists.txt index 509e07bc..4946881b 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,23 +1,31 @@ ################################################################################ # Check required CMake version -set(REQUIRED_CMAKE_VERSION "3.14.0") +set(REQUIRED_CMAKE_VERSION "3.25.0") cmake_minimum_required(VERSION ${REQUIRED_CMAKE_VERSION}) if(INPUT_POLYFEMPY_DATA_ROOT) - set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/${INPUT_POLYFEMPY_DATA_ROOT}/") + if(IS_ABSOLUTE "${INPUT_POLYFEMPY_DATA_ROOT}") + set(POLYFEMPY_DATA_ROOT "${INPUT_POLYFEMPY_DATA_ROOT}") + else() + set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/${INPUT_POLYFEMPY_DATA_ROOT}") + endif() else() - set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/data/") -endif() -if(NOT EXISTS ${POLYFEMPY_DATA_ROOT}) - file(MAKE_DIRECTORY ${POLYFEMPY_DATA_ROOT}) + set(POLYFEMPY_DATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/polyfem-data") endif() project(polyfempy) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + ################################################################################ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/recipes/") +include(polyfem_cpm_cache) + # Color output include(UseColors) @@ -27,7 +35,7 @@ include(PrependCurrentPath) # Extra warnings include(Warnings) -# Use C++11/14 +# Enable compiler features required by dependencies. include(CXXFeatures) # Sort projects inside the solution @@ -40,22 +48,80 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Polyfem library ################################################################################ +# Use nanobind for Python bindings (pybind11 support removed) +include(CPM) +# Force robin-map to 1.4.1 (or >=1.3.0) BEFORE including polyfem +# This ensures CPM uses the correct version, overriding any indirect dependencies +# (e.g., polyfem's ipc-toolkit may try to use robin-map 1.2.1, which is too old) +# nanobind requires: >= 1.3.0, < 2.0.0 + CPMAddPackage( + NAME robin-map + GITHUB_REPOSITORY Tessil/robin-map + GIT_TAG v1.4.1 # Use 1.4.1 (recommended) or at least >= 1.3.0, < 2.0.0 + OPTIONS + "ROBIN_MAP_BUILD_TESTS OFF" + "ROBIN_MAP_BUILD_EXAMPLES OFF" + ) + if(TARGET tsl::robin_map) + message(STATUS "Pre-declared robin-map 1.4.1 for nanobind compatibility") + else() + message(WARNING "Failed to pre-declare robin-map 1.4.1 - may cause version conflicts") +endif() + # dependencies +set(POLYFEM_WITH_TESTS OFF CACHE BOOL "Build PolyFEM tests") include(polyfem) -include(pybind11) -include(pybind11_json) -#for testing purpose -include(polyfem_data) +# This executable embeds schemas at build time. Only runtime binaries belong in the wheel. +if(TARGET jse_embed_spec_tool) + set_target_properties(jse_embed_spec_tool PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/tools/$" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_CURRENT_BINARY_DIR}/tools/Release") +endif() + + # Use a shared nanobind runtime alongside the extension. + set(NB_STATIC_LIB OFF CACHE BOOL "Disable nanobind static library" FORCE) + + message(STATUS "Using nanobind for Python bindings") + include(nanobind) + +# Mesh data is only needed for examples and numerical tests. +if(INPUT_POLYFEMPY_DATA_ROOT) + include(polyfem_data) +endif() ################################################################################ # 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}") - - - + # Place the shared runtime and the extension in the same package. + nanobind_add_module(polyfempy NB_SHARED) + + # Verify no static library target was created (safety check) + if(TARGET nanobind-static) + message(FATAL_ERROR + "Unexpected static nanobind target.\n" + "Keep NB_STATIC_LIB disabled and use NB_SHARED for this extension." + ) + endif() + + add_subdirectory(src) + target_include_directories(polyfempy PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") + target_link_libraries(polyfempy PRIVATE polyfem::polyfem) + # Define macro for source files + target_compile_definitions(polyfempy PRIVATE USE_NANOBIND) + +# Ensure the produced module has the correct Python extension suffix. +# Prefer FindPython's canonical variable `Python_EXTENSION_MODULE_SUFFIX`. +# Example on Windows: `.cp311-win_amd64.pyd` +if(DEFINED Python_EXTENSION_MODULE_SUFFIX AND NOT "${Python_EXTENSION_MODULE_SUFFIX}" STREQUAL "") + set_target_properties(polyfempy PROPERTIES PREFIX "" SUFFIX "${Python_EXTENSION_MODULE_SUFFIX}") +elseif(DEFINED Python_EXTENSION_SUFFIX AND NOT "${Python_EXTENSION_SUFFIX}" STREQUAL "") + # Backwards/alt name in some CMake setups. + set_target_properties(polyfempy PROPERTIES PREFIX "" SUFFIX "${Python_EXTENSION_SUFFIX}") +elseif(WIN32) + # Last resort: ensure it is importable as a Python extension on Windows. + set_target_properties(polyfempy PROPERTIES PREFIX "" SUFFIX ".pyd") +else() + message(WARNING "Python extension module suffix not defined; leaving default target suffix.") +endif() diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..651fc316 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,146 @@ +# Install PolyFEM for Python + +The distribution is named `polyfempy`. Use `import polyfem` to build a model and +`from polyfempy import solve` to run it. + +## Release status + +The forward release is being prepared. Its reviewed Windows x64 wheel works +with CPython 3.11, including in a new conda environment. Linux and macOS native +packages still need successful release builds and installation checks. + +The existing public packages contain older APIs. As checked on 2026-11-15, +[conda-forge](https://anaconda.org/conda-forge/polyfempy) provides version 0.5.2 +for Windows x64, Linux x64, and Intel macOS. [PyPI](https://pypi.org/project/polyfempy/) +provides a 0.2.3 source archive. Installing either does not install this forward +branch or its new model builder. + +The new release keeps conda, pip, and source installation as release targets. +The initial installation checks use CPython 3.11 on Windows x64, Linux x64, +Intel macOS, and Apple Silicon macOS. A configured job is not proof that a +platform works. + +This branch requires Python 3.10 or later. Python-only tests cover CPython +3.10-3.12. Native package checks for Python 3.10 and Python 3.12 are deferred +until release preparation. The legacy project's Python 3.7/3.8 +support does not apply to the current API. + +## Install a reviewed wheel with pip + +This section assumes a maintainer has supplied a tested `.whl` file. +There is no published forward release to download from the package indexes. +If you do not have a wheel, follow [BUILD.md](BUILD.md). +Choose a wheel for your operating system, CPU architecture, and Python version. +A Windows wheel cannot be used on Linux or macOS. Intel and Apple Silicon Macs +also need matching binaries. + +Create a new environment. For Windows with CPython 3.11 installed: + +```powershell +py -3.11 -m venv .venv +.venv\Scripts\Activate.ps1 +``` + +For Linux or macOS with CPython 3.11 installed: + +```sh +python3.11 -m venv .venv +source .venv/bin/activate +``` + +From the directory containing the wheel, install it with the active environment's +Python. This filename is the reviewed Windows x64 / CPython 3.11 build: + +```sh +python -m pip install --only-binary=:all: ./polyfempy-0.8-cp311-cp311-win_amd64.whl +python -m pip check +``` + +Use the corresponding filename for another platform when its checked wheel is +available. `--only-binary=:all:` prevents an unexpected source build. Wheel users +do not need CMake, a compiler, a separate nanobind installation, or Git submodules. + +## Use pip inside a conda environment + +Create the environment first, then install the matching wheel as shown above: + +```sh +conda create -n polyfem-user --override-channels -c conda-forge python=3.11 pip numpy +conda activate polyfem-user +``` + +Use `python -m pip` after activation so installation uses this environment. +See conda's [environment guide](https://docs.conda.io/projects/conda/en/stable/user-guide/tasks/manage-environments.html#using-pip-in-an-environment) +for guidance on mixing conda and pip packages. + +## Install a native conda package + +The original library's supported command is: + +```sh +conda install -c conda-forge polyfempy +``` + +Until the feedstock is updated, this installs the legacy release. The new native +conda package must pass the recipe's installation and solve checks before it is +submitted to the existing [feedstock](https://github.com/conda-forge/polyfempy-feedstock). +Maintainers can build and test it using [conda/README.md](conda/README.md). + +A native conda package and a pip wheel installed inside conda are separate +distribution routes. Both are part of the release checks. + +## Check the installation + +```sh +python -I -c "import polyfem; from polyfempy import solve; print(type(polyfem.model()).__name__)" +python -I -m polyfempy backend-info --require +``` + +The second command must report `backend_available=True`. + +Save the following code as `check_install.py` and run `python check_install.py`. +It creates a small square mesh, fixes its boundary, and applies a downward body +force. Only the center vertex can move. No example data download is needed. + +```python +from pathlib import Path +from tempfile import TemporaryDirectory + +import polyfem +from polyfempy import solve + +with TemporaryDirectory() as folder: + mesh = Path(folder) / "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\n" + "f 1 2 5\nf 2 3 5\nf 3 4 5\nf 4 1 5\n", + encoding="utf-8", + ) + + model = polyfem.model() + square = model.mesh(mesh=str(mesh)) + square.material(polyfem.neo_hookean(E=1000, nu=0.3)) + square.surface_all().dirichlet(value=[0, 0]) + square.rhs(value=[0, -1]) + model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) + + result = solve(cfg=model.config()) + print(f"Largest displacement component: {abs(result.sol).max():.8f}") +``` + +The last line should report a value of about `0.00011235`. This checks that the +installed package can run a complete simulation. Then try the +[README cantilever beam](README.md#run-a-forward-simulation) with its supplied mesh. + +If pip rejects a wheel, check the Python version and architecture before trying +another file. If an import fails, check the active interpreter with +`python -c "import sys; print(sys.executable)"`. A successful Python import alone +does not establish that the native solver can load. + +## Build from source + +Use [BUILD.md](BUILD.md) when changing the library or building for a platform +without a compatible binary. Source builds need a C++ compiler and native build +dependencies. The current equivalents of the legacy setup.py commands are +`python -m pip install .` and `python -m pip install -e .`, after the preparation +steps in that guide. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 00000000..842220a2 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,16 @@ +include CMakeLists.txt API.md BUILD.md INSTALL.md TESTING.md cibuildwheel.toml +recursive-include conda *.md *.yaml *.sh *.bat +recursive-include examples/quickstart *.py *.obj +recursive-include cmake *.cmake +recursive-include src CMakeLists.txt *.cpp *.hpp *.h +include polyfem/CMakeLists.txt polyfem/LICENSE +graft polyfem/cmake +graft polyfem/src +graft polyfem/json-specs +include python-from-jse/LICENSE +recursive-include python/polyfempy/generated_api *.py *_manifest.json +include tools/check_installed_package.py + +# Repository tests require development tools and reference data not shipped here. +prune tests +global-exclude __pycache__ *.py[cod] .DS_Store diff --git a/README.md b/README.md index ef00ea4c..25cdfbee 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,87 @@ -# polyfem-python -![Build](https://github.com/polyfem/polyfem-python/workflows/Build/badge.svg) +# PolyFEM for Python +Build a finite element model with `import polyfem` and run it with `from polyfempy import solve`. The Python API configures the simulation and the compiled PolyFEM backend computes the solution. -[![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) +## Installation +This forward API is not yet published on PyPI or conda-forge. +[Build this branch from source](BUILD.md), or install a tested wheel supplied +by a maintainer. See the [installation guide](INSTALL.md) for commands and +platform status. +## Run a forward simulation +Simulate a 1 m x 0.2 m elastic beam. Fix its left end, apply a downward body +force, and compute its displacement. This example uses meters and pascals. -The python bindings are in alpha. Expect a lot of API changes and possible bugs. Use at your own peril! +Download [beam.obj](https://raw.githubusercontent.com/polyfem/python_data/6b4751b9c3f40fb9653601efe32ce6b6d0ead96f/quickstart/beam.obj) +(12 KB) and save the following code as `beam.py` in the same folder. -
-I am making efforts to provide a simple python interface to Polyfem. +```python +import polyfem +from polyfempy import solve -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). +model = polyfem.model() +beam = model.mesh(mesh="beam.obj") +beam.material(polyfem.linear_elasticity(E=1e7, nu=0.3)) -Note that the conda deployment is slow and this tutorial will follow the deployment version. +# Fix the left end at x = 0. +left = beam.surface_axis(axis="-x", position=0.0) +left.dirichlet(value=[0, 0]) -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 +# Apply a downward body force (N/m^3). +beam.rhs(value=[0, -1000]) +model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) + +result = solve(cfg=model.config()) +print(f"Largest displacement component: {abs(result.sol).max():.6f} m") ``` -and + +Run it from that folder: + +```sh +python beam.py ``` -python setup.py test + +The last line should be approximately: + +```text +Largest displacement component: 0.003648 m ``` -for testing. -For python documentation [https://polyfem.github.io/python/](https://polyfem.github.io/python/). +Try changing `E` to adjust the material stiffness, or change the load in +`beam.rhs(...)`. The [complete script](https://github.com/polyfem/python_data/blob/8fe9d8b9a1935231d1005f4121cf7866131b4497/quickstart/beam.py) +also works when run from another directory, using the mesh beside it. + +`result.sol` is the raw finite-element solution; do not assume that each row +corresponds to a mesh vertex. For a small check that creates its own mesh, +run the [installation self-check](INSTALL.md#check-the-installation). + +For larger models, see the [classic example guide](https://github.com/polyfem/python_data/blob/8fe9d8b9a1935231d1005f4121cf7866131b4497/README.md) and the +[pinned example sources](https://github.com/polyfem/python_data/tree/8fe9d8b9a1935231d1005f4121cf7866131b4497/classic_example). +These reference examples require their mesh data and may select linear solvers +that are not enabled in every backend build. + +Download either of these scripts and run it with Python in the same environment: +[static elasticity](https://github.com/polyfem/python_data/blob/8fe9d8b9a1935231d1005f4121cf7866131b4497/quickstart/static_elasticity.py) and +[transient elasticity](https://github.com/polyfem/python_data/blob/8fe9d8b9a1935231d1005f4121cf7866131b4497/quickstart/transient_elasticity.py). +Both create their own mesh and use `Eigen::SimplicialLDLT`. The transient example +also shows time settings and an output directory. + +## Source layout + +- `python/polyfem/` exposes the model builder and generated configuration helpers. +- `python/polyfempy/runtime/` implements `solve` and returns the solution in `result.sol`. +- `src/` binds the Python runtime to the C++ solver in the `polyfem/` submodule. +- `python-from-jse/` generates the configuration API from PolyFEM schemas and the rules in `generator-config/`. +- `polyfem-data/` supplies the official meshes, input configurations, and reference values. + +## Forward solver validation -For python jupyter notebook [https://polyfem.github.io/python_examples/](https://polyfem.github.io/python_examples/). +Push checks run Python and API tests on Windows, Linux, and macOS. Native builds +and simulation checks run in separate workflows. On a ready-for-review pull +request targeting `main`, **Generated Contact Backend** builds and installs a +wheel, runs the short examples and cube reference check, then runs the 75 active +contact cases. See [TESTING.md](TESTING.md) for triggers, commands, and artifacts. -For full documentation see [https://polyfem.github.io/](https://polyfem.github.io/). +See the [API guide](API.md) for geometry, materials, boundary conditions and loads. diff --git a/TESTING.md b/TESTING.md new file mode 100644 index 00000000..c952d01f --- /dev/null +++ b/TESTING.md @@ -0,0 +1,173 @@ +# Testing the forward API + +Run development tests from a Git checkout after initializing its submodules. +The source archive omits the repository test suite and its development-only +inputs. It retains the installed-package check and quick-start examples. +See [BUILD.md](BUILD.md) for the native build. + +## Python and example tests + +Generate the Python API before running the tests: + +```sh +python -m pip install numpy pytest "setuptools>=77" +python tools/generate_polyfem_api.py +python -m pytest -q -rs +``` + +The pytest configuration selects `tests/` and adds the public package directory +to the import path. Submodule tests run separately. +The suite includes comparisons between classic example configurations and +official JSON inputs. This forward branch does not require PyTorch. + +When reviewing a new backend revision before rebuilding, exclude native solves: + +```sh +python -m pytest tests --ignore=tests/test_backend_smoke.py --deselect=tests/test_array_mesh_selections.py::test_native_array_selections_match_a_file_solve -q -rs +``` + +This also runs the small CMake adapter fixtures without compiling C++ or +downloading native dependencies. An existing local extension or installed wheel +may belong to an older backend revision; it cannot validate the new source pin. + +The native smoke test skips unless you explicitly select a build as described +below. Windows also skips the tests for the non-Windows runtime branch. Check the reasons with +`-rs`; a skipped native test does not establish that the solver works. + +The generator has its own standalone suite. From `python-from-jse/`, run +`python tools/regenerate_and_test.py`. CI uses this same command to generate +the generic test files before compiling and testing them. Generating the parent +package API does not create these files in `python-from-jse/generated/`. +The parent wrapper's `--check` option runs the parent API/example checks, +not that standalone suite. + +## Native solver + +After rebuilding the Python extension, run +`python -m pytest tests/test_array_mesh_selections.py -q -rs` to check array +selection binding. Two native cases compare whole and partial boundary solves +against file input. They skip when the backend is unavailable; the remaining +cases check Python routing and automatic IDs without a native solve. +These tests do not build the extension. + +With a wheel installed in a clean environment, run the README beam, +installation self-check, and Neo-Hookean cube reference check: + +```sh +python tools/check_installed_package.py --readme README.md --reference polyfem-data/units/neohookean.json --example examples/quickstart/beam.py --example examples/quickstart/static_elasticity.py --example examples/quickstart/transient_elasticity.py +``` + +This check runs outside the checkout and fails if the backend cannot load. +It checks the README beam and the small square in `INSTALL.md` against their +expected results, repeats the square with a Python load function, checks all six +cube metrics, then runs the three quick-start +scripts. The beam mesh is copied from `examples/quickstart/beam.obj`; the check +does not download it. An editable install is not accepted as a wheel validation. + +To check an existing native build, select the package root containing both +`polyfempy/__init__.py` and its compiled extension. For example, with a Windows +Python 3.11 build: + +```sh +python -m pytest tests/test_backend_smoke.py --backend-package-dir build/lib.win-amd64-cpython-311 -q -s +``` + +Use the actual build directory for your platform and Python version. This +option applies to the smoke test. It does not build or install anything. +The test uses isolated child processes, verifies the package and native module +paths, and prints the native binary's SHA-256. The solve must use the same +binary as the initial check. A missing or unloadable selected build fails; +the test does not fall back to another package. Without this option, it skips. + +The path and hash identify the binary being tested, not its PolyFEM commit. +When checking a source-pin update, select the build made for that revision. + +## Code checks + +```sh +python -m pip install "ruff>=0.17.5,<0.18" +python -m ruff check python setup.py tools tests +``` + +These checks cover syntax, undefined names, and unused imports in handwritten +Python code. Generated output and external submodules are excluded. + +Check documentation links, Python snippet syntax, and built archive contents: + +```sh +python tools/check_docs.py --online +python tools/check_distribution.py "dist/*.tar.gz" "dist/*.whl" +``` + +Omit `--online` to check local links without network access. The documentation +check rejects relative links that cross a Git submodule boundary, even when the +file exists locally. Archive checks require runtime files and reject repository +tests, build output, and caches. Use only the archive patterns you have built. +The Test workflow checks documentation and a fresh source archive on every push. + +## GitHub Actions + +| When | What runs | +| --- | --- | +| Push or pull request | Python, generated API, and generator unit tests on Windows, macOS and Linux with Python 3.10-3.12 | +| Manual release-package check before publishing | Source archive, pip wheels, native conda packages, and installed-package checks across the release matrix | +| Draft PR, or PR targeting another branch | Fast Python and documentation checks only | +| Ready-for-review PR targeting `main` | Clean wheel installation, beam, installation self-check, cube and quick-start checks, then the full contact sweep on open, update, reopen, marking ready or retargeting to `main` | +| Manual run of Generated Contact Backend, or push to main | The same wheel and simulation checks, then the full contact sweep | + +Before merging, check **Forward solver checks (Ubuntu, Python 3.11)** on the latest PR revision. The full sweep runs the 75 active cases and compares the generated configurations with the official inputs and their reference metrics. For an on-demand check, open **Actions -> Generated Contact Backend -> Run workflow** and select the branch. To run the same check locally: + +```sh +python tools/run_generated_contact_backend_checks.py --output-root build/contact-check --generated-source-tolerance 1e-5 --max-threads 1 --require-tests-match +``` + +Read `build/contact-check/summary.txt` for the outcome and the per-case logs for failures. In GitHub Actions, download the **generated-contact-backend-results** artifact from the workflow run to inspect those files. + +The sweep follows each reference input's `tests.time_steps`; a transient case +without that field is reduced to one step. It also selects a portable linear +solver for both runs, generally `Eigen::SimplicialLDLT`. Passing the sweep checks +these regression configurations, not every example's original full-duration +command or its original solver choice. + +## Release-package checks + +The **Release Packages** workflow builds one source archive, then uses +it for pip wheels and native conda packages. The initial installation checks +use CPython 3.11 on Windows x64, Linux x64, Intel macOS, and Apple Silicon +macOS. This preserves the legacy conda package's platforms and adds native +support for M-series Macs. There are nine jobs: one source archive, +four wheel builds, and four conda builds. +Expand and validate the matrix for Python 3.10 and Python 3.12 +before publishing packages for those targets. +Each job installs its output and runs the README beam, installation self-check, +Python load function, and all three quick-start scripts. Each simulation has a +five-minute timeout so a stalled native call fails the check. +Wheel builds use cibuildwheel's dependency repair step before installation. + +Pushes and pull requests do not run the package matrix. Use **Actions -> Release Packages +-> Run workflow** when checking installation packages before a release. Manual +runs become available once the workflow exists on the repository's default +branch; see +[GitHub's manual-run instructions](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). + +Before that workflow reaches the default branch, use the local build and +installation commands above. No separate validation branch is needed. +Review every job for the exact revision being released. +Successful jobs produce downloadable artifacts without publishing to package indexes. See +[INSTALL.md](INSTALL.md) for the verified user installation routes and +[conda/README.md](conda/README.md) for the native conda recipe. + +The separate contact-backend workflow builds a source archive and wheel on Linux. It +installs the wheel in a fresh environment and checks it outside the checkout. +This does not establish native wheel support on Windows or macOS. Before +publishing, validate each intended platform and Python version: + +1. Confirm `import polyfem`, `from polyfempy import solve`, and backend loading. +2. Run the README beam and installation self-check against their expected values. +3. Run the cube reference check with the pinned data and inspect all six metrics. +4. Run the required contact sweep on the same release revision. +5. If publishing a source archive, build a wheel from that extracted archive. + See [BUILD.md](BUILD.md#source-archives) for the archive contents. + +A configured GitHub workflow is a test plan; review a successful run for the +actual release commit before treating it as release evidence. diff --git a/cibuildwheel.toml b/cibuildwheel.toml new file mode 100644 index 00000000..68ee62f1 --- /dev/null +++ b/cibuildwheel.toml @@ -0,0 +1,15 @@ +[tool.cibuildwheel] +build = "cp311-*" +skip = "*-musllinux_*" +build-frontend = "build" +environment = { N_THREADS = "1" } +test-command = [ + "python -m pip check", + 'python -I "{package}/tools/check_installed_package.py" --readme "{package}/README.md" --example "{package}/examples/quickstart/beam.py" --example "{package}/examples/quickstart/static_elasticity.py" --example "{package}/examples/quickstart/transient_elasticity.py"', +] + +[tool.cibuildwheel.linux] +manylinux-x86_64-image = "manylinux_2_28" + +[tool.cibuildwheel.macos] +environment = { N_THREADS = "1", MACOSX_DEPLOYMENT_TARGET = "11.0" } diff --git a/cmake/recipes/CPM.cmake b/cmake/recipes/CPM.cmake new file mode 100644 index 00000000..c7b9c090 --- /dev/null +++ b/cmake/recipes/CPM.cmake @@ -0,0 +1,33 @@ +set(CPM_DOWNLOAD_VERSION 0.42.0) + +if(CPM_SOURCE_CACHE) + set(CPM_DOWNLOAD_LOCATION "${CPM_SOURCE_CACHE}/cpm/CPM_${CPM_DOWNLOAD_VERSION}.cmake") +elseif(DEFINED ENV{CPM_SOURCE_CACHE}) + set(CPM_DOWNLOAD_LOCATION "$ENV{CPM_SOURCE_CACHE}/cpm/CPM_${CPM_DOWNLOAD_VERSION}.cmake") +else() + set(CPM_DOWNLOAD_LOCATION "${CMAKE_BINARY_DIR}/cmake/CPM_${CPM_DOWNLOAD_VERSION}.cmake") +endif() + +# Expand relative path. This is important if the provided path contains a tilde (~) +get_filename_component(CPM_DOWNLOAD_LOCATION ${CPM_DOWNLOAD_LOCATION} ABSOLUTE) + +function(download_cpm) + message(STATUS "Downloading CPM.cmake to ${CPM_DOWNLOAD_LOCATION}") + file(DOWNLOAD + https://github.com/cpm-cmake/CPM.cmake/releases/download/v${CPM_DOWNLOAD_VERSION}/CPM.cmake + ${CPM_DOWNLOAD_LOCATION} + ) +endfunction() + +if(NOT (EXISTS ${CPM_DOWNLOAD_LOCATION})) + download_cpm() +else() + # resume download if it previously failed + file(READ ${CPM_DOWNLOAD_LOCATION} check) + if("${check}" STREQUAL "") + download_cpm() + endif() + unset(check) +endif() + +include(${CPM_DOWNLOAD_LOCATION}) diff --git a/cmake/recipes/libigl.cmake b/cmake/recipes/libigl.cmake new file mode 100644 index 00000000..f80394d7 --- /dev/null +++ b/cmake/recipes/libigl.cmake @@ -0,0 +1,40 @@ +# libigl (https://github.com/libigl/libigl) +# License: MPL + +# +# 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 igl::core) + return() +endif() + +# Keep dependency patches in the submodule and build integration in the parent. +message(STATUS "Third-party: creating target 'igl::core'") + +set(LIBIGL_PREDICATES ON CACHE BOOL "Use exact predicates" FORCE) + +include(CMakeDependentOption) +cmake_dependent_option(LIBIGL_RESTRICTED_TRIANGLE "Build target igl_restricted::triangle" ON "POLYFEM_WITH_TRIANGLE" ON) + +find_package(Git REQUIRED) + +file(GLOB_RECURSE patches_for_libigl CONFIGURE_DEPENDS + "${POLYFEMPY_POLYFEM_ROOT}/cmake/patches/igl_*.patch" +) + +include(CPM) +CPMAddPackage( + NAME libigl + GITHUB_REPOSITORY "libigl/libigl" + GIT_TAG "aeeea9b416a5b5474cb9d12c07ff1238a4c83ba1" + PATCH_COMMAND "${GIT_EXECUTABLE}" apply --ignore-whitespace --whitespace=nowarn ${patches_for_libigl} +) diff --git a/cmake/recipes/nanobind.cmake b/cmake/recipes/nanobind.cmake new file mode 100644 index 00000000..9af9daf7 --- /dev/null +++ b/cmake/recipes/nanobind.cmake @@ -0,0 +1,150 @@ +# nanobind (https://github.com/pywrap/nanobind) +# License: BSD-style +if(TARGET nanobind::nanobind) + return() +endif() + +message(STATUS "Third-party: creating target 'nanobind::nanobind'") + +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 () + +# Find Python for nanobind +if(DEFINED PYTHON_EXECUTABLE AND NOT DEFINED Python_EXECUTABLE) + set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}" CACHE FILEPATH "Python executable for FindPython" FORCE) +endif() +find_package(Python COMPONENTS Interpreter Development.Module REQUIRED) +set(PYTHON_EXECUTABLE ${Python_EXECUTABLE}) + +# Try to find nanobind from installed package first +execute_process( + COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir + OUTPUT_STRIP_TRAILING_WHITESPACE + OUTPUT_VARIABLE nanobind_DIR + RESULT_VARIABLE nanobind_found_result + ERROR_QUIET +) + +if(nanobind_found_result EQUAL 0 AND EXISTS "${nanobind_DIR}") + message(STATUS "Found nanobind via pip: ${nanobind_DIR}") + + # Check if nanobind has bundled submodule (ext/robin-map) + # pip-installed nanobind may or may not include submodules + set(NANOBIND_EXT_DIR "${nanobind_DIR}/../ext") + set(NANOBIND_ROBIN_MAP_DIR "${NANOBIND_EXT_DIR}/robin-map") + + if(EXISTS "${NANOBIND_ROBIN_MAP_DIR}/include/tsl/robin_map.h") + message(STATUS "Found nanobind bundled robin-map submodule at: ${NANOBIND_ROBIN_MAP_DIR}") + # Use bundled submodule - this ensures correct 1.x version + set(NB_USE_SUBMODULE_DEPS ON CACHE BOOL "Use nanobind bundled submodule dependencies" FORCE) + else() + message(STATUS "nanobind bundled robin-map not found, will use CPM or existing declaration") + # No bundled submodule - we need to provide compatible robin-map 1.x + # Check if robin-map is already declared (e.g., by top-level CMakeLists.txt) + set(NB_USE_SUBMODULE_DEPS OFF CACHE BOOL "Use external tsl::robin_map" FORCE) + + # Check if tsl::robin_map target already exists (from top-level CMakeLists.txt) + if(NOT TARGET tsl::robin_map) + message(STATUS "robin-map not pre-declared, fetching compatible version via CPM") + # Fetch compatible robin-map 1.x via CPM before finding nanobind + # This ensures find_dependency(tsl-robin-map) finds the correct version + # nanobind requires: >= 1.3.0, < 2.0.0 + include(CPM) + CPMAddPackage( + NAME robin-map + GITHUB_REPOSITORY Tessil/robin-map + GIT_TAG v1.4.1 # Use 1.4.1 (recommended) or at least >= 1.3.0, < 2.0.0 + OPTIONS + "ROBIN_MAP_BUILD_TESTS OFF" + "ROBIN_MAP_BUILD_EXAMPLES OFF" + ) + + if(TARGET tsl::robin_map) + message(STATUS "Successfully fetched robin-map 1.x via CPM") + else() + message(FATAL_ERROR "Failed to fetch compatible robin-map 1.x via CPM") + endif() + else() + message(STATUS "Using pre-declared robin-map (should be >= 1.3.0, < 2.0.0)") + endif() + endif() + + # Explicitly disable static library mode (use shared library) + set(NB_STATIC_LIB OFF CACHE BOOL "Disable nanobind static library" FORCE) + + # Make sure CMake searches this directory for nanobindConfig + list(PREPEND CMAKE_PREFIX_PATH "${nanobind_DIR}") + + # Find nanobind package + find_package(nanobind CONFIG REQUIRED) + + # Diagnostic: Verify robin_map version after find_package + # Check if any robin_map header is found and verify version + # Note: We don't use NO_DEFAULT_PATH to allow searching CMAKE_PREFIX_PATH (including conda paths) + find_path(ROBIN_MAP_HEADER_PATH + NAMES tsl/robin_map.h + PATHS + "${NANOBIND_ROBIN_MAP_DIR}/include" + PATH_SUFFIXES + include + ) + + if(ROBIN_MAP_HEADER_PATH) + message(STATUS "Using robin_map header at: ${ROBIN_MAP_HEADER_PATH}") + # Try to detect version by reading the header + file(READ "${ROBIN_MAP_HEADER_PATH}/tsl/robin_map.h" ROBIN_MAP_HEADER_CONTENT LIMIT 1000) + if(ROBIN_MAP_HEADER_CONTENT MATCHES "TSL_ROBIN_MAP_VERSION_MAJOR[ \t]+([0-9]+)") + set(ROBIN_MAP_VERSION_MAJOR ${CMAKE_MATCH_1}) + message(STATUS "Detected robin_map major version: ${ROBIN_MAP_VERSION_MAJOR}") + if(NOT ROBIN_MAP_VERSION_MAJOR EQUAL 1) + message(FATAL_ERROR + "Incompatible tsl::robin_map version detected: ${ROBIN_MAP_VERSION_MAJOR}.x\n" + "nanobind requires version >= 1.3.0, < 2.0.0.\n" + "Found header at: ${ROBIN_MAP_HEADER_PATH}\n" + "This will cause compilation to fail. Please ensure a compatible 1.x version is used." + ) + endif() + else() + # Try alternative version detection + if(ROBIN_MAP_HEADER_CONTENT MATCHES "version[ \t]+([0-9]+)\\.([0-9]+)") + set(ROBIN_MAP_VERSION_MAJOR ${CMAKE_MATCH_1}) + if(NOT ROBIN_MAP_VERSION_MAJOR EQUAL 1) + message(FATAL_ERROR "Incompatible robin_map version: ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}") + endif() + else() + message(WARNING "Could not detect robin_map version from header, proceeding with caution") + endif() + endif() + else() + message(WARNING "Could not locate robin_map header for version check - may cause build failure") + endif() + + # After find_package, ensure static library is not enabled + if(TARGET nanobind-static) + message(WARNING "nanobind-static target found, but should use shared library mode") + endif() + +else() + message(FATAL_ERROR + "nanobind not found via pip. Please install it with:\n" + " python -m pip install nanobind\n" + "Static nanobind build is not supported (requires tsl::robin_map dependency)." + ) +endif() + +# Verify nanobind_add_module is available +if(COMMAND nanobind_add_module) + message(STATUS "nanobind_add_module() function is available") +else() + message(WARNING "nanobind_add_module() function not found, may need manual setup") +endif() diff --git a/cmake/recipes/polyfem.cmake b/cmake/recipes/polyfem.cmake index a1471835..debc09a2 100644 --- a/cmake/recipes/polyfem.cmake +++ b/cmake/recipes/polyfem.cmake @@ -5,15 +5,36 @@ if(TARGET polyfem::polyfem) return() endif() -message(STATUS "Third-party: creating target 'polyfem::polyfem'") +get_filename_component(POLYFEMPY_REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +set(POLYFEMPY_POLYFEM_ROOT "${POLYFEMPY_REPO_ROOT}/polyfem") -include(FetchContent) -FetchContent_Declare( - polyfem - GIT_REPOSITORY https://github.com/polyfem/polyfem.git - GIT_TAG 12ac634833f91a3946cff26db01972fdb2ec3214 - GIT_SHALLOW FALSE -) -FetchContent_MakeAvailable(polyfem) +message(STATUS "Third-party: using 'polyfem' submodule") +if(NOT EXISTS "${POLYFEMPY_POLYFEM_ROOT}/CMakeLists.txt") + message( + FATAL_ERROR + "polyfem submodule is missing at: ${POLYFEMPY_POLYFEM_ROOT}\n" + "Run: git submodule update --init --recursive\n" + "Or clone with: git clone --recurse-submodules " + ) +endif() + +option(POLYFEM_WITH_PYTHON "Enable Python expressions in PolyFEM" ON) + +function(polyfempy_add_backend) + # The parent supplies extension linking instead of embedding an interpreter. + # Keep this override local so the user's cached option remains unchanged. + set(POLYFEM_WITH_PYTHON OFF) + add_subdirectory("${POLYFEMPY_POLYFEM_ROOT}" "${CMAKE_BINARY_DIR}/polyfem") +endfunction() +polyfempy_add_backend() + +if(POLYFEM_WITH_PYTHON) + find_package(Python3 COMPONENTS Interpreter Development.Module REQUIRED) + include("${POLYFEMPY_POLYFEM_ROOT}/cmake/recipes/pybind11.cmake") + target_link_libraries(polyfem PUBLIC pybind11::module) + target_compile_definitions(polyfem PUBLIC + POLYFEM_WITH_PYTHON + POLYFEM_PYTHON_EXECUTABLE="${Python3_EXECUTABLE}") +endif() diff --git a/cmake/recipes/polyfem_cpm_cache.cmake b/cmake/recipes/polyfem_cpm_cache.cmake new file mode 100644 index 00000000..bd57d222 --- /dev/null +++ b/cmake/recipes/polyfem_cpm_cache.cmake @@ -0,0 +1,24 @@ +# +# Copyright 2021 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(DEFINED ENV{CPM_SOURCE_CACHE}) + set(CPM_SOURCE_CACHE_DEFAULT $ENV{CPM_SOURCE_CACHE}) +else() + # Set CPM cache folder if unset + file(REAL_PATH "~/.cache/CPM" CPM_SOURCE_CACHE_DEFAULT EXPAND_TILDE) +endif() + +set(CPM_SOURCE_CACHE + ${CPM_SOURCE_CACHE_DEFAULT} + CACHE PATH "Directory to download CPM dependencies" +) +message(STATUS "Using CPM cache folder: ${CPM_SOURCE_CACHE}") \ No newline at end of file diff --git a/cmake/recipes/polyfem_data.cmake b/cmake/recipes/polyfem_data.cmake index 95aa1849..3e8e8b10 100644 --- a/cmake/recipes/polyfem_data.cmake +++ b/cmake/recipes/polyfem_data.cmake @@ -1,18 +1,16 @@ # data # License: MIT -message(STATUS "Third-party: fetching 'polyfem data'") +message(STATUS "Third-party: using 'polyfem data' submodule") -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 +if(NOT EXISTS "${POLYFEMPY_DATA_ROOT}/README.md") + message( + FATAL_ERROR + "polyfem-data submodule is missing at: ${POLYFEMPY_DATA_ROOT}\n" + "Run: git submodule update --init --recursive\n" + "Or configure with: -DINPUT_POLYFEMPY_DATA_ROOT=path/to/polyfem-data" + ) +endif() + +message(STATUS "Using polyfem data directory: ${POLYFEMPY_DATA_ROOT}") +set(polyfem_data_POPULATED TRUE) 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/conda/README.md b/conda/README.md new file mode 100644 index 00000000..0e3c8fb4 --- /dev/null +++ b/conda/README.md @@ -0,0 +1,68 @@ +# Build the conda package + +This recipe builds a native conda package from the same source archive used for +the wheels. It does not wrap a prebuilt wheel. The existing conda-forge release +supports `win-64`, `linux-64`, and `osx-64`; those remain required targets. +The initial installation checks use Python 3.11 on these three platforms +and `osx-arm64` for M-series Macs. Other Python versions need validation +before publishing. + +The recipe is prepared for local and CI validation. It has not been published +to conda-forge. Keep its version aligned with `project.version` in +`pyproject.toml` when preparing a release. + +## Local build + +Activate a separate conda environment containing `conda-build`. Prepare a source +archive using [BUILD.md](../BUILD.md), then set its URL and SHA-256 checksum. +For the current version, in PowerShell: + +```powershell +$archive = Get-Item dist/polyfempy-0.8.tar.gz +$env:POLYFEMPY_SDIST_URL = ([Uri]$archive.FullName).AbsoluteUri +$env:POLYFEMPY_SDIST_SHA256 = (Get-FileHash $archive -Algorithm SHA256).Hash.ToLower() +$env:CONDA_BLD_PATH = "C:/pf-cb" +$env:CPM_SOURCE_CACHE = "C:/pf-cpm" +conda-build conda/recipe --python 3.11 --no-anaconda-upload --override-channels -c conda-forge --output-folder conda-out +``` + +On Linux or macOS: + +```sh +export CPM_SOURCE_CACHE="$PWD/.cache/CPM" +export POLYFEMPY_SDIST_URL="$(python -c 'from pathlib import Path; print(Path("dist/polyfempy-0.8.tar.gz").resolve().as_uri())')" +export POLYFEMPY_SDIST_SHA256="$(python -c 'import hashlib; from pathlib import Path; print(hashlib.sha256(Path("dist/polyfempy-0.8.tar.gz").read_bytes()).hexdigest())')" +conda-build conda/recipe --python 3.11 --no-anaconda-upload --override-channels -c conda-forge --output-folder conda-out +``` + +The source archive includes the generated API, builder runtime, and native +sources. The native build still downloads pinned third-party sources. The +recipe installs build tools separately from runtime dependencies and tests the +installed package in conda-build's test environment. It runs the README beam, +installation self-check, and all three quick-start scripts using the mesh +included in the source archive; an import-only check is not sufficient. + +Windows also needs the Visual Studio 2022 C++ tools. Use short build and cache +paths. The recipe selects Ninja so the same build commands work across systems. + +## Release workflow + +Run the package matrix explicitly as described in +[TESTING.md](../TESTING.md#release-package-checks). Ordinary pushes do not build +the complete release matrix. + +For manual dispatch, first make the workflow available on the repository's +default branch. Then use +**Actions -> Release Packages -> Run workflow** and select the release branch. +See [TESTING.md](../TESTING.md#release-package-checks) for the prerequisite. +Each native conda job builds for one platform and Python version, runs the +installed-package checks, and uploads the resulting package as an artifact. +The workflow does not upload to Anaconda.org or PyPI. + +After all required jobs pass, update the existing +[polyfempy feedstock](https://github.com/conda-forge/polyfempy-feedstock). +Replace the local source parameters with the published archive URL and checksum, +preserve the reviewed build and test requirements, and rerender the feedstock +with its normal conda-forge tooling. Review native dependency and license +requirements there before publishing. A successful local build alone does not +complete the conda-forge release. diff --git a/conda/recipe/bld.bat b/conda/recipe/bld.bat new file mode 100644 index 00000000..4557412a --- /dev/null +++ b/conda/recipe/bld.bat @@ -0,0 +1,7 @@ +@echo off +set CMAKE_GENERATOR=Ninja +set CMAKE_GENERATOR_PLATFORM= +set CMAKE_GENERATOR_TOOLSET= +set CONDA_PREFIX=%PREFIX% +"%PYTHON%" -m pip install . --no-deps --no-build-isolation -v +if errorlevel 1 exit /b 1 diff --git a/conda/recipe/build.sh b/conda/recipe/build.sh new file mode 100644 index 00000000..96a1116d --- /dev/null +++ b/conda/recipe/build.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -eux + +export CMAKE_GENERATOR=Ninja +export CONDA_PREFIX="${PREFIX}" +"${PYTHON}" -m pip install . --no-deps --no-build-isolation -v diff --git a/conda/recipe/conda_build_config.yaml b/conda/recipe/conda_build_config.yaml new file mode 100644 index 00000000..4572f494 --- /dev/null +++ b/conda/recipe/conda_build_config.yaml @@ -0,0 +1,8 @@ +c_compiler: + - vs2022 # [win] + - gcc # [linux] + - clang # [osx] +cxx_compiler: + - vs2022 # [win] + - gxx # [linux] + - clangxx # [osx] diff --git a/conda/recipe/meta.yaml b/conda/recipe/meta.yaml new file mode 100644 index 00000000..20d5759b --- /dev/null +++ b/conda/recipe/meta.yaml @@ -0,0 +1,57 @@ +{% set version = "0.8" %} + +package: + name: polyfempy + version: {{ version }} + +source: + url: {{ environ["POLYFEMPY_SDIST_URL"] }} + sha256: {{ environ["POLYFEMPY_SDIST_SHA256"] }} + +build: + number: 0 + skip: true # [py<310] + script_env: + - N_THREADS=1 + - CPM_SOURCE_CACHE + +requirements: + build: + - {{ compiler('c') }} + - {{ compiler('cxx') }} + - cmake >=3.25 + - ninja + - git + host: + - python + - pip + - setuptools >=77 + - wheel + - nanobind >=2 + - numpy >=1.23 + run: + - python + - numpy >=1.23 + +test: + requires: + - pip + source_files: + - README.md + - INSTALL.md + - tools/check_installed_package.py + - examples/quickstart/*.py + - examples/quickstart/*.obj + commands: + - python -m pip check + - python -I tools/check_installed_package.py --readme README.md --example examples/quickstart/beam.py --example examples/quickstart/static_elasticity.py --example examples/quickstart/transient_elasticity.py + +about: + home: https://polyfem.github.io/ + dev_url: https://github.com/polyfem/polyfem-python + license: MIT + license_file: + - LICENSE + - polyfem/LICENSE + - python-from-jse/LICENSE + summary: Python model-building API and native solver bindings for PolyFEM diff --git a/examples b/examples new file mode 160000 index 00000000..8fe9d8b9 --- /dev/null +++ b/examples @@ -0,0 +1 @@ +Subproject commit 8fe9d8b9a1935231d1005f4121cf7866131b4497 diff --git a/generator-config/README.md b/generator-config/README.md new file mode 100644 index 00000000..bebfb6fe --- /dev/null +++ b/generator-config/README.md @@ -0,0 +1,84 @@ +# PolyFEM generator configuration + +The API generator reads these project settings during generation. + +- `builder.json` selects the PolyFEM builder, its extra helpers and the spec paths to exclude. +- `api_aliases.json` defines public names, field aliases and configuration shortcuts. +- `id_relationships.json` connects geometry IDs to materials, boundary conditions and contact settings. Its `id_groups` also defines which selection types share IDs. + +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 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. + +The generator creates methods from the input spec. PolyFEM implements mesh, +obstacle and RHS behavior in `python/polyfempy/_model_builder.py`. A removed +field referenced by a configured shortcut or relationship fails validation +before the generated files are replaced. Regenerate from the repository root. + +```powershell +python tools/generate_polyfem_api.py +``` + +## 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. + +Selection helper names and fields come from the spec and the relationships. +For example, the surface relationships identify `geometry[*].surface_selection` +and its ID, and the selection spec defines the `axis` variant and its arguments. +Together they generate `surface_axis(...)`. Adding a named selection variant +with that ID generates its helper on the next run. + +Each relationship namespace gets its own ID group by default. The project +declares that surface and point share a group and must expose matching methods. +It also reserves curve IDs, which have no corresponding consumer relationship. +The builder can customize a root section through a private `_section_` +method. That method is exposed only when the section exists in the spec. +`builder.source_root` points to the package source relative to `builder.json`, +so the generator can read the adapter's declared methods and retain their type +signatures without importing the package during generation. +A collection handler such as `_item_geometry` receives the generated item +factory name. The spec supplies the collection and its variants. + +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..f335aef2 --- /dev/null +++ b/generator-config/api_aliases.json @@ -0,0 +1,304 @@ +{ + "shortcuts": { + "time": ["tend", "dt"], + "contact": ["enabled", "dhat"] + }, + "field_alias_suffixes": ["_boundary"], + "factory_names": { + "list_item_suffixes": ["_boundary"], + "variant_parent_suffixes": ["_selection"], + "prefix_sections": ["Output"] + }, + "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/builder.json b/generator-config/builder.json new file mode 100644 index 00000000..4611553d --- /dev/null +++ b/generator-config/builder.json @@ -0,0 +1,11 @@ +{ + "exclude_paths": ["/preset_problem", "/tests"], + "builder": { + "base": "polyfempy._model_builder.ModelBuilder", + "source_root": "../python", + "helpers": ["body"] + }, + "record_helpers": [ + {"name": "unit", "fields": ["value", "unit"], "inline_types": [null, "ValueWithUnit"]} + ] +} diff --git a/generator-config/id_relationships.json b/generator-config/id_relationships.json new file mode 100644 index 00000000..869c6e95 --- /dev/null +++ b/generator-config/id_relationships.json @@ -0,0 +1,134 @@ +{ + "id_groups": { + "boundary": {"members": ["surface", "point"], "same_methods": true}, + "curve": {} + }, + "relationships": [ + { + "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 b/polyfem new file mode 160000 index 00000000..836c923c --- /dev/null +++ b/polyfem @@ -0,0 +1 @@ +Subproject commit 836c923cba93772bfc72daeaa42c7e0fcd6ca3e2 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..f89e44f7 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,74 @@ +[build-system] +requires = ["setuptools>=77", "wheel", "nanobind>=2.0.0", "cmake>=3.25"] +build-backend = "setuptools.build_meta" + +[project] +name = "polyfempy" +version = "0.8" +description = "PolyFEM Python bindings" +readme = "README.md" +license = "MIT" +license-files = ["LICENSE", "polyfem/LICENSE", "python-from-jse/LICENSE"] +authors = [ + { name = "Zizhou Huang", email = "zizhou@nyu.edu" }, +] +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] +io = [ + "meshio>=5.0.0", +] +visualization = [ + "matplotlib>=3.5", +] +dev = [ + "pytest>=7.0", + "setuptools>=77", + "build>=1", + "ruff>=0.17.5,<0.18", +] +test = [ + "pytest>=7.0", + "setuptools>=77", +] +all = [ + "matplotlib>=3.5", + "meshio>=5.0.0", + "pytest>=7.0", +] + +[project.scripts] +polyfempy = "polyfempy.cli:main" + +[project.urls] +Homepage = "https://polyfem.github.io/" +Source = "https://github.com/polyfem/polyfem-python" +Issues = "https://github.com/polyfem/polyfem-python/issues" + +[tool.setuptools] +include-package-data = true + +[tool.setuptools.package-data] +"polyfempy.generated_api" = ["*_manifest.json"] + +[tool.pyright] +include = ["python", "tools", "tests", "setup.py", "python-from-jse/generator", "python-from-jse/tools", "python-from-jse/validators", "python-from-jse/tests", "python-from-jse/examples"] +exclude = ["python/polyfempy/generated_api", "**/__pycache__", "**/*.egg-info", "**/node_modules", "**/.*"] +extraPaths = ["python", "examples/classic_example"] +executionEnvironments = [ + { root = "python-from-jse", extraPaths = ["python-from-jse", "python-from-jse/generator", "python-from-jse/tests"] }, + { root = ".", extraPaths = ["python", "examples/classic_example"] }, +] + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["python"] diff --git a/python-from-jse b/python-from-jse new file mode 160000 index 00000000..6e968a3c --- /dev/null +++ b/python-from-jse @@ -0,0 +1 @@ +Subproject commit 6e968a3cb4a219d8781ba2c006444dcb03e694c5 diff --git a/python/polyfem/__init__.py b/python/polyfem/__init__.py new file mode 100644 index 00000000..a3eb98ae --- /dev/null +++ b/python/polyfem/__init__.py @@ -0,0 +1,14 @@ +"""PolyFEM model builder and generated configuration factories.""" + +from typing import TYPE_CHECKING + +from polyfempy.generated_api import generated_api as _api +from polyfempy.generated_api.generated_api import Root as Root +from polyfempy.generated_api.generated_api import model as model + +if TYPE_CHECKING: + from polyfempy.generated_api.generated_api import * # noqa: F403 +else: + __all__ = ["Root", *(name for name, value in vars(_api).items() + if not name.startswith("_") and getattr(value, "__module__", None) == _api.__name__)] + globals().update({name: getattr(_api, name) for name in __all__}) diff --git a/python/polyfempy/__init__.py b/python/polyfempy/__init__.py new file mode 100644 index 00000000..1c5066e1 --- /dev/null +++ b/python/polyfempy/__init__.py @@ -0,0 +1,54 @@ +"""polyfempy Python package. + +This repository contains: +- A pure-Python solve/runtime layer (`polyfempy.runtime.*`) +- A compiled C++ extension submodule built by CMake (nanobind backend) + +Why this shape: +- The Python import path should remain stable: `import polyfempy as pf` + +Important: +- The compiled extension is expected to be available as `polyfempy.polyfempy` + (i.e., a submodule inside this package). When present, we re-export its public + symbols (e.g., `Solver`, `version`, etc.) at the + package top-level for convenience. +""" + +# High-level (pure Python) solve/runtime surface +from .runtime import * # noqa: F403 + +# Low-level C++ extension (optional at import time; required for real compute) +_cpp_backend_available = False +_cpp_backend_error = None +try: + import importlib + import importlib.util + + # This is the compiled extension module produced by CMake: + # full import name: polyfempy.polyfempy + _spec = importlib.util.find_spec(__name__ + ".polyfempy") + if _spec is None: + raise ModuleNotFoundError(f"No module named '{__name__}.polyfempy' (C++ backend not built)") + + _core = importlib.import_module(__name__ + ".polyfempy") # type: ignore + + # Re-export all public names from the C++ extension at package top-level. + for _name in dir(_core): + if not _name.startswith("_"): + globals()[_name] = getattr(_core, _name) + + _cpp_backend_available = True +except Exception as e: + # Keep import working even if the extension is not built/installed yet. + _cpp_backend_error = e + _core = None + + +def cpp_backend_available() -> bool: + """Return True if the compiled C++ backend submodule is importable.""" + return _cpp_backend_available + + +def cpp_backend_error(): + """Return the import error (if any) for the compiled C++ backend.""" + return _cpp_backend_error diff --git a/python/polyfempy/__main__.py b/python/polyfempy/__main__.py new file mode 100644 index 00000000..42fbee7b --- /dev/null +++ b/python/polyfempy/__main__.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +from .cli import main + + +raise SystemExit(main()) diff --git a/python/polyfempy/_model_builder.py b/python/polyfempy/_model_builder.py new file mode 100644 index 00000000..1d5f569a --- /dev/null +++ b/python/polyfempy/_model_builder.py @@ -0,0 +1,880 @@ +from __future__ import annotations + +import json +import uuid +from copy import deepcopy +from pathlib import Path +from typing import Literal, TypeVar, cast, overload + +from ._selection_refs import SelectionPool, SelectionRef + + +_MISSING = object() +_Model = TypeVar("_Model", bound="ModelBuilder") + + +class ModelBuilder: + def __init__( + self, + api_module, + *, + relationships=None, + selection_pool=None, + namespaces=None, + selection_helper_rules=None, + ): + self._api = api_module + manifest = _builder_manifest(api_module) + groups = namespaces if namespaces is not None else manifest.get("namespaces", {}) + self._selection_pool = selection_pool or SelectionPool(groups) + self._selection_refs = {} + if relationships is None: + relationships = manifest.get("relationships", []) + self._relationships_by_api = {} + for item in relationships: + name = item["builder_api"] + if name in self._relationships_by_api: + raise ValueError(f"duplicate id relationship builder_api: {name!r}") + self._relationships_by_api[name] = item + self._config_consumer_sections = list(dict.fromkeys( + item["consumer"].split(".", 1)[0].removesuffix("[*]") for item in self._relationships_by_api.values() + )) + if selection_helper_rules is None: + selection_helper_rules = manifest.get("selection_rules", {}) + self._selection_helper_rules = dict(selection_helper_rules) + self._mesh_by_uuid = {} + self._automatic_volume_ids = set() + self._rhs_only_volume_ids = {} + self._consumer_lists = {} + self._selection_backend_id_by_signature = {} + self._implicit_surface_meshes = set() + self._rhs = _MISSING + self._config_sections = {} + + def body(self): + return BodyHandle(self) + + def rhs(self, value): + if self._consumer_lists.get(("boundary_conditions", "rhs")): + raise TypeError("Use either model.rhs(...) or body.rhs(...), not both") + if self._rhs is not _MISSING: + raise TypeError("rhs already configured on this model") + self._rhs = _copy_payload(value) + return self + + def _register_body_mesh(self, payload): + values = _payload_dict(payload) + volume_selection = values.get("volume_selection") + if values.get("is_obstacle") or ( + volume_selection is not None + and (not isinstance(volume_selection, int) or volume_selection <= 0) + ): + raise ValueError("body.mesh requires a deformable mesh with a single volume group") + body = self._item_geometry("mesh", **values) + assert isinstance(body, BodyHandle) + return body.mesh_uuid, body.volume_ref + + @overload + def _item_geometry(self, factory_name: str, /, *, is_obstacle: Literal[False] = False, + volume_selection: None = None, **kwargs) -> BodyHandle: ... + + @overload + def _item_geometry(self, factory_name: str, /, *, is_obstacle: Literal[False] = False, + volume_selection: int, **kwargs) -> BodyHandle | GeometryHandle: ... + + @overload + def _item_geometry(self, factory_name: str, /, *, is_obstacle: Literal[True], + surface_selection: None = None, **kwargs) -> ObstacleHandle | None: ... + + @overload + def _item_geometry(self, factory_name: str, /, *, is_obstacle: Literal[True], + surface_selection: int, **kwargs) -> SelectionHandle | None: ... + + @overload + def _item_geometry(self, factory_name: str, /, **kwargs) -> BodyHandle | GeometryHandle | ObstacleHandle | SelectionHandle | None: ... + + def _item_geometry(self, factory_name, /, *, same_volume_as=None, **kwargs): + values = dict(kwargs) + if same_volume_as is not None: + if not isinstance(same_volume_as, BodyHandle) or same_volume_as._model is not self: + raise ValueError("same_volume_as requires a body from this model") + if "volume_selection" in values or values.get("is_obstacle"): + raise ValueError("Specify one volume group on a deformable geometry") + values["volume_selection"] = same_volume_as._require_mesh().backend_id + + geometry_object = getattr(self._api, factory_name)(**values) + self._reserve_geometry_ids(_payload_dict(geometry_object), shared_volume=same_volume_as is not None) + if same_volume_as is not None: + same_volume_as._bind_volume() + mesh_uuid = str(uuid.uuid4()) + self._mesh_by_uuid[mesh_uuid] = geometry_object + if values.get("is_obstacle"): + surface_selection = values.get("surface_selection") + if surface_selection is None and factory_name != "mesh_sequence": + return ObstacleHandle(self, geometry_object) + if not isinstance(surface_selection, int) or surface_selection <= 0: + return None + ref = self._allocate_selection("surface", backend_id=surface_selection) + return SelectionHandle(self, ref) + + volume_selection = values.get("volume_selection") + if volume_selection is not None and ( + not isinstance(volume_selection, int) or volume_selection <= 0 + ): + return GeometryHandle(self, mesh_uuid) + # Reserve an ID, but preserve mesh tags until a body-level setting needs it. + volume_ref = self._allocate_selection( + "volume", backend_id=volume_selection, mesh_uuid=mesh_uuid, + ) + if volume_selection is None: + self._automatic_volume_ids.add(volume_ref.backend_id) + return BodyHandle(self, mesh_uuid, volume_ref) + + def _allocate_selection(self, namespace, **kwargs): + ref = self._selection_pool.allocate(namespace, **kwargs) + self._selection_refs[ref.uuid] = ref + return ref + + def _reserve_geometry_ids(self, geometry, *, shared_volume): + """Keep automatic IDs clear of IDs already present in geometry rules.""" + reservations = [] + for namespace in ("volume", "surface", "point", "curve"): + value = geometry.get(namespace + "_selection") + items = value if isinstance(value, list) else [value] + for item in items: + backend_id = item.get("id") if isinstance(item, dict) else item + if not isinstance(backend_id, int) or isinstance(backend_id, bool) or backend_id < 1: + continue + if namespace == "volume" and not shared_volume and backend_id in self._automatic_volume_ids: + raise ValueError( + f"volume ID {backend_id} is already assigned automatically to another body. " + "Choose a different ID or use same_volume_as to share its volume." + ) + reservations.append((namespace, backend_id)) + for namespace, backend_id in reservations: + self._allocate_selection(namespace, backend_id=backend_id) + + def _section_geometry(self): + geometry = [] + for mesh_uuid, mesh in self._mesh_by_uuid.items(): + item = _payload_dict(mesh) + if mesh_uuid in self._rhs_only_volume_ids: + item["volume_selection"] = self._rhs_only_volume_ids[mesh_uuid] + geometry.append(item) + return geometry + + @overload + def _section_materials(self) -> list | dict: ... + + @overload + def _section_materials(self: _Model, value: object) -> _Model: ... + + @overload + def _section_materials(self: _Model, **kwargs) -> _Model | list | dict: ... + + def _section_materials(self: _Model, value=_MISSING, **kwargs) -> _Model | list | dict: + """Set materials, or return the current materials when called without arguments.""" + if value is not _MISSING or kwargs: + if value is not _MISSING and kwargs: + raise TypeError("Use a material value or keyword fields, not both") + if value is not _MISSING: + items = value if isinstance(value, list) else [value] + material = self._api.materials(items) + else: + material = self._api.materials(**kwargs) + return self._set_consumer_section("materials", material) + return cast("list | dict", self._model_section("materials")) + + @overload + def _section_initial_conditions(self) -> dict: ... + + @overload + def _section_initial_conditions(self: _Model, **kwargs) -> _Model | dict: ... + + def _section_initial_conditions(self: _Model, **kwargs) -> _Model | dict: + if kwargs: + value = self._api.initial_conditions(**kwargs) + return self._set_consumer_section("initial_conditions", value) + return cast(dict, self._model_section("initial_conditions")) + + def _section_space(self, **kwargs): + if kwargs: + return self._set_consumer_section("space", self._api.space(**kwargs)) + return self._model_section("space") + + def _section_boundary_conditions(self, **kwargs): + """Save keyword settings and keep the legacy dictionary return value.""" + if kwargs: + self._set_consumer_section("boundary_conditions", kwargs) + return cast(dict, self._model_section("boundary_conditions")) + + def _set_consumer_section(self, name, value): + payload = _as_dict_if_available(value) + self._model_section(name, payload) + return self._set_config_section(name, deepcopy(payload)) + + def _model_section(self, name, explicit=_MISSING): + """Combine explicit settings with body settings without discarding either.""" + bound = self._consumer_root_section(name) + if explicit is _MISSING: + explicit = self._config_sections.get(name, _MISSING) + if explicit is _MISSING: + return deepcopy(bound) + if not bound: + return deepcopy(explicit) + if isinstance(explicit, list) and isinstance(bound, list): + return deepcopy(explicit + bound) + if not isinstance(explicit, dict) or not isinstance(bound, dict): + raise ValueError("%s conflicts with body settings; use per-body lists" % name) + section = deepcopy(explicit) + for key, items in bound.items(): + if name == "boundary_conditions" and key == "rhs" and key in section: + raise TypeError("Use either body.rhs(...) or explicit rhs, not both") + if key in section and section[key] is not None: + if not isinstance(section[key], list): + raise ValueError( + "%s.%s already has a non-list value" % (name, key) + ) + section[key] = section[key] + deepcopy(items) + else: + section[key] = deepcopy(items) + return section + + def _set_config_section(self, name, value): + self._config_sections[name] = value + return self + + def config(self, **kwargs): + # Older callers pass the dictionary returned by boundary_conditions(). + if ( + "boundary_conditions" in self._config_sections + and kwargs.get("boundary_conditions") is not None + ): + if _payload_dict(kwargs["boundary_conditions"]) == self._section_boundary_conditions(): + kwargs.pop("boundary_conditions") + duplicates = self._config_sections.keys() & kwargs.keys() + if duplicates: + raise TypeError("Configuration already set on model: %s" % ", ".join(sorted(duplicates))) + values = dict(self._config_sections) + for name in self._config_consumer_sections: + if name in values and name != "boundary_conditions": + values[name] = self._model_section(name) + values.update(kwargs) + rhs = values.pop("rhs", _MISSING) + if self._rhs is not _MISSING: + if rhs is not _MISSING: + raise TypeError( + "Use either model.rhs(...) or config(rhs=...), not both" + ) + rhs = self._rhs + + use_model_geometry = "geometry" not in values + if use_model_geometry: + values["geometry"] = self._section_geometry() + + explicit_boundary = values.pop("boundary_conditions", _MISSING) + if explicit_boundary is _MISSING: + boundary_kwargs = {} + elif explicit_boundary is None: + boundary_kwargs = {} + else: + boundary_kwargs = _payload_dict(explicit_boundary) + + if rhs is not _MISSING: + if "rhs" in boundary_kwargs: + raise TypeError( + "Use either rhs=... or boundary_conditions with rhs, not both" + ) + boundary_kwargs["rhs"] = rhs + + for section in self._config_consumer_sections: + if section == "boundary_conditions": + continue + if section in values: + continue + payload = self._consumer_root_section(section) + if payload: + values[section] = payload + + boundary_conditions = self._model_section("boundary_conditions", boundary_kwargs) + if ( + boundary_conditions + or explicit_boundary is not _MISSING + or rhs is not _MISSING + ): + values["boundary_conditions"] = boundary_conditions + + if self._consumer_lists.get(("boundary_conditions", "rhs")): + self._export_body_rhs(values, use_model_geometry) + return self._api.config(**values) + + def _export_body_rhs(self, values, use_model_geometry): + loads = values["boundary_conditions"]["rhs"] + vector = None + for entry in loads: + value = entry.get("value") + if entry.keys() != {"id", "value"} or not isinstance(value, (list, tuple)): + return + if not value or not all(type(component) in (int, float) for component in value): + return + if vector is None: + vector = list(value) + elif list(value) != vector: + return + + geometry = values["geometry"] + if not isinstance(geometry, (tuple, list)): + return + volume_ids = set() + shared_ids = set() + for mesh in geometry: + item = _payload_dict(mesh) + if item.get("is_obstacle"): + continue + volume_id = item.get("volume_selection") + if type(volume_id) is not int or volume_id <= 0: + return + if volume_id in volume_ids: + shared_ids.add(volume_id) + volume_ids.add(volume_id) + if volume_ids != {entry["id"] for entry in loads}: + return + + values["boundary_conditions"]["rhs"] = vector + if use_model_geometry and self._rhs_only_volume_ids: + # Only omit tags introduced for the RHS itself. Raw config sections + # can also refer to these IDs without going through a body handle. + referenced_ids = shared_ids | self._other_volume_ids(values) + for mesh_uuid, item in zip(self._mesh_by_uuid, geometry): + if mesh_uuid in self._rhs_only_volume_ids and item["volume_selection"] not in referenced_ids: + del item["volume_selection"] + + def _other_volume_ids(self, values): + ids = set() + for relationship in self._relationships_by_api.values(): + if relationship["namespace"] != "volume" or relationship["builder_api"] == "body.rhs": + continue + path, id_field = _parse_list_item_consumer(relationship["consumer"]) + items = values + for key in path: + items = _as_dict_if_available(items) + items = items.get(key) if isinstance(items, dict) else None + items = _as_dict_if_available(items) + for item in items if isinstance(items, list) else [items]: + item = _as_dict_if_available(item) + if isinstance(item, dict): + labels = item.get(id_field) + if not isinstance(labels, (list, tuple)): + labels = [labels] + ids.update(label for label in labels if type(label) is int) + return ids + + def _shared_surface_id(self, id, same_as): + if same_as is not None: + if id is not None or not isinstance(same_as, SelectionHandle) or same_as._model is not self or same_as.selection_ref.namespace != "surface": + raise ValueError("same_as requires a surface from this model") + id = same_as.selection_ref.backend_id + return {"id": id} if id is not None else {} + + def _whole_surface_method(self, mesh_uuid, name): + builder_api = "surface." + name + if not self.has_builder_api(builder_api): + return None + + def bind_value(*args, **kwargs): + if mesh_uuid is None: + raise ValueError("body.mesh(...) must be called before configuring a boundary") + value = _bind_payload_from_call(builder_api, args, kwargs) + current = _payload_dict(self._mesh_by_uuid[mesh_uuid]).get("surface_selection") + if current is not None and not isinstance(current, int): + raise ValueError( + "This mesh already has a partial or file-based surface selection. " + "Apply the boundary condition to the selected surface." + ) + ref = self._allocate_selection( + "surface", + backend_id=current if current is not None and current > 0 else None, + mesh_uuid=mesh_uuid, + ) + _set_payload_field(self._mesh_by_uuid[mesh_uuid], "surface_selection", ref.backend_id) + surface = SelectionHandle(self, ref) + self.bind(builder_api, ref, value) + self._implicit_surface_meshes.add(mesh_uuid) + return surface + + bind_value.__name__ = name + return bind_value + + def _add_surface_selection(self, mesh_uuid, payload, *, append=True): + return self._add_geometry_selection( + mesh_uuid, + namespace="surface", + geometry_field="surface_selection", + payload=payload, + append=append, + ) + + def _add_geometry_selection( + self, + mesh_uuid, + *, + namespace, + geometry_field, + payload, + append, + geometry_class=None, + ): + values = dict(payload) + backend_id = values.pop("id", None) + if backend_id is None and not append and not values: + current = _payload_dict(self._mesh_by_uuid[mesh_uuid]).get(geometry_field) + if isinstance(current, int) and current > 0: + backend_id = current + signature = (mesh_uuid, _selection_signature(namespace, values)) + if backend_id is None and signature in self._selection_backend_id_by_signature: + backend_id = self._selection_backend_id_by_signature[signature] + selection_ref = self._allocate_selection( + namespace, + backend_id=backend_id, + mesh_uuid=mesh_uuid, + ) + if append or values: + geometry_payload = {"id": selection_ref.backend_id, **values} + if geometry_class: + geometry_payload = _construct_api_class(self._api, geometry_class, geometry_payload) or geometry_payload + else: + geometry_payload = selection_ref.backend_id + + self._set_mesh_selection_field( + mesh_uuid, + geometry_field, + geometry_payload, + append=append, + ) + self._selection_backend_id_by_signature.setdefault( + signature, + selection_ref.backend_id, + ) + return SelectionHandle(self, selection_ref) + + def _set_mesh_selection_field(self, mesh_uuid, field, payload, *, append): + if ( + field == "surface_selection" + and mesh_uuid in self._implicit_surface_meshes + and (append or not isinstance(payload, int)) + ): + raise ValueError( + "A whole-boundary condition is already bound to this mesh. " + "Choose the partial surface before applying its boundary condition." + ) + mesh_object = self._mesh_by_uuid[mesh_uuid] + current = _payload_dict(mesh_object).get(field) + + if append: + if current is None or current == []: + next_value = [_copy_payload(payload)] + elif isinstance(current, list): + if payload in current: + return + next_value = list(current) + [_copy_payload(payload)] + else: + raise ValueError("cannot append %s to existing non-list value" % field) + else: + if current is not None and current != []: + if isinstance(current, int) and isinstance(payload, int) and current == payload: + return + raise ValueError("%s already exists for this mesh" % field) + next_value = payload + + _set_payload_field(mesh_object, field, next_value) + + def bind(self, builder_api, selection_ref, value): + if self._selection_refs.get(selection_ref.uuid) != selection_ref: + raise ValueError("selection must belong to this model") + relationship = self._relationship_for(builder_api) + if relationship["namespace"] != selection_ref.namespace: + raise ValueError( + "%s expects %s selection, got %s" + % (builder_api, relationship["namespace"], selection_ref.namespace) + ) + + consumer_path, id_field = _parse_list_item_consumer(relationship["consumer"]) + payload = _payload_dict(value) + payload[id_field] = selection_ref.backend_id + if consumer_path == ("boundary_conditions", "rhs"): + if self._rhs is not _MISSING: + raise TypeError("Use either model.rhs(...) or body.rhs(...), not both") + if any(item[id_field] == payload[id_field] for item in self._consumer_lists.get(consumer_path, ())): + raise TypeError("rhs already configured for this body ID") + items = self._consumer_lists.setdefault(consumer_path, []) + if payload not in items: + items.append(payload) + return payload + + def _relationship_for(self, builder_api): + relationship = self._relationships_by_api.get(builder_api) + if relationship is None: + raise ValueError("missing ID relationship for builder API %r" % builder_api) + return relationship + + def has_builder_api(self, builder_api): + return builder_api in self._relationships_by_api + + def has_selection_helper(self, method_name): + return method_name in self._selection_helper_rules + + def add_selection_with_helper(self, mesh_uuid, method_name, payload, *, append=True): + rule = self._selection_helper_rules[method_name] + if "same_as" in payload: + if rule["namespace"] != "surface": + raise ValueError("same_as requires a surface") + payload.update(self._shared_surface_id(payload.get("id"), payload.pop("same_as"))) + _validate_selection_helper_payload(method_name, payload, rule["allowed_fields"]) + return self._add_geometry_selection( + mesh_uuid, + namespace=rule["namespace"], + geometry_field=rule["field"], + payload=payload, + append=append, + geometry_class=None if append else rule.get("class_path"), + ) + + def _consumer_section(self, section_path): + section = {} + prefix_len = len(section_path) + for consumer_path, items in self._consumer_lists.items(): + if ( + len(consumer_path) == prefix_len + 1 + and consumer_path[:prefix_len] == section_path + ): + section[consumer_path[-1]] = list(items) + return section + + def _consumer_root_section(self, section): + section_path = (section,) + if section_path in self._consumer_lists: + return list(self._consumer_lists[section_path]) + return self._consumer_section(section_path) + + +class GeometryHandle: + def __init__(self, model, mesh_uuid): + self._model = model + self.mesh_uuid = mesh_uuid + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + + boundary_method = self._model._whole_surface_method(self.mesh_uuid, name) + if boundary_method is not None: + return boundary_method + selection_helper = self._dynamic_selection_helper(name) + if selection_helper is not None: + return selection_helper + raise AttributeError( + "%s has no configured selection helper %r" + % (self.__class__.__name__, name) + ) + + def _dynamic_selection_helper(self, name): + if not self._model.has_selection_helper(name): + return None + + def add_selection(*args, **kwargs): + if args: + raise TypeError("%s accepts keyword fields only" % name) + append = kwargs.pop("append", True) + return self._model.add_selection_with_helper( + self.mesh_uuid, + name, + kwargs, + append=append, + ) + + add_selection.__name__ = name + return add_selection + + def surface_all(self, *, id=None, same_as=None): + payload = self._model._shared_surface_id(id, same_as) + return self._model._add_surface_selection( + self.mesh_uuid, + payload, + append=False, + ) + + +class BodyHandle: + def __init__(self, model, mesh_uuid=None, volume_ref: SelectionRef | None = None): + self._model = model + self.mesh_uuid = mesh_uuid + self.volume_ref = volume_ref + + def mesh(self, *args, **kwargs): + if self.mesh_uuid is not None: + raise ValueError("body.mesh(...) was already configured") + payload = _bind_payload_from_call("body.mesh", args, kwargs) + mesh_uuid, volume_ref = self._model._register_body_mesh(payload) + self.mesh_uuid = mesh_uuid + self.volume_ref = volume_ref + return self + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + + builder_api = "body.%s" % name + if not self._model.has_builder_api(builder_api): + boundary_method = self._model._whole_surface_method(self.mesh_uuid, name) + if boundary_method is not None: + return boundary_method + selection_helper = self._dynamic_selection_helper(name) + if selection_helper is not None: + return selection_helper + raise AttributeError( + "%s has no configured builder API %r" + % (self.__class__.__name__, builder_api) + ) + + def bind_value(*args, **kwargs): + volume_ref = self._require_mesh() + value = _bind_payload_from_call(builder_api, args, kwargs) + self._model.bind(builder_api, volume_ref, value) + if builder_api == "body.rhs": + mesh = self._model._mesh_by_uuid[self.mesh_uuid] + if "volume_selection" not in _payload_dict(mesh): + self._model._rhs_only_volume_ids[self.mesh_uuid] = volume_ref.backend_id + else: + self._bind_volume() + return self + + bind_value.__name__ = name + return bind_value + + def surface_from_file(self, file, *, tag=None): + """Use a PolyFEM sideset. A tag is optional for a single group.""" + self._require_mesh() + with Path(file).open(encoding="utf-8") as rows: + tags = {int(row.split()[0]) for row in rows if row.strip()} + if tag is None: + if len(tags) != 1: + raise ValueError("Specify a tag for a sideset with multiple boundary groups") + tag = next(iter(tags)) + if tag not in tags or tag <= 0: + raise ValueError("Expected a positive tag from the sideset") + geometry = self._model._mesh_by_uuid[self.mesh_uuid] + current = _payload_dict(geometry).get("surface_selection") + payload = {"file": str(file)} + if current != payload: + selection = self._model._api.surface_selection_file(**payload) + self._model._set_mesh_selection_field(self.mesh_uuid, "surface_selection", selection, append=False) + for boundary_tag in tags: + if boundary_tag > 0: + self._model._allocate_selection("surface", backend_id=boundary_tag) + ref = self._model._allocate_selection("surface", backend_id=tag, mesh_uuid=self.mesh_uuid) + return SelectionHandle(self._model, ref) + + def _bind_volume(self): + volume_ref = self._require_mesh() + geometry = self._model._mesh_by_uuid[self.mesh_uuid] + _set_payload_field(geometry, "volume_selection", volume_ref.backend_id) + self._model._rhs_only_volume_ids.pop(self.mesh_uuid, None) + + def _require_mesh(self) -> SelectionRef: + if self.mesh_uuid is None or self.volume_ref is None: + raise ValueError("body.mesh(...) must be called before configuring body") + return self.volume_ref + + def _dynamic_selection_helper(self, name): + if not self._model.has_selection_helper(name): + return None + + def add_selection(*args, **kwargs): + self._require_mesh() + if args: + raise TypeError("%s accepts keyword fields only" % name) + append = kwargs.pop("append", True) + return self._model.add_selection_with_helper( + self.mesh_uuid, + name, + kwargs, + append=append, + ) + + add_selection.__name__ = name + return add_selection + + def surface_all(self, *, id=None, same_as=None): + self._require_mesh() + payload = self._model._shared_surface_id(id, same_as) + return self._model._add_surface_selection( + self.mesh_uuid, + payload, + append=False, + ) + + +class ObstacleHandle: + def __init__(self, model, geometry): + self._model = model + self._geometry = geometry + self._surface = None + + def surface_all(self): + if self._surface is None: + ref = self._model._allocate_selection("surface") + _set_payload_field(self._geometry, "surface_selection", ref.backend_id) + self._surface = SelectionHandle(self._model, ref) + return self._surface + + def __getattr__(self, name): + if name.startswith("_") or not self._model.has_builder_api("surface." + name): + raise AttributeError(name) + return getattr(self.surface_all(), name) + + +class SelectionHandle: + def __init__(self, model, selection_ref): + self._model = model + self.selection_ref = selection_ref + + def __getattr__(self, name): + if name.startswith("_"): + raise AttributeError(name) + + builder_api = "%s.%s" % (self.selection_ref.namespace, name) + if not self._model.has_builder_api(builder_api): + raise AttributeError( + "%s has no configured builder API %r" + % (self.__class__.__name__, builder_api) + ) + + def bind_value(*args, **kwargs): + value = _bind_payload_from_call(builder_api, args, kwargs) + self._model.bind(builder_api, self.selection_ref, value) + return self + + bind_value.__name__ = name + return bind_value + + +def _parse_list_item_consumer(consumer): + parts = consumer.split(".") + if len(parts) < 2 or parts[-1] != "id": + raise ValueError("unsupported ID consumer path: %r" % consumer) + + list_path = [] + for part in parts[:-1]: + if part.endswith("[*]"): + list_path.append(part[:-3]) + else: + list_path.append(part) + + return tuple(list_path), parts[-1] + + +def _bind_payload_from_call(builder_api, args, kwargs): + if len(args) > 1: + raise TypeError("%s accepts at most one payload object" % builder_api) + if args and kwargs: + raise TypeError( + "%s accepts either a payload object or keyword fields, not both" + % builder_api + ) + if args: + return args[0] + if kwargs: + return kwargs + raise TypeError("%s requires a payload object or keyword fields" % builder_api) + + +def _as_dict_if_available(value: object): + as_dict = getattr(value, "as_dict", None) + return as_dict() if callable(as_dict) else value + + +def _payload_dict(value): + if isinstance(value, dict): + return dict(value) + if hasattr(value, "as_dict"): + payload = value.as_dict() + if not isinstance(payload, dict): + raise TypeError("as_dict() must return a dict") + return dict(payload) + raise TypeError("expected dict or generated object with as_dict()") + + +def _copy_payload(value): + if isinstance(value, dict): + return dict(value) + if isinstance(value, list): + return [_copy_payload(item) for item in value] + return value + + +def _selection_signature(namespace, values): + return ( + namespace, + tuple( + (key, _freeze_value(value)) + for key, value in sorted(values.items()) + ), + ) + + +def _freeze_value(value): + if isinstance(value, dict): + return tuple( + (key, _freeze_value(child)) + for key, child in sorted(value.items()) + ) + if isinstance(value, list): + return tuple(_freeze_value(child) for child in value) + return value + + +def _set_payload_field(value, field, field_value): + if isinstance(value, dict): + value[field] = field_value + return + if hasattr(value, field): + setattr(value, field, field_value) + return + raise TypeError("expected dict or generated object with %s field" % field) + + +def _builder_manifest(api_module): + module_file = getattr(api_module, "__file__", None) + if module_file: + path = Path(module_file).with_name("builder_api_manifest.json") + if path.is_file(): + return json.loads(path.read_text(encoding="utf-8")) + return {} + + +def _validate_selection_helper_payload(method_name, payload, allowed_fields): + allowed = set(allowed_fields) + unknown = sorted(set(payload) - allowed) + if unknown: + raise TypeError( + "%s got unsupported field(s): %s" + % (method_name, ", ".join(unknown)) + ) + + +def _construct_api_class(api_module, class_path, payload): + if not class_path: + return None + root = getattr(api_module, "Root", None) + if root is None: + return None + + cls = root + parts = class_path.split(".") + if not parts or parts[0] != "Root": + return None + for part in parts[1:]: + cls = getattr(cls, part, None) + if cls is None: + return None + return cls(**payload) diff --git a/python/polyfempy/_selection_refs.py b/python/polyfempy/_selection_refs.py new file mode 100644 index 00000000..0eb4abe2 --- /dev/null +++ b/python/polyfempy/_selection_refs.py @@ -0,0 +1,46 @@ +import uuid +from dataclasses import dataclass +from typing import Optional + + +@dataclass(frozen=True) +class SelectionRef: + uuid: str + namespace: str + backend_id: int + name: Optional[str] = None + mesh_uuid: Optional[str] = None + + +class SelectionPool: + def __init__(self, groups): + self._groups = dict(groups) + self._next_backend_id = { + group: 1 + for group in set(self._groups.values()) + } + + def allocate(self, namespace, *, name=None, backend_id=None, mesh_uuid=None): + if namespace not in self._groups: + raise ValueError("unsupported selection namespace: %r" % namespace) + + id_group = self._groups[namespace] + if backend_id is None: + backend_id = self._next_backend_id[id_group] + elif not isinstance(backend_id, int): + raise TypeError("selection backend_id must be an int") + elif backend_id < 1: + raise ValueError("selection backend_id must be positive") + + self._next_backend_id[id_group] = max( + self._next_backend_id[id_group], + backend_id + 1, + ) + + return SelectionRef( + uuid=str(uuid.uuid4()), + namespace=namespace, + backend_id=backend_id, + name=name, + mesh_uuid=mesh_uuid, + ) diff --git a/python/polyfempy/cli.py b/python/polyfempy/cli.py new file mode 100644 index 00000000..94ed59f2 --- /dev/null +++ b/python/polyfempy/cli.py @@ -0,0 +1,147 @@ +"""Small command-line entry points for local PolyFEM-Python builds.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path +from typing import Sequence + + +def _load_polyfempy(): + import polyfempy as pf + + return pf + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="polyfempy", + description="PolyFEM-Python command-line helpers.", + ) + subparsers = parser.add_subparsers(dest="command", required=True) + + backend_info = subparsers.add_parser( + "backend-info", + help="print whether the compiled C++ backend is available", + ) + backend_info.add_argument( + "--require", + action="store_true", + help="return a non-zero exit code when the C++ backend is unavailable", + ) + + solve = subparsers.add_parser( + "solve", + help="run PolyFEM with a JSON or YAML config file through the C++ backend", + ) + solve.add_argument("config", help="path to a .json, .yaml, or .yml config file") + solve.add_argument( + "--output-dir", + default="", + help="optional output directory passed to the backend", + ) + solve.add_argument( + "--log-level", + type=int, + default=2, + help="PolyFEM log level, from 0 (all logs) to 6 (off)", + ) + solve.add_argument( + "--max-threads", + type=int, + default=1, + help="maximum number of backend threads", + ) + solve.add_argument( + "--strict-validation", + dest="strict_validation", + action="store_true", + default=True, + help="enable backend settings validation", + ) + solve.add_argument( + "--no-strict-validation", + dest="strict_validation", + action="store_false", + help="disable backend settings validation", + ) + + return parser + + +def _backend_status(pf) -> tuple[bool, object]: + available = bool(getattr(pf, "cpp_backend_available", lambda: False)()) + error = getattr(pf, "cpp_backend_error", lambda: None)() + return available, error + + +def _print_backend_info(pf, *, require: bool) -> int: + available, error = _backend_status(pf) + print(f"backend_available={available}") + print(f"backend_error={error}") + if require and not available: + print( + "C++ backend not loaded. Install a wheel for your Python version " + "and platform, or follow BUILD.md to build from source.", + file=sys.stderr, + ) + return 1 + return 0 + + +def _solve_config(pf, args: argparse.Namespace) -> int: + available, error = _backend_status(pf) + if not available: + print( + "C++ backend not loaded. Real solves require the compiled backend. " + f"Error: {error}", + file=sys.stderr, + ) + return 1 + + if not hasattr(pf, "polyfem_command"): + print( + "C++ backend is loaded but does not expose polyfem_command.", + file=sys.stderr, + ) + return 1 + + config = Path(args.config) + suffix = config.suffix.lower() + yaml_path = str(config) if suffix in {".yaml", ".yml"} else "" + json_path = "" if yaml_path else str(config) + + try: + pf.polyfem_command( + json=json_path, + yaml=yaml_path, + log_level=args.log_level, + strict_validation=args.strict_validation, + max_threads=args.max_threads, + output_dir=args.output_dir, + ) + except Exception as exc: + print(f"polyfempy solve failed: {exc}", file=sys.stderr) + return 1 + + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = _build_parser() + args = parser.parse_args(argv) + pf = _load_polyfempy() + + if args.command == "backend-info": + return _print_backend_info(pf, require=args.require) + + if args.command == "solve": + return _solve_config(pf, args) + + parser.error(f"unknown command: {args.command}") + return 2 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/python/polyfempy/runtime/__init__.py b/python/polyfempy/runtime/__init__.py new file mode 100644 index 00000000..396f519b --- /dev/null +++ b/python/polyfempy/runtime/__init__.py @@ -0,0 +1,29 @@ +"""Handwritten solve/runtime layer for PolyFEM. + +The recommended user-facing surface is intentionally small: + +- ``solve`` for running simulations +- ``Result`` for structured solver output + +Generated configuration helpers are the preferred direction for new authoring +APIs. This package owns runtime preparation, backend dispatch, and result +objects. +""" + +from ._runtime import ( + configure_windows_runtime as _configure_windows_runtime, + should_auto_configure_windows as _should_auto_configure_windows, +) + +if _should_auto_configure_windows(): + _configure_windows_runtime() + +from .result import Result as Result +from .solve import solve as solve + +CORE_RUNTIME = [ + "solve", + "Result", +] + +__all__ = ["solve", "Result"] diff --git a/python/polyfempy/runtime/_runtime.py b/python/polyfempy/runtime/_runtime.py new file mode 100644 index 00000000..9d5f3bf4 --- /dev/null +++ b/python/polyfempy/runtime/_runtime.py @@ -0,0 +1,99 @@ +"""Optional Windows console and OpenMP compatibility settings. + +Importing the package leaves the host process unchanged by default. Set +POLYFEMPY_WINDOWS_AUTOCONFIG=1 before import to enable the legacy settings, +or call configure_windows_runtime() explicitly. The older opt-out variable +POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG takes precedence when both are set. +""" + +from __future__ import annotations + +import io +import os +import sys +from typing import Dict, List + +__all__ = ["configure_windows_runtime", "should_auto_configure_windows"] + + +_TRUTHY = {"1", "true", "yes", "on", "y", "t"} + + +def should_auto_configure_windows() -> bool: + """Return whether the caller explicitly enabled the Windows settings.""" + skip = os.environ.get("POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG", "").strip().lower() + enable = os.environ.get("POLYFEMPY_WINDOWS_AUTOCONFIG", "").strip().lower() + return enable in _TRUTHY and skip not in _TRUTHY + + +def configure_windows_runtime(*, force: bool = False) -> Dict[str, List[str]]: + """Apply Windows-only runtime tweaks to the current Python process. + + The tweaks are: + + - Rewrap ``sys.stdout`` / ``sys.stderr`` as UTF-8 ``TextIOWrapper`` so + Unicode math symbols do not become mojibake under the default CP-1252 + console. Skipped if the stream is already UTF-8. + - Run ``chcp 65001`` so the Windows console code page is UTF-8 too. + - Set ``KMP_DUPLICATE_LIB_OK=TRUE`` to let a process that links multiple + OpenMP runtimes (e.g. PyTorch + polyfempy) continue instead of aborting. + Only set when the variable is not already in the environment so we + never override a deliberate user choice. + + Safe to call multiple times; operations are idempotent unless + ``force=True`` is passed (which re-wraps ``sys.stdout`` / ``sys.stderr`` + even if they are already UTF-8). + + On non-Windows platforms this is a no-op. + + Returns: + A dict with two keys: + + - ``applied``: list of action names that this call actually performed + (e.g. ``["stdout_utf8", "chcp_65001", "kmp_duplicate_lib_ok"]``). + - ``skipped``: list of reasons for every action we chose not to + perform (e.g. ``["not_windows"]``, ``["kmp_already_set"]``, or + ``["stdout_already_utf8"]``). + """ + applied: List[str] = [] + skipped: List[str] = [] + + if sys.platform != "win32": + skipped.append("not_windows") + return {"applied": applied, "skipped": skipped} + + # --- UTF-8 stdout / stderr wrapping --- + for name in ("stdout", "stderr"): + stream = getattr(sys, name, None) + already_utf8 = ( + isinstance(stream, io.TextIOWrapper) + and (getattr(stream, "encoding", "") or "").lower().replace("-", "") == "utf8" + ) + if already_utf8 and not force: + skipped.append(f"{name}_already_utf8") + continue + buf = getattr(stream, "buffer", None) + if buf is None: + skipped.append(f"{name}_no_buffer") + continue + try: + setattr(sys, name, io.TextIOWrapper(buf, encoding="utf-8", errors="replace")) + applied.append(f"{name}_utf8") + except Exception as exc: # pragma: no cover - defensive + skipped.append(f"{name}_utf8_error:{type(exc).__name__}") + + # --- Windows console code page --- + try: + os.system("chcp 65001 >nul 2>&1") + applied.append("chcp_65001") + except Exception as exc: # pragma: no cover - defensive + skipped.append(f"chcp_error:{type(exc).__name__}") + + # --- OpenMP duplicate-runtime toleration --- + if "KMP_DUPLICATE_LIB_OK" in os.environ and not force: + skipped.append("kmp_already_set") + else: + os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" + applied.append("kmp_duplicate_lib_ok") + + return {"applied": applied, "skipped": skipped} diff --git a/python/polyfempy/runtime/_solve_backend.py b/python/polyfempy/runtime/_solve_backend.py new file mode 100644 index 00000000..01aebeb4 --- /dev/null +++ b/python/polyfempy/runtime/_solve_backend.py @@ -0,0 +1,251 @@ +"""Backend adapter helpers for the VarForm forward solve pipeline. + +This module owns only the mechanics of talking to the compiled PolyFEM +VarForm binding: constructing the backend solver, applying settings, attaching +array meshes, and calling ``solve``. User-facing config and mesh-source +semantics live in ``_solve_contract.py``; the final backend bundle is converted +in ``solve.py``. +""" + +from __future__ import annotations + +import copy +import importlib +import json +from typing import Any, Callable, Dict, Optional + +from ._solve_contract import MeshSource, build_canonical_solver_settings + + +def build_solver(): + """Instantiate the compiled VarForm Solver binding.""" + try: + import polyfempy as pf + except Exception as exc: # pragma: no cover - defensive + raise RuntimeError( + "polyfempy bindings not found. Please install/compile them first." + ) from exc + + if not getattr(pf, "cpp_backend_available", lambda: False)(): + err = getattr(pf, "cpp_backend_error", lambda: None)() + raise RuntimeError( + "C++ backend not loaded. Install a wheel for your Python version " + "and platform, or follow BUILD.md to build from source. " + f"Import error: {err}" + ) + + core = importlib.import_module("polyfempy.polyfempy") + if not hasattr(core, "Solver"): + raise RuntimeError("Compiled VarForm backend must expose Solver.") + + solver = core.Solver() + missing = [ + name + for name in ("set_settings", "load_mesh_from_settings", "set_mesh", "solve") + if not hasattr(solver, name) + ] + if missing: + raise RuntimeError( + "Compiled VarForm Solver is missing required methods: " + + ", ".join(missing) + ) + return solver + + +def _apply_settings_json(solver, settings_json: str) -> None: + if not hasattr(solver, "set_settings"): + raise RuntimeError("Compiled VarForm Solver is missing set_settings(...).") + try: + solver.set_settings(settings_json, strict_validation=True) + except RuntimeError as exc: + # Add a focused hint only after the backend rejects the settings. + materials = json.loads(settings_json).get("materials", []) + materials = [materials] if isinstance(materials, dict) else materials + if isinstance(materials, list): + for index, material in enumerate(materials): + if not isinstance(material, dict): + continue + if material.get("type") not in ("LinearElasticity", "NeoHookean"): + continue + if not ({"E", "nu"} <= material.keys() or {"lambda", "mu"} <= material.keys()): + raise RuntimeError( + f"{exc}. materials[{index}] ({material['type']}) requires " + "both E and nu, or both lambda and mu. " + "For example, set E=1000 and nu=0.3." + ) from exc + raise + + +def _configure_json_mode( + solver, + full_json: Optional[Dict[str, Any]], + cfg, + *, + backend_settings: Optional[Dict[str, Any]] = None, +) -> None: + settings_dict = ( + copy.deepcopy(backend_settings) + if backend_settings is not None + else build_canonical_solver_settings( + cfg, + full_json=full_json, + mesh_source=MeshSource(mode="json"), + ) + ) + _apply_settings_json(solver, json.dumps(settings_dict)) + solver.load_mesh_from_settings() + + +def _configure_array_mode( + solver, + cfg, + mesh_source: MeshSource, + *, + backend_settings: Optional[Dict[str, Any]] = None, +) -> None: + if mesh_source.body_ids is not None: + raise NotImplementedError( + "VarForm array mode does not support Python-side body_ids. " + "Use model selections, or put body tags in a mesh file." + ) + if mesh_source.boundary_ids is not None: + raise NotImplementedError( + "VarForm array mode does not support Python-side boundary_ids. " + "Use model selections, or put boundary tags in a mesh file." + ) + settings_dict = ( + copy.deepcopy(backend_settings) + if backend_settings is not None + else build_canonical_solver_settings( + cfg, + full_json=None, + mesh_source=mesh_source, + ) + ) + use_geometry_settings = _array_uses_geometry_settings(settings_dict) + if use_geometry_settings and not hasattr(solver, "set_settings_with_mesh"): + raise RuntimeError( + "This native backend cannot apply geometry selections to array meshes. " + "Install a matching package or rebuild the C++ backend using BUILD.md." + ) + if use_geometry_settings: + solver.set_settings_with_mesh(json.dumps(settings_dict), mesh_source.vertices, mesh_source.cells) + else: + _apply_settings_json(solver, json.dumps(settings_dict)) + _apply_mesh_array_mode(solver, mesh_source) + + +def _array_uses_geometry_settings(settings: Dict[str, Any]) -> bool: + geometry = settings.get("geometry", []) + entries = [geometry] if isinstance(geometry, dict) else geometry + # Older array configurations use this entry only to satisfy the root schema. + if entries == [{"type": "ground", "height": 0.0, "enabled": True, "is_obstacle": False}]: + return False + if not entries: + return False + if not isinstance(entries, list) or not all(isinstance(entry, dict) for entry in entries): + raise ValueError("Array mesh geometry must be an object or a list of objects.") + enabled = [entry for entry in entries if entry.get("enabled", True)] + deformable = [entry for entry in enabled if not entry.get("is_obstacle", False)] + if len(deformable) != 1: + raise ValueError( + "An array mesh requires exactly one enabled deformable geometry entry. " + "Use solve(cfg=...) to load multiple meshes from files." + ) + if deformable[0].get("type", "mesh") != "mesh": + raise ValueError("An array mesh requires a deformable geometry entry of type 'mesh'.") + return True + + +def _apply_mesh_array_mode(solver, mesh_source: MeshSource) -> None: + if not hasattr(solver, "set_mesh"): + raise RuntimeError("Compiled VarForm Solver is missing set_mesh(...).") + + solver.set_mesh(mesh_source.vertices, mesh_source.cells) + + +def configure_solver( + solver, + cfg, + full_json: Optional[dict], + mesh_source: MeshSource, + *, + backend_settings: Optional[Dict[str, Any]] = None, +) -> None: + """Set settings and load or attach the mesh.""" + if mesh_source.mode == "json": + _configure_json_mode( + solver, + full_json, + cfg, + backend_settings=backend_settings, + ) + return + + _configure_array_mode( + solver, + cfg, + mesh_source, + backend_settings=backend_settings, + ) + + +def apply_sidesets(solver, sidesets_func: Optional[Callable]) -> None: + """Reject the old Python-side sideset mutation hook. + + New VarForm solves should receive boundary information through settings and + mesh data before ``load_mesh``/``set_mesh``. The old hook depended on + mutating the backend mesh object after loading. + """ + if sidesets_func is None: + return + raise NotImplementedError( + "sidesets_func is not supported by the VarForm runtime. " + "Encode boundary ids in the mesh/config before calling solve()." + ) + + +def _resolve_log_level(full_json: Optional[dict]) -> int: + if not (full_json and "output" in full_json and "log" in full_json["output"]): + return 2 + log_cfg = full_json["output"]["log"] + # Keep terminal logging aligned with the generated OutputLog default. + # ``OutputLog.to_dict()`` omits ``level`` when it is the default "debug", + # so falling back to "info" here would silently make console output less + # verbose than the file log. + log_level = log_cfg.get("level", "debug") + if isinstance(log_level, int) and not isinstance(log_level, bool): + return max(0, min(6, log_level)) + + if isinstance(log_level, str) and log_level.strip().isdigit(): + return max(0, min(6, int(log_level.strip()))) + + log_level_map = { + "trace": 0, + "debug": 1, + "info": 2, + "warn": 3, + "warning": 3, + "error": 4, + "critical": 5, + "off": 6, + } + if isinstance(log_level, str): + return log_level_map.get(log_level.lower(), 2) + return 2 + + +def run_solver_stage(solver, full_json: Optional[dict]): + """Run the VarForm backend solve entry point and return its raw result.""" + if not hasattr(solver, "solve"): + raise RuntimeError("Compiled VarForm backend requires solve entry point.") + + return solver.solve(log_level=_resolve_log_level(full_json)) + + +__all__ = [ + "apply_sidesets", + "build_solver", + "configure_solver", + "run_solver_stage", +] diff --git a/python/polyfempy/runtime/_solve_contract.py b/python/polyfempy/runtime/_solve_contract.py new file mode 100644 index 00000000..7dfc05e5 --- /dev/null +++ b/python/polyfempy/runtime/_solve_contract.py @@ -0,0 +1,682 @@ +"""Shared solve contract helpers. + +This internal module owns the parts of ``solve`` that define user-facing +semantics before the C++ backend is touched: config normalization, mesh-source +selection, and backend settings construction. +""" + +from __future__ import annotations + +import copy +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Optional, overload + +import numpy as np + +from . import tensor as T + + +class NoMeshSourceError(ValueError): + """Raised when a solve call has no usable JSON or array mesh source.""" + + +@dataclass +class MeshSource: + """Resolved mesh source for a solve call.""" + + mode: str + vertices: Optional[np.ndarray] = None + cells: Optional[np.ndarray] = None + body_ids: Optional[np.ndarray] = None + boundary_ids: Optional[np.ndarray] = None + v_backend: str = "numpy" + + +@dataclass +class CanonicalSolveInput: + """Normalized config, mesh, and backend settings for a solve pipeline.""" + + config: Any + full_json: Optional[Dict[str, Any]] + mesh_source: MeshSource + backend_settings: Dict[str, Any] + metadata: Dict[str, Any] + + +def is_generated_config(obj: Any) -> bool: + """Return True for objects that look like generated config objects.""" + return callable(getattr(obj, "as_dict", None)) + + +def generated_payload_from_config(cfg: Any) -> Dict[str, Any]: + """Return the plain dict emitted by a generated config object.""" + as_dict = getattr(cfg, "as_dict", None) + if not callable(as_dict): + raise TypeError(f"cfg must expose as_dict(), got {type(cfg).__name__}") + + payload = as_dict() + if not isinstance(payload, dict): + raise TypeError( + f"cfg.as_dict() must return dict, got {type(payload).__name__}" + ) + return payload + + +def prepare_generated_backend_payload( + payload: Dict[str, Any], + *, + root_path: str | None = None, +) -> Dict[str, Any]: + """Prepare a generated ``Root.as_dict()`` payload for the backend.""" + backend = copy.deepcopy(payload) + resolved_root_path = root_path or backend.get("root_path") + if resolved_root_path and not backend.get("common"): + _resolve_geometry_mesh_paths_in_place(backend, str(resolved_root_path)) + _resolve_collision_mesh_paths_in_place(backend, str(resolved_root_path)) + _normalize_nonlinear_tolerance_names(backend) + _restore_backend_payload_semantics(backend) + return clean_json_for_cpp(backend) + + +_SOLVER_ADVANCED_GENERATED_DEFAULTS = { + "cache_size": 900000, + "lump_mass_matrix": False, + "lagged_regularization_weight": 0.0, + "lagged_regularization_iterations": 1, + "check_inversion": "Discrete", + "jacobian_threshold": 0.0, + "characteristic_length": -1.0, + "characteristic_force_density": 10000.0, +} + +_NONLINEAR_GENERATED_DEFAULTS = { + "rel_grad_norm_tol": 1e-10, + "newton_decrement_tol": 0.0, + "rel_x_delta_tol": 0.0, + "first_grad_norm_tol": 1e-12, + "norm_type": "L2", + "max_iterations": 500, + "allow_out_of_iterations": False, +} + +_LINE_SEARCH_GENERATED_DEFAULTS = { + "use_grad_norm_tol": 1e-06, + "min_step_size": 1e-10, + "max_step_size_iter": 30, + "min_step_size_final": 1e-20, + "max_step_size_iter_final": 100, + "default_init_step_size": 1.0, + "step_ratio": 0.5, +} + +_NONLINEAR_ADVANCED_GENERATED_DEFAULTS = { + "f_delta_tol": 0.0, + "f_delta_step_tol": 100, + "derivative_along_delta_x_tol": 0, + "apply_gradient_fd": "None", + "gradient_fd_eps": 1e-07, +} + + +def _restore_backend_payload_semantics(payload: Dict[str, Any]) -> None: + _restore_materials_semantics(payload) + _restore_transformation_semantics(payload) + _restore_nonlinear_solver_semantics(payload) + _drop_solver_advanced_generated_defaults(payload) + + +def _restore_materials_semantics(payload: Dict[str, Any]) -> None: + materials = payload.get("materials") + if not isinstance(materials, list) or len(materials) != 1: + return + + material = materials[0] + if isinstance(material, dict) and "id" not in material: + payload["materials"] = material + + +def _restore_transformation_semantics(payload: Dict[str, Any]) -> None: + geometry = payload.get("geometry") + if not isinstance(geometry, list): + return + + for entry in geometry: + if not isinstance(entry, dict): + continue + + transformation = entry.get("transformation") + if not isinstance(transformation, dict): + continue + + for scalar_or_vector_key in ("scale", "rotation"): + value = transformation.get(scalar_or_vector_key) + if isinstance(value, list) and len(value) == 1: + transformation[scalar_or_vector_key] = value[0] + + for empty_list_key in ("translation", "rotation", "scale"): + if transformation.get(empty_list_key) == []: + transformation.pop(empty_list_key) + + if transformation.get("rotation_mode") == "xyz": + transformation.pop("rotation_mode") + + if not transformation: + entry.pop("transformation") + + +def _drop_solver_advanced_generated_defaults(payload: Dict[str, Any]) -> None: + solver = payload.get("solver") + if not isinstance(solver, dict): + return + + advanced = solver.get("advanced") + if not isinstance(advanced, dict): + return + + for key, default_value in _SOLVER_ADVANCED_GENERATED_DEFAULTS.items(): + if advanced.get(key) == default_value: + advanced.pop(key) + + if not advanced: + solver.pop("advanced") + + +def _restore_nonlinear_solver_semantics(payload: Dict[str, Any]) -> None: + solver = payload.get("solver") + if not isinstance(solver, dict): + return + + nonlinear = solver.get("nonlinear") + if not isinstance(nonlinear, dict): + return + + for key, default_value in _NONLINEAR_GENERATED_DEFAULTS.items(): + if nonlinear.get(key) == default_value: + nonlinear.pop(key) + + line_search = nonlinear.get("line_search") + if isinstance(line_search, dict): + for key, default_value in _LINE_SEARCH_GENERATED_DEFAULTS.items(): + if line_search.get(key) == default_value: + line_search.pop(key) + if not line_search: + nonlinear.pop("line_search") + + advanced = nonlinear.get("advanced") + if isinstance(advanced, dict): + for key, default_value in _NONLINEAR_ADVANCED_GENERATED_DEFAULTS.items(): + if advanced.get(key) == default_value: + advanced.pop(key) + if not advanced: + nonlinear.pop("advanced") + + +def _normalize_nonlinear_tolerance_names(payload: Dict[str, Any]) -> None: + """Accept the old f_delta name; an explicit f_delta_tol takes precedence.""" + solver = payload.get("solver") + if not isinstance(solver, dict): + return + for settings in (solver, solver.get("augmented_lagrangian")): + if not isinstance(settings, dict): + continue + nonlinear = settings.get("nonlinear") + if not isinstance(nonlinear, dict): + continue + advanced = nonlinear.get("advanced") + if isinstance(advanced, dict): + _rename_key(advanced, "f_delta", "f_delta_tol") + + +def _rename_key(payload: Dict[str, Any], old: str, new: str) -> None: + if old in payload and new not in payload: + payload[new] = payload.pop(old) + else: + payload.pop(old, None) + + +def _resolve_geometry_mesh_paths_in_place(payload: Dict[str, Any], root_path: str) -> None: + geometry = payload.get("geometry") + if not isinstance(geometry, list): + return + + root = Path(root_path).resolve() + root_dir = root if root.is_dir() else root.parent + for entry in geometry: + if not isinstance(entry, dict): + continue + + _resolve_geometry_selection_files_in_place(entry, root_path) + + mesh_path = entry.get("mesh") + if not isinstance(mesh_path, str) or not mesh_path.strip(): + continue + + mesh_file = Path(mesh_path) + if mesh_file.is_absolute(): + continue + + direct = root_dir / mesh_file + if direct.exists(): + entry["mesh"] = str(direct) + continue + + if mesh_path == mesh_file.name: + sibling = root_dir.parent / "meshes" / mesh_file.name + if sibling.is_file(): + entry["mesh"] = str(sibling) + + +def _resolve_geometry_selection_files_in_place(entry: Dict[str, Any], root_path: str) -> None: + for key in ("volume_selection", "surface_selection", "point_selection"): + selection = entry.get(key) + if isinstance(selection, str) and selection.strip(): + entry[key] = _resolve_existing_path_from_root(root_path, selection) + else: + _resolve_selection_file_paths_in_place(selection, root_path) + + +def _resolve_selection_file_paths_in_place(selection: Any, root_path: str) -> None: + if isinstance(selection, list): + for item in selection: + _resolve_selection_file_paths_in_place(item, root_path) + return + + if not isinstance(selection, dict): + return + + file_path = selection.get("file") + if isinstance(file_path, str) and file_path.strip(): + selection["file"] = _resolve_existing_path_from_root(root_path, file_path) + + +def _resolve_existing_path_from_root(root_path: str, path_value: str) -> str: + path = Path(path_value) + if path.is_absolute(): + return path_value + + root = Path(root_path).resolve() + root_dir = root if root.is_dir() else root.parent + resolved = root_dir / path + if resolved.exists(): + return str(resolved) + return path_value + + +def _resolve_collision_mesh_paths_in_place(payload: Dict[str, Any], root_path: str) -> None: + contact = payload.get("contact") + if not isinstance(contact, dict): + return + + collision_mesh = contact.get("collision_mesh") + if not isinstance(collision_mesh, dict): + return + + for key in ("mesh", "linear_map"): + value = collision_mesh.get(key) + if isinstance(value, str) and value.strip(): + collision_mesh[key] = _resolve_existing_path_from_root(root_path, value) + + +def cfg_array_mesh_payload(cfg: Any) -> Optional[Dict[str, Any]]: + if isinstance(cfg, dict): + payload = cfg.get("_mesh_array_mode") + if isinstance(payload, dict): + return payload + extras = cfg.get("extras") + if isinstance(extras, dict): + payload = extras.get("_mesh_array_mode") + if isinstance(payload, dict): + return payload + return None + + extras = getattr(cfg, "extras", None) + if isinstance(extras, dict): + payload = extras.get("_mesh_array_mode") + if isinstance(payload, dict): + return payload + return None + + +def _load_json_payload(path: str | Path) -> Dict[str, Any]: + json_path = Path(path).resolve() + try: + with json_path.open("r", encoding="utf-8") as f: + payload = json.load(f) + except FileNotFoundError as exc: + raise FileNotFoundError( + f"Configuration file not found: {json_path}. " + "Check the path or pass cfg=model.config()." + ) from exc + except json.JSONDecodeError as exc: + raise ValueError( + f"Invalid JSON in {json_path}, line {exc.lineno}, column {exc.colno}: {exc.msg}" + ) from exc + if not isinstance(payload, dict): + raise TypeError(f"JSON config must contain an object, got {type(payload).__name__}") + root_path = payload.get("root_path", "") + if isinstance(root_path, str): + payload["root_path"] = str((json_path.parent / root_path).resolve() if root_path else json_path) + return payload + + +def _payload_dict_or_raise(cfg: Any, *, context: str) -> Dict[str, Any]: + if isinstance(cfg, dict): + return copy.deepcopy(cfg) + + for method_name in ("to_json_dict", "to_dict"): + method = getattr(cfg, method_name, None) + if not callable(method): + continue + try: + payload = method() + except Exception as exc: + raise RuntimeError(f"cfg.{method_name}() failed while {context}") from exc + if not isinstance(payload, dict): + raise TypeError( + f"cfg.{method_name}() must return dict while {context}, " + f"got {type(payload).__name__}" + ) + return copy.deepcopy(payload) + + raise TypeError( + "cfg must be dict, str/Path JSON file path, generated object with as_dict(), " + f"or expose to_dict()/to_json_dict(); got {type(cfg).__name__}" + ) + + +def normalize_config(cfg: Any) -> Dict[str, Any]: + """Accept a backend-shaped dict, JSON path, or generated-style config object.""" + if cfg is None: + raise ValueError("cfg (configuration) is required") + if isinstance(cfg, dict): + return copy.deepcopy(cfg) + if isinstance(cfg, (str, Path)): + return _load_json_payload(cfg) + if is_generated_config(cfg): + return copy.deepcopy(generated_payload_from_config(cfg)) + return _payload_dict_or_raise(cfg, context="normalizing config") + + +def validate_config(cfg: Any) -> None: + if hasattr(cfg, "validate"): + cfg.validate() + + +def _ensure_i32(cells: np.ndarray) -> np.ndarray: + return cells.astype(np.int32, copy=False) if cells.dtype != np.int32 else cells + + +def _validate_mesh_arrays(vertices: np.ndarray, cells: np.ndarray) -> None: + if vertices.ndim != 2 or vertices.shape[1] not in (2, 3) or not len(vertices): + raise ValueError("vertices must be a non-empty array with shape (n, 2) or (n, 3).") + if vertices.dtype.kind not in "iuf" or not np.isfinite(vertices).all(): + raise ValueError("vertices must contain finite real coordinates; remove NaN and infinity.") + if cells.ndim != 2 or not cells.size: + raise ValueError("cells must be a non-empty 2D array, with one element per row.") + if cells.dtype.kind not in "iuf" or not np.isfinite(cells).all(): + raise ValueError("cells must contain finite integer vertex indices.") + if cells.dtype.kind == "f" and not np.equal(cells, np.floor(cells)).all(): + raise ValueError("cells must contain integer vertex indices; fractional indices are invalid.") + if cells.min() < 0 or cells.max() >= len(vertices): + raise ValueError( + f"cells contains a vertex index outside 0..{len(vertices) - 1}. " + "Use zero-based indices into vertices." + ) + if cells.max() > np.iinfo(np.int32).max: + raise ValueError("cells indices exceed the int32 range supported by the backend.") + + +def _promote_materials_to_list(payload: Dict[str, Any], *, infer_type_from_pde: bool = False) -> None: + materials = payload.get("materials") + if not isinstance(materials, dict): + return + if infer_type_from_pde and "type" not in materials: + pde = payload.get("pde", "LinearElasticity") + materials["type"] = "Laplacian" if pde == "Poisson" else "LinearElasticity" + payload["materials"] = [materials] + + +def merge_user_cfg_over_full_json(cfg: Any, full_json: Dict[str, Any]) -> Dict[str, Any]: + cfg_dict = _payload_dict_or_raise(cfg, context="merging Python-side config over full JSON") + + merged = copy.deepcopy(full_json) if isinstance(full_json, dict) else {} + extras = cfg_dict.pop("extras", None) + for key, value in cfg_dict.items(): + merged[key] = value + + if isinstance(extras, dict) and "_root_path" in extras: + merged["root_path"] = extras["_root_path"] + elif isinstance(full_json, dict) and "root_path" in full_json: + merged["root_path"] = full_json["root_path"] + + return merged + + +def build_full_json(cfg: Any) -> Optional[Dict[str, Any]]: + validate_config(cfg) + + if cfg_array_mesh_payload(cfg) is not None: + return None + + cfg_dict = _payload_dict_or_raise(cfg, context="building full JSON settings") + extras = cfg_dict.get("extras") + if isinstance(extras, dict) and "_full_json_config" in extras: + return merge_user_cfg_over_full_json(cfg_dict, extras["_full_json_config"]) + + if "geometry" not in cfg_dict and not cfg_dict.get("common"): + return None + + full_json = cfg_dict + full_json.pop("extras", None) + full_json.pop("_mesh_array_mode", None) + return full_json + + +def choose_mesh_source( + vertices: Any, + cells: Any, + full_json: Optional[Dict[str, Any]], + *, + dtype: Any = None, + cfg: Any = None, +) -> MeshSource: + """Resolve the real mesh source for this solve. + + Explicit partial array input is an error even when JSON geometry exists, + because silently falling back would change the user's requested data binding. + """ + if (vertices is None) ^ (cells is None): + raise ValueError("array mode requires both vertices and cells") + + array_payload = cfg_array_mesh_payload(cfg) + used_cfg_array_payload = False + if vertices is None and cells is None and array_payload is not None: + vertices = array_payload.get("vertices") + cells = array_payload.get("cells") + used_cfg_array_payload = True + if vertices is None or cells is None: + raise ValueError("guided array mesh payload requires both vertices and cells") + + if vertices is not None and cells is not None: + V_np, v_backend = T.as_numpy(vertices, dtype=dtype) + C_np, _ = T.as_numpy(cells) + _validate_mesh_arrays(V_np, C_np) + body_ids_np = None + boundary_ids_np = None + if used_cfg_array_payload and array_payload is not None: + if array_payload.get("body_ids") is not None: + body_ids_np = np.asarray(array_payload["body_ids"], dtype=np.int32).reshape(-1) + if array_payload.get("boundary_ids") is not None: + boundary_ids_np = np.asarray(array_payload["boundary_ids"], dtype=np.int32).reshape(-1) + return MeshSource( + mode="guided_array" if used_cfg_array_payload else "array", + vertices=V_np, + cells=_ensure_i32(C_np), + body_ids=body_ids_np, + boundary_ids=boundary_ids_np, + v_backend=v_backend, + ) + + if full_json is not None and ("geometry" in full_json or full_json.get("common")): + return MeshSource(mode="json", v_backend="numpy") + + raise NoMeshSourceError( + "Either provide vertices/cells arrays, or use JSON config with geometry (mesh files)" + ) + + +@overload +def clean_json_for_cpp(obj: Dict[str, Any]) -> Dict[str, Any]: ... + + +@overload +def clean_json_for_cpp(obj: Any) -> Any: ... + + +def clean_json_for_cpp(obj: Any) -> Any: + if isinstance(obj, dict): + cleaned = {} + for key, value in obj.items(): + cleaned_value = clean_json_for_cpp(value) + if cleaned_value is not None: + cleaned[key] = cleaned_value + return cleaned + if isinstance(obj, list): + cleaned_items = [] + for item in obj: + cleaned_item = clean_json_for_cpp(item) + if cleaned_item is not None: + cleaned_items.append(cleaned_item) + return cleaned_items + return obj + + +def process_json_config(full_json: Dict[str, Any]) -> Dict[str, Any]: + processed = copy.deepcopy(full_json) + processed.pop("extras", None) + processed.pop("_mesh_array_mode", None) + + root_path = processed.get("root_path") + # A common file can supply its own resource root. Let the backend resolve it first. + if root_path and not processed.get("common"): + _resolve_geometry_mesh_paths_in_place(processed, str(root_path)) + return processed + + +def _strip_guided_array_placeholders(settings: Dict[str, Any]) -> None: + geometry = settings.get("geometry") + if not isinstance(geometry, list): + return + kept = [] + for entry in geometry: + if isinstance(entry, dict) and str(entry.get("mesh", "")).startswith("__array_body__:"): + continue + kept.append(entry) + if kept: + settings["geometry"] = kept + else: + settings.pop("geometry", None) + + +def build_canonical_solver_settings( + cfg: Any, + *, + full_json: Optional[Dict[str, Any]], + mesh_source: MeshSource, +) -> Dict[str, Any]: + """Build backend JSON/settings after config and mesh source are known.""" + if mesh_source.mode == "json": + if full_json is None: + raise ValueError("JSON mesh mode requires full_json settings") + settings = process_json_config(full_json) + _normalize_nonlinear_tolerance_names(settings) + if settings.get("common"): + # JSON Merge Patch uses null to remove a key inherited from the common file. + return settings + return clean_json_for_cpp(settings) + + settings = _payload_dict_or_raise(cfg, context="building array-mode backend settings") + + if mesh_source.mode == "guided_array": + _strip_guided_array_placeholders(settings) + + settings.pop("extras", None) + settings.pop("_mesh_array_mode", None) + + if "geometry" not in settings: + settings["geometry"] = [ + {"type": "ground", "height": 0.0, "enabled": True, "is_obstacle": False} + ] + + _promote_materials_to_list(settings, infer_type_from_pde=True) + _normalize_nonlinear_tolerance_names(settings) + return clean_json_for_cpp(settings) + + +def _prepare_generated_canonical_solve_input( + *, + vertices: Any, + cells: Any, + cfg: Any, + dtype: Any = None, +) -> CanonicalSolveInput: + payload = generated_payload_from_config(cfg) + mesh_source = choose_mesh_source( + vertices, + cells, + payload, + dtype=dtype, + cfg=cfg, + ) + backend_settings = prepare_generated_backend_payload(payload) + return CanonicalSolveInput( + config=cfg, + full_json=payload, + mesh_source=mesh_source, + backend_settings=backend_settings, + metadata={ + "mesh_source": mesh_source.mode, + "config_source": "generated", + }, + ) + + +def prepare_canonical_solve_input( + *, + vertices: Any, + cells: Any, + cfg: Any, + dtype: Any = None, +) -> CanonicalSolveInput: + """Normalize config, resolve mesh source, and build backend settings once.""" + if is_generated_config(cfg): + return _prepare_generated_canonical_solve_input( + vertices=vertices, + cells=cells, + cfg=cfg, + dtype=dtype, + ) + + config = normalize_config(cfg) + full_json = build_full_json(config) + mesh_source = choose_mesh_source( + vertices, + cells, + full_json, + dtype=dtype, + cfg=config, + ) + backend_settings = build_canonical_solver_settings( + config, + full_json=full_json, + mesh_source=mesh_source, + ) + return CanonicalSolveInput( + config=config, + full_json=full_json, + mesh_source=mesh_source, + backend_settings=backend_settings, + metadata={"mesh_source": mesh_source.mode}, + ) diff --git a/python/polyfempy/runtime/result.py b/python/polyfempy/runtime/result.py new file mode 100644 index 00000000..00440de0 --- /dev/null +++ b/python/polyfempy/runtime/result.py @@ -0,0 +1,21 @@ +from typing import Any, Mapping + +import numpy as np +from numpy.typing import ArrayLike, NDArray + + +class Result: + """The solution and metadata returned by a forward solve. + + ``sol`` is the raw solution returned by ``polyfem::State::solve``. It is + not assumed to be aligned with mesh vertices or sampled visualization data. + + Attributes: + sol: Contiguous NumPy array containing the raw solution coefficients. + Its shape and component order depend on the finite-element space. + meta: Dictionary of backend metadata. Its entries depend on the solve. + """ + + def __init__(self, sol: ArrayLike, *, meta: Mapping[str, Any] | None = None): + self.sol: NDArray = np.ascontiguousarray(np.asarray(sol)) + self.meta: dict[str, Any] = {} if meta is None else dict(meta) diff --git a/python/polyfempy/runtime/solve.py b/python/polyfempy/runtime/solve.py new file mode 100644 index 00000000..ce403966 --- /dev/null +++ b/python/polyfempy/runtime/solve.py @@ -0,0 +1,120 @@ +"""Public solve entry point and internal orchestration.""" + +from __future__ import annotations + +from typing import Any, Callable, Optional + +import numpy as np +from numpy.typing import ArrayLike, DTypeLike + +from . import _solve_backend as _backend +from . import _solve_contract as _contract +from .result import Result + +__all__ = ["solve"] + + +def _result_from_backend_return(ret) -> Result: + """Convert the standard C++ backend result bundle into a Result.""" + if not isinstance(ret, dict) or not ret.get("_result_bundle"): + raise RuntimeError( + "PolyFEM backend did not return the standard result bundle. " + "Expected a dict with _result_bundle and sol." + ) + + if "p" in ret: + raise RuntimeError( + "PolyFEM backend returned legacy pressure field 'p'. " + "Rebuild the VarForm backend so Solver.solve() returns only sol." + ) + if "u" in ret: + raise RuntimeError( + "PolyFEM backend returned legacy u field. " + "Rebuild the VarForm backend so Solver.solve() returns raw sol." + ) + + if "sol" not in ret: + raise RuntimeError("PolyFEM backend result bundle is missing required keys: sol") + + meta = {} + if isinstance(ret.get("meta"), dict): + meta.update(ret["meta"]) + + return Result( + np.asarray(ret["sol"]), + meta=meta, + ) + + +def run_pipeline( + vertices=None, + cells=None, + cfg=None, + sidesets_func: Optional[Callable] = None, + dtype=None, +) -> Result: + """Drive the full solve pipeline.""" + _backend.apply_sidesets(None, sidesets_func) + canonical = _contract.prepare_canonical_solve_input( + vertices=vertices, + cells=cells, + cfg=cfg, + dtype=dtype, + ) + solver = _backend.build_solver() + _backend.configure_solver( + solver, + canonical.config, + canonical.full_json, + canonical.mesh_source, + backend_settings=canonical.backend_settings, + ) + ret = _backend.run_solver_stage(solver, canonical.backend_settings) + return _result_from_backend_return(ret) + + +def solve( + vertices: ArrayLike | None = None, + cells: ArrayLike | None = None, + cfg: Any = None, + sidesets_func: Optional[Callable] = None, + dtype: DTypeLike | None = None, +) -> Result: + """Run a forward simulation with the compiled PolyFEM backend. + + Args: + vertices: Optional vertex coordinates. Supply both vertices and cells + to use an array mesh instead of mesh files in the configuration. + cells: Optional element connectivity with zero-based vertex indices. + Connectivity is converted to int32 before calling the backend. + cfg: Required simulation configuration. Use model.config(), a dict, + or a JSON file path. Objects with as_dict(), to_dict(), or + to_json_dict() are also accepted. A JSON file resolves relative + mesh paths from its location. + sidesets_func: Reserved for compatibility. Only None is supported. + Set boundary conditions on the model or in the mesh/configuration. + dtype: Optional NumPy dtype for input vertex coordinates. This does + not select the precision of the native solver. + + Returns: + A Result with the raw finite-element solution in result.sol and + backend metadata in result.meta. Solution rows are not necessarily + mesh vertices. result.sol is a NumPy array, including for tensor input. + + Raises: + ValueError: The configuration or a required mesh input is missing. + TypeError: The configuration has an unsupported type. + NotImplementedError: A legacy sideset callback or unsupported array + mesh tags are supplied. + RuntimeError: The native backend cannot load or the solve fails. + + Example: + result = solve(cfg=model.config()) + """ + return run_pipeline( + vertices=vertices, + cells=cells, + cfg=cfg, + sidesets_func=sidesets_func, + dtype=dtype, + ) diff --git a/python/polyfempy/runtime/tensor.py b/python/polyfempy/runtime/tensor.py new file mode 100644 index 00000000..0a75d34e --- /dev/null +++ b/python/polyfempy/runtime/tensor.py @@ -0,0 +1,168 @@ +import importlib +import numpy as np + + +def _maybe_import(name: str): + """Import a module only when needed. + + Args: + name: Module name, e.g. "torch" or "jax.numpy". + + Returns: + The imported module object if available; otherwise None. + """ + try: + return importlib.import_module(name) + except Exception: + return None + + +def _is_torch_tensor(x) -> bool: + """Check whether `x` is a torch.Tensor without importing torch. + + We detect by inspecting the object's type module name. + + Args: + x: Any Python object. + + Returns: + True if `x` looks like a torch.Tensor; False otherwise. + """ + m = type(x).__module__ + return m.startswith("torch") and type(x).__name__ == "Tensor" + + +def _is_jax_array(x) -> bool: + """Check whether `x` is a JAX array (no import required). + + Args: + x: Any Python object. + + Returns: + True if `x` originates from a 'jax.*' module; False otherwise. + """ + m = type(x).__module__ + return m.startswith("jax") + + +def detect_backend(x): + """Detect the backend of `x` without forcing imports. + + Args: + x: Array/tensor-like object from NumPy, Torch, or JAX. + + Returns: + Literal string: 'numpy', 'torch', or 'jax'. + """ + if _is_torch_tensor(x): + return "torch" + if _is_jax_array(x): + return "jax" + return "numpy" + + +def _torch_to_numpy_zero_copy(t): + """Convert a Torch tensor to NumPy with zero copy when safe. + + Conditions for zero copy: + - CPU device + - contiguous memory layout + + Falls back to moving to CPU and making it contiguous if needed. + + Args: + t: torch.Tensor (any device/contiguity). + + Returns: + np.ndarray sharing memory with `t` if (CPU + contiguous), otherwise a CPU copy. + + Raises: + RuntimeError: If a torch tensor is detected but torch is not installed. + """ + torch = _maybe_import("torch") + if torch is None: + raise RuntimeError("Torch tensor detected but 'torch' is not installed.") + t = t.detach() + if t.device.type != "cpu": + t = t.cpu() + if not t.is_contiguous(): + t = t.contiguous() + return t.numpy() # shares memory with `t` when contiguous CPU + + +def as_numpy(x, dtype=None): + """Normalize any backend array/tensor to a C-contiguous NumPy array on CPU. + + Torch CPU contiguous tensors go through zero copy; Torch GPU tensors are moved + to CPU; JAX arrays are converted via np.asarray (may copy). + + Args: + x: Input array/tensor (NumPy / Torch / JAX). + dtype: Optional target dtype; if provided, cast without copying when possible. + + Returns: + (arr_np, backend): + arr_np (np.ndarray): CPU, C-contiguous NumPy array. + backend (str): 'numpy' | 'torch' | 'jax' indicating the original backend. + """ + backend = detect_backend(x) + if backend == "torch": + arr = _torch_to_numpy_zero_copy(x) + elif backend == "jax": + arr = np.asarray(x) + else: + arr = np.asarray(x) + + if dtype is not None and arr.dtype != dtype: + arr = arr.astype(dtype, copy=False) + if not arr.flags.c_contiguous: + arr = np.ascontiguousarray(arr) + return arr, backend + + +def from_numpy(arr, backend): + """Convert a NumPy array back to the requested backend. + + Torch path uses zero copy (shared memory) when possible. + + Args: + arr: NumPy array (ideally C-contiguous for torch zero copy). + backend: Target backend: 'numpy' | 'torch' | 'jax'. + + Returns: + Array/tensor in the target backend. + + Raises: + RuntimeError: If torch/jax is requested but not installed. + """ + if backend == "torch": + torch = _maybe_import("torch") + if torch is None: + raise RuntimeError("Requested torch backend, but 'torch' is not installed.") + if not arr.flags.c_contiguous: + arr = np.ascontiguousarray(arr) + return torch.from_numpy(arr) + + if backend == "jax": + jnp = _maybe_import("jax.numpy") + if jnp is None: + raise RuntimeError("Requested jax backend, but 'jax' is not installed.") + return jnp.asarray(arr) + + return arr + + +def to_backend(arr, backend): + """None-safe wrapper around from_numpy(). + + Args: + arr: NumPy array or None (when a field/result is optional). + backend: Target backend for conversion. + + Returns: + None if `arr` is None; otherwise converted array/tensor. + """ + if arr is None: + return None + return from_numpy(arr, backend) + \ No newline at end of file diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 00000000..19dc5d3b --- /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 = ["polyfem", "polyfempy"] + diff --git a/setup.py b/setup.py index 5982caf9..42812ad4 100644 --- a/setup.py +++ b/setup.py @@ -1,123 +1,196 @@ +"""Build the Python package and its native extension.""" + import os -import re -import sys -# import sysconfig import platform +import re import subprocess +import sys +import sysconfig +from pathlib import Path -from distutils.version import LooseVersion -from setuptools import setup, Extension, find_packages +from setuptools import Extension, find_packages, setup from setuptools.command.build_ext import build_ext +from setuptools.command.build_py import build_py +from setuptools.command.sdist import sdist + +ROOT = Path(__file__).resolve().parent + + +def check_package_sources(): + """Fail before packaging if the generated API or builder is missing.""" + required = [ + "python/polyfempy/generated_api/__init__.py", + "python/polyfempy/generated_api/generated_api.py", + "python/polyfempy/generated_api/generated_class.py", + "python/polyfempy/generated_api/builder_api_manifest.json", + "python/polyfempy/generated_api/class_tree_manifest.json", + "python/polyfempy/generated_api/generated_api_manifest.json", + "python/polyfempy/_model_builder.py", + "python/polyfempy/_selection_refs.py", + ] + missing = [name for name in required if not (ROOT / name).is_file()] + if missing: + raise RuntimeError( + "Package sources are missing: " + ", ".join(missing) + ".\n" + "Initialize the submodules and run: python tools/generate_polyfem_api.py" + ) + + +class BuildPython(build_py): + """Ship the generated API and the small runtime used by its builder.""" + + def run(self): + check_package_sources() + super().run() -from distutils.sysconfig import get_python_inc + +class SourceDistribution(sdist): + """Require native sources as well as the generated Python package.""" + + def run(self): + check_package_sources() + if not (ROOT / "polyfem/CMakeLists.txt").is_file(): + raise RuntimeError( + "PolyFEM sources are missing. Run: git submodule update --init --recursive" + ) + super().run() class CMakeExtension(Extension): - def __init__(self, name, sourcedir=''): - Extension.__init__(self, name, sources=[]) + def __init__(self, name, sourcedir=""): + super().__init__(name, sources=[]) self.sourcedir = os.path.abspath(sourcedir) class CMakeBuild(build_ext): + def get_output_mapping(self): + """Keep shared runtimes beside the extension in strict editable installs.""" + mapping = super().get_output_mapping() + for output, source in list(mapping.items()): + for pattern in ("*.dll", "*.so", "*.so.*", "*.dylib"): + for library in Path(source).parent.glob(pattern): + if library.is_file(): + mapping[str(Path(output).parent / library.name)] = str(library) + return mapping + def run(self): try: - out = subprocess.check_output(['cmake', '--version']) - except OSError: + output = subprocess.check_output(["cmake", "--version"], text=True) + except OSError as exc: 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") - + "CMake 3.25 or later is required to build polyfempy." + ) from exc + match = re.search(r"version\s+(\d+)\.(\d+)\.(\d+)", output) + if match is None or tuple(map(int, match.groups())) < (3, 25, 0): + raise RuntimeError("CMake 3.25 or later is required to build polyfempy.") 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] - + extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name))) + try: + n_threads = int(os.environ.get("N_THREADS") or min(os.cpu_count() or 1, 2)) + except ValueError as exc: + raise RuntimeError("N_THREADS must be a positive integer.") from exc + if n_threads < 1: + raise RuntimeError("N_THREADS must be a positive integer.") + + python_executable = os.path.abspath(sys.executable) + cmake_args = [ + f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}", + f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY={extdir}", + f"-DPYTHON_EXECUTABLE={python_executable}", + f"-DPython_EXECUTABLE={python_executable}", + f"-DPython3_EXECUTABLE={python_executable}", + f"-DPython_EXTENSION_MODULE_SUFFIX={sysconfig.get_config_var('EXT_SUFFIX')}", + f"-DPYTHON_INCLUDE_DIR={sysconfig.get_path('include')}", + "-DPOLYSOLVE_WITH_SPECTRA=OFF", + "-DPOLYSOLVE_WITH_AMGCL=OFF", + "-DPOLYSOLVE_WITH_UMFPACK=OFF", + "-DPOLYSOLVE_WITH_MPI=OFF", + "-DPOLYSOLVE_WITH_HYPRE=OFF", + "-DPOLYFEM_WITH_MISO=OFF", + "-DPOLYFEM_PORTABLE_BUILD=ON", + "-DCMAKE_POLICY_VERSION_MINIMUM=3.5", + "-DUSE_NANOBIND=ON", + "-DCMAKE_BUILD_TYPE=Release", + ] + conda_prefix = os.environ.get("CONDA_PREFIX") + if conda_prefix: + prefixes = [conda_prefix, os.environ.get("CMAKE_PREFIX_PATH", "")] + cmake_args.append("-DCMAKE_PREFIX_PATH=" + ";".join(filter(None, prefixes))) + + build_env = os.environ.copy() + build_workers = n_threads + if platform.system() == "Darwin": + cmake_args.extend( + ["-DPOLYSOLVE_WITH_MKL=OFF", "-DPOLYSOLVE_WITH_ACCELERATE=ON"] + ) 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() + cmake_args.extend( + [ + f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE={extdir}", + f"-DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE={extdir}", + ] + ) + generator = os.environ.get("CMAKE_GENERATOR", "") + cache = Path(self.build_temp) / "CMakeCache.txt" + if not generator and cache.is_file(): + match = re.search( + r"^CMAKE_GENERATOR:INTERNAL=(.+)$", + cache.read_text(encoding="utf-8"), + re.MULTILINE, + ) + if match: + generator = match.group(1).strip() + if ( + not generator or generator.startswith("Visual Studio") + ) and sys.maxsize > 2**32: + cmake_args.extend(["-A", "x64"]) + if not generator or generator.startswith("Visual Studio"): + # Build one project at a time to keep cl workers within N_THREADS. + build_workers = 1 + build_env["_CL_"] = ( + build_env.get("_CL_", "") + f" /MP{n_threads}" + ).strip() + + build_command = [ + "cmake", + "--build", + ".", + "--config", + "Release", + "--target", + "polyfempy", + "--parallel", + str(build_workers), + "--verbose", + ] + Path(self.build_temp).mkdir(parents=True, exist_ok=True) + for stage, command in ( + ("configuration", ["cmake", ext.sourcedir, *cmake_args]), + ("build", build_command), + ): + try: + # Stream the original output so a failed build keeps its diagnostics. + subprocess.check_call(command, cwd=self.build_temp, env=build_env) + except subprocess.CalledProcessError as exc: + raise RuntimeError( + f"CMake {stage} failed with exit code {exc.returncode}. " + f"See the output above. Build directory: {self.build_temp}" + ) from exc 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' - ] + ext_modules=[CMakeExtension("polyfempy.polyfempy")], + cmdclass={ + "build_ext": CMakeBuild, + "build_py": BuildPython, + "sdist": SourceDistribution, + }, + options={"editable_wheel": {"mode": "strict"}}, + packages=find_packages(where="python", include=["polyfem", "polyfempy", "polyfempy.*"]), + package_dir={ + "": "python", }, - test_suite="test" ) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 00000000..e0c293dd --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,13 @@ +set(SOURCES + binding.cpp +) + +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "Source Files" FILES ${SOURCES}) +target_sources(polyfempy PRIVATE ${SOURCES}) + +################################################################################ +# Subfolders +################################################################################ + +add_subdirectory(mesh) +add_subdirectory(state) diff --git a/src/binding.cpp b/src/binding.cpp index 892143e5..59497dc5 100644 --- a/src/binding.cpp +++ b/src/binding.cpp @@ -1,1073 +1,18 @@ -#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 #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 -{ -}; +#include "binding_wrapper.hpp" -// TODO add save_time_sequence +#include "mesh/binding.hpp" +#include "state/binding.hpp" -namespace +PY_MODULE(polyfempy, m) { - 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) -{ - 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 (...) - { - { - } - } - 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(); + define_pde_types(m); - state.build_basis(); + define_solver(m); + define_solve(m); - state.assemble_rhs(); - state.assemble_stiffness_mat(); - state.solve_problem(); + define_mesh(m); - 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); + m.def("version", []() { return "polyfempy nanobind backend"; }, "Get version information"); } diff --git a/src/binding_wrapper.hpp b/src/binding_wrapper.hpp new file mode 100644 index 00000000..a3451738 --- /dev/null +++ b/src/binding_wrapper.hpp @@ -0,0 +1,32 @@ +// nanobind binding wrapper +// pybind11 support has been removed - only nanobind is used + +#pragma once + +// Hard fail guard: detect if pybind11 was included before this header +#ifdef PYBIND11_VERSION + #error "pybind11 headers included. pybind11 support has been removed - only nanobind is used." +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace py = nanobind; +namespace nb = nanobind; +#define PY_MODULE(name, m) NB_MODULE(name, m) + +// Compatibility macros for return_value_policy +// Note: Use 'inline constexpr' (not 'static inline constexpr') for namespace-scope variables in C++17 +namespace py_return_value_policy { + inline constexpr nanobind::rv_policy reference = nanobind::rv_policy::reference_internal; + inline constexpr nanobind::rv_policy copy = nanobind::rv_policy::copy; + inline constexpr nanobind::rv_policy move = nanobind::rv_policy::move; + inline constexpr nanobind::rv_policy reference_internal = nanobind::rv_policy::reference_internal; +} + diff --git a/src/mesh/CMakeLists.txt b/src/mesh/CMakeLists.txt new file mode 100644 index 00000000..0c8de906 --- /dev/null +++ b/src/mesh/CMakeLists.txt @@ -0,0 +1,6 @@ +set(SOURCES + mesh.cpp +) + +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "Source Files" FILES ${SOURCES}) +target_sources(polyfempy PRIVATE ${SOURCES}) diff --git a/src/mesh/binding.hpp b/src/mesh/binding.hpp new file mode 100644 index 00000000..2ef1a66d --- /dev/null +++ b/src/mesh/binding.hpp @@ -0,0 +1,5 @@ +#pragma once + +#include "binding_wrapper.hpp" + +void define_mesh(py::module_ &m); diff --git a/src/mesh/mesh.cpp b/src/mesh/mesh.cpp new file mode 100644 index 00000000..ab9acf73 --- /dev/null +++ b/src/mesh/mesh.cpp @@ -0,0 +1,107 @@ +#include +#include +#include +#include "binding.hpp" +using namespace polyfem; +using namespace polyfem::mesh; + +void define_mesh(py::module_ &m) +{ + py::class_(m, "Mesh", "Mesh") + + .def("dimension", &Mesh::dimension, "Dimension of the mesh (2 or 3)") + + .def("n_elements", &Mesh::n_elements, "Number of elements") + + .def("n_boundary_elements", &Mesh::n_boundary_elements, + "Number of boundary elements (faces in 3D, edges in 2D)") + + .def("n_vertices", &Mesh::n_vertices, "Number of vertices") + + .def("n_cell_vertices", &Mesh::n_cell_vertices, + "Number of vertices in one cell", py::arg("cell_id")) + + .def("element_vertex", &Mesh::element_vertex, + "Global vertex ID of a local vertex in an element", + py::arg("cell_id"), py::arg("local_vertex_id")) + + .def("boundary_element_vertex", &Mesh::boundary_element_vertex, + "Global vertex ID of a local vertex in a boundary element", + py::arg("boundary_cell_id"), py::arg("local_vertex_id")) + + .def("is_boundary_vertex", &Mesh::is_boundary_vertex, + "Check if a vertex is on boundary", py::arg("vertex_id")) + + .def( + "bounding_box", + [](const Mesh &mesh) { + RowVectorNd min, max; + mesh.bounding_box(min, max); + return py::make_tuple(min, max); + }, + "Get bounding box") + + .def("set_boundary_ids", &Mesh::set_boundary_ids, + "Set boundary IDs with an array", py::arg("ids")) + + .def("get_boundary_id", &Mesh::get_boundary_id, + "Get boundary ID of one boundary primitive", py::arg("primitive")) + + .def("get_body_ids", &Mesh::get_body_ids, "Get body IDs") + + .def("set_body_ids", &Mesh::set_body_ids, "Set body IDs with an array", + py::arg("ids")) + + .def("point", &Mesh::point, "Get vertex position", py::arg("vertex_id")) + + .def("set_point", &Mesh::set_point, "Set vertex position", + py::arg("vertex_id"), py::arg("position")) + + .def( + "vertices", + [](const Mesh &mesh) { + Eigen::MatrixXd points(mesh.n_vertices(), mesh.dimension()); + for (int i = 0; i < mesh.n_vertices(); i++) + points.row(i) = mesh.point(i); + return points; + }, + "Get all vertex positions") + + .def( + "set_vertices", + [](Mesh &mesh, const Eigen::VectorXi &ids, + const Eigen::MatrixXd &points) { + for (int i = 0; i < ids.size(); i++) + { + assert(ids(i) < mesh.n_vertices()); + mesh.set_point(ids(i), points.row(i)); + } + }, + "Set a subset of vertex positions given a list of vertex indices") + + .def( + "set_vertices", + [](Mesh &mesh, const Eigen::MatrixXd &points) { + for (int i = 0; i < mesh.n_vertices(); i++) + mesh.set_point(i, points.row(i)); + }, + "Set all vertex positions") + + .def( + "elements", + [](const Mesh &mesh) { + Eigen::MatrixXi elements(mesh.n_elements(), + mesh.n_cell_vertices(0)); + for (int e = 0; e < mesh.n_elements(); e++) + { + assert(mesh.n_cell_vertices(e) == elements.cols()); + for (int i = 0; i < elements.cols(); i++) + elements(e, i) = mesh.element_vertex(e, i); + } + return elements; + }, + "Get all elements of the mesh"); + + py::class_(m, "Mesh2D", ""); + py::class_(m, "Mesh3D", ""); +} 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/src/state/CMakeLists.txt b/src/state/CMakeLists.txt new file mode 100644 index 00000000..ef83f103 --- /dev/null +++ b/src/state/CMakeLists.txt @@ -0,0 +1,6 @@ +set(SOURCES + state.cpp +) + +source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "Source Files" FILES ${SOURCES}) +target_sources(polyfempy PRIVATE ${SOURCES}) diff --git a/src/state/array_mesh_resources.hpp b/src/state/array_mesh_resources.hpp new file mode 100644 index 00000000..43874354 --- /dev/null +++ b/src/state/array_mesh_resources.hpp @@ -0,0 +1,70 @@ +#pragma once + +#include +#include +#include + +// Expose one array mesh through the backend's existing resource interface. +class ArrayMeshResources final : public polyfem::io::ResourceIO +{ +public: + ArrayMeshResources(const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &cells) + : data_(std::make_shared(Data{vertices, cells})), + files_(std::make_unique(std::filesystem::current_path())) {} + + static std::string mesh_path() { return "/__polyfem_python_array_mesh__"; } + + std::unique_ptr with_root(const std::string &root) const override + { + return std::unique_ptr(new ArrayMeshResources(data_, files_->with_root(root))); + } + std::string canonical_path(const std::string &path) const override + { return owned(path) ? path : files_->canonical_path(path); } + bool exists(const std::string &path) const override + { + if (!owned(path)) return files_->exists(path); + return path == mesh_path() || path == mesh_path() + "/vertices" || path == mesh_path() + "/cells"; + } + bool is_group(const std::string &path) const override + { return owned(path) ? path == mesh_path() : files_->is_group(path); } + std::vector list(const std::string &path) const override + { return owned(path) ? std::vector{mesh_path() + "/vertices", mesh_path() + "/cells"} : files_->list(path); } + Eigen::MatrixXd read_matrix(const std::string &path) const override + { if (path == mesh_path() + "/vertices") return data_->vertices; return files_->read_matrix(path); } + Eigen::MatrixXi read_int_matrix(const std::string &path) const override + { if (path == mesh_path() + "/cells") return data_->cells; return files_->read_int_matrix(path); } + bool has_attribute(const std::string &path, const std::string &name) const override + { + if (!owned(path)) return files_->has_attribute(path, name); + return path == mesh_path() && (name == "schema_version" || name == "mesh_type" || name == "dimension"); + } + long read_integer_attribute(const std::string &path, const std::string &name) const override + { + if (!owned(path)) return files_->read_integer_attribute(path, name); + if (name == "schema_version") return polyfem::mesh::MESH_SCHEMA_VERSION; + if (name == "dimension") return data_->vertices.cols(); + throw std::runtime_error("Unknown array mesh attribute: " + name); + } + std::string read_string_attribute(const std::string &path, const std::string &name) const override + { + if (!owned(path)) return files_->read_string_attribute(path, name); + if (name == "mesh_type") return "fem"; + throw std::runtime_error("Unknown array mesh attribute: " + name); + } + const std::filesystem::path &host_directory() const override { return files_->host_directory(); } + std::unique_ptr open(const std::string &path, bool binary) const override { return files_->open(path, binary); } + std::vector read_double_vector(const std::string &path) const override { return files_->read_double_vector(path); } + std::vector read_int_vector(const std::string &path) const override { return files_->read_int_vector(path); } + std::vector read_long_vector(const std::string &path) const override { return files_->read_long_vector(path); } + std::array read_shape_attribute(const std::string &path, const std::string &name) const override { return files_->read_shape_attribute(path, name); } + std::filesystem::path materialize(const std::string &path) const override { return files_->materialize(path); } + std::string describe(const std::string &path) const override { return files_->describe(path); } +private: + struct Data { Eigen::MatrixXd vertices; Eigen::MatrixXi cells; }; + std::shared_ptr data_; + std::unique_ptr files_; + static bool owned(const std::string &path) + { return path == mesh_path() || path.rfind(mesh_path() + "/", 0) == 0; } + ArrayMeshResources(std::shared_ptr data, std::unique_ptr files) + : data_(std::move(data)), files_(std::move(files)) {} +}; diff --git a/src/state/binding.hpp b/src/state/binding.hpp new file mode 100644 index 00000000..876621f7 --- /dev/null +++ b/src/state/binding.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include "binding_wrapper.hpp" + +void define_pde_types(py::module_ &m); +void define_solver(py::module_ &m); +void define_solve(py::module_ &m); diff --git a/src/state/state.cpp b/src/state/state.cpp new file mode 100644 index 00000000..d1e0b23a --- /dev/null +++ b/src/state/state.cpp @@ -0,0 +1,314 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "binding_wrapper.hpp" +#include "array_mesh_resources.hpp" + +using namespace polyfem; + +namespace +{ + +class PDEs +{ +}; + +bool load_json(const std::string &json_file, json &out) +{ + std::ifstream file(json_file); + if (!file.is_open()) + return false; + + file >> out; + if (!out.contains("root_path")) + out["root_path"] = json_file; + return true; +} + +bool load_yaml(const std::string &yaml_file, json &out) +{ + try + { + const io::FileSystemIO resources(std::filesystem::current_path()); + out = io::yaml_string_to_json(resources.read_string(yaml_file)); + if (!out.contains("root_path")) + out["root_path"] = yaml_file; + } + catch (...) + { + return false; + } + return true; +} + +void init_globals(State &state) +{ + static bool initialized = false; + if (initialized) + return; + + state.set_max_threads(1); + state.init_logger( + "", + spdlog::level::level_enum::info, + spdlog::level::level_enum::debug, + false); + initialized = true; +} + +json settings_from_python(const py::object &settings) +{ + const std::string json_string = nb::cast(py::str(settings)); + return json::parse(json_string); +} + +class PythonSolver +{ +public: + PythonSolver() = default; + + void set_settings(const py::object &settings, bool strict_validation) + { + init_globals(state_); + state_.init(settings_from_python(settings), strict_validation); + } + + void set_settings_with_mesh(const py::object &settings, + const Eigen::MatrixXd &vertices, + const Eigen::MatrixXi &cells) + { + init_globals(state_); + json args = settings_from_python(settings); + json &geometry = args["geometry"]; + if (geometry.is_object()) geometry = json::array({geometry}); + json *body = nullptr; + for (auto &entry : geometry) + { + if (!entry.value("enabled", true) || entry.value("is_obstacle", false)) continue; + if (body != nullptr || entry.value("type", std::string("mesh")) != "mesh") + throw std::invalid_argument("Array input requires one enabled deformable mesh."); + body = &entry; + } + if (body == nullptr) throw std::invalid_argument("Array input requires one enabled deformable mesh."); + (*body)["mesh"] = ArrayMeshResources::mesh_path(); + const ArrayMeshResources resources(vertices, cells); + state_.init(args, resources, true); + state_.load_mesh(); + } + + std::string settings() const + { + return state_.args.dump(2); + } + + void set_max_threads(const int nthreads) + { + state_.set_max_threads(nthreads); + } + + void set_log_level(int log_level) + { + init_globals(state_); + log_level = std::max(0, std::min(6, log_level)); + state_.set_log_level(static_cast(log_level)); + } + + void load_mesh_from_settings() + { + init_globals(state_); + state_.load_mesh(); + } + + void set_mesh( + const Eigen::MatrixXd &vertices, + const Eigen::MatrixXi &cells, + const bool non_conforming) + { + init_globals(state_); + state_.set_mesh(vertices, cells, non_conforming); + } + + py::dict solve(int log_level) + { + set_log_level(log_level); + + Eigen::MatrixXd sol; + { + // Worker threads must be able to call Python expressions. + py::gil_scoped_release release; + state_.solve(sol); + + if (state_.variational_formulation) + { + state_.variational_formulation->compute_errors(sol); + state_.variational_formulation->save_json(sol); + state_.variational_formulation->export_data(sol); + } + } + + py::dict meta; + meta["from_bundle"] = true; + meta["solution"] = "raw_backend_solution"; + + py::dict bundle; + bundle["_result_bundle"] = true; + bundle["sol"] = sol; + bundle["meta"] = meta; + return bundle; + } + +private: + State state_; +}; + +void run_polyfem_command( + const std::string &json_file, + const std::string &yaml_file, + const int log_level, + const bool strict_validation, + const int max_threads, + const std::string &output_dir) +{ + json in_args = json::object(); + const bool ok = !json_file.empty() + ? load_json(json_file, in_args) + : load_yaml(yaml_file, in_args); + + if (!ok) + { + const std::string target = !json_file.empty() ? json_file : yaml_file; + throw std::runtime_error("unable to open " + target + " file"); + } + + json patch = json::object(); + patch["/output/log/level"_json_pointer] = log_level; + patch["/solver/max_threads"_json_pointer] = max_threads; + if (!output_dir.empty()) + patch["/output/directory"_json_pointer] = std::filesystem::absolute(output_dir); + in_args.merge_patch(patch); + + State state; + init_globals(state); + state.init(in_args, strict_validation); + state.load_mesh(); + state.set_log_level(static_cast( + std::max(0, std::min(6, log_level)))); + + Eigen::MatrixXd sol; + { + py::gil_scoped_release release; + state.solve(sol); + + if (state.variational_formulation) + { + state.variational_formulation->compute_errors(sol); + state.variational_formulation->save_json(sol); + state.variational_formulation->export_data(sol); + } + } +} + +} // namespace + +void define_pde_types(py::module_ &m) +{ + const auto &pdes = py::class_(m, "PDEs"); + + const std::vector materials = { + "LinearElasticity", + "HookeLinearElasticity", + "SaintVenant", + "NeoHookean", + "MooneyRivlin", + "MooneyRivlin3Param", + "MooneyRivlin3ParamSymbolic", + "UnconstrainedOgden", + "IncompressibleOgden", + "Stokes", + "NavierStokes", + "OperatorSplitting", + "IncompressibleLinearElasticity", + "Laplacian", + "Helmholtz", + "Bilaplacian", + "AMIPS", + "FixedCorotational"}; + + for (const auto &material : materials) + pdes.attr(material.c_str()) = material; + + pdes.doc() = "List of supported partial differential equations"; + + m.def( + "is_tensor", + [](const std::string &pde) { + return !(pde == "Laplacian" || pde == "Helmholtz" || pde == "Bilaplacian"); + }, + "returns true if the pde is tensorial", + py::arg("pde")); +} + +void define_solver(py::module_ &m) +{ + py::class_(m, "Solver") + .def(py::init<>()) + .def("set_settings_with_mesh", &PythonSolver::set_settings_with_mesh, + "load settings and an array mesh through the geometry loader", + py::arg("json"), py::arg("vertices"), py::arg("connectivity")) + .def("settings", &PythonSolver::settings, "get solver settings as JSON text") + .def( + "set_settings", + &PythonSolver::set_settings, + "load solver settings from JSON text", + py::arg("json"), + py::arg("strict_validation") = false) + .def( + "set_max_threads", + &PythonSolver::set_max_threads, + "set maximum number of threads", + py::arg("nthreads")) + .def( + "set_log_level", + &PythonSolver::set_log_level, + "set PolyFEM log level, from 0 (all logs) to 6 (no logs)", + py::arg("log_level")) + .def( + "load_mesh_from_settings", + &PythonSolver::load_mesh_from_settings, + "load the mesh described by the current JSON settings") + .def( + "set_mesh", + &PythonSolver::set_mesh, + "load a mesh from vertices and connectivity", + py::arg("vertices"), + py::arg("connectivity"), + py::arg("non_conforming") = false) + .def( + "solve", + &PythonSolver::solve, + "solve using the VarForm backend and return the raw solution bundle", + py::arg("log_level") = 3); +} + +void define_solve(py::module_ &m) +{ + m.def( + "polyfem_command", + &run_polyfem_command, + "runs the PolyFEM command entry point", + py::kw_only(), + py::arg("json"), + py::arg("yaml") = std::string(""), + py::arg("log_level") = int(1), + py::arg("strict_validation") = bool(true), + py::arg("max_threads") = int(1), + py::arg("output_dir") = ""); +} 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..5a629225 --- /dev/null +++ b/tests/test_api_errors.py @@ -0,0 +1,72 @@ +"""Invalid user inputs should produce useful errors without a native solve.""" + +import json + +import numpy as np +import pytest + +from polyfempy import solve +from polyfempy.runtime import _solve_backend as backend +from polyfempy.runtime._solve_contract import choose_mesh_source + + +VERTICES = [[0, 0], [1, 0], [0, 1]] + + +@pytest.mark.parametrize("vertices,cells,message", [ + (VERTICES, [[0, 1, 1.9]], "fractional"), + (VERTICES, [[0, 1, 3]], "zero-based"), + (VERTICES, [[0, 1, -1]], "zero-based"), + (VERTICES, [[0, 1, 2**40]], "zero-based"), + ([[0, 0], [float("nan"), 0]], [[0, 1, 1]], "finite real"), + ([[0, 0], [float("inf"), 0]], [[0, 1, 1]], "finite real"), + ([0, 1, 2], [[0, 1, 2]], "shape"), + ([], [[0, 1, 2]], "shape"), + (VERTICES, [0, 1, 2], "2D"), + (VERTICES, [], "non-empty"), +]) +def test_bad_arrays_fail_before_backend_creation(monkeypatch, vertices, cells, message): + def unexpected_backend(): + pytest.fail("Invalid mesh reached the native backend") + monkeypatch.setattr(backend, "build_solver", unexpected_backend) + with pytest.raises(ValueError, match=message): + solve(vertices=vertices, cells=cells, cfg={}) + + +def test_integer_valued_connectivity_is_preserved(): + source = choose_mesh_source(VERTICES, [[0.0, 1.0, 2.0]], None) + np.testing.assert_array_equal(source.cells, [[0, 1, 2]]) + assert source.cells is not None + assert source.cells.dtype == np.int32 + + +def test_config_path_errors_name_the_file(tmp_path): + missing = tmp_path / "missing.json" + with pytest.raises(FileNotFoundError, match="Configuration file not found") 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) + assert str(bad) in str(error.value) + + +def test_rejected_elastic_material_has_parameter_hint(): + class RejectingSolver: + def set_settings(self, *args, **kwargs): + raise RuntimeError("Invalid input json file") + payload = {"materials": [{"type": "NeoHookean", "E": 1000}]} + with pytest.raises(RuntimeError, match=r"materials\[0\].*both E and nu"): + backend._apply_settings_json(RejectingSolver(), json.dumps(payload)) + payload["materials"][0].update({"lambda": 1, "mu": 2}) + with pytest.raises(RuntimeError, match="^Invalid input json file$"): + backend._apply_settings_json(RejectingSolver(), json.dumps(payload)) + + +def test_successful_backend_settings_are_not_revalidated(): + class AcceptingSolver: + def set_settings(self, value, strict_validation): + assert strict_validation is True + assert json.loads(value) == {"materials": {"type": "CustomMaterial"}} + backend._apply_settings_json(AcceptingSolver(), '{"materials": {"type": "CustomMaterial"}}') diff --git a/tests/test_array_mesh_selections.py b/tests/test_array_mesh_selections.py new file mode 100644 index 00000000..f12b5f56 --- /dev/null +++ b/tests/test_array_mesh_selections.py @@ -0,0 +1,190 @@ +"""Keep model selections attached when solve receives an array mesh.""" + +import copy +import json + +import numpy as np +import pytest + +import polyfem +from polyfempy import solve +from polyfempy.runtime import _solve_backend as backend + + +VERTICES = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]], dtype=float) +CELLS = np.array([[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]]) + + +class RecordingSolver: + def __init__(self): + self.calls = [] + + def set_settings(self, settings, strict_validation): + assert strict_validation is True + self.settings = json.loads(settings) + self.calls.append("settings") + + def set_mesh(self, vertices, cells): + self.calls.append("raw arrays") + + def set_settings_with_mesh(self, settings, vertices, cells): + self.set_settings(settings, strict_validation=True) + self.calls.append("configured arrays") + np.testing.assert_array_equal(vertices, VERTICES) + np.testing.assert_array_equal(cells, CELLS) + assert cells.dtype == np.int32 + + def load_mesh_from_settings(self): + self.calls.append("file") + + def solve(self, log_level): + self.calls.append("solve") + return {"_result_bundle": True, "sol": np.zeros((10, 1))} + + +@pytest.mark.parametrize("config_kind", ["model", "dict", "file"]) +@pytest.mark.parametrize("whole_boundary", [False, True]) +def test_solve_preserves_automatic_material_and_boundary_links( + monkeypatch, tmp_path, config_kind, whole_boundary, +): + model = polyfem.model() + body = model.mesh(mesh="array.msh") + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + if whole_boundary: + body.dirichlet(value=[0, 0]) + else: + body.surface_axis(axis="-x", position=0, relative=True).dirichlet(value=[0, 0]) + body.surface_axis(axis="x", position=1, relative=True).neumann(value=[1, 0]) + body.rhs(value=[0, -1]) + config = model.config() + original = config.as_dict() + if config_kind == "dict": + config = copy.deepcopy(original) + elif config_kind == "file": + config = tmp_path / "simulation.json" + config.write_text(json.dumps(original), encoding="utf-8") + solver = RecordingSolver() + monkeypatch.setattr(backend, "build_solver", lambda: solver) + + solve(VERTICES, CELLS, cfg=config) + + assert solver.calls == ["settings", "configured arrays", "solve"] + geometry = solver.settings["geometry"][0] + assert geometry == original["geometry"][0] + assert solver.settings["materials"][0]["id"] == geometry["volume_selection"] + conditions = solver.settings["boundary_conditions"] + assert conditions["rhs"] == [0, -1] + selection = geometry["surface_selection"] + if whole_boundary: + assert conditions["dirichlet_boundary"][0]["id"] == selection + else: + assert conditions["dirichlet_boundary"][0]["id"] == selection[0]["id"] + assert conditions["neumann_boundary"][0]["id"] == selection[1]["id"] + assert selection[0]["id"] != selection[1]["id"] + assert model.config().as_dict() == original + if config_kind == "dict": + assert config == original + + +def test_array_mesh_keeps_obstacles_and_skips_disabled_bodies(monkeypatch): + config = { + "geometry": [ + {"mesh": "unused.obj", "enabled": False}, + {"mesh": "array.msh", "surface_selection": 4}, + {"type": "ground", "height": -1, "is_obstacle": True}, + ], + "materials": {"type": "NeoHookean", "E": 1000, "nu": 0.3}, + } + original = copy.deepcopy(config) + solver = RecordingSolver() + monkeypatch.setattr(backend, "build_solver", lambda: solver) + + solve(VERTICES, CELLS, cfg=config) + + assert solver.calls == ["settings", "configured arrays", "solve"] + assert solver.settings["geometry"] == original["geometry"] + assert config == original + + +@pytest.mark.parametrize("geometry,message", [ + ([{"mesh": "first.obj"}, {"mesh": "second.obj"}], "exactly one"), + ([{"mesh": "unused.obj", "enabled": False}], "exactly one"), + ([{"type": "ground", "height": 0, "is_obstacle": True}], "exactly one"), + ([{"type": "mesh_array", "mesh": "part.obj", "array": {}}], "type 'mesh'"), +]) +def test_ambiguous_array_geometry_fails_before_loading_settings(monkeypatch, geometry, message): + solver = RecordingSolver() + monkeypatch.setattr(backend, "build_solver", lambda: solver) + + with pytest.raises(ValueError, match=message): + solve(VERTICES, CELLS, cfg={"geometry": geometry}) + + assert solver.calls == [] + + +def test_old_backend_reports_missing_array_selection_support(monkeypatch): + class OldSolver: + def set_settings(self, *args, **kwargs): + pytest.fail("An incompatible backend must fail before settings are applied") + + monkeypatch.setattr(backend, "build_solver", OldSolver) + with pytest.raises(RuntimeError, match="cannot apply geometry selections.*array meshes"): + solve(VERTICES, CELLS, cfg={"geometry": {"mesh": "array.msh"}}) + + +def test_arrays_without_geometry_keep_the_existing_backend_path(monkeypatch): + class OldSolver(RecordingSolver): + def __getattribute__(self, name): + if name == "set_settings_with_mesh": + raise AttributeError(name) + return super().__getattribute__(name) + + solver = OldSolver() + monkeypatch.setattr(backend, "build_solver", lambda: solver) + solve(VERTICES, CELLS, cfg={"materials": {"type": "NeoHookean", "E": 1000, "nu": 0.3}}) + assert solver.calls == ["settings", "raw arrays", "solve"] + + +def test_file_mesh_still_uses_the_file_loader(monkeypatch): + solver = RecordingSolver() + monkeypatch.setattr(backend, "build_solver", lambda: solver) + solve(cfg={"geometry": {"mesh": "part.msh"}}) + assert solver.calls == ["settings", "file", "solve"] + + +@pytest.mark.parametrize("whole_boundary", [False, True]) +def test_native_array_selections_match_a_file_solve(tmp_path, monkeypatch, whole_boundary): + import polyfempy + + if not polyfempy.cpp_backend_available(): + pytest.skip("C++ backend is unavailable; array selection integration requires a native build") + + monkeypatch.chdir(tmp_path) + mesh = tmp_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\n" + "f 1 2 5\nf 2 3 5\nf 3 4 5\nf 4 1 5\n", + encoding="utf-8", + ) + model = polyfem.model() + body = model.mesh(mesh=str(mesh)) + body.material(polyfem.neo_hookean(E=1000, nu=0.3)) + if whole_boundary: + body.dirichlet(value=[0, 0]) + else: + body.surface_axis(axis="-x", position=0, relative=True).dirichlet(value=[0, 0]) + model.solver(linear=polyfem.linear(solver="Eigen::SimplicialLDLT")) + body.rhs(value=[0, -1]) + config = model.config() + + file_result = solve(cfg=config) + # The array path must not open the configured FEM file. + mesh.unlink() + array_result = solve(VERTICES, CELLS, cfg=config) + + assert np.isfinite(array_result.sol).all() + assert abs(array_result.sol).max() > 1e-6 + # File decoding can change the numbering of the same finite-element nodes. + np.testing.assert_allclose( + np.sort(array_result.sol.ravel()), np.sort(file_result.sol.ravel()), rtol=1e-6, atol=1e-9, + ) diff --git a/tests/test_backend_smoke.py b/tests/test_backend_smoke.py new file mode 100644 index 00000000..ae9e8a0d --- /dev/null +++ b/tests/test_backend_smoke.py @@ -0,0 +1,171 @@ +from pathlib import Path +import json +import subprocess +import sys + +import numpy as np +import pytest + + +_BACKEND_RUNNER = """ +import hashlib +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}") +if not pf.cpp_backend_available(): + raise RuntimeError(f"Native backend is unavailable: {pf.cpp_backend_error()}") +native_path = Path(pf._core.__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: + from polyfempy.cli import main + raise SystemExit(main(sys.argv[3:])) +""" + + +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)) + } + + +@pytest.mark.parametrize(("inherit_geometry", "relative_root"), [(False, None), (True, None), (True, "inputs")]) +def test_solve_json_inherits_common_settings(tmp_path, monkeypatch, inherit_geometry, relative_root): + import polyfempy + + if not polyfempy.cpp_backend_available(): + pytest.skip("Common-file integration requires the native backend") + monkeypatch.chdir(tmp_path) + beam = Path(__file__).resolve().parents[1] / "examples/quickstart/beam.obj" + geometry = [{"mesh": str(beam), "surface_selection": [{"id": 1, "axis": "-x", "position": 0.0}]}] + shared = { + "geometry": geometry, + "boundary_conditions": {"rhs": [0, -1000]}, + } + local = { + "materials": {"type": "LinearElasticity", "E": 1e7, "nu": 0.3}, + "boundary_conditions": {"dirichlet_boundary": [{"id": 1, "value": [0, 0]}]}, + "solver": {"linear": {"solver": "Eigen::SimplicialLDLT"}}, + } + expected = polyfempy.solve(cfg={ + **local, "geometry": geometry, + "boundary_conditions": {**local["boundary_conditions"], **shared["boundary_conditions"]}, + }).sol + assert np.max(np.abs(expected)) > 1e-6 + + case_dir = tmp_path / "case" + resources = case_dir / (relative_root or ".") + resources.mkdir(parents=True) + (resources / "common.json").write_text(json.dumps(shared), encoding="utf-8") + if relative_root: + local["root_path"] = relative_root + if not inherit_geometry: + local["geometry"] = geometry + case = case_dir / "case.json" + case.write_text(json.dumps({"common": "common.json", **local}), encoding="utf-8") + np.testing.assert_allclose(polyfempy.solve(cfg=case).sol, expected, rtol=1e-8, atol=1e-12) + + +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..b10e5e33 --- /dev/null +++ b/tests/test_backend_smoke_selection.py @@ -0,0 +1,127 @@ +"""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( + "from types import SimpleNamespace\n" + f"_core = SimpleNamespace(__file__={str(native)!r})\n" + f"def cpp_backend_available(): return {available!r}\n" + "def cpp_backend_error(): return 'test backend unavailable'\n", + encoding="utf-8", + ) + (package / "cli.py").write_text( + "def main(args):\n" + f" print({marker!r})\n" + " return 0\n", + 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() + + solve = smoke._run_backend(selected, ["solve"], cwd=old_cwd, expected_backend=info) + assert solve.returncode == 0, solve.stderr + assert "selected" in solve.stdout + assert "OLD_ENV_USED" not in solve.stdout + assert "OLD_CWD_USED" not in solve.stdout + + +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_cli.py b/tests/test_cli.py new file mode 100644 index 00000000..129fd3c3 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import subprocess +import sys +import types +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_backend_info_reports_backend_status(capsys): + from polyfempy.cli import main + + exit_code = main(["backend-info"]) + + captured = capsys.readouterr() + assert exit_code == 0 + assert "backend_available=" in captured.out + + +def test_backend_info_can_require_backend(monkeypatch, capsys): + from polyfempy import cli + + fake_polyfempy = types.SimpleNamespace( + cpp_backend_available=lambda: False, + cpp_backend_error=lambda: RuntimeError("not built"), + ) + monkeypatch.setattr(cli, "_load_polyfempy", lambda: fake_polyfempy) + + exit_code = cli.main(["backend-info", "--require"]) + + captured = capsys.readouterr() + assert exit_code == 1 + assert "C++ backend not loaded" in captured.err + + +def test_solve_reports_missing_backend_cleanly(monkeypatch, capsys, tmp_path): + from polyfempy import cli + + fake_polyfempy = types.SimpleNamespace( + cpp_backend_available=lambda: False, + cpp_backend_error=lambda: RuntimeError("not built"), + ) + monkeypatch.setattr(cli, "_load_polyfempy", lambda: fake_polyfempy) + config = tmp_path / "input.json" + config.write_text("{}", encoding="utf-8") + + exit_code = cli.main(["solve", str(config)]) + + captured = capsys.readouterr() + assert exit_code == 1 + assert "C++ backend not loaded" in captured.err + + +def test_solve_dispatches_json_config_to_backend(monkeypatch, tmp_path): + from polyfempy import cli + + calls = [] + + def polyfem_command(**kwargs): + calls.append(kwargs) + + fake_polyfempy = types.SimpleNamespace( + cpp_backend_available=lambda: True, + cpp_backend_error=lambda: None, + polyfem_command=polyfem_command, + ) + monkeypatch.setattr(cli, "_load_polyfempy", lambda: fake_polyfempy) + + config = tmp_path / "input.json" + config.write_text("{}", encoding="utf-8") + output_dir = tmp_path / "out" + + exit_code = cli.main( + [ + "solve", + str(config), + "--output-dir", + str(output_dir), + "--log-level", + "4", + "--max-threads", + "2", + "--no-strict-validation", + ] + ) + + assert exit_code == 0 + assert calls == [ + { + "json": str(config), + "yaml": "", + "log_level": 4, + "strict_validation": False, + "max_threads": 2, + "output_dir": str(output_dir), + } + ] + + +def test_solve_dispatches_yaml_config_to_backend(monkeypatch, tmp_path): + from polyfempy import cli + + calls = [] + + def polyfem_command(**kwargs): + calls.append(kwargs) + + fake_polyfempy = types.SimpleNamespace( + cpp_backend_available=lambda: True, + cpp_backend_error=lambda: None, + polyfem_command=polyfem_command, + ) + monkeypatch.setattr(cli, "_load_polyfempy", lambda: fake_polyfempy) + + config = tmp_path / "input.yaml" + config.write_text("problem: test\n", encoding="utf-8") + + exit_code = cli.main(["solve", str(config)]) + + assert exit_code == 0 + assert calls == [ + { + "json": "", + "yaml": str(config), + "log_level": 2, + "strict_validation": True, + "max_threads": 1, + "output_dir": "", + } + ] + + +def test_python_module_help_works_without_backend(monkeypatch): + monkeypatch.setenv("PYTHONPATH", str(ROOT / "python")) + result = subprocess.run( + [sys.executable, "-m", "polyfempy", "--help"], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + + assert result.returncode == 0 + assert "backend-info" in result.stdout + assert "solve" in result.stdout + + +def test_pyproject_declares_console_script(): + pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + + assert "[project.scripts]" in pyproject + assert 'polyfempy = "polyfempy.cli:main"' in pyproject + assert "cmake>=3.25" in pyproject + + +def test_setup_py_always_passes_conda_prefix_to_cmake(): + setup_py = (ROOT / "setup.py").read_text(encoding="utf-8") + + conda_prefix_line = next( + line for line in setup_py.splitlines() if "CONDA_PREFIX" in line + ) + assert conda_prefix_line.startswith(" conda_prefix = ") + + +def test_setup_py_disables_heavy_optional_polysolve_dependencies(): + setup_py = (ROOT / "setup.py").read_text(encoding="utf-8") + + assert "-DPOLYSOLVE_WITH_SPECTRA=OFF" in setup_py + assert "-DPOLYSOLVE_WITH_AMGCL=OFF" in setup_py + assert "-DPOLYSOLVE_WITH_UMFPACK=OFF" in setup_py + assert "-DPOLYSOLVE_WITH_MPI=OFF" in setup_py + assert "-DPOLYSOLVE_WITH_HYPRE=OFF" in setup_py + + +def test_github_actions_generates_ignored_api_before_tests(): + workflow = (ROOT / ".github" / "workflows" / "test.yml").read_text( + encoding="utf-8" + ) + + assert "matrix:" in workflow + assert '"3.10"' in workflow + assert '"3.11"' in workflow + assert '"3.12"' in workflow + assert "submodules: recursive" in workflow + assert "python tools/generate_polyfem_api.py" in workflow + assert "python -m pytest tests -q" in workflow + + +def test_github_actions_include_python_backend_and_release_workflows(): + workflow_dir = ROOT / ".github" / "workflows" + workflow_names = {path.name for path in workflow_dir.glob("*.yml")} + + assert { + "generated-contact-backend.yml", + "release-packages.yml", + "test.yml", + } <= workflow_names + + +def test_backend_workflow_checks_main_and_ready_main_pull_requests(): + workflow = ( + ROOT / ".github" / "workflows" / "generated-contact-backend.yml" + ).read_text(encoding="utf-8") + + assert "push:" in workflow + assert "branches:" in workflow + assert "- main" in workflow + assert "- jingyao" not in workflow + assert "pull_request:\n branches: [main]" in workflow + assert "types: [opened, synchronize, reopened, ready_for_review, edited]" in workflow + assert "workflow_dispatch:" in workflow + assert "GENERATED_SOURCE_TOLERANCE" in workflow + assert "github.event.inputs.generated_source_tolerance || '1e-5'" in workflow + assert "MAX_THREADS" in workflow + assert "github.event.inputs.max_threads || '1'" in workflow + assert "submodules: recursive" in workflow + assert "python tools/generate_polyfem_api.py" in workflow + assert "python -m build --no-isolation" in workflow + assert "python -m pip install --force-reinstall --no-deps dist/*.whl" in workflow + assert "python -I -m polyfempy backend-info --require" in workflow + smoke, sweep = workflow.split("- name: Run active generated contact backend sweep") + assert "tools/check_installed_package.py" in smoke + assert "--readme README.md --reference polyfem-data/units/neohookean.json" in smoke + assert "github.event.pull_request.draft == false" in workflow + assert "github.event.action != 'edited' || github.event.changes.base != null" in workflow + assert "if: always()" in sweep + assert "tools/run_generated_contact_backend_checks.py" in sweep + assert "--require-tests-match" in workflow + assert "tools/generated_contact_expected_failures.json" in workflow + assert "actions/upload-artifact@v7" in workflow + + +def test_github_actions_use_node24_compatible_action_versions(): + workflow_dir = ROOT / ".github" / "workflows" + workflows = { + path.name: path.read_text(encoding="utf-8") + for path in workflow_dir.glob("*.yml") + } + + assert workflows + for workflow in workflows.values(): + assert "actions/checkout@v4" not in workflow + assert "actions/setup-python@v5" not in workflow + assert "actions/checkout@v7" in workflow + assert "actions/setup-python@v7" in workflow diff --git a/tests/test_cmake_build_adapters.py b/tests/test_cmake_build_adapters.py new file mode 100644 index 00000000..bbbf1b33 --- /dev/null +++ b/tests/test_cmake_build_adapters.py @@ -0,0 +1,116 @@ +"""Configure the parent adapters without native dependencies or compilation.""" + +from pathlib import Path +import shutil +import subprocess + +import pytest + + +ROOT = Path(__file__).resolve().parents[1] + + +def write(root, name, content): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +@pytest.mark.parametrize("python_enabled", ["ON", "OFF"]) +def test_parent_adapters_configure_without_backend_patches(tmp_path, python_enabled): + cmake = shutil.which("cmake") + if cmake is None: + pytest.skip("CMake is required for adapter configuration tests") + + # Spaces exercise patch paths without relying on shell quoting. + source = tmp_path / "parent with spaces" + for name in ("polyfem.cmake", "libigl.cmake"): + write(source, f"cmake/recipes/{name}", + (ROOT / "cmake/recipes" / name).read_text(encoding="utf-8")) + write(source, "CMakeLists.txt", """ +cmake_minimum_required(VERSION 3.25) +project(AdapterTest NONE) +# These rules are only needed by generators that require a language rule. +# No build command is run. +set(CMAKE_CXX_COMPILE_OBJECT "unused") +set(CMAKE_CXX_CREATE_STATIC_LIBRARY "unused") +set(CMAKE_CXX_ARCHIVE_CREATE "unused") +set(CMAKE_CXX_ARCHIVE_FINISH "unused") +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/recipes") +include(polyfem) +get_target_property(links polyfem INTERFACE_LINK_LIBRARIES) +get_target_property(definitions polyfem COMPILE_DEFINITIONS) +file(WRITE "${CMAKE_BINARY_DIR}/result.txt" + "option=${POLYFEM_WITH_PYTHON}\nlinks=${links}\ndefinitions=${definitions}\n") +""") + write(source, "polyfem/CMakeLists.txt", """ +option(POLYFEM_WITH_PYTHON "Upstream interpreter support" ON) +if(POLYFEM_WITH_PYTHON) + message(FATAL_ERROR "The backend must not configure interpreter embedding") +endif() +list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/recipes") +include(libigl) +include(libigl) +add_library(polyfem STATIC dummy.cpp) +set_target_properties(polyfem PROPERTIES LINKER_LANGUAGE CXX) +add_library(polyfem::polyfem ALIAS polyfem) +""") + write(source, "polyfem/dummy.cpp", "") + write(source, "polyfem/cmake/recipes/libigl.cmake", + 'message(FATAL_ERROR "The parent libigl recipe was not selected")') + write(source, "polyfem/cmake/patches/igl_first.patch", "test patch") + write(source, "polyfem/cmake/patches/igl_second.patch", "test patch") + write(source, "cmake/recipes/FindPython3.cmake", """ +if(NOT Python3_FIND_COMPONENTS STREQUAL "Interpreter;Development.Module") + message(FATAL_ERROR "Only interpreter and extension development are needed") +endif() +set(Python3_EXECUTABLE "test python/python.exe") +add_library(Python3::Module INTERFACE IMPORTED) +""") + write(source, "polyfem/cmake/recipes/pybind11.cmake", """ +if(NOT TARGET Python3::Module) + message(FATAL_ERROR "Python extension support was not configured") +endif() +add_library(pybind11::module INTERFACE IMPORTED) +set_property(TARGET pybind11::module PROPERTY + INTERFACE_LINK_LIBRARIES Python3::Module) +""") + write(source, "cmake/recipes/CPM.cmake", """ +function(CPMAddPackage) + cmake_parse_arguments(PACKAGE "" "NAME;GITHUB_REPOSITORY;GIT_TAG" "PATCH_COMMAND" ${ARGN}) + file(APPEND "${CMAKE_BINARY_DIR}/dependency.txt" + "${PACKAGE_NAME}|${PACKAGE_GITHUB_REPOSITORY}|${PACKAGE_GIT_TAG}\n") + foreach(arg IN LISTS PACKAGE_PATCH_COMMAND) + file(APPEND "${CMAKE_BINARY_DIR}/patch-args.txt" "${arg}\n") + endforeach() + add_library(igl::core INTERFACE IMPORTED GLOBAL) +endfunction() +""") + build = tmp_path / "build" + result = subprocess.run( + [cmake, "-S", str(source), "-B", str(build), + f"-DPOLYFEM_WITH_PYTHON={python_enabled}"], + capture_output=True, text=True, timeout=45, + ) + assert result.returncode == 0, result.stdout + result.stderr + config = (build / "result.txt").read_text() + assert f"option={python_enabled}" in config + assert "pybind11::embed" not in config + assert "Python3::Python" not in config + if python_enabled == "ON": + assert "pybind11::module" in config + assert "POLYFEM_WITH_PYTHON" in config + assert 'POLYFEM_PYTHON_EXECUTABLE="test python/python.exe"' in config + else: + assert "pybind11::module" not in config + assert "POLYFEM_WITH_PYTHON" not in config + assert (build / "dependency.txt").read_text().splitlines() == [ + "libigl|libigl/libigl|aeeea9b416a5b5474cb9d12c07ff1238a4c83ba1" + ] + patch_args = (build / "patch-args.txt").read_text().splitlines() + assert Path(patch_args[0]).name.lower() in ("git", "git.exe") + assert patch_args[1:4] == ["apply", "--ignore-whitespace", "--whitespace=nowarn"] + assert patch_args[4:] == [ + (source / f"polyfem/cmake/patches/igl_{name}.patch").as_posix() + for name in ("first", "second") + ] diff --git a/tests/test_cmake_submodule_policy.py b/tests/test_cmake_submodule_policy.py new file mode 100644 index 00000000..d7a002f0 --- /dev/null +++ b/tests/test_cmake_submodule_policy.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from pathlib import Path +import re + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_cmake_defaults_to_polyfem_data_submodule(): + cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + + assert '${CMAKE_CURRENT_SOURCE_DIR}/polyfem-data' in cmake + assert '${CMAKE_CURRENT_SOURCE_DIR}/data/' not in cmake + assert "file(MAKE_DIRECTORY ${POLYFEMPY_DATA_ROOT})" not in cmake + + +def test_polyfem_data_recipe_does_not_fetch_data_repo(): + recipe = (ROOT / "cmake" / "recipes" / "polyfem_data.cmake").read_text( + encoding="utf-8" + ) + + assert "FetchContent" not in recipe + assert "GIT_REPOSITORY https://github.com/polyfem/polyfem-data" not in recipe + assert "git submodule update --init --recursive" in recipe + assert "FATAL_ERROR" in recipe + + +def test_polyfem_recipe_uses_polyfem_submodule_instead_of_fetching_repo(): + recipe = (ROOT / "cmake" / "recipes" / "polyfem.cmake").read_text( + encoding="utf-8" + ) + + assert "CPMAddPackage" not in recipe + assert "FetchContent" not in recipe + assert "GIT_REPOSITORY https://github.com/polyfem/polyfem" not in recipe + assert "/polyfem" in recipe + assert "add_subdirectory" in recipe + assert "git submodule update --init --recursive" in recipe + assert "FATAL_ERROR" in recipe + + +def test_root_cpm_version_matches_polyfem_submodule_cpm_version(): + root_cpm = (ROOT / "cmake" / "recipes" / "CPM.cmake").read_text( + encoding="utf-8" + ) + polyfem_cpm = (ROOT / "polyfem" / "cmake" / "recipes" / "CPM.cmake").read_text( + encoding="utf-8" + ) + + root_version = re.search(r"CPM_DOWNLOAD_VERSION ([0-9.]+)", root_cpm) + polyfem_version = re.search(r"CPM_DOWNLOAD_VERSION ([0-9.]+)", polyfem_cpm) + + assert root_version is not None + assert polyfem_version is not None + assert root_version.group(1) == polyfem_version.group(1) diff --git a/tests/test_examples_public_surface.py b/tests/test_examples_public_surface.py new file mode 100644 index 00000000..231a51bd --- /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 + assert "from polyfempy.runtime import solve" in lines + + +def test_classic_examples_keep_solver_and_output_explicit(): + _require_examples_submodule() + for path in CLASSIC_EXAMPLES.glob("[23]D/*_generated_api.py"): + source = path.read_text(encoding="utf-8") + assert "model.solver(" in source and "model.output(" in source, path.name + assert "polyfem_config = model.config()" in source, path.name + assert "common_solver" not in source and "common_output" not in source, path.name diff --git a/tests/test_generate_polyfem_api.py b/tests/test_generate_polyfem_api.py new file mode 100644 index 00000000..4bf99715 --- /dev/null +++ b/tests/test_generate_polyfem_api.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +import contextlib +import importlib.util +import io +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT_PATH = ROOT / "tools" / "generate_polyfem_api.py" +GENERATOR_SCRIPT = ROOT / "python-from-jse" / "tools" / "generate_with_overrides.py" +POLYFEM_SOURCE_DIR = ROOT / "polyfem" +POLYFEM_SCHEMA_FILE = POLYFEM_SOURCE_DIR / "json-specs" / "input-spec.json" +GENERATED_DIR = ROOT / "python" / "polyfempy" / "generated_api" + + +def import_workflow(module_name: str = "generate_polyfem_api_for_test"): + spec = importlib.util.spec_from_file_location(module_name, SCRIPT_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 + + +class GeneratePolyfemApiWorkflowTests(unittest.TestCase): + def test_default_workflow_runs_generator_from_repo_root(self): + workflow = import_workflow() + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow, "missing_required_paths", return_value=[]), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main([]) + + self.assertEqual(0, result) + self.assertEqual( + [ + [ + sys.executable, + str(GENERATOR_SCRIPT), + "--schema-file", + str(POLYFEM_SCHEMA_FILE), + "--output-file", + str(GENERATED_DIR / "generated_class.py"), + "--api-output-file", + str(GENERATED_DIR / "generated_api.py"), + "--manifest-dir", + str(GENERATED_DIR), + "--overrides", + str(ROOT / "generator-config" / "builder.json"), + "--relationships", + str(ROOT / "generator-config" / "id_relationships.json"), + "--api-aliases", + str(ROOT / "generator-config" / "api_aliases.json"), + "--model-entry", + "polyfem.model", + ], + ], + [call.args[0] for call in run_mock.call_args_list], + ) + self.assertEqual( + [ROOT], + [call.kwargs["cwd"] for call in run_mock.call_args_list], + ) + + def test_polyfem_source_dir_override_changes_schema_location(self): + workflow = import_workflow() + custom_source_dir = ROOT / "custom-polyfem-source" + custom_schema_file = custom_source_dir / "json-specs" / "input-spec.json" + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow, "missing_required_paths", return_value=[]), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main([ + "--polyfem-source-dir", + str(custom_source_dir), + ]) + + self.assertEqual(0, result) + self.assertIn( + str(custom_schema_file), + run_mock.call_args_list[0].args[0], + ) + + def test_include_spec_dir_is_forwarded_to_generator(self): + workflow = import_workflow() + include_dir = ROOT / "custom-linked-specs" + + with ( + mock.patch.object( + workflow, + "resolve_include_spec_dirs", + return_value=[include_dir], + ), + mock.patch.object(workflow, "missing_required_paths", return_value=[]), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main([ + "--include-spec-dir", + str(include_dir), + ]) + + self.assertEqual(0, result) + self.assertIn( + str(include_dir), + run_mock.call_args_list[0].args[0], + ) + + def test_resolved_schema_file_skips_polysolve_cache_resolution(self): + workflow = import_workflow() + resolved_schema_file = ROOT / "build" / "polyfem-resolved-spec.json" + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs") as resolve_mock, + mock.patch.object(workflow, "missing_required_paths", return_value=[]) as missing_mock, + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main([ + "--resolved-schema-file", + str(resolved_schema_file), + ]) + + self.assertEqual(0, result) + resolve_mock.assert_not_called() + missing_mock.assert_called_once_with( + resolved_schema_file, + [], + require_linked_specs=False, + ) + generator_command = run_mock.call_args_list[0].args[0] + self.assertIn(str(resolved_schema_file), generator_command) + self.assertNotIn(str(POLYFEM_SCHEMA_FILE), generator_command) + self.assertNotIn("--include-spec-dir", generator_command) + + def test_resolved_schema_file_keeps_explicit_include_dirs_without_cache_resolution(self): + workflow = import_workflow() + resolved_schema_file = ROOT / "build" / "polyfem-resolved-spec.json" + include_dir = ROOT / "custom-linked-specs" + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs") as resolve_mock, + mock.patch.object(workflow, "missing_required_paths", return_value=[]), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main([ + "--resolved-schema-file", + str(resolved_schema_file), + "--include-spec-dir", + str(include_dir), + ]) + + self.assertEqual(0, result) + resolve_mock.assert_not_called() + generator_command = run_mock.call_args_list[0].args[0] + self.assertIn(str(resolved_schema_file), generator_command) + self.assertIn("--include-spec-dir", generator_command) + self.assertIn(str(include_dir), generator_command) + + def test_missing_resolved_schema_file_points_to_build_dump(self): + workflow = import_workflow() + resolved_schema_file = ROOT / "build" / "polyfem-resolved-spec.json" + + def fake_exists(path: Path) -> bool: + return path != resolved_schema_file + + with ( + mock.patch.object(workflow.Path, "exists", fake_exists), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = workflow.main([ + "--resolved-schema-file", + str(resolved_schema_file), + ]) + + self.assertEqual(1, result) + self.assertIn("--resolved-schema-file", stderr.getvalue()) + self.assertIn("embedded/resolved spec", stderr.getvalue()) + run_mock.assert_not_called() + + def test_missing_linked_solver_specs_are_cached_from_polysolve_pin(self): + workflow = import_workflow() + + with tempfile.TemporaryDirectory() as tmp: + tmp_dir = Path(tmp) + polyfem_source_dir = tmp_dir / "polyfem" + json_spec_dir = polyfem_source_dir / "json-specs" + cmake_dir = polyfem_source_dir / "cmake" / "recipes" + cache_dir = tmp_dir / "build" / "polysolve-json-specs" + json_spec_dir.mkdir(parents=True) + cmake_dir.mkdir(parents=True) + schema_file = json_spec_dir / "input-spec.json" + schema_file.write_text("{}", encoding="utf-8") + cache_dir.mkdir(parents=True) + for name in workflow.LINKED_SOLVER_SPEC_FILES: + (cache_dir / name).write_text("old unversioned spec", encoding="utf-8") + + def fake_urlretrieve(url, target): + Path(target).write_text(url, encoding="utf-8") + + with ( + mock.patch.object(workflow, "POLYSOLVE_SPEC_CACHE_DIR", cache_dir), + mock.patch.object(workflow.urllib.request, "urlretrieve", side_effect=fake_urlretrieve) as download, + ): + for revision, downloads in [("abc123", 2), ("def456", 4), ("abc123", 4)]: + (cmake_dir / "polysolve.cmake").write_text( + f'CPMAddPackage("gh:polyfem/polysolve#{revision}")', encoding="utf-8" + ) + dirs = workflow.resolve_include_spec_dirs(schema_file, [], polyfem_source_dir) + self.assertEqual([cache_dir / revision], dirs) + self.assertEqual(downloads, download.call_count) + for name in workflow.LINKED_SOLVER_SPEC_FILES: + self.assertEqual( + f"https://raw.githubusercontent.com/polyfem/polysolve/{revision}/{name}", + (dirs[0] / name).read_text(encoding="utf-8"), + ) + + def test_check_workflow_runs_backend_free_checks_after_generation(self): + workflow = import_workflow() + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow, "missing_required_paths", return_value=[]), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + run_mock.return_value = mock.Mock(returncode=0) + + with contextlib.redirect_stdout(io.StringIO()): + result = workflow.main(["--check"]) + + self.assertEqual(0, result) + self.assertEqual( + [ + [ + sys.executable, + str(GENERATOR_SCRIPT), + "--schema-file", + str(POLYFEM_SCHEMA_FILE), + "--output-file", + str(GENERATED_DIR / "generated_class.py"), + "--api-output-file", + str(GENERATED_DIR / "generated_api.py"), + "--manifest-dir", + str(GENERATED_DIR), + "--overrides", + str(ROOT / "generator-config" / "builder.json"), + "--relationships", + str(ROOT / "generator-config" / "id_relationships.json"), + "--api-aliases", + str(ROOT / "generator-config" / "api_aliases.json"), + "--model-entry", + "polyfem.model", + ], + [ + sys.executable, + "-m", + "pytest", + "tests/test_examples_public_surface.py", + "tests/test_generated_api_example.py", + ], + ], + [call.args[0] for call in run_mock.call_args_list], + ) + self.assertEqual( + [ROOT, ROOT], + [call.kwargs["cwd"] for call in run_mock.call_args_list], + ) + self.assertNotIn("regenerate_and_test.py", str(run_mock.call_args_list)) + + def test_workflow_reports_missing_required_directory(self): + workflow = import_workflow() + + def fake_exists(path: Path) -> bool: + return path != ROOT / "python-from-jse" + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow.Path, "exists", fake_exists), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = workflow.main([]) + + self.assertEqual(1, result) + self.assertIn("Missing required path", stderr.getvalue()) + self.assertIn("python-from-jse", stderr.getvalue()) + self.assertIn("submodule", stderr.getvalue()) + run_mock.assert_not_called() + + def test_missing_polyfem_schema_points_to_submodule_setup(self): + workflow = import_workflow() + + def fake_exists(path: Path) -> bool: + return path != POLYFEM_SCHEMA_FILE + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow.Path, "exists", fake_exists), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = workflow.main([]) + + self.assertEqual(1, result) + self.assertIn("polyfem", stderr.getvalue()) + self.assertIn("submodule", stderr.getvalue()) + run_mock.assert_not_called() + + def test_missing_linked_solver_spec_points_to_include_spec_dir(self): + workflow = import_workflow() + + def fake_exists(path: Path) -> bool: + return path not in { + POLYFEM_SCHEMA_FILE.parent / "linear-solver-spec.json", + POLYFEM_SCHEMA_FILE.parent / "nonlinear-solver-spec.json", + } + + with ( + mock.patch.object(workflow, "resolve_include_spec_dirs", return_value=[]), + mock.patch.object(workflow.Path, "exists", fake_exists), + mock.patch.object(workflow.subprocess, "run") as run_mock, + ): + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + result = workflow.main([]) + + self.assertEqual(1, result) + self.assertIn("linear-solver-spec.json", stderr.getvalue()) + self.assertIn("--include-spec-dir", stderr.getvalue()) + run_mock.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_generated_api_example.py b/tests/test_generated_api_example.py new file mode 100644 index 00000000..4b9b632e --- /dev/null +++ b/tests/test_generated_api_example.py @@ -0,0 +1,1142 @@ +"""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.runtime._solve_contract import prepare_canonical_solve_input +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 = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=builder_config, + dtype=None, + ) + top_level_canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=top_level_config, + dtype=None, + ) + assert top_level_canonical.backend_settings == builder_canonical.backend_settings + + +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 = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=legacy_config, + dtype=None, + ) + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=config, + dtype=None, + ) + assert canonical.backend_settings == legacy_canonical.backend_settings + + +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") + assert obstacle is not None + 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, + ) + assert surface is not None + 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) + spec.loader.exec_module(module) + 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( + "example_path", + [pytest.param(path, id=path.stem) for path in _generated_example_files()], +) +def test_classic_generated_example_matches_polyfem_data_source(example_path: Path): + example = _import_example(example_path) + source_path = Path(example.SOURCE_JSON).resolve() + _assert_source_parity(example.polyfem_config.as_dict(), _expected_config_from_source(source_path)) + + +@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 = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=example.polyfem_config, + dtype=None, + ) + + assert isinstance(source_config["materials"], dict) + assert canonical.backend_settings["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( + "example_path", + [pytest.param(path, id=path.stem) for path in _generated_example_files()], +) +def test_classic_generated_example_uses_generated_solve_path(example_path: Path): + example = _import_example(example_path) + + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=example.polyfem_config, + dtype=None, + ) + + assert canonical.metadata == {"mesh_source": "json", "config_source": "generated"} + assert canonical.mesh_source.mode == "json" + assert "geometry" in canonical.backend_settings diff --git a/tests/test_generated_example_backend_tool.py b/tests/test_generated_example_backend_tool.py new file mode 100644 index 00000000..a1cdb836 --- /dev/null +++ b/tests/test_generated_example_backend_tool.py @@ -0,0 +1,480 @@ +from __future__ import annotations + +import json +import importlib.util +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +TOOL_PATH = ROOT / "tools" / "check_generated_example_backend.py" +BATCH_TOOL_PATH = ROOT / "tools" / "run_generated_contact_backend_checks.py" + + +def _load_tool_module(): + spec = importlib.util.spec_from_file_location( + "check_generated_example_backend_for_test", + TOOL_PATH, + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + return module + finally: + sys.modules.pop(spec.name, None) + + +def _load_batch_tool_module(): + spec = importlib.util.spec_from_file_location( + "run_generated_contact_backend_checks_for_test", + BATCH_TOOL_PATH, + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + return module + finally: + sys.modules.pop(spec.name, None) + + +def test_generated_example_backend_tool_exists_and_documents_manual_use(): + text = TOOL_PATH.read_text(encoding="utf-8") + + assert "generated example" in text + assert "--example" in text + assert "--source-json" in text + assert "--require-tests-match" in text + + +def test_compare_metric_maps_reports_pass_and_fail_rows(): + tool = _load_tool_module() + + rows = tool.compare_metric_maps( + left={"err_l2": 1.0, "err_h1": 2.0}, + right={"err_l2": 1.0 + 1e-12, "err_h1": 2.1}, + tolerance=1e-9, + ) + + by_key = {row.key: row for row in rows} + assert by_key["err_l2"].passed + assert not by_key["err_h1"].passed + + +def test_reference_comparison_uses_polyfem_default_margin_and_scale(tmp_path): + tool = _load_tool_module() + path = tmp_path / "scene.json" + reference = {"err_h1": 50.0, "err_l2": 0.01, "err_lp": 0.0} + path.write_text(json.dumps({"tests": reference}), encoding="utf-8") + expected, margin = tool.load_test_metrics(path) + actual = {"err_h1": 50.0001, "err_l2": 0.010001, "err_lp": 5e-11} + + rows = tool.compare_metric_maps( + left=actual, right=expected, tolerance=margin, relative_to_reference=True + ) + assert margin == 1e-5 + assert {row.key: row.passed for row in rows} == { + "err_h1": True, "err_l2": False, "err_lp": True, + } + + +def test_reference_comparison_respects_scene_margin_and_rejects_missing_metrics(tmp_path): + tool = _load_tool_module() + path = tmp_path / "scene.json" + path.write_text(json.dumps({"tests": {"err_l2": 0, "err_lp": 1, "margin": 1e-6}})) + expected, margin = tool.load_test_metrics(path) + rows = tool.compare_metric_maps( + left={"err_l2": 5e-11}, right=expected, tolerance=margin, relative_to_reference=True + ) + assert len(rows) == 2 + assert all(not row.passed for row in rows) + + +def test_backend_tool_applies_polyfem_test_time_steps_to_tend_dt_config(tmp_path): + tool = _load_tool_module() + + source_json = tmp_path / "example.json" + source_json.write_text( + json.dumps( + { + "time": {"tend": 2.0, "dt": 0.25}, + "tests": {"time_steps": 3}, + } + ), + encoding="utf-8", + ) + + payload, test_directive = tool.load_reduced_backend_payload(source_json) + + assert test_directive == 3 + assert payload["time"] == {"dt": 0.25, "time_steps": 3} + + +def test_backend_tool_applies_polyfem_test_time_steps_to_tend_steps_config(tmp_path): + tool = _load_tool_module() + + source_json = tmp_path / "example.json" + source_json.write_text( + json.dumps( + { + "time": {"tend": 2.0, "time_steps": 8}, + "tests": {"time_steps": 2}, + } + ), + encoding="utf-8", + ) + + payload, test_directive = tool.load_reduced_backend_payload(source_json) + + assert test_directive == 2 + assert payload["time"] == {"dt": 0.25, "time_steps": 2} + + +def test_backend_tool_defaults_dynamic_examples_to_one_step(tmp_path): + tool = _load_tool_module() + + source_json = tmp_path / "example.json" + source_json.write_text( + json.dumps({"time": {"dt": 0.1, "time_steps": 10}}), + encoding="utf-8", + ) + + payload, test_directive = tool.load_reduced_backend_payload(source_json) + + assert test_directive == 1 + assert payload["time"] == {"dt": 0.1, "time_steps": 1} + + +def test_backend_tool_adds_json_output_to_reduced_payload(tmp_path): + tool = _load_tool_module() + + source_json = tmp_path / "example.json" + source_json.write_text( + json.dumps({"time": {"dt": 0.1, "time_steps": 10}}), + encoding="utf-8", + ) + + payload, _test_directive = tool.load_reduced_backend_payload(source_json) + + assert payload["output"]["json"] == "sim.json" + + +def test_backend_tool_applies_polyfem_verify_run_linear_solver_patch(tmp_path): + tool = _load_tool_module() + + default_source = tmp_path / "example.json" + default_source.write_text( + json.dumps( + { + "solver": {"linear": {"solver": ["A", "B"]}}, + "time": {"dt": 0.1, "time_steps": 10}, + } + ), + encoding="utf-8", + ) + navier_source = tmp_path / "navier-example.json" + navier_source.write_text( + json.dumps( + { + "solver": {"linear": {"solver": ["A", "B"]}}, + "time": {"dt": 0.1, "time_steps": 10}, + } + ), + encoding="utf-8", + ) + + default_payload, _ = tool.load_reduced_backend_payload(default_source) + navier_payload, _ = tool.load_reduced_backend_payload(navier_source) + + assert ( + default_payload["solver"]["linear"]["solver"] + == "Eigen::SimplicialLDLT" + ) + assert navier_payload["solver"]["linear"]["solver"] == "Eigen::SparseLU" + + +def test_generated_run_isolates_output_from_example(tmp_path, monkeypatch): + from types import SimpleNamespace + from polyfempy import runtime + + tool = _load_tool_module() + cfg = {"output": {"directory": "results/sample", "log": {"path": "sample.log"}}} + monkeypatch.setattr(tool, "_import_example", lambda path: SimpleNamespace(polyfem_config=cfg)) + captured = {} + monkeypatch.setattr(runtime, "solve", lambda *, cfg: captured.update(cfg)) + workspace = tool.run_generated_example( + Path("sample.py"), Path("sample.json"), tmp_path, test_time_steps="static", keep_visual_output=True + ) + assert captured["output"] == { + "directory": str(workspace), "json": "sim.json", "log": {"path": str(workspace / "polyfem.log")} + } + assert cfg == {"output": {"directory": "results/sample", "log": {"path": "sample.log"}}} + + +def test_backend_tool_restores_generated_payload_semantics_before_backend_run(tmp_path): + tool = _load_tool_module() + + class GeneratedConfig: + def as_dict(self): + return { + "geometry": [ + { + "mesh": str(tmp_path / "mesh.obj"), + "transformation": { + "rotation": [90.0], + "scale": [0.5], + "translation": [], + }, + } + ], + } + + payload = tool._config_payload_for_backend_run(GeneratedConfig()) + + assert payload["geometry"][0]["transformation"] == { + "rotation": 90.0, + "scale": 0.5, + } + + +def test_backend_tool_keeps_all_and_static_test_directives_unpatched(tmp_path): + tool = _load_tool_module() + + all_source = tmp_path / "all.json" + all_source.write_text( + json.dumps( + { + "time": {"dt": 0.1, "time_steps": 10}, + "tests": {"time_steps": "all"}, + } + ), + encoding="utf-8", + ) + static_source = tmp_path / "static.json" + static_source.write_text(json.dumps({"tests": {}}), encoding="utf-8") + + all_payload, all_directive = tool.load_reduced_backend_payload(all_source) + static_payload, static_directive = tool.load_reduced_backend_payload(static_source) + + assert all_directive == "all" + assert all_payload["time"] == {"dt": 0.1, "time_steps": 10} + assert static_directive == "static" + assert "time" not in static_payload + + +def test_backend_tool_prunes_visual_output_files(tmp_path): + tool = _load_tool_module() + + keep = tmp_path / "sim.json" + keep.write_text("{}", encoding="utf-8") + log = tmp_path / "polyfem.log" + log.write_text("log", encoding="utf-8") + for suffix in (".vtu", ".vtm", ".pvd"): + (tmp_path / f"sim{suffix}").write_text("large", encoding="utf-8") + + removed = tool.prune_visual_outputs(tmp_path) + + assert sorted(path.suffix for path in removed) == [".pvd", ".vtm", ".vtu"] + assert keep.exists() + assert log.exists() + assert not any(tmp_path.glob("*.vtu")) + assert not any(tmp_path.glob("*.vtm")) + assert not any(tmp_path.glob("*.pvd")) + + +def test_backend_tool_uses_short_backend_workspace_names(tmp_path): + tool = _load_tool_module() + + example_path = ( + tmp_path + / "contact_2d_friction_high_school_physics_slopetest_mu_0_49_generated_api.py" + ) + source_json = tmp_path / "high-school-physics-slopetest-mu=0.49.json" + output_root = tmp_path / "generated-contact-backend-check-20260813-model-full" + + generated_workspace = tool._generated_workspace(output_root, example_path) + source_workspace = tool._source_json_workspace(output_root, source_json) + + assert generated_workspace == output_root / "generated" / "run" + assert source_workspace == output_root / "source-json" / "run" + assert example_path.stem not in str(generated_workspace) + assert source_json.stem not in str(source_workspace) + + +def test_generated_contact_workflow_runs_batch_backend_checker(): + workflow = ( + ROOT / ".github" / "workflows" / "generated-contact-backend.yml" + ).read_text( + encoding="utf-8" + ) + + assert "tools/run_generated_contact_backend_checks.py" in workflow + assert "--require-tests-match" in workflow + assert "tools/generated_contact_expected_failures.json" in workflow + + +def test_batch_backend_tool_reads_polyfem_active_contact_lists(): + tool = _load_batch_tool_module() + + cases = tool.iter_active_contact_cases(tool.CONTACT_LISTS) + by_source = {case.source_rel: case for case in cases} + + assert len(cases) == 75 + assert all(Path(case.generated_example).exists() for case in cases) + assert "contact/examples/3D/pile/cubes.json" in by_source + assert "contact/examples/3D/hex_tet/params.json" in by_source + assert "contact/examples/3D/rigid/proxy/screw.json" in by_source + assert "contact/examples/3D/static/two-cubes.json" not in by_source + assert by_source[ + "contact/examples/3D/friction/high-school-physics-slopetest-mu=0.50.json" + ].generated_example.endswith( + "contact_3d_friction_high_school_slopetest_generated_api.py" + ) + + +def test_batch_backend_tool_writes_logs_outside_checkout(tmp_path, monkeypatch): + tool = _load_batch_tool_module() + case = tool.ContactCase( + list_file="contact_2d.txt", + line_number=1, + source_rel="contact/examples/2D/example.json", + source_json=str(tmp_path / "source.json"), + generated_example=str(ROOT / "examples" / "example.py"), + ) + completed = tool.subprocess.CompletedProcess( + args=[], returncode=0, stdout="Reference metrics passed.", stderr="" + ) + monkeypatch.setattr(tool.subprocess, "run", lambda *args, **kwargs: completed) + + result = tool.run_case( + case, + tmp_path, + generated_source_tolerance=1e-5, + require_tests_match=True, + keep_visual_output=False, + log_level=2, + max_threads=1, + ) + log_file = Path(result.log_file) + assert log_file.is_absolute() + assert "Reference metrics passed." in log_file.read_text(encoding="utf-8") + tool.write_summaries(tmp_path, [case], [result]) + summary = json.loads((tmp_path / "summary.json").read_text(encoding="utf-8")) + assert summary["passed"] == 1 + assert summary["failed"] == 0 + + +def test_batch_backend_tool_loads_expected_failure_config(tmp_path): + tool = _load_batch_tool_module() + + config_path = tmp_path / "expected_failures.json" + config_path.write_text( + json.dumps( + { + "ignored": [ + { + "source": "contact/examples/3D/rigid/proxy/screw.json", + "reason": "teacher-approved HDF5 issue", + "approved": True, + } + ] + } + ), + encoding="utf-8", + ) + + expected_failures = tool.load_expected_failures(config_path) + + assert set(expected_failures) == { + "contact/examples/3D/rigid/proxy/screw.json" + } + ignored = expected_failures["contact/examples/3D/rigid/proxy/screw.json"] + assert ignored.source == "contact/examples/3D/rigid/proxy/screw.json" + assert ignored.reason == "teacher-approved HDF5 issue" + assert ignored.approved is True + + +def test_default_expected_failure_config_does_not_ignore_passing_screw_case(): + tool = _load_batch_tool_module() + + expected_failures = tool.load_expected_failures(tool.DEFAULT_EXPECTED_FAILURES) + + assert "contact/examples/3D/rigid/proxy/screw.json" not in expected_failures + + +def test_batch_backend_tool_classifies_expected_failures_in_summary(tmp_path): + tool = _load_batch_tool_module() + expected_failures = { + "contact/examples/3D/rigid/proxy/screw.json": tool.ExpectedFailure( + source="contact/examples/3D/rigid/proxy/screw.json", + reason="teacher-approved HDF5 issue", + approved=True, + ), + "contact/examples/3D/expected/pass-now.json": tool.ExpectedFailure( + source="contact/examples/3D/expected/pass-now.json", + reason="old expected failure", + approved=True, + ), + } + raw_results = [ + tool.CaseResult( + source_rel="contact/examples/2D/friction/card-house.json", + generated_example="examples/card-house.py", + status="PASS", + returncode=0, + log_file="logs/card-house.log", + ), + tool.CaseResult( + source_rel="contact/examples/3D/rigid/proxy/screw.json", + generated_example="examples/screw.py", + status="FAIL", + returncode=1, + log_file="logs/screw.log", + ), + tool.CaseResult( + source_rel="contact/examples/3D/expected/pass-now.json", + generated_example="examples/pass-now.py", + status="PASS", + returncode=0, + log_file="logs/pass-now.log", + ), + tool.CaseResult( + source_rel="contact/examples/3D/pile/cubes.json", + generated_example="examples/cubes.py", + status="FAIL", + returncode=1, + log_file="logs/cubes.log", + ), + ] + + results = tool.apply_expected_failures(raw_results, expected_failures) + + assert [result.status for result in results] == [ + "PASS", + "IGNORED", + "UNEXPECTED_PASS", + "FAIL", + ] + assert results[1].raw_status == "FAIL" + assert results[1].reason == "teacher-approved HDF5 issue" + assert results[2].raw_status == "PASS" + assert results[2].reason == "old expected failure" + + tool.write_summaries(tmp_path, [], results) + + summary = json.loads((tmp_path / "summary.json").read_text(encoding="utf-8")) + assert summary["passed"] == 1 + assert summary["ignored"] == 1 + assert summary["failed"] == 1 + assert summary["unexpected_pass"] == 1 + assert summary["unexpected_fail"] == 1 + + summary_text = (tmp_path / "summary.txt").read_text(encoding="utf-8") + assert "PASS: 1" in summary_text + assert "IGNORED: 1" in summary_text + assert "FAIL: 1" in summary_text + assert "Unexpected pass: 1" in summary_text + assert "Unexpected fail: 1" in summary_text diff --git a/tests/test_generated_payload.py b/tests/test_generated_payload.py new file mode 100644 index 00000000..d6c2171d --- /dev/null +++ b/tests/test_generated_payload.py @@ -0,0 +1,366 @@ +"""Tests for the generated-class payload boundary. + +These tests stay in pure Python. They protect the first generated-only layer: +``Root.as_dict()``-style payloads should be prepared for the backend without +constructing a second config object. +""" + +from __future__ import annotations + +import copy +import sys +import tempfile +import unittest +from pathlib import Path + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime._solve_contract import ( # noqa: E402 + generated_payload_from_config, + prepare_canonical_solve_input, + prepare_generated_backend_payload, +) + + +def _canonical_path_text(path: Path) -> str: + return str(path.resolve()) + + +class GeneratedPayloadTests(unittest.TestCase): + def test_generated_payload_helpers_live_in_solve_contract(self): + self.assertFalse((_REPO / "python" / "polyfempy" / "api" / "_generated_payload.py").exists()) + + def test_generated_payload_from_config_requires_dict(self): + class BadGeneratedConfig: + def as_dict(self): + return ["not", "a", "dict"] + + with self.assertRaisesRegex(TypeError, "as_dict\\(\\) must return dict"): + generated_payload_from_config(BadGeneratedConfig()) + + def test_prepare_payload_does_not_mutate_input_and_preserves_backend_fields(self): + payload = { + "geometry": [{"mesh": "beam.msh", "enabled": True, "unused": None}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + "solver": {"new_backend_option": False}, + "output": {"directory": "", "stats": False}, + } + snapshot = copy.deepcopy(payload) + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual(payload, snapshot) + self.assertNotIn("unused", prepared["geometry"][0]) + self.assertFalse(prepared["solver"]["new_backend_option"]) + self.assertEqual(prepared["output"]["directory"], "") + self.assertFalse(prepared["output"]["stats"]) + + def test_prepare_payload_leaves_output_schema_validation_to_backend(self): + payload = { + "geometry": [{"mesh": "beam.msh"}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + "output": { + "directory": "out", + "future_backend_option": {"enabled": True}, + }, + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual(prepared["output"], payload["output"]) + + def test_prepare_payload_restores_single_global_material_object_shape(self): + payload = { + "materials": [ + {"type": "NeoHookean", "E": 10000.0, "nu": 0.4, "rho": 1000.0} + ] + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual( + {"type": "NeoHookean", "E": 10000.0, "nu": 0.4, "rho": 1000.0}, + prepared["materials"], + ) + + def test_prepare_payload_keeps_id_materials_as_list(self): + payload = { + "materials": [ + {"id": 1, "type": "LinearElasticity", "E": 20.0, "nu": 0.3} + ] + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual(payload["materials"], prepared["materials"]) + + def test_prepare_payload_resolves_relative_geometry_mesh_from_root_path(self): + with tempfile.TemporaryDirectory() as tmp: + case_dir = Path(tmp) / "case" + case_dir.mkdir() + mesh_file = case_dir / "beam.msh" + mesh_file.write_text("placeholder", encoding="utf-8") + + payload = { + "root_path": str(case_dir / "config.json"), + "geometry": [{"mesh": "beam.msh"}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual( + prepared["geometry"][0]["mesh"], + _canonical_path_text(mesh_file), + ) + + def test_prepare_payload_resolves_relative_selection_files_from_root_path(self): + with tempfile.TemporaryDirectory() as tmp: + case_dir = Path(tmp) / "case" + case_dir.mkdir() + volume_file = case_dir / "volume.txt" + surface_file = case_dir / "surface.txt" + volume_file.write_text("1", encoding="utf-8") + surface_file.write_text("2", encoding="utf-8") + + payload = { + "root_path": str(case_dir / "config.json"), + "geometry": [ + { + "mesh": "beam.msh", + "volume_selection": {"file": "volume.txt"}, + "surface_selection": {"file": "surface.txt"}, + } + ], + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual( + prepared["geometry"][0]["volume_selection"]["file"], + _canonical_path_text(volume_file), + ) + self.assertEqual( + prepared["geometry"][0]["surface_selection"]["file"], + _canonical_path_text(surface_file), + ) + + def test_prepare_payload_resolves_relative_collision_mesh_files_from_root_path(self): + with tempfile.TemporaryDirectory() as tmp: + case_dir = Path(tmp) / "case" + case_dir.mkdir() + mesh_file = case_dir / "proxy.ply" + map_file = case_dir / "coarse-to-proxy.hdf5" + mesh_file.write_text("placeholder", encoding="utf-8") + map_file.write_text("placeholder", encoding="utf-8") + + payload = { + "root_path": str(case_dir / "config.json"), + "contact": { + "collision_mesh": { + "mesh": "proxy.ply", + "linear_map": "coarse-to-proxy.hdf5", + } + }, + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual( + prepared["contact"]["collision_mesh"]["mesh"], + _canonical_path_text(mesh_file), + ) + self.assertEqual( + prepared["contact"]["collision_mesh"]["linear_map"], + _canonical_path_text(map_file), + ) + + def test_prepare_payload_restores_uniform_scale_scalar_for_backend(self): + payload = { + "geometry": [ + { + "mesh": "ball.obj", + "transformation": { + "translation": [], + "rotation": [], + "rotation_mode": "xyz", + "scale": [0.04], + }, + } + ], + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual(0.04, prepared["geometry"][0]["transformation"]["scale"]) + self.assertNotIn("translation", prepared["geometry"][0]["transformation"]) + self.assertNotIn("rotation", prepared["geometry"][0]["transformation"]) + self.assertNotIn("rotation_mode", prepared["geometry"][0]["transformation"]) + + def test_prepare_payload_drops_generated_solver_advanced_defaults(self): + payload = { + "solver": { + "advanced": { + "cache_size": 900000, + "lump_mass_matrix": True, + "lagged_regularization_weight": 0.0, + "lagged_regularization_iterations": 1, + "check_inversion": "Discrete", + "jacobian_threshold": 0.0, + "characteristic_length": -1.0, + "characteristic_force_density": 10000.0, + } + } + } + + prepared = prepare_generated_backend_payload(payload) + + self.assertEqual({"lump_mass_matrix": True}, prepared["solver"]["advanced"]) + + def test_prepare_payload_keeps_backend_nonlinear_solver_names(self): + payload = { + "solver": { + "nonlinear": { + "solver": "Newton", + "x_delta_tol": 1e-12, + "grad_norm_tol": 1e-5, + "rel_grad_norm_tol": 1e-10, + "newton_decrement_tol": 0.0, + "rel_x_delta_tol": 0.0, + "first_grad_norm_tol": 1e-12, + "norm_type": "L2", + "max_iterations": 500, + "allow_out_of_iterations": False, + "iterations_per_strategy": 1, + "line_search": { + "method": "RobustArmijo", + "use_grad_norm_tol": 1e-6, + "min_step_size": 1e-10, + "max_step_size_iter": 30, + "min_step_size_final": 1e-20, + "max_step_size_iter_final": 100, + "default_init_step_size": 1.0, + "step_ratio": 0.5, + }, + "advanced": { + "f_delta_tol": 1e-5, + "f_delta_step_tol": 100, + "derivative_along_delta_x_tol": 0, + "apply_gradient_fd": "None", + "gradient_fd_eps": 1e-7, + }, + } + } + } + + prepared = prepare_generated_backend_payload(payload) + nonlinear = prepared["solver"]["nonlinear"] + + self.assertEqual(1e-12, nonlinear["x_delta_tol"]) + self.assertEqual(1e-5, nonlinear["grad_norm_tol"]) + self.assertNotIn("x_delta", nonlinear) + self.assertNotIn("grad_norm", nonlinear) + self.assertNotIn("rel_grad_norm_tol", nonlinear) + self.assertNotIn("newton_decrement_tol", nonlinear) + self.assertNotIn("rel_x_delta_tol", nonlinear) + self.assertNotIn("first_grad_norm_tol", nonlinear) + self.assertNotIn("norm_type", nonlinear) + self.assertNotIn("max_iterations", nonlinear) + self.assertEqual({"method": "RobustArmijo"}, nonlinear["line_search"]) + self.assertEqual({"f_delta_tol": 1e-5}, nonlinear["advanced"]) + + def test_prepare_payload_accepts_legacy_f_delta_without_mutating_input(self): + for augmented in (False, True): + with self.subTest(augmented=augmented): + solver = {"nonlinear": {"advanced": {"f_delta": 1e-5}}} + payload = {"solver": {"augmented_lagrangian": solver} if augmented else solver} + snapshot = copy.deepcopy(payload) + + prepared = prepare_generated_backend_payload(payload)["solver"] + if augmented: + prepared = prepared["augmented_lagrangian"] + + self.assertEqual({"f_delta_tol": 1e-5}, prepared["nonlinear"]["advanced"]) + self.assertEqual(snapshot, payload) + + def test_prepare_payload_prefers_current_f_delta_tol_including_zero(self): + for value in (0.0, 2e-5): + with self.subTest(value=value): + payload = {"solver": {"nonlinear": {"advanced": { + "f_delta": 1e-5, "f_delta_tol": value, "track_info": True, + }}}} + + advanced = prepare_generated_backend_payload(payload)["solver"]["nonlinear"]["advanced"] + + expected = {"track_info": True, "f_delta_tol": value} + if value == 0: + expected.pop("f_delta_tol") + self.assertEqual(expected, advanced) + + def test_prepare_payload_drops_zero_tolerance_default_for_both_names(self): + for key in ("f_delta", "f_delta_tol"): + with self.subTest(key=key): + payload = {"solver": {"nonlinear": {"advanced": {key: 0.0}}}} + + prepared = prepare_generated_backend_payload(payload) + + self.assertNotIn("advanced", prepared["solver"]["nonlinear"]) + + def test_model_solver_preserves_f_delta_tol_for_the_backend(self): + import polyfem + + model = polyfem.model() + model.mesh(mesh="triangle.obj") + model.solver(nonlinear=polyfem.nonlinear( + advanced=polyfem.nonlinear_advanced(f_delta_tol=1e-5), + )) + cfg = model.config() + snapshot = cfg.as_dict() + + canonical = prepare_canonical_solve_input(vertices=None, cells=None, cfg=cfg) + + self.assertEqual( + {"f_delta_tol": 1e-5}, + canonical.backend_settings["solver"]["nonlinear"]["advanced"], + ) + self.assertEqual(snapshot, cfg.as_dict()) + + def test_dictionary_tolerance_names_for_file_and_array_meshes(self): + cases = ( + ({"f_delta": 1e-5}, 1e-5), + ({"f_delta_tol": 1e-5}, 1e-5), + ({"f_delta": 1e-5, "f_delta_tol": 2e-5}, 2e-5), + ({"f_delta": 1e-5, "f_delta_tol": 0.0}, 0.0), + ) + for advanced, expected in cases: + for augmented in (False, True): + for array_mesh in (False, True): + with self.subTest(advanced=advanced, augmented=augmented, array_mesh=array_mesh): + solver = {"nonlinear": {"advanced": dict(advanced, track_info=True)}} + cfg: dict[str, object] = { + "solver": {"augmented_lagrangian": solver} if augmented else solver, + } + vertices, cells = None, None + if array_mesh: + vertices, cells = [[0, 0], [1, 0], [0, 1]], [[0, 1, 2]] + else: + cfg["geometry"] = [{"mesh": "triangle.obj"}] + snapshot = copy.deepcopy(cfg) + + settings = prepare_canonical_solve_input( + vertices=vertices, cells=cells, cfg=cfg, + ).backend_settings["solver"] + if augmented: + settings = settings["augmented_lagrangian"] + + self.assertEqual( + {"f_delta_tol": expected, "track_info": True}, + settings["nonlinear"]["advanced"], + ) + self.assertEqual(snapshot, cfg) + + +if __name__ == "__main__": + unittest.main() 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..4a93cbc3 --- /dev/null +++ b/tests/test_import_public_api.py @@ -0,0 +1,101 @@ +"""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(NotImplementedError, match="sidesets_func"): + solve(sidesets_func=lambda *_: 1) + + +def test_public_api_imports(): + from polyfempy.runtime import Result, solve + + assert solve is not None + assert Result is not None + + +def test_runtime_imports_are_the_preferred_solve_surface(): + import polyfempy.runtime as runtime + from polyfempy.runtime import Result, solve + + assert runtime.CORE_RUNTIME == ["solve", "Result"] + assert runtime.__all__ == runtime.CORE_RUNTIME + assert solve is not None + assert Result is not None + + +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_runtime_recommended_surface_is_small(): + import polyfempy.runtime as runtime + + assert runtime.CORE_RUNTIME == ["solve", "Result"] + assert runtime.__all__ == runtime.CORE_RUNTIME + + for name in ( + "SimulationConfig", + "Output", + "ParaviewOutput", + "result_output", + "solve_with_timing", + "configure_windows_runtime", + "batch_solve", + "HistoryView", + ): + assert not hasattr(runtime, name) + + +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.runtime.solve") + + assert solve_module.__all__ == ["solve"] + assert "sampled_vtu_fallback" not in inspect.signature(solve_module.solve).parameters + assert not hasattr(solve_module, "populate_sampled_history") diff --git a/tests/test_model_selection_ids.py b/tests/test_model_selection_ids.py new file mode 100644 index 00000000..49dd61f0 --- /dev/null +++ b/tests/test_model_selection_ids.py @@ -0,0 +1,195 @@ +"""Check model associations without loading meshes or running the native solver.""" + +import pytest + +import polyfem +from polyfempy._model_builder import SelectionHandle + + +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 isinstance(first, SelectionHandle) + assert isinstance(second, SelectionHandle) + 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 + + +@pytest.mark.parametrize("volume_selection", [1, [{"id": 1, "axis": "-x", "position": 0.0}]]) +def test_late_explicit_volume_id_cannot_claim_another_bodys_rhs(volume_selection): + model = polyfem.model() + loaded = model.mesh(mesh="loaded.msh") + loaded.rhs(value=[0, -9]) + before = model.config().as_dict() + + with pytest.raises(ValueError, match="volume.*1.*same_volume_as"): + model.mesh(mesh="unloaded.msh", volume_selection=volume_selection) + assert model.config().as_dict() == before + + model.mesh(mesh="unloaded.msh", volume_selection=2) + cfg = model.config().as_dict() + assert [g["volume_selection"] for g in cfg["geometry"]] == [1, 2] + assert cfg["boundary_conditions"]["rhs"] == [{"id": 1, "value": [0, -9]}] + + +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) + assert obstacle is not None + 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..87ec6b1d --- /dev/null +++ b/tests/test_model_settings.py @@ -0,0 +1,266 @@ +"""Model settings must survive export without changing existing config calls.""" + +from functools import partial + +import pytest + +import 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 + + +@pytest.mark.parametrize("via_factory", [False, True], ids=["model.config", "polyfem.config"]) +def test_config_rejects_duplicate_global_rhs(via_factory): + model = polyfem.model() + export = partial(polyfem.config, model=model) if via_factory else model.config + boundary = {"rhs": [1, 0]} + + with pytest.raises(TypeError, match="rhs"): + export(rhs=[0, -1], boundary_conditions=boundary) + + model.rhs([0, -1]) + with pytest.raises(TypeError, match="rhs"): + export(rhs=[1, 0]) + with pytest.raises(TypeError, match="rhs"): + export(boundary_conditions=boundary) + with pytest.raises(TypeError, match="rhs"): + export(boundary_conditions=polyfem.boundary_conditions(**boundary)) + + +def test_uniform_body_rhs_tracks_the_current_deformable_geometry(): + model = polyfem.model() + first = model.mesh(mesh="first.msh") + first.rhs(value=[0, -1]) + model.mesh(mesh="wall.obj", is_obstacle=True) + single = model.config().as_dict() + assert single["boundary_conditions"]["rhs"] == [0, -1] + assert "volume_selection" not in single["geometry"][0] + + second = model.mesh_array(mesh="second.msh", array=polyfem.array(size=[2, 1], offset=1)) + partial = model.config().as_dict() + first_id = partial["geometry"][0]["volume_selection"] + assert partial["boundary_conditions"]["rhs"] == [{"id": first_id, "value": [0, -1]}] + assert "volume_selection" not in partial["geometry"][2] + + second.rhs(value=(0, -1)) + uniform = model.config().as_dict() + assert uniform["boundary_conditions"]["rhs"] == [0, -1] + assert all("volume_selection" not in mesh for mesh in uniform["geometry"]) + assert model.config().as_dict() == uniform + + +def test_uniform_body_rhs_keeps_ids_needed_by_other_settings(): + model = polyfem.model() + first = model.mesh(mesh="first.msh", volume_selection=7) + second = model.mesh(mesh="second.msh") + third = model.mesh(mesh="third.msh") + for body in (first, second, third): + body.rhs(value=[0, -1]) + material = polyfem.neo_hookean(E=1000, nu=0.3) + second.material(material) + assert third.volume_ref is not None + third_id = third.volume_ref.backend_id + cfg = model.config(initial_conditions=polyfem.initial_conditions( + velocity=[{"id": third_id, "value": [1, 0]}] + )).as_dict() + assert cfg["boundary_conditions"]["rhs"] == [0, -1] + assert [g["volume_selection"] for g in cfg["geometry"]] == [7, cfg["materials"][0]["id"], third_id] + assert "volume_selection" not in model.config().as_dict()["geometry"][2] + + +def test_body_rhs_preserves_shared_volumes_and_fe_space(): + model = polyfem.model() + first = model.mesh(mesh="first.msh") + first.rhs(value=[0, -1]) + model.mesh(mesh="second.msh", same_volume_as=first) + cfg = model.config().as_dict() + assert cfg["boundary_conditions"]["rhs"] == [0, -1] + assert cfg["geometry"][0]["volume_selection"] == cfg["geometry"][1]["volume_selection"] + + model = polyfem.model() + model.mesh(mesh="solid.msh").rhs(value=[0, -1], fe_space=1) + cfg = model.config().as_dict() + volume_id = cfg["geometry"][0]["volume_selection"] + assert cfg["boundary_conditions"]["rhs"] == [{"id": volume_id, "value": [0, -1], "fe_space": 1}] + + +def test_rejected_body_rhs_keeps_existing_global_rhs_and_mesh_tags(): + model = polyfem.model() + beam = model.mesh(mesh="beam.msh") + model.rhs([0, -1]) + before = model.config().as_dict() + with pytest.raises(TypeError, match="rhs"): + beam.rhs(value=[1, 0]) + assert model.config().as_dict() == before diff --git a/tests/test_package_build.py b/tests/test_package_build.py new file mode 100644 index 00000000..8f5f490a --- /dev/null +++ b/tests/test_package_build.py @@ -0,0 +1,147 @@ +"""Check build failures without compiling the native solver.""" + +import runpy +import subprocess +import sys +import sysconfig +from pathlib import Path +from unittest.mock import patch + +import pytest +from setuptools import Distribution + + +@pytest.fixture +def build_script(): + with patch("setuptools.setup"): + return runpy.run_path(str(Path(__file__).resolve().parents[1] / "setup.py")) + + +def test_missing_cmake_has_installation_hint(build_script): + command = build_script["CMakeBuild"](Distribution()) + with patch("subprocess.check_output", side_effect=FileNotFoundError): + with pytest.raises(RuntimeError, match="CMake 3.25 or later"): + command.run() + + +@pytest.mark.parametrize("runtime", ["nanobind.dll", "libnanobind.so", "libnanobind.so.1", "libnanobind.dylib"]) +def test_editable_mapping_includes_shared_runtime(build_script, tmp_path, runtime): + from setuptools.command.build_ext import build_ext + + source = tmp_path / "python" / "polyfempy" + output = tmp_path / "build" / "polyfempy" + source.mkdir(parents=True) + (source / runtime).write_bytes(b"runtime") + (source / "debug.pdb").write_bytes(b"debug symbols") + extension = "polyfempy.pyd" + mapping = {str(output / extension): str(source / extension)} + command = build_script["CMakeBuild"](Distribution()) + with patch.object(build_ext, "get_output_mapping", return_value=mapping.copy()): + assert command.get_output_mapping() == { + **mapping, str(output / runtime): str(source / runtime), + } + + +@pytest.mark.parametrize( + "system,generator", + [("Windows", "Ninja"), ("Linux", "Ninja"), ("Windows", "Visual Studio 17 2022")], +) +def test_build_uses_cmake_parallel_options( + build_script, monkeypatch, tmp_path, system, generator +): + monkeypatch.setenv("CMAKE_GENERATOR", generator) + monkeypatch.setenv("N_THREADS", "2") + # Build dependencies are discovered by CMake using the build interpreter. + monkeypatch.setitem(sys.modules, "nanobind", None) + command = build_script["CMakeBuild"](Distribution()) + command.build_temp = str(tmp_path / "build") + command.build_lib = str(tmp_path / "lib") + with ( + patch("platform.system", return_value=system), + patch("subprocess.check_call") as call, + ): + command.build_extension(build_script["CMakeExtension"]("polyfempy.polyfempy")) + configure, build = [entry.args[0] for entry in call.call_args_list] + assert ("-A" in configure) == ( + generator.startswith("Visual Studio") and sys.maxsize > 2**32 + ) + visual_studio = system == "Windows" and generator.startswith("Visual Studio") + assert build[-3:] == ["--parallel", "1" if visual_studio else "2", "--verbose"] + assert "--" not in build + assert "-DPOLYFEM_PORTABLE_BUILD=ON" in configure + assert f"-DPython_EXECUTABLE={sys.executable}" in configure + assert f"-DPython_EXTENSION_MODULE_SUFFIX={sysconfig.get_config_var('EXT_SUFFIX')}" in configure + if visual_studio: + assert call.call_args.kwargs["env"]["_CL_"].endswith("/MP2") + + +def test_failed_build_is_not_repeated(build_script, tmp_path): + command = build_script["CMakeBuild"](Distribution()) + command.build_temp = str(tmp_path / "build") + command.build_lib = str(tmp_path / "lib") + with patch( + "subprocess.check_call", + side_effect=[0, subprocess.CalledProcessError(1, "cmake")], + ) as call: + with pytest.raises(RuntimeError, match="CMake build failed"): + command.build_extension( + build_script["CMakeExtension"]("polyfempy.polyfempy") + ) + assert call.call_count == 2 + + +def test_existing_ninja_build_does_not_receive_visual_studio_options( + build_script, monkeypatch, tmp_path +): + monkeypatch.delenv("CMAKE_GENERATOR", raising=False) + monkeypatch.setenv("N_THREADS", "2") + (tmp_path / "CMakeCache.txt").write_text("CMAKE_GENERATOR:INTERNAL=Ninja\n") + command = build_script["CMakeBuild"](Distribution()) + command.build_temp = str(tmp_path) + command.build_lib = str(tmp_path / "lib") + with ( + patch("platform.system", return_value="Windows"), + patch("subprocess.check_call") as call, + ): + command.build_extension(build_script["CMakeExtension"]("polyfempy.polyfempy")) + configure, build = [entry.args[0] for entry in call.call_args_list] + assert "-A" not in configure + assert build[-3:] == ["--parallel", "2", "--verbose"] + + +def test_missing_generated_sources_fail_before_packaging(build_script, tmp_path): + check = build_script["check_package_sources"] + with patch.dict(check.__globals__, ROOT=tmp_path): + with pytest.raises(RuntimeError, match="tools/generate_polyfem_api.py"): + check() + + +@pytest.mark.parametrize("workers", ["0", "-1", "many"]) +def test_invalid_worker_count_has_clear_error( + build_script, monkeypatch, tmp_path, workers +): + monkeypatch.setenv("N_THREADS", workers) + command = build_script["CMakeBuild"](Distribution()) + command.build_lib = str(tmp_path) + with pytest.raises(RuntimeError, match="N_THREADS must be a positive integer"): + command.build_extension(build_script["CMakeExtension"]("polyfempy.polyfempy")) + + +def test_package_discovery_preserves_installed_names(): + root = Path(__file__).resolve().parents[1] + with patch("setuptools.setup") as setup: + runpy.run_path(str(root / "setup.py")) + options = setup.call_args.kwargs + packages = options["packages"] + assert {"polyfem", "polyfempy", "polyfempy.runtime", "polyfempy.generated_api"} <= set(packages) + assert not any(name.startswith("python.") for name in packages) + distribution = Distribution({"packages": packages, "package_dir": options["package_dir"]}) + distribution.script_name = "setup.py" + command = distribution.get_command_obj("build_py") + command.ensure_finalized() + for package in ("polyfem", "polyfempy", "polyfempy.runtime"): + assert Path(command.get_package_dir(package)) == Path("python", *package.split(".")) + assert "polyfempy.generated_api.generator" not in packages + shipped_modules = {name for _, name, _ in command.find_all_modules()} + assert {"_model_builder", "_selection_refs"} <= shipped_modules + assert options["ext_modules"][0].name == "polyfempy.polyfempy" diff --git a/tests/test_pipeline_backend.py b/tests/test_pipeline_backend.py new file mode 100644 index 00000000..0ee77f28 --- /dev/null +++ b/tests/test_pipeline_backend.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import json +from typing import Any + +import numpy as np +import pytest + + +@pytest.mark.parametrize("array_mesh", [False, True]) +@pytest.mark.parametrize("log_level,expected", [(4, 4), ("off", 6)]) +def test_solve_respects_log_level_for_both_mesh_inputs(monkeypatch, array_mesh, log_level, expected): + from polyfempy import solve + from polyfempy.runtime import _solve_backend as backend + + calls = {} + + class FakeSolver: + def set_settings(self, settings, strict_validation): + calls["settings"] = json.loads(settings) + + def load_mesh_from_settings(self): + calls["mesh"] = "file" + + def set_mesh(self, vertices, cells): + calls["mesh"] = "array" + + def solve(self, log_level): + calls["log_level"] = log_level + return {"_result_bundle": True, "sol": np.zeros((6, 1))} + + monkeypatch.setattr(backend, "build_solver", FakeSolver) + config: dict[str, Any] = {"output": {"log": {"level": log_level}}} + if array_mesh: + solve([[0, 0], [1, 0], [0, 1]], [[0, 1, 2]], cfg=config) + else: + config["geometry"] = [{"mesh": "triangle.obj"}] + solve(cfg=config) + + assert calls["mesh"] == ("array" if array_mesh else "file") + assert calls["settings"]["output"]["log"]["level"] == log_level + assert calls["log_level"] == expected + + +def test_backend_adapter_exports_pipeline_runtime_helpers(): + from polyfempy.runtime import _solve_backend as backend + + expected = [ + "build_solver", + "configure_solver", + "apply_sidesets", + "run_solver_stage", + ] + + for name in expected: + assert hasattr(backend, name) + + +def test_solve_module_does_not_reexport_backend_helpers(): + import importlib + + pipeline = importlib.import_module("polyfempy.runtime.solve") + + for name in ( + "build_solver", + "configure_solver", + "apply_sidesets", + "run_solver_stage", + ): + assert not hasattr(pipeline, name) + + +def test_backend_adapter_no_longer_exports_legacy_context_or_retouch_helpers(): + from polyfempy.runtime import _solve_backend as backend + + assert not hasattr(backend, "SolverConfigContext") + assert not hasattr(backend, "_retouch_bc_after_mesh") + + +def test_run_solver_stage_leaves_basis_and_assembly_to_backend_solve(): + from polyfempy.runtime import _solve_backend as backend + + class FakeSolver: + def build_basis(self): + raise AssertionError("Python runtime should not call build_basis") + + def assemble(self): + raise AssertionError("Python runtime should not call assemble") + + def solve(self, log_level=None): + return {"_result_bundle": True, "log_level": log_level} + + result = backend.run_solver_stage( + FakeSolver(), + {"output": {"log": {"level": "debug"}}}, + ) + + assert result == {"_result_bundle": True, "log_level": 1} + + +def test_run_solver_stage_accepts_integer_log_level_from_config(): + from polyfempy.runtime import _solve_backend as backend + + class FakeSolver: + def solve(self, log_level=None): + return {"_result_bundle": True, "log_level": log_level} + + result = backend.run_solver_stage( + FakeSolver(), + {"output": {"log": {"level": 4}}}, + ) + + assert result == {"_result_bundle": True, "log_level": 4} + + +def test_run_solver_stage_requires_varform_solve_entry_point(): + from polyfempy.runtime import _solve_backend as backend + + class LegacyRunOnlySolver: + def run(self): + return {"_result_bundle": True} + + try: + backend.run_solver_stage(LegacyRunOnlySolver(), {}) + except RuntimeError as exc: + assert "requires solve" in str(exc) + else: + raise AssertionError("run-only legacy backends must not be accepted") + + +def test_apply_sidesets_rejects_legacy_mesh_mutation_path(): + from polyfempy.runtime import _solve_backend as backend + + try: + backend.apply_sidesets(object(), lambda *_: 1) + except NotImplementedError as exc: + assert "VarForm" in str(exc) + assert "sidesets_func" in str(exc) + else: + raise AssertionError("sidesets_func should be rejected for the VarForm runtime") + + +def test_backend_adapter_source_has_no_legacy_solver_fallbacks(): + from pathlib import Path + + source = Path("python/polyfempy/runtime/_solve_backend.py").read_text(encoding="utf-8") + + assert '"State"' not in source + assert '"run"' not in source + assert "solver.settings(settings_json" not in source + assert "solver.mesh()" not in source + assert "set_mesh_data" not in source + assert "load_mesh_from_points" not in source diff --git a/tests/test_pipeline_clean_json.py b/tests/test_pipeline_clean_json.py new file mode 100644 index 00000000..0b54908b --- /dev/null +++ b/tests/test_pipeline_clean_json.py @@ -0,0 +1,211 @@ +"""Unit tests for JSON normalization helpers in `_solve_contract`. + +Covers: + - clean_json_for_cpp: recursively drop None leaves from dicts and lists + - process_json_config: preserve common-file references and backend output keys, + resolve relative mesh paths via `root_path` + +These tests never touch the C++ backend. They only exercise pure Python stages. +""" + +from __future__ import annotations + +import copy +import sys +import tempfile +import unittest +from pathlib import Path + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime._solve_contract import ( # noqa: E402 + clean_json_for_cpp, + process_json_config, +) + + +def _canonical_path_text(path: Path) -> str: + return str(path.resolve()) + + +class CleanJsonForCppTests(unittest.TestCase): + def test_drops_top_level_none_values(self): + self.assertEqual( + clean_json_for_cpp({"a": 1, "b": None, "c": 2}), + {"a": 1, "c": 2}, + ) + + def test_drops_nested_dict_none_leaves(self): + self.assertEqual( + clean_json_for_cpp({"outer": {"x": None, "y": 2}}), + {"outer": {"y": 2}}, + ) + + def test_drops_none_items_from_lists(self): + self.assertEqual( + clean_json_for_cpp({"items": [None, 1, None, 2]}), + {"items": [1, 2]}, + ) + + def test_keeps_empty_dicts_and_lists(self): + # clean_json_for_cpp only drops *None* leaves. An empty dict / list + # is a legitimate value and must be preserved, otherwise solver blocks + # like "boundary_conditions": {} could vanish. + self.assertEqual( + clean_json_for_cpp({"empty_dict": {}, "empty_list": [], "real": None}), + {"empty_dict": {}, "empty_list": []}, + ) + + def test_preserves_zero_and_false_and_empty_string(self): + self.assertEqual( + clean_json_for_cpp({"zero": 0, "flag": False, "text": "", "skip": None}), + {"zero": 0, "flag": False, "text": ""}, + ) + + def test_does_not_mutate_input(self): + original = {"a": 1, "b": None, "nested": {"x": None}} + snapshot = copy.deepcopy(original) + clean_json_for_cpp(original) + self.assertEqual(original, snapshot) + + def test_cleans_list_items_once(self): + class OneShotDict(dict): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.items_calls = 0 + + def items(self): + self.items_calls += 1 + if self.items_calls > 1: + raise AssertionError("list item was cleaned more than once") + return super().items() + + item = OneShotDict({"keep": 1}) + + self.assertEqual(clean_json_for_cpp([item]), [{"keep": 1}]) + self.assertEqual(item.items_calls, 1) + + def test_passes_through_scalars(self): + for v in (1, 1.5, "text", True, False, 0): + with self.subTest(value=v): + self.assertEqual(clean_json_for_cpp(v), v) + + +class ProcessJsonConfigTests(unittest.TestCase): + def _base(self) -> dict: + return { + "pde": "LinearElasticity", + "output": { + "directory": "out", + "json": True, + }, + "materials": [{"type": "LinearElasticity", "E": 20, "nu": 0.3}], + } + + def test_keeps_common_reference_for_native_merge(self): + processed = process_json_config({**self._base(), "common": "shared/common.json"}) + self.assertEqual(processed["common"], "shared/common.json") + + def test_keeps_backend_output_keys(self): + processed = process_json_config(self._base()) + self.assertIn("output", processed) + self.assertEqual(processed["output"].get("directory"), "out") + self.assertTrue(processed["output"].get("json")) + + def test_leaves_output_schema_validation_to_backend(self): + payload = self._base() + payload["output"].update( + { + "future_backend_option": {"enabled": True}, + "nested_backend_option": {"mode": "raw"}, + } + ) + + processed = process_json_config(payload) + + self.assertEqual(processed["output"], payload["output"]) + + def test_does_not_mutate_input(self): + original = self._base() + snapshot = copy.deepcopy(original) + process_json_config(original) + self.assertEqual(original, snapshot) + + def test_leaves_absolute_mesh_paths_untouched(self): + d = self._base() + d["geometry"] = [{"mesh": "/abs/path/to/mesh.msh"}] + d["root_path"] = "/tmp/cfg.json" + processed = process_json_config(d) + self.assertEqual(processed["geometry"][0]["mesh"], "/abs/path/to/mesh.msh") + + def test_resolves_relative_mesh_against_root_path_dir(self): + with tempfile.TemporaryDirectory() as tmp: + cfg_dir = Path(tmp) + mesh_file = cfg_dir / "beam.msh" + mesh_file.write_text("placeholder", encoding="utf-8") + + d = self._base() + d["geometry"] = [{"mesh": "beam.msh"}] + d["root_path"] = str(cfg_dir / "config.json") + + processed = process_json_config(d) + self.assertEqual( + processed["geometry"][0]["mesh"], + _canonical_path_text(mesh_file), + ) + + def test_resolves_relative_mesh_against_sibling_meshes_dir(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case_dir = root / "case" + case_dir.mkdir() + meshes_dir = root / "meshes" + meshes_dir.mkdir() + mesh_file = meshes_dir / "beam.msh" + mesh_file.write_text("placeholder", encoding="utf-8") + + d = self._base() + d["geometry"] = [{"mesh": "beam.msh"}] + d["root_path"] = str(case_dir / "config.json") + + processed = process_json_config(d) + # Not under case_dir directly, so falls back to ../meshes/beam.msh. + self.assertEqual( + processed["geometry"][0]["mesh"], + _canonical_path_text(mesh_file), + ) + + def test_leaves_unresolvable_relative_mesh_alone(self): + d = self._base() + d["geometry"] = [{"mesh": "does_not_exist.msh"}] + d["root_path"] = "/tmp/nonexistent_dir/config.json" + processed = process_json_config(d) + # When the file cannot be located, the original mesh string is kept + # (the C++ solver will raise its own error later if that's wrong). + self.assertEqual(processed["geometry"][0]["mesh"], "does_not_exist.msh") + + def test_missing_explicit_mesh_path_does_not_pick_a_sibling_with_the_same_name(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case = root / "case" + case.mkdir() + (root / "meshes").mkdir() + (root / "meshes" / "beam.msh").touch() + for requested in ("variantB/beam.msh", "./beam.msh"): + with self.subTest(requested=requested): + cfg = {"root_path": str(case), "geometry": [{"mesh": requested}]} + self.assertEqual(process_json_config(cfg)["geometry"][0]["mesh"], requested) + + def test_handles_geometry_entries_that_are_not_dicts(self): + d = self._base() + # Non-dict entries should be ignored gracefully rather than crashing. + d["geometry"] = ["not-a-dict", {"mesh": "beam.msh"}] + d["root_path"] = "/tmp/cfg.json" + processed = process_json_config(d) + self.assertEqual(processed["geometry"][0], "not-a-dict") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pipeline_extract_outputs.py b/tests/test_pipeline_extract_outputs.py new file mode 100644 index 00000000..0293f7ee --- /dev/null +++ b/tests/test_pipeline_extract_outputs.py @@ -0,0 +1,100 @@ +"""Unit tests for converting the standard backend result bundle to Result.""" + +from __future__ import annotations + +import importlib +import sys +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime import _solve_backend as backend_module # noqa: E402 +from polyfempy.runtime import _solve_contract as contract_module # noqa: E402 + + +def _run_pipeline_from_backend_return(ret): + solve_module = importlib.import_module("polyfempy.runtime.solve") + canonical = SimpleNamespace( + config={}, + full_json=None, + mesh_source=SimpleNamespace( + mode="json", + vertices=None, + cells=None, + body_ids=None, + boundary_ids=None, + v_backend="numpy", + ), + backend_settings={}, + ) + + with ( + patch.object(contract_module, "prepare_canonical_solve_input", return_value=canonical), + patch.object(backend_module, "build_solver", return_value=object()), + patch.object(backend_module, "configure_solver", return_value=None), + patch.object(backend_module, "apply_sidesets", return_value=None), + patch.object(backend_module, "run_solver_stage", return_value=ret), + ): + return solve_module.run_pipeline(cfg={}) + + +class BackendBundleTests(unittest.TestCase): + def test_pipeline_extracts_raw_varform_solution_bundle_fields(self): + ret = { + "_result_bundle": True, + "sol": np.array([[0.0, 0.0], [0.1, 0.0], [0.0, 0.1]]), + "meta": {"from_bundle": True}, + } + + result = _run_pipeline_from_backend_return(ret) + + np.testing.assert_array_equal(result.sol, ret["sol"]) + self.assertEqual(result.meta, {"from_bundle": True}) + self.assertFalse(hasattr(result, "vertices")) + self.assertFalse(hasattr(result, "cells")) + self.assertFalse(hasattr(result, "p")) + self.assertFalse(hasattr(result, "u")) + self.assertFalse(hasattr(result, "fields")) + + def test_pipeline_rejects_legacy_pressure_bundle_field(self): + ret = { + "_result_bundle": True, + "sol": np.array([[0.0, 0.0], [0.1, 0.0], [0.0, 0.1]]), + "p": np.array([]), + } + + with self.assertRaisesRegex(RuntimeError, "legacy pressure"): + _run_pipeline_from_backend_return(ret) + + def test_pipeline_rejects_legacy_u_bundle_field(self): + ret = { + "_result_bundle": True, + "sol": np.array([[0.0, 0.0], [0.1, 0.0], [0.0, 0.1]]), + "u": np.array([[0.0, 0.0], [0.1, 0.0], [0.0, 0.1]]), + } + + with self.assertRaisesRegex(RuntimeError, "legacy u"): + _run_pipeline_from_backend_return(ret) + + def test_pipeline_rejects_non_bundle_backend_result(self): + with self.assertRaisesRegex(RuntimeError, "standard result bundle"): + _run_pipeline_from_backend_return((np.array([1.0]),)) + + def test_pipeline_rejects_bundle_missing_required_keys(self): + ret = { + "_result_bundle": True, + } + + with self.assertRaisesRegex(RuntimeError, "missing required keys: sol"): + _run_pipeline_from_backend_return(ret) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pipeline_helpers.py b/tests/test_pipeline_helpers.py new file mode 100644 index 00000000..2c66daeb --- /dev/null +++ b/tests/test_pipeline_helpers.py @@ -0,0 +1,66 @@ +"""Unit tests for small solve-contract helpers. + +Covers edges that the other pipeline tests don't exercise directly: + - _promote_materials_to_list: dict->list promotion, optional type-inference + +These tests never touch the C++ backend. They only exercise pure Python helpers. +""" + +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime._solve_contract import ( # noqa: E402 + _promote_materials_to_list, +) + + +class PromoteMaterialsToListTests(unittest.TestCase): + def test_promotes_dict_to_singleton_list(self): + payload = {"materials": {"E": 20, "nu": 0.3}} + _promote_materials_to_list(payload) + self.assertEqual(payload["materials"], [{"E": 20, "nu": 0.3}]) + + def test_leaves_list_materials_untouched(self): + payload = {"materials": [{"E": 1}, {"E": 2}]} + original = payload["materials"] + _promote_materials_to_list(payload) + self.assertIs(payload["materials"], original) + + def test_noop_when_materials_missing(self): + payload = {"pde": "LinearElasticity"} + _promote_materials_to_list(payload) + self.assertNotIn("materials", payload) + + def test_infer_type_fills_missing_type_for_linear_elasticity(self): + payload = {"pde": "LinearElasticity", "materials": {"E": 20, "nu": 0.3}} + _promote_materials_to_list(payload, infer_type_from_pde=True) + self.assertEqual(payload["materials"][0]["type"], "LinearElasticity") + + def test_infer_type_uses_laplacian_for_poisson(self): + payload = {"pde": "Poisson", "materials": {"k": 1.0}} + _promote_materials_to_list(payload, infer_type_from_pde=True) + self.assertEqual(payload["materials"][0]["type"], "Laplacian") + + def test_infer_type_does_not_override_existing_type(self): + payload = { + "pde": "Poisson", + "materials": {"type": "NeoHookean", "E": 20, "nu": 0.3}, + } + _promote_materials_to_list(payload, infer_type_from_pde=True) + self.assertEqual(payload["materials"][0]["type"], "NeoHookean") + + def test_without_infer_type_flag_no_type_is_added(self): + payload = {"pde": "LinearElasticity", "materials": {"E": 20, "nu": 0.3}} + _promote_materials_to_list(payload, infer_type_from_pde=False) + self.assertNotIn("type", payload["materials"][0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pipeline_normalize.py b/tests/test_pipeline_normalize.py new file mode 100644 index 00000000..aae29fb8 --- /dev/null +++ b/tests/test_pipeline_normalize.py @@ -0,0 +1,446 @@ +"""Pure-Python tests for cfg and mesh normalization. + +The solve path now accepts backend-shaped dicts, JSON paths, and generated +objects directly. It no longer bridges through SimulationConfig. +""" + +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime._solve_backend import configure_solver # noqa: E402 +from polyfempy.runtime._solve_contract import ( # noqa: E402 + MeshSource, + build_canonical_solver_settings, + build_full_json, + choose_mesh_source, + merge_user_cfg_over_full_json, + normalize_config as normalize_cfg, + prepare_canonical_solve_input, +) + + +_MINIMAL_FULL = { + "pde": "LinearElasticity", + "discr_order": 1, + "materials": [{"type": "LinearElasticity", "E": 20, "nu": 0.3}], + "boundary_conditions": {}, + "geometry": [{"mesh": "beam.msh"}], +} + + +class NormalizeCfgTests(unittest.TestCase): + def test_accepts_plain_dict(self): + cfg = normalize_cfg(dict(_MINIMAL_FULL)) + self.assertIsInstance(cfg, dict) + self.assertEqual(cfg["pde"], "LinearElasticity") + + def test_plain_dict_is_copied(self): + original = dict(_MINIMAL_FULL) + cfg = normalize_cfg(original) + cfg["pde"] = "Poisson" + self.assertEqual(original["pde"], "LinearElasticity") + + def test_accepts_json_file_path(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "config.json" + path.write_text(json.dumps(_MINIMAL_FULL), encoding="utf-8") + cfg = normalize_cfg(str(path)) + self.assertIsInstance(cfg, dict) + self.assertEqual(cfg["root_path"], str(path.resolve())) + + def test_accepts_generated_config_object_with_as_dict(self): + class GeneratedConfig: + def as_dict(self): + return dict(_MINIMAL_FULL) + + cfg = normalize_cfg(GeneratedConfig()) + + self.assertIsInstance(cfg, dict) + self.assertEqual(cfg["geometry"], [{"mesh": "beam.msh"}]) + + def test_none_raises_value_error(self): + with self.assertRaises(ValueError): + normalize_cfg(None) + + def test_bad_type_raises_type_error(self): + for bad in (123, 1.5, ["a"], object()): + with self.subTest(bad=type(bad).__name__): + with self.assertRaises(TypeError): + normalize_cfg(bad) + + +class BuildFullJsonTests(unittest.TestCase): + def test_returns_full_json_for_backend_dict(self): + fj = build_full_json(dict(_MINIMAL_FULL)) + assert isinstance(fj, dict) + self.assertEqual(fj["pde"], "LinearElasticity") + self.assertEqual(fj["geometry"], [{"mesh": "beam.msh"}]) + + def test_json_mode_preserves_material_dict_shape(self): + cfg = { + "pde": "LinearElasticity", + "materials": {"type": "LinearElasticity", "E": 20, "nu": 0.3}, + "geometry": [{"mesh": "beam.msh"}], + } + fj = build_full_json(cfg) + assert fj is not None + self.assertEqual( + fj["materials"], + {"type": "LinearElasticity", "E": 20, "nu": 0.3}, + ) + + def test_payload_override_wins_over_original_full_json(self): + cfg = { + "extras": {"_full_json_config": dict(_MINIMAL_FULL)}, + "discr_order": 2, + } + fj = build_full_json(cfg) + assert fj is not None + self.assertEqual(fj["discr_order"], 2) + self.assertEqual(fj["geometry"], _MINIMAL_FULL["geometry"]) + + def test_returns_none_when_no_geometry(self): + cfg = {"pde": "LinearElasticity", "materials": {"E": 2100, "nu": 0.3}} + fj = build_full_json(cfg) + self.assertIsNone(fj) + + def test_raises_when_cfg_to_dict_raises(self): + class BrokenCfg: + def to_dict(self): + raise RuntimeError("boom") + + with self.assertRaisesRegex(RuntimeError, r"cfg\.to_dict\(\) failed"): + build_full_json(BrokenCfg()) + + +class MergeUserCfgOverFullJsonTests(unittest.TestCase): + def test_python_side_keys_overlay_original_full_json(self): + full_json = dict(_MINIMAL_FULL) + merged = merge_user_cfg_over_full_json({"discr_order": 3}, full_json) + self.assertEqual(merged["discr_order"], 3) + self.assertEqual(merged["geometry"], full_json["geometry"]) + + def test_root_path_preserved_from_extras_when_present(self): + full_json = dict(_MINIMAL_FULL) + full_json["root_path"] = "/tmp/legacy" + cfg = {"extras": {"_root_path": "/tmp/new"}} + merged = merge_user_cfg_over_full_json(cfg, full_json) + self.assertEqual(merged["root_path"], "/tmp/new") + + def test_root_path_falls_back_to_full_json_when_extras_absent(self): + full_json = dict(_MINIMAL_FULL) + full_json["root_path"] = "/tmp/legacy" + merged = merge_user_cfg_over_full_json({}, full_json) + self.assertEqual(merged["root_path"], "/tmp/legacy") + + def test_raises_when_cfg_to_dict_fails(self): + class BrokenCfg: + def to_dict(self): + raise RuntimeError("boom") + + with self.assertRaisesRegex(RuntimeError, r"cfg\.to_dict\(\) failed"): + merge_user_cfg_over_full_json(BrokenCfg(), {"a": 1}) + + +class ChooseMeshSourceTests(unittest.TestCase): + def test_mesh_source_is_the_only_normalized_mesh_contract(self): + import polyfempy.runtime._solve_contract as contract + + self.assertFalse(hasattr(contract, "NormalizedInputs")) + self.assertFalse(hasattr(contract, "inputs_from_mesh_source")) + self.assertFalse(hasattr(contract, "normalize_mesh_inputs")) + + def test_array_mode_returns_numpy_arrays(self): + V = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64) + C = np.array([[0, 1, 2]], dtype=np.int64) + mesh_source = choose_mesh_source(V, C, None, dtype=None) + self.assertIsInstance(mesh_source, MeshSource) + self.assertEqual(mesh_source.mode, "array") + assert mesh_source.vertices is not None + self.assertEqual(mesh_source.vertices.shape, (3, 2)) + assert mesh_source.cells is not None + self.assertEqual(mesh_source.cells.dtype, np.int32) + self.assertEqual(mesh_source.v_backend, "numpy") + + def test_json_mode_when_full_json_has_geometry_and_no_arrays(self): + full_json = {"geometry": [{"mesh": "beam.msh"}]} + mesh_source = choose_mesh_source(None, None, full_json, dtype=None) + self.assertEqual(mesh_source.mode, "json") + self.assertIsNone(mesh_source.vertices) + self.assertIsNone(mesh_source.cells) + + def test_neither_arrays_nor_geometry_raises(self): + with self.assertRaises(ValueError): + choose_mesh_source(None, None, None, dtype=None) + with self.assertRaises(ValueError): + choose_mesh_source(None, None, {"pde": "LinearElasticity"}, dtype=None) + + def test_arrays_override_json_mode_when_both_provided(self): + V = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64) + C = np.array([[0, 1, 2]], dtype=np.int32) + full_json = {"geometry": [{"mesh": "beam.msh"}]} + mesh_source = choose_mesh_source(V, C, full_json, dtype=None) + self.assertEqual(mesh_source.mode, "array") + self.assertIsNotNone(mesh_source.vertices) + + def test_partial_array_input_raises_even_when_json_geometry_exists(self): + V = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64) + full_json = {"geometry": [{"mesh": "beam.msh"}]} + + with self.assertRaisesRegex(ValueError, "array mode requires both vertices and cells"): + choose_mesh_source(V, None, full_json, dtype=None) + + +class CanonicalSolverSettingsTests(unittest.TestCase): + def test_prepare_canonical_solve_input_for_json_mode(self): + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=dict(_MINIMAL_FULL), + dtype=None, + ) + + self.assertEqual(canonical.mesh_source.mode, "json") + self.assertEqual(canonical.metadata["mesh_source"], "json") + self.assertIn("geometry", canonical.backend_settings) + self.assertNotIn("common", canonical.backend_settings) + + def test_prepare_canonical_solve_input_for_generated_object_uses_generated_path(self): + class GeneratedConfig: + def as_dict(self): + return { + "geometry": [{"mesh": "beam.msh"}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + "solver": {"new_backend_option": False}, + } + + generated = GeneratedConfig() + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=generated, + dtype=None, + ) + + self.assertIs(canonical.config, generated) + self.assertEqual(canonical.metadata["config_source"], "generated") + self.assertEqual(canonical.mesh_source.mode, "json") + self.assertFalse(canonical.backend_settings["solver"]["new_backend_option"]) + + def test_prepare_canonical_solve_input_for_direct_array_mode(self): + cfg = {"pde": "LinearElasticity", "materials": {"E": 20.0, "nu": 0.3}} + V = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64) + C = np.array([[0, 1, 2]], dtype=np.int64) + + canonical = prepare_canonical_solve_input( + vertices=V, + cells=C, + cfg=cfg, + dtype=None, + ) + + self.assertEqual(canonical.mesh_source.mode, "array") + self.assertEqual(canonical.metadata["mesh_source"], "array") + assert canonical.mesh_source.cells is not None + self.assertEqual(canonical.mesh_source.cells.dtype, np.int32) + self.assertEqual(canonical.backend_settings["geometry"][0]["type"], "ground") + self.assertEqual(canonical.backend_settings["materials"][0]["type"], "LinearElasticity") + + def test_array_mode_leaves_output_schema_validation_to_backend(self): + V = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]], dtype=np.float64) + C = np.array([[0, 1, 2]], dtype=np.int64) + output = { + "directory": "out", + "future_backend_option": {"enabled": True}, + } + cfg = { + "pde": "LinearElasticity", + "materials": {"E": 20.0, "nu": 0.3}, + "output": output, + } + + canonical = prepare_canonical_solve_input( + vertices=V, + cells=C, + cfg=cfg, + dtype=None, + ) + + self.assertEqual(canonical.backend_settings["output"], output) + + def test_prepare_canonical_solve_input_for_guided_array_mode(self): + cfg = { + "pde": "LinearElasticity", + "materials": {"E": 20.0, "nu": 0.3}, + "extras": { + "_mesh_array_mode": { + "vertices": np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]), + "cells": np.array([[0, 1, 2]], dtype=np.int32), + "body_ids": np.array([3], dtype=np.int32), + } + }, + } + + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=cfg, + dtype=None, + ) + + self.assertEqual(canonical.mesh_source.mode, "guided_array") + self.assertEqual(canonical.metadata["mesh_source"], "guided_array") + np.testing.assert_array_equal(canonical.mesh_source.body_ids, np.array([3], dtype=np.int32)) + self.assertNotIn("extras", canonical.backend_settings) + + def test_guided_array_placeholder_is_removed_from_backend_settings(self): + cfg = { + "pde": "LinearElasticity", + "geometry": [{"mesh": "__array_body__:beam"}], + "materials": {"E": 20.0, "nu": 0.3}, + } + mesh_source = MeshSource( + mode="guided_array", + vertices=np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]), + cells=np.array([[0, 1, 2]], dtype=np.int32), + body_ids=np.array([1], dtype=np.int32), + boundary_ids=None, + v_backend="numpy", + ) + + settings = build_canonical_solver_settings( + cfg, + full_json=None, + mesh_source=mesh_source, + ) + + self.assertNotIn("__array_body__", json.dumps(settings)) + self.assertEqual( + settings["geometry"], + [{"type": "ground", "height": 0.0, "enabled": True, "is_obstacle": False}], + ) + self.assertIsInstance(settings["materials"], list) + + def test_generated_config_preserves_supported_output_log_level(self): + from polyfempy.generated_api import generated_api as polyfem + + cfg = polyfem.config( + materials=[ + polyfem.linear_elasticity( + E=20.0, + nu=0.3, + id=1, + ) + ], + geometry=[ + polyfem.mesh( + mesh="beam.msh", + ) + ], + output=polyfem.output( + log=polyfem.output_log( + level=4, + ) + ), + ) + + canonical = prepare_canonical_solve_input( + vertices=None, + cells=None, + cfg=cfg, + dtype=None, + ) + + assert canonical.full_json is not None + self.assertEqual(canonical.full_json["output"]["log"]["level"], 4) + self.assertEqual(canonical.backend_settings["output"]["log"]["level"], 4) + + +class ConfigureSolverContractTests(unittest.TestCase): + def test_array_configure_uses_prebuilt_backend_settings(self): + class FakeSolver: + def __init__(self): + self.settings_json = None + self.strict_validation = None + self.mesh_args = None + + def set_settings(self, settings_json, strict_validation=False): + self.settings_json = settings_json + self.strict_validation = strict_validation + + def set_mesh(self, vertices, cells): + self.mesh_args = (vertices, cells) + + mesh_source = MeshSource( + mode="guided_array", + vertices=np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]), + cells=np.array([[0, 1, 2]], dtype=np.int32), + body_ids=None, + boundary_ids=None, + v_backend="numpy", + ) + backend_settings = { + "pde": "LinearElasticity", + "geometry": [{"type": "ground", "height": 0.0, "enabled": True, "is_obstacle": False}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + } + solver = FakeSolver() + + configure_solver( + solver, + {}, + full_json=None, + mesh_source=mesh_source, + backend_settings=backend_settings, + ) + + assert solver.settings_json is not None + self.assertNotIn("__array_body__", solver.settings_json) + self.assertIs(solver.strict_validation, True) + assert solver.mesh_args is not None + self.assertEqual(solver.mesh_args[1].dtype, np.int32) + + def test_array_configure_rejects_python_side_mesh_ids_for_varform_runtime(self): + class FakeSolver: + def set_settings(self, settings_json, strict_validation=False): + pass + + def set_mesh(self, vertices, cells): + pass + + mesh_source = MeshSource( + mode="guided_array", + vertices=np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]), + cells=np.array([[0, 1, 2]], dtype=np.int32), + body_ids=np.array([1], dtype=np.int32), + boundary_ids=None, + v_backend="numpy", + ) + + with self.assertRaisesRegex(NotImplementedError, "body_ids"): + configure_solver( + FakeSolver(), + {}, + full_json=None, + mesh_source=mesh_source, + backend_settings={ + "pde": "LinearElasticity", + "geometry": [{"type": "ground", "height": 0.0}], + "materials": [{"type": "LinearElasticity", "E": 20.0, "nu": 0.3}], + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_pipeline_outputs.py b/tests/test_pipeline_outputs.py new file mode 100644 index 00000000..1babb44a --- /dev/null +++ b/tests/test_pipeline_outputs.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from pathlib import Path + + +def test_removed_output_adapter_module_is_absent(): + package_dir = Path(__file__).resolve().parents[1] / "python" / "polyfempy" + + assert not (package_dir / "runtime" / "_solve_outputs.py").exists() + + +def test_solve_module_does_not_reexport_output_helpers(): + import importlib + + pipeline = importlib.import_module("polyfempy.runtime.solve") + + assert not hasattr(pipeline, "NativeOutputs") + assert not hasattr(pipeline, "extract_native_outputs") + assert not hasattr(pipeline, "populate_sampled_history") + assert not hasattr(pipeline, "apply_sampled_vtu_fallback") + assert not hasattr(pipeline, "finalize_result") diff --git a/tests/test_polyfem_builder.py b/tests/test_polyfem_builder.py new file mode 100644 index 00000000..f4b43590 --- /dev/null +++ b/tests/test_polyfem_builder.py @@ -0,0 +1,1123 @@ +"""PolyFEM handle, ID and JSON export behavior of the generated builder.""" +import importlib +import json +from pathlib import Path +import sys +import tempfile +import unittest + +from polyfempy._selection_refs import SelectionPool +from polyfempy._model_builder import SelectionHandle +from polyfempy.generated_api import generated_api +from polyfempy.generated_api.generated_api import ModelBuilder + +ROOT = Path(__file__).resolve().parents[1] +RULES = json.loads((ROOT / "generator-config/builder.json").read_text())["builder"] +GENERATED_GROUPS = json.loads(Path(generated_api.__file__).with_name("builder_api_manifest.json").read_text())["namespaces"] + + +def manifest_tools(): + from unittest.mock import patch + with patch.object(sys, "path", [str(ROOT / "python-from-jse"), *sys.path]): + return importlib.import_module("generator.model_builder") + + +def make_builder(api, **kwargs): + return ModelBuilder(api, namespaces=GENERATED_GROUPS, **kwargs) + + +def _generator_helpers(): + import importlib.util + helper = ROOT / "python-from-jse/tests/generator_test_helpers.py" + spec = importlib.util.spec_from_file_location("polyfem_generator_test_helpers", helper) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class ProjectApiGenerationTests(unittest.TestCase): + def test_model_geometry_methods_follow_new_spec_types(self): + generator = _generator_helpers().import_generator("json_to_tree_new_geometry") + root = generator.build_tree([ + {"pointer": "/", "type": "object", "required": ["geometry"]}, + {"pointer": "/geometry", "type": "list"}, + { + "pointer": "/geometry/*", "type": "object", "type_name": "VoxelMesh", + "required": ["type", "mesh"], "optional": ["is_obstacle"], + }, + {"pointer": "/geometry/*/type", "type": "string", "options": ["VoxelMesh"]}, + {"pointer": "/geometry/*/mesh", "type": "string"}, + {"pointer": "/geometry/*/is_obstacle", "type": "bool"}, + ]) + generated = _generator_helpers().module_from_generated_text(generator.generated_class_text(root)) + api = _generator_helpers().module_from_generated_api_text(generator.generated_api_text(root, {"builder": RULES}), generated.Root) + model = api.model(relationships=[], selection_helper_rules={}, namespaces=GENERATED_GROUPS) + model.voxel_mesh(mesh="grid.mesh", is_obstacle=True) + self.assertEqual( + [api.voxel_mesh(mesh="grid.mesh", is_obstacle=True).as_dict()], + model.config().as_dict()["geometry"], + ) + + def test_generated_api_exposes_model_builder_factory(self): + generator = _generator_helpers().import_generator("json_to_tree_generated_api_model_builder") + root = generator.build_tree([ + { + "pointer": "/", + "type": "object", + "required": ["geometry", "materials"], + }, + { + "pointer": "/geometry", + "type": "list", + }, + { + "pointer": "/geometry/*", + "type": "object", + "type_name": "Mesh", + "required": ["type", "mesh"], + "optional": ["volume_selection"], + }, + { + "pointer": "/geometry/*/type", + "type": "string", + "options": ["mesh"], + }, + { + "pointer": "/geometry/*/mesh", + "type": "string", + }, + { + "pointer": "/geometry/*/volume_selection", + "type": "int", + }, + { + "pointer": "/materials", + "type": "list", + }, + { + "pointer": "/materials/*", + "type": "object", + "type_name": "NeoHookean", + "required": ["type", "E", "nu"], + "optional": ["id"], + }, + { + "pointer": "/materials/*/type", + "type": "string", + "options": ["NeoHookean"], + }, + { + "pointer": "/materials/*/E", + "type": "float", + }, + { + "pointer": "/materials/*/nu", + "type": "float", + }, + { + "pointer": "/materials/*/id", + "type": "int", + }, + ]) + generated_module = _generator_helpers().module_from_generated_text(generator.generated_class_text(root)) + api_module = _generator_helpers().module_from_generated_api_text( + generator.generated_api_text(root, {"builder": RULES}), + generated_module.Root, + ) + + relationships = [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "materials[*].id", + "builder_api": "body.material", + "status": "required", + } + ] + model = api_module.model(relationships=relationships, namespaces=GENERATED_GROUPS) + body = model.mesh(mesh="beam.msh") + body.material(api_module.neo_hookean(E=20.0, nu=0.45)) + + explicit_cfg = api_module.config( + geometry=model.geometry(), + materials=model.materials(), + ) + cfg = api_module.config(model=model) + + self.assertIs(model.__class__, api_module.ModelBuilder) + self.assertEqual(explicit_cfg.as_dict(), cfg.as_dict()) + self.assertEqual(1, cfg.as_dict()["geometry"][0]["volume_selection"]) + self.assertEqual(1, cfg.as_dict()["materials"][0]["id"]) + self.assertNotIn("uuid", repr(cfg.as_dict())) + + new_model = api_module.model(relationships=relationships, namespaces=GENERATED_GROUPS) + new_body = api_module.body(model=new_model) + mesh_descriptor = api_module.mesh(mesh="beam.msh") + new_body.mesh(mesh_descriptor) + new_body.material(api_module.neo_hookean(E=20.0, nu=0.45)) + new_cfg = api_module.config(model=new_model) + + self.assertEqual(cfg.as_dict(), new_cfg.as_dict()) + self.assertNotIn("volume_selection", mesh_descriptor.as_dict()) + + +class FakeGeneratedApi: + __file__: str + + def config(self, **kwargs): + return dict(kwargs) + + def mesh(self, **kwargs): + return dict(kwargs) + + def neo_hookean(self, **kwargs): + result = {"type": "NeoHookean"} + result.update(kwargs) + return result + + +class FakeGeneratedObject: + def __init__(self, payload): + self._payload = dict(payload) + + def as_dict(self): + return dict(self._payload) + + +POLYFEM_RELATIONSHIPS = [ + { + "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.neumann_boundary[*].id", + "builder_api": "point.neumann", + "status": "required", + }, +] +POLYFEM_SELECTION_HELPER_RULES = { + "surface_axis": { + "namespace": "surface", + "field": "surface_selection", + "allowed_fields": ("id", "axis", "position"), + }, + "point_box": { + "namespace": "point", + "field": "point_selection", + "allowed_fields": ("id", "box"), + }, +} + + +class SelectionPoolTests(unittest.TestCase): + def test_selection_pool_allocates_uuid_and_namespace_backend_ids(self): + pool = SelectionPool(GENERATED_GROUPS) + + volume = pool.allocate("volume", name="body") + surface = pool.allocate("surface", name="fixed") + second_volume = pool.allocate("volume", name="other") + + self.assertEqual("volume", volume.namespace) + self.assertEqual(1, volume.backend_id) + self.assertEqual(1, surface.backend_id) + self.assertEqual(2, second_volume.backend_id) + self.assertNotEqual(volume.uuid, surface.uuid) + + +class ModelBuilderTests(unittest.TestCase): + def test_existing_geometry_rule_ids_are_reserved(self): + model = make_builder( + FakeGeneratedApi(), relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + model.mesh( + mesh="tagged.msh", + volume_selection=[{"id": 4, "axis": 1, "position": 0}], + point_selection=[{"id": 8, "box": [[0, 0], [1, 1]]}], + ) + body = model.mesh(mesh="auto.msh") + body.material({"type": "NeoHookean", "E": 1000, "nu": 0.3}) + body.surface_all().dirichlet(value=[0, 0]) + self.assertGreater(model.geometry()[1]["volume_selection"], 4) + self.assertGreater(model.geometry()[1]["surface_selection"], 8) + + def test_repeated_selection_does_not_duplicate_geometry_rules(self): + model = make_builder( + FakeGeneratedApi(), relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="part.msh") + first = body.surface_axis(axis=1, position=0) + second = body.surface_axis(axis=1, position=0) + assert isinstance(first, SelectionHandle) + assert isinstance(second, SelectionHandle) + self.assertEqual(first.selection_ref.backend_id, second.selection_ref.backend_id) + self.assertEqual(1, len(model.geometry()[0]["surface_selection"])) + whole_body = model.mesh(mesh="whole.msh") + first = whole_body.dirichlet(value=[0, 0]) + second = whole_body.surface_all() + assert isinstance(first, SelectionHandle) + self.assertEqual(first.selection_ref.backend_id, second.selection_ref.backend_id) + + def test_bind_rejects_foreign_refs_with_a_shared_pool(self): + pool = SelectionPool(GENERATED_GROUPS) + models = [ + make_builder( + FakeGeneratedApi(), relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules={}, selection_pool=pool, + ) + for _ in range(2) + ] + foreign = models[0].mesh(mesh="foreign.msh").surface_all() + local = models[1].mesh(mesh="local.msh").surface_all() + before = models[1].config() + with self.assertRaisesRegex(ValueError, "this model"): + models[1].bind("surface.dirichlet", foreign.selection_ref, {"value": [1, 0]}) + self.assertEqual(before, models[1].config()) + models[1].bind("surface.dirichlet", local.selection_ref, {"value": [0, 0]}) + self.assertEqual( + local.selection_ref.backend_id, + models[1].boundary_conditions()["dirichlet_boundary"][0]["id"], + ) + + def test_boundary_settings_persist_and_keep_the_dictionary_api(self): + model = make_builder( + FakeGeneratedApi(), relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules={}, + ) + model.mesh(mesh="part.msh").surface_all().dirichlet(value=[0, 0]) + boundary = model.boundary_conditions(rhs=[0, -1]) + self.assertIsInstance(boundary, dict) + self.assertEqual(boundary, model.config()["boundary_conditions"]) + self.assertEqual(model.config(), model.config(boundary_conditions=boundary)) + self.assertEqual(1, len(model.config()["boundary_conditions"]["dirichlet_boundary"])) + model.boundary_conditions(rhs=[0, -2]) + self.assertEqual([0, -2], model.config()["boundary_conditions"]["rhs"]) + + def test_config_does_not_save_one_time_boundary_settings(self): + model = make_builder( + FakeGeneratedApi(), relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules={}, + ) + before = model.config() + self.assertEqual([0, -1], model.config(rhs=[0, -1])["boundary_conditions"]["rhs"]) + self.assertEqual(before, model.config()) + self.assertEqual({}, model.boundary_conditions()) + + def test_boundary_conflict_does_not_replace_previous_settings(self): + relationships = [{ + "namespace": "volume", "producer": "geometry[*].volume_selection", + "consumer": "boundary_conditions.rhs[*].id", "builder_api": "body.rhs", + "status": "required", + }] + model = make_builder( + FakeGeneratedApi(), relationships=relationships, selection_helper_rules={}, + ) + model.mesh(mesh="part.msh").rhs(value=[0, -1]) + before = model.config() + with self.assertRaises(TypeError): + model.boundary_conditions(rhs=[0, -2]) + self.assertEqual(before, model.config()) + + def test_model_builder_loads_relationships_from_api_adjacent_manifest(self): + + with tempfile.TemporaryDirectory() as tmpdir: + api = FakeGeneratedApi() + api.__file__ = str(Path(tmpdir) / "generated_api.py") + (Path(tmpdir) / "builder_api_manifest.json").write_text( + json.dumps({ + "version": 1, + "model_entry": "polyfem.model", + "relationships": [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "materials[*].id", + "builder_api": "body.material", + } + ], + }), + encoding="utf-8", + ) + + model = make_builder(api, selection_helper_rules={}) + body = model.mesh(mesh="beam.msh") + body.material(api.neo_hookean(E=20.0, nu=0.45)) + + self.assertEqual( + [{"type": "NeoHookean", "E": 20.0, "nu": 0.45, "id": 1}], + model.materials(), + ) + + def test_model_builder_loads_selection_helpers_from_api_adjacent_manifest(self): + + with tempfile.TemporaryDirectory() as tmpdir: + api = FakeGeneratedApi() + api.__file__ = str(Path(tmpdir) / "generated_api.py") + generated_dir = Path(tmpdir) + (generated_dir / "builder_api_manifest.json").write_text( + json.dumps({ + "version": 1, + "model_entry": "polyfem.model", + "relationships": [ + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.dirichlet_boundary[*].id", + "builder_api": "surface.dirichlet", + } + ], + }), + encoding="utf-8", + ) + (generated_dir / "class_tree_manifest.json").write_text( + json.dumps([ + { + "class_path": "Root.Geometry.Mesh.Surface_selection", + "params": ["axis"], + }, + { + "class_path": "Root.Geometry.Mesh.Surface_selection.Axis", + "schema_path": "geometry[*].surface_selection", + "variant": "axis", + "params": ["id", "axis", "position"], + }, + ]), + encoding="utf-8", + ) + + # Runtime reads the validated rules shipped in the builder manifest. + manifest_file = generated_dir / "builder_api_manifest.json" + manifest = json.loads(manifest_file.read_text()) + class_tree = json.loads((generated_dir / "class_tree_manifest.json").read_text()) + manifest["selection_rules"] = manifest_tools().selection_helper_rules_from_manifest( + class_tree, manifest["relationships"], + ) + manifest_file.write_text(json.dumps(manifest)) + model = make_builder(api) + body = model.mesh(mesh="beam.msh") + body.surface_axis(axis=1, position=0.5).dirichlet(value=[0, 0]) + + self.assertEqual( + {"dirichlet_boundary": [{"value": [0, 0], "id": 1}]}, + model.boundary_conditions(), + ) + + def test_body_material_uses_relationship_map_and_exports_backend_ids_only(self): + api = FakeGeneratedApi() + model = make_builder( + api, + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + + body = model.mesh(mesh="beam.msh") + material = api.neo_hookean(E=20.0, nu=0.45) + body.material(material) + + self.assertEqual( + [{"mesh": "beam.msh", "volume_selection": 1}], + model.geometry(), + ) + self.assertEqual( + [{"type": "NeoHookean", "E": 20.0, "nu": 0.45, "id": 1}], + model.materials(), + ) + self.assertNotIn("uuid", repr(model.geometry())) + self.assertNotIn("uuid", repr(model.materials())) + self.assertNotIn("name", repr(model.geometry())) + self.assertNotIn("name", repr(model.materials())) + + def test_body_methods_are_provided_from_relationship_map(self): + relationships = [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "materials[*].id", + "builder_api": "body.alt_material", + "status": "required", + } + ] + model = make_builder(FakeGeneratedApi(), relationships=relationships) + body = model.mesh(mesh="beam.msh") + + body.alt_material({"type": "NeoHookean", "E": 20.0, "nu": 0.45}) + + self.assertEqual( + [{"type": "NeoHookean", "E": 20.0, "nu": 0.45, "id": 1}], + model.materials(), + ) + + def test_material_binding_does_not_mutate_user_material_object(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="beam.msh") + material = {"type": "NeoHookean", "E": 20.0, "nu": 0.45} + + body.material(material) + + self.assertEqual({"type": "NeoHookean", "E": 20.0, "nu": 0.45}, material) + self.assertEqual(1, model.materials()[0]["id"]) + + def test_material_binding_accepts_generated_object_payload(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="beam.msh") + material = FakeGeneratedObject({"type": "NeoHookean", "E": 20.0, "nu": 0.45}) + + body.material(material) + + self.assertEqual( + [{"type": "NeoHookean", "E": 20.0, "nu": 0.45, "id": 1}], + model.materials(), + ) + + def test_body_velocity_uses_volume_relationship_and_exports_initial_conditions(self): + relationships = [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "initial_conditions.velocity[*].id", + "builder_api": "body.velocity", + "status": "required", + } + ] + model = make_builder(FakeGeneratedApi(), relationships=relationships) + body = model.mesh(mesh="beam.msh") + + body.velocity({"value": [67.0, 0.0]}) + + self.assertEqual( + {"velocity": [{"value": [67.0, 0.0], "id": 1}]}, + model.initial_conditions(), + ) + self.assertNotIn("uuid", repr(model.initial_conditions())) + self.assertNotIn("name", repr(model.initial_conditions())) + + def test_default_body_initial_condition_methods_export_volume_ids(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="beam.msh") + + body.solution({"value": [0.0, 0.0]}) + body.velocity({"value": [67.0, 0.0]}) + body.acceleration({"value": [0.0, 0.0]}) + + self.assertEqual( + { + "solution": [{"value": [0.0, 0.0], "id": 1}], + "velocity": [{"value": [67.0, 0.0], "id": 1}], + "acceleration": [{"value": [0.0, 0.0], "id": 1}], + }, + model.initial_conditions(), + ) + + def test_default_body_discr_order_exports_space_volume_id(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + model.mesh(mesh="sphere.msh") + wall = model.mesh(mesh="cube.msh") + + wall.discr_order(order=2) + + self.assertEqual( + {"discr_order": [{"order": 2, "id": 2}]}, + model.space(), + ) + self.assertEqual( + [ + {"mesh": "sphere.msh"}, + {"mesh": "cube.msh", "volume_selection": 2}, + ], + model.geometry(), + ) + + def test_explicit_volume_selection_is_reused_for_material_id(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + + body = model.mesh(mesh="beam.msh", volume_selection=7) + body.material({"type": "NeoHookean", "E": 20.0, "nu": 0.45}) + next_body = model.mesh(mesh="other.msh") + + self.assertEqual(7, model.geometry()[0]["volume_selection"]) + self.assertEqual(7, model.materials()[0]["id"]) + assert next_body.volume_ref is not None + self.assertEqual(8, next_body.volume_ref.backend_id) + + def test_surface_axis_selection_binds_boundary_conditions(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + wall = model.mesh(mesh="wall.obj") + + fixed = wall.surface_axis(axis=1, position=0.1025) + loaded = wall.surface_axis(axis=-1, position=-0.1025) + fixed.dirichlet(value=[0, 0]) + loaded.neumann(value=[0, -10]) + loaded.normal_aligned_neumann(value=5) + loaded.pressure(value=100) + loaded.pressure_cavity(value=200) + loaded.obstacle_displacement(value=[0, 0]) + + self.assertEqual( + [ + { + "mesh": "wall.obj", + "surface_selection": [ + {"id": 1, "axis": 1, "position": 0.1025}, + {"id": 2, "axis": -1, "position": -0.1025}, + ], + } + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 1}], + "neumann_boundary": [{"value": [0, -10], "id": 2}], + "normal_aligned_neumann_boundary": [{"value": 5, "id": 2}], + "pressure_boundary": [{"value": 100, "id": 2}], + "pressure_cavity": [{"value": 200, "id": 2}], + "obstacle_displacements": [{"value": [0, 0], "id": 2}], + }, + model.boundary_conditions(), + ) + + def test_unbound_geometry_mesh_can_create_surface_selection_without_volume_id(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + wall = model.mesh(mesh="wall.obj") + + fixed = wall.surface_all(id=3) + fixed.dirichlet(value=[0, 0]) + + self.assertEqual( + [ + { + "mesh": "wall.obj", + "surface_selection": 3, + } + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 3}], + }, + model.boundary_conditions(), + ) + + def test_selection_helper_can_preserve_single_object_shape(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + wall = model.mesh(mesh="wall.obj") + + fixed = wall.surface_axis( + id=3, + axis="-y", + position=1e-05, + append=False, + ) + fixed.dirichlet(value=[0, 0]) + + self.assertEqual( + [ + { + "mesh": "wall.obj", + "surface_selection": { + "id": 3, + "axis": "-y", + "position": 1e-05, + }, + } + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 3}], + }, + model.boundary_conditions(), + ) + + def test_matching_surface_helpers_on_different_meshes_bind_independently(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + ball = model.mesh(mesh="ball.obj") + wall = model.mesh(mesh="wall.obj") + + ball_fixed = ball.surface_axis(axis=1, position=0.1025) + wall_fixed = wall.surface_axis(axis=1, position=0.1025) + ball_fixed.dirichlet(value=[0, 0]) + wall_fixed.dirichlet(value=[1, 0]) + + self.assertEqual( + [ + { + "mesh": "ball.obj", + "surface_selection": [ + {"id": 1, "axis": 1, "position": 0.1025}, + ], + }, + { + "mesh": "wall.obj", + "surface_selection": [ + {"id": 2, "axis": 1, "position": 0.1025}, + ], + }, + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 1}, {"value": [1, 0], "id": 2}], + }, + model.boundary_conditions(), + ) + + def test_point_selection_uses_same_boundary_id_pool_as_surface_selection(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="body.obj") + + side = body.surface_axis(axis=1, position=0.5) + pin = body.point_box(box=[[0.1, 2, -10], [1, 10, 10]]) + side.dirichlet(value=[0, 0]) + pin.neumann(value=[0, -10]) + + self.assertEqual( + [ + { + "mesh": "body.obj", + "surface_selection": [ + {"id": 1, "axis": 1, "position": 0.5}, + ], + "point_selection": [ + {"id": 2, "box": [[0.1, 2, -10], [1, 10, 10]]}, + ], + } + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 1}], + "neumann_boundary": [{"value": [0, -10], "id": 2}], + }, + model.boundary_conditions(), + ) + + def test_selection_helpers_are_loaded_from_class_tree_manifest(self): + manifest = [ + { + "class_path": "Root.Geometry.Mesh.Surface_selection", + "params": ["ring"], + }, + { + "class_path": "Root.Geometry.Mesh.Surface_selection.Ring", + "schema_path": "geometry[*].surface_selection", + "variant": "ring", + "params": ["id", "radius", "relative"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection", + "params": ["list"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection.List", + "params": ["ring"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection.List.Ring", + "schema_path": "geometry[*].point_selection[*]", + "variant": "ring", + "params": ["id", "radius", "relative"], + }, + ] + selection_helper_rules = manifest_tools().selection_helper_rules_from_manifest( + manifest, POLYFEM_RELATIONSHIPS + ) + self.assertEqual( + "Root.Geometry.Mesh.Surface_selection.Ring", + selection_helper_rules["surface_ring"]["class_path"], + ) + self.assertEqual( + "Root.Geometry.Mesh.Point_selection.List.Ring", + selection_helper_rules["point_ring"]["class_path"], + ) + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=selection_helper_rules, + ) + body = model.mesh(mesh="body.obj") + + surface = body.surface_ring(radius=0.01) + point = body.point_ring(radius=0.02) + surface.dirichlet(value=[0, 0]) + point.neumann(value=[0, -10]) + + self.assertEqual( + [ + { + "mesh": "body.obj", + "surface_selection": [ + {"id": 1, "radius": 0.01}, + ], + "point_selection": [ + {"id": 2, "radius": 0.02}, + ], + } + ], + model.geometry(), + ) + self.assertEqual( + { + "dirichlet_boundary": [{"value": [0, 0], "id": 1}], + "neumann_boundary": [{"value": [0, -10], "id": 2}], + }, + model.boundary_conditions(), + ) + + def test_builder_api_manifest_is_generated_from_relationships_and_class_tree(self): + relationships = [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "materials[*].id", + "builder_api": "body.material", + "status": "required", + }, + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.dirichlet_boundary[*].id", + "builder_api": "surface.dirichlet", + "status": "required", + }, + { + "namespace": "point", + "producer": "geometry[*].point_selection", + "consumer": "boundary_conditions.neumann_boundary[*].id", + "builder_api": "point.neumann", + "status": "required", + }, + ] + class_tree_manifest = [ + { + "class_path": "Root.Geometry.Mesh.Surface_selection", + "params": ["axis"], + }, + { + "class_path": "Root.Geometry.Mesh.Surface_selection.Axis", + "schema_path": "geometry[*].surface_selection", + "variant": "axis", + "params": ["id", "axis", "position"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection", + "params": ["list"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection.List", + "params": ["axis"], + }, + { + "class_path": "Root.Geometry.Mesh.Point_selection.List.Axis", + "schema_path": "geometry[*].point_selection[*]", + "variant": "axis", + "params": ["id", "axis", "position"], + }, + ] + + manifest = manifest_tools().builder_api_manifest_from_inputs( + relationships, + class_tree_manifest, rules=RULES, + ) + + self.assertEqual("generated_api.model", manifest["model_entry"]) + self.assertEqual(["material"], manifest["body_methods"]) + self.assertEqual(["dirichlet"], manifest["selection_methods"]["surface"]) + self.assertEqual(["neumann"], manifest["selection_methods"]["point"]) + self.assertEqual(["surface_axis"], manifest["selection_helpers"]["surface"]) + self.assertEqual(["point_axis"], manifest["selection_helpers"]["point"]) + self.assertEqual( + ["boundary_conditions", "materials"], + manifest["config_auto_sections"], + ) + + def test_builder_api_manifest_accepts_project_model_entry_override(self): + + manifest = manifest_tools().builder_api_manifest_from_inputs( + [], + [], + model_entry="polyfem.model", + ) + + self.assertEqual("polyfem.model", manifest["model_entry"]) + + def test_model_config_collects_builder_sections_and_rhs(self): + api = FakeGeneratedApi() + model = make_builder( + api, + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.mesh(mesh="beam.msh") + body.material(api.neo_hookean(E=20.0, nu=0.45)) + body.velocity({"value": [67.0, 0.0]}) + body.surface_axis(axis=1, position=0.5).dirichlet(value=[0, 0]) + + cfg = model.config( + rhs=[0, 0], + time_tend=0.004, + time_dt=2e-05, + ) + + self.assertEqual( + [ + { + "mesh": "beam.msh", + "volume_selection": 1, + "surface_selection": [ + {"id": 1, "axis": 1, "position": 0.5}, + ], + } + ], + cfg["geometry"], + ) + self.assertEqual( + [{"type": "NeoHookean", "E": 20.0, "nu": 0.45, "id": 1}], + cfg["materials"], + ) + self.assertEqual( + { + "rhs": [0, 0], + "dirichlet_boundary": [{"value": [0, 0], "id": 1}], + }, + cfg["boundary_conditions"], + ) + self.assertEqual( + {"velocity": [{"value": [67.0, 0.0], "id": 1}]}, + cfg["initial_conditions"], + ) + self.assertEqual(0.004, cfg["time_tend"]) + self.assertEqual(2e-05, cfg["time_dt"]) + self.assertNotIn("output", cfg) + self.assertNotIn("solver", cfg) + + def test_body_mesh_matches_legacy_model_mesh_without_mutating_descriptor(self): + api = FakeGeneratedApi() + + legacy_model = make_builder( + api, + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + legacy_body = legacy_model.mesh(mesh="beam.msh") + legacy_body.material(api.neo_hookean(E=20.0, nu=0.45)) + legacy_body.surface_axis(axis=1, position=0.5).dirichlet(value=[0, 0]) + legacy_cfg = legacy_model.config(rhs=[0, 0]) + + new_model = make_builder( + api, + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + mesh_descriptor = api.mesh(mesh="beam.msh") + body = new_model.body() + body.mesh(mesh_descriptor) + body.material(api.neo_hookean(E=20.0, nu=0.45)) + body.surface_axis(axis=1, position=0.5).dirichlet(value=[0, 0]) + new_model.rhs([0, 0]) + new_cfg = new_model.config() + + self.assertEqual(legacy_cfg, new_cfg) + self.assertEqual({"mesh": "beam.msh"}, mesh_descriptor) + + def test_body_requires_mesh_before_body_or_surface_bindings(self): + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + body = model.body() + + with self.assertRaisesRegex(ValueError, "body.mesh"): + body.material({"type": "NeoHookean", "E": 20.0, "nu": 0.45}) + with self.assertRaisesRegex(ValueError, "body.mesh"): + body.surface_all(id=1) + + def test_model_config_preserves_explicit_solver(self): + explicit_solver = {"linear": {"solver": "custom"}} + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + + cfg = model.config(solver=explicit_solver) + + self.assertIs(explicit_solver, cfg["solver"]) + + def test_model_config_preserves_explicit_output(self): + explicit_output = {"json": "custom.json"} + model = make_builder( + FakeGeneratedApi(), + relationships=POLYFEM_RELATIONSHIPS, + selection_helper_rules=POLYFEM_SELECTION_HELPER_RULES, + ) + + cfg = model.config(output=explicit_output) + + self.assertIs(explicit_output, cfg["output"]) + + def test_model_config_collects_sections_from_relationship_consumers(self): + relationships = [ + { + "namespace": "volume", + "producer": "geometry[*].volume_selection", + "consumer": "constraints.some_constraint[*].id", + "builder_api": "body.constraint", + "status": "required", + } + ] + model = make_builder( + FakeGeneratedApi(), + relationships=relationships, + ) + body = model.mesh(mesh="beam.msh") + + body.constraint({"value": "fixed"}) + cfg = model.config() + + self.assertEqual( + {"some_constraint": [{"value": "fixed", "id": 1}]}, + cfg["constraints"], + ) + + def test_missing_body_material_relationship_reports_clear_error(self): + relationships = [ + { + "namespace": "surface", + "producer": "geometry[*].surface_selection", + "consumer": "boundary_conditions.dirichlet_boundary[*].id", + "builder_api": "surface.dirichlet", + "status": "required", + } + ] + model = make_builder(FakeGeneratedApi(), relationships=relationships) + body = model.mesh(mesh="beam.msh") + + with self.assertRaisesRegex(AttributeError, "body.material"): + body.material({"type": "NeoHookean", "E": 20.0, "nu": 0.45}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_release_checks.py b/tests/test_release_checks.py new file mode 100644 index 00000000..082f1c50 --- /dev/null +++ b/tests/test_release_checks.py @@ -0,0 +1,82 @@ +"""Protect against broken GitHub links and incomplete release archives.""" + +from pathlib import Path +import subprocess + +import pytest + +from tools.check_docs import check_markdown, headings +from tools.check_distribution import PACKAGE_FILES, SOURCE_FILES, check_files + + +def test_submodule_file_exists_but_relative_github_link_is_rejected(tmp_path): + examples = tmp_path / "examples" + examples.mkdir() + (examples / "beam.py").write_text("pass\n") + readme = tmp_path / "README.md" + readme.write_text("[Beam](examples/beam.py)\n") + with pytest.raises(ValueError, match="pinned GitHub URL"): + check_markdown(readme, tmp_path, [examples]) + + +def test_local_anchor_and_python_syntax_are_checked(tmp_path): + readme = tmp_path / "README.md" + readme.write_text("# Run a model\n[Run](#run-a-model)\n```python\nprint(1)\n```\n") + assert check_markdown(readme, tmp_path, []) == set() + readme.write_text("[Run](#missing)\n") + with pytest.raises(ValueError, match="heading is missing"): + check_markdown(readme, tmp_path, []) + readme.write_text("```python\nif:\n```\n") + with pytest.raises(SyntaxError): + check_markdown(readme, tmp_path, []) + + +def test_repeated_headings_and_code_examples(): + assert headings("# Setup\n# Setup\n```sh\n# Not a heading\n```\n") == {"setup", "setup-1"} + + +def source_files(): + return {f"python/{name}" for name in PACKAGE_FILES} | SOURCE_FILES + + +def test_source_archive_requires_quickstart_mesh_and_builder(): + names = source_files() + check_files(names, wheel=False) + for name in ["examples/quickstart/beam.obj", "python/polyfempy/_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 | {"polyfem/__init__.py", "polyfempy-0.8.dist-info/licenses/LICENSE"} + with pytest.raises(ValueError, match="native"): + check_files(names, wheel=True) + check_files(names | {"polyfempy/polyfempy.cp311-win_amd64.pyd"}, wheel=True) + + +@pytest.mark.parametrize("path, ignored", [ + ("docs/guide.md", False), ("tests/fixtures/mesh.obj", False), + ("tests/fixtures/reference.csv", False), ("tests/fixtures/reference.npz", False), + ("build/native.obj", True), ("dist/package.whl", True), + ("results/solution.vtu", True), (".venv/pyvenv.cfg", True), +]) +def test_repository_ignore_rules_preserve_source_data(path, ignored): + result = subprocess.run( + ["git", "check-ignore", "--no-index", "-q", path], + cwd=Path(__file__).resolve().parents[1], check=False, + ) + assert result.returncode == (0 if ignored else 1) + + +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_release_docs.py b/tests/test_release_docs.py new file mode 100644 index 00000000..eac4823c --- /dev/null +++ b/tests/test_release_docs.py @@ -0,0 +1,10 @@ +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_local_doc_folder_is_not_tracked_release_content(): + gitignore = (ROOT / ".gitignore").read_text(encoding="utf-8") + + assert "/doc/" in gitignore diff --git a/tests/test_result_container.py b/tests/test_result_container.py new file mode 100644 index 00000000..0707c830 --- /dev/null +++ b/tests/test_result_container.py @@ -0,0 +1,81 @@ +"""Tests for the minimal runtime ``Result`` container.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime.result 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={"from_bundle": True}) + + np.testing.assert_array_equal(result.sol, sol) + assert result.meta == {"from_bundle": True} + 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/tests/test_runtime_windows_shim.py b/tests/test_runtime_windows_shim.py new file mode 100644 index 00000000..0ede9dc2 --- /dev/null +++ b/tests/test_runtime_windows_shim.py @@ -0,0 +1,201 @@ +"""Check that Windows compatibility settings require explicit opt-in.""" + +from __future__ import annotations + +import importlib +import io +import os +import sys +import unittest +import unittest.mock +from pathlib import Path + +_REPO = Path(__file__).resolve().parents[1] +if str(_REPO / "python") not in sys.path: + sys.path.insert(0, str(_REPO / "python")) + +from polyfempy.runtime._runtime import ( # noqa: E402 + configure_windows_runtime, + should_auto_configure_windows, +) + + +class PublicSurfaceTests(unittest.TestCase): + def test_function_is_not_reexported_from_polyfempy_runtime(self): + """Advanced callers use ``polyfempy.runtime._runtime`` explicitly.""" + runtime_mod = importlib.import_module("polyfempy.runtime") + self.assertFalse(hasattr(runtime_mod, "configure_windows_runtime")) + self.assertEqual(runtime_mod.__all__, ["solve", "Result"]) + + def test_returns_applied_and_skipped_keys(self): + result = configure_windows_runtime() + self.assertIn("applied", result) + self.assertIn("skipped", result) + self.assertIsInstance(result["applied"], list) + self.assertIsInstance(result["skipped"], list) + + def test_dead_private_stream_wrapper_is_not_present(self): + runtime_mod = importlib.import_module("polyfempy.runtime._runtime") + self.assertFalse(hasattr(runtime_mod, "_wrap_stream_as_utf8")) + + +class NonWindowsNoOpTests(unittest.TestCase): + def test_linux_is_a_noop_and_reports_why(self): + if sys.platform == "win32": + self.skipTest("This test verifies the non-Windows no-op branch.") + result = configure_windows_runtime() + self.assertEqual(result["applied"], []) + self.assertIn("not_windows", result["skipped"]) + + def test_linux_does_not_touch_env_or_stdout(self): + """On non-Windows, the helper must leave the process environment and + ``sys.stdout`` / ``sys.stderr`` exactly as they were.""" + if sys.platform == "win32": + self.skipTest("This test verifies the non-Windows no-op branch.") + before_stdout = sys.stdout + before_stderr = sys.stderr + # Use a placeholder value that's highly unlikely to already be set. + os.environ.pop("POLYFEMPY_T7_SENTINEL", None) + + configure_windows_runtime() + + self.assertIs(sys.stdout, before_stdout) + self.assertIs(sys.stderr, before_stderr) + self.assertNotIn("POLYFEMPY_T7_SENTINEL", os.environ) + + +class OptOutEnvVarTests(unittest.TestCase): + def _set_env(self, value): + if value is None: + os.environ.pop("POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG", None) + else: + os.environ["POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG"] = value + + def setUp(self): + self._saved = os.environ.get("POLYFEMPY_SKIP_WINDOWS_AUTOCONFIG") + self._enabled = os.environ.pop("POLYFEMPY_WINDOWS_AUTOCONFIG", None) + + def tearDown(self): + self._set_env(self._saved) + if self._enabled is None: + os.environ.pop("POLYFEMPY_WINDOWS_AUTOCONFIG", None) + else: + os.environ["POLYFEMPY_WINDOWS_AUTOCONFIG"] = self._enabled + + def test_default_does_not_auto_configure(self): + self._set_env(None) + self.assertFalse(should_auto_configure_windows()) + + def test_empty_string_is_treated_as_unset(self): + self._set_env("") + self.assertFalse(should_auto_configure_windows()) + + def test_truthy_values_disable_auto_configure(self): + os.environ["POLYFEMPY_WINDOWS_AUTOCONFIG"] = "1" + for v in ("1", "true", "TRUE", "Yes", "on", " yes "): + with self.subTest(value=v): + self._set_env(v) + self.assertFalse(should_auto_configure_windows()) + + def test_falsy_values_keep_auto_configure_enabled(self): + os.environ["POLYFEMPY_WINDOWS_AUTOCONFIG"] = "1" + for v in ("0", "false", "no", "off", "nope", "anything-else"): + with self.subTest(value=v): + self._set_env(v) + self.assertTrue(should_auto_configure_windows()) + + def test_opt_in_accepts_truthy_values(self): + self._set_env(None) + for value in ("1", "true", "TRUE", "Yes", "on", " yes "): + with self.subTest(value=value): + os.environ["POLYFEMPY_WINDOWS_AUTOCONFIG"] = value + self.assertTrue(should_auto_configure_windows()) + + +class WindowsBranchTests(unittest.TestCase): + """The Windows-only branches. We patch ``sys.platform`` so these run on + any host.""" + + def setUp(self): + self._saved_kmp = os.environ.get("KMP_DUPLICATE_LIB_OK") + + def tearDown(self): + if self._saved_kmp is None: + os.environ.pop("KMP_DUPLICATE_LIB_OK", None) + else: + os.environ["KMP_DUPLICATE_LIB_OK"] = self._saved_kmp + + def test_kmp_is_set_when_not_present(self): + os.environ.pop("KMP_DUPLICATE_LIB_OK", None) + with unittest.mock.patch.object(sys, "platform", "win32"), \ + unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ + unittest.mock.patch.object(sys, "stderr", io.StringIO()), \ + unittest.mock.patch("os.system", return_value=0): + result = configure_windows_runtime() + self.assertEqual(os.environ.get("KMP_DUPLICATE_LIB_OK"), "TRUE") + self.assertIn("kmp_duplicate_lib_ok", result["applied"]) + + def test_kmp_not_overwritten_when_already_set(self): + os.environ["KMP_DUPLICATE_LIB_OK"] = "FALSE" # user's deliberate choice + with unittest.mock.patch.object(sys, "platform", "win32"), \ + unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ + unittest.mock.patch.object(sys, "stderr", io.StringIO()), \ + unittest.mock.patch("os.system", return_value=0): + result = configure_windows_runtime() + self.assertEqual(os.environ.get("KMP_DUPLICATE_LIB_OK"), "FALSE") + self.assertIn("kmp_already_set", result["skipped"]) + + def test_kmp_overwritten_when_force_is_true(self): + os.environ["KMP_DUPLICATE_LIB_OK"] = "FALSE" + with unittest.mock.patch.object(sys, "platform", "win32"), \ + unittest.mock.patch.object(sys, "stdout", io.StringIO()), \ + unittest.mock.patch.object(sys, "stderr", io.StringIO()), \ + unittest.mock.patch("os.system", return_value=0): + result = configure_windows_runtime(force=True) + self.assertEqual(os.environ.get("KMP_DUPLICATE_LIB_OK"), "TRUE") + self.assertIn("kmp_duplicate_lib_ok", result["applied"]) + + def test_stdout_already_utf8_is_skipped(self): + """If ``sys.stdout`` is already a UTF-8 TextIOWrapper, the helper + must not re-wrap it (would double-buffer and lose writes).""" + utf8_stream = io.TextIOWrapper( + io.BytesIO(), encoding="utf-8", errors="replace" + ) + with unittest.mock.patch.object(sys, "platform", "win32"), \ + unittest.mock.patch.object(sys, "stdout", utf8_stream), \ + unittest.mock.patch.object(sys, "stderr", utf8_stream), \ + unittest.mock.patch("os.system", return_value=0): + result = configure_windows_runtime() + self.assertIs(sys.stdout, utf8_stream) + self.assertIn("stdout_already_utf8", result["skipped"]) + self.assertIn("stderr_already_utf8", result["skipped"]) + + def test_idempotency_second_call_applies_nothing_new(self): + """Calling the function twice in a row must not keep re-wrapping + streams or re-setting the KMP flag.""" + os.environ.pop("KMP_DUPLICATE_LIB_OK", None) + + class _FakeStream: + def __init__(self): + self.buffer = io.BytesIO() + + fake_out = _FakeStream() + fake_err = _FakeStream() + with unittest.mock.patch.object(sys, "platform", "win32"), \ + unittest.mock.patch.object(sys, "stdout", fake_out), \ + unittest.mock.patch.object(sys, "stderr", fake_err), \ + unittest.mock.patch("os.system", return_value=0): + first = configure_windows_runtime() + second = configure_windows_runtime() + + # First call applies the full set of actions. + self.assertIn("kmp_duplicate_lib_ok", first["applied"]) + self.assertIn("stdout_utf8", first["applied"]) + # The second call keeps the configured streams and environment value. + self.assertIn("kmp_already_set", second["skipped"]) + self.assertIn("stdout_already_utf8", second["skipped"]) + self.assertIn("stderr_already_utf8", second["skipped"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_varform_binding_contract.py b/tests/test_varform_binding_contract.py new file mode 100644 index 00000000..53c0e101 --- /dev/null +++ b/tests/test_varform_binding_contract.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_forward_solver_binding_targets_varform_state_only(): + source = (ROOT / "src" / "state" / "state.cpp").read_text( + encoding="utf-8", + errors="ignore", + ) + + assert "#include " in source + assert "solve_problem" not in source + assert ".build_basis(" not in source + assert ".assemble_rhs(" not in source + assert ".assemble_mass_mat(" not in source + assert "s.assembler" not in source + assert "s.bases" not in source + assert "set_per_element_material" not in source + assert 'bundle["sol"] = sol' in source + assert 'bundle["u"]' not in source + assert 'bundle["p"]' not in source + assert 'bundle["vertices"]' not in source + assert 'bundle["cells"]' not in source + + +def test_default_cpp_module_does_not_register_differentiable_bindings(): + src_cmake = (ROOT / "src" / "CMakeLists.txt").read_text() + binding_cpp = (ROOT / "src" / "binding.cpp").read_text() + + assert "add_subdirectory(differentiable)" not in src_cmake + assert "add_subdirectory(solver)" not in src_cmake + assert "differentiable/binding.hpp" not in binding_cpp + assert "solver/binding.hpp" not in binding_cpp + assert "define_differentiable_cache" not in binding_cpp + assert "define_adjoint" not in binding_cpp + assert "define_objective" not in binding_cpp + assert "define_opt_utils" not in binding_cpp + assert "define_nonlinear_problem" not in binding_cpp + assert not (ROOT / "src" / "solver" / "binding.hpp").exists() + assert not (ROOT / "src" / "solver" / "nl_problem.cpp").exists() + assert not (ROOT / "src" / "solver" / "CMakeLists.txt").exists() diff --git a/tools/check_distribution.py b/tools/check_distribution.py new file mode 100644 index 00000000..c3c16515 --- /dev/null +++ b/tools/check_distribution.py @@ -0,0 +1,85 @@ +"""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 = { + "polyfempy/__init__.py", "polyfempy/__main__.py", "polyfempy/cli.py", "polyfempy/runtime/solve.py", + "polyfempy/runtime/result.py", "polyfempy/runtime/_solve_contract.py", + "polyfempy/runtime/__init__.py", "polyfempy/runtime/_solve_backend.py", + "polyfempy/runtime/_runtime.py", "polyfempy/runtime/tensor.py", + "polyfempy/_model_builder.py", "polyfempy/_selection_refs.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", +} +SOURCE_FILES = { + "pyproject.toml", "setup.py", "CMakeLists.txt", "LICENSE", "README.md", "INSTALL.md", "API.md", + "src/binding.cpp", "polyfem/CMakeLists.txt", "polyfem/LICENSE", + "polyfem/json-specs/input-spec.json", "python-from-jse/LICENSE", + "python/polyfem/__init__.py", "tools/check_installed_package.py", + "examples/quickstart/beam.py", "examples/quickstart/beam.obj", + "examples/quickstart/static_elasticity.py", "examples/quickstart/transient_elasticity.py", +} + + +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}") + package_files = PACKAGE_FILES if wheel else {f"python/{name}" for name in PACKAGE_FILES} + required = set(package_files) + required |= {"polyfem/__init__.py"} if wheel else 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_docs.py b/tools/check_docs.py new file mode 100644 index 00000000..63ee5afe --- /dev/null +++ b/tools/check_docs.py @@ -0,0 +1,93 @@ +"""Check project Markdown links and Python syntax without building the solver.""" + +from __future__ import annotations + +import argparse +import ast +from collections import Counter +from pathlib import Path +import re +import subprocess +import time +from urllib.parse import unquote, urldefrag, urlsplit +from urllib.request import Request, urlopen + + +def headings(text: str) -> set[str]: + """Return GitHub-style anchors for the plain headings used in these guides.""" + text = re.sub(r"```.*?```", "", text, flags=re.DOTALL) + counts: Counter[str] = Counter() + anchors = set() + for title in re.findall(r"^#{1,6}\s+(.+)$", text, re.MULTILINE): + slug = re.sub(r"[^\w\- ]", "", title.strip().lower()).replace(" ", "-") + anchors.add(f"{slug}-{counts[slug]}" if counts[slug] else slug) + counts[slug] += 1 + return anchors + + +def check_markdown(path: Path, repo: Path, submodules: list[Path]) -> set[str]: + text = path.read_text(encoding="utf-8") + for code in re.findall(r"```python\s*\n(.*?)```", text, re.DOTALL): + ast.parse(code, filename=str(path)) + prose = re.sub(r"```.*?```", "", text, flags=re.DOTALL) + urls = set() + for target in re.findall(r"\[[^\]]*\]\(([^)\s]+)\)", prose): + url, fragment = urldefrag(target) + scheme = urlsplit(url).scheme + if scheme in ("http", "https"): + urls.add(url) + continue + if scheme == "mailto": + continue + resolved = (path.parent / unquote(url)).resolve() if url else path.resolve() + if not resolved.is_relative_to(repo.resolve()): + raise ValueError(f"{path}: link leaves its repository: {target}") + if any(resolved.is_relative_to(sub.resolve()) for sub in submodules): + raise ValueError(f"{path}: use a pinned GitHub URL for submodule link: {target}") + if not resolved.exists(): + raise ValueError(f"{path}: link target is missing: {target}") + if fragment and resolved.suffix == ".md": + if unquote(fragment) not in headings(resolved.read_text(encoding="utf-8")): + raise ValueError(f"{path}: heading is missing: {target}") + return urls + + +def check_url(url: str) -> None: + for attempt in range(3): + try: + request = Request(url, headers={"User-Agent": "PolyFEM-doc-check"}) + with urlopen(request, timeout=30) as response: + if response.status != 200: + raise ValueError(f"HTTP {response.status}") + return + except (OSError, ValueError) as exc: + if attempt == 2: + raise RuntimeError(f"Could not read documentation link {url}: {exc}") from exc + time.sleep(1 + attempt) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) + parser.add_argument("--online", action="store_true", help="Also request public HTTP links") + args = parser.parse_args() + root = args.root.resolve() + submodules = [root / name for name in ("examples", "python-from-jse", "polyfem", "polyfem-data")] + urls = set() + count = 0 + for repo in [root, root / "examples", root / "python-from-jse"]: + names = subprocess.check_output( + ["git", "ls-files", "-z", "*.md"], cwd=repo + ).decode("utf-8").split("\0") + for name in filter(None, names): + urls.update(check_markdown(repo / name, repo, submodules if repo == root else [])) + count += 1 + if args.online: + for url in sorted(urls): + check_url(url) + print(f"Checked {len(urls)} public URLs.") + print(f"Checked links and Python syntax in {count} Markdown files.") + + +if __name__ == "__main__": + main() diff --git a/tools/check_generated_example_backend.py b/tools/check_generated_example_backend.py new file mode 100644 index 00000000..04ed15dc --- /dev/null +++ b/tools/check_generated_example_backend.py @@ -0,0 +1,571 @@ +"""Compare a generated example backend run against its source JSON run. + +This is a manual diagnostic tool for generated example backend coverage. It +does two comparisons: + +1. generated example output vs. source JSON output +2. generated example output vs. the source JSON ``tests`` block + +By default only the first comparison is required to pass. Use +``--require-tests-match`` after the PolyFEM backend and polyfem-data tests are +known to be synchronized. +""" + +from __future__ import annotations + +import argparse +import copy +import importlib.util +import json +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Sequence + + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_EXAMPLE = ( + ROOT + / "examples" + / "classic_example" + / "2D" + / "contact_2d_golf_ball_deformable_wall_generated_api.py" +) +DEFAULT_SOURCE_JSON = ( + ROOT + / "polyfem-data" + / "contact" + / "examples" + / "2D" + / "golf-ball-doformable-wall.json" +) +DEFAULT_OUTPUT_ROOT = ROOT / "build" / "generated-example-backend-check" +VISUAL_OUTPUT_SUFFIXES = {".pvd", ".vtm", ".vtu"} + + +@dataclass(frozen=True) +class MetricDiff: + key: str + left: float + right: float + diff: float + tolerance: float + + @property + def passed(self) -> bool: + return self.diff <= self.tolerance + + +def _error_metrics(payload: dict[str, Any]) -> dict[str, float]: + return { + key: float(value) + for key, value in payload.items() + if key.startswith("err_") and isinstance(value, (int, float)) + } + + +def _load_json(path: Path) -> dict[str, Any]: + with path.open(encoding="utf-8") as f: + payload = json.load(f) + if not isinstance(payload, dict): + raise TypeError(f"expected JSON object in {path}") + return payload + + +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 _json_pointer_tokens(pointer: str) -> list[str]: + if not pointer.startswith("/"): + raise ValueError(f"JSON patch path must start with '/': {pointer!r}") + return [ + token.replace("~1", "/").replace("~0", "~") + for token in pointer[1:].split("/") + ] + + +def _replace_json_pointer(payload: Any, pointer: str, value: Any) -> None: + target = payload + 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 _apply_json_patch( + payload: dict[str, Any], + patch: list[dict[str, Any]], +) -> dict[str, Any]: + patched = copy.deepcopy(payload) + for item in patch: + if item.get("op") != "replace": + raise ValueError(f"unsupported JSON patch op: {item!r}") + _replace_json_pointer(patched, item["path"], item.get("value")) + return patched + + +def _load_effective_source_payload(source_json: Path) -> dict[str, Any]: + source_json = source_json.resolve() + source = _load_json(source_json) + common_ref = source.pop("common", None) + patch = source.pop("patch", None) + + if common_ref is None: + payload = source + else: + common_path = (source_json.parent / common_ref).resolve() + payload = _deep_merge(_load_effective_source_payload(common_path), source) + + if patch: + payload = _apply_json_patch(payload, patch) + return payload + + +def _resolve_mesh_paths(value: Any, source_dir: Path) -> None: + if isinstance(value, list): + for item in value: + _resolve_mesh_paths(item, source_dir) + return + + if not isinstance(value, dict): + return + + mesh = value.get("mesh") + if isinstance(mesh, str): + value["mesh"] = str((source_dir / mesh).resolve()) + + for child in value.values(): + _resolve_mesh_paths(child, source_dir) + + +def verify_run_linear_solver(source_json: Path) -> str: + source_text = str(source_json).lower() + if any( + marker in source_text + for marker in ("navier", "bilaplace", "thermoelastic") + ): + return "Eigen::SparseLU" + return "Eigen::SimplicialLDLT" + + +def apply_verify_run_linear_solver(payload: dict[str, Any], source_json: Path) -> None: + solver = payload.setdefault("solver", {}) + if not isinstance(solver, dict): + solver = {} + payload["solver"] = solver + + linear = solver.setdefault("linear", {}) + if not isinstance(linear, dict): + linear = {} + solver["linear"] = linear + + linear["solver"] = verify_run_linear_solver(source_json) + + +def _test_time_steps(payload: dict[str, Any]) -> int | str: + if "time" not in payload: + return "static" + + tests = payload.get("tests") + if not isinstance(tests, dict) or "time_steps" not in tests: + return 1 + + time_steps = tests["time_steps"] + if isinstance(time_steps, bool): + raise TypeError("tests.time_steps must be an integer, 'all', or 'static'") + if isinstance(time_steps, (int, float)): + return int(time_steps) + if time_steps in {"all", "static"}: + return time_steps + raise TypeError(f"unsupported tests.time_steps value: {time_steps!r}") + + +def apply_test_time_steps( + payload: dict[str, Any], + time_steps: int | str, +) -> dict[str, Any]: + reduced = copy.deepcopy(payload) + if not isinstance(time_steps, int): + return reduced + + time_args = reduced.get("time") + if not isinstance(time_args, dict): + raise ValueError("numeric tests.time_steps requires a time block") + + time_args = copy.deepcopy(time_args) + if "tend" in time_args and "dt" in time_args: + time_args.pop("tend", None) + time_args["time_steps"] = time_steps + elif "tend" in time_args and "time_steps" in time_args: + original_steps = int(time_args["time_steps"]) + time_args["dt"] = float(time_args["tend"]) / original_steps + time_args["time_steps"] = time_steps + time_args.pop("tend", None) + elif "dt" in time_args and "time_steps" in time_args: + time_args["time_steps"] = time_steps + else: + raise ValueError("time block must contain two of tend, dt, and time_steps") + + reduced["time"] = time_args + return reduced + + +def load_reduced_backend_payload(source_json: Path) -> tuple[dict[str, Any], int | str]: + source_json = source_json.resolve() + payload = _load_effective_source_payload(source_json) + time_steps = _test_time_steps(payload) + + backend_payload = copy.deepcopy(payload) + backend_payload.pop("tests", None) + backend_payload.pop("default_params", None) + backend_payload["root_path"] = str(source_json) + _resolve_mesh_paths(backend_payload, source_json.parent) + apply_verify_run_linear_solver(backend_payload, source_json) + ensure_json_output(backend_payload) + return apply_test_time_steps(backend_payload, time_steps), time_steps + + +def ensure_json_output(payload: dict[str, Any]) -> None: + output = payload.setdefault("output", {}) + if not isinstance(output, dict): + raise TypeError("output block must be an object") + output.setdefault("json", "sim.json") + + +def _config_payload_for_backend_run(cfg: Any) -> dict[str, Any]: + if isinstance(cfg, dict): + return copy.deepcopy(cfg) + + as_dict = getattr(cfg, "as_dict", None) + if callable(as_dict): + payload = as_dict() + if not isinstance(payload, dict): + raise TypeError( + f"cfg.as_dict() must return dict, got {type(payload).__name__}" + ) + from polyfempy.runtime._solve_contract import prepare_generated_backend_payload + + return prepare_generated_backend_payload(payload) + + raise TypeError( + "polyfem_config must be a dict or object " + f"with as_dict(), got {type(cfg).__name__}" + ) + + +def write_backend_payload( + payload: dict[str, Any], + output_root: Path, + source_json: Path, +) -> Path: + input_dir = output_root / "inputs" + input_dir.mkdir(parents=True, exist_ok=True) + payload_path = input_dir / f"{source_json.stem}_reduced.json" + payload_path.write_text( + json.dumps(payload, indent=2, sort_keys=True), + encoding="utf-8", + ) + return payload_path + + +def prune_visual_outputs(output_dir: Path) -> list[Path]: + removed: list[Path] = [] + if not output_dir.exists(): + return removed + + for path in sorted(output_dir.rglob("*")): + if path.is_file() and path.suffix.lower() in VISUAL_OUTPUT_SUFFIXES: + path.unlink() + removed.append(path) + return removed + + +def load_output_metrics(output_dir: Path) -> dict[str, float]: + sim_json = output_dir / "sim.json" + if not sim_json.exists(): + raise FileNotFoundError(f"backend output is missing {sim_json}") + return _error_metrics(_load_json(sim_json)) + + +def load_test_metrics(source_json: Path) -> tuple[dict[str, float], float]: + payload = _load_effective_source_payload(source_json) + tests = payload.get("tests") + if not isinstance(tests, dict): + return {}, 1e-5 + tolerance = float(tests.get("margin", 1e-5)) + return _error_metrics(tests), tolerance + + +def compare_metric_maps( + *, + left: dict[str, float], + right: dict[str, float], + tolerance: float, + relative_to_reference: bool = False, +) -> list[MetricDiff]: + keys = sorted(set(left) | set(right)) + rows: list[MetricDiff] = [] + for key in keys: + if key not in left or key not in right: + rows.append(MetricDiff(key, left.get(key, float("nan")), right.get(key, float("nan")), float("inf"), tolerance)) + continue + diff = abs(left[key] - right[key]) + if relative_to_reference: + # Match PolyFEM's verify_run.cpp, including its scale near zero. + diff /= max(abs(right[key]), 1e-5) + rows.append(MetricDiff(key, left[key], right[key], diff, tolerance)) + return rows + + +def _print_rows(title: str, rows: Sequence[MetricDiff]) -> bool: + print(title) + all_passed = True + for row in rows: + status = "PASS" if row.passed else "FAIL" + all_passed = all_passed and row.passed + print( + f" {status} {row.key}: " + f"left={row.left:.17g} right={row.right:.17g} " + f"diff={row.diff:.3g} tolerance={row.tolerance:.3g}" + ) + return all_passed + + +def _import_example(example_path: Path): + if str(example_path.parent) not in sys.path: + sys.path.insert(0, str(example_path.parent)) + spec = importlib.util.spec_from_file_location(example_path.stem, example_path) + if spec is None or spec.loader is None: + raise ImportError(f"Cannot load example module from {example_path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _generated_workspace(output_root: Path, example_path: Path) -> Path: + return output_root / "generated" / "run" + + +def _source_json_workspace(output_root: Path, source_json: Path) -> Path: + return output_root / "source-json" / "run" + + +def run_generated_example( + example_path: Path, + source_json: Path, + output_root: Path, + *, + test_time_steps: int | str, + keep_visual_output: bool, +) -> Path: + from polyfempy.runtime import solve + + module = _import_example(example_path) + workspace = _generated_workspace(output_root, example_path) + workspace.mkdir(parents=True, exist_ok=True) + payload = _config_payload_for_backend_run(module.polyfem_config) + output = payload.setdefault("output", {}) + output["directory"] = str(workspace) + output.setdefault("json", "sim.json") + if isinstance(output.get("log"), dict): + output["log"]["path"] = str(workspace / "polyfem.log") + payload = apply_test_time_steps(payload, test_time_steps) + apply_verify_run_linear_solver(payload, source_json) + solve(cfg=payload) + if not keep_visual_output: + removed = prune_visual_outputs(workspace) + if removed: + print(f"pruned generated visual outputs: {len(removed)} files") + return workspace + + +def run_source_json( + reduced_source_json: Path, + source_json: Path, + output_root: Path, + *, + log_level: int, + max_threads: int, + keep_visual_output: bool, +) -> Path: + workspace = _source_json_workspace(output_root, source_json) + workspace.mkdir(parents=True, exist_ok=True) + command = [ + sys.executable, + "-I", + "-m", + "polyfempy", + "solve", + str(reduced_source_json), + "--output-dir", + str(workspace), + "--log-level", + str(log_level), + "--max-threads", + str(max_threads), + ] + result = subprocess.run( + command, + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + print(result.stdout) + print(result.stderr, file=sys.stderr) + raise RuntimeError( + "source JSON backend run failed with exit code " + f"{result.returncode}: {' '.join(command)}" + ) + if not keep_visual_output: + removed = prune_visual_outputs(workspace) + if removed: + print(f"pruned source JSON visual outputs: {len(removed)} files") + return workspace + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Run a generated example and its source JSON through the backend, " + "then compare their err_* metrics." + ) + ) + parser.add_argument( + "--example", + type=Path, + default=DEFAULT_EXAMPLE, + help="generated example Python file to run", + ) + parser.add_argument( + "--source-json", + type=Path, + default=DEFAULT_SOURCE_JSON, + help="polyfem-data source JSON mirrored by the generated example", + ) + parser.add_argument( + "--output-root", + type=Path, + default=DEFAULT_OUTPUT_ROOT, + help="directory for generated and source JSON backend outputs", + ) + parser.add_argument( + "--generated-source-tolerance", + type=float, + default=1e-8, + help="required tolerance for generated output vs source JSON output", + ) + parser.add_argument( + "--require-tests-match", + action="store_true", + help=( + "also fail if generated output does not match the source JSON " + "tests block" + ), + ) + parser.add_argument( + "--keep-visual-output", + action="store_true", + help="keep .vtu/.vtm/.pvd files instead of pruning them after comparison", + ) + parser.add_argument("--log-level", type=int, default=2) + parser.add_argument("--max-threads", type=int, default=1) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = _build_parser().parse_args(argv) + + example_path = args.example.resolve() + source_json = args.source_json.resolve() + output_root = args.output_root.resolve() + output_root.mkdir(parents=True, exist_ok=True) + + print(f"generated example: {example_path}") + print(f"source JSON: {source_json}") + print(f"output root: {output_root}") + + source_payload, test_time_steps = load_reduced_backend_payload(source_json) + reduced_source_json = write_backend_payload(source_payload, output_root, source_json) + print(f"tests.time_steps: {test_time_steps}") + print(f"reduced JSON: {reduced_source_json}") + + generated_output = run_generated_example( + example_path, + source_json, + output_root, + test_time_steps=test_time_steps, + keep_visual_output=args.keep_visual_output, + ) + source_output = run_source_json( + reduced_source_json, + source_json, + output_root, + log_level=args.log_level, + max_threads=args.max_threads, + keep_visual_output=args.keep_visual_output, + ) + + generated_metrics = load_output_metrics(generated_output) + source_metrics = load_output_metrics(source_output) + test_metrics, test_tolerance = load_test_metrics(source_json) + + print(f"generated output: {generated_output}") + print(f"source output: {source_output}") + + generated_source_rows = compare_metric_maps( + left=generated_metrics, + right=source_metrics, + tolerance=args.generated_source_tolerance, + ) + generated_matches_source = _print_rows( + "generated output vs source JSON output:", + generated_source_rows, + ) + + generated_matches_tests = True + if test_metrics: + tests_rows = compare_metric_maps( + left=generated_metrics, + right=test_metrics, + tolerance=test_tolerance, + relative_to_reference=True, + ) + generated_matches_tests = _print_rows( + "generated output vs source JSON tests (relative error):", + tests_rows, + ) + else: + print("source JSON has no tests block; skipping tests comparison") + + if not generated_matches_source: + return 1 + if args.require_tests_match and not generated_matches_tests: + return 1 + if not generated_matches_tests: + print( + "WARNING: generated output matches the source JSON run, but does " + "not match the source JSON tests block." + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/check_installed_package.py b/tools/check_installed_package.py new file mode 100644 index 00000000..22c75e0b --- /dev/null +++ b/tools/check_installed_package.py @@ -0,0 +1,162 @@ +"""Check an installed package from a directory outside the source checkout.""" + +from __future__ import annotations + +import argparse +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + + +def first_python_example(path: Path) -> str: + blocks = re.findall(r"```python\n(.*?)```", path.read_text(encoding="utf-8"), re.DOTALL) + if not blocks: + raise RuntimeError(f"{path} has no Python example.") + return blocks[0] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--readme", type=Path, required=True) + parser.add_argument("--reference", type=Path, help="PolyFEM cube reference JSON") + parser.add_argument("--example", type=Path, action="append", default=[]) + args = parser.parse_args() + readme = args.readme.resolve() + examples = [ + ("README", first_python_example(readme), 0.003648, 5e-7), + ( + "Installation", + first_python_example(readme.with_name("INSTALL.md")), + 0.00011234567901234568, + 1e-10, + ), + ( + "Python expression", + ''' +from pathlib import Path +from polyfempy import solve + +load = Path("body_load.py").resolve() +load.write_text("def value(x, y, z, t, index):\\n return -1.0\\n", encoding="utf-8") +vertices = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]]) +cells = np.array([[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]]) +config = { + "materials": {"type": "NeoHookean", "E": 1000, "nu": 0.3}, + "boundary_conditions": { + "dirichlet_boundary": [{"id": "all", "value": [0, 0]}], + "rhs": [0, {"file_name": str(load), "function_name": "value"}], + }, + "solver": {"linear": {"solver": "Eigen::SimplicialLDLT"}}, +} +result = solve(vertices, cells, cfg=config) +''', + 0.00011234567901234568, + 1e-10, + ), + ] + + with TemporaryDirectory(prefix="polyfem-installed-") as folder: + shutil.copyfile( + readme.parent / "examples/quickstart/beam.obj", Path(folder) / "beam.obj" + ) + # -I excludes the checkout, PYTHONPATH, and user site-packages. + check = """ +import os +import pathlib +import sys +streams = (sys.stdout, sys.stderr) +openmp_setting = os.environ.get("KMP_DUPLICATE_LIB_OK") +import polyfem +import polyfempy +if (sys.stdout, sys.stderr) != streams or os.environ.get("KMP_DUPLICATE_LIB_OK") != openmp_setting: + raise RuntimeError("Import changed the host streams or OpenMP settings.") +for module in (polyfem, polyfempy): + path = pathlib.Path(module.__file__).resolve() + if not path.is_relative_to(pathlib.Path(sys.prefix).resolve()): + raise RuntimeError(f"Expected an installed package, imported {path}") + print(f"{module.__name__}: {path}") +if not polyfempy.cpp_backend_available(): + raise RuntimeError(f"Native backend is unavailable: {polyfempy.cpp_backend_error()}") +from importlib.metadata import distribution +dist = distribution("polyfempy") +if not any(entry.name == "polyfempy" and entry.value == "polyfempy.cli:main" for entry in dist.entry_points): + raise RuntimeError("The package is missing the polyfempy console entry point.") +print(f"Installed version: {dist.version}") +import numpy as np +""" + for label, code, expected, atol in examples: + validation = ( + f"\nnp.testing.assert_allclose(abs(result.sol).max(), {expected!r}, " + f"rtol=1e-5, atol={atol!r})\n" + f"print({label!r} + ' example passed.')\n" + ) + subprocess.run( + [sys.executable, "-I", "-c", check + code + validation], + cwd=folder, + check=True, + timeout=300, + ) + subprocess.run( + [sys.executable, "-I", "-m", "polyfempy", "backend-info", "--require"], + cwd=folder, + check=True, + timeout=300, + ) + if args.reference is not None: + reference = args.reference.resolve() + expected = json.loads(reference.read_text(encoding="utf-8"))["tests"] + output = Path(folder) / "cube" + subprocess.run( + [ + sys.executable, + "-I", + "-m", + "polyfempy", + "solve", + str(reference), + "--output-dir", + str(output), + "--log-level", + "2", + "--max-threads", + "1", + ], + cwd=folder, + check=True, + timeout=300, + ) + actual = json.loads((output / "sim.json").read_text(encoding="utf-8")) + metrics = { + key: value for key, value in expected.items() if key.startswith("err_") + } + if not metrics: + raise RuntimeError("The reference JSON has no error metrics.") + for key, value in metrics.items(): + if not abs(actual[key] - value) <= expected.get("margin", 1e-8): + raise AssertionError(f"{key}: got {actual[key]}, expected {value}") + print(f"Cube reference passed ({len(metrics)} metrics).") + for example in args.example: + subprocess.run( + [ + sys.executable, + "-I", + "-c", + "import runpy, sys, numpy as np; " + "result = runpy.run_path(sys.argv[1])['main'](); " + "assert np.isfinite(result.sol).all(); " + "assert abs(result.sol).max() > 0", + str(example.resolve()), + ], + cwd=folder, + check=True, + timeout=300, + ) + print(f"Example passed: {example.name}") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_classic_contact_examples.py b/tools/generate_classic_contact_examples.py new file mode 100644 index 00000000..cea44679 --- /dev/null +++ b/tools/generate_classic_contact_examples.py @@ -0,0 +1,1048 @@ +"""Generate explicit classic contact examples from polyfem-data JSON files.""" + +from __future__ import annotations + +import copy +import json +import keyword +from operator import attrgetter +from pathlib import Path +import re +import sys +from typing import Any, Literal, overload + + +ROOT = Path(__file__).resolve().parents[1] +CONTACT_ROOT = ROOT / "polyfem-data" / "contact" +CONTACT_EXAMPLES = CONTACT_ROOT / "examples" +CONTACT_MESHES = CONTACT_ROOT / "meshes" +CLASSIC_EXAMPLES = ROOT / "examples" / "classic_example" +GENERATED_MARKER = "Generated by tools/generate_classic_contact_examples.py" + +sys.path.insert(0, str(ROOT / "python")) +sys.path.insert(0, str(CLASSIC_EXAMPLES)) + +from _contact_source_loader import load_contact_source_payload # noqa: E402 +from polyfempy.generated_api import generated_api as polyfem # noqa: E402 + + +TARGET_NAME_OVERRIDES = { + "2D/golf-ball-doformable-wall.json": ( + "contact_2d_golf_ball_deformable_wall_generated_api.py" + ), + "3D/friction/high-school-physics-slopetest-mu=0.50.json": ( + "contact_3d_friction_high_school_slopetest_generated_api.py" + ), +} + +FACTORY_BY_CLASS = {} + +BODY_ITEM_CLASSES = { + "material": polyfem.Root.Materials, + "velocity": polyfem.Root.Initial_conditions.Velocity.Item, + "solution": polyfem.Root.Initial_conditions.Solution.Item, + "acceleration": polyfem.Root.Initial_conditions.Acceleration.Item, + "discr_order": polyfem.Root.Space.Discr_order.List.Item, +} + +BOUNDARY_ITEM_CLASSES = { + "dirichlet_boundary": ( + "dirichlet", + polyfem.Root.Boundary_conditions.Dirichlet_boundary.Item, + ), + "neumann_boundary": ( + "neumann", + polyfem.Root.Boundary_conditions.Neumann_boundary.Item, + ), + "normal_aligned_neumann_boundary": ( + "normal_aligned_neumann", + polyfem.Root.Boundary_conditions.Normal_aligned_neumann_boundary.Item, + ), + "pressure_boundary": ( + "pressure", + polyfem.Root.Boundary_conditions.Pressure_boundary.Item, + ), + "pressure_cavity": ( + "pressure_cavity", + polyfem.Root.Boundary_conditions.Pressure_cavity.Item, + ), + "obstacle_displacements": ( + "obstacle_displacement", + polyfem.Root.Boundary_conditions.Obstacle_displacements.Item, + ), +} + +PREFERRED_FACTORY_NAMES = { + polyfem.Root.Output.Data: "output_data", + polyfem.Root.Output.Log: "output_log", + polyfem.Root.Output.Paraview: "output_paraview", + polyfem.Root.Output.Advanced: "output_advanced", + polyfem.Root.Output.Reference: "output_reference", +} + + +def main() -> int: + written = 0 + skipped = 0 + for source_json in source_jsons(): + target = target_path_for_source(source_json) + if target.exists() and GENERATED_MARKER not in target.read_text(encoding="utf-8"): + skipped += 1 + continue + + target.write_text( + wrapper_text(source_json, target), + encoding="utf-8", + newline="\n", + ) + written += 1 + + print( + f"Generated {written} classic contact example(s); " + f"skipped {skipped} hand-written file(s)." + ) + return 0 + + +def source_jsons() -> list[Path]: + paths: list[Path] = [] + for dim in ("2D", "3D"): + for source_json in (CONTACT_EXAMPLES / dim).rglob("*.json"): + if is_auxiliary_source(source_json): + continue + paths.append(source_json) + return sorted(paths) + + +def is_auxiliary_source(source_json: Path) -> bool: + return ( + source_json.name == "common.json" + or source_json.name.endswith("-common.json") + ) + + +def target_path_for_source(source_json: Path) -> Path: + dim = source_json.relative_to(CONTACT_EXAMPLES).parts[0] + source_key = source_json.relative_to(CONTACT_EXAMPLES).as_posix() + override = TARGET_NAME_OVERRIDES.get(source_key) + if override is not None: + return CLASSIC_EXAMPLES / dim / override + + relative_without_suffix = source_json.relative_to(CONTACT_EXAMPLES / dim).with_suffix("") + slug = slugify("_".join(relative_without_suffix.parts)) + return CLASSIC_EXAMPLES / dim / f"contact_{dim.lower()}_{slug}_generated_api.py" + + +def slugify(value: str) -> str: + return re.sub(r"_+", "_", re.sub(r"[^0-9A-Za-z]+", "_", value)).strip("_").lower() + + +def wrapper_text(source_json: Path, target: Path) -> str: + dim = source_json.relative_to(CONTACT_EXAMPLES).parts[0] + common_module = "_contact_2d_common" if dim == "2D" else "_contact_3d_common" + source_expr = path_expression(source_json.relative_to(CONTACT_EXAMPLES)) + source_label = source_json.relative_to(ROOT).as_posix() + payload = load_contact_source_payload(source_json) + case_path = source_json.relative_to(CONTACT_EXAMPLES).with_suffix("") + payload.setdefault("output", {}).setdefault("directory", f"results/{case_path.as_posix()}") + try: + polyfem.config(**copy.deepcopy(payload)) + except TypeError as exc: + config_text = fallback_config_text(payload, str(exc)) + extra_import = " SourcePayloadConfig,\n" + else: + builder_text = render_builder_config(payload) + config_text = ( + builder_text + if builder_text is not None + else "polyfem_config = " + render_config(payload) + ) + extra_import = "" + + return f'''#!/usr/bin/env python3 +"""Classic {dim} contact example using generated_api. + +Mirrors ``{source_label}``. +{GENERATED_MARKER} +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import polyfem +from polyfempy.runtime import solve + +EXAMPLE_DIR = Path(__file__).resolve().parent +if str(EXAMPLE_DIR) not in sys.path: + sys.path.insert(0, str(EXAMPLE_DIR)) + +from {common_module} import ( # noqa: E402 + CONTACT_EXAMPLES_DIR, + MESHES_DIR, +{extra_import}) + + +SOURCE_JSON = {source_expr} + +{config_text} + + +if __name__ == "__main__": + solve(cfg=polyfem_config) +''' + + +def fallback_config_text(payload: dict[str, Any], reason: str) -> str: + return ( + "# This source shape is not yet expressible by the generated API schema.\n" + f"UNSUPPORTED_GENERATED_API_PAYLOAD = {render_literal(payload, 0)}\n\n" + f"GENERATED_API_FALLBACK_REASON = {reason!r}\n" + "polyfem_config = SourcePayloadConfig(\n" + " UNSUPPORTED_GENERATED_API_PAYLOAD,\n" + " source_json=SOURCE_JSON,\n" + " fallback_reason=GENERATED_API_FALLBACK_REASON,\n" + ")" + ) + + +def render_builder_config(payload: dict[str, Any]) -> str | None: + geometry = payload.get("geometry") + if not isinstance(geometry, list): + return None + if any( + not isinstance(item, dict) + or item.get("type") not in ("mesh", "mesh_array", "mesh_sequence") + for item in geometry + ): + return None + if any( + not item.get("is_obstacle") + and "volume_selection" in item + and ( + not isinstance(item.get("volume_selection"), int) + or item.get("volume_selection") <= 0 + ) + for item in geometry + ): + return None + + materials = normalize_optional_items(payload.get("materials")) + if any(not isinstance(item, dict) for item in materials): + return None + + volume_body_by_id: dict[int, str] = {} + material_by_id = {item["id"]: item for item in materials if "id" in item} + selection_handle_by_id: dict[int, list[str]] = {} + boundary_ids = set() + for section in BOUNDARY_ITEM_CLASSES: + for item in normalize_optional_items(payload.get("boundary_conditions", {}).get(section)): + if isinstance(item, dict) and isinstance(item.get("id"), int): + boundary_ids.add(item["id"]) + conditions = payload.get("boundary_conditions", {}) + rhs = conditions.get("rhs") + # A mesh with file-defined tags can overlap a different mesh's explicit ID. + # Keep the source's global RHS when it mixes the two tagging schemes. + volume_tag_modes = {"volume_selection" in item for item in geometry if not item.get("is_obstacle")} + use_body_rhs = ( + isinstance(rhs, list) + and bool(rhs) + and all(isinstance(component, (int, float)) for component in rhs) + and len(volume_tag_modes) == 1 + ) + obstacle_targets = [ + entry.get("id") for key in ("dirichlet_boundary", "obstacle_displacements") + for entry in normalize_optional_items(conditions.get(key)) if isinstance(entry, dict) + ] + moves_tag_zero = any( + target in (0, "all") or isinstance(target, list) and 0 in target + for target in obstacle_targets + ) + surface_ids = [] + for item in geometry: + for field in ("surface_selection", "point_selection"): + selection = item.get(field) + if isinstance(selection, int): + surface_ids.append(selection) + else: + for rule in normalize_optional_items(selection): + if isinstance(rule, dict) and "id" in rule: + surface_ids.append(rule["id"]) + direct_surface_ids = { + label for label in boundary_ids if label > 0 and surface_ids.count(label) == 1 + } + consumed_top_sections = {"geometry"} + if len(material_by_id) == len(materials): + consumed_top_sections.add("materials") + lines = ["model = polyfem.model()", ""] + + for index, material in enumerate(material_by_id.values(), start=1): + material_id = material["id"] + material_values = without_key(material, "id") + lines.extend( + assign_code( + f"material_{index}", + render_material_item(material_values, 0), + ) + ) + material_by_id[material_id] = { + "payload": material, + "variable": f"material_{index}", + } + if materials: + lines.append("") + + for index, item in enumerate(geometry, start=1): + body_var = f"body_{index}" + item_type = item.get("type", "mesh") + item_cls = ( + polyfem.Root.Geometry.Mesh_array + if item_type == "mesh_array" + else polyfem.Root.Geometry.Mesh_sequence + if item_type == "mesh_sequence" + else polyfem.Root.Geometry.Mesh + ) + mesh_values = dict(item) + mesh_values.pop("type", None) + surface_selection = mesh_values.pop("surface_selection", None) + point_selection = mesh_values.pop("point_selection", None) + is_obstacle = bool(mesh_values.get("is_obstacle", False)) + selection = mesh_values.get("volume_selection") + volume_id = selection if isinstance(selection, int) and selection > 0 else None + if volume_id is not None and not is_obstacle and item_type == "mesh" and volume_id in material_by_id: + mesh_values.pop("volume_selection") + if is_obstacle: + if point_selection not in (None, 0): + return None + if surface_selection is not None and (not isinstance(surface_selection, int) or surface_selection < 0): + mesh_values["surface_selection"] = surface_selection + if point_selection is not None: + mesh_values["point_selection"] = point_selection + elif point_selection == 0: + mesh_values["point_selection"] = point_selection + + needs_geometry_handle = any( + value not in (None, 0) + for value in (surface_selection, point_selection) + ) + method = item_type + mesh_kwargs = render_kwargs(item_cls, mesh_values, 4) + assign_whole_surface = ( + surface_selection == 0 and volume_id is not None and not is_obstacle and item_type == "mesh" + and not moves_tag_zero and 0 not in boundary_ids + and all(isinstance(g.get("surface_selection"), int) for g in geometry) + and sum(g["surface_selection"] == 0 for g in geometry) == 1 + ) + unused_obstacle_tag = is_obstacle and item_type in ("mesh", "mesh_array") and not moves_tag_zero + if surface_selection == 0 and not (assign_whole_surface or unused_obstacle_tag): + mesh_kwargs.append(("surface_selection", "0")) + if volume_id in volume_body_by_id and item_type == "mesh": + mesh_kwargs.append(("same_volume_as", volume_body_by_id[volume_id])) + write_body_rhs = use_body_rhs and not is_obstacle and volume_id not in volume_body_by_id + if is_obstacle or volume_id is None: + call = render_method_call( + "model", + method, + [], + mesh_kwargs, + 0, + ) + if is_obstacle and isinstance(surface_selection, int) and surface_selection > 0: + handle_var = f"obstacle_{index}" + if surface_selection in boundary_ids: + selection_handle_by_id.setdefault(surface_selection, []).append(handle_var) + lines.extend(assign_code(handle_var, call)) + else: + lines.extend((call + ".surface_all()").splitlines()) + elif not is_obstacle and (needs_geometry_handle or write_body_rhs): + lines.extend(assign_code(body_var, call)) + else: + lines.extend(call.splitlines()) + else: + lines.extend( + assign_code( + body_var, + render_method_call( + "model", + method, + [], + mesh_kwargs, + 0, + ), + ) + ) + if assign_whole_surface: + lines.append(f"{body_var}.surface_all()") + if volume_id in material_by_id: + material_var = material_by_id[volume_id]["variable"] + lines.extend(render_method_call(body_var, "material", [material_var], [], 0).splitlines()) + volume_body_by_id.setdefault(volume_id, body_var) + + if write_body_rhs: + fields = [("value", render_literal(rhs, 4))] + lines.extend(render_method_call(body_var, "rhs", [], fields, 0).splitlines()) + + selection_owner = body_var + if is_obstacle: + selection_owner = None + + if selection_owner is not None: + if isinstance(surface_selection, dict) and "file" in surface_selection: + # The first column of a PolyFEM sideset contains the boundary tags. + path = Path(surface_selection["file"]) + if volume_id is None or not path.is_file(): + return None + if set(surface_selection) != {"file"}: + return None + tags = {int(row.split()[0]) for row in path.read_text().splitlines() if row.strip()} + used_tags = sorted(tags & boundary_ids) + if not used_tags: + return None + for tag in used_tags: + args = [data_string_expression(str(path))] + if len(tags) > 1: + args.append(f"tag={tag}") + handle = f"{body_var}_surface_file_{tag}" + lines.append(f"{handle} = {body_var}.surface_from_file({', '.join(args)})") + selection_handle_by_id.setdefault(tag, []).append(handle) + surface_selection = None + for selection_kind, selection_value in ( + ("surface", surface_selection), + ("point", point_selection), + ): + if ( + selection_kind == "surface" + and isinstance(selection_value, int) + and selection_value in direct_surface_ids + ): + selection_handle_by_id.setdefault(selection_value, []).append(selection_owner) + continue + selection_lines = render_selection_setup( + selection_owner, + selection_kind, + selection_value, + selection_handle_by_id, + ) + if selection_lines is None: + return None + lines.extend(selection_lines) + + lines.append("") + + initial_lines, consumed_initial = render_initial_condition_bindings( + payload.get("initial_conditions"), + volume_body_by_id, + ) + if initial_lines is None: + return None + consumed_top_sections.update(consumed_initial) + lines.extend(initial_lines) + + space_lines, consumed_space = render_space_bindings( + payload.get("space"), + volume_body_by_id, + ) + if space_lines is None: + return None + consumed_top_sections.update(consumed_space) + lines.extend(space_lines) + + boundary_lines, config_rhs, consumed_boundary = render_boundary_bindings( + payload.get("boundary_conditions"), + selection_handle_by_id, + ) + if boundary_lines is None: + return None + consumed_top_sections.update(consumed_boundary) + lines.extend(boundary_lines) + + config_kwargs = [] + for key, value in payload.items(): + if key in consumed_top_sections: + continue + if key == "materials": + items = [render_material_item(item, 8) for item in normalize_optional_items(value)] + fields = [("items", render_code_list(items, 4))] + elif key in ("time", "contact", "solver", "output", "space") and isinstance(value, dict): + _, section = polyfem._FIELD_WRAPPERS[polyfem.Root][key] + if key == "time": + section = polyfem._select_variant(value, polyfem._POLYMORPHIC_VARIANTS[section]) + fields = render_kwargs(section, value, 4) + else: + config_kwargs.append((keyword_name(key), render_field_value(polyfem.Root, key, value, 4))) + continue + lines.extend(render_method_call("model", key, [], fields, 0).splitlines()) + if config_rhs is not None and not use_body_rhs: + lines.extend(render_method_call("model", "rhs", [render_literal(config_rhs, 4)], [], 0).splitlines()) + + lines.append("") + lines.extend( + assign_code( + "polyfem_config", + render_method_call("model", "config", [], config_kwargs, 0), + ) + ) + return "\n".join(drop_repeated_blank_lines(lines)) + + +def render_initial_condition_bindings( + initial_conditions: Any, + volume_body_by_id: dict[int, str], +) -> tuple[list[str] | None, set[str]]: + if initial_conditions is None: + return [], set() + if not isinstance(initial_conditions, dict): + return None, set() + + lines: list[str] = [] + for section, method in ( + ("velocity", "velocity"), + ("solution", "solution"), + ("acceleration", "acceleration"), + ): + items = normalize_optional_items(initial_conditions.get(section)) + for item in items: + if not isinstance(item, dict) or item.get("id") not in volume_body_by_id: + return None, set() + body_var = volume_body_by_id[item["id"]] + item_values = without_key(item, "id") + lines.extend( + render_method_call( + body_var, + method, + [ + render_construct( + BODY_ITEM_CLASSES[method], + item_values, + 4, + ) + ], + [], + 0, + ).splitlines() + ) + if lines: + lines.append("") + + handled = {"velocity", "solution", "acceleration"} + if any(key not in handled for key in initial_conditions): + return None, set() + return lines, {"initial_conditions"} + + +def render_space_bindings( + space: Any, + volume_body_by_id: dict[int, str], +) -> tuple[list[str] | None, set[str]]: + if space is None: + return [], set() + if not isinstance(space, dict): + return None, set() + + discr_order = space.get("discr_order") + items = normalize_optional_items(discr_order) + if not items or not all(isinstance(item, dict) for item in items): + return [], set() + if any(item.get("id") not in volume_body_by_id for item in items): + return None, set() + if any(key != "discr_order" for key in space): + return None, set() + + lines: list[str] = [] + for item in items: + body_var = volume_body_by_id[item["id"]] + item_values = without_key(item, "id") + lines.extend( + render_method_call( + body_var, + "discr_order", + [], + render_kwargs(BODY_ITEM_CLASSES["discr_order"], item_values, 4), + 0, + ).splitlines() + ) + if lines: + lines.append("") + return lines, {"space"} + + +def render_boundary_bindings( + boundary_conditions: Any, + selection_handle_by_id: dict[int, list[str]], +) -> tuple[list[str] | None, Any, set[str]]: + if boundary_conditions is None: + return [], None, set() + if not isinstance(boundary_conditions, dict): + return None, None, set() + + lines: list[str] = [] + rhs = boundary_conditions.get("rhs") + for section, (method, item_cls) in BOUNDARY_ITEM_CLASSES.items(): + items = normalize_optional_items(boundary_conditions.get(section)) + for item in items: + if not isinstance(item, dict) or item.get("id") not in selection_handle_by_id: + return None, None, set() + item_values = without_key(item, "id") + for selection_var in selection_handle_by_id[item["id"]]: + lines.extend(render_method_call( + selection_var, method, [], render_kwargs(item_cls, item_values, 4), 0, + ).splitlines()) + + handled = {"rhs", *BOUNDARY_ITEM_CLASSES} + if any(key not in handled for key in boundary_conditions): + return None, None, set() + if lines: + lines.append("") + return lines, rhs, {"boundary_conditions"} + + +def render_selection_setup( + body_var: str, + selection_kind: str, + selection_value: Any, + selection_handle_by_id: dict[int, list[str]], +) -> list[str] | None: + if selection_value is None: + return [] + if isinstance(selection_value, int): + if selection_value <= 0: + return [] + handle_var = f"{body_var}_{selection_kind}" + method = "surface_all" if selection_kind == "surface" else None + if method is None: + return None + handles = selection_handle_by_id.setdefault(selection_value, []) + kwargs = [("same_as", handles[0])] if handles else [] + handles.append(handle_var) + return assign_code( + handle_var, + render_method_call( + body_var, + method, + [], + kwargs, + 0, + ), + ) + + is_single_object = isinstance(selection_value, dict) + items = selection_value if isinstance(selection_value, list) else [selection_value] + lines: list[str] = [] + for index, item in enumerate(items, start=1): + if not isinstance(item, dict): + return None + selection_id = item.get("id") + if not isinstance(selection_id, int) or selection_id <= 0: + return None + method = selection_helper_method(selection_kind, item) + if method is None: + return None + handle_var = f"{body_var}_{selection_kind}_{index}" + handles = selection_handle_by_id.setdefault(selection_id, []) + kwargs = [ + (keyword_name(key), render_literal(value, 4)) + for key, value in item.items() if key != "id" + ] + if handles and selection_kind == "surface": + kwargs.append(("same_as", handles[0])) + handles.append(handle_var) + if is_single_object: + kwargs.append(("append", "False")) + lines.extend( + assign_code( + handle_var, + render_method_call( + body_var, + method, + [], + kwargs, + 0, + ), + ) + ) + return lines + + +def selection_helper_method(selection_kind: str, item: dict[str, Any]) -> str | None: + helper_keys = [ + key + for key in ("axis", "box", "sphere", "cylinder", "plane") + if key in item + ] + if len(helper_keys) != 1: + return None + return f"{selection_kind}_{helper_keys[0]}" + + +def render_material_item(material: dict[str, Any], indent: int) -> str: + variant = polyfem._select_variant( + material, + polyfem._LIST_VARIANTS[polyfem.Root.Materials], + ) + return render_construct(variant, material, indent) + + +def render_kwargs( + cls: type, + values: dict[str, Any], + value_indent: int, +) -> list[tuple[str, str]]: + return [ + ( + keyword_name(polyfem._FIELD_ALIASES.get(cls, {}).get(key, key)), + render_field_value( + cls, + polyfem._FIELD_ALIASES.get(cls, {}).get(key, key), + value, + value_indent, + ), + ) + for key, value in values.items() + ] + + +def normalize_optional_items(value: Any) -> list[Any]: + if value is None: + return [] + return value if isinstance(value, list) else [value] + + +def without_key(value: dict[str, Any], key: str) -> dict[str, Any]: + result = dict(value) + result.pop(key, None) + return result + + +def assign_code(variable: str, expression: str) -> list[str]: + lines = expression.splitlines() + lines[0] = f"{variable} = {lines[0]}" + return lines + + +def drop_repeated_blank_lines(lines: list[str]) -> list[str]: + result: list[str] = [] + previous_blank = False + for line in lines: + is_blank = line == "" + if is_blank and previous_blank: + continue + result.append(line) + previous_blank = is_blank + return result + + +def render_config(payload: dict[str, Any]) -> str: + return render_call( + "config", + [], + [ + (keyword_name(key), render_field_value(polyfem.Root, key, value, 4)) + for key, value in payload.items() + ], + 0, + ) + + +def render_field_value(parent_cls: type, key: str, value: Any, indent: int) -> str: + canonical_key = polyfem._FIELD_ALIASES.get(parent_cls, {}).get(key, key) + if canonical_key == "value" and not isinstance(value, dict): + return render_literal(value, indent) + + wrapper_info = polyfem._FIELD_WRAPPERS.get(parent_cls, {}).get(canonical_key) + if wrapper_info is None: + return render_literal(value, indent) + + kind, wrapper = wrapper_info + return render_wrapped_value(value, kind, wrapper, indent) + + +def render_wrapped_value(value: Any, kind: str, wrapper: type, indent: int) -> str: + if value is None: + return render_literal(value, indent) + + if kind == "object" and isinstance(value, dict): + return render_construct(wrapper, value, indent) + + if kind == "list": + items = value if isinstance(value, list) else [value] + rendered_items = [ + render_list_item(wrapper, item, indent + 8) + for item in items + ] + factory = factory_name(wrapper, required=False) + if factory is None: + return render_code_list(rendered_items, indent) + return render_call( + factory, + [], + [("items", render_code_list(rendered_items, indent + 4))], + indent, + ) + + if kind == "polymorphic": + if isinstance(value, dict): + variant = polyfem._select_variant( + value, + polyfem._POLYMORPHIC_VARIANTS[wrapper], + ) + inner = render_construct(variant, value, indent + 4) + return render_call(factory_name(wrapper), [inner], [], indent) + return render_literal(value, indent) + + return render_literal(value, indent) + + +def render_list_item(wrapper: type, item: Any, indent: int) -> str: + variants = polyfem._LIST_VARIANTS.get(wrapper, ()) + if isinstance(item, dict): + variant = polyfem._select_variant(item, variants) + return render_construct(variant, item, indent) + + if len(variants) == 1 and not variants[0][2]: + variant = variants[0][0] + return render_call( + factory_name(variant), + [render_literal(item, indent + 4)], + [], + indent, + ) + + return render_literal(item, indent) + + +def render_construct(cls: type, values: dict[str, Any], indent: int) -> str: + factory = factory_name(cls, required=False) + if factory is None: + return render_dict_literal(values, indent) + + auto_type = polyfem._CLASS_TYPE_NAMES.get(cls) + non_type_keys = [key for key in values if key != "type"] + kwargs = [] + for key, value in values.items(): + if key == "type" and value == auto_type and non_type_keys: + continue + canonical_key = polyfem._FIELD_ALIASES.get(cls, {}).get(key, key) + kwargs.append( + ( + keyword_name(canonical_key), + render_field_value(cls, canonical_key, value, indent + 4), + ) + ) + return render_call(factory, [], kwargs, indent) + + +def render_call( + factory: str, + args: list[str], + kwargs: list[tuple[str, str]], + indent: int, +) -> str: + return render_callable_call(f"polyfem.{factory}", args, kwargs, indent) + + +def render_method_call( + receiver: str, + method: str, + args: list[str], + kwargs: list[tuple[str, str]], + indent: int, +) -> str: + return render_callable_call(f"{receiver}.{method}", args, kwargs, indent) + + +def render_callable_call( + callee: str, + args: list[str], + kwargs: list[tuple[str, str]], + indent: int, +) -> str: + spaces = " " * indent + child_spaces = " " * (indent + 4) + arguments = [arg.strip() for arg in args] + arguments.extend(f"{key}={value.strip()}" for key, value in kwargs) + inline = f"{spaces}{callee}({', '.join(arguments)})" + if "\n" not in inline and len(inline) <= 88: + return inline + + lines = [f"{spaces}{callee}("] + for arg in args: + arg_lines = arg.splitlines() + if arg_lines: + first = arg_lines[0] + if first.startswith(child_spaces): + arg_lines[0] = first + else: + arg_lines[0] = f"{child_spaces}{first.lstrip()}" + lines.extend(arg_lines) + lines[-1] += "," + for key, value in kwargs: + value_lines = value.splitlines() + first = value_lines[0] + if first.startswith(child_spaces): + first = first[len(child_spaces):] + else: + first = first.lstrip() + lines.append(f"{child_spaces}{key}={first}") + lines.extend(value_lines[1:]) + lines[-1] += "," + lines.append(f"{spaces})") + return "\n".join(lines) + + +def render_literal(value: Any, indent: int) -> str: + spaces = " " * indent + simple = simple_literal(value) + if simple is not None: + return f"{spaces}{simple}" + + if isinstance(value, list): + return render_list_literal(value, indent) + if isinstance(value, dict): + return render_dict_literal(value, indent) + return f"{spaces}{value!r}" + + +def simple_literal(value: Any) -> str | None: + if isinstance(value, str): + return data_string_expression(value) + if value is None or isinstance(value, (bool, int, float)): + return repr(value) + if isinstance(value, list) and is_simple_list(value): + return "[" + ", ".join(render_literal(item, 0) for item in value) + "]" + return None + + +def is_simple_list(value: list[Any]) -> bool: + if not value: + return True + total_length = 0 + for item in value: + rendered = simple_literal(item) + if rendered is None: + return False + total_length += len(rendered) + return total_length <= 80 + + +def render_list_literal(value: list[Any], indent: int) -> str: + spaces = " " * indent + if not value: + return f"{spaces}[]" + + lines = [f"{spaces}["] + for item in value: + item_text = render_literal(item, indent + 4) + lines.extend(item_text.splitlines()) + lines[-1] += "," + lines.append(f"{spaces}]") + return "\n".join(lines) + + +def render_code_list(items: list[str], indent: int) -> str: + spaces = " " * indent + if not items: + return f"{spaces}[]" + + lines = [f"{spaces}["] + for item in items: + lines.extend(item.splitlines()) + lines[-1] += "," + lines.append(f"{spaces}]") + return "\n".join(lines) + + +def render_dict_literal(value: dict[str, Any], indent: int) -> str: + spaces = " " * indent + if not value: + return f"{spaces}{{}}" + + lines = [f"{spaces}{{"] + for key, item in value.items(): + item_text = render_literal(item, indent + 4) + item_lines = item_text.splitlines() + first = item_lines[0][indent + 4 :] + lines.append(f"{' ' * (indent + 4)}{key!r}: {first}") + lines.extend(item_lines[1:]) + lines[-1] += "," + lines.append(f"{spaces}}}") + return "\n".join(lines) + + +def data_string_expression(value: str) -> str: + path = Path(value) + if not path.is_absolute(): + return repr(value) + + for name, root in ( + ("MESHES_DIR", CONTACT_MESHES.resolve()), + ("CONTACT_EXAMPLES_DIR", CONTACT_EXAMPLES.resolve()), + ): + try: + relative = path.resolve().relative_to(root) + except ValueError: + continue + return path_expression(relative, base=name, as_str=True) + + return repr(value) + + +def path_expression( + relative_source: Path, + *, + base: str = "CONTACT_EXAMPLES_DIR", + as_str: bool = False, +) -> str: + expr = base + for part in relative_source.parts: + expr += f' / "{part}"' + return f"str({expr})" if as_str else expr + + +def keyword_name(name: str) -> str: + if keyword.iskeyword(name): + return f"{name}_" + if not name.isidentifier(): + raise ValueError(f"cannot render {name!r} as a Python keyword argument") + return name + + +@overload +def factory_name(cls: type, *, required: Literal[True] = True) -> str: ... + + +@overload +def factory_name(cls: type, *, required: Literal[False]) -> str | None: ... + + +@overload +def factory_name(cls: type, *, required: bool) -> str | None: ... + + +def factory_name(cls: type, *, required: bool = True) -> str | None: + preferred = PREFERRED_FACTORY_NAMES.get(cls) + if preferred is not None: + return preferred + + if not FACTORY_BY_CLASS: + FACTORY_BY_CLASS.update(load_factory_map()) + try: + return FACTORY_BY_CLASS[cls] + except KeyError as exc: + if not required: + return None + raise KeyError(f"no generated API factory found for {cls!r}") from exc + + +def load_factory_map() -> dict[type, str]: + manifest = Path(polyfem.__file__).with_name("generated_api_manifest.json") + factories: dict[type, str] = {} + for entry in json.loads(manifest.read_text(encoding="utf-8")): + if entry["exported"]: + cls = attrgetter(entry["class_path"])(polyfem) + factories.setdefault(cls, entry["api_custom_name"] or entry["api_generated_name"]) + return factories + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/generate_polyfem_api.py b/tools/generate_polyfem_api.py new file mode 100644 index 00000000..f1db6361 --- /dev/null +++ b/tools/generate_polyfem_api.py @@ -0,0 +1,282 @@ +"""Generate PolyFEM's packaged Python API from the repo root.""" + +from __future__ import annotations + +import argparse +import os +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" +DEFAULT_POLYFEM_SOURCE_DIR = REPO_ROOT / "polyfem" +POLYFEMPY_PACKAGE_DIR = REPO_ROOT / "python" / "polyfempy" +GENERATED_DIR = POLYFEMPY_PACKAGE_DIR / "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 polyfem_schema_file(polyfem_source_dir: Path) -> Path: + return polyfem_source_dir / "json-specs" / "input-spec.json" + + +def workflow_steps( + run_checks: bool, + *, + schema_file: Path, + include_spec_dirs: list[Path] | None = None, +) -> list[tuple[list[str], Path, dict[str, str] | None]]: + include_spec_dirs = include_spec_dirs or [] + generator_command = [ + sys.executable, + str(GENERATOR_ROOT / "tools" / "generate_with_overrides.py"), + "--schema-file", + str(schema_file), + ] + for include_spec_dir in include_spec_dirs: + generator_command.extend(["--include-spec-dir", str(include_spec_dir)]) + generator_command.extend([ + "--output-file", + str(GENERATED_DIR / "generated_class.py"), + "--api-output-file", + str(GENERATED_DIR / "generated_api.py"), + "--manifest-dir", + str(GENERATED_DIR), + "--overrides", + str(GENERATOR_CONFIG_DIR / "builder.json"), + "--relationships", + str(GENERATOR_CONFIG_DIR / "id_relationships.json"), + "--api-aliases", + str(GENERATOR_CONFIG_DIR / "api_aliases.json"), + "--model-entry", + "polyfem.model", + ]) + steps: list[tuple[list[str], Path, dict[str, str] | None]] = [ + ( + generator_command, + REPO_ROOT, + None, + ), + ] + if run_checks: + steps.extend([ + ( + [ + sys.executable, + "-m", + "pytest", + "tests/test_examples_public_surface.py", + "tests/test_generated_api_example.py", + ], + REPO_ROOT, + None, + ), + ]) + return steps + + +def missing_required_paths( + schema_file: Path, + include_spec_dirs: list[Path], + *, + require_linked_specs: bool = True, +) -> list[Path]: + required = [ + GENERATOR_ROOT, + GENERATOR_ROOT / "tools" / "generate_with_overrides.py", + schema_file, + GENERATOR_CONFIG_DIR, + GENERATOR_CONFIG_DIR / "api_aliases.json", + GENERATOR_CONFIG_DIR / "id_relationships.json", + GENERATOR_CONFIG_DIR / "builder.json", + POLYFEMPY_PACKAGE_DIR, + ] + for include_spec_dir in include_spec_dirs: + required.extend([ + include_spec_dir, + ]) + if require_linked_specs: + search_dirs = [schema_file.parent, *include_spec_dirs] + for spec_file in LINKED_SOLVER_SPEC_FILES: + if not any((search_dir / spec_file).exists() for search_dir in search_dirs): + required.append(schema_file.parent / spec_file) + return [path for path in required if not path.exists()] + + +def _linked_solver_specs_are_available(search_dirs: list[Path]) -> bool: + return all( + any((search_dir / spec_file).exists() for search_dir in search_dirs) + for spec_file in LINKED_SOLVER_SPEC_FILES + ) + + +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 resolve_include_spec_dirs( + schema_file: Path, + include_spec_dirs: list[Path], + polyfem_source_dir: Path, +) -> list[Path]: + """Return include spec dirs, auto-caching PolySolve linked specs if needed.""" + resolved_include_dirs = list(include_spec_dirs) + search_dirs = [schema_file.parent, *resolved_include_dirs] + if _linked_solver_specs_are_available(search_dirs): + return resolved_include_dirs + + cache_dir = _cache_polysolve_solver_specs(polyfem_source_dir) + if cache_dir is not None: + resolved_include_dirs.append(cache_dir) + + return resolved_include_dirs + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Generate python/polyfempy/generated_api from python-from-jse and " + "generator-config." + ), + ) + parser.add_argument( + "--check", + action="store_true", + help="Run backend-free generated API and example parity checks.", + ) + parser.add_argument( + "--polyfem-source-dir", + default=DEFAULT_POLYFEM_SOURCE_DIR, + type=Path, + help=( + "Path to a PolyFEM source checkout. Defaults to the " + "polyfem submodule." + ), + ) + parser.add_argument( + "--resolved-schema-file", + default=None, + type=Path, + help=( + "Path to a complete PolyFEM schema JSON dumped from the PolyFEM " + "build/embedded spec. When set, automatic PolySolve linked-spec " + "cache resolution is skipped." + ), + ) + parser.add_argument( + "--include-spec-dir", + action="append", + default=[], + type=Path, + help=( + "Additional directory to search for included spec files. " + "Can be passed more than once." + ), + ) + args = parser.parse_args(argv) + + if args.resolved_schema_file is not None: + schema_file = args.resolved_schema_file + include_spec_dirs = list(args.include_spec_dir) + require_linked_specs = False + else: + schema_file = polyfem_schema_file(args.polyfem_source_dir) + include_spec_dirs = resolve_include_spec_dirs( + schema_file, + args.include_spec_dir, + args.polyfem_source_dir, + ) + require_linked_specs = True + + missing = missing_required_paths( + schema_file, + include_spec_dirs, + require_linked_specs=require_linked_specs, + ) + if missing: + for path in missing: + print(f"Missing required path: {path}", file=sys.stderr) + if args.resolved_schema_file is not None: + print( + "If using --resolved-schema-file, build PolyFEM and dump the " + "embedded/resolved spec first, then pass that JSON path.", + file=sys.stderr, + ) + else: + print( + "If this is a fresh checkout, run " + "`git submodule update --init --recursive` so polyfem " + "and python-from-jse are present. " + "If the missing file is a linked solver spec, pass " + "`--include-spec-dir `.", + file=sys.stderr, + ) + return 1 + + for command, cwd, extra_env in workflow_steps( + args.check, + schema_file=schema_file, + include_spec_dirs=include_spec_dirs, + ): + print("+ " + " ".join(command), flush=True) + env = None + if extra_env is not None: + env = os.environ.copy() + env.update(extra_env) + result = subprocess.run(command, cwd=cwd, env=env) + if result.returncode != 0: + return result.returncode + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/generated_contact_expected_failures.json b/tools/generated_contact_expected_failures.json new file mode 100644 index 00000000..655ea6ba --- /dev/null +++ b/tools/generated_contact_expected_failures.json @@ -0,0 +1,3 @@ +{ + "ignored": [] +} diff --git a/tools/run_generated_contact_backend_checks.py b/tools/run_generated_contact_backend_checks.py new file mode 100644 index 00000000..dae0b04e --- /dev/null +++ b/tools/run_generated_contact_backend_checks.py @@ -0,0 +1,354 @@ +"""Run generated contact examples listed by PolyFEM contact test files. + +This is a thin batch wrapper around ``tools/check_generated_example_backend.py``. +It keeps the single-case checker as the source of truth and only adds: + +- reading ``polyfem/tests/contact_2d.txt`` and ``contact_3d.txt`` +- mapping each source JSON to its generated example +- saving per-case logs plus machine-readable and text summaries +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from dataclasses import asdict, dataclass, replace +from datetime import datetime +from pathlib import Path +from typing import Mapping, Sequence + + +ROOT = Path(__file__).resolve().parents[1] +CONTACT_LISTS = [ + ROOT / "polyfem" / "tests" / "contact_2d.txt", + ROOT / "polyfem" / "tests" / "contact_3d.txt", +] +DEFAULT_OUTPUT_ROOT = ROOT / "build" / "generated-contact-backend-check" +DEFAULT_EXPECTED_FAILURES = ROOT / "tools" / "generated_contact_expected_failures.json" + +TARGET_NAME_OVERRIDES = { + "2D/golf-ball-doformable-wall.json": ( + "contact_2d_golf_ball_deformable_wall_generated_api.py" + ), + "3D/friction/high-school-physics-slopetest-mu=0.50.json": ( + "contact_3d_friction_high_school_slopetest_generated_api.py" + ), +} + + +@dataclass(frozen=True) +class ContactCase: + list_file: str + line_number: int + source_rel: str + source_json: str + generated_example: str + + +@dataclass(frozen=True) +class CaseResult: + source_rel: str + generated_example: str + status: str + returncode: int + log_file: str + raw_status: str = "" + reason: str = "" + + +@dataclass(frozen=True) +class ExpectedFailure: + source: str + reason: str + approved: bool = False + + +def slugify(value: str) -> str: + import re + + return re.sub(r"_+", "_", re.sub(r"[^0-9A-Za-z]+", "_", value)).strip("_").lower() + + +def generated_example_for_source(source_rel: str) -> Path: + if not source_rel.startswith("contact/examples/"): + raise ValueError(f"unsupported source path: {source_rel}") + + contact_relative = Path(source_rel.removeprefix("contact/examples/")) + dim = contact_relative.parts[0] + source_key = contact_relative.as_posix() + override = TARGET_NAME_OVERRIDES.get(source_key) + if override is not None: + return ROOT / "examples" / "classic_example" / dim / override + + relative_without_suffix = contact_relative.relative_to(dim).with_suffix("") + name = f"contact_{dim.lower()}_{slugify('_'.join(relative_without_suffix.parts))}_generated_api.py" + return ROOT / "examples" / "classic_example" / dim / name + + +def iter_active_contact_cases(list_paths: Sequence[Path]) -> list[ContactCase]: + cases: list[ContactCase] = [] + for list_path in list_paths: + for line_number, line in enumerate(list_path.read_text(encoding="utf-8").splitlines(), 1): + source_rel = line.strip() + if not source_rel or source_rel.startswith("#"): + continue + if not source_rel.startswith("contact/examples/"): + continue + + source_json = ROOT / "polyfem-data" / source_rel + generated_example = generated_example_for_source(source_rel) + cases.append( + ContactCase( + list_file=str(list_path.relative_to(ROOT)), + line_number=line_number, + source_rel=source_rel, + source_json=str(source_json), + generated_example=str(generated_example), + ) + ) + return cases + + +def safe_case_name(source_rel: str) -> str: + return slugify(source_rel.removeprefix("contact/examples/").removesuffix(".json")) + + +def load_expected_failures(config_path: Path | None) -> dict[str, ExpectedFailure]: + if config_path is None or not config_path.exists(): + return {} + + payload = json.loads(config_path.read_text(encoding="utf-8")) + expected_failures: dict[str, ExpectedFailure] = {} + for item in payload.get("ignored", []): + source = str(item["source"]).replace("\\", "/") + expected_failures[source] = ExpectedFailure( + source=source, + reason=str(item.get("reason", "")), + approved=bool(item.get("approved", False)), + ) + return expected_failures + + +def apply_expected_failures( + results: Sequence[CaseResult], + expected_failures: Mapping[str, ExpectedFailure], +) -> list[CaseResult]: + classified: list[CaseResult] = [] + for result in results: + raw_status = result.raw_status or result.status + expected_failure = expected_failures.get(result.source_rel) + if expected_failure is None: + classified.append(replace(result, raw_status=raw_status)) + continue + + if raw_status == "FAIL": + status = "IGNORED" + elif raw_status == "PASS": + status = "UNEXPECTED_PASS" + else: + status = result.status + + classified.append( + replace( + result, + status=status, + raw_status=raw_status, + reason=expected_failure.reason, + ) + ) + return classified + + +def run_case( + case: ContactCase, + output_root: Path, + *, + generated_source_tolerance: float, + require_tests_match: bool, + keep_visual_output: bool, + log_level: int, + max_threads: int, +) -> CaseResult: + case_name = safe_case_name(case.source_rel) + case_root = output_root / "runs" / case_name + case_root.mkdir(parents=True, exist_ok=True) + log_file = output_root / "logs" / f"{case_name}.log" + log_file.parent.mkdir(parents=True, exist_ok=True) + + command = [ + sys.executable, + str(ROOT / "tools" / "check_generated_example_backend.py"), + "--example", + case.generated_example, + "--source-json", + case.source_json, + "--output-root", + str(case_root), + "--generated-source-tolerance", + str(generated_source_tolerance), + "--log-level", + str(log_level), + "--max-threads", + str(max_threads), + ] + if require_tests_match: + command.append("--require-tests-match") + if keep_visual_output: + command.append("--keep-visual-output") + + result = subprocess.run( + command, + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + log_file.write_text( + "\n".join( + [ + "$ " + " ".join(command), + "", + "STDOUT:", + result.stdout, + "", + "STDERR:", + result.stderr, + ] + ), + encoding="utf-8", + ) + + status = "PASS" if result.returncode == 0 else "FAIL" + log_path = log_file.relative_to(ROOT) if log_file.is_relative_to(ROOT) else log_file + return CaseResult( + source_rel=case.source_rel, + generated_example=str(Path(case.generated_example).relative_to(ROOT)), + status=status, + returncode=result.returncode, + log_file=str(log_path), + raw_status=status, + ) + + +def write_summaries( + output_root: Path, + cases: Sequence[ContactCase], + results: Sequence[CaseResult], +) -> None: + passed = sum(1 for result in results if result.status == "PASS") + ignored = sum(1 for result in results if result.status == "IGNORED") + failed = sum(1 for result in results if result.status == "FAIL") + unexpected_pass = sum(1 for result in results if result.status == "UNEXPECTED_PASS") + unexpected_fail = failed + summary = { + "total": len(results), + "passed": passed, + "ignored": ignored, + "failed": failed, + "unexpected_pass": unexpected_pass, + "unexpected_fail": unexpected_fail, + "cases": [asdict(result) for result in results], + } + (output_root / "summary.json").write_text( + json.dumps(summary, indent=2), + encoding="utf-8", + ) + + lines = [ + "Generated contact backend check summary", + f"Total active: {len(results)}", + f"PASS: {passed}", + f"IGNORED: {ignored}", + f"FAIL: {failed}", + f"Unexpected pass: {unexpected_pass}", + f"Unexpected fail: {unexpected_fail}", + "", + "| Status | Source JSON | Generated example | Log | Reason |", + "| --- | --- | --- | --- | --- |", + ] + for result in results: + lines.append( + f"| {result.status} | `{result.source_rel}` | " + f"`{result.generated_example}` | `{result.log_file}` | {result.reason} |" + ) + + if len(cases) != len(results): + lines.extend(["", f"Stopped early after {len(results)} of {len(cases)} cases."]) + + (output_root / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Run generated backend checks for active PolyFEM contact tests." + ) + parser.add_argument( + "--output-root", + type=Path, + default=DEFAULT_OUTPUT_ROOT + / datetime.now().strftime("%Y%m%d-%H%M%S"), + ) + parser.add_argument("--limit", type=int, default=None) + parser.add_argument("--match", default=None, help="only run cases containing this text") + parser.add_argument("--generated-source-tolerance", type=float, default=1e-5) + parser.add_argument("--require-tests-match", action="store_true") + parser.add_argument("--keep-visual-output", action="store_true") + parser.add_argument("--log-level", type=int, default=2) + parser.add_argument("--max-threads", type=int, default=1) + parser.add_argument( + "--expected-failures", + type=Path, + default=DEFAULT_EXPECTED_FAILURES, + help="JSON config listing teacher-approved generated contact failures.", + ) + parser.add_argument( + "--no-expected-failures", + action="store_true", + help="disable expected-failure classification.", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + args = build_parser().parse_args(argv) + output_root = args.output_root.resolve() + output_root.mkdir(parents=True, exist_ok=True) + expected_failures = ( + {} + if args.no_expected_failures + else load_expected_failures(args.expected_failures) + ) + + cases = iter_active_contact_cases(CONTACT_LISTS) + if args.match: + cases = [case for case in cases if args.match in case.source_rel] + if args.limit is not None: + cases = cases[: args.limit] + + results: list[CaseResult] = [] + for index, case in enumerate(cases, 1): + print(f"[{index}/{len(cases)}] {case.source_rel}") + result = run_case( + case, + output_root, + generated_source_tolerance=args.generated_source_tolerance, + require_tests_match=args.require_tests_match, + keep_visual_output=args.keep_visual_output, + log_level=args.log_level, + max_threads=args.max_threads, + ) + results.append(result) + classified_results = apply_expected_failures(results, expected_failures) + displayed_result = classified_results[-1] + print(f" {displayed_result.status} log={displayed_result.log_file}") + write_summaries(output_root, cases, classified_results) + + classified_results = apply_expected_failures(results, expected_failures) + allowed_statuses = {"PASS", "IGNORED"} + return 0 if all(result.status in allowed_statuses for result in classified_results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main())