Skip to content

ESO / MTR API

High-performance parser for EnergyPlus .eso Standard Output and .mtr Meter time-series files. The data dictionary is parsed eagerly; variable data is extracted lazily with a single targeted scan (get_column), or all at once with eager=True / .columns.

ESOResult

idfkit.simulation.parsers.eso.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 Program Version header line.

variables tuple[ESOVariable, ...]

All variables declared in the data dictionary.

Source code in idfkit/simulation/parsers/eso.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
class 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``:

    ```python
    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:
        program_version: The ``Program Version`` header line.
        variables: All variables declared in the data dictionary.
    """

    __slots__ = (
        "_by_id",
        "_data",
        "_data_start",
        "_eager_columns",
        "_env_cache",
        "_scan_cache",
        "program_version",
        "variables",
    )

    def __init__(self, data: bytes, *, eager: bool = False) -> None:
        # Normalize line endings once so the hot loops only deal with "\n".
        if b"\r\n" in data:
            data = data.replace(b"\r\n", b"\n")
        self._data = data
        self.program_version, self._by_id, self._data_start = _parse_dictionary(data)
        self.variables: tuple[ESOVariable, ...] = tuple(self._by_id.values())
        self._env_cache: tuple[ESOEnvironment, ...] | None = None
        self._scan_cache: dict[int, tuple[ESOColumn, ...]] = {}
        self._eager_columns: tuple[ESOColumn, ...] | None = None
        if eager:
            self._eager_columns = self._scan_all()

    @classmethod
    def from_bytes(cls, data: bytes, *, eager: bool = False) -> ESOResult:
        """Parse an ESO/MTR file from raw bytes (the fastest entry point)."""
        return cls(data, eager=eager)

    @classmethod
    def from_file(cls, path: str | Path, *, eager: bool = False) -> ESOResult:
        """Parse an ESO/MTR file from disk."""
        return cls(Path(path).read_bytes(), eager=eager)

    @classmethod
    def from_string(cls, text: str, *, eager: bool = False) -> ESOResult:
        """Parse ESO/MTR content from a string."""
        return cls(text.encode("latin-1"), eager=eager)

    @property
    def environments(self) -> tuple[ESOEnvironment, ...]:
        """All environment periods in the file (lazily scanned and cached).

        This is the index → title map for ``environment_index``: each
        [ESOEnvironment][idfkit.simulation.parsers.eso.ESOEnvironment] has an
        ``index`` (use it as ``environment_index`` in ``get_column``) and a
        ``title`` (the design-day / run-period name).
        """
        if self._env_cache is None:
            self._env_cache = self._scan_environments()
        return self._env_cache

    @property
    def columns(self) -> tuple[ESOColumn, ...]:
        """Every variable's time series across all environments (full parse).

        Accessing this triggers (and caches) a full parse of the data section.
        """
        if self._eager_columns is None:
            self._eager_columns = self._scan_all()
        return self._eager_columns

    def get_variable(
        self, variable_name: str, key_value: str | None = None, frequency: str | None = None
    ) -> ESOVariable | 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][idfkit.simulation.parsers.eso.ESOResult.get_column]
        refuses such an ambiguous lookup instead.
        """
        name_lower = variable_name.lower()
        for var in self.variables:
            if (
                var.variable_name.lower() == name_lower
                and (key_value is None or var.key_value.lower() == key_value.lower())
                and (frequency is None or var.frequency.lower() == frequency.lower())
            ):
                return var
        return None

    def get_column(
        self,
        variable_name: str,
        key_value: str | None = None,
        frequency: str | None = None,
        environment_index: int | None = None,
    ) -> ESOColumn:
        """Extract one variable's time series with a single targeted scan.

        The lookup must resolve to one reported series, as
        [SQLResult.get_timeseries][idfkit.simulation.parsers.sql.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.

        Args:
            variable_name: Variable name to look up (case-insensitive).
            key_value: Key value (e.g. zone name, case-insensitive). Needed only
                when the variable is reported for more than one key.
            frequency: Frequency (e.g. ``"Hourly"``). Needed only when the
                variable is reported at more than one frequency.
            environment_index: 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 ``environments`` (e.g.
                ``next(e.index for e in eso.environments if "HTG" in e.title)``)
                and pass it here.

        Returns:
            The matching [ESOColumn][idfkit.simulation.parsers.eso.ESOColumn]. Its
            ``environment_index`` cross-references back to ``environments``.

        Raises:
            ResultLookupError: A ``KeyError`` subclass, if the variable, key or
                frequency is not in the file (with the closest names and the
                reported keys), if several keys or frequencies match, or if the
                variable has no data (in *environment_index*, when given).
        """
        var = self._resolve(variable_name, key_value, frequency)
        return self._pick_environment(var, key_value, self._scan_variable(var.report_id), environment_index)

    def get_columns(
        self,
        series: Iterable[ESOSeriesSpec],
        environment_index: int | None = None,
    ) -> list[ESOColumn]:
        """Extract several variables' time series in one scan of the file.

        Each [get_column][idfkit.simulation.parsers.eso.ESOResult.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).

        Args:
            series: The series to read, each an ``ESOVariable`` (as
                ``variables`` lists them), a variable name, or a
                ``(name, key)`` or ``(name, key, frequency)`` tuple, resolved
                as ``get_column`` resolves its arguments.
            environment_index: Which environment to return for every series,
                as in ``get_column``; defaults to the last one in the file.

        Returns:
            One [ESOColumn][idfkit.simulation.parsers.eso.ESOColumn] per item
            of *series*, in the same order.

        Raises:
            ResultLookupError: If any series does not resolve to exactly one
                reported series or has no data, as in ``get_column``.
        """
        resolved: list[tuple[ESOVariable, str | None]] = []
        for spec in series:
            if isinstance(spec, ESOVariable):
                resolved.append((self._resolve(spec.variable_name, spec.key_value, spec.frequency), spec.key_value))
            elif isinstance(spec, str):
                resolved.append((self._resolve(spec, None, None), None))
            else:
                key = spec[1]
                resolved.append((self._resolve(spec[0], key, spec[2] if len(spec) == 3 else None), key))
        scanned = self._scan_variables([var.report_id for var, _ in resolved])
        return [self._pick_environment(var, key, scanned[var.report_id], environment_index) for var, key in resolved]

    def _resolve(self, variable_name: str, key_value: str | None, frequency: str | None) -> ESOVariable:
        """The one declared variable *variable_name*, *key_value* and *frequency* name."""
        return resolve_series(
            self.variables,
            variable_name,
            key_value,
            frequency,
            name_of=lambda v: v.variable_name,
            key_of=lambda v: v.key_value,
            frequency_of=lambda v: v.frequency,
            not_found_hint=" Request it with an Output:Variable (or Output:Meter) object.",
        )

    @staticmethod
    def _pick_environment(
        var: ESOVariable, key_value: str | None, cols: tuple[ESOColumn, ...], environment_index: int | None
    ) -> ESOColumn:
        """The column of *cols* in *environment_index* (the last one when ``None``)."""
        if not cols:
            msg = f"Variable '{var.variable_name}'{for_key(key_value)} has no data in this file."
            raise ResultLookupError(msg)
        if environment_index is None:
            return cols[-1]
        for col in cols:
            if col.environment_index == environment_index:
                return col
        indexes = [str(col.environment_index) for col in cols]
        msg = (
            f"Variable '{var.variable_name}'{for_key(key_value)} has no data in environment {environment_index}."
            f" It has data in environment {listing(indexes)}; eso.environments maps each index to its title."
        )
        raise ResultLookupError(msg, available=indexes)

    def to_dataframe(
        self,
        variable_name: str,
        key_value: str | None = None,
        frequency: str | None = None,
        environment_index: int | None = None,
    ) -> pd.DataFrame:
        """Extract a variable and return it as a pandas DataFrame.

        Raises:
            ResultLookupError: A ``KeyError`` subclass, as
                [get_column][idfkit.simulation.parsers.eso.ESOResult.get_column] raises it.
            ImportError: If pandas is not installed.
        """
        return self.get_column(variable_name, key_value, frequency, environment_index).to_dataframe()

    # -- internal scans ----------------------------------------------------

    def _scan_variable(self, report_id: int) -> tuple[ESOColumn, ...]:  # noqa: C901
        """Single targeted scan that float-parses only ``report_id``'s records."""
        cached = self._scan_cache.get(report_id)
        if cached is not None:
            return cached

        var = self._by_id[report_id]
        marker = _FREQ_TO_MARKER.get(var.frequency, _TIMESTEP_MARKER)
        data = self._data
        find = data.find
        startswith = data.startswith
        n = len(data)

        target_prefix = f"{report_id},".encode("latin-1")
        target_comma = len(target_prefix) - 1  # offset of the id's trailing comma
        env_prefix = b"1,"
        marker_prefix = f"{marker},".encode("latin-1")

        columns: list[ESOColumn] = []
        environments: list[ESOEnvironment] = []
        env_index = -1
        current_ts: datetime | None = None
        timestamps: list[datetime] = []
        values = array("d")

        # A single guard around the whole loop (not per line, so zero hot-loop
        # overhead) makes a truncated/garbled tail degrade gracefully: we stop
        # and keep whatever was parsed cleanly.
        start = self._data_start
        try:
            while start < n:
                end = find(b"\n", start)
                if end == -1:
                    end = n
                if startswith(target_prefix, start):
                    comma = start + target_comma
                    value_end = find(b",", comma + 1, end)
                    if value_end == -1:
                        value_end = end
                    values.append(float(data[comma + 1 : value_end]))
                    # current_ts is set by this variable's frequency marker; fall back
                    # to a stable sentinel if a value precedes any marker.
                    timestamps.append(current_ts if current_ts is not None else datetime(REFERENCE_YEAR, 1, 1))
                elif startswith(env_prefix, start):
                    # Parsed before the flush, so a garbled marker cannot store the open column twice.
                    environment = _parse_environment(env_index + 1, data[start:end].split(b","))
                    if values:
                        columns.append(ESOColumn(var, env_index, tuple(timestamps[: len(values)]), tuple(values)))
                    env_index += 1
                    environments.append(environment)
                    timestamps = []
                    values = array("d")
                    current_ts = None
                elif startswith(marker_prefix, start):
                    current_ts = _marker_timestamp(marker, data[start:end].split(b","))
                start = end + 1
        except (ValueError, IndexError):
            pass

        if values:
            columns.append(ESOColumn(var, env_index, tuple(timestamps[: len(values)]), tuple(values)))

        if self._env_cache is None and environments:
            self._env_cache = tuple(environments)
        result = tuple(columns)
        self._scan_cache[report_id] = result
        return result

    def _scan_variables(self, report_ids: Sequence[int]) -> dict[int, tuple[ESOColumn, ...]]:  # noqa: C901
        """Single scan that float-parses the records of every id in *report_ids* not yet cached."""
        pending = [rid for rid in dict.fromkeys(report_ids) if rid not in self._scan_cache]
        if len(pending) == 1:
            self._scan_variable(pending[0])  # the prefix-test scan is faster for one id
        elif pending:
            by_id = self._by_id
            marker_of = {rid: _FREQ_TO_MARKER.get(by_id[rid].frequency, _TIMESTEP_MARKER) for rid in pending}
            # Leading id bytes -> id, for the wanted variables and the markers their timestamps come from.
            wanted = {str(rid).encode("latin-1"): rid for rid in pending}
            markers = {str(m).encode("latin-1"): m for m in {_ENV_MARKER, *marker_of.values()}}
            data = self._data
            find = data.find
            n = len(data)
            sentinel = datetime(REFERENCE_YEAR, 1, 1)

            columns: dict[int, list[ESOColumn]] = {rid: [] for rid in pending}
            environments: list[ESOEnvironment] = []
            env_index = -1
            current_ts: dict[int, datetime] = {}
            timestamps: dict[int, list[datetime]] = {rid: [] for rid in pending}
            values: dict[int, array[float]] = {rid: array("d") for rid in pending}

            def _flush() -> None:
                for rid in pending:
                    if values[rid]:
                        columns[rid].append(
                            ESOColumn(by_id[rid], env_index, tuple(timestamps[rid]), tuple(values[rid]))
                        )

            # Each id stops at its first record that will not parse, as _scan_variable stops for it alone, so a
            # garbled value of one series never truncates another. A garbled timestamp marker stops the ids
            # that read it; a garbled environment marker stops them all.
            start = self._data_start
            while start < n:
                end = find(b"\n", start)
                if end == -1:
                    end = n
                comma = find(b",", start, end)
                if comma != -1:
                    head = data[start:comma]
                    rid = wanted.get(head)
                    if rid is not None:
                        value_end = find(b",", comma + 1, end)
                        if value_end == -1:
                            value_end = end
                        try:
                            value = float(data[comma + 1 : value_end])
                        except ValueError:
                            del wanted[head]
                        else:
                            values[rid].append(value)
                            timestamps[rid].append(current_ts.get(marker_of[rid], sentinel))
                    else:
                        marker = markers.get(head)
                        if marker == _ENV_MARKER:
                            try:
                                environment = _parse_environment(env_index + 1, data[start:end].split(b","))
                            except (ValueError, IndexError):
                                break  # the closing _flush() keeps what was read
                            _flush()
                            env_index += 1
                            environments.append(environment)
                            timestamps = {r: [] for r in pending}
                            values = {r: array("d") for r in pending}
                            current_ts = {}
                        elif marker is not None:
                            try:
                                current_ts[marker] = _marker_timestamp(marker, data[start:end].split(b","))
                            except (ValueError, IndexError):
                                for key, r in list(wanted.items()):
                                    if marker_of[r] == marker:
                                        del wanted[key]
                if not wanted:
                    break
                start = end + 1
            _flush()

            if self._env_cache is None and environments:
                self._env_cache = tuple(environments)
            for rid in pending:
                self._scan_cache[rid] = tuple(columns[rid])
        return {rid: self._scan_cache[rid] for rid in report_ids}

    def _scan_environments(self) -> tuple[ESOEnvironment, ...]:
        """Cheap scan that enumerates only the ``1,...`` environment markers."""
        data = self._data
        find = data.find
        startswith = data.startswith
        n = len(data)
        environments: list[ESOEnvironment] = []
        index = -1
        start = self._data_start
        while start < n:
            end = find(b"\n", start)
            if end == -1:
                end = n
            if startswith(b"1,", start):
                index += 1
                environments.append(_parse_environment(index, data[start:end].split(b",")))
            start = end + 1
        return tuple(environments)

    def _scan_all(self) -> tuple[ESOColumn, ...]:  # noqa: C901
        """Full single pass that materializes every variable's columns."""
        data = self._data
        find = data.find
        n = len(data)
        by_id = self._by_id
        var_marker = {rid: _FREQ_TO_MARKER.get(v.frequency, _TIMESTEP_MARKER) for rid, v in by_id.items()}

        columns: list[ESOColumn] = []
        environments: list[ESOEnvironment] = []
        env_index = -1
        ts_by_marker: dict[int, list[datetime]] = {}
        values_by_id: dict[int, array[float]] = {}

        def _flush() -> None:
            for rid, arr in values_by_id.items():
                if not arr:
                    continue
                ts = ts_by_marker.get(var_marker[rid], [])
                # Trim timestamps to the value count so a truncated final
                # record cannot misalign the column.
                columns.append(ESOColumn(by_id[rid], env_index, tuple(ts[: len(arr)]), tuple(arr)))

        # One guard around the whole loop keeps a truncated tail from raising.
        start = self._data_start
        try:
            while start < n:
                end = find(b"\n", start)
                if end == -1:
                    end = n
                comma = find(b",", start, end)
                if comma == -1:
                    if data[start:end].lstrip().startswith(_END_OF_DATA):
                        break
                    start = end + 1
                    continue
                try:
                    report_id = int(data[start:comma])
                except ValueError:
                    start = end + 1
                    continue
                if report_id == _ENV_MARKER:
                    _flush()
                    env_index += 1
                    environments.append(_parse_environment(env_index, data[start:end].split(b",")))
                    ts_by_marker = {}
                    values_by_id = {rid: array("d") for rid in by_id}
                elif report_id in _MARKER_IDS:
                    lst = ts_by_marker.get(report_id)
                    if lst is None:
                        lst = []
                        ts_by_marker[report_id] = lst
                    lst.append(_marker_timestamp(report_id, data[start:end].split(b",")))
                else:
                    arr = values_by_id.get(report_id)
                    if arr is None:
                        start = end + 1
                        continue
                    value_end = find(b",", comma + 1, end)
                    if value_end == -1:
                        value_end = end
                    arr.append(float(data[comma + 1 : value_end]))
                start = end + 1
        except (ValueError, IndexError):
            pass
        _flush()

        if self._env_cache is None:
            self._env_cache = tuple(environments)
        return tuple(columns)

columns property

Every variable's time series across all environments (full parse).

Accessing this triggers (and caches) a full parse of the data section.

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).

variables = tuple(self._by_id.values()) instance-attribute

from_bytes(data, *, eager=False) classmethod

Parse an ESO/MTR file from raw bytes (the fastest entry point).

Source code in idfkit/simulation/parsers/eso.py
@classmethod
def from_bytes(cls, data: bytes, *, eager: bool = False) -> ESOResult:
    """Parse an ESO/MTR file from raw bytes (the fastest entry point)."""
    return cls(data, eager=eager)

from_file(path, *, eager=False) classmethod

Parse an ESO/MTR file from disk.

Source code in idfkit/simulation/parsers/eso.py
@classmethod
def from_file(cls, path: str | Path, *, eager: bool = False) -> ESOResult:
    """Parse an ESO/MTR file from disk."""
    return cls(Path(path).read_bytes(), eager=eager)

from_string(text, *, eager=False) classmethod

Parse ESO/MTR content from a string.

Source code in idfkit/simulation/parsers/eso.py
@classmethod
def from_string(cls, text: str, *, eager: bool = False) -> ESOResult:
    """Parse ESO/MTR content from a string."""
    return cls(text.encode("latin-1"), eager=eager)

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. "Hourly"). Needed only when the variable is reported at more than one frequency.

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 environments (e.g. next(e.index for e in eso.environments if "HTG" in e.title)) and pass it here.

None

Returns:

Type Description
ESOColumn

The matching ESOColumn. Its

ESOColumn

environment_index cross-references back to environments.

Raises:

Type Description
ResultLookupError

A KeyError subclass, if the variable, key or frequency is not in the file (with the closest names and the reported keys), if several keys or frequencies match, or if the variable has no data (in environment_index, when given).

Source code in idfkit/simulation/parsers/eso.py
def get_column(
    self,
    variable_name: str,
    key_value: str | None = None,
    frequency: str | None = None,
    environment_index: int | None = None,
) -> ESOColumn:
    """Extract one variable's time series with a single targeted scan.

    The lookup must resolve to one reported series, as
    [SQLResult.get_timeseries][idfkit.simulation.parsers.sql.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.

    Args:
        variable_name: Variable name to look up (case-insensitive).
        key_value: Key value (e.g. zone name, case-insensitive). Needed only
            when the variable is reported for more than one key.
        frequency: Frequency (e.g. ``"Hourly"``). Needed only when the
            variable is reported at more than one frequency.
        environment_index: 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 ``environments`` (e.g.
            ``next(e.index for e in eso.environments if "HTG" in e.title)``)
            and pass it here.

    Returns:
        The matching [ESOColumn][idfkit.simulation.parsers.eso.ESOColumn]. Its
        ``environment_index`` cross-references back to ``environments``.

    Raises:
        ResultLookupError: A ``KeyError`` subclass, if the variable, key or
            frequency is not in the file (with the closest names and the
            reported keys), if several keys or frequencies match, or if the
            variable has no data (in *environment_index*, when given).
    """
    var = self._resolve(variable_name, key_value, frequency)
    return self._pick_environment(var, key_value, self._scan_variable(var.report_id), environment_index)

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 ESOVariable (as variables lists them), a variable name, or a (name, key) or (name, key, frequency) tuple, resolved as get_column resolves its arguments.

required
environment_index int | None

Which environment to return for every series, as in get_column; defaults to the last one in the file.

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 get_column.

Source code in idfkit/simulation/parsers/eso.py
def get_columns(
    self,
    series: Iterable[ESOSeriesSpec],
    environment_index: int | None = None,
) -> list[ESOColumn]:
    """Extract several variables' time series in one scan of the file.

    Each [get_column][idfkit.simulation.parsers.eso.ESOResult.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).

    Args:
        series: The series to read, each an ``ESOVariable`` (as
            ``variables`` lists them), a variable name, or a
            ``(name, key)`` or ``(name, key, frequency)`` tuple, resolved
            as ``get_column`` resolves its arguments.
        environment_index: Which environment to return for every series,
            as in ``get_column``; defaults to the last one in the file.

    Returns:
        One [ESOColumn][idfkit.simulation.parsers.eso.ESOColumn] per item
        of *series*, in the same order.

    Raises:
        ResultLookupError: If any series does not resolve to exactly one
            reported series or has no data, as in ``get_column``.
    """
    resolved: list[tuple[ESOVariable, str | None]] = []
    for spec in series:
        if isinstance(spec, ESOVariable):
            resolved.append((self._resolve(spec.variable_name, spec.key_value, spec.frequency), spec.key_value))
        elif isinstance(spec, str):
            resolved.append((self._resolve(spec, None, None), None))
        else:
            key = spec[1]
            resolved.append((self._resolve(spec[0], key, spec[2] if len(spec) == 3 else None), key))
    scanned = self._scan_variables([var.report_id for var, _ in resolved])
    return [self._pick_environment(var, key, scanned[var.report_id], environment_index) for var, key in resolved]

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.

Source code in idfkit/simulation/parsers/eso.py
def get_variable(
    self, variable_name: str, key_value: str | None = None, frequency: str | None = None
) -> ESOVariable | 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][idfkit.simulation.parsers.eso.ESOResult.get_column]
    refuses such an ambiguous lookup instead.
    """
    name_lower = variable_name.lower()
    for var in self.variables:
        if (
            var.variable_name.lower() == name_lower
            and (key_value is None or var.key_value.lower() == key_value.lower())
            and (frequency is None or var.frequency.lower() == frequency.lower())
        ):
            return var
    return None

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 KeyError subclass, as get_column raises it.

ImportError

If pandas is not installed.

Source code in idfkit/simulation/parsers/eso.py
def to_dataframe(
    self,
    variable_name: str,
    key_value: str | None = None,
    frequency: str | None = None,
    environment_index: int | None = None,
) -> pd.DataFrame:
    """Extract a variable and return it as a pandas DataFrame.

    Raises:
        ResultLookupError: A ``KeyError`` subclass, as
            [get_column][idfkit.simulation.parsers.eso.ESOResult.get_column] raises it.
        ImportError: If pandas is not installed.
    """
    return self.get_column(variable_name, key_value, frequency, environment_index).to_dataframe()

ESOColumn

idfkit.simulation.parsers.eso.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 ESOResult.environments to get the design-day / run-period title: result.environments[col.environment_index].title.

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).

Source code in idfkit/simulation/parsers/eso.py
@dataclass(frozen=True, slots=True, repr=False)
class ESOColumn:
    """One variable's time series within a single environment.

    Attributes:
        variable: The [ESOVariable][idfkit.simulation.parsers.eso.ESOVariable] this column belongs to.
        environment_index: Index of the environment these values belong to.
            Look it up in ``ESOResult.environments`` to get the design-day /
            run-period title: ``result.environments[col.environment_index].title``.
        timestamps: Timestamp for each data point.
        values: The reported value for each data point (the primary value for
            aggregated daily/monthly records).
    """

    variable: ESOVariable
    environment_index: int
    timestamps: tuple[datetime, ...]
    values: tuple[float, ...]

    def __repr__(self) -> str:
        # A summary, not the data: one hourly annual series would otherwise print about 500 KB.
        var = self.variable
        return (
            f"ESOColumn({var.variable_name!r}, {var.key_value!r}, units={var.units!r}, "
            f"frequency={var.frequency!r}, environment_index={self.environment_index}, "
            f"{summarize_series(self.timestamps, self.values)})"
        )

    def to_dataframe(self) -> pd.DataFrame:
        """Convert to a pandas DataFrame.

        Returns:
            A DataFrame with a ``timestamp`` index and a column named after the
            variable.

        Raises:
            ImportError: If pandas is not installed.
        """
        try:
            import pandas as _pd  # type: ignore[import-not-found]
        except ImportError:
            msg = "pandas is required for DataFrame conversion. Install it with: pip install idfkit[dataframes]"
            raise ImportError(msg) from None
        return _pd.DataFrame(  # type: ignore[no-any-return]
            {"timestamp": list(self.timestamps), self.variable.variable_name: list(self.values)}
        ).set_index("timestamp")

    def plot(self, *, backend: PlotBackend | None = None, title: str | None = None) -> Any:
        """Plot this time series as a line chart.

        Args:
            backend: A PlotBackend instance. If not provided, auto-detects.
            title: Optional plot title. Defaults to ``"key_value: variable_name"``.

        Returns:
            A figure object from the backend.

        Raises:
            ImportError: If no plotting backend is available.
        """
        if backend is None:
            from ..plotting import get_default_backend

            backend = get_default_backend()
        var = self.variable
        plot_title = title or (f"{var.key_value}: {var.variable_name}" if var.key_value else var.variable_name)
        return backend.line(
            list(self.timestamps),
            list(self.values),
            title=plot_title,
            xlabel="Time",
            ylabel=f"{var.variable_name} ({var.units})" if var.units else var.variable_name,
            label=var.key_value or var.variable_name,
        )

environment_index instance-attribute

timestamps instance-attribute

values instance-attribute

variable instance-attribute

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 "key_value: variable_name".

None

Returns:

Type Description
Any

A figure object from the backend.

Raises:

Type Description
ImportError

If no plotting backend is available.

Source code in idfkit/simulation/parsers/eso.py
def plot(self, *, backend: PlotBackend | None = None, title: str | None = None) -> Any:
    """Plot this time series as a line chart.

    Args:
        backend: A PlotBackend instance. If not provided, auto-detects.
        title: Optional plot title. Defaults to ``"key_value: variable_name"``.

    Returns:
        A figure object from the backend.

    Raises:
        ImportError: If no plotting backend is available.
    """
    if backend is None:
        from ..plotting import get_default_backend

        backend = get_default_backend()
    var = self.variable
    plot_title = title or (f"{var.key_value}: {var.variable_name}" if var.key_value else var.variable_name)
    return backend.line(
        list(self.timestamps),
        list(self.values),
        title=plot_title,
        xlabel="Time",
        ylabel=f"{var.variable_name} ({var.units})" if var.units else var.variable_name,
        label=var.key_value or var.variable_name,
    )

to_dataframe()

Convert to a pandas DataFrame.

Returns:

Type Description
DataFrame

A DataFrame with a timestamp index and a column named after the

DataFrame

variable.

Raises:

Type Description
ImportError

If pandas is not installed.

Source code in idfkit/simulation/parsers/eso.py
def to_dataframe(self) -> pd.DataFrame:
    """Convert to a pandas DataFrame.

    Returns:
        A DataFrame with a ``timestamp`` index and a column named after the
        variable.

    Raises:
        ImportError: If pandas is not installed.
    """
    try:
        import pandas as _pd  # type: ignore[import-not-found]
    except ImportError:
        msg = "pandas is required for DataFrame conversion. Install it with: pip install idfkit[dataframes]"
        raise ImportError(msg) from None
    return _pd.DataFrame(  # type: ignore[no-any-return]
        {"timestamp": list(self.timestamps), self.variable.variable_name: list(self.values)}
    ).set_index("timestamp")

ESOVariable

idfkit.simulation.parsers.eso.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 ("Hourly", "Daily" …).

num_values int

Number of numeric values each data record carries (1 for detailed/hourly; more for aggregated daily/monthly min/max records).

Source code in idfkit/simulation/parsers/eso.py
@dataclass(frozen=True, slots=True)
class ESOVariable:
    """A reporting variable declared in an ESO/MTR data dictionary.

    Attributes:
        report_id: The integer id that prefixes this variable's data records.
        variable_name: The output variable or meter name.
        key_value: The key (e.g. zone or surface name); empty for meters.
        units: The variable units (may be empty).
        frequency: Normalized reporting frequency (``"Hourly"``, ``"Daily"`` …).
        num_values: Number of numeric values each data record carries (1 for
            detailed/hourly; more for aggregated daily/monthly min/max records).
    """

    report_id: int
    variable_name: str
    key_value: str
    units: str
    frequency: str
    num_values: int

frequency instance-attribute

key_value instance-attribute

num_values instance-attribute

report_id instance-attribute

units instance-attribute

variable_name instance-attribute

ESOEnvironment

idfkit.simulation.parsers.eso.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 environment_index.

title str

The environment title from the 1,... marker line, e.g. "DENVER ... ANN HTG 99% CONDNS DB" or "RUN PERIOD 1".

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.

Source code in idfkit/simulation/parsers/eso.py
@dataclass(frozen=True, slots=True)
class ESOEnvironment:
    """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:
        index: 0-based order of appearance; pass it as ``environment_index``.
        title: The environment title from the ``1,...`` marker line, e.g.
            ``"DENVER ... ANN HTG 99% CONDNS DB"`` or ``"RUN PERIOD 1"``.
        latitude: Site latitude in degrees.
        longitude: Site longitude in degrees.
        time_zone: Site time zone in hours from GMT.
        elevation: Site elevation in metres.
    """

    index: int
    title: str
    latitude: float
    longitude: float
    time_zone: float
    elevation: float

elevation instance-attribute

index instance-attribute

latitude instance-attribute

longitude instance-attribute

time_zone instance-attribute

title instance-attribute