Skip to content

Batch API

Parallel simulation execution with thread-pool parallelism.

simulate_batch

idfkit.simulation.batch.simulate_batch(jobs, *, energyplus=None, max_workers=None, cache=None, progress=None, fs=None, on_progress=None, fail_fast=False)

Run multiple EnergyPlus simulations in parallel.

Uses ThreadPoolExecutor to dispatch simulations concurrently. Individual job failures are captured as failed SimulationResult entries -- the batch never raises due to a single job failing, and by default every other job still runs.

With fail_fast=True the first failed job stops the batch instead: queued jobs never start, running EnergyPlus processes are killed, and the batch returns. Those jobs are reported as cancelled results (BatchResult.cancelled); jobs that had already finished keep their results.

An exception in the calling thread -- Ctrl-C, or one raised by a progress callback -- stops the batch the same way, but propagates once the workers have stopped, so no results are returned.

Parameters:

Name Type Description Default
jobs Sequence[SimulationJob]

Sequence of simulation jobs to execute.

required
energyplus EnergyPlusConfig | None

Shared EnergyPlus configuration (auto-discovered if None).

None
max_workers int | None

Maximum number of concurrent simulations. Defaults to min(len(jobs), os.cpu_count() or 1).

None
cache SimulationCache | None

Optional simulation cache for content-hash lookups. See SimulationCache for what the key covers and which models are never cached.

None
progress BatchProgressCallback | None

Optional callback invoked after each job completes. Called as progress(completed=N, total=M, label=label, success=bool); see BatchProgressCallback. A callback that cannot take those keywords is refused before any job runs.

None
fs FileSystem | None

Optional file system backend passed through to each simulate call.

None
on_progress Callable[[SimulationProgress], None] | None

Optional callback invoked with SimulationProgress events during each individual simulation. Events include job_index and job_label to identify which batch job they belong to. The "tqdm" shorthand is not supported for batch runners; use tqdm_progress with a custom per-job callback instead.

None
fail_fast bool

Stop the batch at the first failed job, cancelling the jobs still queued or running, instead of running every job.

False

Returns:

Type Description
BatchResult

A BatchResult with results in the same order as jobs.

Raises:

Type Description
ValueError

If jobs is empty, or fs is given and a job has no output_dir.

TypeError

If progress cannot be called with the four keyword arguments above.

Source code in idfkit/simulation/batch.py
def simulate_batch(
    jobs: Sequence[SimulationJob],
    *,
    energyplus: EnergyPlusConfig | None = None,
    max_workers: int | None = None,
    cache: SimulationCache | None = None,
    progress: BatchProgressCallback | None = None,
    fs: FileSystem | None = None,
    on_progress: Callable[[SimulationProgress], None] | None = None,
    fail_fast: bool = False,
) -> BatchResult:
    """Run multiple EnergyPlus simulations in parallel.

    Uses [ThreadPoolExecutor][concurrent.futures.ThreadPoolExecutor] to dispatch
    simulations concurrently.  Individual job failures are captured as
    failed [SimulationResult][idfkit.simulation.result.SimulationResult] entries -- the batch never raises
    due to a single job failing, and by default every other job still runs.

    With ``fail_fast=True`` the first failed job stops the batch instead:
    queued jobs never start, running EnergyPlus processes are killed, and the
    batch returns. Those jobs are reported as cancelled results
    ([BatchResult.cancelled][idfkit.simulation.batch.BatchResult.cancelled]);
    jobs that had already finished keep their results.

    An exception in the calling thread -- Ctrl-C, or one raised by a
    *progress* callback -- stops the batch the same way, but propagates once
    the workers have stopped, so no results are returned.

    Args:
        jobs: Sequence of simulation jobs to execute.
        energyplus: Shared EnergyPlus configuration (auto-discovered if
            ``None``).
        max_workers: Maximum number of concurrent simulations.  Defaults
            to ``min(len(jobs), os.cpu_count() or 1)``.
        cache: Optional simulation cache for content-hash lookups.  See
            [SimulationCache][idfkit.simulation.cache.SimulationCache] for what
            the key covers and which models are never cached.
        progress: Optional callback invoked after each job completes.
            Called as ``progress(completed=N, total=M, label=label,
            success=bool)``; see
            [BatchProgressCallback][idfkit.simulation.batch.BatchProgressCallback].
            A callback that cannot take those keywords is refused before any
            job runs.
        fs: Optional file system backend passed through to each
            [simulate][idfkit.simulation.runner.simulate] call.
        on_progress: Optional callback invoked with
            [SimulationProgress][idfkit.simulation.progress.SimulationProgress] events
            during each individual simulation.  Events include
            ``job_index`` and ``job_label`` to identify which batch job
            they belong to.  The ``"tqdm"`` shorthand is not supported
            for batch runners; use
            [tqdm_progress][idfkit.simulation.progress_bars.tqdm_progress]
            with a custom per-job callback instead.
        fail_fast: Stop the batch at the first failed job, cancelling the jobs
            still queued or running, instead of running every job.

    Returns:
        A [BatchResult][idfkit.simulation.batch.BatchResult] with results in the same order as *jobs*.

    Raises:
        ValueError: If *jobs* is empty, or *fs* is given and a job has no
            ``output_dir``.
        TypeError: If *progress* cannot be called with the four keyword
            arguments above.
    """
    if not jobs:
        msg = "jobs must not be empty"
        raise ValueError(msg)
    check_jobs_for_fs(jobs, fs)
    if progress is not None:
        _check_progress_callback(progress)

    if on_progress == "tqdm":
        msg = (
            'on_progress="tqdm" is not supported for batch simulations because a single '
            "progress bar cannot represent multiple concurrent jobs. Use the tqdm_progress() "
            "context manager with a custom callback instead."
        )
        raise ValueError(msg)

    progress_cb, progress_cleanup = resolve_on_progress(on_progress)

    try:
        if max_workers is None:
            max_workers = min(len(jobs), os.cpu_count() or 1)

        logger.info("Starting batch of %d jobs with %d workers", len(jobs), max_workers)

        results: list[SimulationResult | None] = [None] * len(jobs)
        completed_count = 0
        total = len(jobs)

        start = time.monotonic()

        group = ProcessGroup()
        executor = ThreadPoolExecutor(max_workers=max_workers)
        try:
            future_to_index = {
                executor.submit(_run_job, idx, job, energyplus, cache, fs, progress_cb, group): idx
                for idx, job in enumerate(jobs)
            }

            def _record(idx: int, result: SimulationResult) -> None:
                nonlocal completed_count
                results[idx] = result
                completed_count += 1
                if progress is not None:
                    progress(completed=completed_count, total=total, label=jobs[idx].label, success=result.success)

            _collect(future_to_index, jobs, group, fail_fast=fail_fast, record=_record)
        except BaseException:
            # Interrupted (Ctrl-C, or a progress callback raised): start no queued job,
            # kill the EnergyPlus processes that are running, then wait for the workers.
            executor.shutdown(wait=False, cancel_futures=True)
            group.cancel()
            executor.shutdown(wait=True)
            raise
        executor.shutdown(wait=True)
    finally:
        if progress_cleanup is not None:
            progress_cleanup()

    elapsed = time.monotonic() - start

    # All slots filled — assert for type checker
    final: list[SimulationResult] = []
    for r in results:
        assert r is not None  # noqa: S101
        final.append(r)

    batch_result = BatchResult(results=tuple(final), total_runtime_seconds=elapsed)
    logger.info(
        "Batch complete: %d succeeded, %d failed, %d cancelled in %.1fs",
        len(batch_result.succeeded),
        len(batch_result.failed),
        len(batch_result.cancelled),
        elapsed,
    )
    return batch_result

SimulationJob

idfkit.simulation.batch.SimulationJob dataclass

Specification for a single simulation within a batch.

Attributes:

Name Type Description
model AnyIDFDocument

The EnergyPlus model to simulate.

weather str | Path | None

Path to the weather file, or None to run without one. None is accepted only for a design-day-only job (design_day=True and annual=False); see simulate for the models that still require a weather file. A refused job is reported as a failed result whose refusal carries the reason.

label str

Human-readable label for progress reporting.

output_dir str | Path | None

Directory for output files. None (the default) runs in a new temporary directory, deleted by BatchResult.cleanup.

expand_objects bool

Run ExpandObjects before simulation.

annual bool

Run annual simulation.

design_day bool

Run design-day-only simulation.

output_prefix str

Prefix for output files.

output_suffix Literal['C', 'L', 'D']

Output file naming suffix ("C", "L", or "D").

readvars bool

Run ReadVarsESO after simulation.

timeout float

Maximum runtime in seconds for the main EnergyPlus subprocess.

preprocessor_timeout float | None

Per-subprocess timeout (seconds) applied individually to ExpandObjects, Slab, and Basement when they run automatically. None consults the IDFKIT_PREPROCESSOR_TIMEOUT environment variable, falling back to 120 s.

extra_args Sequence[str] | None

Additional command-line arguments. Any sequence of strings is accepted, as simulate(extra_args=...) takes, and stored as a tuple.

auto_migrate bool

Forward-migrate a copy of the model to the installed EnergyPlus version before the run, as simulate(..., auto_migrate=True) does.

Raises:

Type Description
TypeError

If model is a path rather than a loaded document (load it with load_idf first), or extra_args is a single string rather than a sequence of them.

Source code in idfkit/simulation/batch.py
@dataclass(frozen=True, slots=True)
class SimulationJob:
    """Specification for a single simulation within a batch.

    Attributes:
        model: The EnergyPlus model to simulate.
        weather: Path to the weather file, or ``None`` to run without one.
            ``None`` is accepted only for a design-day-only job
            (``design_day=True`` and ``annual=False``); see
            [simulate][idfkit.simulation.runner.simulate] for the models that
            still require a weather file. A refused job is reported as a
            failed result whose ``refusal`` carries the reason.
        label: Human-readable label for progress reporting.
        output_dir: Directory for output files. ``None`` (the default) runs
            in a new temporary directory, deleted by
            [BatchResult.cleanup][idfkit.simulation.batch.BatchResult.cleanup].
        expand_objects: Run ExpandObjects before simulation.
        annual: Run annual simulation.
        design_day: Run design-day-only simulation.
        output_prefix: Prefix for output files.
        output_suffix: Output file naming suffix (``"C"``, ``"L"``, or ``"D"``).
        readvars: Run ReadVarsESO after simulation.
        timeout: Maximum runtime in seconds for the main EnergyPlus
            subprocess.
        preprocessor_timeout: Per-subprocess timeout (seconds) applied
            individually to ExpandObjects, Slab, and Basement when they
            run automatically.  ``None`` consults the
            ``IDFKIT_PREPROCESSOR_TIMEOUT`` environment variable, falling
            back to 120 s.
        extra_args: Additional command-line arguments. Any sequence of
            strings is accepted, as ``simulate(extra_args=...)`` takes, and
            stored as a tuple.
        auto_migrate: Forward-migrate a copy of the model to the installed
            EnergyPlus version before the run, as
            ``simulate(..., auto_migrate=True)`` does.

    Raises:
        TypeError: If *model* is a path rather than a loaded document (load it
            with [load_idf][idfkit.load_idf] first), or *extra_args* is a
            single string rather than a sequence of them.
    """

    model: AnyIDFDocument
    weather: str | Path | None = None
    label: str = ""
    output_dir: str | Path | None = None
    expand_objects: bool = True
    annual: bool = False
    design_day: bool = False
    output_prefix: str = "eplus"
    output_suffix: Literal["C", "L", "D"] = "C"
    readvars: bool = False
    timeout: float = 3600.0
    preprocessor_timeout: float | None = None
    extra_args: Sequence[str] | None = None
    auto_migrate: bool = False

    def __post_init__(self) -> None:
        model: object = self.model
        if isinstance(model, (str, os.PathLike)):
            msg = (
                f"SimulationJob(model=...) takes a loaded document, not the path {str(model)!r}; "
                "load it with load_idf() or load_epjson() first."
            )
            raise TypeError(msg)
        extra_args: object = self.extra_args
        if isinstance(extra_args, str):
            msg = f"extra_args takes a sequence of arguments, not the string {extra_args!r}; pass [{extra_args!r}]."
            raise TypeError(msg)
        if self.extra_args is not None and not isinstance(self.extra_args, tuple):
            # Frozen: store an immutable copy, so the job stays hashable and a caller's list edits do not leak in.
            object.__setattr__(self, "extra_args", tuple(self.extra_args))

annual = False class-attribute instance-attribute

auto_migrate = False class-attribute instance-attribute

design_day = False class-attribute instance-attribute

expand_objects = True class-attribute instance-attribute

extra_args = None class-attribute instance-attribute

label = '' class-attribute instance-attribute

model instance-attribute

output_dir = None class-attribute instance-attribute

output_prefix = 'eplus' class-attribute instance-attribute

output_suffix = 'C' class-attribute instance-attribute

preprocessor_timeout = None class-attribute instance-attribute

readvars = False class-attribute instance-attribute

timeout = 3600.0 class-attribute instance-attribute

weather = None class-attribute instance-attribute

BatchResult

idfkit.simulation.batch.BatchResult dataclass

Bases: Sequence[SimulationResult]

Aggregated results from a batch simulation run.

A real Sequence of the results, in job order, so for result in batch, enumerate(batch), batch[0], len(batch), reversed(batch) and result in batch all work and all type-check.

It behaved that way at runtime long before it type-checked. __len__ and __getitem__ alone make an object iterable through the legacy sequence protocol, so for result in batch ran fine and every static checker rejected it, which pushed seven documented examples into writing batch.results instead. Documenting a workaround for a call that already worked is worse than either fixing it or removing it, so the base class is declared.

Every result is in exactly one of succeeded, failed and cancelled.

Attributes:

Name Type Description
results tuple[SimulationResult, ...]

Simulation results in the same order as the input jobs.

total_runtime_seconds float

Wall-clock time for the entire batch.

Source code in idfkit/simulation/batch.py
@dataclass(frozen=True, slots=True)
class BatchResult(Sequence[SimulationResult]):
    """Aggregated results from a batch simulation run.

    A real [Sequence][collections.abc.Sequence] of the results, in job order, so
    ``for result in batch``, ``enumerate(batch)``, ``batch[0]``, ``len(batch)``,
    ``reversed(batch)`` and ``result in batch`` all work and all type-check.

    It behaved that way at runtime long before it type-checked. ``__len__`` and
    ``__getitem__`` alone make an object iterable through the legacy sequence
    protocol, so ``for result in batch`` ran fine and every static checker rejected
    it, which pushed seven documented examples into writing ``batch.results``
    instead. Documenting a workaround for a call that already worked is worse than
    either fixing it or removing it, so the base class is declared.

    Every result is in exactly one of
    [succeeded][idfkit.simulation.batch.BatchResult.succeeded],
    [failed][idfkit.simulation.batch.BatchResult.failed] and
    [cancelled][idfkit.simulation.batch.BatchResult.cancelled].

    Attributes:
        results: Simulation results in the same order as the input jobs.
        total_runtime_seconds: Wall-clock time for the entire batch.
    """

    results: tuple[SimulationResult, ...]
    total_runtime_seconds: float

    @property
    def succeeded(self) -> tuple[SimulationResult, ...]:
        """Results that completed successfully."""
        return tuple(r for r in self.results if r.success)

    @property
    def failed(self) -> tuple[SimulationResult, ...]:
        """Results that failed, not counting the jobs ``fail_fast=True`` cancelled."""
        return tuple(r for r in self.results if not r.success and not r.cancelled)

    @property
    def cancelled(self) -> tuple[SimulationResult, ...]:
        """Results of the jobs ``fail_fast=True`` cancelled after another job failed.

        Always empty without ``fail_fast``. Each has
        [cancelled][idfkit.simulation.result.SimulationResult.cancelled] set and
        its ``refusal`` names the job that failed.
        """
        return tuple(r for r in self.results if r.cancelled)

    @property
    def all_succeeded(self) -> bool:
        """Whether every job in the batch succeeded."""
        return all(r.success for r in self.results)

    def __len__(self) -> int:
        return len(self.results)

    @overload
    def __getitem__(self, index: int) -> SimulationResult: ...

    @overload
    def __getitem__(self, index: slice) -> tuple[SimulationResult, ...]: ...

    def __getitem__(self, index: int | slice) -> SimulationResult | tuple[SimulationResult, ...]:
        return self.results[index]

    def __iter__(self) -> Iterator[SimulationResult]:
        # Sequence would synthesise this from __getitem__, one index at a time. Iterating the
        # underlying tuple directly is the same answer without the index arithmetic, and it is
        # the path every `for result in batch` actually takes.
        return iter(self.results)

    def cleanup(self) -> None:
        """Call [SimulationResult.cleanup][idfkit.simulation.result.SimulationResult.cleanup] on every result.

        Deletes the temporary run directories idfkit created for jobs without an
        ``output_dir``; a job's own ``output_dir`` is never touched. Using the
        batch as a context manager (``with simulate_batch(jobs) as batch:``)
        calls this on exit. Safe to call more than once.
        """
        for result in self.results:
            result.cleanup()

    async def async_cleanup(self) -> None:
        """Non-blocking [cleanup][idfkit.simulation.batch.BatchResult.cleanup]; ``async with`` calls it on exit."""
        for result in self.results:
            await result.async_cleanup()

    def __enter__(self) -> BatchResult:
        return self

    def __exit__(self, *exc: object) -> None:
        self.cleanup()

    async def __aenter__(self) -> BatchResult:
        return self

    async def __aexit__(self, *exc: object) -> None:
        await self.async_cleanup()

all_succeeded property

Whether every job in the batch succeeded.

cancelled property

Results of the jobs fail_fast=True cancelled after another job failed.

Always empty without fail_fast. Each has cancelled set and its refusal names the job that failed.

failed property

Results that failed, not counting the jobs fail_fast=True cancelled.

results instance-attribute

succeeded property

Results that completed successfully.

total_runtime_seconds instance-attribute

async_cleanup() async

Non-blocking cleanup; async with calls it on exit.

Source code in idfkit/simulation/batch.py
async def async_cleanup(self) -> None:
    """Non-blocking [cleanup][idfkit.simulation.batch.BatchResult.cleanup]; ``async with`` calls it on exit."""
    for result in self.results:
        await result.async_cleanup()

cleanup()

Call SimulationResult.cleanup on every result.

Deletes the temporary run directories idfkit created for jobs without an output_dir; a job's own output_dir is never touched. Using the batch as a context manager (with simulate_batch(jobs) as batch:) calls this on exit. Safe to call more than once.

Source code in idfkit/simulation/batch.py
def cleanup(self) -> None:
    """Call [SimulationResult.cleanup][idfkit.simulation.result.SimulationResult.cleanup] on every result.

    Deletes the temporary run directories idfkit created for jobs without an
    ``output_dir``; a job's own ``output_dir`` is never touched. Using the
    batch as a context manager (``with simulate_batch(jobs) as batch:``)
    calls this on exit. Safe to call more than once.
    """
    for result in self.results:
        result.cleanup()