π Case manipulationο
- class foamlib.FoamCaseBase(path: PathLike[str] | str = PosixPath('.'))ο
Bases:
Sequence[FoamCaseBase.TimeDirectory],PathLike[str]Base class for OpenFOAM cases.
Provides methods for accessing files and time directories in the case, but does not provide methods for running the case or any commands. Users are encouraged to use
FoamCaseorAsyncFoamCaseinstead of this class.Access the time directories of the case as a sequence, e.g.
case[0]orcase[-1]. These will returnFoamCaseBase.TimeDirectoryobjects.- Parameters:
path β The path to the case directory. Defaults to the current working directory.
- property name: strο
The name of the case.
- property application: strο
The application name.
- file(path: PathLike[str] | str) FoamFileο
Return a
FoamFileobject for the given path in the case.
- __getitem__(index: int | float | str) TimeDirectoryο
- __getitem__(index: slice) Sequence[TimeDirectory]
Return the time directory at the given index (
int), indices (slice), name (str), or time (float).
- __iter__() Iterator[TimeDirectory]ο
Return an iterator over the time directories in the case.
- __contains__(value: object) boolο
Return
Trueif the given time directory, name, or time exists in the case.
- __len__() intο
Return the number of time directories in the case.
- __delitem__(key: int | float | str, /) Noneο
Delete the time directory at the given index (
int), name (str), or time (float).
- class TimeDirectory(path: PathLike[str] | str)ο
Bases:
Set[FoamFieldFile],PathLike[str]A time directory in an OpenFOAM case.
Use to access field files in the directory (e.g.
time["U"]). These will be returned asFoamFieldFileobjects.It also behaves as a set of
FoamFieldFileobjects (e.g. it can be iterated over withfor field in time: ...).- property TimeDirectory.name: strο
The name of this time directory (the time as a string).
- property TimeDirectory.time: floatο
The time that corresponds to this directory, as a float.
- TimeDirectory.__getitem__(key: str, /) FoamFieldFileο
Return the field file with the given name in this time directory.
- TimeDirectory.__iter__() Iterator[FoamFieldFile]ο
Return an iterator over the field files in this time directory.
- TimeDirectory.__contains__(x: object) boolο
Return
Trueif the given field file or name exists in this time directory.
- TimeDirectory.__len__() intο
Return the number of field files in this time directory.
- TimeDirectory.__delitem__(name: str, /) Noneο
Delete the field file with the given name in this time directory.
- class foamlib.FoamCase(path: PathLike[str] | str = PosixPath('.'))ο
Bases:
FoamCaseRunBaseAn OpenFOAM case with synchronous execution capabilities.
Extends
FoamCaseBaseto provide methods for running and cleaning cases, as well as accessing files.Access the time directories of the case as a sequence, e.g.
case[0]orcase[-1]. These will returnFoamCase.TimeDirectoryobjects.- Parameters:
path β The path to the case directory. Defaults to the current working directory.
Example usage:
from foamlib import FoamCase case = FoamCase("path/to/case") # Load an OpenFOAM case case[0]["U"].internal_field = [0, 0, 0] # Set the initial velocity field to zero case.run() # Run the case for time in case: # Iterate over the time directories print(time.time) # Print the time print(time["U"].internal_field) # Print the velocity field
- class TimeDirectory(path: PathLike[str] | str)ο
Bases:
TimeDirectory- cell_centers() FoamFieldFileο
Write and return the cell centers.
Currently only works for reconstructed cases (decomposed cases will need to be reconstructed first).
- block_mesh(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Run blockMesh on this case.
- clean(*, check: bool = False) Noneο
Clean this case.
If a
cleanorAllcleanscript is present in the case directory, it will be invoked. Otherwise, the case directory will be cleaned using these rules:All time directories except
0will be deleted.The
0time directory will be deleted if0.origexists.processor*directories will be deleted if asystem/decomposeParDictfile is present.constant/polyMeshwill be deleted if asystem/blockMeshDictfile is present.All
log.*files will be deleted.
If this behavior is not appropriate for a case, it is recommended to write a custom
cleanscript.- Parameters:
check β If True, raise a
CalledProcessErrorif the clean script returns a non-zero exit code.
- clone(dst: PathLike[str] | str | None = None) Selfο
Clone this case (make a clean copy).
This is equivalent to running
self.copy().clean(), but it can be more efficient in cases that do not contain custom clean scripts.If used as a context manager (i.e., within a
withblock) the cloned copy will be deleted automatically when exiting the block.- Parameters:
dst β The destination path. If
None, clone to a new directory in$FOAM_RUN/foamlib.- Returns:
The clone of the case.
Example usage:
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")
- copy(dst: PathLike[str] | str | None = None) Selfο
Make a copy of this case.
If used as a context manager (i.e., within a
withblock) the copy will be deleted automatically when exiting the block.- Parameters:
dst β The destination path. If
None, copy to a new directory in$FOAM_RUN/foamlib.- Returns:
The copy of the case.
Example usage:
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.copy("myPitz")
- decompose_par(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Decompose this case for parallel running.
- reconstruct_par(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Reconstruct this case after parallel running.
- restore_0_dir() Noneο
Restore the 0 directory from the 0.orig directory.
- run(cmd: Sequence[str | PathLike[str]] | str | None = None, *, parallel: bool | None = None, cpus: int | None = None, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Run this case, or a specified command in the context of this case.
If
cmdis given, this method will run the given command in the context of the case.If
cmdisNone, a series of heuristic rules will be used to run the case. This works as follows:If a
run,AllrunorAllrun-parallelscript is present in the case directory, it will be invoked. If bothrunandAllrunare present,Allrunwill be used. If bothAllrunandAllrun-parallelare present and :param:`parallel` isNone, an error will be raised.If no run script is present but an
Allrun.prescript exists, it will be invoked.Otherwise, if a
system/blockMeshDictfile is present, the method will callblock_mesh().Then, if a
0.origdirectory is present, it will callrestore_0_dir().Then, if the case is to be run in parallel (see the :param:`parallel` option) and no
processor*directories exist but asystem/decomposeParDictfile is present, it will calldecompose_par().Then, it will run the case using the application specified in the controlDict file.
If this behavior is not appropriate for a case, it is recommended to write a custom
run,Allrun,Allrun-parallelorAllrun.prescript.- Parameters:
cmd β The command to run. If
None, run the case. If a sequence, the first element is the command and the rest are arguments. If a string,cmdis executed in a shell.parallel β If
True, run in parallel using MPI. If None, autodetect whether to run in parallel.cpus β The number of CPUs to use. If
None, autodetect from to the case.check β If
True, raise aCalledProcessErrorif any command returns a non-zero exit code.log β If
True, log the command output tolog.*files in the case directory.
- class foamlib.AsyncFoamCase(path: PathLike[str] | str = PosixPath('.'))ο
Bases:
FoamCaseRunBaseAn OpenFOAM case with asynchronous execution capabilities.
Extends
FoamCaseBasewith methods for running and cleaning cases asynchronously. This allows for non-blocking execution and parallel execution of multiple cases.Access the time directories of the case as a sequence, e.g.
case[0]orcase[-1]. These will returnAsyncFoamCase.TimeDirectoryobjects.- Parameters:
path β The path to the case directory. Defaults to the current working directory.
Example usage:
from foamlib import AsyncFoamCase case = AsyncFoamCase("path/to/case") # Load an OpenFOAM case case[0]["U"].internal_field = [0, 0, 0] # Set the initial velocity field to zero await case.run() # Run the case for time in case: # Iterate over the time directories print(time.time) # Print the time print(time["U"].internal_field) # Print the velocity field
- class TimeDirectory(path: PathLike[str] | str)ο
Bases:
TimeDirectory- async cell_centers() FoamFieldFileο
Write and return the cell centers.
Currently only works for reconstructed cases (decomposed cases will need to be reconstructed first).
- async block_mesh(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Run blockMesh on this case.
- async clean(*, check: bool = False) Noneο
Clean this case.
If a
cleanorAllcleanscript is present in the case directory, it will be invoked. Otherwise, the case directory will be cleaned using these rules:All time directories except
0will be deleted.The
0time directory will be deleted if0.origexists.processor*directories will be deleted if asystem/decomposeParDictfile is present.constant/polyMeshwill be deleted if asystem/blockMeshDictfile is present.All
log.*files will be deleted.
If this behavior is not appropriate for a case, it is recommended to write a custom
cleanscript.- Parameters:
check β If True, raise a
CalledProcessErrorif the clean script returns a non-zero exit code.
- clone(dst: PathLike[str] | str | None = None) AsyncGenerator[Self]ο
Clone this case (make a clean copy).
This is equivalent to running
(await self.copy()).clean(), but it can be more efficient in cases that do not contain custom clean scripts.If used as an asynchronous context manager (i.e., within an
async withblock) the cloned copy will be deleted automatically when exiting the block.- Parameters:
dst β The destination path. If
None, clone to a new directory in$FOAM_RUN/foamlib.- Returns:
The clone of the case.
Example usage:
import os from pathlib import Path from foamlib import AsyncFoamCase pitz_tutorial = AsyncFoamCase(Path(os.environ["FOAM_TUTORIALS"]) / "incompressible/simpleFoam/pitzDaily") my_pitz = await pitz_tutorial.clone("myPitz")
- copy(dst: PathLike[str] | str | None = None) AsyncGenerator[Self]ο
Make a copy of this case.
If used as an asynchronous context manager (i.e., within an
async withblock) the copy will be deleted automatically when exiting the block.- Parameters:
dst β The destination path. If
None, copy to a new directory in$FOAM_RUN/foamlib.- Returns:
The copy of the case.
Example usage:
import os from pathlib import Path from foamlib import AsyncFoamCase pitz_tutorial = AsyncFoamCase(Path(os.environ["FOAM_TUTORIALS"]) / "incompressible/simpleFoam/pitzDaily") my_pitz = await pitz_tutorial.copy("myPitz")
- async decompose_par(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Decompose this case for parallel running.
- static map(coro: Callable[[_X], Awaitable[_Y]], iterable: Iterable[_X], /) Iterable[_Y]ο
Run an async function on each element of an iterable concurrently.
Note that if coro runs
AsyncFoamCase`s, these will be executed in parallel if possible (this parallelism is automatically limited by the :attr:`max_cpusattribute in order to avoid oversubscription of available CPUs).- Parameters:
coro β An async function to run on each element.
iterable β An iterable of arguments to pass to the function.
- Returns:
An iterable of results from the function.
Example usage:
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 objective_function(x): async with base.clone() as case: # Set inlet velocity based on optimization parameters case[0]["U"].boundary_field["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 = differential_evolution( objective_function, bounds=[(-1, 1)], workers=AsyncSlurmFoamCase.map, polish=False ) print(f"Optimal inlet velocity: {result.x[0]}")
- max_cpus = 2ο
Maximum number of CPUs to use for running instances of
AsyncFoamCaseconcurrently.Defaults to the number of CPUs on the system.
- async reconstruct_par(*, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Reconstruct this case after parallel running.
- async restore_0_dir() Noneο
Restore the 0 directory from the 0.orig directory.
- async run(cmd: Sequence[str | PathLike[str]] | str | None = None, *, parallel: bool | None = None, cpus: int | None = None, check: bool = True, log: bool | str | PathLike[str] = True) Noneο
Run this case, or a specified command in the context of this case.
If
cmdis given, this method will run the given command in the context of the case.If
cmdisNone, a series of heuristic rules will be used to run the case. This works as follows:If a
run,AllrunorAllrun-parallelscript is present in the case directory, it will be invoked. If bothrunandAllrunare present,Allrunwill be used. If bothAllrunandAllrun-parallelare present andparallelisNone, an error will be raised.If no run script is present but an
Allrun.prescript exists, it will be invoked.Otherwise, if a
system/blockMeshDictfile is present, the method will callblock_mesh().Then, if a
0.origdirectory is present, it will callrestore_0_dir().Then, if the case is to be run in parallel (see the
paralleloption) and noprocessor*directories exist but asystem/decomposeParDictfile is present, it will calldecompose_par().Then, it will run the case using the application specified in the controlDict file.
If this behavior is not appropriate for a case, it is recommended to write a custom
run,Allrun,Allrun-parallelorAllrun.prescript.- Parameters:
cmd β The command to run. If
None, run the case. If a sequence, the first element is the command and the rest are arguments. If a string,cmdis executed in a shell.parallel β If
True, run in parallel using MPI. If None, autodetect whether to run in parallel.cpus β The number of CPUs to use. If
None, autodetect from to the case.check β If
True, raise aCalledProcessErrorif any command returns a non-zero exit code.log β If
True, log the command output tolog.*files in the case directory.
- async static run_all(cases: Iterable[AsyncFoamCase | Awaitable[object]], /) Noneο
Run multiple cases concurrently.
Multiple cases will be run in parallel if possible (this parallelism is automatically limited by the
max_cpusattribute in order to avoid oversubscription of available CPUs).- Parameters:
cases β Instances of
AsyncFoamCase(run()will be called) or arbitrary awaitables (will be awaited as-is).
Example usage:
from foamlib import AsyncFoamCase case1 = AsyncFoamCase("path/to/case1") case2 = AsyncFoamCase("path/to/case2") await AsyncFoamCase.run_all([case1, case2])
- class foamlib.AsyncSlurmFoamCase(path: PathLike[str] | str = PosixPath('.'))ο
Bases:
AsyncFoamCaseAn asynchronous OpenFOAM case that launches jobs on a Slurm cluster.
AsyncSlurmFoamCaseis a subclass ofAsyncFoamCase. It provides the same interface, as the latter, except that it will launch jobs on a Slurm cluster (usingsallocandsrun) on the userβs behalf when running a case or command.- Parameters:
path β The path to the case directory. Defaults to the current working directory.
- async run(cmd: Sequence[str | PathLike[str]] | str | None = None, *, parallel: bool | None = None, cpus: int | None = None, check: bool = True, log: bool | str | PathLike[str] = True, fallback: bool = False) Noneο
Run this case, or a specified command in the context of this case.
- Parameters:
cmd β The command to run. If
None, run the case. If a sequence, the first element is the command and the rest are arguments. If a string, cmd is executed in a shell.parallel β If
True, run in parallel using MPI. IfNone, autodetect whether to run in parallel.cpus β The number of CPUs to use. If
None, autodetect according to the case. If0, run locally.check β If
True, raise aCalledProcessErrorif any command returns a non-zero exit code.log β If
True, log the command output to a file.fallback β If
True, fall back to running the command locally if Slurm is not available.
Exceptionsο
- class foamlib.CalledProcessError(returncode, cmd, output=None, stderr=None)ο