How to use the textworld.logic.Proposition function in textworld

To help you get started, we’ve selected a few textworld examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / TextWorld / textworld / generator / world.py View on Github external
e = G[src][dest]

        room_src = rooms[src]
        room_dest = rooms[dest]
        if e["has_door"]:
            door = Variable(e['door_name'], "d")
            pred1 = Proposition("{}_of".format(d), [room_dest, room_src])
            pred2 = Proposition("{}_of".format(d_r), [room_src, room_dest])
            state.append(Proposition(e["door_state"], [door]))
            state.append(Proposition("link", [room_src, door, room_dest]))
            state.append(Proposition("link", [room_dest, door, room_src]))
            if e["door_state"] == "open":
                state.append(Proposition("free", [room_dest, room_src]))
                state.append(Proposition("free", [room_src, room_dest]))
        else:
            pred1 = Proposition("{}_of".format(d), [room_dest, room_src])
            pred2 = Proposition("{}_of".format(d_r), [room_src, room_dest])
            state.append(Proposition("free", [room_dest, room_src]))
            state.append(Proposition("free", [room_src, room_dest]))

        state.append(pred1)
        state.append(pred2)

    return state
github microsoft / TextWorld / textworld / generator / world.py View on Github external
def connect(room1: Variable, direction: str, room2: Variable,
            door: Optional[Variable] = None) -> List[Proposition]:
    """ Generate predicates that connect two rooms.

    Args:
        room1: A room variable.
        direction: Direction that we need to travel to go from
                   room1 to room2.
        room2: A room variable.
        door: The door separating the two rooms. If `None`, there is no
              door between the rooms.
    """
    r_direction = reverse_direction(direction) + "_of"
    direction += "_of"
    facts = [Proposition(direction, [room2, room1]),
             Proposition(r_direction, [room1, room2]),
             Proposition("free", [room1, room2]),
             Proposition("free", [room2, room1])]

    if door is not None:
        facts += [Proposition("link", [room1, door, room2]),
                  Proposition("link", [room2, door, room1])]

    return facts
github microsoft / TextWorld / textworld / generator / world.py View on Github external
obj_type = "k"
            else:
                obj_type = self.kb.types.sample(parent_type='t', rng=rng, exceptions=["d", "r"],
                                                include_parent=False, probs=object_types_probs)

            if self.kb.types.is_descendant_of(obj_type, "o"):
                obj_name = get_new(obj_type, types_counts)
                obj = Variable(obj_name, obj_type)
                allowed_objects_holder = list(objects_holder)

                if obj_type == "k":
                    if len(locked_or_closed_objects) > 0:
                        # Look for a *locked* container or a door.
                        rng.shuffle(locked_or_closed_objects)
                        locked_or_closed_obj = locked_or_closed_objects.pop()
                        state.append(Proposition("match", [obj, locked_or_closed_obj]))
                        lockable_objects.remove(locked_or_closed_obj)

                        # Do not place the key in its own matching container.
                        if locked_or_closed_obj in allowed_objects_holder:
                            allowed_objects_holder.remove(locked_or_closed_obj)

                    elif len(lockable_objects) > 0:
                        # Look for a container or a door.
                        rng.shuffle(lockable_objects)
                        lockable_obj = lockable_objects.pop()
                        state.append(Proposition("match", [obj, lockable_obj]))
                    else:
                        continue  # Unuseful key is not allowed.

                elif obj_type == "f":
                    # HACK: manually add the edible property to food items.
github microsoft / TextWorld / textworld / generator / world.py View on Github external
remaining_objects_id = list(range(len(objects)))
        rng.shuffle(remaining_objects_id)
        for idx in remaining_objects_id:
            obj = objects[idx]
            obj_type = obj.type

            if self.kb.types.is_descendant_of(obj_type, "o"):
                allowed_objects_holder = list(objects_holder)

                # Place the object somewhere.
                obj_holder = rng.choice(allowed_objects_holder)
                if self.kb.types.is_descendant_of(obj_holder.type, "s"):
                    state.append(Proposition("on", [obj, obj_holder]))
                elif self.kb.types.is_descendant_of(obj_holder.type, "c"):
                    state.append(Proposition("in", [obj, obj_holder]))
                elif self.kb.types.is_descendant_of(obj_holder.type, "r"):
                    state.append(Proposition("at", [obj, obj_holder]))
                else:
                    raise ValueError("Unknown type for object holder: {}".format(obj_holder))

            elif self.kb.types.is_descendant_of(obj_type, "s"):
                supporter = obj
                state.append(Proposition("at", [supporter, room]))
                objects_holder.append(supporter)

            elif self.kb.types.is_descendant_of(obj_type, "c"):
                container = obj
                state.append(Proposition("at", [container, room]))
                objects_holder.append(container)

                container_state = rng.choice(["open", "closed", "locked"])
github microsoft / TextWorld / textworld / generator / maker.py View on Github external
def get_failing_constraints(state, kb: Optional[KnowledgeBase] = None):
    kb = kb or KnowledgeBase.default()
    fail = Proposition("fail", [])

    failed_constraints = []
    constraints = state.all_applicable_actions(kb.constraints.values())
    for constraint in constraints:
        if state.is_applicable(constraint):
            # Optimistically delay copying the state
            copy = state.copy()
            copy.apply(constraint)

            if copy.is_fact(fail):
                failed_constraints.append(constraint)

    return failed_constraints
github microsoft / TextWorld / textworld / generator / maker.py View on Github external
def facts(self) -> List[Proposition]:
        """ Facts related to this path.

        Returns:
            The facts that make up this path.
        """
        facts = []
        facts.append(Proposition("{}_of".format(self.src_exit), [self.dest.var, self.src.var]))
        facts.append(Proposition("{}_of".format(self.dest_exit), [self.src.var, self.dest.var]))

        if self.door is None or self.door.has_property("open"):
            facts.append(Proposition("free", [self.src.var, self.dest.var]))
            facts.append(Proposition("free", [self.dest.var, self.src.var]))

        if self.door is not None:
            facts.extend(self.door.facts)
            facts.append(Proposition("link", [self.src.var, self.door.var, self.dest.var]))
            facts.append(Proposition("link", [self.dest.var, self.door.var, self.src.var]))

        return facts
github microsoft / TextWorld / textworld / generator / world.py View on Github external
def set_player_room(self, start_room: Union[None, WorldRoom, str] = None) -> None:
        if start_room is None:
            if len(self.rooms) == 0:
                start_room = WorldRoom("r_0", "r")
            else:
                start_room = self.rooms[0]

        elif start_room in self._entities:
            start_room = self._entities[start_room]
        elif isinstance(start_room, Variable) and start_room.name in self._entities:
            start_room = self._entities[start_room.name]
        else:
            raise ValueError("Unknown room: {}".format(start_room))

        self.add_fact(Proposition("at", [self.player, start_room]))
github microsoft / TextWorld / textworld / generator / game.py View on Github external
conditions: Set of propositions which need to
                        be all true in order for this event
                        to get triggered.
        Returns:
            Action that can only be applied when all conditions are statisfied.
        """
        if not conditions:
            if len(self.actions) == 0:
                raise UnderspecifiedEventError()

            # The default winning conditions are the postconditions of the
            # last action in the quest.
            conditions = self.actions[-1].postconditions

        variables = sorted(set([v for c in conditions for v in c.arguments]))
        event = Proposition("event", arguments=variables)
        self.condition = Action("trigger", preconditions=conditions,
                                postconditions=list(conditions) + [event])
        return self.condition
github microsoft / TextWorld / textworld / generator / maker.py View on Github external
def remove_fact(self, name: str, *entities: List["WorldEntity"]) -> None:
        args = [entity.var for entity in entities]
        self._facts.remove(Proposition(name, args))