forked from Learning-and-Intelligent-Systems/predicators
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstructs.py
More file actions
1570 lines (1288 loc) · 56.7 KB
/
structs.py
File metadata and controls
1570 lines (1288 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Structs used throughout the codebase."""
from __future__ import annotations
import abc
from dataclasses import dataclass, field
from functools import cached_property, lru_cache
from typing import Any, Callable, Collection, DefaultDict, Dict, Iterator, \
List, Optional, Sequence, Set, Tuple, TypeVar, Union, cast
import numpy as np
from gym.spaces import Box
from numpy.typing import NDArray
from tabulate import tabulate
from predicators.settings import CFG
@dataclass(frozen=True, order=True)
class Type:
"""Struct defining a type."""
name: str
feature_names: Sequence[str] = field(repr=False)
parent: Optional[Type] = field(default=None, repr=False)
@property
def dim(self) -> int:
"""Dimensionality of the feature vector of this object type."""
return len(self.feature_names)
def __call__(self, name: str) -> _TypedEntity:
"""Convenience method for generating _TypedEntities."""
if name.startswith("?"):
return Variable(name, self)
return Object(name, self)
def __hash__(self) -> int:
return hash((self.name, tuple(self.feature_names)))
@dataclass(frozen=True, order=True, repr=False)
class _TypedEntity:
"""Struct defining an entity with some type, either an object (e.g.,
block3) or a variable (e.g., ?block).
Should not be instantiated externally.
"""
name: str
type: Type
@cached_property
def _str(self) -> str:
return f"{self.name}:{self.type.name}"
@cached_property
def _hash(self) -> int:
return hash(str(self))
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return self._str
def is_instance(self, t: Type) -> bool:
"""Return whether this entity is an instance of the given type, taking
hierarchical typing into account."""
cur_type: Optional[Type] = self.type
while cur_type is not None:
if cur_type == t:
return True
cur_type = cur_type.parent
return False
@dataclass(frozen=True, order=True, repr=False)
class Object(_TypedEntity):
"""Struct defining an Object, which is just a _TypedEntity whose name does
not start with "?"."""
def __post_init__(self) -> None:
assert not self.name.startswith("?")
def __hash__(self) -> int:
# By default, the dataclass generates a new __hash__ method when
# frozen=True and eq=True, so we need to override it.
return self._hash
@dataclass(frozen=True, order=True, repr=False)
class Variable(_TypedEntity):
"""Struct defining a Variable, which is just a _TypedEntity whose name
starts with "?"."""
def __post_init__(self) -> None:
assert self.name.startswith("?")
def __hash__(self) -> int:
# By default, the dataclass generates a new __hash__ method when
# frozen=True and eq=True, so we need to override it.
return self._hash
@dataclass
class State:
"""Struct defining the low-level state of the world."""
data: Dict[Object, Array]
# Some environments will need to store additional simulator state, so
# this field is provided.
simulator_state: Optional[Any] = None
def __post_init__(self) -> None:
# Check feature vector dimensions.
for obj in self:
assert len(self[obj]) == obj.type.dim
def __iter__(self) -> Iterator[Object]:
"""An iterator over the state's objects, in sorted order."""
return iter(sorted(self.data))
def __getitem__(self, key: Object) -> Array:
return self.data[key]
def get(self, obj: Object, feature_name: str) -> Any:
"""Look up an object feature by name."""
idx = obj.type.feature_names.index(feature_name)
return self.data[obj][idx]
def set(self, obj: Object, feature_name: str, feature_val: Any) -> None:
"""Set the value of an object feature by name."""
idx = obj.type.feature_names.index(feature_name)
self.data[obj][idx] = feature_val
def get_objects(self, object_type: Type) -> List[Object]:
"""Return objects of the given type in the order of __iter__()."""
return [o for o in self if o.type == object_type]
def vec(self, objects: Sequence[Object]) -> Array:
"""Concatenated vector of features for each of the objects in the given
ordered list."""
feats: List[Array] = []
if len(objects) == 0:
return np.zeros(0, dtype=np.float32)
for obj in objects:
feats.append(self[obj])
return np.hstack(feats)
def copy(self) -> State:
"""Return a copy of this state.
The simulator state is assumed to be immutable.
"""
new_data = {}
for obj in self:
new_data[obj] = self._copy_state_value(self.data[obj])
return State(new_data, simulator_state=self.simulator_state)
def _copy_state_value(self, val: Any) -> Any:
if val is None or isinstance(val, (float, bool, int, str)):
return val
if isinstance(val, (list, tuple, set)):
return type(val)(self._copy_state_value(v) for v in val)
assert hasattr(val, "copy")
return val.copy()
def allclose(self, other: State) -> bool:
"""Return whether this state is close enough to another one, i.e., its
objects are the same, and the features are close."""
if self.simulator_state is not None or \
other.simulator_state is not None:
raise NotImplementedError("Cannot use allclose when "
"simulator_state is not None.")
if not sorted(self.data) == sorted(other.data):
return False
for obj in self.data:
if not np.allclose(self.data[obj], other.data[obj], atol=1e-3):
return False
return True
def pretty_str(self) -> str:
"""Display the state in a nice human-readable format."""
type_to_table: Dict[Type, List[List[str]]] = {}
for obj in self:
if obj.type not in type_to_table:
type_to_table[obj.type] = []
type_to_table[obj.type].append([obj.name] + \
list(map(str, self[obj])))
table_strs = []
for t in sorted(type_to_table):
headers = ["type: " + t.name] + list(t.feature_names)
table_strs.append(tabulate(type_to_table[t], headers=headers))
ll = max(
len(line) for table in table_strs for line in table.split("\n"))
prefix = "#" * (ll // 2 - 3) + " STATE " + "#" * (ll - ll // 2 -
4) + "\n"
suffix = "\n" + "#" * ll + "\n"
return prefix + "\n\n".join(table_strs) + suffix
DefaultState = State({})
@dataclass(frozen=True, order=True, repr=False)
class Predicate:
"""Struct defining a predicate (a lifted classifier over states)."""
name: str
types: Sequence[Type]
# The classifier takes in a complete state and a sequence of objects
# representing the arguments. These objects should be the only ones
# treated "specially" by the classifier.
_classifier: Callable[[State, Sequence[Object]],
bool] = field(compare=False)
def __call__(self, entities: Sequence[_TypedEntity]) -> _Atom:
"""Convenience method for generating Atoms."""
if self.arity == 0:
raise ValueError("Cannot use __call__ on a 0-arity predicate, "
"since we can't determine whether it becomes a "
"LiftedAtom or a GroundAtom. Use the LiftedAtom "
"or GroundAtom constructors directly instead")
if all(isinstance(ent, Variable) for ent in entities):
return LiftedAtom(self, entities)
if all(isinstance(ent, Object) for ent in entities):
return GroundAtom(self, entities)
raise ValueError("Cannot instantiate Atom with mix of "
"variables and objects")
@cached_property
def _hash(self) -> int:
return hash(str(self))
def __hash__(self) -> int:
return self._hash
@cached_property
def arity(self) -> int:
"""The arity of this predicate (number of arguments)."""
return len(self.types)
def holds(self,
state: State,
objects: Sequence[Object],
skip_allclose_check: bool = False) -> bool:
"""Public method for calling the classifier.
Performs type checking first.
"""
assert len(objects) == self.arity
for obj, pred_type in zip(objects, self.types):
assert isinstance(obj, Object)
assert obj.is_instance(pred_type)
if CFG.env != "behavior":
return self._classifier(state, objects)
# Note: This line skips the allclose check for Behavior when
# grounding inserts. We need to ignore typing here because
# the classfiers have an extra parameter for skipping allclose.
return self._classifier( # pragma: no cover
state,
objects,
skip_allclose_check=skip_allclose_check) # type:ignore
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return str(self)
def pretty_str(self) -> Tuple[str, str]:
"""Display the predicate in a nice human-readable format.
Returns a tuple of (variables string, body string).
"""
if hasattr(self._classifier, "pretty_str"):
# This is an invented predicate, from the predicate grammar.
pretty_str_f = getattr(self._classifier, "pretty_str")
return pretty_str_f()
# This is a known predicate, not from the predicate grammar.
vars_str = ", ".join(
f"{CFG.grammar_search_classifier_pretty_str_names[i]}:{t.name}"
for i, t in enumerate(self.types))
vars_str_no_types = ", ".join(
f"{CFG.grammar_search_classifier_pretty_str_names[i]}"
for i in range(self.arity))
body_str = f"{self.name}({vars_str_no_types})"
return vars_str, body_str
def pddl_str(self) -> str:
"""Get a string representation suitable for writing out to a PDDL
file."""
if self.arity == 0:
return f"({self.name})"
vars_str = " ".join(f"?x{i} - {t.name}"
for i, t in enumerate(self.types))
return f"({self.name} {vars_str})"
def get_negation(self) -> Predicate:
"""Return a negated version of this predicate."""
return Predicate("NOT-" + self.name, self.types,
self._negated_classifier)
def _negated_classifier(self, state: State,
objects: Sequence[Object]) -> bool:
# Separate this into a named function for pickling reasons.
return not self._classifier(state, objects)
@dataclass(frozen=True, repr=False, eq=False)
class _Atom:
"""Struct defining an atom (a predicate applied to either variables or
objects).
Should not be instantiated externally.
"""
predicate: Predicate
entities: Sequence[_TypedEntity]
def __post_init__(self) -> None:
if isinstance(self.entities, _TypedEntity):
raise ValueError("Atoms expect a sequence of entities, not a "
"single entity.")
assert len(self.entities) == self.predicate.arity
for ent, pred_type in zip(self.entities, self.predicate.types):
assert ent.is_instance(pred_type)
@property
def _str(self) -> str:
raise NotImplementedError("Override me")
@cached_property
def _hash(self) -> int:
return hash(str(self))
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return str(self)
def pddl_str(self) -> str:
"""Get a string representation suitable for writing out to a PDDL
file."""
if not self.entities:
return f"({self.predicate.name})"
entities_str = " ".join(e.name for e in self.entities)
return f"({self.predicate.name} {entities_str})"
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
assert isinstance(other, _Atom)
return str(self) == str(other)
def __lt__(self, other: object) -> bool:
assert isinstance(other, _Atom)
return str(self) < str(other)
@dataclass(frozen=True, repr=False, eq=False)
class LiftedAtom(_Atom):
"""Struct defining a lifted atom (a predicate applied to variables)."""
@cached_property
def variables(self) -> List[Variable]:
"""Arguments for this lifted atom.
A list of "Variable"s.
"""
return list(cast(Variable, ent) for ent in self.entities)
@cached_property
def _str(self) -> str:
return (str(self.predicate) + "(" +
", ".join(map(str, self.variables)) + ")")
def ground(self, sub: VarToObjSub) -> GroundAtom:
"""Create a GroundAtom with a given substitution."""
assert set(self.variables).issubset(set(sub.keys()))
return GroundAtom(self.predicate, [sub[v] for v in self.variables])
@dataclass(frozen=True, repr=False, eq=False)
class GroundAtom(_Atom):
"""Struct defining a ground atom (a predicate applied to objects)."""
@cached_property
def objects(self) -> List[Object]:
"""Arguments for this ground atom.
A list of "Object"s.
"""
return list(cast(Object, ent) for ent in self.entities)
@cached_property
def _str(self) -> str:
return (str(self.predicate) + "(" + ", ".join(map(str, self.objects)) +
")")
def lift(self, sub: ObjToVarSub) -> LiftedAtom:
"""Create a LiftedAtom with a given substitution."""
assert set(self.objects).issubset(set(sub.keys()))
return LiftedAtom(self.predicate, [sub[o] for o in self.objects])
def holds(self, state: State) -> bool:
"""Check whether this ground atom holds in the given state."""
return self.predicate.holds(state, self.objects)
@dataclass(frozen=True, eq=False)
class Task:
"""Struct defining a task, which is a pair of initial state and goal."""
init: State
goal: Set[GroundAtom]
def __post_init__(self) -> None:
# Verify types.
assert isinstance(self.init, State)
for atom in self.goal:
assert isinstance(atom, GroundAtom)
def goal_holds(self, state: State) -> bool:
"""Return whether the goal of this task holds in the given state."""
return all(goal_atom.holds(state) for goal_atom in self.goal)
DefaultTask = Task(DefaultState, set())
@dataclass(frozen=True, eq=False)
class ParameterizedOption:
"""Struct defining a parameterized option, which has a parameter space and
can be ground into an Option, given parameter values.
An option is composed of a policy, an initiation classifier, and a
termination condition. We will stick with deterministic termination
conditions. For a parameterized option, all of these are conditioned
on parameters.
"""
name: str
types: Sequence[Type]
params_space: Box = field(repr=False)
# A policy maps a state, memory dict, objects, and parameters to an action.
# The objects' types will match those in self.types. The parameters
# will be contained in params_space.
policy: Callable[[State, Dict, Sequence[Object], Array],
Action] = field(repr=False)
# An initiation classifier maps a state, memory dict, objects, and
# parameters to a bool, which is True iff the option can start
# now. The objects' types will match those in self.types. The
# parameters will be contained in params_space.
initiable: Callable[[State, Dict, Sequence[Object], Array],
bool] = field(repr=False)
# A termination condition maps a state, memory dict, objects, and
# parameters to a bool, which is True iff the option should
# terminate now. The objects' types will match those in
# self.types. The parameters will be contained in params_space.
terminal: Callable[[State, Dict, Sequence[Object], Array],
bool] = field(repr=False)
@cached_property
def _hash(self) -> int:
return hash(str(self))
def __eq__(self, other: object) -> bool:
assert isinstance(other, ParameterizedOption)
return self.name == other.name
def __lt__(self, other: object) -> bool:
assert isinstance(other, ParameterizedOption)
return self.name < other.name
def __gt__(self, other: object) -> bool:
assert isinstance(other, ParameterizedOption)
return self.name > other.name
def __hash__(self) -> int:
return self._hash
def ground(self, objects: Sequence[Object], params: Array) -> _Option:
"""Ground into an Option, given objects and parameter values."""
assert len(objects) == len(self.types)
for obj, t in zip(objects, self.types):
assert obj.is_instance(t)
params = np.array(params, dtype=self.params_space.dtype)
assert self.params_space.contains(params)
memory: Dict = {} # each option has its own memory dict
return _Option(
self.name,
lambda s: self.policy(s, memory, objects, params),
initiable=lambda s: self.initiable(s, memory, objects, params),
terminal=lambda s: self.terminal(s, memory, objects, params),
parent=self,
objects=objects,
params=params,
memory=memory)
@dataclass(eq=False)
class _Option:
"""Struct defining an option, which is like a parameterized option except
that its components are not conditioned on objects/parameters.
Should not be instantiated externally.
"""
name: str
# A policy maps a state to an action.
_policy: Callable[[State], Action] = field(repr=False)
# An initiation classifier maps a state to a bool, which is True
# iff the option can start now.
initiable: Callable[[State], bool] = field(repr=False)
# A termination condition maps a state to a bool, which is True
# iff the option should terminate now.
terminal: Callable[[State], bool] = field(repr=False)
# The parameterized option that generated this option.
parent: ParameterizedOption = field(repr=False)
# The objects that were used to ground this option.
objects: Sequence[Object]
# The parameters that were used to ground this option.
params: Array
# The memory dictionary for this option.
memory: Dict = field(repr=False)
def policy(self, state: State) -> Action:
"""Call the policy and set the action's option."""
action = self._policy(state)
action.set_option(self)
return action
DummyOption: _Option = ParameterizedOption(
"DummyOption", [], Box(0, 1,
(1, )), lambda s, m, o, p: Action(np.array([0.0])),
lambda s, m, o, p: False, lambda s, m, o, p: True).ground([],
np.array([0.0]))
DummyOption.parent.params_space.seed(0) # for reproducibility
@dataclass(frozen=True, repr=False, eq=False)
class STRIPSOperator:
"""Struct defining a symbolic operator (as in STRIPS).
Lifted! Note here that the ignore_effects - unlike the
add_effects and delete_effects - are universally
quantified over all possible groundings.
"""
name: str
parameters: Sequence[Variable]
preconditions: Set[LiftedAtom]
add_effects: Set[LiftedAtom]
delete_effects: Set[LiftedAtom]
ignore_effects: Set[Predicate]
def make_nsrt(
self,
option: ParameterizedOption,
option_vars: Sequence[Variable],
sampler: NSRTSampler = field(repr=False)
) -> NSRT:
"""Make an NSRT out of this STRIPSOperator object, given the necessary
additional fields."""
return NSRT(self.name, self.parameters, self.preconditions,
self.add_effects, self.delete_effects, self.ignore_effects,
option, option_vars, sampler)
@lru_cache(maxsize=None)
def ground(self, objects: Tuple[Object]) -> _GroundSTRIPSOperator:
"""Ground into a _GroundSTRIPSOperator, given objects.
Insist that objects are tuple for hashing in cache.
"""
assert isinstance(objects, tuple)
assert len(objects) == len(self.parameters)
assert all(
o.is_instance(p.type) for o, p in zip(objects, self.parameters))
sub = dict(zip(self.parameters, objects))
preconditions = {atom.ground(sub) for atom in self.preconditions}
add_effects = {atom.ground(sub) for atom in self.add_effects}
delete_effects = {atom.ground(sub) for atom in self.delete_effects}
return _GroundSTRIPSOperator(self, list(objects), preconditions,
add_effects, delete_effects)
@cached_property
def _str(self) -> str:
return f"""STRIPS-{self.name}:
Parameters: {self.parameters}
Preconditions: {sorted(self.preconditions, key=str)}
Add Effects: {sorted(self.add_effects, key=str)}
Delete Effects: {sorted(self.delete_effects, key=str)}
Ignore Effects: {sorted(self.ignore_effects, key=str)}"""
@cached_property
def _hash(self) -> int:
return hash(str(self))
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return str(self)
def pddl_str(self) -> str:
"""Get a string representation suitable for writing out to a PDDL
file."""
params_str = " ".join(f"{p.name} - {p.type.name}"
for p in self.parameters)
preconds_str = "\n ".join(
atom.pddl_str() for atom in sorted(self.preconditions))
effects_str = "\n ".join(atom.pddl_str()
for atom in sorted(self.add_effects))
if self.delete_effects:
effects_str += "\n "
effects_str += "\n ".join(
f"(not {atom.pddl_str()})"
for atom in sorted(self.delete_effects))
if self.ignore_effects:
if len(effects_str) != 0:
effects_str += "\n "
for pred in sorted(self.ignore_effects):
pred_types_str = " ".join(f"?x{i} - {t.name}"
for i, t in enumerate(pred.types))
pred_eff_variables_str = " ".join(f"?x{i}"
for i in range(pred.arity))
effects_str += f"(forall ({pred_types_str})" +\
f" (not ({pred.name} {pred_eff_variables_str})))"
effects_str += "\n "
return f"""(:action {self.name}
:parameters ({params_str})
:precondition (and {preconds_str})
:effect (and {effects_str})
)"""
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
assert isinstance(other, STRIPSOperator)
return str(self) == str(other)
def __lt__(self, other: object) -> bool:
assert isinstance(other, STRIPSOperator)
return str(self) < str(other)
def __gt__(self, other: object) -> bool:
assert isinstance(other, STRIPSOperator)
return str(self) > str(other)
def copy_with(self, **kwargs: Any) -> STRIPSOperator:
"""Create a copy of the operator, optionally while replacing any of the
arguments."""
default_kwargs = dict(name=self.name,
parameters=self.parameters,
preconditions=self.preconditions,
add_effects=self.add_effects,
delete_effects=self.delete_effects,
ignore_effects=self.ignore_effects)
assert set(kwargs.keys()).issubset(default_kwargs.keys())
default_kwargs.update(kwargs)
# mypy is known to have issues with this pattern:
# https://github.com/python/mypy/issues/5382
return STRIPSOperator(**default_kwargs) # type: ignore
def effect_to_ignore_effect(self, effect: LiftedAtom,
option_vars: Sequence[Variable],
add_or_delete: str) -> STRIPSOperator:
"""Return a new STRIPS operator resulting from turning the given effect
(either add or delete) into an ignore effect."""
assert add_or_delete in ("add", "delete")
if add_or_delete == "add":
assert effect in self.add_effects
new_add_effects = self.add_effects - {effect}
new_delete_effects = self.delete_effects
else:
new_add_effects = self.add_effects
assert effect in self.delete_effects
new_delete_effects = self.delete_effects - {effect}
# Since we are removing an effect, it could be the case
# that parameters need to be removed from the operator.
remaining_params = {
p
for atom in self.preconditions | new_add_effects
| new_delete_effects for p in atom.variables
} | set(option_vars)
new_params = [p for p in self.parameters if p in remaining_params]
return STRIPSOperator(self.name, new_params, self.preconditions,
new_add_effects, new_delete_effects,
self.ignore_effects | {effect.predicate})
def get_complexity(self) -> float:
"""Get the complexity of this operator.
We only care about the arity of the operator, since that is what
affects grounding. We'll use 2^arity as a measure of grounding
effort.
"""
return float(2**len(self.parameters))
@dataclass(frozen=True, repr=False, eq=False)
class _GroundSTRIPSOperator:
"""A STRIPSOperator + objects.
Should not be instantiated externally.
"""
parent: STRIPSOperator
objects: Sequence[Object]
preconditions: Set[GroundAtom]
add_effects: Set[GroundAtom]
delete_effects: Set[GroundAtom]
@cached_property
def _str(self) -> str:
return f"""GroundSTRIPS-{self.name}:
Parameters: {self.objects}
Preconditions: {sorted(self.preconditions, key=str)}
Add Effects: {sorted(self.add_effects, key=str)}
Delete Effects: {sorted(self.delete_effects, key=str)}
Ignore Effects: {sorted(self.ignore_effects, key=str)}"""
@cached_property
def _hash(self) -> int:
return hash(str(self))
@property
def name(self) -> str:
"""Name of this ground STRIPSOperator."""
return self.parent.name
@property
def ignore_effects(self) -> Set[Predicate]:
"""Ignore effects from the parent."""
return self.parent.ignore_effects
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return str(self)
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
assert isinstance(other, _GroundSTRIPSOperator)
return str(self) == str(other)
def __lt__(self, other: object) -> bool:
assert isinstance(other, _GroundSTRIPSOperator)
return str(self) < str(other)
def __gt__(self, other: object) -> bool:
assert isinstance(other, _GroundSTRIPSOperator)
return str(self) > str(other)
@dataclass(frozen=True, repr=False, eq=False)
class NSRT:
"""Struct defining an NSRT, which contains the components of a STRIPS
operator, a parameterized option, and a sampler function.
"NSRT" stands for "Neuro-Symbolic Relational Transition Model".
Paper: https://arxiv.org/abs/2105.14074
"""
name: str
parameters: Sequence[Variable]
preconditions: Set[LiftedAtom]
add_effects: Set[LiftedAtom]
delete_effects: Set[LiftedAtom]
ignore_effects: Set[Predicate]
option: ParameterizedOption
# A subset of parameters corresponding to the (lifted) arguments of the
# option that this NSRT contains.
option_vars: Sequence[Variable]
# A sampler maps a state, RNG, and objects to option parameters.
_sampler: NSRTSampler = field(repr=False)
@cached_property
def _str(self) -> str:
option_var_str = ", ".join([str(v) for v in self.option_vars])
return f"""NSRT-{self.name}:
Parameters: {self.parameters}
Preconditions: {sorted(self.preconditions, key=str)}
Add Effects: {sorted(self.add_effects, key=str)}
Delete Effects: {sorted(self.delete_effects, key=str)}
Ignore Effects: {sorted(self.ignore_effects, key=str)}
Option Spec: {self.option.name}({option_var_str})"""
@cached_property
def _hash(self) -> int:
return hash(str(self))
@property
def op(self) -> STRIPSOperator:
"""Return the STRIPSOperator associated with this NSRT."""
return STRIPSOperator(self.name, self.parameters, self.preconditions,
self.add_effects, self.delete_effects,
self.ignore_effects)
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return str(self)
def pddl_str(self) -> str:
"""Get a string representation suitable for writing out to a PDDL
file."""
return self.op.pddl_str()
def pretty_str(self, name_map: Dict[str, str]) -> str:
"""Display the NSRT in a nice human-readable format, given a mapping to
new predicate names for any invented predicates."""
out = ""
out += f"{self.name}:\n\tParameters: {self.parameters}"
for name, atoms in [("Preconditions", self.preconditions),
("Add Effects", self.add_effects),
("Delete Effects", self.delete_effects)]:
out += f"\n\t{name}:"
for atom in atoms:
pretty_pred = atom.predicate.pretty_str()[1]
new_name = (name_map[pretty_pred] if pretty_pred in name_map
else str(atom.predicate))
var_str = ", ".join(map(str, atom.variables))
out += f"\n\t\t{new_name}({var_str})"
option_var_strs = [str(v) for v in self.option_vars]
out += f"\n\tOption Spec: ({self.option.name}, {option_var_strs})"
return out
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
assert isinstance(other, NSRT)
return str(self) == str(other)
def __lt__(self, other: object) -> bool:
assert isinstance(other, NSRT)
return str(self) < str(other)
def __gt__(self, other: object) -> bool:
assert isinstance(other, NSRT)
return str(self) > str(other)
@property
def sampler(self) -> NSRTSampler:
"""This NSRT's sampler."""
return self._sampler
def ground(self, objects: Sequence[Object]) -> _GroundNSRT:
"""Ground into a _GroundNSRT, given objects."""
assert len(objects) == len(self.parameters)
assert all(
o.is_instance(p.type) for o, p in zip(objects, self.parameters))
sub = dict(zip(self.parameters, objects))
preconditions = {atom.ground(sub) for atom in self.preconditions}
add_effects = {atom.ground(sub) for atom in self.add_effects}
delete_effects = {atom.ground(sub) for atom in self.delete_effects}
option_objs = [sub[v] for v in self.option_vars]
return _GroundNSRT(self, objects, preconditions, add_effects,
delete_effects, self.option, option_objs,
self._sampler)
def filter_predicates(self, kept: Collection[Predicate]) -> NSRT:
"""Keep only the given predicates in the preconditions, add effects,
delete effects, and ignore effects.
Note that the parameters must stay the same for the sake of the
sampler inputs.
"""
preconditions = {a for a in self.preconditions if a.predicate in kept}
add_effects = {a for a in self.add_effects if a.predicate in kept}
delete_effects = {
a
for a in self.delete_effects if a.predicate in kept
}
ignore_effects = {a for a in self.ignore_effects if a in kept}
return NSRT(self.name, self.parameters, preconditions, add_effects,
delete_effects, ignore_effects, self.option,
self.option_vars, self._sampler)
@dataclass(frozen=True, repr=False, eq=False)
class _GroundNSRT:
"""A ground NSRT is an NSRT + objects.
Should not be instantiated externally.
"""
parent: NSRT
objects: Sequence[Object]
preconditions: Set[GroundAtom]
add_effects: Set[GroundAtom]
delete_effects: Set[GroundAtom]
option: ParameterizedOption
option_objs: Sequence[Object]
_sampler: NSRTSampler = field(repr=False)
@cached_property
def _str(self) -> str:
return f"""GroundNSRT-{self.name}:
Parameters: {self.objects}
Preconditions: {sorted(self.preconditions, key=str)}
Add Effects: {sorted(self.add_effects, key=str)}
Delete Effects: {sorted(self.delete_effects, key=str)}
Ignore Effects: {sorted(self.ignore_effects, key=str)}
Option: {self.option}
Option Objects: {self.option_objs}"""
@cached_property
def _hash(self) -> int:
return hash(str(self))
@property
def name(self) -> str:
"""Name of this ground NSRT."""
return self.parent.name
@property
def ignore_effects(self) -> Set[Predicate]:
"""Ignore effects from the parent."""
return self.parent.ignore_effects
def __str__(self) -> str:
return self._str
def __repr__(self) -> str:
return str(self)
def __hash__(self) -> int:
return self._hash
def __eq__(self, other: object) -> bool:
assert isinstance(other, _GroundNSRT)
return str(self) == str(other)
def __lt__(self, other: object) -> bool:
assert isinstance(other, _GroundNSRT)
return str(self) < str(other)
def __gt__(self, other: object) -> bool:
assert isinstance(other, _GroundNSRT)
return str(self) > str(other)
def sample_option(self, state: State, goal: Set[GroundAtom],
rng: np.random.Generator) -> _Option:
"""Sample an _Option for this ground NSRT, by invoking the contained
sampler.
On the Option that is returned, one can call, e.g.,
policy(state).
"""
# Note that the sampler takes in ALL self.objects, not just the subset
# self.option_objs of objects that are passed into the option.
params = self._sampler(state, goal, rng, self.objects)
# Clip the params into the params_space of self.option, for safety.
low = self.option.params_space.low
high = self.option.params_space.high
params = np.clip(params, low, high)
return self.option.ground(self.option_objs, params)
def copy_with(self, **kwargs: Any) -> _GroundNSRT:
"""Create a copy of the ground NSRT, optionally while replacing any of
the arguments."""
default_kwargs = dict(parent=self.parent,
objects=self.objects,
preconditions=self.preconditions,
add_effects=self.add_effects,
delete_effects=self.delete_effects,
option=self.option,
option_objs=self.option_objs,
_sampler=self._sampler)
assert set(kwargs.keys()).issubset(default_kwargs.keys())
default_kwargs.update(kwargs)
# mypy is known to have issues with this pattern:
# https://github.com/python/mypy/issues/5382
return _GroundNSRT(**default_kwargs) # type: ignore
@dataclass(eq=False)
class Action:
"""An action in an environment.
This is a light wrapper around a numpy float array that can
optionally store the option which produced it.
"""
_arr: Array
_option: _Option = field(repr=False, default=DummyOption)
@property
def arr(self) -> Array:
"""The array representation of this action."""
return self._arr
def has_option(self) -> bool:
"""Whether this action has a non-default option attached."""
return self._option.parent != DummyOption.parent
def get_option(self) -> _Option:
"""Get the option that produced this action."""
assert self.has_option()
return self._option