Skip to content

I/O -- Parsers & Writers

Functions and classes for reading and writing EnergyPlus models in IDF (text) and epJSON (JSON) formats.

Convenience Loaders

Top-level convenience functions:

  • load_idf(path, version=None, *, as_type=None, since=None, before=None, strict_parsing=True, strict=True, preserve_formatting=False, normalize_choices=True, encoding=None) for IDF files.
  • load_epjson(path, version=None, *, as_type=None, since=None, before=None, strict_parsing=True, strict=True, preserve_formatting=False, normalize_choices=True) for epJSON files.

Both parse strictly by default: a malformed object or an unknown object type raises IDFParseError, and strict_parsing=False skips it instead. Both return an AnyIDFDocument unless as_type=, since= or before= names the model's release; see Typed for a Release.

strict governs field access on the loaded objects: an unknown field name raises InvalidFieldError, or returns None with strict=False, and an assigned value the schema refuses raises ValidationFailedError.

encoding=None reads an IDF file as UTF-8 when its bytes are valid UTF-8, and as latin-1 otherwise. save_idf() writes the document back in the same encoding.

load_idf_with_diagnostics() reads tolerantly and returns the document together with the recoverable findings it skipped; it takes the arguments of load_idf() except strict_parsing.

Load an IDF file and return its document.

A model's EnergyPlus release is read from its file, so a type checker cannot know it: the document is typed as AnyIDFDocument, which offers what every supported release has. Name the release with as_type=, or a range of releases with since= and before=, to type it for that release; the release is checked once the file is read, as idfkit.versioned.as_version checks it.

Parameters:

Name Type Description Default
path Path | str

Path to the IDF file

required
version tuple[int, int, int] | None

Optional version override (major, minor, patch): the release whose schema the file is read with. A Version object in the file still sets doc.version, and that is what as_type=, since= and before= are checked against.

None
as_type DocumentTypeTarget | None

The document type of the release the file must be, such as IDFDocumentV9_4 from idfkit.versioned, or a tuple of them. The document is returned typed as it, or as the union of the tuple's types. A type argument states the strictness: IDFDocumentV9_4[Literal[False]] loads a non-strict document, as strict=False does.

None
since ReleaseBound | None

The first release of a range the file must be in: its document type, "major.minor" or a version tuple. The document is typed as the union of the range's releases.

None
before ReleaseBound | None

The release that range stops before, the same way.

None
strict_parsing bool

If True, fail fast on malformed IDF objects (default: True)

True
strict bool

When True, accessing or setting an unknown field name on any IDFObject raises InvalidFieldError instead of returning None, and assigning a value the schema refuses raises ValidationFailedError, as add() does.

True
preserve_formatting bool

When True, build a Concrete Syntax Tree (CST) so that write_idf and save_idf reproduce the original formatting, comments, and whitespace for unmodified objects. Choice normalization does not affect this: an unmodified object is written as read. Without it, save() over this file drops its ! comments and re-sorts its objects, and warns with FormattingLossWarning when the file has comments.

False
normalize_choices bool

When True (the default), each choice value is stored in the spelling its schema declares, whatever case the file used: a surface the file calls WALL has surface_type == "Wall", as its Literal type says, so an exhaustive match holds on models you did not write. EnergyPlus reads choices case-insensitively, so no simulation changes. False keeps the file's text, and a choice field's Literal type then does not hold; see IDFDocument.normalize_choices.

True
encoding str | None

The file's text encoding. None (the default) reads it as UTF-8 when its bytes are valid UTF-8 and as latin-1 otherwise, dropping a UTF-8 byte-order mark. save_idf writes the document back in the same encoding.

None

Returns:

Type Description
AnyIDFDocument

The parsed document: an AnyIDFDocument, or typed as as_type= or the

AnyIDFDocument

since=/before= range when one is given.

Raises:

Type Description
TypeError

If the file's release is not the one as_type= names or is outside the since=/before= range; or, before the file is read, if both as_type= and a range are given, as_type= is not a document type, or its type argument states a strict document while strict=False.

ValueError

Before the file is read, if since= or before= names no supported release, or the range holds none.

Examples:

Load a DOE reference building and list its zones:

```python
model = load_idf("RefBldgSmallOfficeNew2004.idf")
print(f"Loaded {len(model)} objects")
for zone in model["Zone"]:
    print(zone.name)
```

State the release, so the model is checked against that release's object types:

```python
from idfkit.versioned import IDFDocumentV9_4

legacy = load_idf("legacy.idf", as_type=IDFDocumentV9_4)
recent = load_idf("model.idf", since="9.6")  # 9.6, 22.1, ... and the latest
recent["Space"].first()  # Space exists in every one of those releases
```

Override the version for a legacy model:

```python
model = load_idf("pre_v9_building.idf", version=(9, 6, 0))
```

Lossless round-trip:

```python
model = load_idf("building.idf", preserve_formatting=True)
save_idf(model, "building_copy.idf")  # byte-identical
```
Source code in idfkit/_loaders.py
def load_idf(
    path: Path | str,
    version: tuple[int, int, int] | None = None,
    *,
    as_type: DocumentTypeTarget | None = None,
    since: ReleaseBound | None = None,
    before: ReleaseBound | None = None,
    strict_parsing: bool = True,
    strict: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
    encoding: str | None = None,
) -> AnyIDFDocument:
    """
    Load an IDF file and return its document.

    A model's EnergyPlus release is read from its file, so a type checker cannot know it: the
    document is typed as ``AnyIDFDocument``, which offers what every supported release has. Name
    the release with ``as_type=``, or a range of releases with ``since=`` and ``before=``, to type
    it for that release; the release is checked once the file is read, as
    [idfkit.versioned.as_version][idfkit.versioned.as_version] checks it.

    Args:
        path: Path to the IDF file
        version: Optional version override (major, minor, patch): the release whose schema the
            file is read with. A ``Version`` object in the file still sets ``doc.version``, and
            that is what ``as_type=``, ``since=`` and ``before=`` are checked against.
        as_type: The document type of the release the file must be, such as ``IDFDocumentV9_4``
            from [idfkit.versioned][idfkit.versioned], or a tuple of them. The document is returned typed as
            it, or as the union of the tuple's types. A type argument states the strictness:
            ``IDFDocumentV9_4[Literal[False]]`` loads a non-strict document, as ``strict=False`` does.
        since: The first release of a range the file must be in: its document type,
            ``"major.minor"`` or a version tuple. The document is typed as the union of the
            range's releases.
        before: The release that range stops before, the same way.
        strict_parsing: If True, fail fast on malformed IDF objects (default: True)
        strict: When ``True``, accessing or setting an unknown field name on any
            IDFObject raises [InvalidFieldError][idfkit.exceptions.InvalidFieldError] instead
            of returning ``None``, and assigning a value the schema refuses raises
            [ValidationFailedError][idfkit.exceptions.ValidationFailedError], as ``add()`` does.
        preserve_formatting: When ``True``, build a Concrete Syntax Tree
            (CST) so that [write_idf][idfkit.writers.write_idf] and [save_idf][idfkit.writers.save_idf]
            reproduce the original
            formatting, comments, and whitespace for unmodified objects. Choice
            normalization does not affect this: an unmodified object is written as read.
            Without it, ``save()`` over this file drops its ``!`` comments and re-sorts its
            objects, and warns with [FormattingLossWarning][idfkit.exceptions.FormattingLossWarning]
            when the file has comments.
        normalize_choices: When ``True`` (the default), each choice value is stored in the
            spelling its schema declares, whatever case the file used: a surface the file
            calls ``WALL`` has ``surface_type == "Wall"``, as its ``Literal`` type says, so an
            exhaustive ``match`` holds on models you did not write. EnergyPlus reads choices
            case-insensitively, so no simulation changes. ``False`` keeps the file's text, and
            a choice field's ``Literal`` type then does not hold; see
            [IDFDocument.normalize_choices][idfkit.document.IDFDocument.normalize_choices].
        encoding: The file's text encoding. ``None`` (the default) reads it as UTF-8 when its
            bytes are valid UTF-8 and as latin-1 otherwise, dropping a UTF-8 byte-order mark.
            [save_idf][idfkit.writers.save_idf] writes the document back in the same encoding.

    Returns:
        The parsed document: an ``AnyIDFDocument``, or typed as ``as_type=`` or the
        ``since=``/``before=`` range when one is given.

    Raises:
        TypeError: If the file's release is not the one ``as_type=`` names or is outside the
            ``since=``/``before=`` range; or, before the file is read, if both ``as_type=`` and a
            range are given, ``as_type=`` is not a document type, or its type argument states a
            strict document while ``strict=False``.
        ValueError: Before the file is read, if ``since=`` or ``before=`` names no supported
            release, or the range holds none.

    Examples:
        Load a DOE reference building and list its zones:

            ```python
            model = load_idf("RefBldgSmallOfficeNew2004.idf")
            print(f"Loaded {len(model)} objects")
            for zone in model["Zone"]:
                print(zone.name)
            ```

        State the release, so the model is checked against that release's object types:

            ```python
            from idfkit.versioned import IDFDocumentV9_4

            legacy = load_idf("legacy.idf", as_type=IDFDocumentV9_4)
            recent = load_idf("model.idf", since="9.6")  # 9.6, 22.1, ... and the latest
            recent["Space"].first()  # Space exists in every one of those releases
            ```

        Override the version for a legacy model:

            ```python
            model = load_idf("pre_v9_building.idf", version=(9, 6, 0))
            ```

        Lossless round-trip:

            ```python
            model = load_idf("building.idf", preserve_formatting=True)
            save_idf(model, "building_copy.idf")  # byte-identical
            ```
    """
    strict = _prepare(as_type, since, before, strict, version)
    doc = parse_idf(
        Path(path),
        version=version,
        encoding=encoding,
        strict_parsing=strict_parsing,
        strict=strict,
        preserve_formatting=preserve_formatting,
        normalize_choices=normalize_choices,
    )
    return _narrow(doc, path, as_type, since, before)

Load an epJSON file and return its document.

The document is typed as AnyIDFDocument unless as_type=, since= or before= names its release, as for load_idf.

Parameters:

Name Type Description Default
path Path | str

Path to the epJSON file

required
version tuple[int, int, int] | None

Optional version override (major, minor, patch)

None
as_type DocumentTypeTarget | None

The document type of the release the file must be, or a tuple of them, as for load_idf.

None
since ReleaseBound | None

The first release of a range the file must be in, as for load_idf.

None
before ReleaseBound | None

The release that range stops before, as for load_idf.

None
strict_parsing bool

When True (the default), an object type the schema does not have raises IDFParseError, as load_idf does, and the message suggests the closest type; EnergyPlus refuses such a file. False skips it with a logged warning.

True
strict bool

When True, accessing or setting an unknown field name on any IDFObject raises InvalidFieldError instead of returning None, and assigning a value the schema refuses raises ValidationFailedError, as add() does.

True
preserve_formatting bool

When True, store the raw JSON text so that write_epjson and save_epjson can reproduce it byte-for-byte when no objects have been modified.

False
normalize_choices bool

When True (the default), each choice value is stored in the spelling its schema declares, whatever case the file used: a surface the file calls WALL has surface_type == "Wall", as its Literal type says, so an exhaustive match holds on models you did not write. EnergyPlus reads choices case-insensitively, so no simulation changes. False keeps the file's text, and a choice field's Literal type then does not hold; see IDFDocument.normalize_choices.

True

Returns:

Type Description
AnyIDFDocument

The parsed document: an AnyIDFDocument, or typed as as_type= or the

AnyIDFDocument

since=/before= range when one is given.

Raises:

Type Description
IDFParseError

For an object type the schema does not have, with strict_parsing.

TypeError

As load_idf raises it.

ValueError

As load_idf raises it.

Examples:

Load an epJSON model and iterate over zones:

```python
model = load_epjson("SmallOffice.epJSON")
for zone in model["Zone"]:
    print(zone.name, zone.x_origin)
```

Load it typed for the release it must be:

```python
from idfkit.versioned import IDFDocumentV24_1

model = load_epjson("SmallOffice.epJSON", as_type=IDFDocumentV24_1)
```

Specify an explicit EnergyPlus version:

```python
model = load_epjson("SmallOffice.epJSON", version=(24, 1, 0))
```
Source code in idfkit/_loaders.py
def load_epjson(
    path: Path | str,
    version: tuple[int, int, int] | None = None,
    *,
    as_type: DocumentTypeTarget | None = None,
    since: ReleaseBound | None = None,
    before: ReleaseBound | None = None,
    strict_parsing: bool = True,
    strict: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> AnyIDFDocument:
    """
    Load an epJSON file and return its document.

    The document is typed as ``AnyIDFDocument`` unless ``as_type=``, ``since=`` or ``before=``
    names its release, as for [load_idf][idfkit.load_idf].

    Args:
        path: Path to the epJSON file
        version: Optional version override (major, minor, patch)
        as_type: The document type of the release the file must be, or a tuple of them, as for
            [load_idf][idfkit.load_idf].
        since: The first release of a range the file must be in, as for [load_idf][idfkit.load_idf].
        before: The release that range stops before, as for [load_idf][idfkit.load_idf].
        strict_parsing: When ``True`` (the default), an object type the schema does not
            have raises [IDFParseError][idfkit.exceptions.IDFParseError], as [load_idf][idfkit.load_idf] does,
            and the message suggests the closest type; EnergyPlus refuses such a file. ``False``
            skips it with a logged warning.
        strict: When ``True``, accessing or setting an unknown field name on any
            IDFObject raises [InvalidFieldError][idfkit.exceptions.InvalidFieldError] instead
            of returning ``None``, and assigning a value the schema refuses raises
            [ValidationFailedError][idfkit.exceptions.ValidationFailedError], as ``add()`` does.
        preserve_formatting: When ``True``, store the raw JSON text so
            that [write_epjson][idfkit.writers.write_epjson] and [save_epjson][idfkit.writers.save_epjson] can
            reproduce it byte-for-byte
            when no objects have been modified.
        normalize_choices: When ``True`` (the default), each choice value is stored in the
            spelling its schema declares, whatever case the file used: a surface the file
            calls ``WALL`` has ``surface_type == "Wall"``, as its ``Literal`` type says, so an
            exhaustive ``match`` holds on models you did not write. EnergyPlus reads choices
            case-insensitively, so no simulation changes. ``False`` keeps the file's text, and
            a choice field's ``Literal`` type then does not hold; see
            [IDFDocument.normalize_choices][idfkit.document.IDFDocument.normalize_choices].

    Returns:
        The parsed document: an ``AnyIDFDocument``, or typed as ``as_type=`` or the
        ``since=``/``before=`` range when one is given.

    Raises:
        IDFParseError: For an object type the schema does not have, with *strict_parsing*.
        TypeError: As [load_idf][idfkit.load_idf] raises it.
        ValueError: As [load_idf][idfkit.load_idf] raises it.

    Examples:
        Load an epJSON model and iterate over zones:

            ```python
            model = load_epjson("SmallOffice.epJSON")
            for zone in model["Zone"]:
                print(zone.name, zone.x_origin)
            ```

        Load it typed for the release it must be:

            ```python
            from idfkit.versioned import IDFDocumentV24_1

            model = load_epjson("SmallOffice.epJSON", as_type=IDFDocumentV24_1)
            ```

        Specify an explicit EnergyPlus version:

            ```python
            model = load_epjson("SmallOffice.epJSON", version=(24, 1, 0))
            ```
    """
    strict = _prepare(as_type, since, before, strict, version)
    doc = parse_epjson(
        Path(path),
        version=version,
        strict=strict,
        strict_parsing=strict_parsing,
        preserve_formatting=preserve_formatting,
        normalize_choices=normalize_choices,
    )
    return _narrow(doc, path, as_type, since, before)

IDF Parser

Streaming IDF parser - parses EnergyPlus IDF files into IDFDocument.

Features: - Memory-efficient streaming for large files - Regex-based tokenization - Direct parsing into IDFDocument (no intermediate structures) - Type coercion based on schema - Optional CST (Concrete Syntax Tree) for lossless round-tripping

logger = logging.getLogger(__name__) module-attribute

IDFParser

Streaming parser for IDF files.

Uses memory mapping for large files and regex for tokenization.

Source code in idfkit/idf_parser.py
 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
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
class IDFParser:
    """
    Streaming parser for IDF files.

    Uses memory mapping for large files and regex for tokenization.
    """

    __slots__ = (
        "_content",
        "_diagnostics",
        "_encoding",
        "_filepath",
        "_normalize_choices",
        "_requested_encoding",
        "_schema",
        "_strict_parsing",
    )

    _filepath: Path
    _schema: EpJSONSchema | None
    #: The codec the parse in progress decodes with: the requested one, else the detected one.
    _encoding: str
    #: The codec the caller asked for, or ``None`` to detect it from each file's bytes.
    _requested_encoding: str | None
    _content: bytes | None
    _strict_parsing: bool
    _diagnostics: list[ParseDiagnostic]
    #: Whether the parse in progress stores choices in their schema's spelling; set by
    #: [parse][idfkit.idf_parser.IDFParser.parse].
    _normalize_choices: bool

    def __init__(
        self,
        filepath: Path,
        schema: EpJSONSchema | None = None,
        encoding: str | None = None,
        strict_parsing: bool = True,
    ):
        self._filepath = filepath
        self._schema = schema
        self._requested_encoding = encoding
        self._encoding = encoding or "latin-1"
        self._strict_parsing = strict_parsing
        self._normalize_choices = True
        self._content: bytes | None = None
        # Recoverable findings from the last parse: the ones that did not stop it.
        #
        # These have always been produced; they went to the logging module and nowhere else, so a
        # caller who wanted them had to install a handler before parsing. They are collected here
        # too, so `load_idf_with_diagnostics` can hand them back in one call. Every logging
        # announcement still fires exactly as it did (FR-014); this adds a second way to reach the
        # same findings and removes none.
        self._diagnostics = []

    @property
    def diagnostics(self) -> tuple[ParseDiagnostic, ...]:
        """Recoverable findings from the most recent parse, in the order they were noticed."""
        return tuple(self._diagnostics)

    def _record(
        self,
        message: str,
        *,
        code: ParseDiagnosticCode,
        obj_type: str | None = None,
        obj_name: str | None = None,
        content: bytes | None = None,
        offset: int | None = None,
    ) -> None:
        """Note a recoverable finding, resolving its position while the offset is still in hand.

        The position has to be captured here rather than recovered later. The aggregate site used
        to reduce its findings to a set of type names before warning, which threw away every offset
        it had, and a finding with no position is not the finding the other language returns.
        """
        line: int | None = None
        column: int | None = None
        if content is not None and offset is not None:
            line, column = self._line_and_column(content, offset)
        self._diagnostics.append(
            ParseDiagnostic(
                message=message,
                filepath=str(self._filepath),
                obj_type=obj_type,
                obj_name=obj_name,
                line=line,
                column=column,
                code=code,
            )
        )

    def parse(
        self,
        version: tuple[int, int, int] | None = None,
        *,
        strict: bool = True,
        preserve_formatting: bool = False,
        normalize_choices: bool = True,
    ) -> IDFDocument:
        """
        Parse the IDF file into an IDFDocument.

        Args:
            version: Optional version override
            strict: Enforce strict field access on the resulting document.
            preserve_formatting: Build a CST for lossless round-tripping.
            normalize_choices: Store each choice value in the spelling its schema declares.

        Returns:
            Parsed IDFDocument
        """
        t0 = time.perf_counter()
        # A parser may be reused, and findings belong to one parse rather than to its whole life.
        self._diagnostics = []
        self._normalize_choices = normalize_choices
        logger.debug("Parsing IDF file %s", self._filepath)

        # Load content (with mmap for large files)
        content, self._encoding, source_encoding = _resolve_encoding(self._load_content(), self._requested_encoding)
        if _EPJSON_START.match(content):
            raise FileFormatError(str(self._filepath), "epjson")

        # Detect version if not provided
        if version is None:
            version = self._detect_version(content)
            logger.debug("Detected version %d.%d.%d", *version)

        # Load schema if not provided
        schema = self._schema
        if schema is None:
            from .schema import get_schema

            schema = get_schema(version)

        # Create document
        doc = IDFDocument(
            version=version,
            schema=schema,
            filepath=self._filepath,
            strict=strict,
            normalize_choices=normalize_choices,
        )
        doc._source_encoding = source_encoding
        doc._source_newline = _detect_newline(content)

        # Parse objects
        self._parse_objects(content, doc, schema)

        # Build CST for lossless round-tripping (opt-in, no cost when False)
        if preserve_formatting:
            original_text = content.decode(self._encoding)
            cst = _build_idf_cst(original_text)
            cst.encoding = source_encoding
            if _link_cst_to_objects(cst, doc, self._diagnostics, str(self._filepath)):
                doc._cst = cst  # pyright: ignore[reportAttributeAccessIssue]
                doc._raw_text = original_text  # pyright: ignore[reportAttributeAccessIssue]
            else:
                logger.warning("CST discarded due to linking failure — lossless round-trip disabled")
                # No position: the failure is a property of the whole tree, not of one place in it.
                self._record(
                    "CST discarded due to linking failure, lossless round-trip disabled",
                    code="ParseError",
                )

        elapsed = time.perf_counter() - t0
        logger.info("Parsed %d objects from %s in %.3fs", len(doc), self._filepath, elapsed)

        return doc

    def _load_content(self) -> bytes:
        """Load file content, using mmap for large files."""
        file_size = self._filepath.stat().st_size
        use_mmap = file_size > _MMAP_THRESHOLD

        if use_mmap:
            logger.debug("Using mmap for large file (%d bytes)", file_size)
            # Use memory mapping for large files
            with open(self._filepath, "rb") as f:
                mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
                content = bytes(mm)
                mm.close()
        else:
            with open(self._filepath, "rb") as f:
                content = f.read()

        return content

    def _detect_version(self, content: bytes) -> tuple[int, int, int]:
        """Detect EnergyPlus version from file content."""
        # Search the whole file. ``content`` is already in memory, so a window
        # saves nothing here and costs correctness: nothing in the format puts
        # the Version object near the top, and three of the example files
        # shipped with EnergyPlus 26.1.0 carry it past the first 10 KB.
        match = _search_version(content)
        if match:
            major = int(match.group(1))
            minor = int(match.group(2))
            patch = int(match.group(3)) if match.group(3) else 0
            return (major, minor, patch)

        raise VersionNotFoundError(str(self._filepath))

    def _parse_objects(
        self,
        content: bytes,
        doc: AnyIDFDocument,
        schema: EpJSONSchema | None,
    ) -> None:
        """Parse all objects from content into document."""
        # Strip comments before matching to prevent phantom objects
        # (e.g. "!- X,Y,Z Origin" matching "X," as an object type)
        content = _COMMENT_PATTERN.sub(b"", content)

        # Local per-type caches avoid repeated schema lookups
        type_cache: dict[str, ParsingCache | None] = {}
        canonical_cache: dict[str, str] = {}
        encoding = self._encoding
        # Values are normalized while the fields are read, so objects are filed as they are.
        addidfobject = doc._adopt  # pyright: ignore[reportPrivateUsage]
        skipped_types: set[str] = set()

        # Every match ends at a `;`, so nothing past the last one can match. Bounding the scan there
        # keeps the scanner off the unterminated tail, which is reported on its own below.
        end = content.rfind(b";") + 1

        for match in _OBJECT_PATTERN.finditer(content, 0, end):
            match_offset = match.start(1)
            obj_type: str | None = None
            obj_name: str | None = None

            try:
                decoded_obj_type = match.group(1).decode(encoding).strip()
                obj_type = decoded_obj_type

                obj_name = self._extract_object_name(match, encoding)

                pc, should_skip, decoded_obj_type = self._resolve_type_cache(
                    content=content,
                    schema=schema,
                    type_cache=type_cache,
                    canonical_cache=canonical_cache,
                    skipped_types=skipped_types,
                    obj_type=decoded_obj_type,
                    obj_name=obj_name,
                    match_offset=match_offset,
                )
                if should_skip:
                    continue

                obj = self._parse_object_cached(match, pc, encoding, obj_type_override=decoded_obj_type, schema=schema)
                if obj:
                    addidfobject(obj)
            except IDFParseError:
                raise
            except Exception as exc:
                if self._strict_parsing:
                    self._raise_parse_error(
                        content,
                        match_offset,
                        f"Failed to parse object: {exc}",
                        obj_type=obj_type,
                        obj_name=obj_name,
                    )
                logger.warning("Skipping malformed object %r: %s", obj_type or "<decode_error>", exc)
                self._record(
                    f"Skipping malformed object: {exc}",
                    code="ParseError",
                    obj_type=obj_type,
                    obj_name=obj_name,
                    content=content,
                    offset=match_offset,
                )

        if skipped_types:
            logger.warning(
                "Skipped %d unknown object type(s): %s", len(skipped_types), ", ".join(sorted(skipped_types))
            )

        self._check_unterminated_tail(content, end, encoding)

    def _check_unterminated_tail(self, content: bytes, end: int, encoding: str) -> None:
        """Report text after the last ``;`` that is not blank, which is an object missing its ``;``.

        The object pattern only matches text that reaches a semicolon, so such an object used to be
        discarded without a word (idfkit#187). *content* has had its comments stripped already, so
        a trailing comment is blank here, and offsets still give the original line numbers.
        """
        tail = content[end:]
        stripped = tail.lstrip(_TRAILING_BLANK)
        if not stripped.rstrip(_TRAILING_BLANK):
            return

        offset = end + len(tail) - len(stripped)
        # A truncated file can end inside a multibyte character, so decoding must not raise here:
        # that would replace the finding with a UnicodeDecodeError, even on the returning path.
        type_match = _TAIL_TYPE_PATTERN.match(stripped)
        obj_type = type_match.group(1).decode(encoding, errors="replace").strip() if type_match else None
        # Only a few bytes per quoted character are needed; the tail may be most of the file.
        head = stripped[: _UNTERMINATED_EXCERPT * 8].decode(encoding, errors="replace")
        excerpt = " ".join(head.split())
        if len(excerpt) > _UNTERMINATED_EXCERPT or len(stripped) > _UNTERMINATED_EXCERPT * 8:
            excerpt = excerpt[:_UNTERMINATED_EXCERPT] + "..."
        message = f'Unterminated object near "{excerpt}" (missing ";")'

        if self._strict_parsing:
            self._raise_parse_error(content, offset, message, obj_type=obj_type)
        logger.warning("Skipping unterminated object %r: %s", obj_type or "<unknown>", message)
        self._record(message, code="ParseError", obj_type=obj_type, content=content, offset=offset)

    def _parse_object_cached(
        self,
        match: re.Match[bytes],
        pc: ParsingCache | None,
        encoding: str,
        *,
        obj_type_override: str | None = None,
        schema: EpJSONSchema | None = None,
    ) -> IDFObject | None:
        """Parse a single object from regex match using cached metadata.

        *schema* names the object types a value running onto the next line is checked against.
        """
        obj_type = obj_type_override or match.group(1).decode(encoding).strip()
        fields_raw = match.group(2).decode(encoding)

        fields = self._parse_fields(fields_raw)
        if not fields:
            return None

        swallowed: int | None = None
        if pc is not None and schema is not None and _VALUE_THEN_LINE_BREAK.search(fields_raw) is not None:
            swallowed = self._check_swallowed_object(match, fields_raw, encoding, obj_type, fields, pc, schema)

        if pc is not None:
            has_name = pc.has_name
            # Mutable copy since extensible parsing appends to it
            field_names: list[str] = list(pc.field_names) if has_name else list(pc.all_field_names)

            name, remaining_fields = (fields[0], fields[1:]) if has_name else ("", fields)

            invalid: list[tuple[int, str, str]] = []
            data = self._build_data_dict_cached(remaining_fields, field_names, pc, invalid)
            if invalid and swallowed is not None:
                # The values from the swallowed one on are the lost object's, read into this one's
                # fields; the missing ';' was reported once already, so they are not reported again.
                invalid = [entry for entry in invalid if entry[0] + (1 if has_name else 0) < swallowed]
            if invalid:
                self._report_invalid_fields(match, fields_raw, encoding, obj_type, fields, pc, invalid)

            return IDFObject(
                obj_type=obj_type,
                name=name,
                data=data,
                schema=pc.obj_schema,
                field_order=field_names,
                ref_fields=pc.ref_fields,
                extensibles=frozenset(pc.ext_field_names),
                wrapper_key=pc.ext_wrapper_key,
                ext_inner_names=tuple(pc.ext_inner_props.keys()),
                aliases=pc.field_aliases,
            )

        # No-schema fallback
        name = fields[0] if fields else ""
        remaining = fields[1:]
        data: dict[str, Any] = {}
        for i, value in enumerate(remaining):
            if value:
                data[f"field_{i + 1}"] = value
        return IDFObject(obj_type=obj_type, name=name, data=data)

    def _check_swallowed_object(
        self,
        match: re.Match[bytes],
        fields_raw: str,
        encoding: str,
        obj_type: str,
        fields: list[str],
        pc: ParsingCache,
        schema: EpJSONSchema,
    ) -> int | None:
        """Report a value that runs onto a line starting with an object type: a missing ``;``.

        ``Zone, A, 0, 0, 0`` followed by ``Material, M;`` reads as one Zone whose y origin is
        ``"0\nMaterial"``, and the Material is lost. The finding never stops the parse, in either mode:
        a line break inside a value is legal (``My`` then ``Zone,`` is the one name ``"My Zone"``), so
        the object is kept as read, a warning is logged, and a ``ParseError`` diagnostic is recorded,
        which [load_idf_with_diagnostics][idfkit.load_idf_with_diagnostics] returns.

        Returns the index in *fields* of the value reported, or ``None`` when there is none.
        """
        for index, value in enumerate(fields):
            if "\n" not in value:
                continue
            before, _, after = value.partition("\n")
            next_type = next((line.strip() for line in after.split("\n") if line.strip()), "")
            if schema.resolve_type_name(next_type) is None:
                continue
            field_name = _swallowed_field_name(pc, index)
            message = (
                f"Field {field_name!r} runs onto the next line, which starts with {next_type!r}: "
                f"missing ';' after {before.strip()!r}, before {next_type!r}?"
            )
            offset = _field_offset(fields_raw, index)
            prefix = 0 if offset is None else len(fields_raw[:offset].encode(encoding))
            position = match.start(2) + prefix
            # When the name itself ran on, the object's name is the part before the line break.
            obj_name = (before.strip() if index == 0 else fields[0]) if pc.has_name else None
            logger.warning("Possible missing ';' in %s %r: %s", obj_type, obj_name, message)
            self._record(
                message, code="ParseError", obj_type=obj_type, obj_name=obj_name, content=match.string, offset=position
            )
            return index
        return None

    def _report_invalid_fields(
        self,
        match: re.Match[bytes],
        fields_raw: str,
        encoding: str,
        obj_type: str,
        fields: list[str],
        pc: ParsingCache,
        invalid: list[tuple[int, str, str]],
    ) -> None:
        """Report values the schema declares numeric that are neither numeric nor a legal sentinel.

        Never raises, in either mode. A value of the wrong kind does not stop the parse: the object
        is built and the document is returned, so a caller who was reading strictly still gets what
        they got before (FR-014). The value is kept as read, so ``validate_document()`` reports it.
        This adds a finding where there was silence, and nothing else.

        The finding is positioned at the offending FIELD rather than at the object, because that is
        what makes it useful: the shape this catches is a missing semicolon swallowing the object
        below, and the object's own first line is nowhere near the damage.
        """
        name_offset = 1 if pc.has_name else 0
        for index, field_name, value in invalid:
            if _string_is_legal(pc.obj_schema, field_name, value):
                continue

            offset = _field_offset(fields_raw, index + name_offset)
            prefix = 0 if offset is None else len(fields_raw[:offset].encode(encoding))
            position = match.start(2) + prefix

            self._record(
                f"Field {field_name!r} expects a number, got {value!r}",
                code="InvalidField",
                obj_type=obj_type,
                obj_name=fields[0] if pc.has_name and fields else None,
                content=match.string,
                offset=position,
            )

    def _build_data_dict_cached(
        self,
        remaining_fields: list[str],
        field_names: list[str],
        pc: ParsingCache,
        invalid: list[tuple[int, str, str]] | None = None,
    ) -> dict[str, Any]:
        """Build the data dict using pre-computed field types from the cache.

        *invalid* collects ``(index, field name, value)`` for each value the schema declares numeric
        that did not coerce. It is almost always empty, and detecting that costs one identity test
        and one frozenset lookup per field: ``_coerce_value_fast`` returns a NEW object when it
        succeeds and hands back the very string it was given when it fails, so ``is`` separates the
        two without re-parsing anything.

        Whether such a value is actually wrong is not decided here. A numeric field routinely
        accepts ``autosize``; that question needs the schema and is asked on the reporting path.

        A value left a string is, when it folds to one of its field's choices, stored in the
        spelling the schema declares, so the field's ``Literal`` type holds for any file. The
        same identity test confines that lookup to strings: a coerced number never pays for it.
        """
        data: dict[str, Any] = {}
        field_types = pc.field_types
        num_named = len(field_names)
        choices = pc.choice_spellings if self._normalize_choices else None

        # zip stops at the named fields: the extensible tail is bucketed below, not walked here.
        for i, (field_name, value) in enumerate(zip(field_names, remaining_fields, strict=False)):
            # A blank field is unset and stays absent, as in epJSON and as the extensible groups below
            # already do. Holding it as "" made the model disagree with both writers, which drop it,
            # so a re-parse of idfkit's own output was not equal to the original (idfkit#183).
            if value:
                field_type = field_types.get(field_name)
                coerced = _coerce_value_fast(field_type, value)
                if coerced is value:
                    if invalid is not None and field_type in _NUMERIC_FIELD_TYPES:
                        invalid.append((i, field_name, value))
                    if choices and (table := choices.get(field_name)) is not None:
                        coerced = table.get(value.casefold(), value)
                data[field_name] = coerced

        if len(remaining_fields) > num_named:
            extra = remaining_fields[num_named:]
            if pc.extensible:
                self._append_extensible_fields(
                    data=data,
                    extra=extra,
                    field_names=field_names,
                    field_types=field_types,
                    pc=pc,
                )
            elif self._strict_parsing and any(extra):
                # Trailing blanks past the last field are unset, like any other blank field, and are
                # not extra values: EnergyPlus accepts ``Timestep,4,,;`` and refuses ``Timestep,4,5;``.
                # It is also how idfkit writes an object with nothing in it to keep its terminator,
                # ``GroundHeatTransfer:Slab:XFACE,;``. Only the values up to the last non-blank one
                # are counted as extra.
                overflow = len(extra) - next(i for i, value in enumerate(reversed(extra)) if value)
                msg = (
                    f"Object has {overflow} extra field(s) but type is not extensible "
                    f"(expected at most {num_named}, got {num_named + overflow})"
                )
                raise ValueError(msg)

        return data

    def _append_extensible_fields(
        self,
        *,
        data: dict[str, Any],
        extra: list[str],
        field_names: list[str],
        field_types: dict[str, str | None],
        pc: ParsingCache,
    ) -> None:
        """Bucket extensible-group tokens into a canonical wrapper array.

        Tokens are split into ``ext_size``-wide groups; each group becomes
        a dict keyed by the schema's inner property names, and the resulting
        list is stored under ``data[wrapper_key]`` (e.g. ``data["vertices"]``).
        The wrapper key is *not* added to ``field_names`` — the IDF writer
        handles wrapper expansion separately via the schema cache.
        """
        ext_size = pc.ext_size
        if ext_size <= 0:
            if self._strict_parsing:
                msg = "Object is marked extensible but extensible group size is invalid"
                raise ValueError(msg)
            return

        ext_names = pc.ext_field_names
        num_ext = len(ext_names)
        ext_types = tuple(field_types.get(name) for name in ext_names)
        wrapper_key = pc.ext_wrapper_key
        ext_choices = pc.ext_choice_spellings if self._normalize_choices else None

        items: list[dict[str, Any]] = []
        for group_start in range(0, len(extra), ext_size):
            group = extra[group_start : group_start + ext_size]
            # A blank slot is absent rather than "", as in epJSON; the IDF writer restores it (idfkit#182).
            item: dict[str, Any] = {
                ext_names[j]: _coerce_value_fast(ext_types[j], value)
                for j, value in enumerate(group[:num_ext])
                if value
            }
            # Drop all-empty groups (e.g. an extra "," at the end of the extensible block).
            # Keeping them would emit phantom vertices.
            if item:
                if ext_choices:
                    for name, value in item.items():
                        table = ext_choices.get(name)
                        if table is not None and type(value) is str:
                            item[name] = table.get(value.casefold(), value)
                items.append(item)

        if items and wrapper_key is not None:
            data[wrapper_key] = items

    def _parse_fields(self, fields_raw: str) -> list[str]:
        """Parse and clean field values from raw string."""
        # Fast path: comments already stripped by _COMMENT_PATTERN in _parse_objects
        if "!" not in fields_raw:
            return [part.strip() for part in fields_raw.split(",")]

        # Slow path: strip inline comments (safety fallback)
        lines: list[str] = []
        for line in fields_raw.split("\n"):
            idx = line.find("!")
            if idx >= 0:
                line = line[:idx]
            lines.append(line)
        clean_text = " ".join(lines)
        return [part.strip() for part in clean_text.split(",")]

    @staticmethod
    def _line_and_column(content: bytes, offset: int) -> tuple[int, int]:
        """Convert a byte offset to 1-based (line, column)."""
        line = content.count(b"\n", 0, offset) + 1
        previous_newline = content.rfind(b"\n", 0, offset)
        if previous_newline < 0:
            return (line, offset + 1)
        return (line, offset - previous_newline)

    @staticmethod
    def _extract_object_name(match: re.Match[bytes], encoding: str) -> str | None:
        """Best-effort extraction of the raw first field (typically object name)."""
        fields_raw = match.group(2).decode(encoding)
        first = fields_raw.split(",", maxsplit=1)[0].strip()
        return first or None

    def _raise_parse_error(
        self,
        content: bytes,
        offset: int,
        message: str,
        *,
        obj_type: str | None = None,
        obj_name: str | None = None,
        code: ParseDiagnosticCode = "ParseError",
    ) -> None:
        """Raise a ParseError with contextual diagnostics."""
        line, column = self._line_and_column(content, offset)
        diagnostic = ParseDiagnostic(
            message=message,
            filepath=str(self._filepath),
            obj_type=obj_type,
            obj_name=obj_name,
            line=line,
            column=column,
            code=code,
        )
        summary = "Failed to parse IDF"
        raise IDFParseError(summary, diagnostics=[diagnostic])

    def _resolve_type_cache(
        self,
        *,
        content: bytes,
        schema: EpJSONSchema | None,
        type_cache: dict[str, ParsingCache | None],
        canonical_cache: dict[str, str],
        skipped_types: set[str],
        obj_type: str,
        obj_name: str | None,
        match_offset: int,
    ) -> tuple[ParsingCache | None, bool, str]:
        """Resolve and cache parsing metadata for an object type.

        Returns ``(cache, should_skip, canonical_type)`` where *canonical_type*
        is the PascalCase schema name (may differ from the raw IDF casing).
        """
        if schema is None:
            return (None, False, obj_type)

        pc = type_cache.get(obj_type)
        if pc is None and obj_type not in type_cache:
            pc = schema.get_parsing_cache(obj_type)
            type_cache[obj_type] = pc

        if pc is not None:
            # Return cached canonical name (resolved once per raw type).
            canonical = canonical_cache.get(obj_type)
            if canonical is None:
                canonical = schema.resolve_type_name(obj_type) or obj_type
                canonical_cache[obj_type] = canonical
            return (pc, False, canonical)

        if self._strict_parsing:
            # The same code the recoverable path below uses, and the same one the other language
            # reports for this input. A finding must not change kind depending on which mode was
            # asked for: it is the same finding, arriving on a different path.
            msg = f"Unknown object type '{obj_type}'"
            self._raise_parse_error(
                content,
                match_offset,
                msg,
                obj_type=obj_type,
                obj_name=obj_name,
                code="UnknownObjectType",
            )

        # One finding per skip, positioned, and recorded HERE rather than after the loop.
        #
        # `skipped_types` is a set and stays one, because the log line it feeds is a summary and
        # changing it would change what an existing caller sees. But a set of type names is not
        # what the other language returns: it collapses four skips of the same type into one and
        # discards every offset. The offset is in hand at exactly this point and nowhere later,
        # which is why the finding is built here.
        self._record(
            f"Unknown object type '{obj_type}'",
            code="UnknownObjectType",
            obj_type=obj_type,
            obj_name=obj_name,
            content=content,
            offset=match_offset,
        )
        skipped_types.add(obj_type)
        return (None, True, obj_type)

diagnostics property

Recoverable findings from the most recent parse, in the order they were noticed.

parse(version=None, *, strict=True, preserve_formatting=False, normalize_choices=True)

Parse the IDF file into an IDFDocument.

Parameters:

Name Type Description Default
version tuple[int, int, int] | None

Optional version override

None
strict bool

Enforce strict field access on the resulting document.

True
preserve_formatting bool

Build a CST for lossless round-tripping.

False
normalize_choices bool

Store each choice value in the spelling its schema declares.

True

Returns:

Type Description
IDFDocument

Parsed IDFDocument

Source code in idfkit/idf_parser.py
def parse(
    self,
    version: tuple[int, int, int] | None = None,
    *,
    strict: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> IDFDocument:
    """
    Parse the IDF file into an IDFDocument.

    Args:
        version: Optional version override
        strict: Enforce strict field access on the resulting document.
        preserve_formatting: Build a CST for lossless round-tripping.
        normalize_choices: Store each choice value in the spelling its schema declares.

    Returns:
        Parsed IDFDocument
    """
    t0 = time.perf_counter()
    # A parser may be reused, and findings belong to one parse rather than to its whole life.
    self._diagnostics = []
    self._normalize_choices = normalize_choices
    logger.debug("Parsing IDF file %s", self._filepath)

    # Load content (with mmap for large files)
    content, self._encoding, source_encoding = _resolve_encoding(self._load_content(), self._requested_encoding)
    if _EPJSON_START.match(content):
        raise FileFormatError(str(self._filepath), "epjson")

    # Detect version if not provided
    if version is None:
        version = self._detect_version(content)
        logger.debug("Detected version %d.%d.%d", *version)

    # Load schema if not provided
    schema = self._schema
    if schema is None:
        from .schema import get_schema

        schema = get_schema(version)

    # Create document
    doc = IDFDocument(
        version=version,
        schema=schema,
        filepath=self._filepath,
        strict=strict,
        normalize_choices=normalize_choices,
    )
    doc._source_encoding = source_encoding
    doc._source_newline = _detect_newline(content)

    # Parse objects
    self._parse_objects(content, doc, schema)

    # Build CST for lossless round-tripping (opt-in, no cost when False)
    if preserve_formatting:
        original_text = content.decode(self._encoding)
        cst = _build_idf_cst(original_text)
        cst.encoding = source_encoding
        if _link_cst_to_objects(cst, doc, self._diagnostics, str(self._filepath)):
            doc._cst = cst  # pyright: ignore[reportAttributeAccessIssue]
            doc._raw_text = original_text  # pyright: ignore[reportAttributeAccessIssue]
        else:
            logger.warning("CST discarded due to linking failure — lossless round-trip disabled")
            # No position: the failure is a property of the whole tree, not of one place in it.
            self._record(
                "CST discarded due to linking failure, lossless round-trip disabled",
                code="ParseError",
            )

    elapsed = time.perf_counter() - t0
    logger.info("Parsed %d objects from %s in %.3fs", len(doc), self._filepath, elapsed)

    return doc

ParseResult dataclass

Bases: Generic[_DocT]

A document, and the recoverable findings from the parse that produced it.

What load_idf_with_diagnostics hands back. The findings here are the ones that did NOT stop the parse: a skipped unknown type, a malformed object, a formatting tree that could not be linked. The ones that did stop it never reach this type, because there is no document to pair them with; they arrive on IDFParseError.diagnostics instead.

Field names match the other language's ParseResult exactly, so a reader moving between the two reads the same two names in the same order.

Generic in the document's type: ParseResult alone carries an AnyIDFDocument, since a file's release is known only once it is read, and load_idf_with_diagnostics(path, as_type=IDFDocumentV9_4) returns a ParseResult[IDFDocumentV9_4].

Source code in idfkit/idf_parser.py
@dataclass(frozen=True)
class ParseResult(Generic[_DocT]):
    """A document, and the recoverable findings from the parse that produced it.

    What `load_idf_with_diagnostics` hands back. The findings here are the ones that did NOT stop
    the parse: a skipped unknown type, a malformed object, a formatting tree that could not be
    linked. The ones that did stop it never reach this type, because there is no document to pair
    them with; they arrive on `IDFParseError.diagnostics` instead.

    Field names match the other language's `ParseResult` exactly, so a reader moving between the
    two reads the same two names in the same order.

    Generic in the document's type: ``ParseResult`` alone carries an ``AnyIDFDocument``, since a
    file's release is known only once it is read, and
    ``load_idf_with_diagnostics(path, as_type=IDFDocumentV9_4)`` returns a
    ``ParseResult[IDFDocumentV9_4]``.
    """

    document: _DocT
    diagnostics: tuple[ParseDiagnostic, ...]

diagnostics instance-attribute

document instance-attribute

get_idf_version(filepath)

Quick version detection without full parsing.

Reads the first 10 KB of the file, which holds the Version object in almost every model, and falls back to reading the rest only when it does not. The common case costs one small read; no valid file is refused for stating its version late. Nothing in the IDF format requires Version to appear near the top, and three of the example files shipped with EnergyPlus 26.1.0 carry it past 10 KB.

Parameters:

Name Type Description Default
filepath Path | str

Path to IDF file

required

Returns:

Type Description
tuple[int, int, int]

Version tuple (major, minor, patch)

Raises:

Type Description
VersionNotFoundError

If the file holds no Version object

Examples:

Check which EnergyPlus version a model was created for (usually reads only the first 10 KB):

```python
from idfkit import get_idf_version

version = get_idf_version("5ZoneAirCooled.idf")
print(f"EnergyPlus v{version[0]}.{version[1]}.{version[2]}")
```
Source code in idfkit/idf_parser.py
def get_idf_version(filepath: Path | str) -> tuple[int, int, int]:
    """
    Quick version detection without full parsing.

    Reads the first 10 KB of the file, which holds the ``Version`` object in
    almost every model, and falls back to reading the rest only when it does
    not. The common case costs one small read; no valid file is refused for
    stating its version late. Nothing in the IDF format requires ``Version``
    to appear near the top, and three of the example files shipped with
    EnergyPlus 26.1.0 carry it past 10 KB.

    Args:
        filepath: Path to IDF file

    Returns:
        Version tuple (major, minor, patch)

    Raises:
        VersionNotFoundError: If the file holds no Version object

    Examples:
        Check which EnergyPlus version a model was created for
        (usually reads only the first 10 KB):

            ```python
            from idfkit import get_idf_version

            version = get_idf_version("5ZoneAirCooled.idf")
            print(f"EnergyPlus v{version[0]}.{version[1]}.{version[2]}")
            ```
    """
    filepath = Path(filepath)

    with open(filepath, "rb") as f:
        head = f.read(_VERSION_SCAN_BYTES)
        # A comment's `!` precedes its text, so the window holds it whenever it holds the text.
        match = _search_version(head)
        if match is None:
            # The scan window may have split the Version object, so re-search
            # the whole file rather than only the remainder.
            match = _search_version(head + f.read())

    if match:
        major = int(match.group(1))
        minor = int(match.group(2))
        patch = int(match.group(3)) if match.group(3) else 0
        return (major, minor, patch)

    raise VersionNotFoundError(str(filepath))

iter_idf_objects(filepath, encoding=None)

Iterate over objects in an IDF file without loading into document.

Yields:

Type Description
tuple[str, str, list[str]]

Tuples of (object_type, name, [field_values])

This is useful for quick scanning or filtering without full parsing. encoding is read as parse_idf reads it: None detects UTF-8 or latin-1.

Note

Type names are returned exactly as they appear in the IDF file (no schema-based case normalization). Use case-insensitive comparisons when filtering: obj_type.upper() == "ZONE".

Examples:

Count thermal zones without loading the full document (useful for quickly sizing batch runs):

```python
from idfkit import iter_idf_objects

zone_count = sum(
    1 for obj_type, name, _
    in iter_idf_objects("5ZoneAirCooled.idf")
    if obj_type == "Zone"
)
```

Collect all material names for an audit report:

```python
materials = [
    name for obj_type, name, _
    in iter_idf_objects("LargeOffice.idf")
    if obj_type == "Material"
]
```
Source code in idfkit/idf_parser.py
def iter_idf_objects(
    filepath: Path | str,
    encoding: str | None = None,
) -> Iterator[tuple[str, str, list[str]]]:
    """
    Iterate over objects in an IDF file without loading into document.

    Yields:
        Tuples of (object_type, name, [field_values])

    This is useful for quick scanning or filtering without full parsing.
    ``encoding`` is read as [parse_idf][idfkit.idf_parser.parse_idf] reads it: ``None`` detects UTF-8 or latin-1.

    Note:
        Type names are returned exactly as they appear in the IDF file
        (no schema-based case normalization).  Use case-insensitive
        comparisons when filtering: ``obj_type.upper() == "ZONE"``.

    Examples:
        Count thermal zones without loading the full document
        (useful for quickly sizing batch runs):

            ```python
            from idfkit import iter_idf_objects

            zone_count = sum(
                1 for obj_type, name, _
                in iter_idf_objects("5ZoneAirCooled.idf")
                if obj_type == "Zone"
            )
            ```

        Collect all material names for an audit report:

            ```python
            materials = [
                name for obj_type, name, _
                in iter_idf_objects("LargeOffice.idf")
                if obj_type == "Material"
            ]
            ```
    """
    filepath = Path(filepath)

    with open(filepath, "rb") as f:
        content = f.read()
    content, encoding, _ = _resolve_encoding(content, encoding)

    # Strip comments before matching to prevent phantom objects
    content = _COMMENT_PATTERN.sub(b"", content)

    # As in `IDFParser._parse_objects`: no match reaches past the last `;`, and scanning an
    # unterminated tail costs time quadratic in its length for nothing (idfkit#187).
    end = content.rfind(b";") + 1
    if content[end:].strip(_TRAILING_BLANK):
        logger.warning('Ignoring unterminated object at the end of %s (missing ";")', filepath)

    for match in _OBJECT_PATTERN.finditer(content, 0, end):
        obj_type = match.group(1).decode(encoding).strip()
        fields_raw = match.group(2).decode(encoding)

        # Split and clean fields
        fields: list[str] = []
        for part in fields_raw.split(","):
            if "!" in part:
                part = part[: part.index("!")]
            fields.append(part.strip())

        obj_name = fields[0] if fields else ""
        yield (obj_type, obj_name, fields[1:])

parse_idf(filepath, schema=None, version=None, encoding=None, strict_parsing=True, strict=True, *, preserve_formatting=False, normalize_choices=True)

Parse an IDF file into an IDFDocument.

Parameters:

Name Type Description Default
filepath Path | str

Path to the IDF file

required
schema EpJSONSchema | None

Optional EpJSONSchema for field ordering and type coercion

None
version tuple[int, int, int] | None

Optional version override (auto-detected if not provided)

None
encoding str | None

File encoding. None (the default) reads the file as UTF-8 when its bytes are valid UTF-8, and as latin-1 otherwise. A leading UTF-8 byte-order mark is dropped. The document remembers the encoding, and save_idf writes it back unless told otherwise.

None
strict_parsing bool

If True, fail fast on malformed objects (default: True)

True
strict bool

When True, accessing or setting an unknown field name on any IDFObject raises InvalidFieldError instead of returning None, and assigning a value the schema refuses raises ValidationFailedError, as add() does.

True
preserve_formatting bool

If True, build a Concrete Syntax Tree (CST) so that writing the document back preserves original formatting, comments, and whitespace for unmodified objects. The default code path is unchanged — no performance penalty when False.

False
normalize_choices bool

When True (the default), each choice value is stored in the spelling its schema declares, whatever case the file used: WALL reads back "Wall", as the field's Literal type says. False keeps the file's text. Either way, a preserve_formatting=True write emits unmodified objects verbatim.

True

Returns:

Type Description
IDFDocument

Parsed IDFDocument

Raises:

Type Description
VersionNotFoundError

If version cannot be detected

IdfKitError

If parsing fails

Examples:

Load and inspect a DOE reference building:

```python
from idfkit import parse_idf

model = parse_idf("RefBldgSmallOfficeNew2004.idf")
for zone in model["Zone"]:
    print(zone.name, zone.x_origin)
```

Force a specific EnergyPlus version when auto-detection fails (e.g., a pre-v8.9 file that was manually upgraded):

```python
model = parse_idf("legacy_building.idf", version=(9, 6, 0))
```

Round-trip an IDF file losslessly:

```python
model = parse_idf("building.idf", preserve_formatting=True)
# write_idf(model) reproduces the original byte-for-byte
```
Source code in idfkit/idf_parser.py
def parse_idf(
    filepath: Path | str,
    schema: EpJSONSchema | None = None,
    version: tuple[int, int, int] | None = None,
    encoding: str | None = None,
    strict_parsing: bool = True,
    strict: bool = True,
    *,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> IDFDocument:
    """
    Parse an IDF file into an IDFDocument.

    Args:
        filepath: Path to the IDF file
        schema: Optional EpJSONSchema for field ordering and type coercion
        version: Optional version override (auto-detected if not provided)
        encoding: File encoding. ``None`` (the default) reads the file as UTF-8 when its bytes
            are valid UTF-8, and as latin-1 otherwise. A leading UTF-8 byte-order mark is dropped.
            The document remembers the encoding, and [save_idf][idfkit.writers.save_idf] writes it
            back unless told otherwise.
        strict_parsing: If True, fail fast on malformed objects (default: True)
        strict: When ``True``, accessing or setting an unknown field name on any
            IDFObject raises [InvalidFieldError][idfkit.exceptions.InvalidFieldError] instead
            of returning ``None``, and assigning a value the schema refuses raises
            [ValidationFailedError][idfkit.exceptions.ValidationFailedError], as ``add()`` does.
        preserve_formatting: If ``True``, build a Concrete Syntax Tree (CST)
            so that writing the document back preserves original formatting,
            comments, and whitespace for unmodified objects.  The default
            code path is unchanged — no performance penalty when ``False``.
        normalize_choices: When ``True`` (the default), each choice value is stored in the
            spelling its schema declares, whatever case the file used: ``WALL`` reads back
            ``"Wall"``, as the field's ``Literal`` type says. ``False`` keeps the file's text.
            Either way, a ``preserve_formatting=True`` write emits unmodified objects verbatim.

    Returns:
        Parsed IDFDocument

    Raises:
        VersionNotFoundError: If version cannot be detected
        IdfKitError: If parsing fails

    Examples:
        Load and inspect a DOE reference building:

            ```python
            from idfkit import parse_idf

            model = parse_idf("RefBldgSmallOfficeNew2004.idf")
            for zone in model["Zone"]:
                print(zone.name, zone.x_origin)
            ```

        Force a specific EnergyPlus version when auto-detection fails
        (e.g., a pre-v8.9 file that was manually upgraded):

            ```python
            model = parse_idf("legacy_building.idf", version=(9, 6, 0))
            ```

        Round-trip an IDF file losslessly:

            ```python
            model = parse_idf("building.idf", preserve_formatting=True)
            # write_idf(model) reproduces the original byte-for-byte
            ```
    """
    filepath = Path(filepath)

    if not filepath.exists():
        raise FileNotFoundError(f"IDF file not found: {filepath}")  # noqa: TRY003

    parser = IDFParser(filepath, schema, encoding, strict_parsing=strict_parsing)
    return parser.parse(
        version, strict=strict, preserve_formatting=preserve_formatting, normalize_choices=normalize_choices
    )

parse_idf_with_diagnostics(filepath, schema=None, version=None, encoding=None, *, strict=True, preserve_formatting=False, normalize_choices=True)

Parse an IDF file, keeping the findings that did not stop the parse.

The same work parse_idf(..., strict_parsing=False) does, handing back the recoverable findings alongside the document instead of only announcing them through the logging module.

strict_parsing is not a parameter: a strict parse has no recoverable findings by definition, so this function always parses non-strictly. Findings that stop a parse still raise, and still arrive on IDFParseError.diagnostics.

Every logging announcement fires exactly as it does today. A caller with a handler installed sees no change (FR-014); this is a second way to reach the same findings, not a replacement.

encoding and normalize_choices are the parameters of parse_idf.

Source code in idfkit/idf_parser.py
def parse_idf_with_diagnostics(
    filepath: Path | str,
    schema: EpJSONSchema | None = None,
    version: tuple[int, int, int] | None = None,
    encoding: str | None = None,
    *,
    strict: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> ParseResult[IDFDocument]:
    """Parse an IDF file, keeping the findings that did not stop the parse.

    The same work `parse_idf(..., strict_parsing=False)` does, handing back the recoverable
    findings alongside the document instead of only announcing them through the logging module.

    `strict_parsing` is not a parameter: a strict parse has no recoverable findings by definition,
    so this function always parses non-strictly. Findings that stop a parse still raise, and still
    arrive on `IDFParseError.diagnostics`.

    Every logging announcement fires exactly as it does today. A caller with a handler installed
    sees no change (FR-014); this is a second way to reach the same findings, not a replacement.

    `encoding` and `normalize_choices` are the parameters of [parse_idf][idfkit.idf_parser.parse_idf].
    """
    filepath = Path(filepath)

    if not filepath.exists():
        raise FileNotFoundError(f"IDF file not found: {filepath}")  # noqa: TRY003

    parser = IDFParser(filepath, schema, encoding, strict_parsing=False)
    document = parser.parse(
        version, strict=strict, preserve_formatting=preserve_formatting, normalize_choices=normalize_choices
    )
    return ParseResult(document=document, diagnostics=parser.diagnostics)

epJSON Parser

epJSON parser - parses EnergyPlus epJSON files into IDFDocument.

The epJSON format is the native JSON representation of EnergyPlus models. Parsing is straightforward since it's already structured JSON.

logger = logging.getLogger(__name__) module-attribute

EpJSONParser

Parser for epJSON files.

epJSON is the native JSON format for EnergyPlus models, making parsing straightforward - just json.load() and transform.

Source code in idfkit/epjson_parser.py
class EpJSONParser:
    """
    Parser for epJSON files.

    epJSON is the native JSON format for EnergyPlus models, making
    parsing straightforward - just json.load() and transform.
    """

    __slots__ = ("_filepath", "_schema")

    def __init__(
        self,
        filepath: Path,
        schema: EpJSONSchema | None = None,
    ):
        self._filepath = filepath
        self._schema = schema

    def parse(
        self,
        version: tuple[int, int, int] | None = None,
        *,
        strict: bool = True,
        strict_parsing: bool = True,
        preserve_formatting: bool = False,
        normalize_choices: bool = True,
    ) -> IDFDocument:
        """
        Parse the epJSON file into an IDFDocument.

        Args:
            version: Optional version override
            strict: Enforce strict field access on the resulting document.
            strict_parsing: Raise on an object type the schema does not have, rather than skip it.
            preserve_formatting: Store raw JSON text for lossless round-tripping.
            normalize_choices: Store each choice value in the spelling its schema declares.

        Returns:
            Parsed IDFDocument
        """
        t0 = time.perf_counter()
        logger.debug("Parsing epJSON file %s", self._filepath)

        # Load JSON
        try:
            with open(self._filepath, encoding="utf-8") as f:
                raw_text = f.read()
            data: dict[str, Any] = json.loads(raw_text, parse_constant=_constant_refuser(self._filepath))
        except (UnicodeDecodeError, json.JSONDecodeError) as exc:
            # IDF text starts with a comment or an object type, never with '{'. An IDF file is often
            # latin-1 (save_idf's default) and so not UTF-8 at all: look at the bytes, not the text.
            with open(self._filepath, "rb") as f:
                head = f.read(4096)
            first = head.removeprefix(b"\xef\xbb\xbf").lstrip(b" \t\r\n")[:1]
            if first == b"!" or first.isalpha():
                raise FileFormatError(str(self._filepath), "idf") from exc
            raise

        # Detect version if not provided
        if version is None:
            version = self._detect_version(data)
            logger.debug("Detected version %d.%d.%d", *version)

        # Load schema if not provided
        schema = self._schema
        if schema is None:
            from .schema import get_schema

            schema = get_schema(version)

        # Create document
        doc = IDFDocument(
            version=version,
            schema=schema,
            filepath=self._filepath,
            strict=strict,
            normalize_choices=normalize_choices,
        )

        # Parse objects
        self._parse_objects(data, doc, schema, strict_parsing=strict_parsing, normalize_choices=normalize_choices)

        # Store raw text for lossless round-tripping (opt-in).
        if preserve_formatting:
            doc._raw_text = raw_text  # pyright: ignore[reportAttributeAccessIssue]
            # Mark all objects as "pristine" with a sentinel source_text so
            # that the writer can detect mutations.
            for obj in doc.all_objects:
                object.__setattr__(obj, "_source_text", "")
            # How many there were, so that a removal is visible to the writer.
            # The sentinel above only marks the objects that are still here, and
            # a removed one is not among them to ask.
            doc._count_at_read = len(doc)

        elapsed = time.perf_counter() - t0
        logger.info("Parsed %d objects from %s in %.3fs", len(doc), self._filepath, elapsed)

        return doc

    def _detect_version(self, data: dict[str, Any]) -> tuple[int, int, int]:
        """Detect EnergyPlus version from epJSON data."""
        # Version is in the "Version" object
        version_obj = data.get("Version")

        if version_obj:
            # epJSON format: {"Version": {"Version 1": {"version_identifier": "23.2"}}}
            for _name, fields in version_obj.items():
                version_str: str = fields.get("version_identifier", "")
                if version_str:
                    return self._parse_version_string(version_str)

        raise VersionNotFoundError(str(self._filepath))

    @staticmethod
    def _parse_version_string(version_str: str) -> tuple[int, int, int]:
        """Parse version string like '23.2' or '9.2.0'."""
        parts = version_str.split(".")
        major = int(parts[0]) if len(parts) > 0 else 0
        minor = int(parts[1]) if len(parts) > 1 else 0
        patch = int(parts[2]) if len(parts) > 2 else 0
        return (major, minor, patch)

    def _parse_objects(
        self,
        data: dict[str, Any],
        doc: AnyIDFDocument,
        schema: EpJSONSchema | None,
        *,
        strict_parsing: bool = True,
        normalize_choices: bool = True,
    ) -> None:
        """Parse all objects from epJSON data into document.

        An object type *schema* does not have raises with *strict_parsing*, and is skipped
        without, as the IDF parser treats one.

        With *normalize_choices*, each choice is stored in the spelling its schema declares, as the
        IDF parser stores it. EnergyPlus's own epJSON is already canonical; a hand-written or
        converted file need not be.
        """
        # Values are normalized below while each object is built, so objects are filed as they are.
        addidfobject = doc._adopt  # pyright: ignore[reportPrivateUsage]
        unknown_fields: list[ParseDiagnostic] = []

        for obj_type, objects in data.items():
            if not isinstance(objects, dict):
                continue

            # Get schema info from parsing cache
            pc: ParsingCache | None = None
            obj_schema: dict[str, Any] | None = None
            base_field_names: tuple[str, ...] | None = None
            ref_fields: frozenset[str] | None = None
            has_name = True
            # epJSON format: {"ObjectType": {"obj_name": {fields...}, ...}}
            objects_dict = cast(dict[str, Any], objects)
            if schema:
                pc = schema.get_parsing_cache(obj_type)
                if pc is None:
                    self._unknown_type(obj_type, objects_dict, schema, strict_parsing=strict_parsing)
                    continue
                obj_schema = pc.obj_schema
                has_name = pc.has_name
                base_field_names = pc.field_names if has_name else pc.all_field_names
                ref_fields = pc.ref_fields

            for obj_name, fields in objects_dict.items():
                if not isinstance(fields, dict):
                    continue

                # Nameless objects: use empty string instead of epJSON dict key
                name = obj_name if has_name else ""

                fields_dict = cast(dict[str, Any], fields)

                # Real EnergyPlus epJSON is canonical for extensible types, but
                # hand-authored or legacy epJSON sometimes uses flat suffixed
                # keys (vertex_x_coordinate_2, time_3, ...). Coerce them into
                # the canonical wrapper-array shape so downstream consumers see
                # uniform storage.
                if pc and pc.extensible and pc.ext_wrapper_key and pc.ext_field_names:
                    fields_dict = drop_blank_group_slots(_bucket_flat_extensibles(fields_dict, pc), pc.ext_wrapper_key)

                field_order = list(base_field_names) if base_field_names is not None else None
                # A copy, without blank values ("" or null): a blank field is unset, as in IDF (idfkit#183).
                obj_data = {key: value for key, value in fields_dict.items() if not is_blank_slot(value)}
                if normalize_choices and pc is not None:
                    canonicalize_choices(obj_data, pc)
                if has_name and pc is not None and "name" in obj_data:
                    self._drop_body_name(obj_type, obj_name, obj_data)
                unknown_fields.extend(
                    self._unknown_fields(obj_type, obj_name, obj_data, pc, strict_parsing=strict_parsing)
                )

                obj = IDFObject(
                    obj_type=obj_type,
                    name=name,
                    data=obj_data,
                    schema=obj_schema,
                    field_order=field_order,
                    ref_fields=ref_fields,
                    extensibles=frozenset(pc.ext_field_names) if pc else None,
                    wrapper_key=pc.ext_wrapper_key if pc else None,
                    ext_inner_names=tuple(pc.ext_inner_props.keys()) if pc else (),
                    aliases=pc.field_aliases if pc else None,
                )

                addidfobject(obj)

        _raise_unknown_fields(unknown_fields)

    def _drop_body_name(self, obj_type: str, obj_name: str, obj_data: dict[str, Any]) -> None:
        """Drop a ``name`` key repeated inside a named object's body.

        The object's key is its name; some writers repeat it in the body as well. EnergyPlus reads
        the key, so a body name that differs from it is logged and dropped too.
        """
        body_name = obj_data.pop("name")
        if not isinstance(body_name, str) or body_name.upper() != obj_name.upper():
            logger.warning(
                "%s '%s' in %s repeats a different name, %r, in its body; the key is the name",
                obj_type,
                obj_name,
                self._filepath,
                body_name,
            )

    def _unknown_fields(
        self, obj_type: str, obj_name: str, obj_data: dict[str, Any], pc: ParsingCache | None, *, strict_parsing: bool
    ) -> list[ParseDiagnostic]:
        """The keys of *obj_data* that no release ever had as fields of *obj_type*, one diagnostic each.

        EnergyPlus ignores a key that is not a field, so a misspelt field's value is silently
        lost and the field takes its default. With *strict_parsing* those are returned, to be
        raised; without, each is logged and kept, as before. A field an earlier release had, and
        this one removed, is logged and kept either way: EnergyPlus's own example files carry
        some, and EnergyPlus runs them.
        """
        if pc is None:
            return []
        unknown = [key for key in obj_data if key not in pc.known_keys]
        if not unknown:
            return []
        candidates = (*pc.known_keys, *pc.ext_field_names)
        diagnostics: list[ParseDiagnostic] = []
        for key in unknown:
            if key in get_schema_manager().field_names_in_any_release(obj_type):
                logger.warning(
                    "Field '%s' of %s '%s' in %s is not in this release's schema; EnergyPlus ignores it",
                    key,
                    obj_type,
                    obj_name,
                    self._filepath,
                )
                continue
            message = f"Unknown field '{key}' for {obj_type}"
            suggestion = closest_name(key, candidates)
            if suggestion is not None:
                message += f". Did you mean '{suggestion}'?"
            if not strict_parsing:
                logger.warning("%s in %s [name: %s]; kept as is", message, self._filepath, obj_name)
                continue
            diagnostics.append(
                ParseDiagnostic(
                    message=message,
                    filepath=str(self._filepath),
                    obj_type=obj_type,
                    obj_name=obj_name,
                    code="InvalidField",
                )
            )
        return diagnostics

    def _unknown_type(
        self, obj_type: str, objects: dict[str, Any], schema: EpJSONSchema, *, strict_parsing: bool
    ) -> None:
        """Raise for an object type *schema* does not have, or, without *strict_parsing*, log it."""
        suggestion = closest_name(obj_type, schema.object_types)
        message = f"Unknown object type '{obj_type}'"
        if suggestion is not None:
            message += f". Did you mean '{suggestion}'?"
        if not strict_parsing:
            logger.warning("%s in %s; skipped %d object(s)", message, self._filepath, len(objects))
            return
        diagnostic = ParseDiagnostic(
            message=message,
            filepath=str(self._filepath),
            obj_type=obj_type,
            obj_name=next(iter(objects), None),
            code="UnknownObjectType",
        )
        summary = "Failed to parse epJSON"
        raise IDFParseError(summary, diagnostics=[diagnostic])

parse(version=None, *, strict=True, strict_parsing=True, preserve_formatting=False, normalize_choices=True)

Parse the epJSON file into an IDFDocument.

Parameters:

Name Type Description Default
version tuple[int, int, int] | None

Optional version override

None
strict bool

Enforce strict field access on the resulting document.

True
strict_parsing bool

Raise on an object type the schema does not have, rather than skip it.

True
preserve_formatting bool

Store raw JSON text for lossless round-tripping.

False
normalize_choices bool

Store each choice value in the spelling its schema declares.

True

Returns:

Type Description
IDFDocument

Parsed IDFDocument

Source code in idfkit/epjson_parser.py
def parse(
    self,
    version: tuple[int, int, int] | None = None,
    *,
    strict: bool = True,
    strict_parsing: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> IDFDocument:
    """
    Parse the epJSON file into an IDFDocument.

    Args:
        version: Optional version override
        strict: Enforce strict field access on the resulting document.
        strict_parsing: Raise on an object type the schema does not have, rather than skip it.
        preserve_formatting: Store raw JSON text for lossless round-tripping.
        normalize_choices: Store each choice value in the spelling its schema declares.

    Returns:
        Parsed IDFDocument
    """
    t0 = time.perf_counter()
    logger.debug("Parsing epJSON file %s", self._filepath)

    # Load JSON
    try:
        with open(self._filepath, encoding="utf-8") as f:
            raw_text = f.read()
        data: dict[str, Any] = json.loads(raw_text, parse_constant=_constant_refuser(self._filepath))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        # IDF text starts with a comment or an object type, never with '{'. An IDF file is often
        # latin-1 (save_idf's default) and so not UTF-8 at all: look at the bytes, not the text.
        with open(self._filepath, "rb") as f:
            head = f.read(4096)
        first = head.removeprefix(b"\xef\xbb\xbf").lstrip(b" \t\r\n")[:1]
        if first == b"!" or first.isalpha():
            raise FileFormatError(str(self._filepath), "idf") from exc
        raise

    # Detect version if not provided
    if version is None:
        version = self._detect_version(data)
        logger.debug("Detected version %d.%d.%d", *version)

    # Load schema if not provided
    schema = self._schema
    if schema is None:
        from .schema import get_schema

        schema = get_schema(version)

    # Create document
    doc = IDFDocument(
        version=version,
        schema=schema,
        filepath=self._filepath,
        strict=strict,
        normalize_choices=normalize_choices,
    )

    # Parse objects
    self._parse_objects(data, doc, schema, strict_parsing=strict_parsing, normalize_choices=normalize_choices)

    # Store raw text for lossless round-tripping (opt-in).
    if preserve_formatting:
        doc._raw_text = raw_text  # pyright: ignore[reportAttributeAccessIssue]
        # Mark all objects as "pristine" with a sentinel source_text so
        # that the writer can detect mutations.
        for obj in doc.all_objects:
            object.__setattr__(obj, "_source_text", "")
        # How many there were, so that a removal is visible to the writer.
        # The sentinel above only marks the objects that are still here, and
        # a removed one is not among them to ask.
        doc._count_at_read = len(doc)

    elapsed = time.perf_counter() - t0
    logger.info("Parsed %d objects from %s in %.3fs", len(doc), self._filepath, elapsed)

    return doc

get_epjson_version(filepath)

Quick version detection from epJSON file.

Parameters:

Name Type Description Default
filepath Path | str

Path to epJSON file

required

Returns:

Type Description
tuple[int, int, int]

Version tuple (major, minor, patch)

Raises:

Type Description
VersionNotFoundError

If version cannot be detected

Examples:

Detect the EnergyPlus version of an epJSON file:

```python
from idfkit.epjson_parser import get_epjson_version

version = get_epjson_version("SmallOffice.epJSON")
print(f"EnergyPlus v{version[0]}.{version[1]}")
```
Source code in idfkit/epjson_parser.py
def get_epjson_version(filepath: Path | str) -> tuple[int, int, int]:
    """
    Quick version detection from epJSON file.

    Args:
        filepath: Path to epJSON file

    Returns:
        Version tuple (major, minor, patch)

    Raises:
        VersionNotFoundError: If version cannot be detected

    Examples:
        Detect the EnergyPlus version of an epJSON file:

            ```python
            from idfkit.epjson_parser import get_epjson_version

            version = get_epjson_version("SmallOffice.epJSON")
            print(f"EnergyPlus v{version[0]}.{version[1]}")
            ```
    """
    filepath = Path(filepath)

    with open(filepath, encoding="utf-8") as f:
        # Parse just enough to get version
        data = json.load(f, parse_constant=_constant_refuser(filepath))

    version_obj = data.get("Version")
    if version_obj:
        for _name, fields in version_obj.items():
            version_str: str = fields.get("version_identifier", "")
            if version_str:
                parts = version_str.split(".")
                major = int(parts[0]) if len(parts) > 0 else 0
                minor = int(parts[1]) if len(parts) > 1 else 0
                patch = int(parts[2]) if len(parts) > 2 else 0
                return (major, minor, patch)

    raise VersionNotFoundError(str(filepath))

load_epjson(filepath)

Load raw epJSON data without parsing into document.

Useful for quick inspection or manipulation when you need the raw JSON dict rather than an IDFDocument.

Examples:

Grab the raw JSON dict for custom post-processing:

```python
from idfkit.epjson_parser import load_epjson

data = load_epjson("SmallOffice.epJSON")
zone_names = list(data.get("Zone", {}).keys())
```
Source code in idfkit/epjson_parser.py
def load_epjson(filepath: Path | str) -> dict[str, Any]:
    """
    Load raw epJSON data without parsing into document.

    Useful for quick inspection or manipulation when you need the
    raw JSON dict rather than an [IDFDocument][idfkit.document.IDFDocument].

    Examples:
        Grab the raw JSON dict for custom post-processing:

            ```python
            from idfkit.epjson_parser import load_epjson

            data = load_epjson("SmallOffice.epJSON")
            zone_names = list(data.get("Zone", {}).keys())
            ```
    """
    filepath = Path(filepath)
    with open(filepath, encoding="utf-8") as f:
        return json.load(f, parse_constant=_constant_refuser(filepath))

parse_epjson(filepath, schema=None, version=None, strict=True, *, strict_parsing=True, preserve_formatting=False, normalize_choices=True)

Parse an epJSON file into an IDFDocument.

Parameters:

Name Type Description Default
filepath Path | str

Path to the epJSON file

required
schema EpJSONSchema | None

Optional EpJSONSchema for validation

None
version tuple[int, int, int] | None

Optional version override (auto-detected if not provided)

None
strict bool

When True, accessing or setting an unknown field name on any IDFObject raises InvalidFieldError instead of returning None, and assigning a value the schema refuses raises ValidationFailedError, as add() does.

True
strict_parsing bool

When True (the default), an object type the schema does not have raises IDFParseError, as load_idf does, and the message suggests the closest type; EnergyPlus refuses such a file. False skips it with a logged warning.

True
preserve_formatting bool

If True, store the raw JSON text so that write_epjson and save_epjson can reproduce it byte-for-byte when no objects have been modified.

False
normalize_choices bool

When True (the default), each choice value is stored in the spelling its schema declares, whatever case the file used, as the field's Literal type says. False keeps the file's text.

True

Returns:

Type Description
IDFDocument

Parsed IDFDocument

Raises:

Type Description
VersionNotFoundError

If version cannot be detected

IDFParseError

For an object type the schema does not have, with strict_parsing

IdfKitError

If parsing fails

Examples:

Load an epJSON model and list its thermal zones:

```python
from idfkit import parse_epjson

model = parse_epjson("SmallOffice.epJSON")
for zone in model["Zone"]:
    print(zone.name)
```
Source code in idfkit/epjson_parser.py
def parse_epjson(
    filepath: Path | str,
    schema: EpJSONSchema | None = None,
    version: tuple[int, int, int] | None = None,
    strict: bool = True,
    *,
    strict_parsing: bool = True,
    preserve_formatting: bool = False,
    normalize_choices: bool = True,
) -> IDFDocument:
    """
    Parse an epJSON file into an IDFDocument.

    Args:
        filepath: Path to the epJSON file
        schema: Optional EpJSONSchema for validation
        version: Optional version override (auto-detected if not provided)
        strict: When ``True``, accessing or setting an unknown field name on any
            IDFObject raises [InvalidFieldError][idfkit.exceptions.InvalidFieldError] instead
            of returning ``None``, and assigning a value the schema refuses raises
            [ValidationFailedError][idfkit.exceptions.ValidationFailedError], as ``add()`` does.
        strict_parsing: When ``True`` (the default), an object type the schema does not
            have raises [IDFParseError][idfkit.exceptions.IDFParseError], as [load_idf][idfkit.load_idf]
            does, and the message suggests the closest type; EnergyPlus refuses such a file.
            ``False`` skips it with a logged warning.
        preserve_formatting: If ``True``, store the raw JSON text so that
            [write_epjson][idfkit.writers.write_epjson] and
            [save_epjson][idfkit.writers.save_epjson] can reproduce it
            byte-for-byte when no objects have been modified.
        normalize_choices: When ``True`` (the default), each choice value is stored in the
            spelling its schema declares, whatever case the file used, as the field's
            ``Literal`` type says. ``False`` keeps the file's text.

    Returns:
        Parsed IDFDocument

    Raises:
        VersionNotFoundError: If version cannot be detected
        IDFParseError: For an object type the schema does not have, with *strict_parsing*
        IdfKitError: If parsing fails

    Examples:
        Load an epJSON model and list its thermal zones:

            ```python
            from idfkit import parse_epjson

            model = parse_epjson("SmallOffice.epJSON")
            for zone in model["Zone"]:
                print(zone.name)
            ```
    """
    filepath = Path(filepath)

    if not filepath.exists():
        raise FileNotFoundError(f"epJSON file not found: {filepath}")  # noqa: TRY003

    parser = EpJSONParser(filepath, schema)
    return parser.parse(
        version,
        strict=strict,
        strict_parsing=strict_parsing,
        preserve_formatting=preserve_formatting,
        normalize_choices=normalize_choices,
    )

Writers

Writers for IDF and epJSON formats.

Provides serialization of IDFDocument to both formats. Each format has two entry points: write_* serializes to a string and never touches the disk, and save_* serializes and writes the result to a path.

The write_idf and save_idf functions accept an output_type parameter that mirrors eppy's idf.outputtype options:

  • "standard" (default): field comments included (!- Field Name).
  • "nocomment": no field comments, one field per line.
  • "compressed": entire object on a single line (minimal whitespace).

DEFAULT_COMMENT_COLUMN = 30 module-attribute

DEFAULT_INDENT = 2 module-attribute

FieldComments = Literal['preserve', 'generate'] module-attribute

Ordering = Literal['sorted', 'source'] module-attribute

OutputType = Literal['standard', 'nocomment', 'compressed'] module-attribute

logger = logging.getLogger(__name__) module-attribute

EpJSONWriter

Writes IDFDocument to epJSON format.

The epJSON format is:

{
  "Version": {
    "Version 1": {
      "version_identifier": "23.2"
    }
  },
  "Zone": {
    "Zone 1": {
      "direction_of_relative_north": 0.0,
      ...
    }
  }
}

Source code in idfkit/writers.py
class EpJSONWriter:
    """
    Writes IDFDocument to epJSON format.

    The epJSON format is:
    ```json
    {
      "Version": {
        "Version 1": {
          "version_identifier": "23.2"
        }
      },
      "Zone": {
        "Zone 1": {
          "direction_of_relative_north": 0.0,
          ...
        }
      }
    }
    ```
    """

    def __init__(self, doc: AnyIDFDocument):
        self._doc = doc
        self._group_needs_format: dict[str, bool] = {}

    def to_dict(self) -> dict[str, Any]:
        """Convert document to epJSON dict."""
        result: dict[str, Any] = {}

        # Add Version
        result["Version"] = {"Version 1": {"version_identifier": _resolve_version_identifier(self._doc)}}

        # Add objects by type
        for obj_type, collection in self._doc.collections.items():
            if obj_type.upper() == "VERSION":
                continue
            if not collection:
                continue

            result[obj_type] = {}
            # A blank Name is not an absent Name. Only a type that declares no Name field at all
            # gets the synthetic "<Type> N" key, numbered 1-based in file order. A type whose Name
            # field is optional and left blank keeps the blank verbatim, so its key is "". Keying a
            # blank Name as "<Type> N" manufactures a name into a namespace the writer does not own,
            # and any object the user genuinely named "<Type> N" is then silently overwritten.
            type_has_name = self._type_has_name(obj_type, collection.first())
            schema = self._doc.schema
            pc = schema.get_parsing_cache(obj_type) if schema is not None else None
            nameless_counter = 0
            for obj in collection:
                obj_data = self._object_to_dict(obj, pc)
                if type_has_name:
                    key = obj.name
                else:
                    # Generate unique key for nameless objects (e.g. Output:Variable)
                    nameless_counter += 1
                    key = f"{obj_type} {nameless_counter}"
                result[obj_type][key] = obj_data

        return result

    def _type_has_name(self, obj_type: str, sample: IDFObject | None) -> bool:
        """Whether *obj_type* declares a Name field.

        Answered from the document schema when one is loaded, otherwise from the schema dict carried
        by the objects themselves. With no schema information at all the answer is ``True``, which
        matches what the IDF parser assumes when it has no parsing cache for a type: the first field
        is the name.
        """
        schema = self._doc.schema
        if schema is not None:
            return schema.has_name(obj_type)
        if sample is not None and sample.schema_dict is not None:
            return "name" in sample.schema_dict
        return True

    def _object_to_dict(self, obj: IDFObject, pc: ParsingCache | None) -> dict[str, Any]:
        """Convert object to epJSON dict (excluding name).

        Drops blank values, writes each choice in the spelling its schema declares and each sizing
        sentinel as the one its field declares (idfkit#180, idfkit#181). A document read or built
        with ``normalize_choices=True``, the default, already holds that spelling; this also covers
        one that opted out, since only the epJSON reader is strict about it. The IDF writer writes
        what the document holds, which EnergyPlus reads in any case, as in idfkit-js#60.
        """
        wrapper_key = pc.ext_wrapper_key if pc is not None else None
        choice_spellings: Mapping[str, ChoiceSpellings] = pc.choice_spellings if pc is not None else {}
        field_types: Mapping[str, str | None] = pc.field_types if pc is not None else {}

        result: dict[str, Any] = {}
        for field_name, value in obj.data.items():
            if value is None or value == "":
                continue
            if isinstance(value, str):
                result[field_name] = self._format_value(value, choice_spellings.get(field_name))
            elif isinstance(value, float):
                integral = value.is_integer() and field_types.get(field_name) == "integer"
                result[field_name] = int(value) if integral else value
            elif field_name == wrapper_key and isinstance(value, list):
                groups = cast("list[Any]", value)
                result[field_name] = (
                    [self._format_group(g, pc) for g in groups]
                    if self._groups_need_format(obj.obj_type, pc)
                    else groups
                )
            else:
                result[field_name] = value
        return result

    def _groups_need_format(self, obj_type: str, pc: ParsingCache | None) -> bool:
        """Whether any group field of *obj_type* can need formatting: a choice, an integer or a string.

        Groups hold no blank slot (idfkit#182), so a type whose group fields are all plain numbers,
        such as ``Matrix:TwoDimension`` with tens of thousands of groups, is emitted as stored.
        """
        needed = self._group_needs_format.get(obj_type)
        if needed is None:
            needed = (
                pc is None
                or bool(pc.ext_choice_spellings)
                or any(pc.field_types.get(name) != "number" for name in pc.ext_field_names)
            )
            self._group_needs_format[obj_type] = needed
        return needed

    def _format_group(self, group: Any, pc: ParsingCache | None) -> Any:
        """Format one extensible group, omitting its blank slots (idfkit#182).

        A group set wholesale, as ``doc.add(..., equipment=[...])`` or through ``obj.data``, can still
        hold a blank, which EnergyPlus's epJSON reader refuses.
        """
        if not isinstance(group, dict):
            return group
        return {
            name: self._format_value(
                value,
                pc.ext_choice_spellings.get(name) if pc is not None else None,
                pc.field_types.get(name) if pc is not None else None,
            )
            for name, value in cast("dict[str, Any]", group).items()
            if not is_blank_slot(value)
        }

    def _format_value(self, value: Any, spellings: ChoiceSpellings | None = None, field_type: str | None = None) -> Any:
        """Format a field value for epJSON output.

        A float holding a whole number in an ``integer`` field is written as an integer, whatever
        produced it, since EnergyPlus's epJSON reader refuses ``1.0`` there (idfkit#179).
        """
        # epJSON uses native JSON types
        if isinstance(value, str):
            folded = value.casefold()
            if spellings and folded in spellings:
                return spellings[folded]
            return _FALLBACK_SPELLINGS.get(folded, value)
        if field_type == "integer" and isinstance(value, float) and value.is_integer():
            return int(value)
        return value

    def to_json(self, indent: int | str | None = 2) -> str:
        """The document as epJSON text.

        Raises:
            ValueError: A field holds NaN or infinity, which JSON cannot express (``json`` would
                write ``NaN``, which EnergyPlus's epJSON reader refuses). The message names the
                object and field.
        """
        data = self.to_dict()
        try:
            return json.dumps(data, indent=indent, allow_nan=False)
        except ValueError:
            # Found only on failure, so a clean document pays nothing for the search.
            for obj in self._doc.all_objects:
                for field_name, value in non_finite_fields(obj.data):
                    raise ValueError(non_finite_message(_where(obj), field_name, value)) from None
            raise

    def write_to_file(self, filepath: Path | str, indent: int | str | None = 2) -> None:
        """Write to file."""
        text = self.to_json(indent)
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(text)

to_dict()

Convert document to epJSON dict.

Source code in idfkit/writers.py
def to_dict(self) -> dict[str, Any]:
    """Convert document to epJSON dict."""
    result: dict[str, Any] = {}

    # Add Version
    result["Version"] = {"Version 1": {"version_identifier": _resolve_version_identifier(self._doc)}}

    # Add objects by type
    for obj_type, collection in self._doc.collections.items():
        if obj_type.upper() == "VERSION":
            continue
        if not collection:
            continue

        result[obj_type] = {}
        # A blank Name is not an absent Name. Only a type that declares no Name field at all
        # gets the synthetic "<Type> N" key, numbered 1-based in file order. A type whose Name
        # field is optional and left blank keeps the blank verbatim, so its key is "". Keying a
        # blank Name as "<Type> N" manufactures a name into a namespace the writer does not own,
        # and any object the user genuinely named "<Type> N" is then silently overwritten.
        type_has_name = self._type_has_name(obj_type, collection.first())
        schema = self._doc.schema
        pc = schema.get_parsing_cache(obj_type) if schema is not None else None
        nameless_counter = 0
        for obj in collection:
            obj_data = self._object_to_dict(obj, pc)
            if type_has_name:
                key = obj.name
            else:
                # Generate unique key for nameless objects (e.g. Output:Variable)
                nameless_counter += 1
                key = f"{obj_type} {nameless_counter}"
            result[obj_type][key] = obj_data

    return result

to_json(indent=2)

The document as epJSON text.

Raises:

Type Description
ValueError

A field holds NaN or infinity, which JSON cannot express (json would write NaN, which EnergyPlus's epJSON reader refuses). The message names the object and field.

Source code in idfkit/writers.py
def to_json(self, indent: int | str | None = 2) -> str:
    """The document as epJSON text.

    Raises:
        ValueError: A field holds NaN or infinity, which JSON cannot express (``json`` would
            write ``NaN``, which EnergyPlus's epJSON reader refuses). The message names the
            object and field.
    """
    data = self.to_dict()
    try:
        return json.dumps(data, indent=indent, allow_nan=False)
    except ValueError:
        # Found only on failure, so a clean document pays nothing for the search.
        for obj in self._doc.all_objects:
            for field_name, value in non_finite_fields(obj.data):
                raise ValueError(non_finite_message(_where(obj), field_name, value)) from None
        raise

write_to_file(filepath, indent=2)

Write to file.

Source code in idfkit/writers.py
def write_to_file(self, filepath: Path | str, indent: int | str | None = 2) -> None:
    """Write to file."""
    text = self.to_json(indent)
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(text)

FieldAnnotation dataclass

What the author wrote around one field.

before are comment lines standing on their own above the field, in order, exactly as written. They live INSIDE the object, so unlike a comment between two objects they are not carried by the text around it and are lost the moment the object is reformatted unless they are emitted with the field below them.

trailing is the comment after the field's delimiter on the same line, or None when the author left the field bare. Bare is a thing the author wrote, and telling it apart from "this field had no author" is the whole reason this carries None rather than a label.

Source code in idfkit/writers.py
@dataclass(frozen=True, slots=True)
class FieldAnnotation:
    """What the author wrote around one field.

    ``before`` are comment lines standing on their own above the field, in order, exactly as
    written. They live INSIDE the object, so unlike a comment between two objects they are not
    carried by the text around it and are lost the moment the object is reformatted unless they are
    emitted with the field below them.

    ``trailing`` is the comment after the field's delimiter on the same line, or ``None`` when the
    author left the field bare. Bare is a thing the author wrote, and telling it apart from "this
    field had no author" is the whole reason this carries ``None`` rather than a label.
    """

    before: tuple[str, ...]
    trailing: str | None
    starts_line: bool = True
    """Whether the author began a new line with this field.

    False for the second and third coordinate of a vertex written ``0,0,4.572,`` on one line.
    Writing one value per line regardless turns a four-line surface into twelve, which is the most
    visible thing a reformat does to a geometry file: 21.5 percent of the statements in the 693
    EnergyPlus example files group values this way, and 690 of those files contain at least one.
    """

before instance-attribute

starts_line = True class-attribute instance-attribute

Whether the author began a new line with this field.

False for the second and third coordinate of a vertex written 0,0,4.572, on one line. Writing one value per line regardless turns a four-line surface into twelve, which is the most visible thing a reformat does to a geometry file: 21.5 percent of the statements in the 693 EnergyPlus example files group values this way, and 690 of those files contain at least one.

trailing instance-attribute

IDFWriter

Writes IDFDocument to IDF text format.

The IDF format is:

ObjectType,
  field1,    !- Field 1 Name
  field2,    !- Field 2 Name
  field3;    !- Field 3 Name

Supports three output_type modes mirroring eppy's idf.outputtype:

  • "standard" — full comments (default).
  • "nocomment" — no field comments, one field per line.
  • "compressed" — each object on a single line.
Source code in idfkit/writers.py
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
class IDFWriter:
    """
    Writes IDFDocument to IDF text format.

    The IDF format is:
    ```
    ObjectType,
      field1,    !- Field 1 Name
      field2,    !- Field 2 Name
      field3;    !- Field 3 Name
    ```

    Supports three *output_type* modes mirroring eppy's
    ``idf.outputtype``:

    - ``"standard"`` — full comments (default).
    - ``"nocomment"`` — no field comments, one field per line.
    - ``"compressed"`` — each object on a single line.
    """

    def __init__(
        self,
        doc: AnyIDFDocument,
        output_type: OutputType = "standard",
        *,
        indent: int = DEFAULT_INDENT,
        comment_column: int = DEFAULT_COMMENT_COLUMN,
        ordering: Ordering = "sorted",
        version_first: bool = True,
        field_comments: FieldComments = "preserve",
    ):
        self._doc = doc
        self._field_comments = field_comments
        self._output_type = output_type
        self._indent = indent
        self._comment_column = comment_column
        self._ordering = ordering
        self._version_first = version_first

    def _header_lines(self) -> list[str]:
        """The generator header, or nothing in compressed output.

        The `!-Option` directive states the order the file is actually in. IDFEditor reads it, so
        writing `SortedOrder` over source-ordered objects would announce an order the file does not
        have. `sorted` is the default, so the default header does not move.
        """
        if self._output_type == "compressed":
            return []

        from . import __version__

        directive = "SortedOrder" if self._ordering == "sorted" else "OriginalOrderTop"
        return [f"!-Generator idfkit v{__version__}", f"!-Option {directive}", ""]

    def _version_lines(self) -> list[str]:
        """The Version object, written by hand rather than through the field loop."""
        version_identifier = _resolve_version_identifier(self._doc)
        pad = " " * self._indent

        if self._output_type == "compressed":
            return [f"Version,{version_identifier};"]
        if self._output_type == "standard":
            # A fixed twenty-space GAP, not a column, which is the one line in a formatted file whose
            # `!-` does not align with the rest. The distinction is not pedantic: the gap puts the
            # marker at 26 after `9.0`, 27 after `26.1` and 28 after `9.0.1`, so it drifts with the
            # length of the version string while every other line holds `comment_column`.
            #
            # Kept as a literal anyway, and deliberately. Aligning it would move the first line of
            # every file this writer has ever produced, and this path is the FORMATTING one: a
            # preserving write never reaches here, so the seam it leaves is in output nobody is
            # comparing against a source. Only the indent moves when the caller moves it.
            return ["Version,", f"{pad}{version_identifier};                    !- Version Identifier", ""]
        return ["Version,", f"{pad}{version_identifier};", ""]

    def to_string(self) -> str:
        """Convert document to IDF string."""
        lines: list[str] = self._header_lines()

        def write_version() -> None:
            lines.extend(self._version_lines())

        # Version ahead of everything else, which is what this writer has always done and what
        # `version_first` defaults to, so the default does not move (FR-017). Turning it off leaves
        # Version in whichever position the chosen ordering puts it, which is what a caller wants
        # when the output is going to be diffed against a source file that did not lead with it.
        if self._version_first:
            write_version()

        # Write objects grouped by type.
        #
        # `sorted` is this writer's default and does not move. `source` keeps the document's own
        # collection order, which is what the other language does and what a caller wants when the
        # output is going to be diffed against an input rather than against another writer.
        type_order = (
            sorted(self._doc.collections.keys()) if self._ordering == "sorted" else list(self._doc.collections.keys())
        )
        for obj_type in type_order:
            if obj_type.upper() == "VERSION":
                if not self._version_first:
                    write_version()
                continue
            collection = self._doc.collections[obj_type]
            if not collection:
                continue

            for obj in collection:
                obj_str = self.format_object(obj)
                lines.append(obj_str)
                if self._output_type != "compressed":
                    lines.append("")

        return "\n".join(lines)

    def _comment_for(self, annotation: FieldAnnotation | None, label: str) -> str:
        """The comment to write beside one field, or the empty string for none.

        The author's where there is one. Where the author left the field bare, nothing, unless the
        caller asked for a label: absence is as much a thing the author wrote as the words are.
        Where there is no author at all, because the object gained this field, the label as always.
        """
        if annotation is None:
            # A field with no label at all, the blank written into a GroundHeatTransfer face object,
            # gets no comment rather than a bare ``!- `` and its trailing space.
            return f"!- {label}" if label else ""
        if annotation.trailing is not None:
            return annotation.trailing
        return f"!- {label}" if self._field_comments == "generate" else ""

    def _get_field_values_and_comments(  # noqa: C901
        self, obj: IDFObject, keep_at_least: int = 0
    ) -> tuple[list[str], list[str]]:
        """Get the ordered field values and comment labels for *obj*.

        Storage is canonical: extensible groups live as a list of dicts under
        the wrapper key (e.g. ``obj.data["vertices"]``). For IDF output we
        flatten them into the legacy positional sequence with comment labels
        synthesised on the fly (``Vertex X Coordinate 2`` for the second
        ``vertex_x_coordinate`` token, etc.).
        """
        obj_type = obj.obj_type
        schema = self._doc.schema

        # Everything about the type is read from its parsing cache, which resolves the type name the way
        # the document does. ``schema.has_name`` and ``schema.get_all_field_names`` look the raw
        # spelling up exactly, so an object filed as ``Timestep`` but spelled ``TIMESTEP`` lost its
        # name and every field, and came out with nothing in it.
        pc = schema.get_parsing_cache(obj_type) if schema else None
        obj_has_name = pc.has_name if pc else True

        if obj.field_order:
            if obj_has_name:
                field_names: list[str] = ["name", *list(obj.field_order)]
            else:
                field_names = list(obj.field_order)
        elif pc:
            field_names = list(pc.all_field_names)
        else:
            field_names = ["name", *list(obj.data.keys())] if obj_has_name else list(obj.data.keys())

        values: list[str] = []
        comments: list[str] = []
        wrapper_key = pc.ext_wrapper_key if pc and pc.extensible else None

        for field_name in field_names:
            if field_name == "name":
                values.append(_idf_text(obj, "name", obj.name or ""))
                comments.append("Name")
            elif field_name == wrapper_key:
                # Skip — handled below as positional extensible expansion.
                continue
            else:
                value = obj.data.get(field_name)
                _check_finite(obj, field_name, value)
                text = self._format_value(value)
                # A list is joined with commas on purpose; only a single value must not hold one.
                values.append(text if isinstance(value, list) else _idf_text(obj, field_name, text))
                comments.append(_field_label(field_name))

        # Pad an HVACTemplate object's fixed fields to the schema's ``min_fields`` with blanks, as
        # IDF Editor does. EnergyPlus fills a short object with defaults, but ExpandObjects reads the
        # IDF text and stops with a fatal "number of fields in the IDD do not match" when a template
        # is shorter, so a template built in code never expanded. Padding stops the trimming below
        # too, on the preserving path as on the plain one: a short template fails either way.
        min_fields = _min_fixed_fields(obj_type, pc)
        while len(values) < min_fields:
            values.append("")
            comments.append(_field_label(pc.all_field_names[len(comments)]) if pc else "")

        # Append extensible groups as positional tokens (legacy IDF layout).
        if wrapper_key and pc and pc.ext_field_names:
            inner_names = pc.ext_field_names
            ext_items_raw: Any = obj.data.get(wrapper_key) or []
            if isinstance(ext_items_raw, list):
                ext_items: list[dict[str, Any]] = cast("list[dict[str, Any]]", ext_items_raw)
                for group_idx, item in enumerate(ext_items, start=1):
                    suffix = "" if group_idx == 1 else f" {group_idx}"
                    for inner in inner_names:
                        slot = item.get(inner)
                        _check_finite(obj, inner, slot)
                        values.append(_idf_text(obj, inner, self._format_value(slot)))
                        if inner.endswith("_1"):
                            # A key the schema numbered after the IDD's first group (``x_value_1``,
                            # from ``X Value #1``): the group's number replaces it, or every group
                            # after the first would read ``X Value 1 2``.
                            comments.append(f"{_field_label(inner[:-2])} {group_idx}")
                        else:
                            comments.append(f"{_field_label(inner)}{suffix}")

        # Trim trailing empty fields, but never below what the author actually wrote.
        #
        # A field written out as a blank is as much a thing the author wrote as a field left bare of
        # its comment, and dropping it takes the author's own ``!- Cooling Design Capacity Method``
        # with it. A single-field edit shortened one Sizing:System from 38 lines to 22; across the
        # 693 example files it is 20,571 lines, more than any other difference a rewrite makes.
        #
        # *keep_at_least* is non-zero only on the preserving path. A write with no author behind it
        # trims as it always has, because there is nothing there to be faithful to.
        #
        # Counted in VALUES, name included, because an annotation is produced for the name too. The
        # TypeScript core states the same rule in a different index space, as an index into the
        # fixed fields with the name subtracted out. Both are right against their own annotations
        # and neither would notice if the other's convention moved, so a change to either belongs
        # in both.
        while len(values) > max(1, keep_at_least, min_fields) and values[-1] == "":
            values.pop()
            comments.pop()

        # An object with nothing to write still needs one value to carry its terminator. Only a
        # nameless type with no fixed fields gets here, when it holds no groups: Output:Diagnostics,
        # Output:Table:SummaryReports, OutdoorAir:NodeList, EnergyManagementSystem:GlobalVariable and
        # the GroundHeatTransfer face types. Without this the object came out as a bare
        # ``Output:Diagnostics,`` that swallowed the object after it.
        #
        # IDF has no spelling EnergyPlus reads as such an object with nothing in it. ``Type;`` is not
        # one: EnergyPlus reads on into the next object exactly as it does with no terminator, and
        # idfkit's parser skips it. ``Type,;`` keeps the next object intact, but EnergyPlus reads it
        # as one BLANK GROUP. That is a warning for Output:Diagnostics and a Severe for
        # Output:Table:SummaryReports, and EnergyPlus refuses the input for OutdoorAir:NodeList and
        # EnergyManagementSystem:GlobalVariable, whose group has a required field. Only epJSON can
        # carry these objects empty. An empty one does nothing in EnergyPlus, so the writer keeps
        # what the document holds and validate_document reports it (W004).
        if not values:
            values.append("")
            comments.append(_field_label(pc.ext_field_names[0]) if pc and pc.ext_field_names else "")

        return values, comments

    def format_object(self, obj: IDFObject, source_text: str | None = None) -> str:
        """Convert a single object to IDF string.

        *source_text* is the object as it was read, supplied by the preserving writer for an object
        that has been changed. Its per-field comments are reused in place of generated ones: an edit
        asks for the VALUES to be re-rendered and never for the comments, and rebuilding them
        destroys whatever the schema cannot regenerate. That is the field's unit, which the
        generated label does not carry, and any note the author wrote there.
        """
        annotations = _annotations(source_text) if source_text is not None else []
        values, comments = self._get_field_values_and_comments(obj, keep_at_least=len(annotations))
        obj_type = obj.obj_type

        if self._output_type == "compressed":
            parts = ",".join(values)
            return f"{obj_type},{parts};"

        lines: list[str] = []
        pad = " " * self._indent

        # A line under construction, so fields the author wrote together stay together. Flushed
        # when the next field opens a line of its own, and once at the end.
        #
        # It starts as the TYPE NAME rather than the type name going straight out, so that an object
        # the author wrote entirely on one line, ``Timestep,4;``, comes back on one line. That is
        # 11.3 percent of the statements in the example files, and it is the case that surprises on
        # a file with no geometry in it.
        open_line = f"{obj_type},"
        open_comment = ""

        def flush() -> None:
            nonlocal open_line, open_comment
            if not open_line:
                return
            if open_comment:
                # Minus one because the option is a COLUMN, counted from 1, while ljust takes a
                # WIDTH. Passing the column as the width put every comment one place right of where
                # the files this imitates put it. The max keeps a space after a long line.
                width = max(self._comment_column - 1, len(open_line) + 1)
                lines.append(open_line.ljust(width) + open_comment)
            else:
                lines.append(open_line)
            open_line = ""
            open_comment = ""

        if self._output_type != "standard":
            # nocomment: one value per line, as this writer has always emitted it, and none of the
            # annotations apply. Hoisted out of the field loop rather than tested per field, which
            # also retires the subtlety that used to carry it: the type name is the line still open
            # when the loop starts, so this path depended on the first `flush()` emitting it and on
            # every later one being a no-op. That dependence cost a regression once already.
            last = len(values) - 1
            body = (f"{pad}{v}{';' if i == last else ','}" for i, v in enumerate(values))
            return "\n".join([open_line, *body])

        for i, (value, comment) in enumerate(zip(values, comments, strict=False)):
            is_last = i == len(values) - 1
            terminator = ";" if is_last else ","
            annotation = annotations[i] if i < len(annotations) else None

            # No annotation means no author to be faithful to, so one value per line. Field 0 is
            # the one that decides whether the object opens on the type name's own line.
            opens_line = annotation is None or annotation.starts_line
            if opens_line:
                flush()
                # The author's own lines above the field, which live inside the object and are
                # carried by nothing else.
                if annotation is not None:
                    lines.extend(f"{pad}{line}" for line in annotation.before)
                open_line = f"{pad}{value}{terminator}"
            else:
                open_line = f"{open_line} {value}{terminator}"

            # On a line carrying several values only the last of them has a comment, which is what
            # the author wrote and what the delimiter rule recovers.
            chosen = self._comment_for(annotation, comment)
            if chosen:
                open_comment = chosen

        flush()

        return "\n".join(lines)

    def _format_value(self, value: Any) -> str:
        """Format a field value for IDF output."""
        if value is None:
            return ""
        if isinstance(value, bool):
            return "Yes" if value else "No"
        if isinstance(value, float):
            if value == 0.0:
                return "0"
            abs_val = abs(value)
            text = f"{value:.6e}" if abs_val >= 1e10 or abs_val < 0.0001 else f"{value:g}"
            # The short form keeps six significant digits; a value it would round is written in full.
            return text if float(text) == value else repr(value)
        if isinstance(value, list):
            # Handle vertex lists etc.
            items = cast(list[Any], value)
            return ", ".join(str(v) for v in items)
        return str(value)

    def write_to_file(self, filepath: Path | str, encoding: str | None = None) -> None:
        """Write to file.

        Args:
            filepath: Output path.
            encoding: Output encoding. ``None`` (the default) writes the encoding the document's
                IDF file was read in, without a byte-order mark, and latin-1 for a document not
                read from an IDF file.
        """
        content = _with_newline(self.to_string(), source_newline(self._doc) or os.linesep)
        if encoding is None:
            encoding = source_encoding(self._doc, bom=False)
        with open(filepath, "w", encoding=encoding, newline="") as f:
            f.write(content)

format_object(obj, source_text=None)

Convert a single object to IDF string.

source_text is the object as it was read, supplied by the preserving writer for an object that has been changed. Its per-field comments are reused in place of generated ones: an edit asks for the VALUES to be re-rendered and never for the comments, and rebuilding them destroys whatever the schema cannot regenerate. That is the field's unit, which the generated label does not carry, and any note the author wrote there.

Source code in idfkit/writers.py
def format_object(self, obj: IDFObject, source_text: str | None = None) -> str:
    """Convert a single object to IDF string.

    *source_text* is the object as it was read, supplied by the preserving writer for an object
    that has been changed. Its per-field comments are reused in place of generated ones: an edit
    asks for the VALUES to be re-rendered and never for the comments, and rebuilding them
    destroys whatever the schema cannot regenerate. That is the field's unit, which the
    generated label does not carry, and any note the author wrote there.
    """
    annotations = _annotations(source_text) if source_text is not None else []
    values, comments = self._get_field_values_and_comments(obj, keep_at_least=len(annotations))
    obj_type = obj.obj_type

    if self._output_type == "compressed":
        parts = ",".join(values)
        return f"{obj_type},{parts};"

    lines: list[str] = []
    pad = " " * self._indent

    # A line under construction, so fields the author wrote together stay together. Flushed
    # when the next field opens a line of its own, and once at the end.
    #
    # It starts as the TYPE NAME rather than the type name going straight out, so that an object
    # the author wrote entirely on one line, ``Timestep,4;``, comes back on one line. That is
    # 11.3 percent of the statements in the example files, and it is the case that surprises on
    # a file with no geometry in it.
    open_line = f"{obj_type},"
    open_comment = ""

    def flush() -> None:
        nonlocal open_line, open_comment
        if not open_line:
            return
        if open_comment:
            # Minus one because the option is a COLUMN, counted from 1, while ljust takes a
            # WIDTH. Passing the column as the width put every comment one place right of where
            # the files this imitates put it. The max keeps a space after a long line.
            width = max(self._comment_column - 1, len(open_line) + 1)
            lines.append(open_line.ljust(width) + open_comment)
        else:
            lines.append(open_line)
        open_line = ""
        open_comment = ""

    if self._output_type != "standard":
        # nocomment: one value per line, as this writer has always emitted it, and none of the
        # annotations apply. Hoisted out of the field loop rather than tested per field, which
        # also retires the subtlety that used to carry it: the type name is the line still open
        # when the loop starts, so this path depended on the first `flush()` emitting it and on
        # every later one being a no-op. That dependence cost a regression once already.
        last = len(values) - 1
        body = (f"{pad}{v}{';' if i == last else ','}" for i, v in enumerate(values))
        return "\n".join([open_line, *body])

    for i, (value, comment) in enumerate(zip(values, comments, strict=False)):
        is_last = i == len(values) - 1
        terminator = ";" if is_last else ","
        annotation = annotations[i] if i < len(annotations) else None

        # No annotation means no author to be faithful to, so one value per line. Field 0 is
        # the one that decides whether the object opens on the type name's own line.
        opens_line = annotation is None or annotation.starts_line
        if opens_line:
            flush()
            # The author's own lines above the field, which live inside the object and are
            # carried by nothing else.
            if annotation is not None:
                lines.extend(f"{pad}{line}" for line in annotation.before)
            open_line = f"{pad}{value}{terminator}"
        else:
            open_line = f"{open_line} {value}{terminator}"

        # On a line carrying several values only the last of them has a comment, which is what
        # the author wrote and what the delimiter rule recovers.
        chosen = self._comment_for(annotation, comment)
        if chosen:
            open_comment = chosen

    flush()

    return "\n".join(lines)

to_string()

Convert document to IDF string.

Source code in idfkit/writers.py
def to_string(self) -> str:
    """Convert document to IDF string."""
    lines: list[str] = self._header_lines()

    def write_version() -> None:
        lines.extend(self._version_lines())

    # Version ahead of everything else, which is what this writer has always done and what
    # `version_first` defaults to, so the default does not move (FR-017). Turning it off leaves
    # Version in whichever position the chosen ordering puts it, which is what a caller wants
    # when the output is going to be diffed against a source file that did not lead with it.
    if self._version_first:
        write_version()

    # Write objects grouped by type.
    #
    # `sorted` is this writer's default and does not move. `source` keeps the document's own
    # collection order, which is what the other language does and what a caller wants when the
    # output is going to be diffed against an input rather than against another writer.
    type_order = (
        sorted(self._doc.collections.keys()) if self._ordering == "sorted" else list(self._doc.collections.keys())
    )
    for obj_type in type_order:
        if obj_type.upper() == "VERSION":
            if not self._version_first:
                write_version()
            continue
        collection = self._doc.collections[obj_type]
        if not collection:
            continue

        for obj in collection:
            obj_str = self.format_object(obj)
            lines.append(obj_str)
            if self._output_type != "compressed":
                lines.append("")

    return "\n".join(lines)

write_to_file(filepath, encoding=None)

Write to file.

Parameters:

Name Type Description Default
filepath Path | str

Output path.

required
encoding str | None

Output encoding. None (the default) writes the encoding the document's IDF file was read in, without a byte-order mark, and latin-1 for a document not read from an IDF file.

None
Source code in idfkit/writers.py
def write_to_file(self, filepath: Path | str, encoding: str | None = None) -> None:
    """Write to file.

    Args:
        filepath: Output path.
        encoding: Output encoding. ``None`` (the default) writes the encoding the document's
            IDF file was read in, without a byte-order mark, and latin-1 for a document not
            read from an IDF file.
    """
    content = _with_newline(self.to_string(), source_newline(self._doc) or os.linesep)
    if encoding is None:
        encoding = source_encoding(self._doc, bom=False)
    with open(filepath, "w", encoding=encoding, newline="") as f:
        f.write(content)

convert_epjson_to_idf(epjson_path, idf_path=None)

Convert an epJSON file to IDF format.

Parameters:

Name Type Description Default
epjson_path Path | str

Input epJSON file path

required
idf_path Path | str | None

Output IDF path (default: same name with .idf extension)

None

Returns:

Type Description
Path

Path to the output file

Examples:

Convert an epJSON model back to classic IDF format:

```python
output = convert_epjson_to_idf("5ZoneAirCooled.epJSON")
# Creates 5ZoneAirCooled.idf

convert_epjson_to_idf("modern_model.epJSON", "classic_model.idf")
```
Source code in idfkit/writers.py
def convert_epjson_to_idf(
    epjson_path: Path | str,
    idf_path: Path | str | None = None,
) -> Path:
    """
    Convert an epJSON file to IDF format.

    Args:
        epjson_path: Input epJSON file path
        idf_path: Output IDF path (default: same name with .idf extension)

    Returns:
        Path to the output file

    Examples:
        Convert an epJSON model back to classic IDF format:

            ```python
            output = convert_epjson_to_idf("5ZoneAirCooled.epJSON")
            # Creates 5ZoneAirCooled.idf

            convert_epjson_to_idf("modern_model.epJSON", "classic_model.idf")
            ```
    """
    from .epjson_parser import parse_epjson

    epjson_path = Path(epjson_path)

    idf_path = epjson_path.with_suffix(".idf") if idf_path is None else Path(idf_path)

    doc = parse_epjson(epjson_path)
    save_idf(doc, idf_path)

    return idf_path

convert_idf_to_epjson(idf_path, epjson_path=None)

Convert an IDF file to epJSON format.

Parameters:

Name Type Description Default
idf_path Path | str

Input IDF file path

required
epjson_path Path | str | None

Output epJSON path (default: same name with .epJSON extension)

None

Returns:

Type Description
Path

Path to the output file

Examples:

Convert an IDF model to native JSON format:

```python
output = convert_idf_to_epjson("5ZoneAirCooled.idf")
# Creates 5ZoneAirCooled.epJSON

convert_idf_to_epjson("legacy_model.idf", "modern_model.epJSON")
```
Source code in idfkit/writers.py
def convert_idf_to_epjson(
    idf_path: Path | str,
    epjson_path: Path | str | None = None,
) -> Path:
    """
    Convert an IDF file to epJSON format.

    Args:
        idf_path: Input IDF file path
        epjson_path: Output epJSON path (default: same name with .epJSON extension)

    Returns:
        Path to the output file

    Examples:
        Convert an IDF model to native JSON format:

            ```python
            output = convert_idf_to_epjson("5ZoneAirCooled.idf")
            # Creates 5ZoneAirCooled.epJSON

            convert_idf_to_epjson("legacy_model.idf", "modern_model.epJSON")
            ```
    """
    from .idf_parser import parse_idf

    idf_path = Path(idf_path)

    epjson_path = idf_path.with_suffix(".epJSON") if epjson_path is None else Path(epjson_path)

    doc = parse_idf(idf_path)
    save_epjson(doc, epjson_path)

    return epjson_path

render_cst_node(doc, node, *, field_comments='preserve')

One anchored node's object, rendered the way a preserving write renders it.

The node's own text goes with it: the formatter reuses that object's field comments rather than generating new ones, which is the whole reason a rewritten object keeps the author's units and notes.

Shared with IDFDocument.render_object so a consumer splicing one object into the range it came from gets the bytes a whole write would have put there. Two constructions of the formatter would be two answers to that question, and field_comments already had to be threaded through this path by hand once.

No trailing separator: what ran between this object and the next is the caller's to keep.

Source code in idfkit/writers.py
def render_cst_node(
    doc: AnyIDFDocument[bool],
    node: CSTNode,
    *,
    field_comments: FieldComments = "preserve",
) -> str:
    """One anchored node's object, rendered the way a preserving write renders it.

    The node's own text goes with it: the formatter reuses that object's field comments rather than
    generating new ones, which is the whole reason a rewritten object keeps the author's units and
    notes.

    Shared with [IDFDocument.render_object][idfkit.document.IDFDocument.render_object] so a consumer splicing one object
    into the range it came from gets the bytes a whole write would have put there. Two constructions of the
    formatter would be two answers to that question, and `field_comments` already had to be threaded
    through this path by hand once.

    No trailing separator: what ran between this object and the next is the caller's to keep.
    """
    if node.obj is None:
        return node.text
    formatter = IDFWriter(doc, output_type="standard", field_comments=field_comments)
    return _with_newline(formatter.format_object(node.obj, node.text), source_newline(doc) or "\n")

save_epjson(doc, path, indent=2, *, preserve_formatting=None)

Serialize a document to epJSON text and write it to path.

The disk-writing counterpart of write_epjson.

Parameters:

Name Type Description Default
doc AnyIDFDocument[bool]

The document to save.

required
path Path | str

Output path.

required
indent int | str | None

JSON indentation, as for write_epjson.

2
preserve_formatting bool | None

Lossless output control, as for write_epjson.

None

Raises:

Type Description
TypeError

If doc is not a document, as when the arguments are swapped, or indent is not an indent.

ValueError

If path ends in .idf or .imf, which EnergyPlus reads as IDF: use save_idf for those.

Examples:

Write to disk:

```python
save_epjson(model, "in.epJSON")
```
Source code in idfkit/writers.py
def save_epjson(
    doc: AnyIDFDocument[bool],
    path: Path | str,
    indent: int | str | None = 2,
    *,
    preserve_formatting: bool | None = None,
) -> None:
    """
    Serialize a document to epJSON text and write it to *path*.

    The disk-writing counterpart of
    [write_epjson][idfkit.writers.write_epjson].

    Args:
        doc: The document to save.
        path: Output path.
        indent: JSON indentation, as for [write_epjson][idfkit.writers.write_epjson].
        preserve_formatting: Lossless output control, as for
            [write_epjson][idfkit.writers.write_epjson].

    Raises:
        TypeError: If *doc* is not a document, as when the arguments are swapped, or
            *indent* is not an indent.
        ValueError: If *path* ends in ``.idf`` or ``.imf``, which EnergyPlus reads as IDF:
            use [save_idf][idfkit.writers.save_idf] for those.

    Examples:
        Write to disk:

            ```python
            save_epjson(model, "in.epJSON")
            ```
    """
    _check_document(doc, "save_epjson")
    _check_indent(indent, "save_epjson", "save_epjson")
    path = Path(path)
    _check_save_path(path, "save_epjson", _IDF_SUFFIXES, "save_idf")
    content = write_epjson(doc, indent, preserve_formatting=preserve_formatting)
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)
    logger.info("Wrote epJSON (%d objects) to %s", len(doc), path)

save_idf(doc, path, encoding=None, output_type='standard', *, preserve_formatting=None, indent=DEFAULT_INDENT, comment_column=DEFAULT_COMMENT_COLUMN, ordering='sorted', version_first=True, newline=None)

Serialize a document to IDF text and write it to *path*.

The disk-writing counterpart of [write_idf][idfkit.writers.write_idf].

Args:
    doc: The document to save.
    path: Output path.
    encoding: Output encoding. ``None`` (the default) writes the encoding the document's IDF
        file was read in (UTF-8 or latin-1), and latin-1 for a document not read from an IDF
        file. A byte-order mark the file had is written back only by a lossless rewrite.
    output_type: Output formatting mode, as for
        [write_idf][idfkit.writers.write_idf].
    preserve_formatting: Lossless output control, as for
        [write_idf][idfkit.writers.write_idf].
    indent: Field-line indent, as for
        [write_idf][idfkit.writers.write_idf].
    comment_column: Comment column, as for
        [write_idf][idfkit.writers.write_idf].
    ordering: Object ordering, as for
        [write_idf][idfkit.writers.write_idf].
    version_first: Version placement, as for
        [write_idf][idfkit.writers.write_idf].
    newline: Line ending, ``"

"or" ".None`` (the default) writes the line ending of the IDF file the document was read from, so a Windows file stays CRLF, and the platform's own for a document not read from an IDF file.

Warns:
    FormattingLossWarning: *path* is the IDF file the document was read from, it has ``!``
        comments, and the document was loaded without ``preserve_formatting=True``: the
        write drops them and re-sorts the objects. Not warned when *preserve_formatting* is
        given, which says the caller chose.

Raises:
    TypeError: If *doc* is not a document, as when the arguments are swapped.
    ValueError: If *path* ends in ``.epJSON`` or ``.json``, which EnergyPlus reads as epJSON:
        use [save_epjson][idfkit.writers.save_epjson] for those.

Examples:
    Write to disk for EnergyPlus simulation:

        ```python
        save_idf(model, "in.idf")
        ```

    Lossless round-trip:

        ```python
        from idfkit import load_idf, save_idf
        model = load_idf("building.idf", preserve_formatting=True)
        save_idf(model, "building_copy.idf")  # byte-identical
        ```
Source code in idfkit/writers.py
def save_idf(
    doc: AnyIDFDocument[bool],
    path: Path | str,
    encoding: str | None = None,
    output_type: OutputType = "standard",
    *,
    preserve_formatting: bool | None = None,
    indent: int = DEFAULT_INDENT,
    comment_column: int = DEFAULT_COMMENT_COLUMN,
    ordering: Ordering = "sorted",
    version_first: bool = True,
    newline: Literal["\n", "\r\n"] | None = None,
) -> None:
    """
    Serialize a document to IDF text and write it to *path*.

    The disk-writing counterpart of [write_idf][idfkit.writers.write_idf].

    Args:
        doc: The document to save.
        path: Output path.
        encoding: Output encoding. ``None`` (the default) writes the encoding the document's IDF
            file was read in (UTF-8 or latin-1), and latin-1 for a document not read from an IDF
            file. A byte-order mark the file had is written back only by a lossless rewrite.
        output_type: Output formatting mode, as for
            [write_idf][idfkit.writers.write_idf].
        preserve_formatting: Lossless output control, as for
            [write_idf][idfkit.writers.write_idf].
        indent: Field-line indent, as for
            [write_idf][idfkit.writers.write_idf].
        comment_column: Comment column, as for
            [write_idf][idfkit.writers.write_idf].
        ordering: Object ordering, as for
            [write_idf][idfkit.writers.write_idf].
        version_first: Version placement, as for
            [write_idf][idfkit.writers.write_idf].
        newline: Line ending, ``"\n"`` or ``"\r\n"``. ``None`` (the default) writes the line
            ending of the IDF file the document was read from, so a Windows file stays CRLF, and the
            platform's own for a document not read from an IDF file.

    Warns:
        FormattingLossWarning: *path* is the IDF file the document was read from, it has ``!``
            comments, and the document was loaded without ``preserve_formatting=True``: the
            write drops them and re-sorts the objects. Not warned when *preserve_formatting* is
            given, which says the caller chose.

    Raises:
        TypeError: If *doc* is not a document, as when the arguments are swapped.
        ValueError: If *path* ends in ``.epJSON`` or ``.json``, which EnergyPlus reads as epJSON:
            use [save_epjson][idfkit.writers.save_epjson] for those.

    Examples:
        Write to disk for EnergyPlus simulation:

            ```python
            save_idf(model, "in.idf")
            ```

        Lossless round-trip:

            ```python
            from idfkit import load_idf, save_idf
            model = load_idf("building.idf", preserve_formatting=True)
            save_idf(model, "building_copy.idf")  # byte-identical
            ```
    """
    _check_document(doc, "save_idf")
    _check_output_type(output_type, "save_idf", "save_idf")
    path = Path(path)
    _check_save_path(path, "save_idf", _EPJSON_SUFFIXES, "save_epjson")
    if newline not in (None, "\n", "\r\n"):
        msg = f"newline must be '\\n', '\\r\\n' or None, not {newline!r}"
        raise ValueError(msg)
    content = write_idf(
        doc,
        output_type,
        preserve_formatting=preserve_formatting,
        indent=indent,
        comment_column=comment_column,
        ordering=ordering,
        version_first=version_first,
    )
    lossless = _writes_lossless(
        doc,
        output_type,
        preserve_formatting,
        formatting_requested=_formatting_requested(indent, comment_column, ordering, version_first),
    )
    # A document holding its source text (preserve_formatting=True) and written in another layout
    # was reformatted on request (output_type or a layout control), so only a document loaded
    # without its source text warns.
    if not lossless and preserve_formatting is None and doc.cst is None:
        _warn_on_overwriting_comments(doc, path)
    if encoding is None:
        # A byte-order mark the source had is part of its text, so only a lossless rewrite keeps it.
        encoding = source_encoding(doc, bom=lossless)
    # A lossless rewrite is already in the source's line endings, and is written exactly as it is.
    if newline is not None or not lossless:
        content = _with_newline(content.replace("\r\n", "\n"), newline or source_newline(doc) or os.linesep)
    # newline="" writes the text as it is: Python's own translation would turn a CRLF into CR CR LF.
    with open(path, "w", encoding=encoding, newline="") as f:
        f.write(content)
    logger.info("Wrote IDF (%d objects) to %s", len(doc), path)

write_epjson(doc, indent=2, *, preserve_formatting=None)

Serialize a document to epJSON text.

Returns the text; it never touches the disk. Use save_epjson to put the text on disk.

Parameters:

Name Type Description Default
doc AnyIDFDocument[bool]

The document to serialize.

required
indent int | str | None

JSON indentation, as json.dumps takes it: a number of spaces, a whitespace string such as "\t", or None for compact output.

2
preserve_formatting bool | None

If True, return the original JSON text verbatim when no objects have been modified. When None (the default), automatically uses lossless output if raw text is available and no objects were mutated.

None

Returns:

Type Description
str

The epJSON text.

Raises:

Type Description
TypeError

If doc is not a document, or indent is not an indent, as when a path is passed where save_epjson takes one.

ValueError

A number is NaN or infinity, which JSON cannot express; the message names the object and field.

Examples:

Serialize the model to epJSON for use with EnergyPlus v9.3+:

>>> from idfkit import new_document, write_epjson
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> json_str = write_epjson(model)
>>> '"Zone"' in json_str
True
Source code in idfkit/writers.py
def write_epjson(
    doc: AnyIDFDocument[bool],
    indent: int | str | None = 2,
    *,
    preserve_formatting: bool | None = None,
) -> str:
    """
    Serialize a document to epJSON text.

    Returns the text; it never touches the disk. Use
    [save_epjson][idfkit.writers.save_epjson] to put the text on disk.

    Args:
        doc: The document to serialize.
        indent: JSON indentation, as ``json.dumps`` takes it: a number of spaces, a
            whitespace string such as ``"\\t"``, or ``None`` for compact output.
        preserve_formatting: If ``True``, return the original JSON text
            verbatim when no objects have been modified. When ``None``
            (the default), automatically uses lossless output if raw text
            is available and no objects were mutated.

    Returns:
        The epJSON text.

    Raises:
        TypeError: If *doc* is not a document, or *indent* is not an indent, as when
            a path is passed where [save_epjson][idfkit.writers.save_epjson] takes one.
        ValueError: A number is NaN or infinity, which JSON cannot express; the
            message names the object and field.

    Examples:
        Serialize the model to epJSON for use with EnergyPlus v9.3+:

        >>> from idfkit import new_document, write_epjson
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> json_str = write_epjson(model)
        >>> '"Zone"' in json_str
        True
    """
    _check_document(doc, "write_epjson")
    _check_indent(indent, "write_epjson", "save_epjson")
    # Note: epJSON preservation is all-or-nothing (any mutation or addition
    # falls back to the standard JSON writer), unlike IDF which has per-object
    # granularity via CST nodes.
    use_preserve = preserve_formatting if preserve_formatting is not None else doc.raw_text is not None

    # If preserve_formatting and we have raw text, check whether the document is
    # still the one that text describes: nothing touched, nothing added, nothing
    # removed.
    #
    # The count is the half that asking the survivors cannot supply. Every object
    # left after a removal is still pristine, so `all_clean` alone reproduced the
    # original text with the removed object still in it: a file that loads and
    # misrepresents the model. An addition is caught by the same comparison from
    # the other side, since a new object carries no sentinel and fails
    # `all_clean` anyway.
    if use_preserve and doc.raw_text is not None:
        count_at_read = doc._count_at_read
        unchanged = count_at_read == len(doc) and all(obj.source_text is not None for obj in doc.all_objects)
        if unchanged:
            logger.debug("Serialized epJSON (%d objects, lossless) to string", len(doc))
            return doc.raw_text

    # Fall back to standard writer.
    writer = EpJSONWriter(doc)
    text = writer.to_json(indent)

    logger.debug("Serialized epJSON (%d objects) to string", len(doc))
    return text

write_idf(doc, output_type='standard', *, preserve_formatting=None, indent=DEFAULT_INDENT, comment_column=DEFAULT_COMMENT_COLUMN, ordering='sorted', version_first=True, field_comments='preserve')

Serialize a document to IDF text.

Returns the text; it never touches the disk. Use save_idf to put the text on disk.

Parameters:

Name Type Description Default
doc AnyIDFDocument[bool]

The document to serialize.

required
output_type OutputType

Output formatting mode, "standard" (with comments), "nocomment" (no comments), or "compressed" (single-line objects). Mirrors eppy's idf.outputtype. An output type other than "standard" takes precedence over preserve_formatting, including over an explicit True: a different output form is a different artifact, which the original text was never going to express.

'standard'
preserve_formatting bool | None

If True, reproduce the original source text for unmodified objects and apply standard formatting only to objects that were mutated or added after parsing. Requires the document to have been parsed with preserve_formatting=True. When None (the default), automatically uses lossless output if a CST is available and output_type is "standard".

Cheapest where it is used: a write that reproduces most of the file copies text rather than building it. It CROSSES OVER once most objects have changed, because this path renders each of them AND walks the tiling, which is more work than formatting alone. On a 13 MB model with every object edited it is roughly four times slower than a formatting write. Nothing to guard against, since an edit touches a handful of objects and a whole model rewrite is what preserve_formatting=False is for, but worth knowing before timing the wrong one.

None
indent int

Spaces before each field line. Defaults to the two this writer has always used.

DEFAULT_INDENT
comment_column int

Column the !- field comments are aligned to, counting from 1 as an editor does. The default puts the marker where EnergyPlus itself puts it, which is what keeps a rewritten object flush with the untouched objects around it. Defaults to 30. A value longer than the column pushes its comment right rather than being truncated.

DEFAULT_COMMENT_COLUMN
ordering Ordering

"sorted" to write object types in alphabetical order, which is the default and what the !-Option SortedOrder header declares, or "source" to keep the document's own collection order, which writes !-Option OriginalOrderTop instead. An enumeration rather than a boolean because three orderings exist across the two libraries and two formats.

'sorted'

Returns:

Type Description
str

The IDF text.

Raises:

Type Description
TypeError

If doc is not a document, or output_type is a path object.

ValueError

If output_type is not one of the three forms, as when a path is passed where save_idf takes one.

ValueError

If preserve_formatting is explicitly True on a document that carries a CST while indent, comment_column, ordering or version_first is away from its default. Reproducing the original text and reformatting it are contradictory requests. Also when a name or value holds ,, ; or !, or a number is NaN or infinity, none of which IDF can express; the message names the object and field.

Examples:

Serialize the model to an IDF string for inspection:

>>> from idfkit import new_document, write_idf
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> idf_str = write_idf(model)
>>> "Zone," in idf_str
True

Use compressed format for batch parametric runs:

>>> compressed = write_idf(model, output_type="compressed")
>>> "\n" not in compressed.split("Zone")[1].split(";")[0]
True
Source code in idfkit/writers.py
def write_idf(
    doc: AnyIDFDocument[bool],
    output_type: OutputType = "standard",
    *,
    preserve_formatting: bool | None = None,
    indent: int = DEFAULT_INDENT,
    comment_column: int = DEFAULT_COMMENT_COLUMN,
    ordering: Ordering = "sorted",
    version_first: bool = True,
    field_comments: FieldComments = "preserve",
) -> str:
    """
    Serialize a document to IDF text.

    Returns the text; it never touches the disk. Use
    [save_idf][idfkit.writers.save_idf] to put the text on disk.

    Args:
        doc: The document to serialize.
        output_type: Output formatting mode, ``"standard"`` (with
            comments), ``"nocomment"`` (no comments), or
            ``"compressed"`` (single-line objects). Mirrors eppy's
            ``idf.outputtype``. An output type other than ``"standard"``
            takes precedence over *preserve_formatting*, including over an
            explicit ``True``: a different output form is a different
            artifact, which the original text was never going to express.
        preserve_formatting: If ``True``, reproduce the original source
            text for unmodified objects and apply standard formatting only
            to objects that were mutated or added after parsing. Requires
            the document to have been parsed with
            ``preserve_formatting=True``. When ``None`` (the default),
            automatically uses lossless output if a CST is available and
            *output_type* is ``"standard"``.

            Cheapest where it is used: a write that reproduces most of the
            file copies text rather than building it. It CROSSES OVER once
            most objects have changed, because this path renders each of
            them AND walks the tiling, which is more work than formatting
            alone. On a 13 MB model with every object edited it is roughly
            four times slower than a formatting write. Nothing to guard
            against, since an edit touches a handful of objects and a whole
            model rewrite is what ``preserve_formatting=False`` is for, but
            worth knowing before timing the wrong one.
        indent: Spaces before each field line. Defaults to the two this
            writer has always used.
        comment_column: Column the ``!-`` field comments are aligned to, counting
            from 1 as an editor does. The default puts the marker where EnergyPlus
            itself puts it, which is what keeps a rewritten object flush with the
            untouched objects around it.
            Defaults to 30. A value longer than the column pushes its
            comment right rather than being truncated.
        ordering: ``"sorted"`` to write object types in alphabetical order,
            which is the default and what the ``!-Option SortedOrder``
            header declares, or ``"source"`` to keep the document's own
            collection order, which writes ``!-Option OriginalOrderTop``
            instead. An enumeration rather than a boolean because three
            orderings exist across the two libraries and two formats.

    Returns:
        The IDF text.

    Raises:
        TypeError: If *doc* is not a document, or *output_type* is a path object.
        ValueError: If *output_type* is not one of the three forms, as when a path is
            passed where [save_idf][idfkit.writers.save_idf] takes one.
        ValueError: If *preserve_formatting* is explicitly ``True`` on a
            document that carries a CST while *indent*, *comment_column*,
            *ordering* or *version_first* is away from its default.
            Reproducing the original text and reformatting it are
            contradictory requests. Also when a name or value holds ``,``,
            ``;`` or ``!``, or a number is NaN or infinity, none of which
            IDF can express; the message names the object and field.

    Examples:
        Serialize the model to an IDF string for inspection:

        >>> from idfkit import new_document, write_idf
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> idf_str = write_idf(model)
        >>> "Zone," in idf_str
        True

        Use compressed format for batch parametric runs:

        >>> compressed = write_idf(model, output_type="compressed")
        >>> "\\n" not in compressed.split("Zone")[1].split(";")[0]
        True
    """
    _check_document(doc, "write_idf")
    _check_output_type(output_type, "write_idf", "save_idf")
    # An explicitly requested output FORM wins over preservation, including over an explicit
    # `preserve_formatting=True`. A form is a different artifact, which the original text was never
    # going to express, so producing it is honest; granting preservation instead drops the request
    # in silence, which is what this did until the other language's decision table was written down
    # beside it and the two were compared.
    if output_type != "standard":
        use_preserve = False
    elif preserve_formatting is not None:
        use_preserve = preserve_formatting
    else:
        use_preserve = doc.cst is not None

    # A control that is not at its default asks for output the original text does not have, so the
    # lossless path cannot honour it. Reproducing the file byte for byte and indenting to three
    # spaces are contradictory requests, and silently doing the first would be the wrong answer.
    #
    # `version_first` belongs in this set and was missing from it, so asking to move the version
    # statement while preserving was granted silently: the file came back with the statement where
    # the author left it and no word about the request. It is a reformatting control like the other
    # three, because moving a statement is a change to how the text is laid out.
    #
    # Away from its default is a REQUEST TO FORMAT on the default path too, which is what the
    # `not formatting_requested` clause below says: a caller who names a control and does not name
    # preservation gets the control, not a silent drop of it.
    #
    # The conflict is only real when the lossless path would actually be taken. `preserve_formatting=True`
    # on a document that carries no CST has always fallen back to this writer, and asking for a control at
    # the same time must not turn that quiet fallback into an error.
    formatting_requested = _formatting_requested(indent, comment_column, ordering, version_first)
    if formatting_requested and use_preserve and preserve_formatting and doc.cst is not None:
        msg = (
            "preserve_formatting reproduces the original text, so it cannot also apply indent, "
            "comment_column, ordering or version_first. Pass one or the other."
        )
        raise ValueError(msg)

    if _writes_lossless(doc, output_type, preserve_formatting, formatting_requested=formatting_requested):
        content = _write_idf_lossless(doc, field_comments)
    else:
        writer = IDFWriter(
            doc,
            output_type=output_type,
            indent=indent,
            comment_column=comment_column,
            ordering=ordering,
            version_first=version_first,
        )
        content = writer.to_string()

    logger.debug("Serialized IDF (%d objects) to string", len(doc))
    return content