示例#1
0
    def ForceNextCodelet(self, codelet, *, forcer=None):
        """Force codelet to be the next one retrieved by GetCodelet.

    Args:
      codelet:
        The codelet to force as the return value of the next GetCodelet.

    Raises:
      FargError:
        codelet is not in fact present in the coderack.

    .. Note::

      This mechanism should only be used during testing. It is unsafe in that if
      the codelet is expunged (because of new codelets being added), the program
      can crash. This will never happen if the next codelet is marked and
      GetCodelet called soon thereafter.
    """
        if codelet not in self._codelets:
            raise FargError(
                "Cannot mark a non-existant codelet as the next to retrieve.")
        self._forced_next_codelet = codelet
        if forcer:
            History.AddEvent(EventType.CODELET_FORCED,
                             "Codelet forced to be next",
                             [[codelet, ""], [forcer, "forcer"]])
        else:
            History.AddEvent(EventType.CODELET_FORCED,
                             "Codelet forced to be next", [[codelet, ""]])
示例#2
0
 def _ExpungeSomeCodelet(self):
     """Removes a codelet, chosen uniformly randomly."""
     codelet = random.choice(list(self._codelets))
     kLogger.info("Coderack over capacity: expunged codelet of family %s." %
                  codelet.family.__name__)
     self._RemoveCodelet(codelet)
     History.AddEvent(EventType.CODELET_FORCED, "Codelet expunged",
                      [[codelet, ""]])
示例#3
0
 def Step(self):
     """Executes the next (stochastically chosen) step in the model."""
     self.steps_taken += 1
     if self.ltm:
         self.ltm._timesteps = self.steps_taken
     self._AddRoutineCodelets()
     if not self.coderack.IsEmpty():
         codelet = self.coderack.GetCodelet()
         History.AddEvent(EventType.CODELET_RUN_START,
                          "Codelet run started", [[codelet, ""]])
         codelet.Run()
     if self.stopping_condition:
         if self.steps_taken % farg_flags.FargFlags.stopping_condition_granularity == 0:
             if self.stopping_condition(self):
                 raise StoppingConditionMet(codelet_count=self.steps_taken)
 def MergeObject(self, obj):
     merge_map = dict()
     merged = self._MergeObject(obj, merge_map)
     for old, new in merge_map.items():
         for tgt, rel in old.relations.items():
             effective_tgt = tgt
             if tgt in merge_map:
                 effective_tgt = merge_map[tgt]
             rel_in_arena = new.GetRelationTo(effective_tgt)
             rel_in_arena.MergeCategoriesFrom(rel)
     History.AddEvent(event_type=EventType.OBJ_MERGED,
                      log_msg="Merged",
                      item_msg_list=dict(obj="outside arena",
                                         merged="Inside arena"))
     return merged
 def Step(self):
     """Executes the next (stochastically chosen) step in the model."""
     self.steps_taken += 1
     if self.ltm:
         self.ltm._timesteps = self.steps_taken
     self._AddRoutineCodelets()
     if not self.coderack.IsEmpty():
         codelet = self.coderack.GetCodelet()
         roles = [[codelet, "codelet"]]
         for k, v in codelet.args.items():
             if hasattr(v, "_hid"):
                 roles.append([v, "Argument %s" % k])
         History.AddEvent(EventType.CODELET_RUN_START, "", roles)
         codelet.Run()
     if self.stopping_condition:
         if self.steps_taken % farg_flags.FargFlags.stopping_condition_granularity == 0:
             if self.stopping_condition(self):
                 raise StoppingConditionMet(codelet_count=self.steps_taken)
示例#6
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)
    def Run(self):
        """Runs the subspace by first trying to quickly estimate need for deeper exploration.

       If deeper exploration is called for, sets up the controller, workspace, and so forth,
       and runs the controller for upto the specified number of steps.
    """
        History.AddEvent(EventType.SUBSPACE_ENTER, "", [(self, '')])
        quick_reconn_result = self.QuickReconn()
        if quick_reconn_result.state == QuickReconnResults.kAnswerFound:
            History.AddEvent(EventType.SUBSPACE_EXIT, "Answer found",
                             [(self, '')])
            return quick_reconn_result.answer
        elif quick_reconn_result.state == QuickReconnResults.kAnswerCannotBeFound:
            History.AddEvent(EventType.SUBSPACE_EXIT, "Answer cannot be found",
                             [(self, '')])
            return None

        History.AddEvent(EventType.SUBSPACE_DEEPER_EX, "", [(self, '')])
        # So we need deeper exploration.
        parent_controller = self.parent_controller
        self.controller = self.controller_class(
            ui=parent_controller.ui,
            controller_depth=(parent_controller.controller_depth + 1),
            workspace_arguments=self.workspace_arguments,
            parent_controller=parent_controller)
        self.InitializeCoderack()
        try:
            self.controller.RunUptoNSteps(self.nsteps)
        except AnswerFoundException as e:
            History.AddEvent(EventType.SUBSPACE_EXIT, "Found answer",
                             [(self, '')])
            return e.answer
        except NoAnswerException:
            History.AddEvent(EventType.SUBSPACE_EXIT, "No answer",
                             [(self, '')])
            return None
        History.AddEvent(EventType.SUBSPACE_EXIT, "No answer", [(self, '')])
        return None
 def Run(self):
     self.Refresher()
     History.AddEvent(EventType.SETUP_FINISHED)
     self.ui.mw.mainloop()