示例#1
0
 def Run(cls, controller, *, me):
     workspace = controller.workspace
     supergroups_map = workspace.CalculateSupergroupMap()
     History.Note("CF_RemoveSpuriousRelations: called")
     for element in workspace.elements:
         supergps = supergroups_map[element]
         if not supergps:
             continue
         relations_to_remove = []
         for relation in element.relations:
             if relation.first == element:
                 other_end = relation.second
             else:
                 other_end = relation.first
             other_supergps = supergroups_map[other_end]
             if not other_supergps:
                 continue
             if supergps.intersection(other_supergps):
                 continue
             other_end.relations.discard(relation)
             relations_to_remove.append(relation)
         History.Note("CF_RemoveSpuriousRelations: removed",
                      times=len(relations_to_remove))
         for relation in relations_to_remove:
             element.relations.discard(relation)
示例#2
0
文件: stream.py 项目: superMDguy/DNHN
    def FocusOn(self, focusable, controller):
        fringe = focusable.GetFringe()
        # TODO(amahabal) This way, anything that was ever a fringe element of an item stays that way.
        # But this way is much cheaper than updating everything, and not super wrong...
        # When we choose an object based on fringe overlap, we can recalculate,
        # if we wish...
        for fe, wt in fringe.items():
            self.fringe_element_to_item_to_wt[fe][focusable] = wt
        timestamp = controller.steps_taken
        self.last_focus_time[focusable] = timestamp
        controller.ltm.GetNode(content=focusable).IncreaseActivation(
            5, current_time=controller.steps_taken)
        actions = focusable.GetActions(controller)
        prior_overlapping_foci = self.PriorFociWithSimilarFringe(
            current_focus=focusable, timestamp=timestamp)
        if prior_overlapping_foci:
            actions.extend(focusable.GetRemindingBasedActions(
                prior_overlapping_foci))
            History.Note("In FocusOn: Prior overlapping foci seen")

        if actions:
            selected_actions = ChooseAboutN(2, [(x, x.urgency) for x in actions])
            History.Note("In FocusOn: Total of suggested actions", times=len(actions))
            History.Note(
                "In FocusOn: Total of selected actions", times=len(selected_actions))
            for action in selected_actions:
                controller.coderack.AddCodelet(
                    action,
                    msg="While focusing on %s" % focusable.BriefLabel(),

                    parents=(focusable, ))
示例#3
0
    def InsertGroup(self, group, *, parent=None):
        """Inserts a group into the workspace. It must not conflict with an existing group, else
           a ConflictingGroupException is raised.

           Returns a new group formed from things added to the workspace.
        """
        conflicting_groups = tuple(self.GetConflictingGroups(group))
        if conflicting_groups:
            logger.info('Conflicts while adding %s: %s', group,
                        '; '.join(str(x) for x in conflicting_groups))
            History.Note("Group insert: conflict")
            raise ConflictingGroupException(
                conflicting_groups=conflicting_groups)
        else:
            History.Note("Group insert: no conflict")
            return self._PlonkIntoPlace(group)
 def __init__(self, *, first, second, parents=[]):
     self.first = first
     self.second = second
     Categorizable.__init__(self)
     if History._is_history_on:
         roles = {first._hid: "first end", second._hid: "second end"}
         History.AddArtefact(self, ObjectType.WS_RELN, "", parents, roles)
         History.Note("Created relation")
示例#5
0
 def GetFringe(self):
     fringe = self.CalculateFringe()
     for cat, instance_logic in self.categories.items():
         fringe[cat] = 1
         for att, val in instance_logic._attributes.items():
             fringe[(cat, att, val.Structure())] = 0.5
     self.stored_fringe = fringe
     History.Note("GetFringe called")
     return fringe
示例#6
0
 def FindCategories(self, *, end_category):
     new_cats = []
     for reln_cat in end_category._RelationCategories:
         if self.IsKnownAsInstanceOf(reln_cat):
             continue
         if (self.DescribeAs(reln_cat)):
             History.Note("Category added to reln")
             new_cats.append(reln_cat)
     return new_cats
示例#7
0
 def Append(self, *, magnitudes):
     """Adds elements with these magnitudes at the end."""
     to_add = [PSElement(magnitude=x) for x in magnitudes]
     for idx, el in enumerate(to_add, self._next_index):
         el._span = (idx, idx)
         self._objects_with_span[(idx, idx)][el.Structure()] = el
     self.element.extend(to_add)
     self._next_index += len(magnitudes)
     History.Note("Arena: elements added", times=len(magnitudes))
示例#8
0
 def InsertElement(self, element):
     """Insert an element beyond the last element."""
     assert isinstance(element, SElement)
     anchored = SAnchored(sobj=element,
                          items=[],
                          start_pos=self.num_elements,
                          end_pos=self.num_elements,
                          is_sequence_element=True)
     self.num_elements += 1
     History.AddArtefact(anchored, ObjectType.WS_GROUP, "Initial creation")
     History.Note("Element Inserted")
     self.elements.append(anchored)
示例#9
0
    def FocusOn(self, focusable, *, parents=None):
        """Focus on focusable, and act on a fringe-hit."""
        History.AddEvent(EventType.OBJECT_FOCUS, "", [(focusable, "")])
        assert (isinstance(focusable, FocusableMixin))
        focusable.OnFocus(self.controller)
        self._PrepareForFocusing(focusable)
        hit_map = self.StoreFringeAndCalculateOverlap(focusable)

        # Possibly add codelets based on the fringe hit.
        potential_codelets = []
        for prior_focusable, overlap_amount in hit_map.items():
            if overlap_amount < Stream.kMinOverlapToTriggerSimilarity:
                continue
            potential_codelets.extend(
                prior_focusable.GetSimilarityAffordances(
                    focusable,
                    other_fringe=self.stored_fringes[focusable],
                    my_fringe=self.stored_fringes[prior_focusable],
                    controller=self.controller))

        potential_codelets.extend(
            focusable.GetAffordances(controller=self.controller))
        if potential_codelets:
            selected_codelets = ChooseAboutN(2, [(x, x.urgency)
                                                 for x in potential_codelets])
            History.Note("Chose to keep codelet during FocusOn",
                         times=len(selected_codelets))
            History.Note("Chose not to keep codelet during FocusOn",
                         times=len(potential_codelets) -
                         len(selected_codelets))
            effective_parents = [focusable]
            if parents:
                effective_parents.extend(parents)
            for codelet in selected_codelets:
                self.controller.coderack.AddCodelet(
                    codelet,
                    msg="While focusing on %s" % focusable.BriefLabel(),
                    parents=effective_parents)
示例#10
0
 def Run(cls, controller, left, right, *, me):
     if left not in controller.workspace.groups or right not in controller.workspace.groups:
         # Groups gone, fizzle.
         History.Note("CF_ActOnOverlappingGroups: left group now dead")
         return
     if set(left.items).intersection(set(right.items)):
         # So overlap, and share elements.
         left_underlying_set = left.object.underlying_mapping_set
         right_underlying_set = right.object.underlying_mapping_set
         # TODO(# --- Jan 28, 2012): Even if the following fails, there is reason to try and
         # see how the two may be made to agree.
         if left_underlying_set and left_underlying_set.intersection(
                 right_underlying_set):
             # This calls out for merging!
             new_group_items = sorted(set(left.items).union(set(
                 right.items)),
                                      key=lambda x: x.start_pos)
             logging.debug("New group items: %s",
                           '; '.join(str(x) for x in new_group_items))
             new_group = SAnchored.Create(
                 new_group_items,
                 underlying_mapping_set=left_underlying_set.intersection(
                     right_underlying_set))
             try:
                 controller.workspace.Replace((left, right), new_group)
             except ConflictingGroupException as e:
                 SubspaceDealWithConflictingGroups(
                     controller,
                     workspace_arguments=dict(
                         new_group=new_group,
                         incumbents=e.conflicting_groups),
                     parents=[me, left, right],
                     msg="Conflict when merging overlapping groups").Run()
             except CannotReplaceSubgroupException as e:
                 SubspaceDealWithConflictingGroups(
                     controller,
                     workspace_arguments=dict(new_group=new_group,
                                              incumbents=e.supergroups),
                     parents=[me, left, right],
                     msg=
                     "Cannot replace subgp when merging overlapping groups"
                 ).Run()
示例#11
0
 def Run(cls, controller, relation, *, me):
     # If there is a group spanning the proposed group, perish the thought.
     left, right = relation.first.start_pos, relation.second.end_pos
     from farg.apps.seqsee.util import GreaterThanEq, LessThanEq
     if tuple(
             controller.workspace.GetGroupsWithSpan(LessThanEq(left),
                                                    GreaterThanEq(right))):
         History.Note("CF_GroupFromRelation: a spanning group exists")
         return
     anchored = SAnchored.Create(
         (relation.first, relation.second),
         underlying_mapping_set=relation.mapping_set)
     try:
         controller.workspace.InsertGroup(anchored, parent=[me])
     except ConflictingGroupException as e:
         SubspaceDealWithConflictingGroups(
             controller,
             workspace_arguments=dict(new_group=anchored,
                                      incumbents=e.conflicting_groups),
             parents=[me, relation],
             msg="Conflict while inserting %s" %
             anchored.BriefLabel()).Run()
示例#12
0
 def __init__(self):
     self.stored_fringe = None
     History.Note("Focusable created")
     Categorizable.__init__(self)
示例#13
0
 def __init__(self, *, first, second):
     self.first = first
     self.second = second
     Categorizable.__init__(self)
     History.Note("Created relation")
示例#14
0
    def Run(cls, controller, item, *, me):
        if item not in controller.workspace.groups:
            History.Note("CF_ExtendGroup: item not in workspace")
            # item deleted?
            return
        # QUALITY TODO(Feb 14, 2012): Direction to extend choice can be
        # improved.
        extend_right = True
        if (item.start_pos > 0 and Toss(0.5)):
            extend_right = False

        parts = item.items
        underlying_mapping_set = item.object.underlying_mapping_set
        if not underlying_mapping_set:
            History.Note("CF_ExtendGroup: no underlying relations")
            return
        mapping = SelectWeightedByActivation(
            controller.ltm, underlying_mapping_set)
        if extend_right:
            next_part = mapping.Apply(parts[-1].object)
            if not next_part:
                History.Note(
                    "CF_ExtendGroup: could not apply mapping to last part")
                return
            magnitudes = next_part.FlattenedMagnitudes()
            number_of_known_elements = len(
                controller.workspace.elements) - item.end_pos - 1
            if len(magnitudes) > number_of_known_elements:
                # TODO(# --- Feb 14, 2012): This is where we may go beyond known elements.
                # To the extent that the next few elements are known, ensure that they agree with
                # what's known.
                if not controller.workspace.CheckForPresence(item.end_pos + 1,
                                                             magnitudes[:number_of_known_elements]):
                    return
                # The following either returns false soon if the user will not be asked, or asks
                # the user and returns the response. If the response is yes, the elements are also
                # added.
                should_continue = SubspaceGoBeyondKnown(
                    controller,
                    workspace_arguments=dict(basis_of_extension=item,
                                             suggested_terms=magnitudes),
                    parents=[me, item]).Run()
                if not should_continue:
                    return
            else:
                if not controller.workspace.CheckForPresence(item.end_pos + 1, magnitudes):
                    return
            next_part_anchored = SAnchored.CreateAt(
                item.end_pos + 1, next_part)
            new_parts = list(parts[:])
            new_parts.append(next_part_anchored)
        else:
            flipped = mapping.FlippedVersion()
            if not flipped:
                return
            previous_part = flipped.Apply(parts[0].object)
            if not previous_part:
                return
            magnitudes = previous_part.FlattenedMagnitudes()
            if len(magnitudes) > item.start_pos:
                return
            if not controller.workspace.CheckForPresence(item.start_pos - len(magnitudes),
                                                         magnitudes):
                return
            prev_part_anchored = SAnchored.CreateAt(item.start_pos - len(magnitudes),
                                                    previous_part)
            new_parts = [prev_part_anchored]
            new_parts.extend(parts)
        new_group = SAnchored.Create(new_parts,
                                     underlying_mapping_set={mapping})

        from farg.apps.seqsee.exceptions import ConflictingGroupException
        from farg.apps.seqsee.exceptions import CannotReplaceSubgroupException
        from farg.apps.seqsee.subspaces.deal_with_conflicting_groups import SubspaceDealWithConflictingGroups
        try:
            controller.workspace.Replace(item, new_group)
        except ConflictingGroupException as e:
            SubspaceDealWithConflictingGroups(
                controller,
                workspace_arguments=dict(new_group=new_group,
                                         incumbents=e.conflicting_groups),
                parents=[me, item],
                msg="Conflict when replacing item with enlarged group").Run()
        except CannotReplaceSubgroupException as e:
            SubspaceDealWithConflictingGroups(
                controller,
                workspace_arguments=dict(new_group=new_group,
                                         incumbents=e.supergroups),
                parents=[me, item],
                msg="Cannot replace subgp when extending item").Run()