How to query simulation SQL output¶
The SQLResult class provides structured access to EnergyPlus's SQLite
output database, containing time-series data, tabular reports, and metadata.
Python only, permanently
Running a locally installed EnergyPlus and reading its results belongs to Python alone. JavaScript is not waiting on a port and will not gain a counterpart: this is a permanent boundary, so no issue tracks it, and moving the capability out of that state takes a constitutional amendment rather than a ledger edit.
Requires an EnergyPlus installation on the machine and a subprocess to drive it, then
reads the eplusout files that run leaves on disk. Neither the installation nor the
subprocess is available in a browser, which is the runtime the JavaScript library
targets. JavaScript reaches EnergyPlus by the other mechanism instead: see
browser-simulation, which is not a
workaround for this entry but a different capability.
The full entry, including the vocabulary this capability owns, is on the capability parity page.
Opening the Database¶
from idfkit.simulation import simulate
result = simulate(model, weather)
sql = result.sql # raises OutputNotFoundError if the run wrote no .sql file
Or open directly:
Time-Series Data¶
Basic Query¶
ts = sql.get_timeseries(
variable_name="Zone Mean Air Temperature",
key_value="THERMAL ZONE 1",
)
print(f"Variable: {ts.variable_name}")
print(f"Key: {ts.key_value}")
print(f"Units: {ts.units}")
print(f"Frequency: {ts.frequency}")
print(f"Data points: {len(ts.values)}")
print(f"Min: {min(ts.values):.1f}, Max: {max(ts.values):.1f}")
A query returns a TimeSeriesResult. For its full list of attributes and
methods, see the
TimeSeriesResult reference.
Filtering by Environment¶
Specify which simulation environment to query:
# Design day results only (use for design_day=True simulations)
ts = sql.get_timeseries(
"Zone Mean Air Temperature",
"ZONE 1",
environment="sizing",
)
# Run period results only
ts = sql.get_timeseries(
"Zone Mean Air Temperature",
"ZONE 1",
environment="annual",
)
# All environments (design days, then run periods)
ts = sql.get_timeseries(
"Zone Mean Air Temperature",
"ZONE 1",
environment="all",
)
The environment parameter accepts:
| Value | Description |
|---|---|
None |
The run periods when the variable has data there, else the design days, so the two never mix (default) |
"annual" |
Weather-file run period data only |
"sizing" |
Design day data only |
"all" |
Design days and run periods, in run order |
Any other value raises ValueError. Asking for an environment the variable has
no data in raises ResultLookupError.
Reading Several Series¶
Each get_timeseries() call scans the whole ReportData table.
get_timeseries_many()
reads many series in a single scan and returns them in the order asked. Each
item is a variable name, a (name, key) or (name, key, frequency) tuple, or a
VariableInfo from list_variables():
series = sql.get_timeseries_many([("Zone Mean Air Temperature", zone) for zone in ["ZONE 1", "ZONE 2"]])
Converting to DataFrame¶
df = ts.to_dataframe()
print(df.head())
# Zone Mean Air Temperature
# timestamp
# 2017-01-01 01:00:00 21.2
# 2017-01-01 02:00:00 21.1
# ...
Requires pandas: pip install idfkit[dataframes]
Plotting Time Series¶
Requires matplotlib or plotly: pip install idfkit[plot]
Tabular Data¶
Query Tabular Reports¶
rows = sql.get_tabular_data(report_name="AnnualBuildingUtilityPerformanceSummary")
for row in rows[:5]:
print(f"{row.table_name} | {row.row_name} | {row.column_name}: {row.value}")
Each row is a TabularRow. Its value is the cell text with the padding
stripped; an empty cell is "". row.as_float() parses it as a number. For
its full list of attributes, see the
TabularRow reference.
When filters are given and no row matches, get_tabular_data() raises
ResultLookupError, naming the filter that matches nothing. Without filters it
returns [] for a database with no tabular reports.
Read a Single Number¶
get_tabular_float() returns one cell as a float. It and get_tabular_value(),
which returns the text, raise ResultLookupError when no row or several rows
match:
area = sql.get_tabular_float(
"AnnualBuildingUtilityPerformanceSummary",
"Building Area",
"Net Conditioned Building Area",
"Area",
)
Filter by Table¶
rows = sql.get_tabular_data(
report_name="AnnualBuildingUtilityPerformanceSummary",
table_name="Site and Source Energy",
)
Common Reports¶
| Report Name | Description |
|---|---|
AnnualBuildingUtilityPerformanceSummary |
Energy use summary |
InputVerificationandResultsSummary |
Model summary |
EnvelopeSummary |
Building envelope details |
LightingSummary |
Lighting power densities |
EquipmentSummary |
Equipment capacities |
HVACSizingSummary |
HVAC sizing results |
ZoneComponentLoadSummary |
Zone load components |
Variable Metadata¶
List Available Variables¶
variables = sql.list_variables()
for var in variables[:10]:
print(f"{var.name} ({var.key_value}) [{var.units}] - {var.frequency}")
Each entry is a VariableInfo. For its full list of attributes, see the
VariableInfo reference.
Search Variables¶
# By name pattern
temp_vars = [v for v in variables if "Temperature" in v.name]
# By key
zone1_vars = [v for v in variables if v.key_value == "ZONE 1"]
Environment Metadata¶
List Environments¶
environments = sql.list_environments()
for env in environments:
print(f"{env.index}: {env.name} (type={env.environment_type})")
Environment Types¶
| Type | Value | Description |
|---|---|---|
| Design Day | 1 | SizingPeriod:DesignDay simulation |
| Design Run Period | 2 | SizingPeriod:WeatherFileDays |
| Weather File Run Period | 3 | Regular RunPeriod simulation |
Each environment is an EnvironmentInfo. For its full list of attributes, see
the EnvironmentInfo reference.
Timestamps¶
EnergyPlus uses a fixed reference year (2017) for timestamps. The SQLResult
automatically converts database timestamps to Python datetime objects.
EnergyPlus Time Convention¶
- Hour 24 in the database → midnight of the next day
- Warmup days are filtered out automatically
ts = sql.get_timeseries("Zone Mean Air Temperature", "ZONE 1")
# Timestamps are proper Python datetime objects
first = ts.timestamps[0]
print(f"Year: {first.year}") # 2017 (reference year)
print(f"Month: {first.month}")
print(f"Day: {first.day}")
print(f"Hour: {first.hour}")
Context Manager¶
SQLResult is a context manager for clean database cleanup:
with SQLResult("/path/to/eplusout.sql") as sql:
ts = sql.get_timeseries("Zone Mean Air Temperature", "ZONE 1")
# Connection automatically closed on exit
SimulationResult — the usual entry point via simulate() — is also a
context manager. Exiting the with block closes the SQLite connection that
result.sql opened lazily, which matters on Windows where the open
connection locks eplus.sql and blocks deleting the run directory. When
simulate() ran in a temporary directory (no output_dir), the exit also
deletes that directory:
with simulate(model, weather) as result:
ts = result.sql.get_timeseries("Zone Mean Air Temperature", "ZONE 1")
# On exit: SQLite connection closed, temporary run directory deleted
See Releasing File Handles for details.
Error Handling¶
def read_zone_temperature(result: SimulationResult) -> None:
try:
sql = result.sql
except OutputNotFoundError as e:
print(e) # names the Output:SQLite object to add
return
# Get time series (raises ResultLookupError, a KeyError, if not found)
try:
ts = sql.get_timeseries("Nonexistent Variable", "ZONE 1")
except ResultLookupError as e:
print(e) # the message names the closest variables and the reported keys
print(e.suggestions) # closest names, closest first
print(e.available) # keys or frequencies that could be passed instead
ResultLookupError (from idfkit.exceptions) subclasses KeyError, so code
that catches KeyError keeps working. get_timeseries() also raises it when
several keys or frequencies match: pass key_value or frequency to pick one.
Performance Tips¶
- Filter early — Use the
environmentparameter to reduce data size - Query once — Store results in variables rather than re-querying
- Read several series together —
get_timeseries_many()scans the data once, where a loop ofget_timeseries()scans it per call - Use lazy loading — Don't access
result.sqlif you don't need it
See Also¶
- How to access simulation results — Overview of result parsing
- How to plot simulation results — Visualizing query results
- How to discover output variables — Finding available variables