Skip to content

Custom Encoder Toolkit

StateView

Read-only planner-neutral view of one problem/task and its states.

Source code in src/mifrost/encoders/custom/state_view.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
class StateView:
    """Read-only planner-neutral view of one problem/task and its states."""

    def __init__(self, source: Any, *, backend: str | None = None) -> None:
        """Wrap a pymimir Problem or pytyr PlanningTask.

        The backend is auto-detected from the source type unless ``backend=``
        names one explicitly ('pymimir' or 'pytyr').
        """

        selected = _normalize_backend(backend)
        if selected is None:
            selected = "pytyr" if _looks_like_pytyr_task(source) else "pymimir"
        self._reader: Any
        if selected == "pytyr":
            from ...backends.pytyr import PyTyrSnapshotReader

            self._reader = PyTyrSnapshotReader(source)
        else:
            from ...backends.pymimir import PymimirSnapshotReader

            self._reader = PymimirSnapshotReader(source)
        self.backend: str = selected
        domain = self._reader.domain_snapshot()
        problem = self._reader.problem_snapshot()
        self._problem_name: str = problem.name
        self._objects: list[str] = list(problem.objects)
        self._object_types: tuple[str, ...] | None = problem.object_types
        self._type_names: tuple[str, ...] | None = domain.types
        self._type_bases: Mapping[str, tuple[str, ...]] | None = domain.type_bases
        self._predicates: tuple[PredicateInfo, ...] = tuple(
            PredicateInfo(key.name, key.arity, key.category.value)
            for key in domain.predicates
        )
        self._action_schemas: tuple[ActionInfo, ...] = tuple(
            ActionInfo(key.name, key.arity) for key in domain.actions
        )
        self._static_facts: tuple[Atom, ...] = tuple(
            _atom_from_key(key) for key in problem.static_atoms
        )
        self._goal_literals: tuple[Literal, ...] = tuple(
            _literal_from_key(key) for key in problem.goals
        )
        self._action_structures: tuple[ActionStructure, ...] | None = None
        self._state_facts_cache: dict[Any, tuple[Atom, ...]] = {}
        self._state_facts_cacheable: bool | None = None

    @property
    def objects(self) -> list[str]:
        """All constant object names of the problem, sorted."""

        return list(self._objects)

    @property
    def type_names(self) -> list[str] | None:
        """Domain-declared object-type names, or ``None`` when unavailable.

        Scoped to the whole *domain*, like :attr:`predicates` and
        :attr:`action_schemas` -- stable across every problem of the same
        domain, independent of which types a particular problem's objects
        happen to use, and independent of state. Always includes the
        implicit PDDL root type ``"object"`` when not ``None`` (see
        :attr:`object_types`).

        ``None`` exactly when :attr:`object_types` is ``None`` (pytyr): both
        come from the same backend capability, so a caller never sees one
        without the other.
        """

        if self._type_names is None:
            return None
        return list(self._type_names)

    @property
    def type_bases(self) -> dict[str, tuple[str, ...]] | None:
        """Direct parents of each declared type, or ``None`` when unavailable.

        One entry per name in :attr:`type_names`; a root type maps to an
        empty tuple. These are the *direct* edges of the PDDL type
        hierarchy, not its transitive closure -- ``spanner``'s ``man`` maps
        to ``("locatable",)``, not ``("locatable", "object")``. Consumers
        that need ancestors close the relation themselves, since the closure
        is only useful once type *ids* have been assigned (see
        ``mifrost.encoders.sparse_atom.SparseAtomTypeSchema.ancestor_matrix``).

        ``None`` exactly when :attr:`type_names` is ``None``, for the same
        backend reason.
        """

        if self._type_bases is None:
            return None
        return {name: tuple(bases) for name, bases in self._type_bases.items()}

    @property
    def object_types(self) -> list[str] | None:
        """Per-object most specific declared type name, or ``None`` if unavailable.

        Index-aligned with :attr:`objects`. Backend support is asymmetric:

        - **pymimir**: resolved from ``Object.get_bases()``. Contrary to an
          earlier assumption recorded here, the installed pymimir wrapper's
          ``Object`` (and ``Type``) expose ``get_bases()`` in addition to
          ``get_index``/``get_name`` -- verified directly against
          ``pymimir.advanced.formalism.Object``/``Type``. Every object,
          even in an untyped domain, resolves to at least the implicit PDDL
          root type ``"object"``, since pymimir's ``Domain.get_types()``
          always declares it (confirmed on every domain under
          ``data/pddl/``, typed and untyped alike) -- so an untyped domain
          degrades to a single, real type id rather than an absent field:
          the field being present reflects "this backend can classify
          objects", not "this domain declares more than one type".
        - **pytyr**: always ``None``. The translated
          ``pytyr.formalism.planning`` task this backend wraps drops type
          information during PDDL-to-task translation -- confirmed at the
          C++ layer too, not just the Python binding: PDDL types exist on
          the raw parsed AST (``pypddl.formalism.Task.get_objects()[i]
          .get_types()``, with the full ancestor chain reachable via
          ``Type.get_bases()``) but ``tyr::formalism::planning::Object``'s
          own ``Data`` struct (pytyr's ``native/include/tyr/formalism/
          object_data.hpp``) stores only ``index`` and ``name`` -- the
          translation compiles types away rather than merely omitting a
          binding for them. The ``PlanningTask`` this reader is built from
          keeps no reference back to that AST or to the original PDDL file
          paths needed to re-parse it, so this is a genuine backend
          capability gap, not unfinished plumbing.

        Only the **most specific** declared type is exposed, never the
        ancestor chain: the one real consumer today
        (``mifrost.encoders.sparse_atom``, feeding
        ``relmo.models.SparseAtomCompositionGNN.object_type_embedding``)
        models this as a single categorical id via one embedding lookup, and
        the most specific type is the most informative single label (a
        ``truck`` implies ``locatable`` implies ``object``, never the
        reverse). The ancestor chain remains separately derivable, domain
        side, by walking ``pymimir.Type.get_bases()`` from the type named in
        :attr:`type_names`; it is not threaded through here because nothing
        today reads it, and adding an unread field would be exactly the kind
        of write-only plumbing this design avoids.

        An object declared with a PDDL ``either`` type (more than one
        declared base) has no single "the" type; pymimir's snapshot layer
        raises ``ValueError`` in that case rather than silently choosing one
        (no domain under ``data/pddl/`` exercises this).
        """

        if self._object_types is None:
            return None
        return list(self._object_types)

    @property
    def predicates(self) -> list[PredicateInfo]:
        """Domain predicates sorted by category, then name, then arity."""

        return list(self._predicates)

    @property
    def action_schemas(self) -> list[ActionInfo]:
        """Lifted action schemas sorted by name, then arity."""

        return list(self._action_schemas)

    @property
    def has_action_structures(self) -> bool:
        """Whether this backend exposes lifted precondition/effect data."""

        return True

    def action_structures(self) -> tuple[ActionStructure, ...]:
        """Lifted action schemas with canonicalized preconditions/effects.

        Both supported backends expose the full structure; parameters are
        canonically renamed positionally (see :class:`ActionStructure`).
        Collections are sorted canonically so the two backends agree
        byte-for-byte on the same PDDL files — including domains with
        ``:disjunctive-preconditions``, where both backends flatten each
        disjunct into a duplicate-named schema and ordering is
        canonicalized over full records rather than names alone.
        """

        if self._action_structures is None:
            if self.backend == "pytyr":
                self._action_structures = _pytyr_action_structures(self._reader)
            else:
                self._action_structures = _pymimir_action_structures(self._reader)
        return self._action_structures

    @property
    def static_facts(self) -> tuple[Atom, ...]:
        """Static atoms that hold in every state of this problem."""

        return self._static_facts

    @property
    def problem_name(self) -> str:
        """The problem's declared name (best effort)."""

        return self._problem_name

    def state_facts(self, state: Any) -> tuple[Atom, ...]:
        """True fluent atoms followed by true derived atoms, stable order.

        Results are memoized per state object: backend states are immutable
        value objects whose fact tuples are pure functions of their content,
        so repeated encodes of the same state reuse the first conversion.
        Unhashable states simply skip the memo.
        """

        if self._state_facts_cacheable is not False:
            try:
                cached = self._state_facts_cache.get(state)
            except TypeError:
                self._state_facts_cacheable = False
            else:
                if cached is not None:
                    return cached
                facts = self._compute_state_facts(state)
                cache = self._state_facts_cache
                if len(cache) >= _STATE_FACTS_CACHE_LIMIT:
                    cache.clear()
                cache[state] = facts
                return facts
        return self._compute_state_facts(state)

    def _compute_state_facts(self, state: Any) -> tuple[Atom, ...]:
        snapshot = self._reader.state_snapshot(state)
        return tuple(
            _atom_from_key(key)
            for key in (*snapshot.fluent_atoms, *snapshot.derived_atoms)
        )

    def goal_literals(self, state: Any) -> tuple[Literal, ...]:
        """The problem's default goal literals."""

        del state
        return self._goal_literals

    def neutral_actions(self, state: Any, actions: Iterable[Any]) -> tuple[Atom, ...]:
        """Map native ground actions to ``Atom(predicate=name, args=objects)``."""

        del state
        atoms: list[Atom] = []
        for action in actions:
            atom = self._action_from_native(action)
            if atom is None:
                raise TypeError(
                    "actions lane leaf is not a recognized "
                    f"{self.backend} ground action: {type(action)!r}"
                )
            atoms.append(atom)
        return tuple(atoms)

    def _action_from_native(self, action: Any) -> Atom | None:
        try:
            return _action_atom_from_key(self._reader.action_key(action))
        except TypeError:
            return None

    def neutral_literals(
        self, values: Iterable[Any], *, field: str = "goals"
    ) -> tuple[Literal, ...]:
        """Map native ground literals (or neutral records) to `Literal`.

        Already-neutral `Literal` records pass through unchanged, as do
        semantic `LiteralKey` values. Unknown leaf types raise TypeError
        naming the lane and the backend.
        """

        literals: list[Literal] = []
        for value in values:
            literal = self._literal_from_native(value)
            if literal is None:
                raise TypeError(
                    f"{field} lane leaf is not a recognized "
                    f"{self.backend} ground literal: {type(value)!r}"
                )
            literals.append(literal)
        return tuple(literals)

    def _literal_from_native(self, value: Any) -> Literal | None:
        if isinstance(value, Literal):
            return value
        if isinstance(value, LiteralKey):
            return _literal_from_key(value)
        try:
            if self.backend == "pytyr":
                from ...backends.pytyr import SemanticPlanningTaskAdapter

                return _literal_from_key(
                    SemanticPlanningTaskAdapter._literal_key(value)
                )
            from ...backends.pymimir import _literal_key

            return _literal_from_key(_literal_key(value))
        except (AttributeError, TypeError, ValueError):
            return None

objects property

All constant object names of the problem, sorted.

type_names property

Domain-declared object-type names, or None when unavailable.

Scoped to the whole domain, like :attr:predicates and :attr:action_schemas -- stable across every problem of the same domain, independent of which types a particular problem's objects happen to use, and independent of state. Always includes the implicit PDDL root type "object" when not None (see :attr:object_types).

None exactly when :attr:object_types is None (pytyr): both come from the same backend capability, so a caller never sees one without the other.

type_bases property

Direct parents of each declared type, or None when unavailable.

One entry per name in :attr:type_names; a root type maps to an empty tuple. These are the direct edges of the PDDL type hierarchy, not its transitive closure -- spanner's man maps to ("locatable",), not ("locatable", "object"). Consumers that need ancestors close the relation themselves, since the closure is only useful once type ids have been assigned (see mifrost.encoders.sparse_atom.SparseAtomTypeSchema.ancestor_matrix).

None exactly when :attr:type_names is None, for the same backend reason.

object_types property

Per-object most specific declared type name, or None if unavailable.

Index-aligned with :attr:objects. Backend support is asymmetric:

  • pymimir: resolved from Object.get_bases(). Contrary to an earlier assumption recorded here, the installed pymimir wrapper's Object (and Type) expose get_bases() in addition to get_index/get_name -- verified directly against pymimir.advanced.formalism.Object/Type. Every object, even in an untyped domain, resolves to at least the implicit PDDL root type "object", since pymimir's Domain.get_types() always declares it (confirmed on every domain under data/pddl/, typed and untyped alike) -- so an untyped domain degrades to a single, real type id rather than an absent field: the field being present reflects "this backend can classify objects", not "this domain declares more than one type".
  • pytyr: always None. The translated pytyr.formalism.planning task this backend wraps drops type information during PDDL-to-task translation -- confirmed at the C++ layer too, not just the Python binding: PDDL types exist on the raw parsed AST (pypddl.formalism.Task.get_objects()[i] .get_types(), with the full ancestor chain reachable via Type.get_bases()) but tyr::formalism::planning::Object's own Data struct (pytyr's native/include/tyr/formalism/ object_data.hpp) stores only index and name -- the translation compiles types away rather than merely omitting a binding for them. The PlanningTask this reader is built from keeps no reference back to that AST or to the original PDDL file paths needed to re-parse it, so this is a genuine backend capability gap, not unfinished plumbing.

Only the most specific declared type is exposed, never the ancestor chain: the one real consumer today (mifrost.encoders.sparse_atom, feeding relmo.models.SparseAtomCompositionGNN.object_type_embedding) models this as a single categorical id via one embedding lookup, and the most specific type is the most informative single label (a truck implies locatable implies object, never the reverse). The ancestor chain remains separately derivable, domain side, by walking pymimir.Type.get_bases() from the type named in :attr:type_names; it is not threaded through here because nothing today reads it, and adding an unread field would be exactly the kind of write-only plumbing this design avoids.

An object declared with a PDDL either type (more than one declared base) has no single "the" type; pymimir's snapshot layer raises ValueError in that case rather than silently choosing one (no domain under data/pddl/ exercises this).

predicates property

Domain predicates sorted by category, then name, then arity.

action_schemas property

Lifted action schemas sorted by name, then arity.

has_action_structures property

Whether this backend exposes lifted precondition/effect data.

static_facts property

Static atoms that hold in every state of this problem.

problem_name property

The problem's declared name (best effort).

__init__(source, *, backend=None)

Wrap a pymimir Problem or pytyr PlanningTask.

The backend is auto-detected from the source type unless backend= names one explicitly ('pymimir' or 'pytyr').

Source code in src/mifrost/encoders/custom/state_view.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def __init__(self, source: Any, *, backend: str | None = None) -> None:
    """Wrap a pymimir Problem or pytyr PlanningTask.

    The backend is auto-detected from the source type unless ``backend=``
    names one explicitly ('pymimir' or 'pytyr').
    """

    selected = _normalize_backend(backend)
    if selected is None:
        selected = "pytyr" if _looks_like_pytyr_task(source) else "pymimir"
    self._reader: Any
    if selected == "pytyr":
        from ...backends.pytyr import PyTyrSnapshotReader

        self._reader = PyTyrSnapshotReader(source)
    else:
        from ...backends.pymimir import PymimirSnapshotReader

        self._reader = PymimirSnapshotReader(source)
    self.backend: str = selected
    domain = self._reader.domain_snapshot()
    problem = self._reader.problem_snapshot()
    self._problem_name: str = problem.name
    self._objects: list[str] = list(problem.objects)
    self._object_types: tuple[str, ...] | None = problem.object_types
    self._type_names: tuple[str, ...] | None = domain.types
    self._type_bases: Mapping[str, tuple[str, ...]] | None = domain.type_bases
    self._predicates: tuple[PredicateInfo, ...] = tuple(
        PredicateInfo(key.name, key.arity, key.category.value)
        for key in domain.predicates
    )
    self._action_schemas: tuple[ActionInfo, ...] = tuple(
        ActionInfo(key.name, key.arity) for key in domain.actions
    )
    self._static_facts: tuple[Atom, ...] = tuple(
        _atom_from_key(key) for key in problem.static_atoms
    )
    self._goal_literals: tuple[Literal, ...] = tuple(
        _literal_from_key(key) for key in problem.goals
    )
    self._action_structures: tuple[ActionStructure, ...] | None = None
    self._state_facts_cache: dict[Any, tuple[Atom, ...]] = {}
    self._state_facts_cacheable: bool | None = None

action_structures()

Lifted action schemas with canonicalized preconditions/effects.

Both supported backends expose the full structure; parameters are canonically renamed positionally (see :class:ActionStructure). Collections are sorted canonically so the two backends agree byte-for-byte on the same PDDL files — including domains with :disjunctive-preconditions, where both backends flatten each disjunct into a duplicate-named schema and ordering is canonicalized over full records rather than names alone.

Source code in src/mifrost/encoders/custom/state_view.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def action_structures(self) -> tuple[ActionStructure, ...]:
    """Lifted action schemas with canonicalized preconditions/effects.

    Both supported backends expose the full structure; parameters are
    canonically renamed positionally (see :class:`ActionStructure`).
    Collections are sorted canonically so the two backends agree
    byte-for-byte on the same PDDL files — including domains with
    ``:disjunctive-preconditions``, where both backends flatten each
    disjunct into a duplicate-named schema and ordering is
    canonicalized over full records rather than names alone.
    """

    if self._action_structures is None:
        if self.backend == "pytyr":
            self._action_structures = _pytyr_action_structures(self._reader)
        else:
            self._action_structures = _pymimir_action_structures(self._reader)
    return self._action_structures

state_facts(state)

True fluent atoms followed by true derived atoms, stable order.

Results are memoized per state object: backend states are immutable value objects whose fact tuples are pure functions of their content, so repeated encodes of the same state reuse the first conversion. Unhashable states simply skip the memo.

Source code in src/mifrost/encoders/custom/state_view.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def state_facts(self, state: Any) -> tuple[Atom, ...]:
    """True fluent atoms followed by true derived atoms, stable order.

    Results are memoized per state object: backend states are immutable
    value objects whose fact tuples are pure functions of their content,
    so repeated encodes of the same state reuse the first conversion.
    Unhashable states simply skip the memo.
    """

    if self._state_facts_cacheable is not False:
        try:
            cached = self._state_facts_cache.get(state)
        except TypeError:
            self._state_facts_cacheable = False
        else:
            if cached is not None:
                return cached
            facts = self._compute_state_facts(state)
            cache = self._state_facts_cache
            if len(cache) >= _STATE_FACTS_CACHE_LIMIT:
                cache.clear()
            cache[state] = facts
            return facts
    return self._compute_state_facts(state)

goal_literals(state)

The problem's default goal literals.

Source code in src/mifrost/encoders/custom/state_view.py
500
501
502
503
504
def goal_literals(self, state: Any) -> tuple[Literal, ...]:
    """The problem's default goal literals."""

    del state
    return self._goal_literals

neutral_actions(state, actions)

Map native ground actions to Atom(predicate=name, args=objects).

Source code in src/mifrost/encoders/custom/state_view.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def neutral_actions(self, state: Any, actions: Iterable[Any]) -> tuple[Atom, ...]:
    """Map native ground actions to ``Atom(predicate=name, args=objects)``."""

    del state
    atoms: list[Atom] = []
    for action in actions:
        atom = self._action_from_native(action)
        if atom is None:
            raise TypeError(
                "actions lane leaf is not a recognized "
                f"{self.backend} ground action: {type(action)!r}"
            )
        atoms.append(atom)
    return tuple(atoms)

neutral_literals(values, *, field='goals')

Map native ground literals (or neutral records) to Literal.

Already-neutral Literal records pass through unchanged, as do semantic LiteralKey values. Unknown leaf types raise TypeError naming the lane and the backend.

Source code in src/mifrost/encoders/custom/state_view.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def neutral_literals(
    self, values: Iterable[Any], *, field: str = "goals"
) -> tuple[Literal, ...]:
    """Map native ground literals (or neutral records) to `Literal`.

    Already-neutral `Literal` records pass through unchanged, as do
    semantic `LiteralKey` values. Unknown leaf types raise TypeError
    naming the lane and the backend.
    """

    literals: list[Literal] = []
    for value in values:
        literal = self._literal_from_native(value)
        if literal is None:
            raise TypeError(
                f"{field} lane leaf is not a recognized "
                f"{self.backend} ground literal: {type(value)!r}"
            )
        literals.append(literal)
    return tuple(literals)

GraphWriter

One-graph writer that owns a BatchBuilder, NodeTable and EdgeSink.

A fresh writer is created per encoded graph; finish emits the graph and spends the writer: any further add_* or finish call raises :class:RuntimeError until :meth:reset clears the finished flag and the accumulated content.

A writer created with an explicit builder writes into that SHARED batch builder (the batch fast lane); it must never call finish — build() would reset the shared builder mid-batch and silently drop every graph encoded so far. Shared-mode writers therefore raise :class:RuntimeError from finish; the owning batch loop calls next_graph/build itself.

Source code in src/mifrost/encoders/custom/writer.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
class GraphWriter:
    """One-graph writer that owns a BatchBuilder, NodeTable and EdgeSink.

    A fresh writer is created per encoded graph; `finish` emits the graph
    and spends the writer: any further ``add_*`` or `finish` call raises
    :class:`RuntimeError` until :meth:`reset` clears the finished flag and
    the accumulated content.

    A writer created with an explicit ``builder`` writes into that SHARED
    batch builder (the batch fast lane); it must never call `finish` —
    ``build()`` would reset the shared builder mid-batch and silently drop
    every graph encoded so far. Shared-mode writers therefore raise
    :class:`RuntimeError` from `finish`; the owning batch loop calls
    ``next_graph``/``build`` itself.
    """

    def __init__(
        self,
        view: StateView,
        *,
        graph_kind: str = "homo",
        export_node_names: bool = True,
        builder: Any | None = None,
    ) -> None:
        """Start one empty graph against ``view``'s problem schema.

        Pass ``builder`` to emit into a shared ``BatchBuilder`` (the batch
        fast lane); the writer then never sets the graph kind or builds —
        the owning batch loop calls ``next_graph``/``build`` itself.
        """

        self.view = view
        self.graph_kind = graph_kind
        self.export_node_names = export_node_names
        self._finished = False
        self._shared_builder = builder is not None
        self._builder: Any
        if builder is None:
            self._builder = BatchBuilder()
            self._builder.set_graph_kind(graph_kind)
        else:
            self._builder = builder
        self.nodes = NodeTable()
        self.edges = EdgeSink()
        self._vocabularies: dict[str, Vocabulary] = {}

    def _require_open(self) -> None:
        """Raise when the writer has already been finished."""

        if self._finished:
            raise RuntimeError(
                "this GraphWriter was finished and is spent; call reset() "
                "or create a fresh writer"
            )

    def _require_edge_endpoint(self, value: int, label: str) -> None:
        """Raise IndexError unless ``value`` names an interned node row."""

        count = self.nodes.count
        if not 0 <= value < count:
            raise IndexError(
                f"edge {label}={value} out of range for {count} interned "
                "node(s); intern the node via add_node() before wiring edges"
            )

    def add_node(
        self,
        key: Hashable,
        *,
        role: str,
        channels: Sequence[int] = (),
        name: str | None = None,
    ) -> int:
        """Intern one node in the writer's `NodeTable` and return its id."""

        self._require_open()
        return self.nodes.id_for(key, role=role, channels=channels, name=name)

    def add_edge(
        self,
        src: int,
        dst: int,
        kind: str,
        pos_a: int = 0,
        pos_b: int = 0,
    ) -> None:
        """Append one directed edge to the writer's `EdgeSink`."""

        self._require_open()
        self._require_edge_endpoint(src, "src")
        self._require_edge_endpoint(dst, "dst")
        self.edges.add(src, dst, kind, pos_a, pos_b)

    def add_both(
        self,
        src: int,
        dst: int,
        kind_fwd: str,
        kind_bwd: str,
        pos_a: int = 0,
        pos_b: int = 0,
    ) -> None:
        """Append an edge pair (forward plus reverse) to the edge sink."""

        self._require_open()
        self._require_edge_endpoint(src, "src")
        self._require_edge_endpoint(dst, "dst")
        self.edges.add_both(src, dst, kind_fwd, kind_bwd, pos_a, pos_b)

    def vocabulary(self, name: str) -> Vocabulary:
        """Return the named vocabulary (e.g. ``"predicates"``), creating it."""

        found = self._vocabularies.get(name)
        if found is None:
            found = Vocabulary()
            self._vocabularies[name] = found
        return found

    def set_vocab_attr(self, name: str) -> None:
        """Export the named vocabulary as graph attr ``vocab_<name>``."""

        vocab = self.vocabulary(name)
        self._builder.set_graph_attr(f"vocab_{name}", vocab.names())

    def set_attr(self, key: str, value: Any) -> None:
        """Set one graph-level attribute on the underlying builder."""

        self._builder.set_graph_attr(key, value)

    def set_flag(self, key: str, value: bool) -> None:
        """Set one schema flag on the underlying builder."""

        self._builder.set_schema_flag(key, bool(value))

    def register_field(self, key: str, spec: dict) -> None:
        """Register a graph-field spec on the underlying builder."""

        self._builder.register_field(key, spec)

    def set_field(self, key: str, values: Any) -> None:
        """Set a graph-field value on the underlying builder."""

        self._builder.set_field(key, values)

    def finish(self) -> BatchEncoding:
        """Emit the accumulated graph and spend the writer.

        Nodes are exported under type ``node`` with feature attr ``x_ids``
        and optional node names; edges under ``("node", "edge", "node")``
        with feature attr ``edge_attr`` of fixed width 3. Object names and
        the ``custom_encoder`` schema flag are always attached. Calling
        `finish` (or any ``add_*`` method) again raises
        :class:`RuntimeError`; :meth:`reset` returns the writer to a fresh,
        empty state.

        Writers bound to a shared batch builder (``builder=`` at
        construction, i.e. the batch fast lane) must NOT call `finish`:
        building the shared builder mid-batch would silently drop every
        graph encoded so far, so `finish` raises :class:`RuntimeError`
        there — the batch loop emits the graph.
        """

        self._require_open()
        if self._shared_builder:
            raise RuntimeError(
                "this GraphWriter writes into a shared batch builder; do "
                "not call finish() — the batch loop emits the graph"
            )
        self._write_into(self._builder)
        encoding = self._builder.build()
        self._finished = True
        self.nodes = NodeTable()
        self.edges = EdgeSink()
        self._vocabularies = {}
        return encoding

    def reset(self) -> None:
        """Discard the finished flag and all accumulated content.

        The writer becomes a fresh, empty graph again; the underlying
        builder is replaced with a private one (the shared-builder binding
        is dropped), so a writer bound to a shared batch builder must not
        be reset mid-batch.
        """

        self._builder = BatchBuilder()
        self._builder.set_graph_kind(self.graph_kind)
        self.nodes = NodeTable()
        self.edges = EdgeSink()
        self._vocabularies = {}
        self._finished = False
        self._shared_builder = False

    def _write_into(self, builder: Any) -> None:
        """Write the accumulated graph content into ``builder``.

        Shared by :meth:`finish` and the batch fast lane, which writes
        every graph into one shared ``BatchBuilder`` separated by
        ``next_graph`` instead of collating per-graph encodings.
        """

        nodes = self.nodes
        count = nodes.count
        if count > 0:
            builder.add_nodes("node", count)
            builder.add_node_features("node", "x_ids", nodes.to_float_array())
            names = nodes.names()
            if self.export_node_names and names is not None:
                builder.set_node_names("node", names)
        edge_index, edge_attr = self.edges.to_arrays()
        builder.ensure_edge_type("node", "edge", "node")
        builder.add_edge_features("node", "edge", "node", "edge_attr", edge_attr)
        if len(edge_attr) > 0:
            builder.add_edges("node", "edge", "node", edge_index[0], edge_index[1])
        builder.set_object_names(self.view.objects)
        builder.set_schema_flag("custom_encoder", True)
        builder.set_graph_attr("vocab_edge_kinds", self.edges.kinds.names())

__init__(view, *, graph_kind='homo', export_node_names=True, builder=None)

Start one empty graph against view's problem schema.

Pass builder to emit into a shared BatchBuilder (the batch fast lane); the writer then never sets the graph kind or builds — the owning batch loop calls next_graph/build itself.

Source code in src/mifrost/encoders/custom/writer.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def __init__(
    self,
    view: StateView,
    *,
    graph_kind: str = "homo",
    export_node_names: bool = True,
    builder: Any | None = None,
) -> None:
    """Start one empty graph against ``view``'s problem schema.

    Pass ``builder`` to emit into a shared ``BatchBuilder`` (the batch
    fast lane); the writer then never sets the graph kind or builds —
    the owning batch loop calls ``next_graph``/``build`` itself.
    """

    self.view = view
    self.graph_kind = graph_kind
    self.export_node_names = export_node_names
    self._finished = False
    self._shared_builder = builder is not None
    self._builder: Any
    if builder is None:
        self._builder = BatchBuilder()
        self._builder.set_graph_kind(graph_kind)
    else:
        self._builder = builder
    self.nodes = NodeTable()
    self.edges = EdgeSink()
    self._vocabularies: dict[str, Vocabulary] = {}

add_node(key, *, role, channels=(), name=None)

Intern one node in the writer's NodeTable and return its id.

Source code in src/mifrost/encoders/custom/writer.py
78
79
80
81
82
83
84
85
86
87
88
89
def add_node(
    self,
    key: Hashable,
    *,
    role: str,
    channels: Sequence[int] = (),
    name: str | None = None,
) -> int:
    """Intern one node in the writer's `NodeTable` and return its id."""

    self._require_open()
    return self.nodes.id_for(key, role=role, channels=channels, name=name)

add_edge(src, dst, kind, pos_a=0, pos_b=0)

Append one directed edge to the writer's EdgeSink.

Source code in src/mifrost/encoders/custom/writer.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def add_edge(
    self,
    src: int,
    dst: int,
    kind: str,
    pos_a: int = 0,
    pos_b: int = 0,
) -> None:
    """Append one directed edge to the writer's `EdgeSink`."""

    self._require_open()
    self._require_edge_endpoint(src, "src")
    self._require_edge_endpoint(dst, "dst")
    self.edges.add(src, dst, kind, pos_a, pos_b)

add_both(src, dst, kind_fwd, kind_bwd, pos_a=0, pos_b=0)

Append an edge pair (forward plus reverse) to the edge sink.

Source code in src/mifrost/encoders/custom/writer.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def add_both(
    self,
    src: int,
    dst: int,
    kind_fwd: str,
    kind_bwd: str,
    pos_a: int = 0,
    pos_b: int = 0,
) -> None:
    """Append an edge pair (forward plus reverse) to the edge sink."""

    self._require_open()
    self._require_edge_endpoint(src, "src")
    self._require_edge_endpoint(dst, "dst")
    self.edges.add_both(src, dst, kind_fwd, kind_bwd, pos_a, pos_b)

vocabulary(name)

Return the named vocabulary (e.g. "predicates"), creating it.

Source code in src/mifrost/encoders/custom/writer.py
122
123
124
125
126
127
128
129
def vocabulary(self, name: str) -> Vocabulary:
    """Return the named vocabulary (e.g. ``"predicates"``), creating it."""

    found = self._vocabularies.get(name)
    if found is None:
        found = Vocabulary()
        self._vocabularies[name] = found
    return found

set_vocab_attr(name)

Export the named vocabulary as graph attr vocab_<name>.

Source code in src/mifrost/encoders/custom/writer.py
131
132
133
134
135
def set_vocab_attr(self, name: str) -> None:
    """Export the named vocabulary as graph attr ``vocab_<name>``."""

    vocab = self.vocabulary(name)
    self._builder.set_graph_attr(f"vocab_{name}", vocab.names())

set_attr(key, value)

Set one graph-level attribute on the underlying builder.

Source code in src/mifrost/encoders/custom/writer.py
137
138
139
140
def set_attr(self, key: str, value: Any) -> None:
    """Set one graph-level attribute on the underlying builder."""

    self._builder.set_graph_attr(key, value)

set_flag(key, value)

Set one schema flag on the underlying builder.

Source code in src/mifrost/encoders/custom/writer.py
142
143
144
145
def set_flag(self, key: str, value: bool) -> None:
    """Set one schema flag on the underlying builder."""

    self._builder.set_schema_flag(key, bool(value))

register_field(key, spec)

Register a graph-field spec on the underlying builder.

Source code in src/mifrost/encoders/custom/writer.py
147
148
149
150
def register_field(self, key: str, spec: dict) -> None:
    """Register a graph-field spec on the underlying builder."""

    self._builder.register_field(key, spec)

set_field(key, values)

Set a graph-field value on the underlying builder.

Source code in src/mifrost/encoders/custom/writer.py
152
153
154
155
def set_field(self, key: str, values: Any) -> None:
    """Set a graph-field value on the underlying builder."""

    self._builder.set_field(key, values)

finish()

Emit the accumulated graph and spend the writer.

Nodes are exported under type node with feature attr x_ids and optional node names; edges under ("node", "edge", "node") with feature attr edge_attr of fixed width 3. Object names and the custom_encoder schema flag are always attached. Calling finish (or any add_* method) again raises :class:RuntimeError; :meth:reset returns the writer to a fresh, empty state.

Writers bound to a shared batch builder (builder= at construction, i.e. the batch fast lane) must NOT call finish: building the shared builder mid-batch would silently drop every graph encoded so far, so finish raises :class:RuntimeError there — the batch loop emits the graph.

Source code in src/mifrost/encoders/custom/writer.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def finish(self) -> BatchEncoding:
    """Emit the accumulated graph and spend the writer.

    Nodes are exported under type ``node`` with feature attr ``x_ids``
    and optional node names; edges under ``("node", "edge", "node")``
    with feature attr ``edge_attr`` of fixed width 3. Object names and
    the ``custom_encoder`` schema flag are always attached. Calling
    `finish` (or any ``add_*`` method) again raises
    :class:`RuntimeError`; :meth:`reset` returns the writer to a fresh,
    empty state.

    Writers bound to a shared batch builder (``builder=`` at
    construction, i.e. the batch fast lane) must NOT call `finish`:
    building the shared builder mid-batch would silently drop every
    graph encoded so far, so `finish` raises :class:`RuntimeError`
    there — the batch loop emits the graph.
    """

    self._require_open()
    if self._shared_builder:
        raise RuntimeError(
            "this GraphWriter writes into a shared batch builder; do "
            "not call finish() — the batch loop emits the graph"
        )
    self._write_into(self._builder)
    encoding = self._builder.build()
    self._finished = True
    self.nodes = NodeTable()
    self.edges = EdgeSink()
    self._vocabularies = {}
    return encoding

reset()

Discard the finished flag and all accumulated content.

The writer becomes a fresh, empty graph again; the underlying builder is replaced with a private one (the shared-builder binding is dropped), so a writer bound to a shared batch builder must not be reset mid-batch.

Source code in src/mifrost/encoders/custom/writer.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def reset(self) -> None:
    """Discard the finished flag and all accumulated content.

    The writer becomes a fresh, empty graph again; the underlying
    builder is replaced with a private one (the shared-builder binding
    is dropped), so a writer bound to a shared batch builder must not
    be reset mid-batch.
    """

    self._builder = BatchBuilder()
    self._builder.set_graph_kind(self.graph_kind)
    self.nodes = NodeTable()
    self.edges = EdgeSink()
    self._vocabularies = {}
    self._finished = False
    self._shared_builder = False

CustomGraphEncoder

Bases: EncoderBase[Any]

Base class for pure-Python custom graph encoders.

Subclasses set accepted_kwargs for extra lanes beyond the standard five and override encode_state to draw one graph into a fresh GraphWriter.

Source code in src/mifrost/encoders/custom/base.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
class CustomGraphEncoder(EncoderBase[Any]):
    """Base class for pure-Python custom graph encoders.

    Subclasses set `accepted_kwargs` for extra lanes beyond the standard five
    and override `encode_state` to draw one graph into a fresh `GraphWriter`.
    """

    accepted_kwargs: frozenset[str] = frozenset()

    def __init__(
        self,
        source: Any,
        *,
        graph_kind: str = "homo",
        export_node_names: bool = True,
        backend: str | None = None,
    ) -> None:
        """Build one `StateView` over a pymimir problem or pytyr task."""

        try:
            self.view = StateView(source, backend=backend)
        except TypeError as exc:
            # Duck-type the classic mistake of passing a pymimir Domain
            # where a Problem is required (mirrors the derived-family
            # guidance message) and re-raise with actionable context.
            looks_like_domain = (
                hasattr(source, "get_domain")
                and not hasattr(source, "get_initial_state")
                and not _looks_like_pytyr_task(source)
            )
            if looks_like_domain:
                raise TypeError(
                    "Custom encoders need a Problem, not a Domain: object "
                    "tables, static facts, and goal literals are "
                    f"problem-scoped (got {type(source).__name__})"
                ) from exc
            raise
        self.backend = self.view.backend
        self.graph_kind = graph_kind
        self.export_node_names = export_node_names

    def encode_state(
        self,
        out: GraphWriter,
        state: Any,
        *,
        goals: tuple[Literal, ...] | None = None,
        actions: tuple[Atom, ...] | None = None,
        subgoal_layers: tuple[tuple[Literal, ...], ...] | None = None,
        history_subgoals: tuple[tuple[int, tuple[Literal, ...]], ...] | None = None,
        history_max_steps: int | None = None,
        **kwargs: Any,
    ) -> None:
        """Draw one state's graph into ``out``; the only required override."""

        raise NotImplementedError(
            f"{type(self).__name__} must implement encode_state()"
        )

    def stream(self) -> CustomStream:
        """Create a pure-Python streaming variant of this encoder."""

        return CustomStream(self)

    def _accepted_kwargs(self) -> set[str]:
        return set(_STANDARD_LANES | set(self.accepted_kwargs))

    def _new_writer(self, builder: Any | None = None) -> GraphWriter:
        return GraphWriter(
            self.view,
            graph_kind=self.graph_kind,
            export_node_names=self.export_node_names,
            builder=builder,
        )

    def _neutralize_lanes(
        self,
        state: Any,
        *,
        goals: Any,
        actions: Any,
        subgoal_layers: Any,
        history_subgoals: Any,
    ) -> dict[str, Any]:
        """Convert native lane leaves into neutral records via the view.

        ``None`` lanes stay ``None`` (problem defaults); an explicitly
        empty lane neutralizes to an empty tuple — never to ``None`` — so
        "no goals" survives into `encode_state`.
        """

        view = self.view
        return {
            "goals": (
                None if goals is None else view.neutral_literals(goals, field="goals")
            ),
            "actions": (
                None if actions is None else view.neutral_actions(state, actions)
            ),
            "subgoal_layers": (
                None
                if subgoal_layers is None
                else tuple(
                    view.neutral_literals(layer, field="subgoal_layers")
                    for layer in subgoal_layers
                )
            ),
            "history_subgoals": (
                None
                if history_subgoals is None
                else tuple(
                    (
                        int(delta),
                        view.neutral_literals(literals, field="history_subgoals"),
                    )
                    for delta, literals in history_subgoals
                )
            ),
        }

    def _encode(
        self,
        state: Any,
        *,
        goals: Any = None,
        actions: Any = None,
        subgoal_layers: Any = None,
        **kwargs: Any,
    ) -> Any:
        history_subgoals = kwargs.pop("history_subgoals", None)
        history_max_steps = kwargs.pop("history_max_steps", None)
        out = self._new_writer()
        lanes = self._neutralize_lanes(
            state,
            goals=goals,
            actions=actions,
            subgoal_layers=subgoal_layers,
            history_subgoals=history_subgoals,
        )
        self.encode_state(
            out, state, **lanes, history_max_steps=history_max_steps, **kwargs
        )
        return out.finish()

    def _encode_batch(
        self,
        states: Any,
        *,
        goals: Any = None,
        actions: Any = None,
        subgoal_layers: Any = None,
        **kwargs: Any,
    ) -> Any:
        history_subgoals = kwargs.pop("history_subgoals", None)
        history_max_steps = kwargs.pop("history_max_steps", None)
        state_values = self._state_values(states)
        count = len(state_values)
        goal_lanes = self._split_lane(
            goals, count=count, field="goals", leaf=self._is_goal_leaf
        )
        action_lanes = self._split_lane(
            actions, count=count, field="actions", leaf=self._is_action_leaf
        )
        layer_lanes = self._split_layers(subgoal_layers, count=count)
        history_lanes = self._split_lane(
            history_subgoals,
            count=count,
            field="history_subgoals",
            leaf=_is_history_entry,
        )
        # Batch fast lane: one shared builder, one graph per state separated
        # by next_graph(), one build at the end — no per-graph encodings and
        # no collation pass.
        from ... import _core

        shared = _core.BatchBuilder()
        shared.set_graph_kind(self.graph_kind)
        for index, state in enumerate(state_values):
            lanes = self._neutralize_lanes(
                state,
                goals=goal_lanes[index],
                actions=action_lanes[index],
                subgoal_layers=layer_lanes[index],
                history_subgoals=history_lanes[index],
            )
            writer = self._new_writer(builder=shared)
            self.encode_state(
                writer,
                state,
                **lanes,
                history_max_steps=history_max_steps,
                **kwargs,
            )
            writer._write_into(shared)
            shared.next_graph()
        return shared.build()

    def _state_values(self, states: Any) -> list[Any]:
        """Normalize one state or a state iterable into a list."""

        if _looks_like_state(states):
            return [states]
        values = _sequence(states, field="states")
        if not all(_looks_like_state(value) for value in values):
            raise TypeError("states must be planning states or iterables of them")
        return values

    def _is_goal_leaf(self, value: object) -> bool:
        if self.view._literal_from_native(value) is not None:
            return True
        return not isinstance(value, Sequence)

    def _is_action_leaf(self, value: object) -> bool:
        if self.view._action_from_native(value) is not None:
            return True
        return not isinstance(value, Sequence)

    def _split_lane(
        self,
        value: object,
        *,
        count: int,
        field: str,
        leaf: Any,
    ) -> list[Any | None]:
        """Split a batch lane into per-state values (shared/separate/implicit).

        ``None`` (or the ``none`` batch mode) yields ``[None] * count`` —
        every state falls back to its default. An explicitly passed EMPTY
        lane is NOT ``None``: it broadcasts as "explicitly no goals/actions
        for every state" and must never be swapped for the problem default,
        otherwise batch encoding would fabricate goal nodes that single
        encoding of the same states would not have.
        """

        kind, payload = _batch_param(value)
        if kind == "none" or payload is None:
            return [None] * count
        if kind == "shared":
            return [payload] * count
        if kind == "separate":
            values = _sequence(payload, field=field)
            if len(values) != count:
                raise ValueError(f"{field} length must match states length")
            return values
        values = _sequence(payload, field=field)
        per_state = bool(values) and any(
            item is None or (not leaf(item) and isinstance(item, Sequence))
            for item in values
        )
        if per_state:
            if len(values) != count:
                raise ValueError(f"{field} length must match states length")
            return values
        # Broadcast, but never alias one mutable list across states.
        return [list(values) for _ in range(count)]

    def _split_layers(self, value: object, *, count: int) -> list[Any | None]:
        """Split a subgoal-layers lane where leaves are literal layers."""

        kind, payload = _batch_param(value)
        if kind == "none" or payload is None:
            return [None] * count
        if kind == "shared":
            return [payload] * count
        if kind == "separate":
            values = _sequence(payload, field="subgoal_layers")
            if len(values) != count:
                raise ValueError("subgoal_layers length must match states length")
            return values
        values = _sequence(payload, field="subgoal_layers")
        per_state = any(
            item is None
            or (
                isinstance(item, Sequence)
                and bool(item)
                and isinstance(item[0], Sequence)
            )
            for item in values
        )
        if per_state:
            if len(values) != count:
                raise ValueError("subgoal_layers length must match states length")
            return values
        # Broadcast, but never alias one mutable list across states.
        return [list(values) for _ in range(count)]

__init__(source, *, graph_kind='homo', export_node_names=True, backend=None)

Build one StateView over a pymimir problem or pytyr task.

Source code in src/mifrost/encoders/custom/base.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def __init__(
    self,
    source: Any,
    *,
    graph_kind: str = "homo",
    export_node_names: bool = True,
    backend: str | None = None,
) -> None:
    """Build one `StateView` over a pymimir problem or pytyr task."""

    try:
        self.view = StateView(source, backend=backend)
    except TypeError as exc:
        # Duck-type the classic mistake of passing a pymimir Domain
        # where a Problem is required (mirrors the derived-family
        # guidance message) and re-raise with actionable context.
        looks_like_domain = (
            hasattr(source, "get_domain")
            and not hasattr(source, "get_initial_state")
            and not _looks_like_pytyr_task(source)
        )
        if looks_like_domain:
            raise TypeError(
                "Custom encoders need a Problem, not a Domain: object "
                "tables, static facts, and goal literals are "
                f"problem-scoped (got {type(source).__name__})"
            ) from exc
        raise
    self.backend = self.view.backend
    self.graph_kind = graph_kind
    self.export_node_names = export_node_names

encode_state(out, state, *, goals=None, actions=None, subgoal_layers=None, history_subgoals=None, history_max_steps=None, **kwargs)

Draw one state's graph into out; the only required override.

Source code in src/mifrost/encoders/custom/base.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def encode_state(
    self,
    out: GraphWriter,
    state: Any,
    *,
    goals: tuple[Literal, ...] | None = None,
    actions: tuple[Atom, ...] | None = None,
    subgoal_layers: tuple[tuple[Literal, ...], ...] | None = None,
    history_subgoals: tuple[tuple[int, tuple[Literal, ...]], ...] | None = None,
    history_max_steps: int | None = None,
    **kwargs: Any,
) -> None:
    """Draw one state's graph into ``out``; the only required override."""

    raise NotImplementedError(
        f"{type(self).__name__} must implement encode_state()"
    )

stream()

Create a pure-Python streaming variant of this encoder.

Source code in src/mifrost/encoders/custom/base.py
121
122
123
124
def stream(self) -> CustomStream:
    """Create a pure-Python streaming variant of this encoder."""

    return CustomStream(self)

CustomStream dataclass

Bases: StreamEncoderBase[Any]

Pure-Python stream storing (state, kwargs) recipes until flush.

Recipes hold references to their states, so appended states must outlive the stream: nothing is encoded until flush re-runs every recipe through its encoder in id order.

Source code in src/mifrost/encoders/custom/base.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
@dataclass
class CustomStream(StreamEncoderBase[Any]):
    """Pure-Python stream storing ``(state, kwargs)`` recipes until flush.

    Recipes hold references to their states, so appended states must outlive
    the stream: nothing is encoded until `flush` re-runs every recipe through
    its encoder in id order.
    """

    encoder: CustomGraphEncoder

    def __post_init__(self) -> None:
        self._reuse_removed = False
        self.reset()

    def append(self, state: Any, **kwargs: Any) -> int:
        """Store one encoding recipe and return its stream id."""

        if self._reuse_removed and self._removed:
            stream_id = min(self._removed)
            self._removed.remove(stream_id)
        else:
            stream_id = self._next_id
            self._next_id += 1
        self._items[stream_id] = (state, dict(kwargs))
        return stream_id

    def update(self, stream_id: int, state: Any, **kwargs: Any) -> None:
        """Replace the recipe stored at ``stream_id``."""

        if stream_id not in self._items:
            raise KeyError(stream_id)
        self._items[stream_id] = (state, dict(kwargs))

    def remove(self, stream_id: int) -> None:
        """Drop one recipe; its slot is reusable when reuse is enabled."""

        if stream_id not in self._items:
            raise KeyError(stream_id)
        del self._items[stream_id]
        self._removed.add(stream_id)

    def set_reuse_removed(self, value: bool) -> None:
        """Enable or disable removed-slot reuse (replace-in-order semantics)."""

        self._reuse_removed = bool(value)

    def flush(self) -> Any:
        """Re-encode every stored recipe in id order as one batch encoding."""

        if not self._items:
            raise ValueError("cannot flush an empty CustomStream")
        from ... import batch_encodings

        encodings = []
        for key in sorted(self._items):
            recipe_state, recipe_kwargs = self._items[key]
            encodings.append(self.encoder.encode(recipe_state, **recipe_kwargs))
        result = batch_encodings(encodings)
        self.reset()
        return result

    def reset(self) -> None:
        """Clear every stored recipe."""

        self._items: dict[int, tuple[Any, dict[str, Any]]] = {}
        self._removed: set[int] = set()
        self._next_id = 0

    def _reset_builder(self) -> None:
        self.reset()

append(state, **kwargs)

Store one encoding recipe and return its stream id.

Source code in src/mifrost/encoders/custom/base.py
365
366
367
368
369
370
371
372
373
374
375
def append(self, state: Any, **kwargs: Any) -> int:
    """Store one encoding recipe and return its stream id."""

    if self._reuse_removed and self._removed:
        stream_id = min(self._removed)
        self._removed.remove(stream_id)
    else:
        stream_id = self._next_id
        self._next_id += 1
    self._items[stream_id] = (state, dict(kwargs))
    return stream_id

update(stream_id, state, **kwargs)

Replace the recipe stored at stream_id.

Source code in src/mifrost/encoders/custom/base.py
377
378
379
380
381
382
def update(self, stream_id: int, state: Any, **kwargs: Any) -> None:
    """Replace the recipe stored at ``stream_id``."""

    if stream_id not in self._items:
        raise KeyError(stream_id)
    self._items[stream_id] = (state, dict(kwargs))

remove(stream_id)

Drop one recipe; its slot is reusable when reuse is enabled.

Source code in src/mifrost/encoders/custom/base.py
384
385
386
387
388
389
390
def remove(self, stream_id: int) -> None:
    """Drop one recipe; its slot is reusable when reuse is enabled."""

    if stream_id not in self._items:
        raise KeyError(stream_id)
    del self._items[stream_id]
    self._removed.add(stream_id)

set_reuse_removed(value)

Enable or disable removed-slot reuse (replace-in-order semantics).

Source code in src/mifrost/encoders/custom/base.py
392
393
394
395
def set_reuse_removed(self, value: bool) -> None:
    """Enable or disable removed-slot reuse (replace-in-order semantics)."""

    self._reuse_removed = bool(value)

flush()

Re-encode every stored recipe in id order as one batch encoding.

Source code in src/mifrost/encoders/custom/base.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def flush(self) -> Any:
    """Re-encode every stored recipe in id order as one batch encoding."""

    if not self._items:
        raise ValueError("cannot flush an empty CustomStream")
    from ... import batch_encodings

    encodings = []
    for key in sorted(self._items):
        recipe_state, recipe_kwargs = self._items[key]
        encodings.append(self.encoder.encode(recipe_state, **recipe_kwargs))
    result = batch_encodings(encodings)
    self.reset()
    return result

reset()

Clear every stored recipe.

Source code in src/mifrost/encoders/custom/base.py
412
413
414
415
416
417
def reset(self) -> None:
    """Clear every stored recipe."""

    self._items: dict[int, tuple[Any, dict[str, Any]]] = {}
    self._removed: set[int] = set()
    self._next_id = 0

Vocabulary

Insertion-ordered bidirectional string-to-id map.

Source code in src/mifrost/encoders/custom/tables.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Vocabulary:
    """Insertion-ordered bidirectional string-to-id map."""

    def __init__(self) -> None:
        self._ids: dict[str, int] = {}
        self._names: list[str] = []
        self._frozen = False

    def id_for(self, name: str) -> int:
        """Return the id of ``name``, auto-extending unless frozen.

        After `freeze` the vocabulary rejects unknown names with ValueError;
        known names keep resolving to their existing ids.
        """

        try:
            found = self._ids.get(name)
        except TypeError:
            name = str(name)
            found = self._ids.get(name)
        if found is not None:
            return found
        if self._frozen:
            raise ValueError(f"vocabulary is frozen; cannot add {name!r}")
        index = len(self._names)
        self._ids[name] = index
        self._names.append(name)
        return index

    def name_for(self, id_: int) -> str:
        """Return the name stored at ``id_``."""

        return self._names[int(id_)]

    def __len__(self) -> int:
        return len(self._names)

    def names(self) -> list[str]:
        """All names in insertion order."""

        return list(self._names)

    def freeze(self) -> None:
        """Forbid future extensions; idempotent."""

        self._frozen = True

id_for(name)

Return the id of name, auto-extending unless frozen.

After freeze the vocabulary rejects unknown names with ValueError; known names keep resolving to their existing ids.

Source code in src/mifrost/encoders/custom/tables.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def id_for(self, name: str) -> int:
    """Return the id of ``name``, auto-extending unless frozen.

    After `freeze` the vocabulary rejects unknown names with ValueError;
    known names keep resolving to their existing ids.
    """

    try:
        found = self._ids.get(name)
    except TypeError:
        name = str(name)
        found = self._ids.get(name)
    if found is not None:
        return found
    if self._frozen:
        raise ValueError(f"vocabulary is frozen; cannot add {name!r}")
    index = len(self._names)
    self._ids[name] = index
    self._names.append(name)
    return index

name_for(id_)

Return the name stored at id_.

Source code in src/mifrost/encoders/custom/tables.py
45
46
47
48
def name_for(self, id_: int) -> str:
    """Return the name stored at ``id_``."""

    return self._names[int(id_)]

names()

All names in insertion order.

Source code in src/mifrost/encoders/custom/tables.py
53
54
55
56
def names(self) -> list[str]:
    """All names in insertion order."""

    return list(self._names)

freeze()

Forbid future extensions; idempotent.

Source code in src/mifrost/encoders/custom/tables.py
58
59
60
61
def freeze(self) -> None:
    """Forbid future extensions; idempotent."""

    self._frozen = True

NodeTable

Interning table mapping hashable node keys to dense row ids.

The FIRST call for a key wins: later calls with the same key return the existing row id and silently ignore any new role, channels or name. This makes repeated lookups (e.g. object nodes touched by many atoms) safe and cheap.

Source code in src/mifrost/encoders/custom/tables.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
class NodeTable:
    """Interning table mapping hashable node keys to dense row ids.

    The FIRST call for a key wins: later calls with the same key return the
    existing row id and silently ignore any new role, channels or name. This
    makes repeated lookups (e.g. object nodes touched by many atoms) safe and
    cheap.
    """

    def __init__(self) -> None:
        self._keys: dict[Any, int] = {}
        self._roles: list[str] = []
        self._channels: list[tuple[int, ...]] = []
        self._names: dict[int, str] = {}
        self._roles_vocabulary = Vocabulary()

    def id_for(
        self,
        key: Hashable,
        *,
        role: str,
        channels: Sequence[int] = (),
        name: str | None = None,
    ) -> int:
        """Intern ``key`` and return its dense row id."""

        found = self._keys.get(key)
        if found is not None:
            return found
        row = len(self._roles)
        self._keys[key] = row
        self._roles.append(str(role))
        self._channels.append(tuple(int(value) for value in channels))
        if name is not None:
            self._names[row] = str(name)
        return row

    @property
    def count(self) -> int:
        """Number of interned rows."""

        return len(self._roles)

    @property
    def channel_dim(self) -> int:
        """Maximum per-row channel count seen; shorter rows are zero-padded."""

        return max((len(channels) for channels in self._channels), default=0)

    @property
    def roles(self) -> list[str]:
        """Role string of each row, in row order."""

        return list(self._roles)

    @property
    def roles_vocabulary(self) -> Vocabulary:
        """Insertion-ordered vocabulary over the distinct roles seen."""

        return self._roles_vocabulary

    def role_ids(self) -> list[int]:
        """Vocabulary id of each row's role, in row order."""

        return [self._roles_vocabulary.id_for(role) for role in self._roles]

    def names(self) -> list[str] | None:
        """Row names in row order, or ``None`` when any row is unnamed."""

        if len(self._names) != len(self._roles):
            return None
        return [self._names[row] for row in range(len(self._roles))]

    def to_float_array(self) -> np.ndarray:
        """Row-major float32 array of shape ``[count, channel_dim]``.

        Nodes added without channels still produce one zero column, so the
        feature dimension never collapses to zero (native builders divide
        by the feature dimension).
        """

        width = self.channel_dim if self.channel_dim > 0 else 1
        rows = np.zeros((self.count, width), dtype=np.float32)
        for row, channels in enumerate(self._channels):
            if channels:
                rows[row, : len(channels)] = channels
        return rows

count property

Number of interned rows.

channel_dim property

Maximum per-row channel count seen; shorter rows are zero-padded.

roles property

Role string of each row, in row order.

roles_vocabulary property

Insertion-ordered vocabulary over the distinct roles seen.

id_for(key, *, role, channels=(), name=None)

Intern key and return its dense row id.

Source code in src/mifrost/encoders/custom/tables.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def id_for(
    self,
    key: Hashable,
    *,
    role: str,
    channels: Sequence[int] = (),
    name: str | None = None,
) -> int:
    """Intern ``key`` and return its dense row id."""

    found = self._keys.get(key)
    if found is not None:
        return found
    row = len(self._roles)
    self._keys[key] = row
    self._roles.append(str(role))
    self._channels.append(tuple(int(value) for value in channels))
    if name is not None:
        self._names[row] = str(name)
    return row

role_ids()

Vocabulary id of each row's role, in row order.

Source code in src/mifrost/encoders/custom/tables.py
125
126
127
128
def role_ids(self) -> list[int]:
    """Vocabulary id of each row's role, in row order."""

    return [self._roles_vocabulary.id_for(role) for role in self._roles]

names()

Row names in row order, or None when any row is unnamed.

Source code in src/mifrost/encoders/custom/tables.py
130
131
132
133
134
135
def names(self) -> list[str] | None:
    """Row names in row order, or ``None`` when any row is unnamed."""

    if len(self._names) != len(self._roles):
        return None
    return [self._names[row] for row in range(len(self._roles))]

to_float_array()

Row-major float32 array of shape [count, channel_dim].

Nodes added without channels still produce one zero column, so the feature dimension never collapses to zero (native builders divide by the feature dimension).

Source code in src/mifrost/encoders/custom/tables.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def to_float_array(self) -> np.ndarray:
    """Row-major float32 array of shape ``[count, channel_dim]``.

    Nodes added without channels still produce one zero column, so the
    feature dimension never collapses to zero (native builders divide
    by the feature dimension).
    """

    width = self.channel_dim if self.channel_dim > 0 else 1
    rows = np.zeros((self.count, width), dtype=np.float32)
    for row, channels in enumerate(self._channels):
        if channels:
            rows[row, : len(channels)] = channels
    return rows

EdgeSink

Accumulator for typed edges with two integer positions each.

Source code in src/mifrost/encoders/custom/tables.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
class EdgeSink:
    """Accumulator for typed edges with two integer positions each."""

    def __init__(self) -> None:
        self._sources: list[int] = []
        self._targets: list[int] = []
        self._kinds: list[tuple[int, int, int]] = []
        self._kind_vocabulary = Vocabulary()

    def add(
        self,
        src: int,
        dst: int,
        kind: str,
        pos_a: int = 0,
        pos_b: int = 0,
    ) -> None:
        """Append one directed edge."""

        self._sources.append(int(src))
        self._targets.append(int(dst))
        known = self._kind_vocabulary._ids.get(kind)
        kind_id = known if known is not None else self._kind_vocabulary.id_for(kind)
        self._kinds.append((kind_id, int(pos_a), int(pos_b)))

    def add_both(
        self,
        src: int,
        dst: int,
        kind_fwd: str,
        kind_bwd: str,
        pos_a: int = 0,
        pos_b: int = 0,
    ) -> None:
        """Add ``(src, dst, kind_fwd, pos_a, pos_b)`` plus its reverse edge."""

        self.add(src, dst, kind_fwd, pos_a, pos_b)
        self.add(dst, src, kind_bwd, pos_b, pos_a)

    def ensure_kinds(self, names: Iterable[str]) -> None:
        """Intern every name in the kind vocabulary without adding edges.

        Encoders that want a state-independent ``vocab_edge_kinds`` (so
        batched graphs of one problem share identical graph attributes)
        pre-seed every kind they may emit, even those a given state never
        uses.
        """

        for name in names:
            self._kind_vocabulary.id_for(name)

    @property
    def kinds(self) -> Vocabulary:
        """Insertion-ordered vocabulary over the distinct edge kinds."""

        return self._kind_vocabulary

    def __len__(self) -> int:
        return len(self._sources)

    def to_arrays(self) -> tuple[np.ndarray, np.ndarray]:
        """Return ``(edge_index int64 [2,E], edge_attr float32 [E,3])``.

        The feature columns are ``(kind_id, pos_a, pos_b)``.
        """

        count = len(self._sources)
        edge_index = np.zeros((2, count), dtype=np.int64)
        if count == 0:
            return edge_index, np.zeros((0, 3), dtype=np.float32)
        edge_index[0] = self._sources
        edge_index[1] = self._targets
        edge_attr = np.array(self._kinds, dtype=np.float32).reshape(count, 3)
        return edge_index, edge_attr

kinds property

Insertion-ordered vocabulary over the distinct edge kinds.

add(src, dst, kind, pos_a=0, pos_b=0)

Append one directed edge.

Source code in src/mifrost/encoders/custom/tables.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def add(
    self,
    src: int,
    dst: int,
    kind: str,
    pos_a: int = 0,
    pos_b: int = 0,
) -> None:
    """Append one directed edge."""

    self._sources.append(int(src))
    self._targets.append(int(dst))
    known = self._kind_vocabulary._ids.get(kind)
    kind_id = known if known is not None else self._kind_vocabulary.id_for(kind)
    self._kinds.append((kind_id, int(pos_a), int(pos_b)))

add_both(src, dst, kind_fwd, kind_bwd, pos_a=0, pos_b=0)

Add (src, dst, kind_fwd, pos_a, pos_b) plus its reverse edge.

Source code in src/mifrost/encoders/custom/tables.py
178
179
180
181
182
183
184
185
186
187
188
189
190
def add_both(
    self,
    src: int,
    dst: int,
    kind_fwd: str,
    kind_bwd: str,
    pos_a: int = 0,
    pos_b: int = 0,
) -> None:
    """Add ``(src, dst, kind_fwd, pos_a, pos_b)`` plus its reverse edge."""

    self.add(src, dst, kind_fwd, pos_a, pos_b)
    self.add(dst, src, kind_bwd, pos_b, pos_a)

ensure_kinds(names)

Intern every name in the kind vocabulary without adding edges.

Encoders that want a state-independent vocab_edge_kinds (so batched graphs of one problem share identical graph attributes) pre-seed every kind they may emit, even those a given state never uses.

Source code in src/mifrost/encoders/custom/tables.py
192
193
194
195
196
197
198
199
200
201
202
def ensure_kinds(self, names: Iterable[str]) -> None:
    """Intern every name in the kind vocabulary without adding edges.

    Encoders that want a state-independent ``vocab_edge_kinds`` (so
    batched graphs of one problem share identical graph attributes)
    pre-seed every kind they may emit, even those a given state never
    uses.
    """

    for name in names:
        self._kind_vocabulary.id_for(name)

to_arrays()

Return (edge_index int64 [2,E], edge_attr float32 [E,3]).

The feature columns are (kind_id, pos_a, pos_b).

Source code in src/mifrost/encoders/custom/tables.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def to_arrays(self) -> tuple[np.ndarray, np.ndarray]:
    """Return ``(edge_index int64 [2,E], edge_attr float32 [E,3])``.

    The feature columns are ``(kind_id, pos_a, pos_b)``.
    """

    count = len(self._sources)
    edge_index = np.zeros((2, count), dtype=np.int64)
    if count == 0:
        return edge_index, np.zeros((0, 3), dtype=np.float32)
    edge_index[0] = self._sources
    edge_index[1] = self._targets
    edge_attr = np.array(self._kinds, dtype=np.float32).reshape(count, 3)
    return edge_index, edge_attr

assert_backend_parity(make_encoder, cases)

Assert byte-identical encodings across backends for the same PDDL.

cases yields (source, states) pairs — one per backend (pymimir problem + pymimir states, pytyr task + the corresponding pytyr states; states are backend-native and not interchangeable). make_encoder builds the encoder from a source. Encodings are compared via their canonical dumps() serialization, so any tensor or metadata difference fails the assertion.

Raises :class:ValueError when fewer than two distinct backend names occur among the cases — comparing an encoder against itself is a no-op, not parity.

Source code in src/mifrost/encoders/custom/harness.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def assert_backend_parity(
    make_encoder: Callable[[Any], Any],
    cases: Iterable[tuple[Any, Iterable[Any]]],
) -> None:
    """Assert byte-identical encodings across backends for the same PDDL.

    ``cases`` yields ``(source, states)`` pairs — one per backend (pymimir
    problem + pymimir states, pytyr task + the corresponding pytyr states;
    states are backend-native and not interchangeable). ``make_encoder``
    builds the encoder from a source. Encodings are compared via their
    canonical ``dumps()`` serialization, so any tensor or metadata
    difference fails the assertion.

    Raises :class:`ValueError` when fewer than two *distinct* backend names
    occur among the cases — comparing an encoder against itself is a
    no-op, not parity.
    """

    dumps_per_backend: dict[str, list[bytes]] = {}
    for source, states in cases:
        encoder = make_encoder(source)
        backend = getattr(encoder, "backend", "unknown")
        dumps_per_backend[backend] = [encoder.encode(state).dumps() for state in states]
    if len(dumps_per_backend) < 2:
        raise ValueError(
            "assert_backend_parity needs at least two distinct backends "
            f"among the cases, got {sorted(dumps_per_backend)!r}"
        )
    reference = None
    for backend, dumps in sorted(dumps_per_backend.items()):
        if reference is None:
            reference = dumps
            continue
        for index, (left, right) in enumerate(zip(reference, dumps, strict=True)):
            if left != right:
                raise AssertionError(
                    f"backend parity failure for {backend!r} on state {index}"
                )

channel_summary(data)

Return a small human-readable summary of one derived-style graph.

Source code in src/mifrost/encoders/custom/harness.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def channel_summary(data: Any) -> dict[str, Any]:
    """Return a small human-readable summary of one derived-style graph."""

    summary: dict[str, Any] = {}
    x_ids = getattr(data, "x_ids", None)
    if isinstance(x_ids, torch.Tensor):
        summary["nodes"] = int(x_ids.size(0))
        summary["channels"] = int(x_ids.size(1))
        summary["roles"] = sorted({int(value) for value in x_ids[:, 0].tolist()})
    edge_index = getattr(data, "edge_index", None)
    if isinstance(edge_index, torch.Tensor):
        summary["edges"] = int(edge_index.size(1))
    edge_attr = getattr(data, "edge_attr", None)
    if isinstance(edge_attr, torch.Tensor) and edge_attr.numel() > 0:
        summary["edge_kinds"] = sorted(
            {int(value) for value in edge_attr[:, 0].tolist()}
        )
    for extra in ("hyperedge_index", "tuple_args", "spd_src"):
        tensor = getattr(data, extra, None)
        if isinstance(tensor, torch.Tensor):
            summary[extra] = (
                int(tensor.shape[-1]) if tensor.dim() else int(tensor.numel())
            )
    return summary

conformance_smoke(data, *, hidden_channels=8, with_edge_attr=True)

Run GCNConv and GATv2Conv forward+backward on one encoded graph.

Skips cleanly (returns {"skipped": reason}) when torch_geometric is unavailable; raises AssertionError on non-finite outputs or missing gradients, mirroring the repository conformance suite.

Source code in src/mifrost/encoders/custom/harness.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def conformance_smoke(
    data: Any,
    *,
    hidden_channels: int = 8,
    with_edge_attr: bool = True,
) -> dict[str, Any]:
    """Run GCNConv and GATv2Conv forward+backward on one encoded graph.

    Skips cleanly (returns ``{"skipped": reason}``) when torch_geometric is
    unavailable; raises AssertionError on non-finite outputs or missing
    gradients, mirroring the repository conformance suite.
    """

    try:
        import torch_geometric  # noqa: F401
        from torch_geometric.nn import GATv2Conv, GCNConv
    except ImportError as exc:
        return {"skipped": f"torch_geometric unavailable: {exc}"}

    torch = _torch()
    torch.manual_seed(0)
    x = data.x_ids.float() if hasattr(data, "x_ids") else data.x.float()
    results: dict[str, Any] = {}
    edge_attr = (
        data.edge_attr.float()
        if with_edge_attr and getattr(data, "edge_attr", None) is not None
        else None
    )
    for name, layer in (
        ("gcn", GCNConv(x.size(1), hidden_channels)),
        (
            "gatv2",
            GATv2Conv(x.size(1), hidden_channels, edge_dim=edge_attr.size(1))
            if edge_attr is not None
            else GATv2Conv(x.size(1), hidden_channels),
        ),
    ):
        out = (
            layer(x, data.edge_index, edge_attr)
            if edge_attr is not None and name == "gatv2"
            else layer(x, data.edge_index)
        )
        loss = out.square().mean()
        loss.backward()
        grads = [p.grad for p in layer.parameters() if p.grad is not None]
        if not grads or not all(torch.isfinite(g).all() for g in grads):
            raise AssertionError(f"{name} backward produced no finite gradients")
        if not torch.isfinite(out).all():
            raise AssertionError(f"{name} produced non-finite outputs")
        results[name] = int(out.size(-1))
    return results