Skip to content

Validation

validate_document() checks a document against the epJSON schema: required fields, value types, numeric ranges, enum choices, and reference integrity. It also checks what EnergyPlus would stop on that the schema does not say: compact schedules it cannot read, schedule values outside their limits, window constructions, upside-down floors and roofs, and objects with no entries.

Code Severity Reported for
E001 error A required field, or the name, is missing
E002 error A value matches none of the field's accepted types
E003 error A value of the wrong type, or NaN or infinity
E004 error A choice the field does not list
E005, E006 error A number below the minimum, or not above an exclusive one
E007, E008 error A number above the maximum, or not below an exclusive one
E009 error A reference to a name that does not exist, or that belongs to the wrong type
E010 error More than one instance of a singleton type
E011 error A compact schedule EnergyPlus cannot read
E012 error A schedule value outside the limits of its ScheduleTypeLimits
E013 error A window or glass door whose construction has only opaque layers
W001 warning No schema available, so schema validation was skipped
W002 warning An object type the schema does not have
W003 warning A field the object type does not have
W004 warning An object such as OutdoorAir:NodeList that holds only extensible entries and has none
W005 warning A floor that faces up, or a roof or ceiling that faces down
W006 warning A reference to a missing ScheduleTypeLimits, which EnergyPlus only warns about

Each issue carries the object it was found on in ValidationError.obj, which is how to tell apart issues on objects of a type with no Name field.

On-demand validation system for IDF documents.

Provides validation against EpJSON schema without requiring eager validation during parsing.

logger = logging.getLogger(__name__) module-attribute

Severity

Bases: Enum

Validation issue severity levels.

Source code in idfkit/validation.py
class Severity(Enum):
    """Validation issue severity levels."""

    ERROR = "error"
    WARNING = "warning"
    INFO = "info"

ERROR = 'error' class-attribute instance-attribute

INFO = 'info' class-attribute instance-attribute

WARNING = 'warning' class-attribute instance-attribute

ValidationError dataclass

Represents a validation issue.

Attributes:

Name Type Description
severity Severity

Issue severity (ERROR, WARNING, INFO)

obj_type str

Object type where issue was found

obj_name str

Object name where issue was found

field str | None

Field name where issue was found (if applicable)

message str

Human-readable description

code str

Machine-readable error code

obj IDFObject | None

The object the issue was found on, or None for a document-level issue. Types without a Name field (HVACTemplate:Zone:*, Output:Variable, ...) have an empty obj_name; use obj to find, highlight or fix the object itself. It is a plain attribute, not a dataclass field: dataclasses.asdict/astuple, equality and pickling leave it out (pickling or deep-copying an error drops it), so serializing errors never copies the owning document.

Source code in idfkit/validation.py
@dataclass(init=False)
class ValidationError:
    """
    Represents a validation issue.

    Attributes:
        severity: Issue severity (ERROR, WARNING, INFO)
        obj_type: Object type where issue was found
        obj_name: Object name where issue was found
        field: Field name where issue was found (if applicable)
        message: Human-readable description
        code: Machine-readable error code
        obj: The object the issue was found on, or ``None`` for a document-level
            issue. Types without a Name field (``HVACTemplate:Zone:*``,
            ``Output:Variable``, ...) have an empty ``obj_name``; use ``obj`` to
            find, highlight or fix the object itself. It is a plain attribute,
            not a dataclass field: ``dataclasses.asdict``/``astuple``, equality
            and pickling leave it out (pickling or deep-copying an error drops
            it), so serializing errors never copies the owning document.
    """

    severity: Severity
    obj_type: str
    obj_name: str
    field: str | None
    message: str
    code: str

    def __init__(
        self,
        severity: Severity,
        obj_type: str,
        obj_name: str,
        field: str | None,
        message: str,
        code: str,
        obj: IDFObject | None = None,
    ) -> None:
        self.severity = severity
        self.obj_type = obj_type
        self.obj_name = obj_name
        self.field = field
        self.message = message
        self.code = code
        # Not a dataclass field, so asdict()/astuple()/eq/repr/pickle leave it out (see docstring).
        self.obj: IDFObject | None = obj

    def __getstate__(self) -> dict[str, Any]:
        state = dict(self.__dict__)
        state["obj"] = None
        return state

    def __copy__(self) -> ValidationError:
        return ValidationError(
            self.severity, self.obj_type, self.obj_name, self.field, self.message, self.code, obj=self.obj
        )

    def __str__(self) -> str:
        if not self.obj_name and self.obj is not None:
            # A nameless object reads as its repr, which names it by its first set fields.
            location = repr(self.obj)
        else:
            location = f"{self.obj_type}:'{self.obj_name}'"
        if self.field:
            location += f".{self.field}"
        return f"[{self.severity.value.upper()}] {location}: {self.message}"

code = code instance-attribute

field = field instance-attribute

message = message instance-attribute

obj = obj instance-attribute

obj_name = obj_name instance-attribute

obj_type = obj_type instance-attribute

severity = severity instance-attribute

ValidationResult dataclass

Result of document validation.

Attributes:

Name Type Description
errors list[ValidationError]

List of validation errors

warnings list[ValidationError]

List of validation warnings

info list[ValidationError]

List of informational messages

Source code in idfkit/validation.py
@dataclass
class ValidationResult:
    """
    Result of document validation.

    Attributes:
        errors: List of validation errors
        warnings: List of validation warnings
        info: List of informational messages
    """

    errors: list[ValidationError]
    warnings: list[ValidationError]
    info: list[ValidationError]

    @property
    def is_valid(self) -> bool:
        """True if there are no errors."""
        return len(self.errors) == 0

    @property
    def total_issues(self) -> int:
        """Total number of issues found."""
        return len(self.errors) + len(self.warnings) + len(self.info)

    def __str__(self) -> str:
        lines = [f"Validation: {len(self.errors)} errors, {len(self.warnings)} warnings"]
        for err in self.errors[:10]:
            lines.append(f"  {err}")
        if len(self.errors) > 10:
            lines.append(f"  ... and {len(self.errors) - 10} more errors")
        return "\n".join(lines)

    def __bool__(self) -> bool:
        return self.is_valid

errors instance-attribute

info instance-attribute

is_valid property

True if there are no errors.

total_issues property

Total number of issues found.

warnings instance-attribute

field_value_error(obj, field_name, value, schema)

The finding value would raise as obj's field_name, or None when the schema accepts it.

The type, choice and range checks add() applies to each value, for one value about to be assigned. A blank value clears the field and is not checked, nor is a field the schema does not know: whether a name is a field is the caller's question (strict mode, or update()).

Source code in idfkit/validation.py
def field_value_error(obj: IDFObject, field_name: str, value: Any, schema: EpJSONSchema) -> ValidationError | None:
    """The finding *value* would raise as *obj*'s *field_name*, or None when the schema accepts it.

    The type, choice and range checks ``add()`` applies to each value, for one value about to be
    assigned. A blank value clears the field and is not checked, nor is a field the schema does not
    know: whether a name is a field is the caller's question (strict mode, or ``update()``).
    """
    rules = _object_rules(schema, obj.obj_type)
    if rules is None or is_blank_slot(value):
        return None
    rule = rules.fields.get(field_name)
    if rule is None:
        return None
    if type(value) in rule.accepts_outright:
        return None
    if type(value) is str and value.lower() in rule.accepts_folded:
        return None
    return rule.first_error(obj, field_name, value)

name_error(obj, value, schema)

The finding renaming obj to value would raise, or None when the schema accepts the name.

A blank or whitespace name on a type whose schema requires one is refused, as add() refuses it.

Source code in idfkit/validation.py
def name_error(obj: IDFObject, value: str, schema: EpJSONSchema) -> ValidationError | None:
    """The finding renaming *obj* to *value* would raise, or None when the schema accepts the name.

    A blank or whitespace name on a type whose schema requires one is refused, as ``add()`` refuses it.
    """
    if value.strip():
        return None
    rules = _object_rules(schema, obj.obj_type)
    if rules is None or not rules.name_required:
        return None
    return _missing_name_error(obj)

validate_document(doc, schema=None, check_references=True, check_required=True, check_types=True, check_ranges=True, check_singletons=True, object_types=None, check_geometry=True)

Validate an IDF document against schema.

Parameters:

Name Type Description Default
doc AnyIDFDocument

The document to validate

required
schema EpJSONSchema | None

Schema to validate against (uses doc's schema if not provided)

None
check_references bool

Check reference integrity (E009; a missing ScheduleTypeLimits, which EnergyPlus only warns about, is W006), and that each window or glass door names a window construction rather than an opaque one (E013)

True
check_required bool

Check required fields, and report a group-only object such as OutdoorAir:NodeList that has no entries (W004)

True
check_types bool

Check field types

True
check_ranges bool

Check numeric ranges

True
check_singletons bool

Check singleton (maxProperties) constraints

True
object_types list[str] | None

Only validate these types (None = all)

None
check_geometry bool

Warn about a floor whose vertices make it face up, or a roof or ceiling that faces down (W005): the surface is upside down, as a clockwise footprint extruded into an inside-out zone is, and EnergyPlus runs it with only a warning and a wrong zone volume

True

Returns:

Type Description
ValidationResult

ValidationResult with all issues found

Examples:

Validate a model before running a simulation:

>>> from idfkit import new_document, validate_document
>>> model = new_document()
>>> model.add("Zone", "Perimeter_ZN_1")
Zone('Perimeter_ZN_1')
>>> result = validate_document(model)
>>> result.is_valid
True
>>> result.total_issues
0

Validate only material and construction definitions:

>>> result = validate_document(model, object_types=["Material", "Construction"])
>>> result.is_valid
True
Source code in idfkit/validation.py
def validate_document(  # noqa: C901
    doc: AnyIDFDocument,
    schema: EpJSONSchema | None = None,
    check_references: bool = True,
    check_required: bool = True,
    check_types: bool = True,
    check_ranges: bool = True,
    check_singletons: bool = True,
    object_types: list[str] | None = None,
    check_geometry: bool = True,
) -> ValidationResult:
    """
    Validate an IDF document against schema.

    Args:
        doc: The document to validate
        schema: Schema to validate against (uses doc's schema if not provided)
        check_references: Check reference integrity (``E009``; a missing ``ScheduleTypeLimits``,
            which EnergyPlus only warns about, is ``W006``), and that each window or glass door
            names a window construction rather than an opaque one (``E013``)
        check_required: Check required fields, and report a group-only object such as
            ``OutdoorAir:NodeList`` that has no entries (``W004``)
        check_types: Check field types
        check_ranges: Check numeric ranges
        check_singletons: Check singleton (maxProperties) constraints
        object_types: Only validate these types (None = all)
        check_geometry: Warn about a floor whose vertices make it face up, or a roof or
            ceiling that faces down (``W005``): the surface is upside down, as a clockwise
            footprint extruded into an inside-out zone is, and EnergyPlus runs it with
            only a warning and a wrong zone volume

    Returns:
        ValidationResult with all issues found

    Examples:
        Validate a model before running a simulation:

        >>> from idfkit import new_document, validate_document
        >>> model = new_document()
        >>> model.add("Zone", "Perimeter_ZN_1")  # doctest: +ELLIPSIS
        Zone('Perimeter_ZN_1')
        >>> result = validate_document(model)
        >>> result.is_valid
        True
        >>> result.total_issues
        0

        Validate only material and construction definitions:

        >>> result = validate_document(model, object_types=["Material", "Construction"])
        >>> result.is_valid
        True
    """
    schema = schema or doc.schema

    errors: list[ValidationError] = []
    warnings: list[ValidationError] = []
    info: list[ValidationError] = []

    if schema is None:
        warnings.append(
            ValidationError(
                severity=Severity.WARNING,
                obj_type="Document",
                obj_name="",
                field=None,
                message="No schema available - skipping schema validation",
                code="W001",
            )
        )
        return ValidationResult(errors, warnings, info)

    # Determine which object types to validate
    types_to_check = object_types or list(doc.collections.keys())
    logger.debug("Validating %d object type(s)", len(types_to_check))

    # Check singleton (maxProperties) constraints
    if check_singletons:
        for obj_type in types_to_check:
            if obj_type not in doc.collections:
                continue
            obj_schema = schema.get_object_schema(obj_type)
            if obj_schema and obj_schema.get("maxProperties") == 1:
                coll = doc.get_collection(obj_type)
                count = len(coll)
                if count > 1:
                    first = coll.first()
                    obj_name = first.name if first and first.name else obj_type
                    errors.append(
                        ValidationError(
                            severity=Severity.ERROR,
                            obj_type=obj_type,
                            obj_name=obj_name,
                            obj=first,
                            field=None,
                            message=f"Singleton type '{obj_type}' has {count} instances (maximum 1 allowed)",
                            code="E010",
                        )
                    )

    for obj_type in types_to_check:
        if obj_type not in doc.collections:
            continue

        # W004 is checked here and not in `_validate_object`: `add()` refuses any finding that
        # function makes, and an empty group-only object is a normal step in building one up. Only
        # the finished model is wrong to hold it. Whether the type is group-only is read once.
        group_only = _group_only_type(schema, obj_type) if check_required else None

        for obj in doc.get_collection(obj_type):
            obj_errors = _validate_object(
                obj,
                schema,
                check_required=check_required,
                check_types=check_types,
                check_ranges=check_ranges,
            )
            if group_only is not None:
                empty = _empty_group_only_object(obj, group_only)
                if empty is not None:
                    obj_errors.append(empty)

            for err in obj_errors:
                if err.severity == Severity.ERROR:
                    errors.append(err)
                elif err.severity == Severity.WARNING:
                    warnings.append(err)
                else:
                    info.append(err)

    if check_geometry:
        warnings.extend(_validate_surface_orientation(doc, types_to_check))

    # Schedules EnergyPlus refuses as fatal although every field is valid on its own
    for err in _validate_schedules(doc, types_to_check, check_ranges=check_ranges):
        errors.append(err)

    # Check reference integrity
    if check_references:
        errors.extend(_validate_window_constructions(doc, types_to_check))
        ref_errors = _validate_references(doc, schema)
        for err in ref_errors:
            if err.severity == Severity.ERROR:
                errors.append(err)
            elif err.severity == Severity.WARNING:
                warnings.append(err)

    result = ValidationResult(errors, warnings, info)
    logger.info(
        "Validation complete: %d error(s), %d warning(s), %d info",
        len(errors),
        len(warnings),
        len(info),
    )
    return result

validate_object(obj, schema, *, check_required=True, check_types=True, check_ranges=True, check_unknown=True)

Validate a single object against schema.

This is a public API for validating individual objects, useful for checking objects at creation time with the validate=True option.

Parameters:

Name Type Description Default
obj IDFObject

The IDFObject to validate

required
schema EpJSONSchema

The EpJSON schema to validate against

required
check_required bool

Check that required fields are present

True
check_types bool

Check that field values match expected types

True
check_ranges bool

Check that numeric values are within bounds

True
check_unknown bool

Check for unknown fields (not in schema)

True

Returns:

Type Description
list[ValidationError]

List of ValidationError objects describing any issues found

Examples:

Check a newly created zone for schema violations:

>>> from idfkit import new_document, validate_object, get_schema, LATEST_VERSION
>>> model = new_document()
>>> zone = model.add("Zone", "Perimeter_ZN_1")
>>> errors = validate_object(zone, get_schema(LATEST_VERSION))
>>> len(errors)
0
Source code in idfkit/validation.py
def validate_object(
    obj: IDFObject,
    schema: EpJSONSchema,
    *,
    check_required: bool = True,
    check_types: bool = True,
    check_ranges: bool = True,
    check_unknown: bool = True,
) -> list[ValidationError]:
    """
    Validate a single object against schema.

    This is a public API for validating individual objects, useful for
    checking objects at creation time with the validate=True option.

    Args:
        obj: The IDFObject to validate
        schema: The EpJSON schema to validate against
        check_required: Check that required fields are present
        check_types: Check that field values match expected types
        check_ranges: Check that numeric values are within bounds
        check_unknown: Check for unknown fields (not in schema)

    Returns:
        List of ValidationError objects describing any issues found

    Examples:
        Check a newly created zone for schema violations:

        >>> from idfkit import new_document, validate_object, get_schema, LATEST_VERSION
        >>> model = new_document()
        >>> zone = model.add("Zone", "Perimeter_ZN_1")
        >>> errors = validate_object(zone, get_schema(LATEST_VERSION))
        >>> len(errors)
        0
    """
    return _validate_object(
        obj,
        schema,
        check_required=check_required,
        check_types=check_types,
        check_ranges=check_ranges,
        check_unknown=check_unknown,
    )