foamlib provides a simple, modern, ergonomic and fast Python interface for interacting with OpenFOAM.
Parsing a volVectorField with 200k cells.
foamlib offers the following Python classes:
FoamFile
(andFoamFieldFile
): read-write access to OpenFOAM configuration and field files as if they were Pythondict
s, usingfoamlib
's own parser and in-place editor. Supports ASCII and binary field formats (with or without compression).FoamCase
: a class for configuring, running, and accessing the results of OpenFOAM cases.AsyncFoamCase
: variant ofFoamCase
with asynchronous methods for running multiple cases at once.AsyncSlurmFoamCase
: subclass ofAsyncFoamCase
used for running cases on a Slurm cluster.
import os
from pathlib import Path
from foamlib import FoamCase
pitz_tutorial = FoamCase(Path(os.environ["FOAM_TUTORIALS"]) / "incompressible/simpleFoam/pitzDaily")
my_pitz = pitz_tutorial.clone("myPitz")
my_pitz.run()
latest_time = my_pitz[-1]
p = latest_time["p"]
U = latest_time["U"]
print(p.internal_field)
print(U.internal_field)
my_pitz.clean()
my_pitz.control_dict["writeInterval"] = 10
with my_pitz.fv_schemes as f:
f["gradSchemes"]["default"] = f["divSchemes"]["default"]
f["snGradSchemes"]["default"] = "uncorrected"
import asyncio
from foamlib import AsyncFoamCase
async def run_case():
my_pitz_async = AsyncFoamCase(my_pitz)
await my_pitz_async.run()
asyncio.run(run_case())
π’ Parse a field using the FoamFieldFile
class directly
from foamlib import FoamFieldFile
U = FoamFieldFile(Path(my_pitz) / "0/U")
print(U.internal_field)
import os
from pathlib import Path
from foamlib import AsyncSlurmFoamCase
from scipy.optimize import differential_evolution
base = AsyncSlurmFoamCase(Path(os.environ["FOAM_TUTORIALS"]) / "incompressible/simpleFoam/pitzDaily")
async def cost(x):
async with base.clone() as clone:
clone[0]["U"].boundary_field["inlet"].value = [x[0], 0, 0]
await clone.run(fallback=True) # Run locally if Slurm is not available
return abs(clone[-1]["U"].internal_field[0][0])
result = differential_evolution(cost, bounds=[(-1, 1)], workers=AsyncSlurmFoamCase.map, polish=False)
#!/usr/bin/env python3
from pathlib import Path
from foamlib import FoamCase
case = FoamCase(Path(__file__).parent)
# Any additional configuration here
case.run()
For more information, check out the documentation.