Skip to content

Async API

Non-blocking simulation execution using asyncio.

async_simulate

idfkit.simulation.async_runner.async_simulate(model, weather=None, *, output_dir=None, energyplus=None, expand_objects=True, annual=False, design_day=False, output_prefix='eplus', output_suffix='C', readvars=False, timeout=3600.0, preprocessor_timeout=None, extra_args=None, cache=None, fs=None, on_progress=None, auto_migrate=False) async

async_simulate(
    model: AnyIDFDocument,
    weather: str | Path | None,
    *,
    output_dir: str | Path | None = None,
    energyplus: EnergyPlusConfig | 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: list[str] | None = None,
    cache: SimulationCache | None = None,
    fs: FileSystem | AsyncFileSystem | None = None,
    on_progress: Callable[[SimulationProgress], Any]
    | Literal["tqdm"]
    | None = None,
    auto_migrate: bool = False,
) -> SimulationResult
async_simulate(
    model: AnyIDFDocument,
    weather: None = None,
    *,
    output_dir: str | Path | None = None,
    energyplus: EnergyPlusConfig | None = None,
    expand_objects: bool = True,
    annual: Literal[False] = False,
    design_day: Literal[True],
    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: list[str] | None = None,
    cache: SimulationCache | None = None,
    fs: FileSystem | AsyncFileSystem | None = None,
    on_progress: Callable[[SimulationProgress], Any]
    | Literal["tqdm"]
    | None = None,
    auto_migrate: bool = False,
) -> SimulationResult

Run an EnergyPlus simulation without blocking the event loop.

This is the async counterpart to simulate. All parameters and return values are identical; the only difference is that EnergyPlus runs as an asyncio subprocess, allowing the caller to await the result while other coroutines continue executing.

Cancellation is supported: if the wrapping asyncio.Task is cancelled, the EnergyPlus subprocess is killed and cleaned up.

Parameters:

Name Type Description Default
model AnyIDFDocument

The EnergyPlus model to simulate.

required
weather str | Path | None

Path to the weather file (.epw), or None to run without a weather file. None is accepted only for a design-day-only run (design_day=True and annual=False). A model that contains GroundHeatTransfer:Slab:* or GroundHeatTransfer:Basement:* objects requires a weather file when expand_objects is True and GroundHeatTransfer:Control sets the matching run_slab_preprocessor or run_basement_preprocessor field to Yes, because the Slab and Basement preprocessors read it. Without a weather file, a model that contains SizingPeriod:WeatherFileDays or SizingPeriod:WeatherFileConditionType fails in EnergyPlus and the result has success=False; a model whose Site:WaterMainsTemperature uses CorrelationFromWeatherFile completes with one severe error and a fixed mains temperature of 10 °C.

None
output_dir str | Path | None

Directory for output files. None (the default) runs in a new temporary directory, which stays on disk until you call async_cleanup or leave an async with await async_simulate(...) as result: block. A directory you pass is never deleted.

None
energyplus EnergyPlusConfig | None

Pre-configured EnergyPlus installation. If None, uses find_energyplus for auto-discovery.

None
expand_objects bool

Run ExpandObjects before simulation. When True, also runs the Slab and Basement ground heat-transfer preprocessors if the model contains the corresponding objects.

True
annual bool

Run annual simulation (-a flag). The model needs a RunPeriod; without one the run is refused (see Raises).

False
design_day bool

Run design-day-only simulation (-D flag). With neither flag, SimulationControl decides: by default, the model's sizing periods and then its RunPeriod objects, so the model needs at least one of them (see Raises).

False
output_prefix str

Prefix for output files (default "eplus").

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

EnergyPlus --output-suffix style, which names the output files: "C" (capital, default) gives eplus.err and eplusTable.htm, "L" (legacy) gives eplusout.err and eplustbl.htm, and "D" (dash) gives eplus.err and eplus-table.htm.

'C'
readvars bool

Run ReadVarsESO after simulation (-r flag).

False
timeout float

Maximum runtime in seconds (default 3600). Applied only to the main EnergyPlus subprocess; preprocessor stages have an independent budget — see preprocessor_timeout.

3600.0
preprocessor_timeout float | None

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

None
extra_args list[str] | None

Additional command-line arguments.

None
cache SimulationCache | None

Optional simulation cache for content-hash lookups. The key covers the contents of every file the model names (a Schedule:File CSV staged into output_dir, for example). A model with a PythonPlugin:Instance or a co-simulation ExternalInterface is never cached; a warning is logged. A hit is copied into output_dir like a fresh run; without one, its run_dir is the read-only cache entry. Either way the result has cached=True.

None
fs FileSystem | AsyncFileSystem | None

Optional file system backend for storing results on remote storage (e.g., S3). Both sync FileSystem and async AsyncFileSystem are accepted. When an AsyncFileSystem is provided, uploads and result reads are truly non-blocking. A sync FileSystem is automatically wrapped in asyncio.to_thread to avoid blocking the event loop. As in simulate, the weather file is not uploaded and the local temp directory is deleted afterwards. Combined with cache, a miss is cached from the local run directory and a hit uploads the cached outputs to output_dir, so the remote folder exists either way.

None
on_progress Callable[[SimulationProgress], Any] | Literal['tqdm'] | None

Optional callback invoked with a SimulationProgress event each time EnergyPlus emits a progress line. Both synchronous and async callables are accepted -- async callables are awaited. Pass "tqdm" to use a built-in tqdm progress bar (requires pip install idfkit[progress]).

None
auto_migrate bool

When True and model.version differs from the installed EnergyPlus version, forward-migrate the model before running. See simulate for the full semantics.

False

Returns:

Type Description
SimulationResult

SimulationResult with paths to output files. Its files are read lazily

SimulationResult

from run_dir, so read them before cleaning it up.

Raises:

Type Description
SimulationError

On timeout or OS error, or when the weather argument is refused before EnergyPlus starts: weather is an empty string; weather names a file that does not exist; weather is None and the run is not design-day-only; weather is None, expand_objects is True and the model contains Slab or Basement ground heat-transfer objects whose preprocessor GroundHeatTransfer:Control enables; or weather is None and the run directory already contains in.epw. Also raised before EnergyPlus starts when annual is True and the model has no RunPeriod, when design_day is True and the model has no SizingPeriod:DesignDay, or when neither is set and SimulationControl leaves EnergyPlus nothing to run: no RunPeriod and no SizingPeriod:* (as a fresh new_document() has), or both turned off.

TypeError

If model is not a document (None, or a path).

ExpandObjectsError

If a preprocessing step fails.

EnergyPlusNotFoundError

If EnergyPlus cannot be found.

VersionMismatchError

If model.version names another release line than the installed EnergyPlus (a 9.0 model on 9.0.1 matches) and auto_migrate is False, or if the model is newer than the installed EnergyPlus.

Source code in idfkit/simulation/async_runner.py
async def async_simulate(
    model: AnyIDFDocument,
    weather: str | Path | None = None,
    *,
    output_dir: str | Path | None = None,
    energyplus: EnergyPlusConfig | 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: list[str] | None = None,
    cache: SimulationCache | None = None,
    fs: FileSystem | AsyncFileSystem | None = None,
    on_progress: Callable[[SimulationProgress], Any] | Literal["tqdm"] | None = None,
    auto_migrate: bool = False,
) -> SimulationResult:
    """Run an EnergyPlus simulation without blocking the event loop.

    This is the async counterpart to [simulate][idfkit.simulation.runner.simulate].
    All parameters and return values are identical; the only difference is that
    EnergyPlus runs as an [asyncio][] subprocess, allowing the caller to
    ``await`` the result while other coroutines continue executing.

    Cancellation is supported: if the wrapping [asyncio.Task][] is
    cancelled, the EnergyPlus subprocess is killed and cleaned up.

    Args:
        model: The EnergyPlus model to simulate.
        weather: Path to the weather file (.epw), or ``None`` to run without
            a weather file. ``None`` is accepted only for a design-day-only
            run (``design_day=True`` and ``annual=False``). A model that
            contains ``GroundHeatTransfer:Slab:*`` or
            ``GroundHeatTransfer:Basement:*`` objects requires a weather
            file when *expand_objects* is ``True`` and
            ``GroundHeatTransfer:Control`` sets the matching
            ``run_slab_preprocessor`` or ``run_basement_preprocessor`` field
            to ``Yes``, because the Slab and Basement preprocessors read it. Without a weather file,
            a model that contains ``SizingPeriod:WeatherFileDays`` or
            ``SizingPeriod:WeatherFileConditionType`` fails in EnergyPlus and
            the result has ``success=False``; a model whose
            ``Site:WaterMainsTemperature`` uses ``CorrelationFromWeatherFile``
            completes with one severe error and a fixed mains temperature of
            10 °C.
        output_dir: Directory for output files. ``None`` (the default) runs
            in a new temporary directory, which stays on disk until you call
            [async_cleanup][idfkit.simulation.result.SimulationResult.async_cleanup] or leave an
            ``async with await async_simulate(...) as result:`` block. A
            directory you pass is never deleted.
        energyplus: Pre-configured EnergyPlus installation. If None,
            uses [find_energyplus][idfkit.simulation.config.find_energyplus] for auto-discovery.
        expand_objects: Run ExpandObjects before simulation.  When
            ``True``, also runs the Slab and Basement ground heat-transfer
            preprocessors if the model contains the corresponding objects.
        annual: Run annual simulation (``-a`` flag). The model needs a
            ``RunPeriod``; without one the run is refused (see Raises).
        design_day: Run design-day-only simulation (``-D`` flag). With
            neither flag, ``SimulationControl`` decides: by default, the
            model's sizing periods and then its ``RunPeriod`` objects, so the
            model needs at least one of them (see Raises).
        output_prefix: Prefix for output files (default "eplus").
        output_suffix: EnergyPlus ``--output-suffix`` style, which names the
            output files: ``"C"`` (capital, default) gives ``eplus.err`` and
            ``eplusTable.htm``, ``"L"`` (legacy) gives ``eplusout.err`` and
            ``eplustbl.htm``, and ``"D"`` (dash) gives ``eplus.err`` and
            ``eplus-table.htm``.
        readvars: Run ReadVarsESO after simulation (``-r`` flag).
        timeout: Maximum runtime in seconds (default 3600).  Applied only
            to the main EnergyPlus subprocess; preprocessor stages have an
            independent budget — see *preprocessor_timeout*.
        preprocessor_timeout: Per-subprocess timeout (seconds) applied
            individually to ExpandObjects, Slab, and Basement when they
            run automatically.  ``None`` (the default) consults the
            ``IDFKIT_PREPROCESSOR_TIMEOUT`` environment variable, falling
            back to 120 s.  Independent of *timeout*.
        extra_args: Additional command-line arguments.
        cache: Optional simulation cache for content-hash lookups.  The key
            covers the contents of every file the model names (a
            ``Schedule:File`` CSV staged into *output_dir*, for example).  A
            model with a ``PythonPlugin:Instance`` or a co-simulation
            ``ExternalInterface`` is never cached; a warning is logged.
            A hit is copied into *output_dir* like a fresh run; without one,
            its ``run_dir`` is the read-only cache entry. Either way the
            result has ``cached=True``.
        fs: Optional file system backend for storing results on remote
            storage (e.g., S3).  Both sync [FileSystem][idfkit.simulation.fs.FileSystem]
            and async [AsyncFileSystem][idfkit.simulation.fs.AsyncFileSystem] are accepted.
            When an ``AsyncFileSystem`` is provided, uploads and result reads
            are truly non-blocking.  A sync ``FileSystem`` is automatically
            wrapped in [asyncio.to_thread][] to avoid blocking the event
            loop.  As in ``simulate``, the weather file is not uploaded and
            the local temp directory is deleted afterwards.  Combined with
            *cache*, a miss is cached from the local run directory and a hit uploads the cached outputs to
            ``output_dir``, so the remote folder exists either way.
        on_progress: Optional callback invoked with a
            [SimulationProgress][idfkit.simulation.progress.SimulationProgress] event
            each time EnergyPlus emits a progress line.  Both synchronous
            and async callables are accepted -- async callables are awaited.
            Pass ``"tqdm"`` to use a built-in tqdm progress bar (requires
            ``pip install idfkit[progress]``).
        auto_migrate: When ``True`` and ``model.version`` differs from the
            installed EnergyPlus version, forward-migrate the model before
            running. See [simulate][idfkit.simulation.runner.simulate] for
            the full semantics.

    Returns:
        SimulationResult with paths to output files. Its files are read lazily
        from ``run_dir``, so read them before cleaning it up.

    Raises:
        SimulationError: On timeout or OS error, or when the weather argument
            is refused before EnergyPlus starts: *weather* is an empty
            string; *weather* names a file that does not exist; *weather* is
            ``None`` and the run is not design-day-only; *weather* is
            ``None``, *expand_objects* is ``True`` and the model contains
            Slab or Basement ground heat-transfer objects whose preprocessor
            ``GroundHeatTransfer:Control`` enables; or *weather* is
            ``None`` and the run directory already contains ``in.epw``. Also
            raised before EnergyPlus starts when *annual* is ``True`` and the
            model has no ``RunPeriod``, when *design_day* is ``True`` and
            the model has no ``SizingPeriod:DesignDay``, or when neither is
            set and ``SimulationControl`` leaves EnergyPlus nothing to run:
            no ``RunPeriod`` and no ``SizingPeriod:*`` (as a fresh
            ``new_document()`` has), or both turned off.
        TypeError: If *model* is not a document (``None``, or a path).
        ExpandObjectsError: If a preprocessing step fails.
        EnergyPlusNotFoundError: If EnergyPlus cannot be found.
        VersionMismatchError: If ``model.version`` names another release line
            than the installed EnergyPlus (a ``9.0`` model on 9.0.1 matches) and
            *auto_migrate* is ``False``, or if the model is
            newer than the installed EnergyPlus.
    """
    options: dict[str, Any] = {
        "energyplus": energyplus,
        "expand_objects": expand_objects,
        "annual": annual,
        "design_day": design_day,
        "output_prefix": output_prefix,
        "output_suffix": output_suffix,
        "readvars": readvars,
        "timeout": timeout,
        "preprocessor_timeout": preprocessor_timeout,
        "extra_args": extra_args,
        "cache": cache,
        "on_progress": on_progress,
        "auto_migrate": auto_migrate,
    }
    if fs is None:
        return await _simulate_local(model, weather, output_dir=output_dir, **options)
    if output_dir is None:
        msg = "output_dir is required when using a file system backend"
        raise ValueError(msg)
    # EnergyPlus runs in a local scratch directory, which is uploaded to output_dir and then deleted.
    scratch = Path(tempfile.mkdtemp(prefix="idfkit_sim_"))
    try:
        remote_dir = Path(str(output_dir))
        return await _simulate_local(
            model,
            weather,
            output_dir=scratch,
            publish=lambda local, weather_path: _publish(local, remote_dir, fs, weather_path),
            **options,
        )
    finally:
        await asyncio.to_thread(shutil.rmtree, scratch, ignore_errors=True)

async_simulate_batch

idfkit.simulation.async_batch.async_simulate_batch(jobs, *, energyplus=None, max_concurrent=None, cache=None, fs=None, on_progress=None, fail_fast=False) async

Run multiple EnergyPlus simulations concurrently using asyncio.

This is the async counterpart to simulate_batch. Concurrency is controlled with an asyncio.Semaphore instead of a thread pool.

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 cancels the jobs still queued or running (their EnergyPlus processes are killed) and the batch returns, reporting them in BatchResult.cancelled.

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_concurrent 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
fs FileSystem | AsyncFileSystem | None

Optional file system backend passed through to each async_simulate call.

None
on_progress Callable[[SimulationProgress], Any] | 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. Both sync and async callables are accepted. 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

BatchResult

same order as jobs.

Raises:

Type Description
ValueError

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

Source code in idfkit/simulation/async_batch.py
async def async_simulate_batch(
    jobs: Sequence[SimulationJob],
    *,
    energyplus: EnergyPlusConfig | None = None,
    max_concurrent: int | None = None,
    cache: SimulationCache | None = None,
    fs: FileSystem | AsyncFileSystem | None = None,
    on_progress: Callable[[SimulationProgress], Any] | None = None,
    fail_fast: bool = False,
) -> BatchResult:
    """Run multiple EnergyPlus simulations concurrently using asyncio.

    This is the async counterpart to
    [simulate_batch][idfkit.simulation.batch.simulate_batch].  Concurrency is
    controlled with an [asyncio.Semaphore][] instead of a thread pool.

    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 cancels the jobs
    still queued or running (their EnergyPlus processes are killed) and the
    batch returns, reporting them in
    [BatchResult.cancelled][idfkit.simulation.batch.BatchResult.cancelled].

    Args:
        jobs: Sequence of simulation jobs to execute.
        energyplus: Shared EnergyPlus configuration (auto-discovered if
            ``None``).
        max_concurrent: 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.
        fs: Optional file system backend passed through to each
            [async_simulate][idfkit.simulation.async_runner.async_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.  Both sync and async callables are accepted.
            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``.
    """
    if not jobs:
        msg = "jobs must not be empty"
        raise ValueError(msg)
    check_jobs_for_fs(jobs, fs)

    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_concurrent is None:
            max_concurrent = min(len(jobs), os.cpu_count() or 1)

        logger.info("Starting async batch of %d jobs with concurrency %d", len(jobs), max_concurrent)

        semaphore = asyncio.Semaphore(max_concurrent)
        results: list[SimulationResult | None] = [None] * len(jobs)
        start = time.monotonic()
        stopper = _FailFast(enabled=fail_fast, semaphore=semaphore)

        async def _run_one(idx: int, job: SimulationJob) -> None:
            results[idx] = await stopper.run(
                idx, job, lambda: _async_run_job(idx, job, energyplus, cache, fs, progress_cb)
            )

        tasks = [asyncio.create_task(_run_one(i, job)) for i, job in enumerate(jobs)]
        await asyncio.gather(*tasks)
    finally:
        if progress_cleanup is not None:
            progress_cleanup()

    elapsed = time.monotonic() - start

    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(
        "Async 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

async_simulate_batch_stream

idfkit.simulation.async_batch.async_simulate_batch_stream(jobs, *, energyplus=None, max_concurrent=None, cache=None, fs=None, on_progress=None, fail_fast=False) async

Run simulations concurrently, yielding events as each one completes.

This is an async generator variant of async_simulate_batch that yields SimulationEvent objects in completion order. This enables real-time progress reporting without needing a callback:

.. code-block:: python

async for event in async_simulate_batch_stream(jobs, max_concurrent=4):
    print(f"[{event.completed}/{event.total}] {event.label}")

Closing the generator cancels the jobs still queued or running and kills their EnergyPlus processes. Leaving an async for loop early closes it once the generator is garbage-collected; to close it at a known point, iterate inside contextlib.aclosing(async_simulate_batch_stream(...)).

With fail_fast=True the first failed job cancels the jobs still queued or running. The stream still yields one event per job: each cancelled job's event follows, with event.result.cancelled set.

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_concurrent 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
fs FileSystem | AsyncFileSystem | None

Optional file system backend.

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

Optional callback invoked with SimulationProgress events during each individual simulation. Events include job_index and job_label. 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

Yields:

Type Description
AsyncGenerator[SimulationEvent, None]

SimulationEvent for each completed simulation, in the order

AsyncGenerator[SimulationEvent, None]

they finish.

Raises:

Type Description
ValueError

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

Source code in idfkit/simulation/async_batch.py
async def async_simulate_batch_stream(
    jobs: Sequence[SimulationJob],
    *,
    energyplus: EnergyPlusConfig | None = None,
    max_concurrent: int | None = None,
    cache: SimulationCache | None = None,
    fs: FileSystem | AsyncFileSystem | None = None,
    on_progress: Callable[[SimulationProgress], Any] | None = None,
    fail_fast: bool = False,
) -> AsyncGenerator[SimulationEvent, None]:
    """Run simulations concurrently, yielding events as each one completes.

    This is an async generator variant of [async_simulate_batch][idfkit.simulation.async_batch.async_simulate_batch] that
    yields [SimulationEvent][idfkit.simulation.async_batch.SimulationEvent] objects in *completion order*.  This
    enables real-time progress reporting without needing a callback:

    .. code-block:: python

        async for event in async_simulate_batch_stream(jobs, max_concurrent=4):
            print(f"[{event.completed}/{event.total}] {event.label}")

    Closing the generator cancels the jobs still queued or running and kills
    their EnergyPlus processes. Leaving an ``async for`` loop early closes it
    once the generator is garbage-collected; to close it at a known point,
    iterate inside ``contextlib.aclosing(async_simulate_batch_stream(...))``.

    With ``fail_fast=True`` the first failed job cancels the jobs still queued
    or running. The stream still yields one event per job: each cancelled job's
    event follows, with ``event.result.cancelled`` set.

    Args:
        jobs: Sequence of simulation jobs to execute.
        energyplus: Shared EnergyPlus configuration (auto-discovered if
            ``None``).
        max_concurrent: 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.
        fs: Optional file system backend.
        on_progress: Optional callback invoked with
            [SimulationProgress][idfkit.simulation.progress.SimulationProgress] events
            during each individual simulation.  Events include
            ``job_index`` and ``job_label``.  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.

    Yields:
        [SimulationEvent][idfkit.simulation.async_batch.SimulationEvent] for each completed simulation, in the order
        they finish.

    Raises:
        ValueError: If *jobs* is empty, or *fs* is given and a job has no
            ``output_dir``.
    """
    if not jobs:
        msg = "jobs must not be empty"
        raise ValueError(msg)
    check_jobs_for_fs(jobs, fs)

    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)

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

    semaphore = asyncio.Semaphore(max_concurrent)
    total = len(jobs)
    queue: asyncio.Queue[SimulationEvent] = asyncio.Queue()
    completed_count = 0
    stopper = _FailFast(enabled=fail_fast, semaphore=semaphore)

    async def _run_one(idx: int, job: SimulationJob) -> None:
        nonlocal completed_count
        result = await stopper.run(idx, job, lambda: _async_run_job(idx, job, energyplus, cache, fs, progress_cb))
        completed_count += 1
        await queue.put(
            SimulationEvent(
                index=idx,
                label=job.label,
                result=result,
                completed=completed_count,
                total=total,
            )
        )

    tasks = [asyncio.create_task(_run_one(i, job)) for i, job in enumerate(jobs)]

    try:
        for _ in range(total):
            event = await queue.get()
            yield event
    finally:
        if progress_cleanup is not None:
            progress_cleanup()
        # If the consumer breaks out early, cancel remaining tasks.
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)

SimulationEvent

idfkit.simulation.async_batch.SimulationEvent dataclass

Progress event emitted by async_simulate_batch_stream.

Each event represents a single simulation that has finished (successfully or not). Events are yielded in completion order, not submission order.

Attributes:

Name Type Description
index int

Zero-based position of this job in the original jobs sequence.

label str

Human-readable label from the SimulationJob.

result SimulationResult

The simulation result.

completed int

Number of jobs completed so far (including this one).

total int

Total number of jobs in the batch.

Source code in idfkit/simulation/async_batch.py
@dataclass(frozen=True, slots=True)
class SimulationEvent:
    """Progress event emitted by [async_simulate_batch_stream][idfkit.simulation.async_batch.async_simulate_batch_stream].

    Each event represents a single simulation that has finished (successfully
    or not).  Events are yielded in *completion order*, not submission order.

    Attributes:
        index: Zero-based position of this job in the original *jobs* sequence.
        label: Human-readable label from the [SimulationJob][idfkit.simulation.batch.SimulationJob].
        result: The simulation result.
        completed: Number of jobs completed so far (including this one).
        total: Total number of jobs in the batch.
    """

    index: int
    label: str
    result: SimulationResult
    completed: int
    total: int

completed instance-attribute

index instance-attribute

label instance-attribute

result instance-attribute

total instance-attribute