foamlib

foamlib: A modern Python package for working with OpenFOAM - Published in JOSS (2025)

https://github.com/gerlero/foamlib

Science Score: 98.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 10 DOI reference(s) in README and JOSS metadata
  • Academic publication links
    Links to: joss.theoj.org
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
    Published in Journal of Open Source Software

Keywords

asyncio cases dictionaries fields files openfoam parsing python slurm

Keywords from Contributors

mesh
Last synced: 4 months ago · JSON representation ·

Repository

A modern Python package for interacting with OpenFOAM

Basic Info
Statistics
  • Stars: 132
  • Watchers: 5
  • Forks: 20
  • Open Issues: 5
  • Releases: 108
Topics
asyncio cases dictionaries fields files openfoam parsing python slurm
Created almost 2 years ago · Last pushed 4 months ago
Metadata Files
Readme Contributing License Citation

README.md

foamlib

Documentation CI Codecov Checked with mypy Ruff uv Publish PyPI Conda Version PyPI - Python Version OpenFOAM Docker Docker image DOI

foamlib is a modern Python package that provides a simple, elegant and fast interface for interacting with OpenFOAM. Published in the Journal of Open Source Software, it's designed to make OpenFOAM workflows more accessible and efficient for researchers and engineers.

benchmark Parsing a `volVectorField` with 200k cells.[1](#benchmark)

🚀 Introduction

foamlib is a Python package designed to simplify and streamline OpenFOAM workflows. It provides:

  • 🗄️ Intuitive file handling: Read and write OpenFOAM configuration and field files as if they were Python dictionaries
  • ⚡ High performance: Standalone parser supporting both ASCII and binary formats with or without compression
  • 🔄 Async operations: Run multiple cases concurrently with full asyncio support
  • 🎯 Type safety: A fully typed API for validation and a better development experience
  • ⚙️ Workflow automation: Reduce boilerplate code for pre/post-processing and simulation management
  • 🧩 Fully compatible: Works with OpenFOAM from both openfoam.com and openfoam.org
  • And more!

Compared to PyFoam and other similar tools like fluidfoam, fluidsimfoam, and Ofpp, foamlib offers significant advantages in performance, usability, and modern Python compatibility.

🧱 Core components

foamlib provides these key classes for different aspects of OpenFOAM workflow automation:

File Handling

  • FoamFile - Read and write OpenFOAM configuration files as if they were Python dicts
  • FoamFieldFile - Handle field files with support for ASCII and binary formats (with or without compression)

Case Management

  • FoamCase - Configure, run, and access results of OpenFOAM cases
  • AsyncFoamCase - Asynchronous version for running multiple cases concurrently
  • AsyncSlurmFoamCase - Specialized for Slurm-based HPC clusters

📦 Installation

Choose your preferred installation method:

✨ pip pip install foamlib
🐍 conda conda install -c conda-forge foamlib
🍺 Homebrew brew install gerlero/openfoam/foamlib
🐳 Docker docker pull microfluidica/foamlib

🚀 Quick Start

Here's a simple example to get you started:

```python import os from pathlib import Path from foamlib import FoamCase

Clone and run a case

mycase = FoamCase(Path(os.environ["FOAMTUTORIALS"]) / "incompressible/simpleFoam/pitzDaily").clone("myCase") my_case.run()

Access results

latesttime = mycase[-1] pressure = latesttime["p"].internalfield velocity = latesttime["U"].internalfield

print(f"Max pressure: {max(pressure)}") print(f"Velocity at first cell: {velocity[0]}")

Clean up

my_case.clean() ```

📚 Detailed Examples

🐑 Clone a case

```python import os from pathlib import Path from foamlib import FoamCase

pitztutorial = FoamCase(Path(os.environ["FOAMTUTORIALS"]) / "incompressible/simpleFoam/pitzDaily") mypitz = pitztutorial.clone("myPitz") ```

🏃 Run the case and access results

```python

Run the simulation

my_pitz.run()

Access the latest time step

latesttime = mypitz[-1] p = latesttime["p"] U = latesttime["U"]

print(f"Pressure field: {p.internalfield}") print(f"Velocity field: {U.internalfield}") ```

🧹 Clean up and modify settings

```python

Clean the case

my_pitz.clean()

Modify control settings

mypitz.controldict["writeInterval"] = 10 mypitz.controldict["endTime"] = 2000 ```

📝 Batch file modifications

```python

Make multiple file changes efficiently

with mypitz.fvschemes as f: f["gradSchemes"]["default"] = f["divSchemes"]["default"] f["snGradSchemes"]["default"] = "uncorrected" ```

⏳ Asynchronous execution

```python import asyncio from foamlib import AsyncFoamCase

async def runmultiplecases(): """Run multiple cases concurrently.""" basecase = AsyncFoamCase(mypitz)

# Create and run multiple cases with different parameters
tasks = []
for i, velocity in enumerate([1, 2, 3]):
    case = base_case.clone(f"case_{i}")
    case[0]["U"].boundary_field["inlet"].value = [velocity, 0, 0]
    tasks.append(case.run())

# Wait for all cases to complete
await asyncio.gather(*tasks)

Run the async function

asyncio.run(runmultiplecases()) ```

🔢 Direct field file access

```python import numpy as np from foamlib import FoamFieldFile

Read field data directly

U = FoamFieldFile("0/U") print(f"Velocity field shape: {np.shape(U.internalfield)}") print(f"Boundaries: {list(U.boundaryfield)}") ```

🎯 Optimization with HPC clusters

```python import os from pathlib import Path from foamlib import AsyncSlurmFoamCase from scipy.optimize import differential_evolution

Set up base case for optimization

base = AsyncSlurmFoamCase(Path(os.environ["FOAM_TUTORIALS"]) / "incompressible/simpleFoam/pitzDaily")

async def objectivefunction(x): """Objective function for optimization.""" async with base.clone() as case: # Set inlet velocity based on optimization parameters case[0]["U"].boundaryfield["inlet"].value = [x[0], 0, 0]

    # Run with fallback to local execution if Slurm unavailable
    await case.run(fallback=True)

    # Return objective (minimize velocity magnitude at outlet)
    return abs(case[-1]["U"].internal_field[0][0])

Run optimization with parallel jobs

result = differentialevolution( objectivefunction, bounds=[(-1, 1)], workers=AsyncSlurmFoamCase.map, polish=False ) print(f"Optimal inlet velocity: {result.x[0]}") ```

📄 Create Python-based run/Allrun scripts

```python

!/usr/bin/env python3

"""Run the OpenFOAM case in this directory."""

from pathlib import Path from foamlib import FoamCase

Initialize case from this directory

case = FoamCase(Path(file).parent)

Adjust simulation parameters

case.controldict["endTime"] = 1000 case.controldict["writeInterval"] = 100

Run the simulation

print("Starting OpenFOAM simulation...") case.run() print("Simulation completed successfully!") ```

📘 Documentation

For more details on how to use foamlib, check out the documentation.

🙋 Support

If you have any questions or need help, feel free to open a discussion.

If you believe you have found a bug in foamlib, please open an issue.

🧑‍💻 Contributing

You're welcome to contribute to foamlib! Check out the contributing guidelines for more information.

🖋️ Citation

foamlib has been published in the Journal of Open Source Software!

If you use foamlib in your research, please cite our paper:

Gerlero, G. S., & Kler, P. A. (2025). foamlib: A modern Python package for working with OpenFOAM. Journal of Open Source Software, 10(109), 7633. https://doi.org/10.21105/joss.07633

📋 BibTeX ```bibtex @article{foamlib, author = {Gerlero, Gabriel S. and Kler, Pablo A.}, doi = {10.21105/joss.07633}, journal = {Journal of Open Source Software}, month = may, number = {109}, pages = {7633}, title = {{foamlib: A modern Python package for working with OpenFOAM}}, url = {https://joss.theoj.org/papers/10.21105/joss.07633}, volume = {10}, year = {2025} } ```

👟 Footnotes

[1] foamlib 0.8.1 vs PyFoam 2023.7 on a MacBook Air (2020, M1) with 8 GB of RAM. Benchmark script.

Owner

  • Name: Gabriel Gerlero
  • Login: gerlero
  • Kind: user
  • Location: Santa Fe, Argentina
  • Company: @microfluidica

Information Systems Engineer. PhD candidate in Computational Mechanics at CIMEC. Physics TA at UNL. Santa Fe Microfluidics Group (GSaM).

JOSS Publication

foamlib: A modern Python package for working with OpenFOAM
Published
May 23, 2025
Volume 10, Issue 109, Page 7633
Authors
Gabriel S. Gerlero ORCID
Centro de Investigación en Métodos Computacionales (CIMEC), UNL-CONICET, Argentina, Universidad Nacional de Rafaela (UNRaf), Argentina
Pablo A. Kler ORCID
Centro de Investigación en Métodos Computacionales (CIMEC), UNL-CONICET, Argentina, Departamento de Ingeniería en Sistemas de Información, Universidad Tecnológica Nacional (UTN), Facultad Regional Santa Fe, Argentina
Editor
Mojtaba Barzegari ORCID
Tags
OpenFOAM parsing asyncio Slurm

Citation (CITATION.cff)

cff-version: "1.2.0"
authors:
- family-names: Gerlero
  given-names: Gabriel S.
  orcid: "https://orcid.org/0000-0002-5138-0328"
- family-names: Kler
  given-names: Pablo A.
  orcid: "https://orcid.org/0000-0003-4217-698X"
contact:
- family-names: Gerlero
  given-names: Gabriel S.
  orcid: "https://orcid.org/0000-0002-5138-0328"
doi: 10.5281/zenodo.15442960
message: If you use this software, please cite our article in the
  Journal of Open Source Software.
preferred-citation:
  authors:
  - family-names: Gerlero
    given-names: Gabriel S.
    orcid: "https://orcid.org/0000-0002-5138-0328"
  - family-names: Kler
    given-names: Pablo A.
    orcid: "https://orcid.org/0000-0003-4217-698X"
  date-published: 2025-05-23
  doi: 10.21105/joss.07633
  issn: 2475-9066
  issue: 109
  journal: Journal of Open Source Software
  publisher:
    name: Open Journals
  start: 7633
  title: "foamlib: A modern Python package for working with OpenFOAM"
  type: article
  url: "https://joss.theoj.org/papers/10.21105/joss.07633"
  volume: 10
title: "foamlib: A modern Python package for working with OpenFOAM"

GitHub Events

Total
  • Create event: 228
  • Issues event: 47
  • Release event: 41
  • Watch event: 86
  • Delete event: 182
  • Member event: 1
  • Issue comment event: 322
  • Push event: 507
  • Pull request review event: 24
  • Pull request review comment event: 14
  • Pull request event: 361
  • Fork event: 14
Last Year
  • Create event: 228
  • Issues event: 47
  • Release event: 41
  • Watch event: 87
  • Delete event: 182
  • Member event: 1
  • Issue comment event: 322
  • Push event: 509
  • Pull request review event: 25
  • Pull request review comment event: 14
  • Pull request event: 363
  • Fork event: 14

Committers

Last synced: 7 months ago

All Time
  • Total Commits: 482
  • Total Committers: 4
  • Avg Commits per committer: 120.5
  • Development Distribution Score (DDS): 0.037
Past Year
  • Commits: 310
  • Committers: 3
  • Avg Commits per committer: 103.333
  • Development Distribution Score (DDS): 0.045
Top Committers
Name Email Commits
Gabriel Gerlero g****o 464
dependabot[bot] 4****] 14
Ali Bozorgzadeh 6****g 3
zzkluck z****k@q****m 1
Committer Domains (Top 20 + Academic)
qq.com: 1

Issues and Pull Requests

Last synced: 4 months ago

All Time
  • Total issues: 35
  • Total pull requests: 646
  • Average time to close issues: 24 days
  • Average time to close pull requests: 1 day
  • Total issue authors: 17
  • Total pull request authors: 8
  • Average comments per issue: 3.34
  • Average comments per pull request: 0.84
  • Merged pull requests: 558
  • Bot issues: 0
  • Bot pull requests: 36
Past Year
  • Issues: 35
  • Pull requests: 462
  • Average time to close issues: 24 days
  • Average time to close pull requests: 1 day
  • Issue authors: 17
  • Pull request authors: 7
  • Average comments per issue: 3.34
  • Average comments per pull request: 0.89
  • Merged pull requests: 390
  • Bot issues: 0
  • Bot pull requests: 28
Top Authors
Issue Authors
  • cjbraley (7)
  • zzkluck (3)
  • sturmk (3)
  • gerlero (3)
  • bevanwsjones (3)
  • AndreWeiner (2)
  • olly-writes-code (2)
  • Gallinator (2)
  • benoitpaillard (2)
  • florent314 (1)
  • paugier (1)
  • raphalace (1)
  • vpmapelli (1)
  • Failxxx (1)
  • kgoba (1)
Pull Request Authors
  • gerlero (576)
  • dependabot[bot] (36)
  • Copilot (24)
  • HenningScheufler (4)
  • abzrg (2)
  • zzkluck (2)
  • FoamScience (1)
  • mbarzegary (1)
Top Labels
Issue Labels
bug (11) enhancement (6)
Pull Request Labels
dependencies (36) python (22) github_actions (14) enhancement (1)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 4,781 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 108
  • Total maintainers: 1
pypi.org: foamlib

A Python interface for interacting with OpenFOAM

  • Versions: 108
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 4,781 Last month
Rankings
Dependent packages count: 9.7%
Average: 36.8%
Dependent repos count: 63.9%
Maintainers (1)
Last synced: 4 months ago

Dependencies

.github/workflows/ci.yml actions
  • actions/checkout v4 composite
  • actions/setup-python v5 composite
  • codecov/codecov-action v3 composite
  • psf/black stable composite
.github/workflows/docker.yml actions
  • docker/build-push-action v5 composite
  • docker/login-action v3 composite
  • docker/metadata-action v5 composite
  • docker/setup-buildx-action v3 composite
  • docker/setup-qemu-action v3 composite
.github/workflows/dockerhub-description.yml actions
  • actions/checkout v4 composite
  • peter-evans/dockerhub-description v4 composite
.github/workflows/pypi-publish.yml actions
  • actions/checkout v4 composite
  • actions/setup-python v5 composite
  • pypa/gh-action-pypi-publish release/v1 composite
Dockerfile docker
  • opencfd/openfoam-default 2312 build
pyproject.toml pypi
  • aioshutil >=1,<2
  • pyparsing >=3,<4
benchmark/requirements.txt pypi
  • PyFoam ==2023.7
  • foamlib ==0.8.1