Simulation API Overview¶
The simulation module provides EnergyPlus execution and result parsing.
Quick Reference¶
| Function/Class | Description |
|---|---|
simulate() |
Run a single simulation |
simulate_batch() |
Run multiple simulations in parallel |
async_simulate() |
Non-blocking single simulation |
async_simulate_batch() |
Non-blocking parallel simulations |
async_simulate_batch_stream() |
Streaming progress via async generator |
SimulationEvent |
Progress event from streaming batch |
find_energyplus() |
Discover EnergyPlus installation |
expand_objects() |
Expand HVACTemplate:* objects |
run_slab_preprocessor() |
Run the Slab ground heat-transfer preprocessor |
run_basement_preprocessor() |
Run the Basement ground heat-transfer preprocessor |
run_preprocessing() |
Run all needed preprocessors (combined pipeline) |
needs_ground_heat_preprocessing() |
Check if model needs GHT preprocessing |
SimulationResult |
Simulation result container |
SimulationJob |
Job specification for batch runs |
BatchResult |
Aggregated batch results |
SQLResult |
SQL database query interface |
SimulationCache |
Content-addressed result cache |
FileSystem |
Pluggable storage protocol |
S3FileSystem |
Amazon S3 storage backend |
Module Contents¶
EnergyPlus simulation execution and result handling.
Provides subprocess-based simulation execution, EnergyPlus installation discovery, structured result containers, output parsing, and variable discovery.
Example
from idfkit import load_idf from idfkit.simulation import simulate, find_energyplus
model = load_idf("building.idf") result = simulate(model, "weather.epw") print(result.errors.summary())
Parser Coverage¶
The module provides parsers for the most commonly used EnergyPlus output formats:
- SQLite (SQLResult): Time-series data, tabular reports, and metadata. This is the recommended output format as it contains all simulation data in a single queryable file.
- ESO/MTR (ESOResult): The Standard Output (
.eso) and Meter (.mtr) time-series files. A fast, pure-Python single-pass reader that parses the data dictionary eagerly and extracts individual variables with a targeted scan — so reading a few variables from a large file does not pay to parse the whole file. Useful when the model does not request SQLite output. - CSV (CSVResult): Time-series data in comma-separated format.
- HTML (HTMLResult): Tabular reports in HTML format.
- RDD/MDD (OutputVariableIndex): Available output variables and meters.
- ERR (ErrorReport): Errors, warnings, and simulation status.
The following formats are intentionally not implemented as the SQLite output covers the same data more reliably and completely:
- EIO: Simulation metadata and invariant outputs (use SQLite instead).
If you have a specific need for these formats, please open an issue describing your use case.
REFUSED_RUN_DIR = Path(os.devnull) / 'idfkit-refused-job'
module-attribute
¶
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. |
BatchProgressCallback
¶
Bases: Protocol
The progress= callback of simulate_batch.
Called once per finished job, with keyword arguments only, so a callback
must accept all four by name (def progress(*, completed, total, label,
success), or **kwargs). A job that fail_fast=True cancelled is
reported too, with success=False, so completed still reaches total.
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. |
results
instance-attribute
¶
total_runtime_seconds
instance-attribute
¶
succeeded
property
¶
Results that completed successfully.
failed
property
¶
Results that failed, not counting the jobs fail_fast=True cancelled.
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.
all_succeeded
property
¶
Whether every job in the batch succeeded.
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.
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 |
label |
str
|
Human-readable label for progress reporting. |
output_dir |
str | Path | None
|
Directory for output files. |
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 ( |
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. |
extra_args |
Sequence[str] | None
|
Additional command-line arguments. Any sequence of
strings is accepted, as |
auto_migrate |
bool
|
Forward-migrate a copy of the model to the installed
EnergyPlus version before the run, as
|
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. |
model
instance-attribute
¶
weather = None
class-attribute
instance-attribute
¶
label = ''
class-attribute
instance-attribute
¶
output_dir = None
class-attribute
instance-attribute
¶
expand_objects = True
class-attribute
instance-attribute
¶
annual = False
class-attribute
instance-attribute
¶
design_day = False
class-attribute
instance-attribute
¶
output_prefix = 'eplus'
class-attribute
instance-attribute
¶
output_suffix = 'C'
class-attribute
instance-attribute
¶
readvars = False
class-attribute
instance-attribute
¶
timeout = 3600.0
class-attribute
instance-attribute
¶
preprocessor_timeout = None
class-attribute
instance-attribute
¶
extra_args = None
class-attribute
instance-attribute
¶
auto_migrate = False
class-attribute
instance-attribute
¶
SimulationCache
¶
Content-addressed simulation result cache.
Each entry is a directory named by the cache key containing a copy of
the simulation run directory, less the weather file (whose contents are
already part of the key), plus a _cache_meta.json manifest.
The cache grows with every new run unless it is bounded: pass max_bytes to evict the least recently used entries after each store, or call prune to trim it by size or age.
The key covers the model, the weather file, the run flags and the
contents of every other file the model names, so editing a staged
Schedule:File CSV (in output_dir or anywhere else) is a miss and
restoring it is a hit again. A model that runs a PythonPlugin:Instance
or an ExternalInterface in PtolemyServer or
FunctionalMockupUnitExport mode has inputs no key can cover, so
simulate and
async_simulate neither
look it up nor store it, and log a warning.
cache_dir
property
¶
Root directory for cached simulation entries.
compute_key(model, weather, *, expand_objects=True, annual=False, design_day=False, output_suffix='C', readvars=False, extra_args=None, search_dirs=())
¶
Compute a deterministic cache key for a simulation invocation.
The model is copied and normalised (Output:SQLite is ensured) so
that models differing only in the presence of that object produce the
same key.
Every file the model names for EnergyPlus to read contributes its
contents: Schedule:File, Schedule:File:Shading, the
Table:* external data files, Construction:WindowDataFile, the
ASHRAE 205 representation files and FMUs. An absolute path is read
as is; a relative path is looked up in search_dirs in order, as
EnergyPlus looks in its working directory and then next to its
executable. A file that cannot be found contributes a marker
instead, so its later appearance changes the key. A model that names
no such file gets the same key as it did before this was added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
AnyIDFDocument
|
The EnergyPlus model. |
required |
weather
|
str | Path | None
|
Path to the weather file, or |
required |
expand_objects
|
bool
|
Whether ExpandObjects will run. |
True
|
annual
|
bool
|
Whether annual simulation is used. |
False
|
design_day
|
bool
|
Whether design-day-only simulation is used. |
False
|
output_suffix
|
Literal['C', 'L', 'D']
|
Output file naming suffix ( |
'C'
|
readvars
|
bool
|
Whether ReadVarsESO post-processing will run. |
False
|
extra_args
|
list[str] | tuple[str, ...] | None
|
Additional command-line arguments. |
None
|
search_dirs
|
Sequence[str | Path]
|
Directories a relative external file path resolves
against, in order. The runners pass the run directory
(when |
()
|
Returns:
| Type | Description |
|---|---|
CacheKey
|
get(key)
¶
Retrieve a cached simulation result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
Cache key from compute_key. |
required |
Returns:
| Type | Description |
|---|---|
SimulationResult | None
|
A SimulationResult if a cache hit exists, otherwise |
SimulationResult | None
|
|
SimulationResult | None
|
cache entry itself: treat that directory as read-only. |
SimulationResult | None
|
simulate copies a hit into its |
SimulationResult | None
|
|
put(key, result)
¶
Store a successful simulation result in the cache.
Only results with success=True are cached. The run directory,
less any .epw weather file, is copied into the cache atomically.
With max_bytes set, the least recently used entries are then
evicted until the cache fits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
CacheKey
|
Cache key from compute_key. |
required |
result
|
SimulationResult
|
Successful simulation result to cache. |
required |
contains(key)
¶
Check whether a cache entry exists for key.
size_bytes()
¶
Total size in bytes of the cache's stored entries.
prune(*, max_bytes=None, max_age=None)
¶
Evict entries to bound the cache's size and age.
Entries not used for longer than max_age are removed first; then, while the cache is larger than max_bytes, the least recently used entry is removed. An entry counts as used when it is stored and on every get hit.
A result whose run_dir is a cache entry (a hit read without an
output_dir) stops working when its entry is removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_bytes
|
int | None
|
Size to bring the cache under, or |
None
|
max_age
|
float | None
|
Age in seconds since last use beyond which an entry is
removed, or |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of entries removed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If max_bytes or max_age is negative. |
clear()
¶
Remove all cached entries.
EnergyPlusConfig
dataclass
¶
Validated EnergyPlus installation configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
executable |
Path
|
Path to the energyplus executable. |
version |
tuple[int, int, int]
|
Parsed version as (major, minor, patch). |
install_dir |
Path
|
Root installation directory. |
idd_path |
Path
|
Path to the Energy+.idd file. |
executable
instance-attribute
¶
version
instance-attribute
¶
install_dir
instance-attribute
¶
idd_path
instance-attribute
¶
weather_dir
property
¶
Path to the bundled WeatherData directory, if present.
schema_path
property
¶
Path to Energy+.schema.epJSON, if present.
expand_objects_exe
property
¶
Path to ExpandObjects executable, if present.
slab_exe
property
¶
Path to the Slab ground heat-transfer preprocessor, if present.
slab_idd
property
¶
Path to SlabGHT.idd, if present.
basement_exe
property
¶
Path to the Basement ground heat-transfer preprocessor, if present.
basement_idd
property
¶
Path to BasementGHT.idd, if present.
version_updater_dir
property
¶
Path to the PreProcess/IDFVersionUpdater directory, if present.
This directory houses the per-step Transition-VX-to-VY binaries
and the VX-Y-Z-Energy+.idd files used to migrate IDF models
between EnergyPlus versions.
transition_exe(from_version, to_version)
¶
Return the transition binary for a single version step, if present.
Probes the registry-exact name first, then patch=0 fallbacks so
callers using version tuples such as (9, 0, 1) still resolve the
Transition-V8-9-0-to-V9-0-0 binary that EnergyPlus actually ships.
Returns:
| Type | Description |
|---|---|
Path | None
|
Path to the transition binary, or |
Path | None
|
directory is missing or no matching binary exists. |
transition_idd(version)
¶
Return the bundled IDD for version inside IDFVersionUpdater, if present.
The transition binaries load V{maj}-{min}-{patch}-Energy+.idd from
the IDFVersionUpdater directory at runtime.
from_path(path)
classmethod
¶
Create config from an explicit installation path.
The path can point to either the installation directory or the energyplus executable directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to EnergyPlus install directory or executable. |
required |
Returns:
| Type | Description |
|---|---|
EnergyPlusConfig
|
Validated EnergyPlusConfig. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If the path is not a valid installation. |
AsyncFileSystem
¶
Bases: Protocol
Protocol for async file system operations used by the async simulation module.
This is the async counterpart to FileSystem. Use this with async_simulate and the async batch functions to avoid blocking the event loop during file I/O — especially important for network-backed storage like S3.
All methods accept str | Path for path arguments.
AsyncLocalFileSystem
¶
Non-blocking local file system using asyncio.to_thread.
Wraps LocalFileSystem so that each blocking I/O call runs in the default executor, keeping the event loop free.
read_bytes(path)
async
¶
Read a file as raw bytes without blocking the event loop.
write_bytes(path, data)
async
¶
Write raw bytes to a file without blocking the event loop.
read_text(path, encoding='utf-8')
async
¶
Read a file as text without blocking the event loop.
write_text(path, text, encoding='utf-8')
async
¶
Write text to a file without blocking the event loop.
exists(path)
async
¶
Check whether a file exists without blocking the event loop.
makedirs(path, *, exist_ok=False)
async
¶
Create directories recursively without blocking the event loop.
copy(src, dst)
async
¶
Copy a file without blocking the event loop.
glob(path, pattern)
async
¶
List files matching a glob pattern without blocking the event loop.
remove(path)
async
¶
Remove a file without blocking the event loop.
AsyncS3FileSystem
¶
Async file system implementation backed by Amazon S3 via aiobotocore.
Requires the aiobotocore package
(install via pip install idfkit[async-s3]).
This is the non-blocking counterpart to S3FileSystem. Use it with async_simulate and the async batch functions to avoid blocking the event loop during S3 I/O.
The client must be initialised via the async context manager protocol:
```python
async with AsyncS3FileSystem(bucket="my-bucket") as fs:
result = await async_simulate(model, weather, output_dir="run-001", fs=fs)
```
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str
|
S3 bucket name. |
required |
prefix
|
str
|
Optional key prefix prepended to all paths. Use this to
namespace simulations (e.g., |
''
|
**boto_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Examples:
from idfkit.simulation import AsyncS3FileSystem, async_simulate
async with AsyncS3FileSystem(bucket="my-bucket", prefix="sims/") as fs:
result = await async_simulate(model, weather, output_dir="run-001", fs=fs)
errors = await result.async_errors()
read_bytes(path)
async
¶
Read a file as raw bytes from S3.
write_bytes(path, data)
async
¶
Write raw bytes to S3.
read_text(path, encoding='utf-8')
async
¶
Read a file as text from S3.
write_text(path, text, encoding='utf-8')
async
¶
Write text to S3.
exists(path)
async
¶
Check whether an object exists in S3.
makedirs(path, *, exist_ok=False)
async
¶
No-op — S3 has no directory concept.
copy(src, dst)
async
¶
Copy an object within the same bucket.
glob(path, pattern)
async
¶
List objects matching a glob pattern under path.
Returns logical paths (without the configured S3 prefix) so that
they can be passed back to other AsyncS3FileSystem methods which
prepend the prefix automatically via _key().
remove(path)
async
¶
Delete an object from S3.
FileSystem
¶
Bases: Protocol
Protocol for file system operations used by the simulation module.
All methods accept str | Path for path arguments.
LocalFileSystem
¶
File system implementation backed by pathlib and shutil.
read_bytes(path)
¶
Read a file as raw bytes.
write_bytes(path, data)
¶
Write raw bytes to a file, creating missing parent directories.
Parents are created so a local run behaves like S3, where writing a key needs no directory to exist first.
read_text(path, encoding='utf-8')
¶
Read a file as text.
write_text(path, text, encoding='utf-8')
¶
Write text to a file, creating missing parent directories.
exists(path)
¶
Check whether a file exists.
makedirs(path, *, exist_ok=False)
¶
Create directories recursively.
copy(src, dst)
¶
Copy a file from src to dst, creating missing parent directories of dst.
glob(path, pattern)
¶
List files matching a glob pattern under path.
remove(path)
¶
Remove a file.
S3FileSystem
¶
File system implementation backed by Amazon S3.
Requires the boto3 package (install via pip install idfkit[s3]).
This backend enables cloud-native simulation workflows where results are stored directly in S3 for later retrieval. EnergyPlus runs locally in a temporary directory, then results are uploaded to S3 after completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket
|
str
|
S3 bucket name. |
required |
prefix
|
str
|
Optional key prefix prepended to all paths. Use this to
namespace simulations (e.g., |
''
|
**boto_kwargs
|
Any
|
Additional keyword arguments passed to
|
{}
|
Examples:
# Basic usage
fs = S3FileSystem(bucket="my-bucket", prefix="simulations/")
# With MinIO (S3-compatible)
fs = S3FileSystem(
bucket="local-bucket",
endpoint_url="http://localhost:9000",
aws_access_key_id="minioadmin",
aws_secret_access_key="minioadmin",
)
# Use with simulate()
result = simulate(model, weather, output_dir="run-001", fs=fs)
read_bytes(path)
¶
Read a file as raw bytes from S3.
write_bytes(path, data)
¶
Write raw bytes to S3.
read_text(path, encoding='utf-8')
¶
Read a file as text from S3.
write_text(path, text, encoding='utf-8')
¶
Write text to S3.
exists(path)
¶
Check whether an object exists in S3.
makedirs(path, *, exist_ok=False)
¶
No-op — S3 has no directory concept.
copy(src, dst)
¶
Copy an object within the same bucket.
glob(path, pattern)
¶
List objects matching a glob pattern under path.
Returns logical paths (without the configured S3 prefix) so that
they can be passed back to other S3FileSystem methods which
prepend the prefix automatically via _key().
remove(path)
¶
Delete an object from S3.
OutputVariableIndex
dataclass
¶
Index of available output variables and meters for a model.
Constructed from .rdd and .mdd files produced by EnergyPlus during a simulation run. Provides search, filtering, and model injection methods.
Attributes:
| Name | Type | Description |
|---|---|---|
variables |
tuple[OutputVariable, ...]
|
Available output variables from the .rdd file. |
meters |
tuple[OutputMeter, ...]
|
Available output meters from the .mdd file. |
variables
instance-attribute
¶
meters
instance-attribute
¶
from_simulation(result)
classmethod
¶
Create an index from a completed simulation result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
SimulationResult
|
A SimulationResult with .rdd (and optionally .mdd) files. |
required |
Returns:
| Type | Description |
|---|---|
OutputVariableIndex
|
An OutputVariableIndex populated from the simulation output. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the .rdd file is not found. |
from_files(rdd_path, mdd_path=None)
classmethod
¶
Create an index from .rdd and .mdd file paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rdd_path
|
str | Path
|
Path to the .rdd file. |
required |
mdd_path
|
str | Path | None
|
Optional path to the .mdd file. |
None
|
Returns:
| Type | Description |
|---|---|
OutputVariableIndex
|
An OutputVariableIndex populated from the files. |
search(pattern)
¶
Search variables and meters by name pattern.
Uses case-insensitive regex matching against variable/meter names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
A regex pattern to match against names. |
required |
Returns:
| Type | Description |
|---|---|
list[OutputVariable | OutputMeter]
|
List of matching OutputVariable and OutputMeter entries. |
filter_by_units(units)
¶
Filter variables and meters by unit type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
units
|
str
|
The unit string to filter by (case-insensitive). |
required |
Returns:
| Type | Description |
|---|---|
list[OutputVariable | OutputMeter]
|
List of matching OutputVariable and OutputMeter entries. |
add_all_to_model(model, *, frequency='Timestep', filter_pattern=None)
¶
Add output variables and meters to a model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
AnyIDFDocument
|
The IDFDocument to add outputs to. |
required |
frequency
|
str
|
The reporting frequency for all added outputs. |
'Timestep'
|
filter_pattern
|
str | None
|
Optional regex pattern to filter which variables and meters are added (case-insensitive match on name). |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of output objects added. |
CSVColumn
dataclass
¶
A single data column from a CSV output file.
Attributes:
| Name | Type | Description |
|---|---|---|
header |
str
|
The raw column header string. |
variable_name |
str
|
Parsed variable name. |
key_value |
str
|
Parsed key value (e.g. |
units |
str
|
Parsed units string. |
values |
tuple[float, ...]
|
The numeric values for this column, across every environment in the file (design days, then run periods), in run order. |
frequency |
str
|
Parsed reporting frequency (e.g. |
CSVResult
dataclass
¶
Parsed EnergyPlus CSV output file.
The CSV file that ReadVarsESO writes carries no environment markers, so
every series spans every environment the run simulated, joined in run
order: the sizing design days first, then the weather run period(s). A
day-of-year index or an annual sum over a column therefore counts the
design days too. To read a single environment, use
SQLResult.get_timeseries
(result.sql), which reads the run period by default, or
ESOResult.get_column
(result.eso), which takes environment_index=.
Attributes:
| Name | Type | Description |
|---|---|---|
timestamps |
tuple[str, ...]
|
The timestamp strings from the Date/Time column. |
columns |
tuple[CSVColumn, ...]
|
Parsed data columns with extracted metadata. |
timestamps
instance-attribute
¶
columns
instance-attribute
¶
from_file(path)
classmethod
¶
from_string(text)
classmethod
¶
get_column(variable_name, key_value=None, frequency=None)
¶
Find the one column reported for a variable, key and frequency.
The lookup must resolve to one column, as SQLResult.get_timeseries does: when a variable is reported for several keys (one per zone, say) or at several frequencies, name the one you want, and the error lists them.
Unlike the SQL and ESO readers, it cannot select an environment: the CSV
file has no explicit environment markers and this parser does not split
environments, so the column holds every environment the run simulated
(design days and run period) joined end to end. For one environment, read
result.sql (run period by default) or
result.eso.get_column(..., environment_index=...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable_name
|
str
|
The variable name to search for (case-insensitive).
A meter is found by its full name ( |
required |
key_value
|
str | None
|
Key value (case-insensitive). Needed only when the variable is reported for more than one key. |
None
|
frequency
|
str | None
|
Frequency (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
CSVColumn
|
The matching CSVColumn. Its values span every environment in the |
CSVColumn
|
file, in run order (design days, then run periods). The parser |
CSVColumn
|
does not split them; only the Date/Time column, where the date |
CSVColumn
|
jumps back at each new environment, hints at the boundaries. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
ErrorMessage
dataclass
¶
ErrorReport
dataclass
¶
Parsed contents of an EnergyPlus .err file.
Attributes:
| Name | Type | Description |
|---|---|---|
fatal |
tuple[ErrorMessage, ...]
|
Fatal error messages. |
severe |
tuple[ErrorMessage, ...]
|
Severe error messages. |
warnings |
tuple[ErrorMessage, ...]
|
Warning messages. |
info |
tuple[ErrorMessage, ...]
|
Informational messages. |
warmup_converged |
bool
|
Whether warmup convergence was reported. |
simulation_complete |
bool
|
Whether the simulation completed successfully. |
raw_text |
str
|
The original unparsed file text. |
fatal
instance-attribute
¶
severe
instance-attribute
¶
warnings
instance-attribute
¶
info
instance-attribute
¶
warmup_converged
instance-attribute
¶
simulation_complete
instance-attribute
¶
raw_text
instance-attribute
¶
has_fatal
property
¶
Whether any fatal errors were found.
has_severe
property
¶
Whether any severe errors were found.
fatal_count
property
¶
Number of fatal errors.
severe_count
property
¶
Number of severe errors.
error_count
property
¶
Total number of fatal + severe errors.
warning_count
property
¶
Total number of warnings.
summary(max_messages=3)
¶
Return a human-readable summary of the error report.
The counts and the run's outcome, then the fatal errors and the first severe ones, with their continuation lines, so the cause of a failed run reads at a glance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_messages
|
int
|
How many severe errors to quote; the fatal ones are always quoted.
|
3
|
Returns:
| Type | Description |
|---|---|
str
|
A multi-line summary string. |
from_file(path)
classmethod
¶
Parse an .err file from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the .err file. |
required |
Returns:
| Type | Description |
|---|---|
ErrorReport
|
Parsed ErrorReport. |
from_string(text)
classmethod
¶
Parse .err content from a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Raw .err file contents. |
required |
Returns:
| Type | Description |
|---|---|
ErrorReport
|
Parsed ErrorReport. |
ESOColumn
dataclass
¶
One variable's time series within a single environment.
Attributes:
| Name | Type | Description |
|---|---|---|
variable |
ESOVariable
|
The ESOVariable this column belongs to. |
environment_index |
int
|
Index of the environment these values belong to.
Look it up in |
timestamps |
tuple[datetime, ...]
|
Timestamp for each data point. |
values |
tuple[float, ...]
|
The reported value for each data point (the primary value for aggregated daily/monthly records). |
variable
instance-attribute
¶
environment_index
instance-attribute
¶
timestamps
instance-attribute
¶
values
instance-attribute
¶
to_dataframe()
¶
Convert to a pandas DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with a |
DataFrame
|
variable. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
plot(*, backend=None, title=None)
¶
Plot this time series as a line chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
PlotBackend | None
|
A PlotBackend instance. If not provided, auto-detects. |
None
|
title
|
str | None
|
Optional plot title. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object from the backend. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If no plotting backend is available. |
ESOEnvironment
dataclass
¶
One environment period (design day or run period) within the file.
Environments appear in the order EnergyPlus ran them: sizing design days
first (in IDF order), then the weather run period(s). index is that
0-based order and is exactly the value used by environment_index
everywhere else (ESOResult.get_column and
ESOColumn.environment_index); title is the human-readable name.
To learn which index is which design day, read ESOResult.environments
and match on title — EnergyPlus does not encode an environment type
code in the ESO format, so the title is the only discriminator (e.g.
"... ANN HTG 99% CONDNS DB" vs "RUN PERIOD 1").
Attributes:
| Name | Type | Description |
|---|---|---|
index |
int
|
0-based order of appearance; pass it as |
title |
str
|
The environment title from the |
latitude |
float
|
Site latitude in degrees. |
longitude |
float
|
Site longitude in degrees. |
time_zone |
float
|
Site time zone in hours from GMT. |
elevation |
float
|
Site elevation in metres. |
ESOResult
¶
Parsed EnergyPlus .eso / .mtr output file.
The data dictionary is parsed on construction; the data section is scanned
lazily on demand (see get_column). Pass eager=True to materialize
every column up front.
A file usually contains several environments — the sizing design days
followed by the weather run period. get_column returns the last one
(the run period) by default. To target a specific design day, read
environments to map each index to its title and pass that index
as environment_index:
eso = ESOResult.from_file("eplusout.eso")
for env in eso.environments:
print(env.index, env.title)
# 0 DENVER ... ANN HTG 99% CONDNS DB
# 1 DENVER ... ANN CLG 1% CONDNS DB=>MWB
# 2 RUN PERIOD 1
# the heating design day is index 0:
col = eso.get_column("Zone Mean Air Temperature", "ZONE ONE", environment_index=0)
Attributes:
| Name | Type | Description |
|---|---|---|
program_version |
The |
|
variables |
tuple[ESOVariable, ...]
|
All variables declared in the data dictionary. |
variables = tuple(self._by_id.values())
instance-attribute
¶
environments
property
¶
All environment periods in the file (lazily scanned and cached).
This is the index → title map for environment_index: each
ESOEnvironment has an
index (use it as environment_index in get_column) and a
title (the design-day / run-period name).
columns
property
¶
Every variable's time series across all environments (full parse).
Accessing this triggers (and caches) a full parse of the data section.
from_bytes(data, *, eager=False)
classmethod
¶
Parse an ESO/MTR file from raw bytes (the fastest entry point).
from_file(path, *, eager=False)
classmethod
¶
Parse an ESO/MTR file from disk.
from_string(text, *, eager=False)
classmethod
¶
Parse ESO/MTR content from a string.
get_variable(variable_name, key_value=None, frequency=None)
¶
Find a declared variable by name (case-insensitive) and optional key/frequency.
Returns the first match, or None; several may match when key_value or
frequency is left out. get_column
refuses such an ambiguous lookup instead.
get_column(variable_name, key_value=None, frequency=None, environment_index=None)
¶
Extract one variable's time series with a single targeted scan.
The lookup must resolve to one reported series, as SQLResult.get_timeseries does: when a variable is reported for several keys (one per zone, say) or at several frequencies, name the one you want, and the error lists them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable_name
|
str
|
Variable name to look up (case-insensitive). |
required |
key_value
|
str | None
|
Key value (e.g. zone name, case-insensitive). Needed only when the variable is reported for more than one key. |
None
|
frequency
|
str | None
|
Frequency (e.g. |
None
|
environment_index
|
int | None
|
Which environment to return. Defaults to the last
environment in the file (typically the run period), mirroring the
most common intent. To pick a specific design day, find its index
by title in |
None
|
Returns:
| Type | Description |
|---|---|
ESOColumn
|
The matching ESOColumn. Its |
ESOColumn
|
|
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
get_columns(series, environment_index=None)
¶
Extract several variables' time series in one scan of the file.
Each get_column call scans the whole data section, so a loop over many variables reads the file once per variable. This reads every requested series in a single pass (series already read are served from the cache).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
Iterable[ESOSeriesSpec]
|
The series to read, each an |
required |
environment_index
|
int | None
|
Which environment to return for every series,
as in |
None
|
Returns:
| Type | Description |
|---|---|
list[ESOColumn]
|
One ESOColumn per item |
list[ESOColumn]
|
of series, in the same order. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
If any series does not resolve to exactly one
reported series or has no data, as in |
to_dataframe(variable_name, key_value=None, frequency=None, environment_index=None)
¶
Extract a variable and return it as a pandas DataFrame.
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
ImportError
|
If pandas is not installed. |
ESOVariable
dataclass
¶
A reporting variable declared in an ESO/MTR data dictionary.
Attributes:
| Name | Type | Description |
|---|---|---|
report_id |
int
|
The integer id that prefixes this variable's data records. |
variable_name |
str
|
The output variable or meter name. |
key_value |
str
|
The key (e.g. zone or surface name); empty for meters. |
units |
str
|
The variable units (may be empty). |
frequency |
str
|
Normalized reporting frequency ( |
num_values |
int
|
Number of numeric values each data record carries (1 for detailed/hourly; more for aggregated daily/monthly min/max records). |
HTMLResult
dataclass
¶
Parsed HTML tabular output from an EnergyPlus simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
tables |
list[HTMLTable]
|
All tables extracted from the file, in document order. |
tables = field(default_factory=lambda: [])
class-attribute
instance-attribute
¶
from_file(path, encoding='latin-1')
classmethod
¶
Parse an EnergyPlus HTML output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str
|
Path to the HTML file (typically |
required |
encoding
|
str
|
File encoding (default |
'latin-1'
|
Returns:
| Type | Description |
|---|---|
HTMLResult
|
Parsed HTMLResult. |
from_string(html)
classmethod
¶
Parse an HTML string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
The raw HTML content. |
required |
Returns:
| Type | Description |
|---|---|
HTMLResult
|
Parsed HTMLResult. |
titletable()
¶
Return (title, rows) pairs like eppy's readhtml.titletable.
Each entry is (bold_title, [header_row, *data_rows]).
tablebyname(name)
¶
Find first table whose title contains name (case-insensitive).
tablebyindex(index)
¶
Get a table by its zero-based position.
tablesbyreport(report_name)
¶
Get all tables belonging to a specific report.
HTMLTable
dataclass
¶
A single table extracted from the EnergyPlus HTML output.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
The bold title preceding the table (e.g.
|
header |
list[str]
|
Column headers: the first |
rows |
list[list[str]]
|
Data rows as lists of strings, without the header row. |
report_name |
str
|
The top-level report name (e.g.
|
for_string |
str
|
The |
title
instance-attribute
¶
header
instance-attribute
¶
rows
instance-attribute
¶
report_name = ''
class-attribute
instance-attribute
¶
for_string = ''
class-attribute
instance-attribute
¶
to_dict()
¶
Convert to a dict mapping row headers to {col_header: value}.
The first column is treated as the row key. Remaining columns are keyed by their respective column headers (starting at index 1). Duplicate row keys are silently overwritten by the last occurrence.
This gives convenient dict-style access similar to eppy's
readhtml.named_grid_h.
OutputMeter
dataclass
¶
An available meter from a .mdd file.
Meters aggregate energy or resource consumption and have no key value, unlike OutputVariable. For post-simulation SQL results where variables and meters are stored together, see VariableInfo.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The meter name (e.g. |
frequency |
str
|
The default reporting frequency (e.g. |
units |
str
|
The meter units (e.g. |
OutputVariable
dataclass
¶
An available output variable from a .rdd file.
Unlike meters, variables are associated with a specific key (zone, surface, etc.). For post-simulation SQL results where variables and meters are stored together, see VariableInfo.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The key value (e.g. |
name |
str
|
The variable name (e.g. |
frequency |
str
|
The default reporting frequency (e.g. |
units |
str
|
The variable units (e.g. |
EnvironmentInfo
dataclass
¶
SQLResult
¶
Query interface for an EnergyPlus SQLite output database.
Opens the database in read-only mode and provides methods for retrieving time-series data, tabular reports, and variable metadata.
Can be used as a context manager:
```python
with SQLResult("eplusout.sql") as sql:
ts = sql.get_timeseries("Zone Mean Air Temperature", "ZONE 1")
```
close()
¶
Close the database connection.
Releases the underlying OS file handle. This matters on Windows,
where an open SQLite connection holds a lock that prevents the
.sql file (and any directory containing it) from being deleted.
Safe to call more than once.
get_timeseries(variable_name, key_value='*', frequency=None, environment=None)
¶
Retrieve a time series for a variable.
The variable name, key and frequency all match case-insensitively, as EnergyPlus matches them. The lookup must resolve to one reported series: when a variable is reported for several keys (one per zone, say) or at several frequencies, name the one you want, and the error lists them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable_name
|
str
|
The output variable name. |
required |
key_value
|
str
|
The key value (e.g. zone name). The default |
'*'
|
frequency
|
str | None
|
Optional frequency filter (e.g. |
None
|
environment
|
Environment | None
|
Which simulation environments to read. |
None
|
Returns:
| Type | Description |
|---|---|
TimeSeriesResult
|
A TimeSeriesResult with timestamps and values. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
ValueError
|
If environment is not a recognized value. |
get_timeseries_many(series, environment=None)
¶
Retrieve several time series in one read of the database.
EnergyPlus does not index ReportData by variable, so each
get_timeseries
call scans the whole table. This reads every requested series in a
single scan, which is much faster than a loop when reading more than
one or two series from a large file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
Iterable[SeriesSpec]
|
The series to read, each a |
required |
environment
|
Environment | None
|
Which simulation environments to read, as in
|
None
|
Returns:
| Type | Description |
|---|---|
list[TimeSeriesResult]
|
One TimeSeriesResult |
list[TimeSeriesResult]
|
per item of series, in the same order. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
If any series does not resolve to exactly one
reported series or has no data for environment, as in
|
ValueError
|
If environment is not a recognized value. |
get_tabular_data(report_name=None, table_name=None, row_name=None, column_name=None, report_for=None)
¶
Retrieve tabular report data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report_name
|
str | None
|
Optional filter by report name. |
None
|
table_name
|
str | None
|
Optional filter by table name. |
None
|
row_name
|
str | None
|
Optional filter by row label. |
None
|
column_name
|
str | None
|
Optional filter by column label. |
None
|
report_for
|
str | None
|
Optional filter by report scope (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
list[TabularRow]
|
List of TabularRow entries matching the filters. With no filter, every row, or an |
list[TabularRow]
|
empty list when the database holds no tabular reports. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
get_tabular_value(report_name, table_name, row_name, column_name, report_for='Entire Facility')
¶
Retrieve a single tabular cell value.
Convenience wrapper around get_tabular_data that returns exactly one cell value. For a number, use get_tabular_float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report_name
|
str
|
Report name (e.g. |
required |
table_name
|
str
|
Table name (e.g. |
required |
row_name
|
str
|
Row label (e.g. |
required |
column_name
|
str
|
Column label (e.g. |
required |
report_for
|
str
|
Report scope (default |
'Entire Facility'
|
Returns:
| Type | Description |
|---|---|
str
|
The cell text, with surrounding whitespace stripped. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
get_tabular_float(report_name, table_name, row_name, column_name, report_for='Entire Facility')
¶
Retrieve a single tabular cell value as a float.
Looks the cell up as get_tabular_value does, then parses it with TabularRow.as_float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report_name
|
str
|
Report name (e.g. |
required |
table_name
|
str
|
Table name (e.g. |
required |
row_name
|
str
|
Row label (e.g. |
required |
column_name
|
str
|
Column label (e.g. |
required |
report_for
|
str
|
Report scope (default |
'Entire Facility'
|
Returns:
| Type | Description |
|---|---|
float
|
The numeric value of the cell. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
A |
ValueError
|
If the cell is not numeric; the message names the cell and quotes its text. |
list_variables()
¶
List all available variables in the database.
Each entry's name, key_value and frequency can be passed
straight to get_timeseries;
a meter's key_value is "".
Returns:
| Type | Description |
|---|---|
list[VariableInfo]
|
List of VariableInfo entries describing each variable. |
list_environments()
¶
List all environment periods in the database.
Returns:
| Type | Description |
|---|---|
list[EnvironmentInfo]
|
List of EnvironmentInfo entries describing each period (e.g. |
list[EnvironmentInfo]
|
design days and run periods). |
list_reports()
¶
List all available tabular report names.
Returns:
| Name | Type | Description |
|---|---|---|
list[str]
|
Sorted list of unique report names. Empty when the database holds no tabular |
|
report |
list[str]
|
EnergyPlus writes them only for a model with |
list[str]
|
( |
|
list[str]
|
|
to_dataframe(variable_name, key_value='*', frequency=None, environment=None)
¶
Retrieve a time series as a pandas DataFrame.
This is a convenience wrapper around get_timeseries that directly returns a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable_name
|
str
|
The output variable name. |
required |
key_value
|
str
|
The key value (case-insensitive). The default |
'*'
|
frequency
|
str | None
|
Optional frequency filter. Required when the variable is reported at more than one frequency. |
None
|
environment
|
Environment | None
|
Which environments to read: |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A pandas DataFrame with a |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
ResultLookupError
|
If the variable, key or frequency is not found,
or if several keys or frequencies match (a |
TabularRow
dataclass
¶
A single row from an EnergyPlus tabular report.
Attributes:
| Name | Type | Description |
|---|---|---|
report_name |
str
|
The report name (e.g. |
report_for |
str
|
The report scope (e.g. |
table_name |
str
|
The table name within the report. |
row_name |
str
|
The row label. |
column_name |
str
|
The column label. |
units |
str
|
The value units. |
value |
str
|
The cell text, with the padding EnergyPlus writes around it stripped
( |
report_name
instance-attribute
¶
report_for
instance-attribute
¶
table_name
instance-attribute
¶
row_name
instance-attribute
¶
column_name
instance-attribute
¶
units
instance-attribute
¶
value
instance-attribute
¶
as_float()
¶
Return the cell value parsed as a float.
Returns:
| Type | Description |
|---|---|
float
|
The numeric value of the cell. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the cell is not numeric (an empty cell, or text such as a zone name or a date); the message names the cell and quotes its text. |
Examples:
TimeSeriesResult
dataclass
¶
A single time series extracted from an EnergyPlus SQL database.
Attributes:
| Name | Type | Description |
|---|---|---|
variable_name |
str
|
The output variable name. |
key_value |
str
|
The key value (e.g. zone or surface name). |
units |
str
|
The variable units. |
frequency |
str
|
The reporting frequency. |
timestamps |
tuple[datetime, ...]
|
Timestamp for each data point. |
values |
tuple[float, ...]
|
Numeric values for each data point. |
variable_name
instance-attribute
¶
key_value
instance-attribute
¶
units
instance-attribute
¶
frequency
instance-attribute
¶
timestamps
instance-attribute
¶
values
instance-attribute
¶
to_dataframe()
¶
Convert to a pandas DataFrame.
Requires pandas to be installed.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with a |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
plot(*, backend=None, title=None)
¶
Plot this time series as a line chart.
Auto-detects the plotting backend if not provided. Requires matplotlib or plotly to be installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
PlotBackend | None
|
A PlotBackend instance. If not provided, auto-detects. |
None
|
title
|
str | None
|
Optional plot title. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object from the backend. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If no plotting backend is available. |
VariableInfo
dataclass
¶
Metadata about an available variable or meter in the SQL database.
This class represents both regular variables and meters because EnergyPlus
stores them in a single ReportDataDictionary table, distinguished only
by an IsMeter column. Use the is_meter flag to tell them
apart.
For pre-simulation discovery from .rdd / .mdd files, see the
separate OutputVariable and
OutputMeter classes instead.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The variable name. |
key_value |
str
|
The key value. Empty for meters. |
frequency |
str
|
The reporting frequency. |
units |
str
|
The variable units. |
is_meter |
bool
|
Whether this is a meter (vs. a regular variable). |
variable_type |
str
|
The variable type string (e.g. |
PlotBackend
¶
Bases: Protocol
Protocol for plotting backends used by the simulation module.
Implementations must provide methods for common chart types. Each method
returns a figure object native to the backend (e.g. matplotlib Figure
or plotly Figure).
line(x, y, *, title=None, xlabel=None, ylabel=None, label=None)
¶
Create a single line plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Sequence[Any]
|
X-axis values (e.g. timestamps). |
required |
y
|
Sequence[float]
|
Y-axis values. |
required |
title
|
str | None
|
Optional plot title. |
None
|
xlabel
|
str | None
|
Optional X-axis label. |
None
|
ylabel
|
str | None
|
Optional Y-axis label. |
None
|
label
|
str | None
|
Optional line label for legend. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object native to the backend. |
multi_line(x, y_series, *, title=None, xlabel=None, ylabel=None)
¶
Create a multi-line plot with legend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Sequence[Any]
|
Shared X-axis values. |
required |
y_series
|
dict[str, Sequence[float]]
|
Mapping of label to Y values for each line. |
required |
title
|
str | None
|
Optional plot title. |
None
|
xlabel
|
str | None
|
Optional X-axis label. |
None
|
ylabel
|
str | None
|
Optional Y-axis label. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object native to the backend. |
heatmap(data, *, x_labels=None, y_labels=None, title=None, colorbar_label=None)
¶
Create a 2D heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Sequence[Sequence[float]]
|
2D array of values (rows, columns). |
required |
x_labels
|
Sequence[str] | None
|
Optional labels for columns. |
None
|
y_labels
|
Sequence[str] | None
|
Optional labels for rows. |
None
|
title
|
str | None
|
Optional plot title. |
None
|
colorbar_label
|
str | None
|
Optional label for the colorbar. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object native to the backend. |
bar(categories, values, *, title=None, xlabel=None, ylabel=None)
¶
Create a bar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
categories
|
Sequence[str]
|
Category labels for each bar. |
required |
values
|
Sequence[float]
|
Values for each bar. |
required |
title
|
str | None
|
Optional plot title. |
None
|
xlabel
|
str | None
|
Optional X-axis label. |
None
|
ylabel
|
str | None
|
Optional Y-axis label. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object native to the backend. |
stacked_bar(categories, series, *, title=None, xlabel=None, ylabel=None)
¶
Create a stacked bar chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
categories
|
Sequence[str]
|
Category labels for each bar group. |
required |
series
|
dict[str, Sequence[float]]
|
Mapping of series label to values. |
required |
title
|
str | None
|
Optional plot title. |
None
|
xlabel
|
str | None
|
Optional X-axis label. |
None
|
ylabel
|
str | None
|
Optional Y-axis label. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object native to the backend. |
ProgressParser
¶
Parse EnergyPlus stdout lines into SimulationProgress events.
Maintains internal state to track the current environment, warmup iteration count, and simulation day for percentage estimation.
Recent EnergyPlus releases (26.1, for one) print Starting Simulation at
01/01/2013 for RUN PERIOD 1 without the period's end date, so the parser cannot learn
the length of the period from stdout alone. Pass environment_days
(see environment_days) so it
can still report percent and sim_total_days. EnergyPlus prints
EnergyPlus Completed Successfully to stderr: feed stderr lines to
parse_line too to
get the "complete" event, which is emitted at most once.
A new instance should be created for each simulation run. The parser
is designed to be defensive — unrecognised lines return None and
never raise.
Examples:
parser = ProgressParser()
for line in energyplus_stdout_lines:
event = parser.parse_line(line)
if event is not None:
print(event.phase, event.percent)
set_job_context(index, label)
¶
parse_line(line)
¶
Parse a single stdout line into a progress event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
A single line from EnergyPlus stdout. |
required |
Returns:
| Type | Description |
|---|---|
SimulationProgress | None
|
A SimulationProgress event, or |
SimulationProgress | None
|
does not contain progress information. |
SimulationProgress
dataclass
¶
Progress event emitted during a single EnergyPlus simulation.
This dataclass represents a progress update parsed from EnergyPlus
stdout output. It is passed to user-supplied on_progress callbacks
on simulate and
async_simulate.
Attributes:
| Name | Type | Description |
|---|---|---|
phase |
Literal['preprocessing', 'initializing', 'warmup', 'simulating', 'postprocessing', 'complete']
|
Current simulation phase. |
message |
str
|
Raw EnergyPlus stdout line (stripped). |
percent |
float | None
|
Estimated completion percentage (0.0-100.0), or |
environment |
str | None
|
Name of the current simulation environment, if known. |
warmup_day |
int | None
|
Current warmup iteration (1-based), only set during
the |
sim_day |
int | None
|
Current simulation day-of-year (1-based), only set during
the |
sim_total_days |
int | None
|
Total number of simulation days, only set when the simulation period is known. |
job_index |
int | None
|
Index of this job in a batch, or |
job_label |
str | None
|
Label of this job in a batch, or |
phase
instance-attribute
¶
message
instance-attribute
¶
percent = None
class-attribute
instance-attribute
¶
environment = None
class-attribute
instance-attribute
¶
warmup_day = None
class-attribute
instance-attribute
¶
sim_day = None
class-attribute
instance-attribute
¶
sim_total_days = None
class-attribute
instance-attribute
¶
job_index = None
class-attribute
instance-attribute
¶
job_label = None
class-attribute
instance-attribute
¶
SimulationResult
dataclass
¶
Result of an EnergyPlus simulation run.
The parsed-output accessors (sql, csv, eso, mtr, html, variables and
their async_* counterparts) never return None: when the run produced no such file they
raise OutputNotFoundError, whose message says which
output object to add. Test for a file without raising with its path property, e.g.
result.sql_path is None.
Attributes:
| Name | Type | Description |
|---|---|---|
run_dir |
Path
|
Directory containing all simulation output. |
success |
bool
|
Whether the simulation exited successfully. |
exit_code |
int | None
|
Process exit code (None if timed out). |
stdout |
str
|
Captured standard output. |
stderr |
str
|
Captured standard error. |
runtime_seconds |
float
|
Wall-clock execution time in seconds. |
output_prefix |
str
|
Output file prefix (default "eplus"). |
fs |
FileSystem | None
|
Optional sync file system backend for reading output files. |
async_fs |
AsyncFileSystem | None
|
Optional async file system backend for non-blocking reads. Set automatically by async_simulate when an AsyncFileSystem is provided. |
migration_report |
MigrationReport | None
|
Populated when |
output_suffix |
Literal['C', 'L', 'D'] | None
|
The run's |
refusal |
str | None
|
Why a batch job produced no simulation result: the message
of the exception |
cached |
bool
|
|
owns_run_dir |
bool
|
|
cancelled |
bool
|
|
run_dir
instance-attribute
¶
success
instance-attribute
¶
exit_code
instance-attribute
¶
stdout = field(repr=False)
class-attribute
instance-attribute
¶
stderr = field(repr=False)
class-attribute
instance-attribute
¶
runtime_seconds
instance-attribute
¶
output_prefix = 'eplus'
class-attribute
instance-attribute
¶
fs = field(default=None, repr=False)
class-attribute
instance-attribute
¶
async_fs = field(default=None, repr=False)
class-attribute
instance-attribute
¶
migration_report = field(default=None, repr=False)
class-attribute
instance-attribute
¶
output_suffix = field(default=None, repr=False)
class-attribute
instance-attribute
¶
refusal = None
class-attribute
instance-attribute
¶
cached = False
class-attribute
instance-attribute
¶
owns_run_dir = field(default=False, repr=False)
class-attribute
instance-attribute
¶
cancelled = False
class-attribute
instance-attribute
¶
errors
property
¶
Parsed error report from the .err file (lazily cached).
Returns:
| Type | Description |
|---|---|
ErrorReport
|
Parsed ErrorReport from the simulation's .err output. |
sql
property
¶
Parsed SQL output database (lazily cached).
Returns:
| Type | Description |
|---|---|
SQLResult
|
An SQLResult for querying time-series and tabular data. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .sql file. The message names the output
object to add, or how to read why the run failed. Check |
variables
property
¶
Output variable/meter index from .rdd/.mdd files (lazily cached).
Returns:
| Type | Description |
|---|---|
OutputVariableIndex
|
An OutputVariableIndex for searching and injecting output |
OutputVariableIndex
|
variables. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .rdd file. The message names the output
object to add, or how to read why the run failed. Check |
csv
property
¶
Parsed CSV output (lazily cached).
Returns:
| Type | Description |
|---|---|
CSVResult
|
A CSVResult with extracted column metadata and values. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .csv file. The message names the output
object to add, or how to read why the run failed. Check |
html
property
¶
Parsed HTML tabular output (lazily cached).
Returns:
| Type | Description |
|---|---|
HTMLResult
|
An HTMLResult with extracted tables and titles. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no HTML table report. The message names the output
object to add, or how to read why the run failed. Check |
eso
property
¶
Parsed ESO time-series output (lazily cached).
Returns:
| Type | Description |
|---|---|
ESOResult
|
An ESOResult for extracting variable time series. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .eso file. The message names the output
object to add, or how to read why the run failed. Check |
mtr
property
¶
Parsed MTR meter time-series output (lazily cached).
The .mtr meter file uses the same format as .eso, so it is parsed by the same reader.
Returns:
| Type | Description |
|---|---|
ESOResult
|
An ESOResult for extracting meter time series. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .mtr file. The message names the output
object to add, or how to read why the run failed. Check |
sql_path
property
¶
Path to the SQLite output file, if present.
err_path
property
¶
Path to the .err output file, if present.
eso_path
property
¶
Path to the .eso output file, if present.
mtr_path
property
¶
Path to the .mtr meter output file, if present.
csv_path
property
¶
Path to the .csv output file, if present.
html_path
property
¶
Path to the HTML tabular output file, if present.
rdd_path
property
¶
Path to the .rdd output file, if present.
mdd_path
property
¶
Path to the .mdd output file, if present.
close()
¶
Release any open file handles held by cached parsers.
Closes the SQLite connection opened lazily by sql / async_sql (and removes the temporary copy made for remote file systems). The other parsers read their files eagerly and hold no handles, so this is currently a no-op for them.
Call this before deleting the run directory yourself. On Windows an
open SQLite connection locks eplus.sql and blocks shutil.rmtree
/ TemporaryDirectory cleanup with PermissionError [WinError 32].
Safe to call more than once; the cached connection is reopened on next
access if needed. Leaves run_dir in place; see
cleanup to delete it.
cleanup()
¶
Close open handles and delete run_dir if idfkit created it.
simulate() without an output_dir runs EnergyPlus in a new
temporary directory, which nothing deletes on its own because the
output accessors read their files from it lazily. This deletes it once
you are done with the result. A caller-supplied output_dir, a remote
fs directory and a cache entry are never touched
(owns_run_dir
is False for them): for those this only calls
close.
The SQLite connection is closed first, so the delete is not blocked by a file lock on Windows. Read what you need before calling it: an output not parsed before the delete can no longer be read. Safe to call more than once.
Using the result as a context manager calls this on exit::
with simulate(model, "weather.epw") as result:
print(result.errors.summary())
# the temporary run directory is gone here
Raises:
| Type | Description |
|---|---|
OSError
|
If the directory exists and cannot be deleted. |
async_cleanup()
async
¶
Close open handles and delete run_dir if idfkit created it (async).
Non-blocking counterpart to
cleanup: the delete
runs in a worker thread. async with calls this on exit.
raise_for_status()
¶
Raise if the run failed; return this result if it succeeded.
simulate() reports a failed run in the result rather than raising, so a caller that
wants to stop on failure calls this: result = simulate(doc, epw).raise_for_status().
Returns:
| Type | Description |
|---|---|
SimulationResult
|
This result, when success is true. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
If the run failed. Its message names the |
RuntimeError
|
If the result reads its files through an |
async_raise_for_status()
async
¶
Raise if the run failed; return this result if it succeeded (async).
Non-blocking counterpart to raise_for_status.
Raises:
| Type | Description |
|---|---|
SimulationError
|
If the run failed. |
async_errors()
async
¶
Parsed error report from the .err file (async, lazily cached).
Non-blocking counterpart to errors that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
ErrorReport
|
Parsed ErrorReport from the simulation's .err output. |
async_sql()
async
¶
Parsed SQL output database (async, lazily cached).
Non-blocking counterpart to sql that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
SQLResult
|
An SQLResult for querying time-series and tabular data. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .sql file. The message names the output
object to add, or how to read why the run failed. Check |
async_variables()
async
¶
Output variable/meter index (async, lazily cached).
Non-blocking counterpart to variables that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
OutputVariableIndex
|
An OutputVariableIndex for searching and injecting output |
OutputVariableIndex
|
variables. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .rdd file. The message names the output
object to add, or how to read why the run failed. Check |
async_csv()
async
¶
Parsed CSV output (async, lazily cached).
Non-blocking counterpart to csv that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
CSVResult
|
A CSVResult with extracted column metadata and values. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .csv file. The message names the output
object to add, or how to read why the run failed. Check |
async_html()
async
¶
Parsed HTML tabular output (async, lazily cached).
Non-blocking counterpart to html that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
HTMLResult
|
An HTMLResult with extracted tables and titles. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no HTML table report. The message names the output
object to add, or how to read why the run failed. Check |
async_eso()
async
¶
Parsed ESO time-series output (async, lazily cached).
Non-blocking counterpart to eso that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
ESOResult
|
An ESOResult for extracting variable time series. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .eso file. The message names the output
object to add, or how to read why the run failed. Check |
async_mtr()
async
¶
Parsed MTR meter time-series output (async, lazily cached).
Non-blocking counterpart to mtr that uses async_fs for file reads.
Returns:
| Type | Description |
|---|---|
ESOResult
|
An ESOResult for extracting meter time series. |
Raises:
| Type | Description |
|---|---|
OutputNotFoundError
|
If the run produced no .mtr file. The message names the output
object to add, or how to read why the run failed. Check |
from_directory(path, *, output_prefix='eplus', output_suffix=None, fs=None, async_fs=None)
classmethod
¶
Reconstruct a SimulationResult from an existing output directory.
Useful for inspecting results from a previous simulation run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the simulation output directory. |
required |
output_prefix
|
str
|
Output file prefix used during the run. |
'eplus'
|
output_suffix
|
Literal['C', 'L', 'D'] | None
|
The run's |
None
|
fs
|
FileSystem | None
|
Optional sync file system backend for reading output files. |
None
|
async_fs
|
AsyncFileSystem | None
|
Optional async file system backend for non-blocking reads. |
None
|
Returns:
| Type | Description |
|---|---|
SimulationResult
|
SimulationResult pointing to the existing output. |
prep_outputs(model)
¶
Add standard output objects to the model if not already present.
Ensures the model includes:
Output:SQLite(SimpleAndTabular) — for SQL-based result queriesOutput:Table:SummaryReports(AllSummary) — for tabular reportsOutput:VariableDictionary(Regular) — for.rdd/.mddgeneration
This is a superset of ensure_sql_output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
AnyIDFDocument
|
The model to modify in place. |
required |
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
|
max_concurrent
|
int | None
|
Maximum number of concurrent simulations. Defaults
to |
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
|
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
|
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
|
max_concurrent
|
int | None
|
Maximum number of concurrent simulations. Defaults
to |
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
|
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
|
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
|
output_dir
|
str | Path | None
|
Directory for output files. |
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
|
annual
|
bool
|
Run annual simulation ( |
False
|
design_day
|
bool
|
Run design-day-only simulation ( |
False
|
output_prefix
|
str
|
Prefix for output files (default "eplus"). |
'eplus'
|
output_suffix
|
Literal['C', 'L', 'D']
|
EnergyPlus |
'C'
|
readvars
|
bool
|
Run ReadVarsESO after simulation ( |
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
|
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
|
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 |
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 |
None
|
auto_migrate
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
SimulationResult
|
SimulationResult with paths to output files. Its files are read lazily |
SimulationResult
|
from |
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
|
TypeError
|
If model is not a document ( |
ExpandObjectsError
|
If a preprocessing step fails. |
EnergyPlusNotFoundError
|
If EnergyPlus cannot be found. |
VersionMismatchError
|
If |
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
|
max_workers
|
int | None
|
Maximum number of concurrent simulations. Defaults
to |
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 |
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
|
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
|
TypeError
|
If progress cannot be called with the four keyword arguments above. |
find_energyplus(*, version=None, path=None)
¶
Find an EnergyPlus installation.
Discovery order
- Explicit path argument.
ENERGYPLUS_DIRenvironment variable.energyplusonPATH(via shutil.which).- Platform-specific default directories (newest version first).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
version
|
tuple[int, int, int] | str | None
|
Optional version filter. Accepts |
None
|
path
|
str | Path | None
|
Explicit path to EnergyPlus install directory or executable. |
None
|
Returns:
| Type | Description |
|---|---|
EnergyPlusConfig
|
Validated EnergyPlusConfig. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If no matching installation is found. |
expand_objects(model, *, energyplus=None, timeout=120.0)
¶
Run the EnergyPlus ExpandObjects preprocessor and return the expanded document.
ExpandObjects replaces HVACTemplate:* objects with their fully
specified low-level HVAC equivalents. The original model is not
mutated.
If the document contains no HVACTemplate:* objects a
copy with no filepath is returned
immediately without invoking the preprocessor (no EnergyPlus installation
required).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_DocT
|
The EnergyPlus model to expand. |
required |
energyplus
|
EnergyPlusConfig | None
|
Pre-configured EnergyPlus installation. If |
None
|
timeout
|
float
|
Maximum time in seconds to wait for the preprocessor (default 120). |
120.0
|
Returns:
| Type | Description |
|---|---|
_DocT
|
A new IDFDocument containing the expanded |
_DocT
|
objects. Its |
_DocT
|
to an explicit path, e.g. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If no EnergyPlus installation (and therefore
no |
ExpandObjectsError
|
If the |
needs_ground_heat_preprocessing(model)
¶
Return True if model contains ground heat-transfer objects.
Checks for GroundHeatTransfer:Slab:* and
GroundHeatTransfer:Basement:* objects that require the Slab or
Basement preprocessor before simulation.
This is used by simulate to decide whether to auto-run the preprocessing pipeline.
run_basement_preprocessor(model, *, energyplus=None, weather=None, timeout=120.0)
¶
Run the Basement ground heat-transfer preprocessor and return the expanded document.
The workflow is:
ExpandObjectsextractsGroundHeatTransfer:Basement:*objects from the model intoBasementGHTIn.idf.- The Basement preprocessor reads
BasementGHTIn.idfand computes ground temperatures, writingEPObjects.TXT. - The resulting boundary conditions are appended to the expanded IDF.
The original model is not mutated.
If the document contains no GroundHeatTransfer:Basement:* objects a
copy with no filepath is returned
immediately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_DocT
|
The EnergyPlus model containing
|
required |
energyplus
|
EnergyPlusConfig | None
|
Pre-configured EnergyPlus installation. If |
None
|
weather
|
str | Path | None
|
Path to a weather file ( |
None
|
timeout
|
float
|
Maximum time in seconds for each subprocess invocation (default 120). |
120.0
|
Returns:
| Type | Description |
|---|---|
_DocT
|
A new IDFDocument with basement ground |
_DocT
|
temperatures appended. Its |
_DocT
|
to an explicit path, e.g. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If no EnergyPlus installation is found. |
ExpandObjectsError
|
If any preprocessor step fails, including a Fatal
|
run_preprocessing(model, *, energyplus=None, weather=None, timeout=120.0)
¶
Run ExpandObjects and any required ground heat-transfer preprocessors.
This is a convenience function that runs all needed preprocessors in
a single call. It runs ExpandObjects once, then checks which
preprocessor input files were produced (GHTIn.idf and/or
BasementGHTIn.idf) and runs the corresponding Fortran solvers.
simulate calls this automatically
when the model contains ground heat-transfer objects and
expand_objects is True. Call it directly only when you need to
inspect or modify the preprocessed model before simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_DocT
|
The EnergyPlus model to preprocess. |
required |
energyplus
|
EnergyPlusConfig | None
|
Pre-configured EnergyPlus installation. If |
None
|
weather
|
str | Path | None
|
Path to a weather file ( |
None
|
timeout
|
float
|
Maximum time in seconds for each subprocess invocation (default 120). |
120.0
|
Returns:
| Type | Description |
|---|---|
_DocT
|
A new IDFDocument with all |
_DocT
|
preprocessing applied. Its |
_DocT
|
to an explicit path, e.g. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If no EnergyPlus installation is found. |
ExpandObjectsError
|
If any preprocessor step fails. |
run_slab_preprocessor(model, *, energyplus=None, weather=None, timeout=120.0)
¶
Run the Slab ground heat-transfer preprocessor and return the expanded document.
The workflow is:
ExpandObjectsextractsGroundHeatTransfer:Slab:*objects from the model intoGHTIn.idf.- The Slab preprocessor reads
GHTIn.idfand computes monthly ground surface temperatures, writingSLABSurfaceTemps.TXT. - The resulting temperature schedules are appended to the expanded IDF.
The original model is not mutated.
If the document contains no GroundHeatTransfer:Slab:* objects a
copy with no filepath is returned
immediately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_DocT
|
The EnergyPlus model containing |
required |
energyplus
|
EnergyPlusConfig | None
|
Pre-configured EnergyPlus installation. If |
None
|
weather
|
str | Path | None
|
Path to a weather file ( |
None
|
timeout
|
float
|
Maximum time in seconds for each subprocess invocation (default 120). |
120.0
|
Returns:
| Type | Description |
|---|---|
_DocT
|
A new IDFDocument with slab ground |
_DocT
|
temperatures appended. Its |
_DocT
|
to an explicit path, e.g. |
Raises:
| Type | Description |
|---|---|
EnergyPlusNotFoundError
|
If no EnergyPlus installation is found. |
ExpandObjectsError
|
If any preprocessor step fails, including a Fatal
|
get_default_backend()
¶
Auto-detect and return an available plotting backend.
Tries matplotlib first, then plotly. Raises ImportError if neither is available.
Returns:
| Type | Description |
|---|---|
PlotBackend
|
A PlotBackend instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If neither matplotlib nor plotly is installed. |
plot_comfort_hours(sql, zones, *, comfort_min=20.0, comfort_max=26.0, frequency=None, backend=None, title='Comfort Hours by Zone and Month')
¶
Create a heatmap of comfort hours by zone and month.
For each zone, calculates the percentage of hours within the comfort range for each month and displays as a heatmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
SQLResult
|
An open SQLResult database. |
required |
zones
|
Sequence[str]
|
Zone names to analyze. |
required |
comfort_min
|
float
|
Minimum comfort temperature (default 20C). |
20.0
|
comfort_max
|
float
|
Maximum comfort temperature (default 26C). |
26.0
|
frequency
|
str | None
|
Reporting frequency of |
None
|
backend
|
PlotBackend | None
|
Plotting backend to use. Auto-detects if not provided. |
None
|
title
|
str
|
Plot title. |
'Comfort Hours by Zone and Month'
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object from the backend. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
If the variable is not reported for a zone, or is
reported at several frequencies, none of them hourly, and
frequency is |
plot_energy_balance(sql, *, backend=None, title='End-Use Energy by Category')
¶
Create a bar chart of end-use energy consumption.
Extracts data from the AnnualBuildingUtilityPerformanceSummary report
and plots energy consumption by end-use category, summed across fuels.
Only energy columns are summed: the Water column (m3 or gal) is left
out. The axis is labelled with the report's energy unit (GJ for SI
reports, kBtu for IP); when the report mixes energy units (IP with
electricity in kWh, for example) every value is converted to the unit
most of its cells use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
SQLResult
|
An open SQLResult database. |
required |
backend
|
PlotBackend | None
|
Plotting backend to use. Auto-detects if not provided. |
None
|
title
|
str
|
Plot title. |
'End-Use Energy by Category'
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object from the backend. |
Raises:
| Type | Description |
|---|---|
ResultLookupError
|
If the database has no |
plot_temperature_profile(sql, zones, *, backend=None, title='Zone Air Temperatures', frequency=None)
¶
Create a multi-line plot of zone air temperatures.
Queries Zone Mean Air Temperature for each specified zone and
plots them on a shared time axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
SQLResult
|
An open SQLResult database. |
required |
zones
|
Sequence[str]
|
Zone names to plot. |
required |
backend
|
PlotBackend | None
|
Plotting backend to use. Auto-detects if not provided. |
None
|
title
|
str
|
Plot title. |
'Zone Air Temperatures'
|
frequency
|
str | None
|
Optional frequency filter (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A figure object from the backend. |
tqdm_progress(*, desc='Simulating', bar_format='{l_bar}{bar}| {n:.0f}/{total_fmt}% [{elapsed}<{remaining}]', leave=True, position=None, file=None, **tqdm_kwargs)
¶
Context manager that yields a tqdm-based on_progress callback.
The progress bar is automatically closed when the context exits, even if an exception is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
desc
|
str
|
Progress bar description (left label). |
'Simulating'
|
bar_format
|
str
|
tqdm bar format string. The default shows percentage, elapsed and estimated remaining time. |
'{l_bar}{bar}| {n:.0f}/{total_fmt}% [{elapsed}<{remaining}]'
|
leave
|
bool
|
Whether the bar remains visible after completion. |
True
|
position
|
int | None
|
Line position for the bar (useful for nested bars). |
None
|
file
|
Any
|
Output stream (default: |
None
|
**tqdm_kwargs
|
Any
|
Extra keyword arguments forwarded to |
{}
|
Yields:
| Type | Description |
|---|---|
Callable[[SimulationProgress], None]
|
A callback suitable for the |
Raises:
| Type | Description |
|---|---|
ImportError
|
If tqdm is not installed. |
Examples:
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)
¶
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 | None = None,
on_progress: Callable[[SimulationProgress], Any]
| Literal["tqdm"]
| None = None,
auto_migrate: bool = False,
) -> SimulationResult
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 | None = None,
on_progress: Callable[[SimulationProgress], Any]
| Literal["tqdm"]
| None = None,
auto_migrate: bool = False,
) -> SimulationResult
Run an EnergyPlus simulation.
Creates an isolated run directory, writes the model, and executes EnergyPlus as a subprocess. The caller's model is not mutated.
When expand_objects is True (the default) and the model contains
GroundHeatTransfer:Slab:* or GroundHeatTransfer:Basement:*
objects, the Slab and/or Basement ground heat-transfer preprocessors
are run automatically before simulation. This is equivalent to
calling run_slab_preprocessor or
run_basement_preprocessor
individually, but happens transparently.
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
|
output_dir
|
str | Path | None
|
Directory for output files. |
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
|
annual
|
bool
|
Run annual simulation ( |
False
|
design_day
|
bool
|
Run design-day-only simulation ( |
False
|
output_prefix
|
str
|
Prefix for output files (default "eplus"). |
'eplus'
|
output_suffix
|
Literal['C', 'L', 'D']
|
EnergyPlus |
'C'
|
readvars
|
bool
|
Run ReadVarsESO after simulation ( |
False
|
timeout
|
float
|
Maximum runtime in seconds (default 3600). Applied only to the main EnergyPlus subprocess; preprocessor stages (ExpandObjects, Slab, Basement) 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
|
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
|
None
|
fs
|
FileSystem | None
|
Optional file system backend for storing results on remote
storage (e.g., S3). When provided, Note The |
None
|
on_progress
|
Callable[[SimulationProgress], Any] | Literal['tqdm'] | None
|
Optional callback invoked with a
SimulationProgress event
each time EnergyPlus emits a progress line (warmup iterations,
simulation day changes, post-processing steps, etc.). Pass
|
None
|
auto_migrate
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
SimulationResult
|
SimulationResult with paths to output files. Its files are read lazily |
SimulationResult
|
from |
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
|
TypeError
|
If model is not a document ( |
ExpandObjectsError
|
If a preprocessing step (ExpandObjects, Slab, or Basement) fails during automatic preprocessing. |
EnergyPlusNotFoundError
|
If EnergyPlus cannot be found. |
VersionMismatchError
|
If |