Skip to content

LiftedTaskEncoder

LiftedTaskEncoder

Bases: CustomGraphEncoder

Schema-level task graph over objects, predicates and lifted actions.

One node per object, predicate schema, action schema and action parameter, wired by lifted precondition/effect/goal edges (see module docstring for channel and edge tables). The input must be a problem (a pymimir.Problem or pytyr PlanningTask); states are passed to encode / encode_batch and ignored unless include_state_facts=True.

Source code in src/mifrost/encoders/lifted.py
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
class LiftedTaskEncoder(CustomGraphEncoder):
    """Schema-level task graph over objects, predicates and lifted actions.

    One node per object, predicate schema, action schema and action
    parameter, wired by lifted precondition/effect/goal edges (see module
    docstring for channel and edge tables). The input must be a *problem*
    (a ``pymimir.Problem`` or pytyr ``PlanningTask``); states are passed to
    `encode` / `encode_batch` and ignored unless
    ``include_state_facts=True``.
    """

    def __init__(
        self,
        problem_or_task: Any,
        *,
        include_parameters: bool = True,
        include_goal: bool = True,
        include_state_facts: bool = False,
        export_node_names: bool = True,
        backend: str | None = None,
    ) -> None:
        """Create one lifted task-structure encoder for one problem/task."""

        super().__init__(
            problem_or_task,
            export_node_names=export_node_names,
            backend=backend,
        )
        self.include_parameters = bool(include_parameters)
        self.include_goal = bool(include_goal)
        self.include_state_facts = bool(include_state_facts)

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

        return LiftedTaskEncoderStream(self)

    def _node_universe(self, view: Any, state: Any) -> list[str]:
        """Problem objects followed by domain constants, extras sorted.

        ``StateView.objects`` covers problem objects only; PDDL domain
        constants are invisible there yet appear as arguments of goal
        literals and facts. Scan exactly the literals this encoder will
        wire (goal literals when `include_goal`, static plus state facts
        when `include_state_facts`) and append their unknown names — the
        domain constants — after the objects, sorted.
        """

        objects = view.objects
        known = set(objects)
        constants: set[str] = set()
        if self.include_goal:
            for literal in view.goal_literals(state):
                constants.update(
                    argument for argument in literal.atom.args if argument not in known
                )
        if self.include_state_facts:
            for atom in (*view.static_facts, *view.state_facts(state)):
                constants.update(
                    argument for argument in atom.args if argument not in known
                )
        return [*objects, *sorted(constants)]

    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 the problem's lifted task graph into ``out``."""

        del kwargs
        encoder_name = type(self).__name__
        if goals is not None:
            raise ValueError(
                f"{encoder_name} derives goals from the problem itself via "
                "StateView.goal_literals; got an explicit goals lane"
            )
        if actions:
            raise ValueError(
                f"{encoder_name} encodes lifted task structure only; got a "
                "non-empty actions lane"
            )
        if subgoal_layers:
            raise ValueError(
                f"{encoder_name} encodes lifted task structure only; got "
                "non-empty subgoal_layers lane"
            )
        if history_subgoals:
            raise ValueError(
                f"{encoder_name} encodes lifted task structure only; got "
                "non-empty history_subgoals lane"
            )
        if history_max_steps is not None:
            raise ValueError(
                f"{encoder_name} encodes lifted task structure only; got "
                f"history_max_steps={history_max_steps!r}"
            )

        view = out.view
        predicates = out.vocabulary("predicates")
        for info in view.predicates:
            predicates.id_for(info.name)
        action_vocab = out.vocabulary("actions")
        for info in view.action_schemas:
            action_vocab.id_for(info.name)

        # Pre-seed every edge kind this encoder may emit under its flags, so
        # vocab_edge_kinds is problem-scoped and state-independent: batches
        # of graphs from one domain share identical graph attributes.
        edge_kinds = ["pre", "eff_add", "eff_del"]
        if self.include_parameters:
            edge_kinds += ["param_of", "pre_arg", "eff_add_arg", "eff_del_arg"]
        if self.include_goal:
            edge_kinds += ["goal_pos", "goal_neg"]
        if self.include_state_facts:
            edge_kinds.append("fact")
        out.edges.ensure_kinds(edge_kinds)

        object_ids = {
            name: out.add_node(
                ("object", name),
                role="object",
                channels=(0, 0, 0, 0, 0),
                name=name,
            )
            for name in self._node_universe(view, state)
        }

        predicate_ids: dict[str, int] = {}
        for info in view.predicates:
            predicate_ids[info.name] = out.add_node(
                ("predicate", info.name),
                role="predicate",
                channels=(
                    1,
                    predicates.id_for(info.name) + 1,
                    info.arity,
                    0,
                    _CATEGORY_IDS[info.category],
                ),
                name=info.name,
            )

        # ``action_schemas`` is name-unique, whereas disjunctive preconditions
        # are flattened by StateView into several same-named structures. Keep
        # the canonical structural order and add an occurrence discriminator to
        # every action/parameter identity so no flattened branch overwrites a
        # previous node.
        action_records: list[tuple[ActionStructure, int]] = []
        occurrences: dict[tuple[str, int], int] = {}
        for structure in view.action_structures():
            schema_key = (structure.name, structure.arity)
            occurrence = occurrences.get(schema_key, 0)
            occurrences[schema_key] = occurrence + 1
            action_records.append((structure, occurrence))

        action_ids: list[int] = []
        for structure, occurrence in action_records:
            action_ids.append(
                out.add_node(
                    ("action", structure.name, structure.arity, occurrence),
                    role="action",
                    channels=(
                        2,
                        action_vocab.id_for(structure.name) + 1,
                        len(structure.parameters),
                        0,
                        0,
                    ),
                    name=structure.name,
                )
            )

        add_edge = out.add_edge
        for (structure, occurrence), action_id in zip(
            action_records, action_ids, strict=True
        ):
            parameter_ids: list[int] | None = None
            if self.include_parameters:
                parameter_ids = []
                schema_id = action_vocab.id_for(structure.name) + 1
                for index, parameter_name in enumerate(structure.parameters):
                    parameter_ids.append(
                        out.add_node(
                            (
                                "parameter",
                                structure.name,
                                structure.arity,
                                occurrence,
                                index,
                            ),
                            role="parameter",
                            channels=(3, schema_id, index, 0, 0),
                            name=f"{structure.name}{parameter_name}",
                        )
                    )
                    add_edge(parameter_ids[-1], action_id, "param_of", pos_a=index)
            for literal in structure.precondition:
                predicate_id = predicate_ids[literal.atom.predicate]
                add_edge(predicate_id, action_id, "pre")
                if parameter_ids is not None:
                    _add_argument_edges(
                        add_edge,
                        parameter_ids,
                        predicate_id,
                        literal.atom.args,
                        "pre_arg",
                    )
            next_conditional_group = 1
            for effect in structure.effects:
                if effect.condition:
                    group_index = next_conditional_group
                    next_conditional_group += 1
                    for literal in effect.condition:
                        add_edge(
                            predicate_ids[literal.atom.predicate],
                            action_id,
                            "eff_cond",
                            pos_a=group_index,
                        )
                else:
                    group_index = 0
                for literal in effect.literals:
                    kind = "eff_add" if literal.positive else "eff_del"
                    predicate_id = predicate_ids[literal.atom.predicate]
                    add_edge(predicate_id, action_id, kind, pos_a=group_index)
                    if parameter_ids is not None:
                        _add_argument_edges(
                            add_edge,
                            parameter_ids,
                            predicate_id,
                            literal.atom.args,
                            f"{kind}_arg",
                        )

        if self.include_goal:
            for literal in view.goal_literals(state):
                kind = "goal_pos" if literal.positive else "goal_neg"
                predicate_id = predicate_ids[literal.atom.predicate]
                if not literal.atom.args:
                    # Arity-0 goal: no argument edges exist, so anchor the
                    # literal as a self-loop on the predicate node.
                    add_edge(predicate_id, predicate_id, kind)
                    continue
                for position, argument in enumerate(literal.atom.args):
                    add_edge(predicate_id, object_ids[argument], kind, pos_a=position)

        if self.include_state_facts:
            for atom in (*view.static_facts, *view.state_facts(state)):
                predicate_id = predicate_ids[atom.predicate]
                if not atom.args:
                    # Arity-0 fact: self-loop on the predicate node.
                    add_edge(predicate_id, predicate_id, "fact")
                    continue
                for position, argument in enumerate(atom.args):
                    add_edge(predicate_id, object_ids[argument], "fact", pos_a=position)

        out.set_attr("vocab_roles", list(ROLE_NAMES))
        out.set_attr("vocab_categories", list(CATEGORY_NAMES))
        out.set_attr("include_parameters", int(self.include_parameters))
        out.set_attr("include_goal", int(self.include_goal))
        out.set_attr("include_state_facts", int(self.include_state_facts))
        out.set_vocab_attr("predicates")
        out.set_vocab_attr("actions")
        out.set_flag("include_reverse_edges", True)

__init__(problem_or_task, *, include_parameters=True, include_goal=True, include_state_facts=False, export_node_names=True, backend=None)

Create one lifted task-structure encoder for one problem/task.

Source code in src/mifrost/encoders/lifted.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def __init__(
    self,
    problem_or_task: Any,
    *,
    include_parameters: bool = True,
    include_goal: bool = True,
    include_state_facts: bool = False,
    export_node_names: bool = True,
    backend: str | None = None,
) -> None:
    """Create one lifted task-structure encoder for one problem/task."""

    super().__init__(
        problem_or_task,
        export_node_names=export_node_names,
        backend=backend,
    )
    self.include_parameters = bool(include_parameters)
    self.include_goal = bool(include_goal)
    self.include_state_facts = bool(include_state_facts)

stream()

Create a pure-Python streaming variant of this encoder.

Source code in src/mifrost/encoders/lifted.py
132
133
134
135
def stream(self) -> LiftedTaskEncoderStream:
    """Create a pure-Python streaming variant of this encoder."""

    return LiftedTaskEncoderStream(self)

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

Draw the problem's lifted task graph into out.

Source code in src/mifrost/encoders/lifted.py
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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 the problem's lifted task graph into ``out``."""

    del kwargs
    encoder_name = type(self).__name__
    if goals is not None:
        raise ValueError(
            f"{encoder_name} derives goals from the problem itself via "
            "StateView.goal_literals; got an explicit goals lane"
        )
    if actions:
        raise ValueError(
            f"{encoder_name} encodes lifted task structure only; got a "
            "non-empty actions lane"
        )
    if subgoal_layers:
        raise ValueError(
            f"{encoder_name} encodes lifted task structure only; got "
            "non-empty subgoal_layers lane"
        )
    if history_subgoals:
        raise ValueError(
            f"{encoder_name} encodes lifted task structure only; got "
            "non-empty history_subgoals lane"
        )
    if history_max_steps is not None:
        raise ValueError(
            f"{encoder_name} encodes lifted task structure only; got "
            f"history_max_steps={history_max_steps!r}"
        )

    view = out.view
    predicates = out.vocabulary("predicates")
    for info in view.predicates:
        predicates.id_for(info.name)
    action_vocab = out.vocabulary("actions")
    for info in view.action_schemas:
        action_vocab.id_for(info.name)

    # Pre-seed every edge kind this encoder may emit under its flags, so
    # vocab_edge_kinds is problem-scoped and state-independent: batches
    # of graphs from one domain share identical graph attributes.
    edge_kinds = ["pre", "eff_add", "eff_del"]
    if self.include_parameters:
        edge_kinds += ["param_of", "pre_arg", "eff_add_arg", "eff_del_arg"]
    if self.include_goal:
        edge_kinds += ["goal_pos", "goal_neg"]
    if self.include_state_facts:
        edge_kinds.append("fact")
    out.edges.ensure_kinds(edge_kinds)

    object_ids = {
        name: out.add_node(
            ("object", name),
            role="object",
            channels=(0, 0, 0, 0, 0),
            name=name,
        )
        for name in self._node_universe(view, state)
    }

    predicate_ids: dict[str, int] = {}
    for info in view.predicates:
        predicate_ids[info.name] = out.add_node(
            ("predicate", info.name),
            role="predicate",
            channels=(
                1,
                predicates.id_for(info.name) + 1,
                info.arity,
                0,
                _CATEGORY_IDS[info.category],
            ),
            name=info.name,
        )

    # ``action_schemas`` is name-unique, whereas disjunctive preconditions
    # are flattened by StateView into several same-named structures. Keep
    # the canonical structural order and add an occurrence discriminator to
    # every action/parameter identity so no flattened branch overwrites a
    # previous node.
    action_records: list[tuple[ActionStructure, int]] = []
    occurrences: dict[tuple[str, int], int] = {}
    for structure in view.action_structures():
        schema_key = (structure.name, structure.arity)
        occurrence = occurrences.get(schema_key, 0)
        occurrences[schema_key] = occurrence + 1
        action_records.append((structure, occurrence))

    action_ids: list[int] = []
    for structure, occurrence in action_records:
        action_ids.append(
            out.add_node(
                ("action", structure.name, structure.arity, occurrence),
                role="action",
                channels=(
                    2,
                    action_vocab.id_for(structure.name) + 1,
                    len(structure.parameters),
                    0,
                    0,
                ),
                name=structure.name,
            )
        )

    add_edge = out.add_edge
    for (structure, occurrence), action_id in zip(
        action_records, action_ids, strict=True
    ):
        parameter_ids: list[int] | None = None
        if self.include_parameters:
            parameter_ids = []
            schema_id = action_vocab.id_for(structure.name) + 1
            for index, parameter_name in enumerate(structure.parameters):
                parameter_ids.append(
                    out.add_node(
                        (
                            "parameter",
                            structure.name,
                            structure.arity,
                            occurrence,
                            index,
                        ),
                        role="parameter",
                        channels=(3, schema_id, index, 0, 0),
                        name=f"{structure.name}{parameter_name}",
                    )
                )
                add_edge(parameter_ids[-1], action_id, "param_of", pos_a=index)
        for literal in structure.precondition:
            predicate_id = predicate_ids[literal.atom.predicate]
            add_edge(predicate_id, action_id, "pre")
            if parameter_ids is not None:
                _add_argument_edges(
                    add_edge,
                    parameter_ids,
                    predicate_id,
                    literal.atom.args,
                    "pre_arg",
                )
        next_conditional_group = 1
        for effect in structure.effects:
            if effect.condition:
                group_index = next_conditional_group
                next_conditional_group += 1
                for literal in effect.condition:
                    add_edge(
                        predicate_ids[literal.atom.predicate],
                        action_id,
                        "eff_cond",
                        pos_a=group_index,
                    )
            else:
                group_index = 0
            for literal in effect.literals:
                kind = "eff_add" if literal.positive else "eff_del"
                predicate_id = predicate_ids[literal.atom.predicate]
                add_edge(predicate_id, action_id, kind, pos_a=group_index)
                if parameter_ids is not None:
                    _add_argument_edges(
                        add_edge,
                        parameter_ids,
                        predicate_id,
                        literal.atom.args,
                        f"{kind}_arg",
                    )

    if self.include_goal:
        for literal in view.goal_literals(state):
            kind = "goal_pos" if literal.positive else "goal_neg"
            predicate_id = predicate_ids[literal.atom.predicate]
            if not literal.atom.args:
                # Arity-0 goal: no argument edges exist, so anchor the
                # literal as a self-loop on the predicate node.
                add_edge(predicate_id, predicate_id, kind)
                continue
            for position, argument in enumerate(literal.atom.args):
                add_edge(predicate_id, object_ids[argument], kind, pos_a=position)

    if self.include_state_facts:
        for atom in (*view.static_facts, *view.state_facts(state)):
            predicate_id = predicate_ids[atom.predicate]
            if not atom.args:
                # Arity-0 fact: self-loop on the predicate node.
                add_edge(predicate_id, predicate_id, "fact")
                continue
            for position, argument in enumerate(atom.args):
                add_edge(predicate_id, object_ids[argument], "fact", pos_a=position)

    out.set_attr("vocab_roles", list(ROLE_NAMES))
    out.set_attr("vocab_categories", list(CATEGORY_NAMES))
    out.set_attr("include_parameters", int(self.include_parameters))
    out.set_attr("include_goal", int(self.include_goal))
    out.set_attr("include_state_facts", int(self.include_state_facts))
    out.set_vocab_attr("predicates")
    out.set_vocab_attr("actions")
    out.set_flag("include_reverse_edges", True)