|
| 1 | +# Copyright 2025 Pasteur Labs. All Rights Reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Solve the Poisson equation on a unit square using Firedrake. |
| 5 | +
|
| 6 | +Firedrake is NOT listed in tesseract_requirements.txt — it's only available |
| 7 | +because system_site_packages is enabled and Firedrake is pre-installed in the |
| 8 | +base image. |
| 9 | +""" |
| 10 | + |
| 11 | +from pydantic import BaseModel, Field |
| 12 | + |
| 13 | + |
| 14 | +class InputSchema(BaseModel): |
| 15 | + mesh_resolution: int = Field( |
| 16 | + description="Number of cells along each edge of the unit square mesh.", |
| 17 | + ge=1, |
| 18 | + ) |
| 19 | + |
| 20 | + |
| 21 | +class OutputSchema(BaseModel): |
| 22 | + num_dofs: int = Field(description="Number of degrees of freedom in the solution.") |
| 23 | + l2_error: float = Field( |
| 24 | + description="L2 norm of the error against the exact solution." |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +def apply(inputs: InputSchema) -> OutputSchema: |
| 29 | + """Solve -laplacian(u) = f on the unit square with known exact solution.""" |
| 30 | + from firedrake import ( |
| 31 | + DirichletBC, |
| 32 | + Function, |
| 33 | + FunctionSpace, |
| 34 | + SpatialCoordinate, |
| 35 | + TestFunction, |
| 36 | + TrialFunction, |
| 37 | + UnitSquareMesh, |
| 38 | + dx, |
| 39 | + errornorm, |
| 40 | + grad, |
| 41 | + inner, |
| 42 | + pi, |
| 43 | + sin, |
| 44 | + solve, |
| 45 | + ) |
| 46 | + |
| 47 | + mesh = UnitSquareMesh(inputs.mesh_resolution, inputs.mesh_resolution) |
| 48 | + V = FunctionSpace(mesh, "CG", 1) |
| 49 | + |
| 50 | + u = TrialFunction(V) |
| 51 | + v = TestFunction(V) |
| 52 | + |
| 53 | + x, y = SpatialCoordinate(mesh) |
| 54 | + exact = sin(pi * x) * sin(pi * y) |
| 55 | + f = 2 * pi**2 * sin(pi * x) * sin(pi * y) |
| 56 | + |
| 57 | + a = inner(grad(u), grad(v)) * dx |
| 58 | + L = f * v * dx |
| 59 | + |
| 60 | + bc = DirichletBC(V, 0, "on_boundary") |
| 61 | + |
| 62 | + u_h = Function(V) |
| 63 | + solve(a == L, u_h, bcs=bc) |
| 64 | + |
| 65 | + l2_err = errornorm(exact, u_h, norm_type="L2") |
| 66 | + |
| 67 | + return OutputSchema(num_dofs=V.dof_count, l2_error=l2_err) |
0 commit comments