Skip to content

Migration API

Forward-migrate IDF models across EnergyPlus versions by orchestrating the Transition-VX-to-VY binaries shipped in PreProcess/IDFVersionUpdater.

migrate

idfkit.migration.runner.migrate(model, target_version, *, energyplus=None, migrator=None, on_progress=None, work_dir=None, keep_work_dir=False, cache=True)

migrate(
    model: AnyIDFDocument,
    target_version: type[ReleaseDocumentT],
    **options: Unpack[_MigrateOptions],
) -> MigrationReport[ReleaseDocumentT]
migrate(
    model: AnyIDFDocument[StrictT],
    target_version: tuple[int, int, int] | str,
    **options: Unpack[_MigrateOptions],
) -> MigrationReport[AnyIDFDocument[StrictT]]

Forward-migrate model to target_version through EnergyPlus transition binaries.

Plans the chain of transition steps between model.version and target_version, runs each one in sequence via the supplied migrator (defaulting to a SubprocessMigrator rooted at the EnergyPlus installation's PreProcess/IDFVersionUpdater directory), re-parses the final IDF into a fresh IDFDocument, and returns a structured MigrationReport.

The input model is never mutated.

Parameters:

Name Type Description Default
model AnyIDFDocument

The document to migrate. Its version defines the source.

required
target_version tuple[int, int, int] | str | type[AnyIDFDocument[Any]]

A (major, minor, patch) tuple, a dotted string (e.g. "25.2.0"), or the document type of the target release, such as IDFDocumentV24_1 from idfkit.versioned or IDFDocument for the latest. A document type also types the report: migrated_model is then typed for that release, while a tuple or string, whose release a type checker cannot know, gives AnyIDFDocument.

required
energyplus EnergyPlusConfig | None

Pre-configured EnergyPlus installation. Ignored when migrator is provided. When neither is supplied, find_energyplus() is used to discover an installation automatically.

None
migrator Migrator | None

Custom backend implementing Migrator. Overrides energyplus when provided.

None
on_progress OnMigrationProgress | None

Optional callback invoked with MigrationProgress events on every phase transition.

None
work_dir str | Path | None

Directory in which to stage per-step work subdirectories. Defaults to a newly-created temporary directory. The directory is removed after migration unless keep_work_dir is True.

None
keep_work_dir bool

Set True to preserve intermediate files for inspection.

False
cache bool

Reuse the result of an earlier migration of the same IDF content along the same steps with the same EnergyPlus install, kept in memory for this process (see idfkit.migration.cache). The transition binaries take seconds per step, so this is what makes repeated simulate(..., auto_migrate=True) runs of one model cheap. The report's from_cache says whether the binaries ran. Set False to always run them. Ignored when work_dir or keep_work_dir is given: those ask for the per-step files, so the binaries always run.

True

Returns:

Type Description
MigrationReport[AnyIDFDocument[Any]]

A MigrationReport whose

MigrationReport[AnyIDFDocument[Any]]

migrated_model is the document at the target version. On a no-op

MigrationReport[AnyIDFDocument[Any]]

migration (source equals target) no step runs and it is a copy of

MigrationReport[AnyIDFDocument[Any]]

model, so migrate(doc, version).migrated_model is a document

MigrationReport[AnyIDFDocument[Any]]

whatever doc's version.

MigrationReport[AnyIDFDocument[Any]]

The migrated document has no filepath (it is None): it was

MigrationReport[AnyIDFDocument[Any]]

read from a scratch file in the work directory, and the source's path

MigrationReport[AnyIDFDocument[Any]]

would make a bare save() overwrite the original with a model at

MigrationReport[AnyIDFDocument[Any]]

another version. Save it to an explicit path, e.g.

MigrationReport[AnyIDFDocument[Any]]

save_idf(report.migrated_model, path) or

MigrationReport[AnyIDFDocument[Any]]

report.migrated_model.save(path).

Raises:

Type Description
UnsupportedVersionError

If the target version is not in ENERGYPLUS_VERSIONS, or no supported release shares the model's major and minor version. A two-component version read from a file (Version, 9.0; as (9, 0, 0)) resolves to its release (9.0.1), as schema selection does.

TypeError

If target_version is a type that names no single release, such as AnyIDFDocument or a union or tuple of document types, or is neither a version nor a type.

ValueError

If target_version is older than model.version (backward migration is not supported).

MigrationError

If any transition step fails. The exception's completed_steps attribute records the prefix of steps that succeeded; inspect it to recover partial progress. A step the migrator has no transition binary for is reported before any step runs.

EnergyPlusNotFoundError

If migrator is None and no EnergyPlus installation can be discovered.

Source code in idfkit/migration/runner.py
def migrate(
    model: AnyIDFDocument,
    target_version: tuple[int, int, int] | str | type[AnyIDFDocument[Any]],
    *,
    energyplus: EnergyPlusConfig | None = None,
    migrator: Migrator | None = None,
    on_progress: OnMigrationProgress | None = None,
    work_dir: str | Path | None = None,
    keep_work_dir: bool = False,
    cache: bool = True,
) -> MigrationReport[AnyIDFDocument[Any]]:
    """Forward-migrate *model* to *target_version* through EnergyPlus transition binaries.

    Plans the chain of transition steps between ``model.version`` and
    *target_version*, runs each one in sequence via the supplied *migrator*
    (defaulting to a [SubprocessMigrator][idfkit.migration.subprocess_backend.SubprocessMigrator]
    rooted at the EnergyPlus installation's ``PreProcess/IDFVersionUpdater``
    directory), re-parses the final IDF into a fresh
    [IDFDocument][idfkit.document.IDFDocument], and returns a structured
    [MigrationReport][idfkit.migration.report.MigrationReport].

    The input *model* is never mutated.

    Args:
        model: The document to migrate. Its ``version`` defines the source.
        target_version: A ``(major, minor, patch)`` tuple, a dotted string
            (e.g. ``"25.2.0"``), or the document type of the target release,
            such as ``IDFDocumentV24_1`` from ``idfkit.versioned`` or
            ``IDFDocument`` for the latest. A document type also types the
            report: ``migrated_model`` is then typed for that release, while a
            tuple or string, whose release a type checker cannot know, gives
            ``AnyIDFDocument``.
        energyplus: Pre-configured EnergyPlus installation. Ignored when
            *migrator* is provided. When neither is supplied,
            [find_energyplus()][idfkit.simulation.config.find_energyplus] is used
            to discover an installation automatically.
        migrator: Custom backend implementing
            [Migrator][idfkit.migration.protocol.Migrator]. Overrides
            *energyplus* when provided.
        on_progress: Optional callback invoked with
            [MigrationProgress][idfkit.migration.progress.MigrationProgress]
            events on every phase transition.
        work_dir: Directory in which to stage per-step work subdirectories.
            Defaults to a newly-created temporary directory. The directory is
            removed after migration unless *keep_work_dir* is ``True``.
        keep_work_dir: Set ``True`` to preserve intermediate files for
            inspection.
        cache: Reuse the result of an earlier migration of the same IDF
            content along the same steps with the same EnergyPlus install,
            kept in memory for this process (see
            [idfkit.migration.cache][idfkit.migration.cache]). The transition
            binaries take seconds per step, so this is what makes repeated
            ``simulate(..., auto_migrate=True)`` runs of one model cheap. The
            report's ``from_cache`` says whether the binaries ran. Set
            ``False`` to always run them. Ignored when *work_dir* or
            *keep_work_dir* is given: those ask for the per-step files, so the
            binaries always run.

    Returns:
        A [MigrationReport][idfkit.migration.report.MigrationReport] whose
        ``migrated_model`` is the document at the target version. On a no-op
        migration (source equals target) no step runs and it is a copy of
        *model*, so ``migrate(doc, version).migrated_model`` is a document
        whatever *doc*'s version.
        The migrated document has no ``filepath`` (it is ``None``): it was
        read from a scratch file in the work directory, and the source's path
        would make a bare ``save()`` overwrite the original with a model at
        another version. Save it to an explicit path, e.g.
        ``save_idf(report.migrated_model, path)`` or
        ``report.migrated_model.save(path)``.

    Raises:
        idfkit.exceptions.UnsupportedVersionError: If the target version is
            not in `ENERGYPLUS_VERSIONS`, or no supported release shares the
            model's major and minor version. A two-component version read from
            a file (``Version, 9.0;`` as ``(9, 0, 0)``) resolves to its
            release (9.0.1), as schema selection does.
        TypeError: If *target_version* is a type that names no single release,
            such as ``AnyIDFDocument`` or a union or tuple of document types,
            or is neither a version nor a type.
        ValueError: If *target_version* is older than ``model.version``
            (backward migration is not supported).
        idfkit.exceptions.MigrationError: If any transition step fails. The
            exception's ``completed_steps`` attribute records the prefix of
            steps that succeeded; inspect it to recover partial progress.
            A step the migrator has no transition binary for is reported
            before any step runs.
        idfkit.exceptions.EnergyPlusNotFoundError: If *migrator* is ``None``
            and no EnergyPlus installation can be discovered.
    """
    target = normalize_target(target_version)
    source = resolve_source_version(model.version)

    _emit(on_progress, MigrationProgress(phase="planning", message="Planning migration chain"))
    chain = plan_migration_chain(source, target)

    if not chain:
        _emit(
            on_progress,
            MigrationProgress(phase="complete", message="Source equals target; nothing to do", percent=100.0),
        )
        return MigrationReport(
            migrated_model=unmigrated_copy(model, target),
            source_version=source,
            target_version=target,
            requested_target=target,
            steps=(),
            diff=MigrationDiff(),
        )

    resolved_migrator = _resolve_migrator(migrator, energyplus)
    check_chain_binaries(resolved_migrator, chain)
    total_steps = len(chain)
    _emit(
        on_progress,
        MigrationProgress(
            phase="preparing",
            message=f"Running {total_steps} transition step{'s' if total_steps != 1 else ''}",
            total_steps=total_steps,
        ),
    )

    owned_work_dir = work_dir is None
    root = Path(tempfile.mkdtemp(prefix="idfkit_migrate_")) if owned_work_dir else Path(work_dir).resolve()
    if not owned_work_dir:
        root.mkdir(parents=True, exist_ok=True)

    try:
        report = _run_chain(
            model=model,
            chain=chain,
            migrator=resolved_migrator,
            work_root=root,
            on_progress=on_progress,
            source=source,
            target=target,
            # Asking for the work directory means asking to inspect the per-step files,
            # which a cache hit would not write.
            use_cache=cache and work_dir is None and not keep_work_dir,
        )
    finally:
        if owned_work_dir and not keep_work_dir:
            shutil.rmtree(root, ignore_errors=True)

    return report

async_migrate

idfkit.migration.async_runner.async_migrate(model, target_version, *, energyplus=None, migrator=None, on_progress=None, work_dir=None, keep_work_dir=False, cache=True) async

async_migrate(
    model: AnyIDFDocument,
    target_version: type[ReleaseDocumentT],
    **options: Unpack[_MigrateOptions],
) -> MigrationReport[ReleaseDocumentT]
async_migrate(
    model: AnyIDFDocument[StrictT],
    target_version: tuple[int, int, int] | str,
    **options: Unpack[_MigrateOptions],
) -> MigrationReport[AnyIDFDocument[StrictT]]

Async counterpart to migrate().

Same semantics as the sync version; the only difference is that each transition step is driven via asyncio.create_subprocess_exec (or a caller-supplied AsyncMigrator), and progress callbacks may be async.

Parameters:

Name Type Description Default
model AnyIDFDocument

The document to migrate.

required
target_version tuple[int, int, int] | str | type[AnyIDFDocument[Any]]

Target version: a tuple, a dotted string, or the target release's document type, which also types the report, as for migrate().

required
energyplus EnergyPlusConfig | None

EnergyPlus installation. Ignored when migrator is set.

None
migrator AsyncMigrator | None

Optional AsyncMigrator. When None, defaults to an AsyncSubprocessMigrator rooted at the installed EnergyPlus's IDFVersionUpdater directory.

None
on_progress OnMigrationProgress | None

Optional sync or async callback receiving MigrationProgress events.

None
work_dir str | Path | None

Directory in which to stage per-step working directories. Defaults to a newly-created temporary directory that is removed after the migration unless keep_work_dir is True.

None
keep_work_dir bool

Preserve intermediate files for inspection.

False
cache bool

Reuse an earlier migration of the same content, shared with migrate(); False always runs the transition binaries. Ignored when work_dir or keep_work_dir is given, which ask for the per-step files.

True

Returns:

Type Description
MigrationReport[AnyIDFDocument[Any]]

A MigrationReport. As with

MigrationReport[AnyIDFDocument[Any]]

migrate, the migrated document has no

MigrationReport[AnyIDFDocument[Any]]

filepath; save it to an explicit path.

Raises:

Type Description
UnsupportedVersionError

For an unsupported target, or a model whose version names no supported release.

TypeError

If target_version is a type that names no single release.

ValueError

If the target is older than model.version.

MigrationError

On any transition-step failure; the exception's completed_steps records the prefix that succeeded. A step with no transition binary is reported before any step runs.

EnergyPlusNotFoundError

If migrator is None and no EnergyPlus installation can be discovered.

Source code in idfkit/migration/async_runner.py
async def async_migrate(
    model: AnyIDFDocument,
    target_version: tuple[int, int, int] | str | type[AnyIDFDocument[Any]],
    *,
    energyplus: EnergyPlusConfig | None = None,
    migrator: AsyncMigrator | None = None,
    on_progress: OnMigrationProgress | None = None,
    work_dir: str | Path | None = None,
    keep_work_dir: bool = False,
    cache: bool = True,
) -> MigrationReport[AnyIDFDocument[Any]]:
    """Async counterpart to [migrate()][idfkit.migration.runner.migrate].

    Same semantics as the sync version; the only difference is that each
    transition step is driven via [asyncio.create_subprocess_exec][] (or a
    caller-supplied [AsyncMigrator][idfkit.migration.protocol.AsyncMigrator]),
    and progress callbacks may be async.

    Args:
        model: The document to migrate.
        target_version: Target version: a tuple, a dotted string, or the
            target release's document type, which also types the report, as
            for [migrate()][idfkit.migration.runner.migrate].
        energyplus: EnergyPlus installation. Ignored when *migrator* is set.
        migrator: Optional [AsyncMigrator][idfkit.migration.protocol.AsyncMigrator].
            When ``None``, defaults to an
            [AsyncSubprocessMigrator][idfkit.migration.async_subprocess_backend.AsyncSubprocessMigrator]
            rooted at the installed EnergyPlus's IDFVersionUpdater directory.
        on_progress: Optional sync or async callback receiving
            [MigrationProgress][idfkit.migration.progress.MigrationProgress]
            events.
        work_dir: Directory in which to stage per-step working directories.
            Defaults to a newly-created temporary directory that is removed
            after the migration unless *keep_work_dir* is ``True``.
        keep_work_dir: Preserve intermediate files for inspection.
        cache: Reuse an earlier migration of the same content, shared with
            [migrate()][idfkit.migration.runner.migrate]; ``False`` always
            runs the transition binaries. Ignored when *work_dir* or
            *keep_work_dir* is given, which ask for the per-step files.

    Returns:
        A [MigrationReport][idfkit.migration.report.MigrationReport]. As with
        [migrate][idfkit.migration.migrate], the migrated document has no
        ``filepath``; save it to an explicit path.

    Raises:
        idfkit.exceptions.UnsupportedVersionError: For an unsupported target, or a
            model whose version names no supported release.
        TypeError: If *target_version* is a type that names no single release.
        ValueError: If the target is older than ``model.version``.
        idfkit.exceptions.MigrationError: On any transition-step failure; the
            exception's ``completed_steps`` records the prefix that succeeded. A
            step with no transition binary is reported before any step runs.
        idfkit.exceptions.EnergyPlusNotFoundError: If *migrator* is ``None``
            and no EnergyPlus installation can be discovered.
    """
    target = normalize_target(target_version)
    source = resolve_source_version(model.version)

    await _emit(on_progress, MigrationProgress(phase="planning", message="Planning migration chain"))
    chain = plan_migration_chain(source, target)

    if not chain:
        await _emit(
            on_progress,
            MigrationProgress(phase="complete", message="Source equals target; nothing to do", percent=100.0),
        )
        return MigrationReport(
            migrated_model=unmigrated_copy(model, target),
            source_version=source,
            target_version=target,
            requested_target=target,
            steps=(),
            diff=MigrationDiff(),
        )

    resolved_migrator = await asyncio.to_thread(_resolve_async_migrator, migrator, energyplus)
    check_chain_binaries(resolved_migrator, chain)
    total_steps = len(chain)
    await _emit(
        on_progress,
        MigrationProgress(
            phase="preparing",
            message=f"Running {total_steps} transition step{'s' if total_steps != 1 else ''}",
            total_steps=total_steps,
        ),
    )

    owned_work_dir = work_dir is None
    root = Path(tempfile.mkdtemp(prefix="idfkit_migrate_")) if owned_work_dir else Path(work_dir).resolve()
    if not owned_work_dir:
        root.mkdir(parents=True, exist_ok=True)

    try:
        report = await _run_chain_async(
            model=model,
            chain=chain,
            migrator=resolved_migrator,
            work_root=root,
            on_progress=on_progress,
            source=source,
            target=target,
            # Asking for the work directory means asking to inspect the per-step files,
            # which a cache hit would not write.
            use_cache=cache and work_dir is None and not keep_work_dir,
        )
    finally:
        if owned_work_dir and not keep_work_dir:
            await asyncio.to_thread(shutil.rmtree, root, True)

    return report

MigrationReport

idfkit.migration.report.MigrationReport dataclass

Bases: Generic[DocumentT_co]

Result of a full migration run.

Generic in the type of migrated_model. migrate given a document type as its target, such as IDFDocumentV24_1 from idfkit.versioned, returns a report typed for that release; given a version tuple or string, whose release a type checker cannot know, it returns one typed with AnyIDFDocument, as a bare MigrationReport annotation also is.

Attributes:

Name Type Description
migrated_model DocumentT_co

The new document, at target_version. Never None: on a no-op migration (source equals target, no steps) it is a copy of the input model. Its filepath is None, so a bare save() raises ValueError; save it to an explicit path, e.g. save_idf(report.migrated_model, path).

source_version tuple[int, int, int]

The version the model started at.

target_version tuple[int, int, int]

The version the model was migrated to. On a partial failure this is the last successfully reached version, which may be earlier than the originally-requested target.

requested_target tuple[int, int, int]

The originally-requested target version.

steps tuple[MigrationStep, ...]

Ordered record of every transition step that ran.

diff MigrationDiff

Structural diff computed after migration. Empty when no steps ran (source == target).

from_cache bool

True when the transition binaries did not run because the same content was migrated earlier in this process (see idfkit.migration.cache); steps are then the records of that earlier run.

Source code in idfkit/migration/report.py
@dataclass(frozen=True)
class MigrationReport(Generic[DocumentT_co]):
    """Result of a full migration run.

    Generic in the type of ``migrated_model``. [migrate][idfkit.migration.migrate]
    given a document type as its target, such as ``IDFDocumentV24_1`` from
    ``idfkit.versioned``, returns a report typed for that release;
    given a version tuple or string, whose release a type checker cannot know,
    it returns one typed with ``AnyIDFDocument``, as a bare ``MigrationReport``
    annotation also is.

    Attributes:
        migrated_model: The new document, at ``target_version``. Never
            ``None``: on a no-op migration (source equals target, no
            ``steps``) it is a copy of the input model. Its ``filepath`` is
            ``None``, so a bare ``save()`` raises ``ValueError``; save it to
            an explicit path, e.g. ``save_idf(report.migrated_model, path)``.
        source_version: The version the model started at.
        target_version: The version the model was migrated to. On a partial
            failure this is the last successfully reached version, which may
            be earlier than the originally-requested target.
        requested_target: The originally-requested target version.
        steps: Ordered record of every transition step that ran.
        diff: Structural diff computed after migration. Empty when no
            steps ran (source == target).
        from_cache: ``True`` when the transition binaries did not run because
            the same content was migrated earlier in this process (see
            [idfkit.migration.cache][idfkit.migration.cache]); ``steps`` are
            then the records of that earlier run.
    """

    migrated_model: DocumentT_co
    source_version: tuple[int, int, int]
    target_version: tuple[int, int, int]
    requested_target: tuple[int, int, int]
    steps: tuple[MigrationStep, ...] = ()
    diff: MigrationDiff = field(default_factory=MigrationDiff)
    from_cache: bool = False

    @property
    def success(self) -> bool:
        """``True`` when every transition step succeeded (or none ran)."""
        return all(s.success for s in self.steps)

    @property
    def completed_steps(self) -> tuple[MigrationStep, ...]:
        """Steps that completed successfully, in order."""
        return tuple(s for s in self.steps if s.success)

    @property
    def failed_step(self) -> MigrationStep | None:
        """The first step that failed, if any."""
        for s in self.steps:
            if not s.success:
                return s
        return None

    def summary(self) -> str:
        """Return a short multi-line summary suitable for logs or CLI output."""
        s_ver = ".".join(str(x) for x in self.source_version)
        t_ver = ".".join(str(x) for x in self.target_version)
        lines = [
            f"Migration: {s_ver} -> {t_ver}"
            + (
                ""
                if self.target_version == self.requested_target
                else f" (requested {'.'.join(str(x) for x in self.requested_target)})"
            ),
            f"Steps: {len(self.completed_steps)}/{len(self.steps)} succeeded",
        ]
        if self.diff.added_object_types:
            lines.append(f"  + object types: {', '.join(self.diff.added_object_types)}")
        if self.diff.removed_object_types:
            lines.append(f"  - object types: {', '.join(self.diff.removed_object_types)}")
        return "\n".join(lines)

completed_steps property

Steps that completed successfully, in order.

diff = field(default_factory=MigrationDiff) class-attribute instance-attribute

failed_step property

The first step that failed, if any.

from_cache = False class-attribute instance-attribute

migrated_model instance-attribute

requested_target instance-attribute

source_version instance-attribute

steps = () class-attribute instance-attribute

success property

True when every transition step succeeded (or none ran).

target_version instance-attribute

summary()

Return a short multi-line summary suitable for logs or CLI output.

Source code in idfkit/migration/report.py
def summary(self) -> str:
    """Return a short multi-line summary suitable for logs or CLI output."""
    s_ver = ".".join(str(x) for x in self.source_version)
    t_ver = ".".join(str(x) for x in self.target_version)
    lines = [
        f"Migration: {s_ver} -> {t_ver}"
        + (
            ""
            if self.target_version == self.requested_target
            else f" (requested {'.'.join(str(x) for x in self.requested_target)})"
        ),
        f"Steps: {len(self.completed_steps)}/{len(self.steps)} succeeded",
    ]
    if self.diff.added_object_types:
        lines.append(f"  + object types: {', '.join(self.diff.added_object_types)}")
    if self.diff.removed_object_types:
        lines.append(f"  - object types: {', '.join(self.diff.removed_object_types)}")
    return "\n".join(lines)

MigrationStep

idfkit.migration.report.MigrationStep dataclass

Record of a single transition step.

Attributes:

Name Type Description
from_version tuple[int, int, int]

Source version for this step.

to_version tuple[int, int, int]

Target version for this step.

success bool

Whether the step completed without error.

binary Path | None

Path to the transition binary that was invoked, if any. None for pure-Python backends or steps that were skipped.

stdout str

Captured standard output (may be empty).

stderr str

Captured standard error (may be empty).

audit_text str | None

Contents of the per-step .audit file if produced, else None.

runtime_seconds float

Wall-clock runtime of the step.

Source code in idfkit/migration/report.py
@dataclass(frozen=True, slots=True)
class MigrationStep:
    """Record of a single transition step.

    Attributes:
        from_version: Source version for this step.
        to_version: Target version for this step.
        success: Whether the step completed without error.
        binary: Path to the transition binary that was invoked, if any. ``None``
            for pure-Python backends or steps that were skipped.
        stdout: Captured standard output (may be empty).
        stderr: Captured standard error (may be empty).
        audit_text: Contents of the per-step ``.audit`` file if produced,
            else ``None``.
        runtime_seconds: Wall-clock runtime of the step.
    """

    from_version: tuple[int, int, int]
    to_version: tuple[int, int, int]
    success: bool
    binary: Path | None = None
    stdout: str = ""
    stderr: str = ""
    audit_text: str | None = None
    runtime_seconds: float = 0.0

audit_text = None class-attribute instance-attribute

binary = None class-attribute instance-attribute

from_version instance-attribute

runtime_seconds = 0.0 class-attribute instance-attribute

stderr = '' class-attribute instance-attribute

stdout = '' class-attribute instance-attribute

success instance-attribute

to_version instance-attribute

MigrationDiff

idfkit.migration.report.MigrationDiff dataclass

Structural diff between pre- and post-migration documents.

Attributes:

Name Type Description
added_object_types tuple[str, ...]

Types present after migration but not before.

removed_object_types tuple[str, ...]

Types present before migration but not after.

object_count_delta dict[str, int]

Per-type signed change in object count. Includes only types with a nonzero delta.

field_changes dict[str, FieldDelta]

Per-type schema-level field changes (only types present in both the before and after schemas are included).

Source code in idfkit/migration/report.py
@dataclass(frozen=True, slots=True)
class MigrationDiff:
    """Structural diff between pre- and post-migration documents.

    Attributes:
        added_object_types: Types present after migration but not before.
        removed_object_types: Types present before migration but not after.
        object_count_delta: Per-type signed change in object count.
            Includes only types with a nonzero delta.
        field_changes: Per-type schema-level field changes (only types present
            in both the before and after schemas are included).
    """

    added_object_types: tuple[str, ...] = ()
    removed_object_types: tuple[str, ...] = ()
    object_count_delta: dict[str, int] = field(default_factory=_empty_count_delta)
    field_changes: dict[str, FieldDelta] = field(default_factory=_empty_field_changes)

    @property
    def is_empty(self) -> bool:
        """``True`` when the migration produced no observable structural change."""
        return (
            not self.added_object_types
            and not self.removed_object_types
            and not self.object_count_delta
            and not self.field_changes
        )

added_object_types = () class-attribute instance-attribute

field_changes = field(default_factory=_empty_field_changes) class-attribute instance-attribute

is_empty property

True when the migration produced no observable structural change.

object_count_delta = field(default_factory=_empty_count_delta) class-attribute instance-attribute

removed_object_types = () class-attribute instance-attribute

FieldDelta

idfkit.migration.report.FieldDelta dataclass

Per-object-type summary of field changes introduced by the migration.

Attributes:

Name Type Description
added tuple[str, ...]

Field names present in to_version schema but not in from_version.

removed tuple[str, ...]

Field names present in from_version schema but not in to_version.

Source code in idfkit/migration/report.py
@dataclass(frozen=True, slots=True)
class FieldDelta:
    """Per-object-type summary of field changes introduced by the migration.

    Attributes:
        added: Field names present in *to_version* schema but not in *from_version*.
        removed: Field names present in *from_version* schema but not in *to_version*.
    """

    added: tuple[str, ...] = ()
    removed: tuple[str, ...] = ()

added = () class-attribute instance-attribute

removed = () class-attribute instance-attribute

MigrationProgress

idfkit.migration.progress.MigrationProgress dataclass

Progress event emitted during a migration run.

Attributes:

Name Type Description
phase MigrationPhase

Current migration phase.

message str

Short human-readable description of the current step.

step_index int | None

0-based index of the current transition step (only set during the "transitioning" phase).

total_steps int | None

Total number of transition steps in the chain (only set once the chain has been planned).

from_version tuple[int, int, int] | None

Source version of the current step, if known.

to_version tuple[int, int, int] | None

Target version of the current step, if known.

percent float | None

Estimated completion percentage (0.0 to 100.0) or None when progress is indeterminate.

Source code in idfkit/migration/progress.py
@dataclass(frozen=True, slots=True)
class MigrationProgress:
    """Progress event emitted during a migration run.

    Attributes:
        phase: Current migration phase.
        message: Short human-readable description of the current step.
        step_index: 0-based index of the current transition step
            (only set during the ``"transitioning"`` phase).
        total_steps: Total number of transition steps in the chain
            (only set once the chain has been planned).
        from_version: Source version of the current step, if known.
        to_version: Target version of the current step, if known.
        percent: Estimated completion percentage (``0.0`` to ``100.0``) or
            ``None`` when progress is indeterminate.
    """

    phase: MigrationPhase
    message: str
    step_index: int | None = None
    total_steps: int | None = None
    from_version: tuple[int, int, int] | None = None
    to_version: tuple[int, int, int] | None = None
    percent: float | None = None

from_version = None class-attribute instance-attribute

message instance-attribute

percent = None class-attribute instance-attribute

phase instance-attribute

step_index = None class-attribute instance-attribute

to_version = None class-attribute instance-attribute

total_steps = None class-attribute instance-attribute

Migrator

idfkit.migration.protocol.Migrator

Bases: Protocol

Protocol implemented by backends that migrate IDF text one version at a time.

Source code in idfkit/migration/protocol.py
@runtime_checkable
class Migrator(Protocol):
    """Protocol implemented by backends that migrate IDF text one version at a time."""

    def migrate_step(
        self,
        idf_text: str,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
        *,
        work_dir: Path,
    ) -> MigrationStepResult:
        """Migrate *idf_text* from *from_version* to *to_version*.

        Args:
            idf_text: The source IDF text.
            from_version: The source version; the migrator should assume the
                IDF conforms to this version's IDD.
            to_version: The target version; the migrator must emit IDF text
                that conforms to this version's IDD.
            work_dir: A clean working directory the backend may use for
                intermediate files. Caller owns cleanup.

        Returns:
            The [MigrationStepResult][idfkit.migration.protocol.MigrationStepResult]
            for this single step.

        Raises:
            idfkit.exceptions.MigrationError: If the migration fails.
        """
        ...

migrate_step(idf_text, from_version, to_version, *, work_dir)

Migrate idf_text from from_version to to_version.

Parameters:

Name Type Description Default
idf_text str

The source IDF text.

required
from_version tuple[int, int, int]

The source version; the migrator should assume the IDF conforms to this version's IDD.

required
to_version tuple[int, int, int]

The target version; the migrator must emit IDF text that conforms to this version's IDD.

required
work_dir Path

A clean working directory the backend may use for intermediate files. Caller owns cleanup.

required

Returns:

Type Description
MigrationStepResult
MigrationStepResult

for this single step.

Raises:

Type Description
MigrationError

If the migration fails.

Source code in idfkit/migration/protocol.py
def migrate_step(
    self,
    idf_text: str,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
    *,
    work_dir: Path,
) -> MigrationStepResult:
    """Migrate *idf_text* from *from_version* to *to_version*.

    Args:
        idf_text: The source IDF text.
        from_version: The source version; the migrator should assume the
            IDF conforms to this version's IDD.
        to_version: The target version; the migrator must emit IDF text
            that conforms to this version's IDD.
        work_dir: A clean working directory the backend may use for
            intermediate files. Caller owns cleanup.

    Returns:
        The [MigrationStepResult][idfkit.migration.protocol.MigrationStepResult]
        for this single step.

    Raises:
        idfkit.exceptions.MigrationError: If the migration fails.
    """
    ...

AsyncMigrator

idfkit.migration.protocol.AsyncMigrator

Bases: Protocol

Async counterpart to Migrator.

Implementations perform a single version-step migration without blocking the event loop. The default implementation, AsyncSubprocessMigrator, uses asyncio.create_subprocess_exec to drive the Transition-VX-to-VY binaries shipped with EnergyPlus.

Source code in idfkit/migration/protocol.py
@runtime_checkable
class AsyncMigrator(Protocol):
    """Async counterpart to [Migrator][idfkit.migration.protocol.Migrator].

    Implementations perform a single version-step migration without blocking
    the event loop. The default implementation,
    [AsyncSubprocessMigrator][idfkit.migration.async_subprocess_backend.AsyncSubprocessMigrator],
    uses [asyncio.create_subprocess_exec][] to drive the ``Transition-VX-to-VY``
    binaries shipped with EnergyPlus.
    """

    async def migrate_step(
        self,
        idf_text: str,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
        *,
        work_dir: Path,
    ) -> MigrationStepResult:
        """Async counterpart to [Migrator.migrate_step][idfkit.migration.protocol.Migrator.migrate_step]."""
        ...

migrate_step(idf_text, from_version, to_version, *, work_dir) async

Async counterpart to Migrator.migrate_step.

Source code in idfkit/migration/protocol.py
async def migrate_step(
    self,
    idf_text: str,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
    *,
    work_dir: Path,
) -> MigrationStepResult:
    """Async counterpart to [Migrator.migrate_step][idfkit.migration.protocol.Migrator.migrate_step]."""
    ...

MigrationStepResult

idfkit.migration.protocol.MigrationStepResult dataclass

Result of a single-step migration.

Attributes:

Name Type Description
idf_text str

The migrated IDF source text.

stdout str

Captured standard output (may be empty).

stderr str

Captured standard error (may be empty).

audit_text str | None

Contents of the per-step .audit file if produced by the backend, else None.

Source code in idfkit/migration/protocol.py
@dataclass(frozen=True, slots=True)
class MigrationStepResult:
    """Result of a single-step migration.

    Attributes:
        idf_text: The migrated IDF source text.
        stdout: Captured standard output (may be empty).
        stderr: Captured standard error (may be empty).
        audit_text: Contents of the per-step ``.audit`` file if produced by
            the backend, else ``None``.
    """

    idf_text: str
    stdout: str = ""
    stderr: str = ""
    audit_text: str | None = None

audit_text = None class-attribute instance-attribute

idf_text instance-attribute

stderr = '' class-attribute instance-attribute

stdout = '' class-attribute instance-attribute

SubprocessMigrator

idfkit.migration.subprocess_backend.SubprocessMigrator dataclass

Migrator backend that shells out to EnergyPlus's transition binaries.

Attributes:

Name Type Description
version_updater_dir Path

Path to PreProcess/IDFVersionUpdater. Must contain the Transition-V*-to-V* binaries and matching V*-Energy+.idd files.

step_timeout float

Maximum wall-clock seconds for a single transition step.

Source code in idfkit/migration/subprocess_backend.py
@dataclass(frozen=True, slots=True)
class SubprocessMigrator:
    """Migrator backend that shells out to EnergyPlus's transition binaries.

    Attributes:
        version_updater_dir: Path to ``PreProcess/IDFVersionUpdater``. Must contain
            the ``Transition-V*-to-V*`` binaries and matching
            ``V*-Energy+.idd`` files.
        step_timeout: Maximum wall-clock seconds for a single transition step.
    """

    version_updater_dir: Path
    step_timeout: float = DEFAULT_STEP_TIMEOUT

    @property
    def cache_key(self) -> str:
        """What the output depends on besides the input: the transition binaries' directory.

        Lets [migrate()][idfkit.migration.migrate] reuse an earlier migration of the same
        content (see [idfkit.migration.cache][idfkit.migration.cache]). The synchronous and
        async backends share it, as they run the same binaries.
        """
        return f"IDFVersionUpdater:{self.version_updater_dir.resolve()}"

    def migrate_step(
        self,
        idf_text: str,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
        *,
        work_dir: Path,
    ) -> MigrationStepResult:
        """Run a single ``Transition-VX-to-VY`` binary on *idf_text*."""
        binary = self.locate_binary(from_version, to_version)

        work_dir.mkdir(parents=True, exist_ok=True)
        stage_transition_files(self.version_updater_dir, work_dir)
        input_idf = work_dir / "in.idf"
        input_idf.write_text(idf_text, encoding="latin-1")

        try:
            # Through run_process so that an interrupted simulate_batch kills a running step.
            proc = run_process([str(binary), str(input_idf)], cwd=work_dir, timeout=self.step_timeout)
        except subprocess.TimeoutExpired as exc:
            msg = f"Transition timed out after {self.step_timeout} seconds"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
                stderr=str(exc.stderr) if exc.stderr else None,
            ) from exc
        except OSError as exc:
            msg = f"Failed to start transition binary: {exc}"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
            ) from exc

        if proc.returncode != 0:
            msg = "Transition binary exited with non-zero status"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
                exit_code=proc.returncode,
                stderr=proc.stderr,
            )

        if not input_idf.is_file():
            msg = f"Transition binary produced no output at {input_idf}"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
                exit_code=proc.returncode,
                stderr=proc.stderr,
            )

        warn_on_missing_companions(proc.stdout, from_version, to_version)
        migrated_text = input_idf.read_text(encoding="latin-1")
        return MigrationStepResult(
            idf_text=migrated_text,
            stdout=proc.stdout,
            stderr=proc.stderr,
            audit_text=collect_audit_text(work_dir),
        )

    def locate_binary(
        self,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
    ) -> Path:
        """Return the absolute path to the transition binary for a single step.

        Tries the registry-exact name first, then falls back to ``(major, minor, 0)``
        for either side -- EnergyPlus's transition binaries are always named with
        ``patch=0`` (notably, v9.0.1 uses the ``V9-0-0`` binary name).
        """
        candidates = binary_candidates(from_version, to_version)
        for name in candidates:
            p = self.version_updater_dir / name
            if p.is_file():
                return p
        if not self.version_updater_dir.is_dir():
            msg = f"IDFVersionUpdater directory not found: {self.version_updater_dir}"
            raise MigrationError(msg, from_version=from_version, to_version=to_version)
        msg = f"No transition binary found. Tried: {', '.join(candidates)}"
        raise MigrationError(msg, from_version=from_version, to_version=to_version)

cache_key property

What the output depends on besides the input: the transition binaries' directory.

Lets migrate() reuse an earlier migration of the same content (see idfkit.migration.cache). The synchronous and async backends share it, as they run the same binaries.

step_timeout = DEFAULT_STEP_TIMEOUT class-attribute instance-attribute

version_updater_dir instance-attribute

locate_binary(from_version, to_version)

Return the absolute path to the transition binary for a single step.

Tries the registry-exact name first, then falls back to (major, minor, 0) for either side -- EnergyPlus's transition binaries are always named with patch=0 (notably, v9.0.1 uses the V9-0-0 binary name).

Source code in idfkit/migration/subprocess_backend.py
def locate_binary(
    self,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
) -> Path:
    """Return the absolute path to the transition binary for a single step.

    Tries the registry-exact name first, then falls back to ``(major, minor, 0)``
    for either side -- EnergyPlus's transition binaries are always named with
    ``patch=0`` (notably, v9.0.1 uses the ``V9-0-0`` binary name).
    """
    candidates = binary_candidates(from_version, to_version)
    for name in candidates:
        p = self.version_updater_dir / name
        if p.is_file():
            return p
    if not self.version_updater_dir.is_dir():
        msg = f"IDFVersionUpdater directory not found: {self.version_updater_dir}"
        raise MigrationError(msg, from_version=from_version, to_version=to_version)
    msg = f"No transition binary found. Tried: {', '.join(candidates)}"
    raise MigrationError(msg, from_version=from_version, to_version=to_version)

migrate_step(idf_text, from_version, to_version, *, work_dir)

Run a single Transition-VX-to-VY binary on idf_text.

Source code in idfkit/migration/subprocess_backend.py
def migrate_step(
    self,
    idf_text: str,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
    *,
    work_dir: Path,
) -> MigrationStepResult:
    """Run a single ``Transition-VX-to-VY`` binary on *idf_text*."""
    binary = self.locate_binary(from_version, to_version)

    work_dir.mkdir(parents=True, exist_ok=True)
    stage_transition_files(self.version_updater_dir, work_dir)
    input_idf = work_dir / "in.idf"
    input_idf.write_text(idf_text, encoding="latin-1")

    try:
        # Through run_process so that an interrupted simulate_batch kills a running step.
        proc = run_process([str(binary), str(input_idf)], cwd=work_dir, timeout=self.step_timeout)
    except subprocess.TimeoutExpired as exc:
        msg = f"Transition timed out after {self.step_timeout} seconds"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
            stderr=str(exc.stderr) if exc.stderr else None,
        ) from exc
    except OSError as exc:
        msg = f"Failed to start transition binary: {exc}"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
        ) from exc

    if proc.returncode != 0:
        msg = "Transition binary exited with non-zero status"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
            exit_code=proc.returncode,
            stderr=proc.stderr,
        )

    if not input_idf.is_file():
        msg = f"Transition binary produced no output at {input_idf}"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
            exit_code=proc.returncode,
            stderr=proc.stderr,
        )

    warn_on_missing_companions(proc.stdout, from_version, to_version)
    migrated_text = input_idf.read_text(encoding="latin-1")
    return MigrationStepResult(
        idf_text=migrated_text,
        stdout=proc.stdout,
        stderr=proc.stderr,
        audit_text=collect_audit_text(work_dir),
    )

AsyncSubprocessMigrator

idfkit.migration.async_subprocess_backend.AsyncSubprocessMigrator dataclass

Async migrator backend built on asyncio.create_subprocess_exec.

Attributes:

Name Type Description
version_updater_dir Path

Path to PreProcess/IDFVersionUpdater.

step_timeout float

Maximum wall-clock seconds for a single transition step.

Source code in idfkit/migration/async_subprocess_backend.py
@dataclass(frozen=True, slots=True)
class AsyncSubprocessMigrator:
    """Async migrator backend built on [asyncio.create_subprocess_exec][].

    Attributes:
        version_updater_dir: Path to ``PreProcess/IDFVersionUpdater``.
        step_timeout: Maximum wall-clock seconds for a single transition step.
    """

    version_updater_dir: Path
    step_timeout: float = DEFAULT_STEP_TIMEOUT

    @property
    def cache_key(self) -> str:
        """What the output depends on besides the input: the transition binaries' directory.

        Lets [migrate()][idfkit.migration.migrate] reuse an earlier migration of the same
        content (see [idfkit.migration.cache][idfkit.migration.cache]). The synchronous and
        async backends share it, as they run the same binaries.
        """
        return f"IDFVersionUpdater:{self.version_updater_dir.resolve()}"

    async def migrate_step(
        self,
        idf_text: str,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
        *,
        work_dir: Path,
    ) -> MigrationStepResult:
        """Run a single ``Transition-VX-to-VY`` binary without blocking."""
        binary = self.locate_binary(from_version, to_version)

        await asyncio.to_thread(work_dir.mkdir, parents=True, exist_ok=True)
        await asyncio.to_thread(stage_transition_files, self.version_updater_dir, work_dir)
        input_idf = work_dir / "in.idf"
        await asyncio.to_thread(input_idf.write_text, idf_text, "latin-1")

        try:
            proc = await asyncio.create_subprocess_exec(
                str(binary),
                str(input_idf),
                stdin=asyncio.subprocess.DEVNULL,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                cwd=str(work_dir),
            )
        except OSError as exc:
            msg = f"Failed to start transition binary: {exc}"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
            ) from exc

        try:
            stdout_bytes, stderr_bytes = await asyncio.wait_for(
                proc.communicate(),
                timeout=self.step_timeout,
            )
        except asyncio.TimeoutError as exc:
            proc.kill()
            with contextlib.suppress(ProcessLookupError):
                await proc.wait()
            msg = f"Transition timed out after {self.step_timeout} seconds"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
            ) from exc
        except asyncio.CancelledError:
            proc.kill()
            with contextlib.suppress(ProcessLookupError):
                await proc.wait()
            raise

        stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""
        stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""
        returncode = proc.returncode if proc.returncode is not None else -1

        if returncode != 0:
            msg = "Transition binary exited with non-zero status"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
                exit_code=returncode,
                stderr=stderr,
            )

        if not input_idf.is_file():
            msg = f"Transition binary produced no output at {input_idf}"
            raise MigrationError(
                msg,
                from_version=from_version,
                to_version=to_version,
                exit_code=returncode,
                stderr=stderr,
            )

        warn_on_missing_companions(stdout, from_version, to_version)
        migrated_text = await asyncio.to_thread(input_idf.read_text, "latin-1")
        audit_text = await asyncio.to_thread(collect_audit_text, work_dir)
        return MigrationStepResult(
            idf_text=migrated_text,
            stdout=stdout,
            stderr=stderr,
            audit_text=audit_text,
        )

    def locate_binary(
        self,
        from_version: tuple[int, int, int],
        to_version: tuple[int, int, int],
    ) -> Path:
        """Return the absolute path to the transition binary for a single step."""
        candidates = binary_candidates(from_version, to_version)
        for name in candidates:
            p = self.version_updater_dir / name
            if p.is_file():
                return p
        if not self.version_updater_dir.is_dir():
            msg = f"IDFVersionUpdater directory not found: {self.version_updater_dir}"
            raise MigrationError(msg, from_version=from_version, to_version=to_version)
        msg = f"No transition binary found. Tried: {', '.join(candidates)}"
        raise MigrationError(msg, from_version=from_version, to_version=to_version)

cache_key property

What the output depends on besides the input: the transition binaries' directory.

Lets migrate() reuse an earlier migration of the same content (see idfkit.migration.cache). The synchronous and async backends share it, as they run the same binaries.

step_timeout = DEFAULT_STEP_TIMEOUT class-attribute instance-attribute

version_updater_dir instance-attribute

locate_binary(from_version, to_version)

Return the absolute path to the transition binary for a single step.

Source code in idfkit/migration/async_subprocess_backend.py
def locate_binary(
    self,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
) -> Path:
    """Return the absolute path to the transition binary for a single step."""
    candidates = binary_candidates(from_version, to_version)
    for name in candidates:
        p = self.version_updater_dir / name
        if p.is_file():
            return p
    if not self.version_updater_dir.is_dir():
        msg = f"IDFVersionUpdater directory not found: {self.version_updater_dir}"
        raise MigrationError(msg, from_version=from_version, to_version=to_version)
    msg = f"No transition binary found. Tried: {', '.join(candidates)}"
    raise MigrationError(msg, from_version=from_version, to_version=to_version)

migrate_step(idf_text, from_version, to_version, *, work_dir) async

Run a single Transition-VX-to-VY binary without blocking.

Source code in idfkit/migration/async_subprocess_backend.py
async def migrate_step(
    self,
    idf_text: str,
    from_version: tuple[int, int, int],
    to_version: tuple[int, int, int],
    *,
    work_dir: Path,
) -> MigrationStepResult:
    """Run a single ``Transition-VX-to-VY`` binary without blocking."""
    binary = self.locate_binary(from_version, to_version)

    await asyncio.to_thread(work_dir.mkdir, parents=True, exist_ok=True)
    await asyncio.to_thread(stage_transition_files, self.version_updater_dir, work_dir)
    input_idf = work_dir / "in.idf"
    await asyncio.to_thread(input_idf.write_text, idf_text, "latin-1")

    try:
        proc = await asyncio.create_subprocess_exec(
            str(binary),
            str(input_idf),
            stdin=asyncio.subprocess.DEVNULL,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            cwd=str(work_dir),
        )
    except OSError as exc:
        msg = f"Failed to start transition binary: {exc}"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
        ) from exc

    try:
        stdout_bytes, stderr_bytes = await asyncio.wait_for(
            proc.communicate(),
            timeout=self.step_timeout,
        )
    except asyncio.TimeoutError as exc:
        proc.kill()
        with contextlib.suppress(ProcessLookupError):
            await proc.wait()
        msg = f"Transition timed out after {self.step_timeout} seconds"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
        ) from exc
    except asyncio.CancelledError:
        proc.kill()
        with contextlib.suppress(ProcessLookupError):
            await proc.wait()
        raise

    stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""
    stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""
    returncode = proc.returncode if proc.returncode is not None else -1

    if returncode != 0:
        msg = "Transition binary exited with non-zero status"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
            exit_code=returncode,
            stderr=stderr,
        )

    if not input_idf.is_file():
        msg = f"Transition binary produced no output at {input_idf}"
        raise MigrationError(
            msg,
            from_version=from_version,
            to_version=to_version,
            exit_code=returncode,
            stderr=stderr,
        )

    warn_on_missing_companions(stdout, from_version, to_version)
    migrated_text = await asyncio.to_thread(input_idf.read_text, "latin-1")
    audit_text = await asyncio.to_thread(collect_audit_text, work_dir)
    return MigrationStepResult(
        idf_text=migrated_text,
        stdout=stdout,
        stderr=stderr,
        audit_text=audit_text,
    )

plan_migration_chain

idfkit.migration.chain.plan_migration_chain(source, target)

Plan the ordered list of transition steps from source to target.

The chain walks forward through ENERGYPLUS_VERSIONS from source to target, emitting a (from, to) pair for each consecutive version boundary.

Parameters:

Name Type Description Default
source tuple[int, int, int]

The model's current version, doc.version as it is. It is resolved to its release with resolve_source_version, so (9, 0, 0) from a file headed Version, 9.0; plans from 9.0.1.

required
target tuple[int, int, int]

The desired version, resolved to its release as source is ((9, 0, 0) is 9.0.1). It must be >= source.

required

Returns:

Type Description
tuple[TransitionStep, ...]

A tuple of (from, to) pairs. Empty when source resolves to target.

Raises:

Type Description
UnsupportedVersionError

If no supported release shares source's or target's major and minor.

ValueError

If target < source (backward migration is not supported).

Examples:

>>> plan_migration_chain((9, 0, 0), (9, 2, 0))
(((9, 0, 1), (9, 1, 0)), ((9, 1, 0), (9, 2, 0)))
Source code in idfkit/migration/chain.py
def plan_migration_chain(
    source: tuple[int, int, int],
    target: tuple[int, int, int],
) -> tuple[TransitionStep, ...]:
    """Plan the ordered list of transition steps from *source* to *target*.

    The chain walks forward through `ENERGYPLUS_VERSIONS`
    from *source* to *target*, emitting a ``(from, to)`` pair for each
    consecutive version boundary.

    Args:
        source: The model's current version, ``doc.version`` as it is. It is
            resolved to its release with
            [resolve_source_version][idfkit.migration.chain.resolve_source_version],
            so ``(9, 0, 0)`` from a file headed ``Version, 9.0;`` plans from 9.0.1.
        target: The desired version, resolved to its release as *source* is
            (``(9, 0, 0)`` is 9.0.1). It must be ``>= source``.

    Returns:
        A tuple of ``(from, to)`` pairs. Empty when *source* resolves to *target*.

    Raises:
        UnsupportedVersionError: If no supported release shares *source*'s or
            *target*'s major and minor.
        ValueError: If ``target < source`` (backward migration is not supported).

    Examples:
        >>> plan_migration_chain((9, 0, 0), (9, 2, 0))
        (((9, 0, 1), (9, 1, 0)), ((9, 1, 0), (9, 2, 0)))
    """
    source = resolve_source_version(source)
    target = resolve_source_version(target)

    if source == target:
        return ()
    if target < source:
        msg = (
            f"Backward migration is not supported: {source[0]}.{source[1]}.{source[2]}"
            f" -> {target[0]}.{target[1]}.{target[2]}."
        )
        raise ValueError(msg)

    source_idx = ENERGYPLUS_VERSIONS.index(source)
    target_idx = ENERGYPLUS_VERSIONS.index(target)
    steps: list[TransitionStep] = []
    for i in range(source_idx, target_idx):
        steps.append((ENERGYPLUS_VERSIONS[i], ENERGYPLUS_VERSIONS[i + 1]))
    return tuple(steps)

document_diff

idfkit.migration.diff.document_diff(before, after)

Compute a structural diff between before and after.

The diff compares the two documents at three levels:

  1. Object types present in one document but not the other.
  2. Per-type signed change in object count.
  3. Per-type schema-level field renames (computed from each document's bundled schema — so after picks up fields that only exist in the newer IDD, and before may carry fields that have since been removed).

Parameters:

Name Type Description Default
before AnyIDFDocument

Document before migration.

required
after AnyIDFDocument

Document after migration.

required

Returns:

Type Description
MigrationDiff

A MigrationDiff capturing

MigrationDiff

the observable changes.

Source code in idfkit/migration/diff.py
def document_diff(before: AnyIDFDocument, after: AnyIDFDocument) -> MigrationDiff:
    """Compute a structural diff between *before* and *after*.

    The diff compares the two documents at three levels:

    1. Object types present in one document but not the other.
    2. Per-type signed change in object count.
    3. Per-type schema-level field renames (computed from each document's
       bundled schema — so ``after`` picks up fields that only exist in the
       newer IDD, and ``before`` may carry fields that have since been removed).

    Args:
        before: Document before migration.
        after: Document after migration.

    Returns:
        A [MigrationDiff][idfkit.migration.report.MigrationDiff] capturing
        the observable changes.
    """
    before_types = set(before.collections.keys())
    after_types = set(after.collections.keys())

    added = tuple(sorted(after_types - before_types))
    removed = tuple(sorted(before_types - after_types))

    count_delta: dict[str, int] = {}
    for obj_type in sorted(before_types | after_types):
        before_count = len(before.collections.get(obj_type, ()))
        after_count = len(after.collections.get(obj_type, ()))
        delta = after_count - before_count
        if delta != 0:
            count_delta[obj_type] = delta

    field_changes = _compute_field_changes(before, after, shared_types=before_types & after_types)

    return MigrationDiff(
        added_object_types=added,
        removed_object_types=removed,
        object_count_delta=count_delta,
        field_changes=field_changes,
    )

resolve_source_version

idfkit.migration.chain.resolve_source_version(version)

Resolve a model's version to the supported release a migration starts from.

An IDF file states its version with two components, so a document loaded from a file headed Version, 9.0; carries (9, 0, 0) while the release is 9.0.1. The rest of idfkit (schema selection, as_version) matches the version to its release line; a migration does the same, with find_release. Unlike schema selection, a version newer than every supported release is not snapped to the latest: a model of an unknown release cannot be migrated from a neighbouring one.

Examples:

>>> resolve_source_version((9, 0, 0))
(9, 0, 1)
>>> resolve_source_version((24, 1, 0))
(24, 1, 0)

Raises:

Type Description
UnsupportedVersionError

If no supported release has version's major and minor.

Source code in idfkit/migration/chain.py
def resolve_source_version(version: tuple[int, int, int]) -> tuple[int, int, int]:
    """Resolve a model's version to the supported release a migration starts from.

    An IDF file states its version with two components, so a document loaded from
    a file headed ``Version, 9.0;`` carries ``(9, 0, 0)`` while the release is
    9.0.1. The rest of idfkit (schema selection, ``as_version``) matches the
    version to its release line; a migration does the same, with
    [find_release][idfkit.versions.find_release]. Unlike schema selection, a
    version newer than every supported release is not snapped to the latest: a
    model of an unknown release cannot be migrated from a neighbouring one.

    Examples:
        >>> resolve_source_version((9, 0, 0))
        (9, 0, 1)
        >>> resolve_source_version((24, 1, 0))
        (24, 1, 0)

    Raises:
        UnsupportedVersionError: If no supported release has *version*'s major and minor.
    """
    release = find_release(version)
    if release is None:
        raise UnsupportedVersionError(version, ENERGYPLUS_VERSIONS)
    return release

Migration cache

idfkit.migration.cache

In-process memo of finished migrations.

Each Transition-VX-to-VY binary spends seconds loading its two IDDs, so a migration across several releases takes tens of seconds even for a tiny model. migrate() and async_migrate() remember the migrated IDF text of their last MAX_ENTRIES migrations, keyed by the hash of the source IDF text, the chain of steps and the migrator's cache_key (for the bundled backends, the IDFVersionUpdater directory they run). Migrating the same content again, as simulate(..., auto_migrate=True) does for every run of one model, then only re-parses the result. Concurrent identical migrations run the binaries once: later callers wait for the first and reuse its result.

A migrator without a cache_key attribute (or with None) is never cached, so a custom backend opts in by exposing a string that changes when its output would.

CacheKey = tuple[str, tuple[TransitionStep, ...], str] module-attribute

MAX_ENTRIES = 32 module-attribute

CachedMigration dataclass

The result of a successful migration chain, as kept in the memo.

idf_text instance-attribute

steps instance-attribute

cache_key(idf_text, chain, migrator)

The memo key for migrating idf_text along chain with migrator, or None.

None when migrator has no cache_key: its output cannot be assumed to depend only on the input text.

cached_progress_event(chain)

The transitioning event of a migration whose result is reused from the cache.

clear_migration_cache()

Forget every memoized migration, so the next one runs the transition binaries again.

Examples:

>>> from idfkit.migration import clear_migration_cache
>>> clear_migration_cache()

get(key)

The memoized migration for key, marking it most recently used.

in_flight(key)

Hold the lock for key, so one thread migrates a content while the others wait for it.

in_flight_async(key) async

Async counterpart of in_flight, per event loop.

put(key, entry)

Remember entry under key, dropping the least recently used beyond MAX_ENTRIES.