Skip to content

ObjectFeatureEncoder

ObjectFeatureEncoder

Bases: CustomGraphEncoder

Objects-only state graph with unary predicates as feature channels.

One node per domain object; facts of arity >= 2 wire the object nodes together according to expansion while unary predicates become per-object integer-id channels (see module docstring for the layout).

The input must be a problem (a pymimir.Problem or a pytyr PlanningTask); states are passed to encode / encode_batch.

last_nullary_count reports how many nullary facts the most recent encode_state call skipped ("last encode wins"): it is per-state scratch, not an aggregate — reading it after a batch or stream flush yields the count of whichever state was encoded last, so capture it right after encoding the state you care about.

Source code in src/mifrost/encoders/object_feature.py
 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
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
class ObjectFeatureEncoder(CustomGraphEncoder):
    """Objects-only state graph with unary predicates as feature channels.

    One node per domain object; facts of arity >= 2 wire the object nodes
    together according to ``expansion`` while unary predicates become
    per-object integer-id channels (see module docstring for the layout).

    The input must be a *problem* (a ``pymimir.Problem`` or a pytyr
    ``PlanningTask``); states are passed to `encode` / `encode_batch`.

    ``last_nullary_count`` reports how many nullary facts the most recent
    `encode_state` call skipped ("last encode wins"): it is per-state
    scratch, not an aggregate — reading it after a batch or stream flush
    yields the count of whichever state was encoded last, so capture it
    right after encoding the state you care about.
    """

    def __init__(
        self,
        problem_or_task: Any,
        *,
        expansion: str = "clique",
        include_unary_features: bool = True,
        include_participation_counts: bool = False,
        include_goal_flags: bool = False,
        export_node_names: bool = True,
        backend: str | None = None,
    ) -> None:
        """Create one objects-only feature encoder for one problem/task."""

        if expansion not in EXPANSIONS:
            raise ValueError(
                f"expansion must be one of {list(EXPANSIONS)}, got {expansion!r}"
            )
        super().__init__(
            problem_or_task,
            export_node_names=export_node_names,
            backend=backend,
        )
        self.expansion = expansion
        self.include_unary_features = include_unary_features
        self.include_participation_counts = include_participation_counts
        self.include_goal_flags = include_goal_flags
        self.last_nullary_count = 0
        # Schema-derived invariants of this problem, hoisted out of encode_state.
        self._predicate_names: tuple[str, ...] | None = None
        self._unary_names: tuple[str, ...] = ()
        self._non_unary_names: tuple[str, ...] = ()

    def _hoist_schema(self) -> None:
        """Cache predicate partitions once; ids follow view.predicates order."""

        if self._predicate_names is not None:
            return
        view = self.view
        self._predicate_names = tuple(info.name for info in view.predicates)
        self._unary_names = tuple(
            info.name for info in view.predicates if info.arity == 1
        )
        self._non_unary_names = tuple(
            info.name for info in view.predicates if info.arity != 1
        )

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

        return ObjectFeatureEncoderStream(self)

    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 objects-only feature graph into ``out``."""

        del kwargs
        encoder_name = type(self).__name__
        if actions:
            raise ValueError(
                f"{encoder_name} encodes states only; got a non-empty actions lane"
            )
        if subgoal_layers:
            raise ValueError(
                f"{encoder_name} encodes states only; got non-empty subgoal_layers lane"
            )
        if history_subgoals:
            raise ValueError(
                f"{encoder_name} encodes states only; got non-empty "
                "history_subgoals lane"
            )
        if history_max_steps is not None:
            raise ValueError(
                f"{encoder_name} encodes states only; got "
                f"history_max_steps={history_max_steps!r}"
            )

        self._hoist_schema()
        view = out.view
        include_unary = self.include_unary_features
        include_counts = self.include_participation_counts
        include_goals = self.include_goal_flags

        # Seed the writer's vocabulary in view.predicates order exactly as the
        # per-state id_for loop did, so every channel id stays identical.
        predicates = out.vocabulary("predicates")
        predicate_names = self._predicate_names
        assert predicate_names is not None  # guaranteed by _hoist_schema above
        for name in predicate_names:
            predicates.id_for(name)
        id_of_predicate = predicates._ids

        facts: tuple[Atom, ...] = (*view.static_facts, *view.state_facts(state))
        literals = view.goal_literals(state) if goals is None else tuple(goals)

        known_objects = set(view.objects)
        unknown_arguments = sorted(
            {
                argument
                for atom in facts
                for argument in atom.args
                if argument not in known_objects
            }
            | {
                argument
                for literal in literals
                for argument in literal.atom.args
                if argument not in known_objects
            }
        )
        if unknown_arguments:
            raise ValueError(
                f"{encoder_name} cannot encode domain constant or unknown object "
                f"references {unknown_arguments!r}; use LiftedTaskEncoder for "
                "constant-aware task graphs"
            )

        unary_holds: dict[str, set[str]] = {}
        counts: Counter[tuple[str, str]] = Counter()
        nullary_count = 0
        for atom in facts:
            args = atom.args
            arity = len(args)
            if arity == 0:
                nullary_count += 1
                continue
            if arity == 1 and include_unary:
                bucket = unary_holds.get(atom.predicate)
                if bucket is None:
                    unary_holds[atom.predicate] = {args[0]}
                else:
                    bucket.add(args[0])
            elif arity > 1:
                if not include_counts:
                    continue
                predicate = atom.predicate
                for arg in args:
                    counts[(predicate, arg)] += 1
        self.last_nullary_count = nullary_count

        goal_objects = {arg for literal in literals for arg in literal.atom.args}

        objects = view.objects
        empty_set: frozenset[str] = frozenset()
        unary_ids = (
            [id_of_predicate[name] + 1 for name in self._unary_names]
            if include_unary
            else ()
        )
        channels: list[list[int]] = []
        add_channel_row = channels.append
        for name in objects:
            row = [0]
            if include_unary:
                for base_id, unary_name in zip(unary_ids, self._unary_names):
                    row.append(
                        base_id if name in unary_holds.get(unary_name, empty_set) else 0
                    )
            if include_counts:
                row.extend(
                    counts.get((info, name), 0) for info in self._non_unary_names
                )
            if include_goals:
                row.append(1 if name in goal_objects else 0)
            add_channel_row(row)

        object_ids = {
            name: out.add_node(
                (_ROLE_OBJECT, name),
                role=_ROLE_OBJECT,
                channels=row,
                name=name,
            )
            for name, row in zip(objects, channels)
        }

        expansion = self.expansion
        # Pre-seed both expansion kinds so vocab_edge_kinds is identical for
        # every state of one problem — even states without any arity>=2
        # fact — keeping batched graph attributes collision-free.
        out.edges.ensure_kinds((f"{expansion}_fwd", f"{expansion}_bwd"))
        add_both = out.add_both
        clique_kinds = ("clique_fwd", "clique_bwd")
        chain_kinds = ("chain_fwd", "chain_bwd")
        star_kinds = ("star_first_fwd", "star_first_bwd")
        for atom in facts:
            args = atom.args
            if len(args) < 2:
                continue
            ids = [object_ids[arg] for arg in args]
            if expansion == "clique":
                kinds = clique_kinds
                count = len(ids)
                for i in range(count):
                    src = ids[i]
                    for j in range(i + 1, count):
                        add_both(src, ids[j], *kinds, pos_a=i, pos_b=j)
            elif expansion == "chain":
                kinds = chain_kinds
                for i in range(len(ids) - 1):
                    add_both(ids[i], ids[i + 1], *kinds, pos_a=i, pos_b=i + 1)
            else:
                kinds = star_kinds
                first = ids[0]
                for j in range(1, len(ids)):
                    add_both(first, ids[j], *kinds, pos_a=0, pos_b=j)

        out.set_vocab_attr("predicates")
        out.set_flag("include_reverse_edges", True)

__init__(problem_or_task, *, expansion='clique', include_unary_features=True, include_participation_counts=False, include_goal_flags=False, export_node_names=True, backend=None)

Create one objects-only feature encoder for one problem/task.

Source code in src/mifrost/encoders/object_feature.py
 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
def __init__(
    self,
    problem_or_task: Any,
    *,
    expansion: str = "clique",
    include_unary_features: bool = True,
    include_participation_counts: bool = False,
    include_goal_flags: bool = False,
    export_node_names: bool = True,
    backend: str | None = None,
) -> None:
    """Create one objects-only feature encoder for one problem/task."""

    if expansion not in EXPANSIONS:
        raise ValueError(
            f"expansion must be one of {list(EXPANSIONS)}, got {expansion!r}"
        )
    super().__init__(
        problem_or_task,
        export_node_names=export_node_names,
        backend=backend,
    )
    self.expansion = expansion
    self.include_unary_features = include_unary_features
    self.include_participation_counts = include_participation_counts
    self.include_goal_flags = include_goal_flags
    self.last_nullary_count = 0
    # Schema-derived invariants of this problem, hoisted out of encode_state.
    self._predicate_names: tuple[str, ...] | None = None
    self._unary_names: tuple[str, ...] = ()
    self._non_unary_names: tuple[str, ...] = ()

stream()

Create a pure-Python streaming variant of this encoder.

Source code in src/mifrost/encoders/object_feature.py
118
119
120
121
def stream(self) -> ObjectFeatureEncoderStream:
    """Create a pure-Python streaming variant of this encoder."""

    return ObjectFeatureEncoderStream(self)

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

Draw one state's objects-only feature graph into out.

Source code in src/mifrost/encoders/object_feature.py
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
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 objects-only feature graph into ``out``."""

    del kwargs
    encoder_name = type(self).__name__
    if actions:
        raise ValueError(
            f"{encoder_name} encodes states only; got a non-empty actions lane"
        )
    if subgoal_layers:
        raise ValueError(
            f"{encoder_name} encodes states only; got non-empty subgoal_layers lane"
        )
    if history_subgoals:
        raise ValueError(
            f"{encoder_name} encodes states only; got non-empty "
            "history_subgoals lane"
        )
    if history_max_steps is not None:
        raise ValueError(
            f"{encoder_name} encodes states only; got "
            f"history_max_steps={history_max_steps!r}"
        )

    self._hoist_schema()
    view = out.view
    include_unary = self.include_unary_features
    include_counts = self.include_participation_counts
    include_goals = self.include_goal_flags

    # Seed the writer's vocabulary in view.predicates order exactly as the
    # per-state id_for loop did, so every channel id stays identical.
    predicates = out.vocabulary("predicates")
    predicate_names = self._predicate_names
    assert predicate_names is not None  # guaranteed by _hoist_schema above
    for name in predicate_names:
        predicates.id_for(name)
    id_of_predicate = predicates._ids

    facts: tuple[Atom, ...] = (*view.static_facts, *view.state_facts(state))
    literals = view.goal_literals(state) if goals is None else tuple(goals)

    known_objects = set(view.objects)
    unknown_arguments = sorted(
        {
            argument
            for atom in facts
            for argument in atom.args
            if argument not in known_objects
        }
        | {
            argument
            for literal in literals
            for argument in literal.atom.args
            if argument not in known_objects
        }
    )
    if unknown_arguments:
        raise ValueError(
            f"{encoder_name} cannot encode domain constant or unknown object "
            f"references {unknown_arguments!r}; use LiftedTaskEncoder for "
            "constant-aware task graphs"
        )

    unary_holds: dict[str, set[str]] = {}
    counts: Counter[tuple[str, str]] = Counter()
    nullary_count = 0
    for atom in facts:
        args = atom.args
        arity = len(args)
        if arity == 0:
            nullary_count += 1
            continue
        if arity == 1 and include_unary:
            bucket = unary_holds.get(atom.predicate)
            if bucket is None:
                unary_holds[atom.predicate] = {args[0]}
            else:
                bucket.add(args[0])
        elif arity > 1:
            if not include_counts:
                continue
            predicate = atom.predicate
            for arg in args:
                counts[(predicate, arg)] += 1
    self.last_nullary_count = nullary_count

    goal_objects = {arg for literal in literals for arg in literal.atom.args}

    objects = view.objects
    empty_set: frozenset[str] = frozenset()
    unary_ids = (
        [id_of_predicate[name] + 1 for name in self._unary_names]
        if include_unary
        else ()
    )
    channels: list[list[int]] = []
    add_channel_row = channels.append
    for name in objects:
        row = [0]
        if include_unary:
            for base_id, unary_name in zip(unary_ids, self._unary_names):
                row.append(
                    base_id if name in unary_holds.get(unary_name, empty_set) else 0
                )
        if include_counts:
            row.extend(
                counts.get((info, name), 0) for info in self._non_unary_names
            )
        if include_goals:
            row.append(1 if name in goal_objects else 0)
        add_channel_row(row)

    object_ids = {
        name: out.add_node(
            (_ROLE_OBJECT, name),
            role=_ROLE_OBJECT,
            channels=row,
            name=name,
        )
        for name, row in zip(objects, channels)
    }

    expansion = self.expansion
    # Pre-seed both expansion kinds so vocab_edge_kinds is identical for
    # every state of one problem — even states without any arity>=2
    # fact — keeping batched graph attributes collision-free.
    out.edges.ensure_kinds((f"{expansion}_fwd", f"{expansion}_bwd"))
    add_both = out.add_both
    clique_kinds = ("clique_fwd", "clique_bwd")
    chain_kinds = ("chain_fwd", "chain_bwd")
    star_kinds = ("star_first_fwd", "star_first_bwd")
    for atom in facts:
        args = atom.args
        if len(args) < 2:
            continue
        ids = [object_ids[arg] for arg in args]
        if expansion == "clique":
            kinds = clique_kinds
            count = len(ids)
            for i in range(count):
                src = ids[i]
                for j in range(i + 1, count):
                    add_both(src, ids[j], *kinds, pos_a=i, pos_b=j)
        elif expansion == "chain":
            kinds = chain_kinds
            for i in range(len(ids) - 1):
                add_both(ids[i], ids[i + 1], *kinds, pos_a=i, pos_b=i + 1)
        else:
            kinds = star_kinds
            first = ids[0]
            for j in range(1, len(ids)):
                add_both(first, ids[j], *kinds, pos_a=0, pos_b=j)

    out.set_vocab_attr("predicates")
    out.set_flag("include_reverse_edges", True)