Exemple #1
0
    def test_unifier(self):

        scheme_eval(self.space, "(use-modules (opencog exec))")
        question = scheme_eval_h(self.space, "find-animals")
        self.assertTrue(question)
        print("\nThe question is:", question)

        answer = scheme_eval_h(self.space, "(cog-execute! find-animals)")
        self.assertTrue(answer)
        print("\nThe answer is:", answer)
        self.assertEqual(answer.type, types.SetLink)
        self.assertEqual(answer.arity, 3)
Exemple #2
0
    def pln_bc(self, query, vardecl=None, maxiter=10, rules=[]):
        """Call PLN backward chainer with the given query and parameters.

        The parameters are

        maxiter: the maximum number of iterations.
        rules: optional list of rule symbols.  If empty keep current rule set.

        Return a python list of solutions.

        """

        agent_log.fine("pln_bc(query={}, maxiter={})".format(query, maxiter))

        # Add rules (should be previously loaded)
        if rules:
            scheme_eval(self.atomspace, "(pln-rm-all-rules)")
            for rule in rules:
                er = scheme_eval(self.atomspace,
                                 "(pln-add-rule '" + rule + ")")
                agent_log.info("(pln-add-rule '" + rule + ")")
                agent_log.info("er = " + str(er))

        # Generate and run query
        command = "(pln-bc "
        command += str(query)
        command += ("#:vardecl " + str(vardecl)) if vardecl else ""
        command += " #:maximum-iterations " + str(maxiter)
        command += ")"
        return scheme_eval_h(self.atomspace, command).out
Exemple #3
0
    def test_d_eval(self):
        basic = scheme_eval_h(self.space,
                              "(ConceptNode \"whatever\" (stv 0.5 0.5))")

        a1 = self.space.add_node(types.ConceptNode, "whatever")
        self.assertTrue(a1)

        # Make sure the truth value is what's in the SCM file.
        expected = TruthValue(0.5, 0.5)
        self.assertEquals(a1.tv, expected)

        # Actually, the atoms overall should compare.
        self.assertEquals(a1, basic)

        # Do it again, from a define in the scm file.
        again = scheme_eval_h(self.space, "wobbly")
        a2 = self.space.add_node(types.ConceptNode, "wobbly")
        self.assertTrue(a2)
        self.assertEquals(a2, again)
Exemple #4
0
    def pln_bc(self, query, maxiter):
        """Call PLN backward chainer with the given query and parameters.

        Return a python list of solutions.

        """

        command = "(pln-bc "
        command += str(query)
        command += " #:maximum-iterations " + str(maxiter)
        command += ")"
        return scheme_eval_h(self.atomspace, command).out
Exemple #5
0
    def predictive_implication_scope_query(self, goal, expiry):
        """Build a PredictiveImplicationScope query for PLN.

        """

        vardecl = VariableNode("$vardecl")
        antecedent = VariableNode("$antecedent")
        # TODO: fix python PredictiveImplicationScopeLink binding!
        # query = QuoteLink(PredictiveImplicationScopeLink(UnquoteLink(vardecl),
        #                                                  to_nat(expiry),
        #                                                  UnquoteLink(antecedent),
        #                                                  goal))
        query = QuoteLink(
            scheme_eval_h(
                self.atomspace, "(PredictiveImplicationScopeLink " +
                str(UnquoteLink(vardecl)) + str(to_nat(expiry)) +
                str(UnquoteLink(antecedent)) + str(goal) + ")"))
        return query
Exemple #6
0
def atomspace_roots(atomspace: AtomSpace) -> set[Atom]:
    """Return all roots of an atomspace."""

    return set(scheme_eval_h(atomspace, "(List (cog-get-all-roots))").out)
Exemple #7
0
    def mine_temporal_patterns(self,
                               lagged_antecedents_succedents,
                               vardecl=None):
        """Given nested lagged, antecedents, succedents, mine temporal patterns.

        More precisely it takes a list of triples

        (lag, antecedents, succedents)

        where antecedents and succedents can themselves be triples of
        lagged antecedents and succedents.

        For instance the input is

        (lag-2, (lag-1, X, Y), Z)

        then it is transformed into the following initial pattern

        Present
          AtTime
            X
            T
          AtTime
            Y
            T + lag-1
          AtTime
            Z
            T + lag-1 + lag-2

        which the miner can start from.

        If no vardecl is provided then it is assumed to be composed of
        all free variables in all antecedents and succedents.

        """

        agent_log.fine(
            "mine_temporal_patterns(lagged_antecedents_succedents={}, vardecl={})"
            .format(lagged_antecedents_succedents, vardecl))

        # Set miner parameters
        minsup = 4
        maxiter = 1000
        cnjexp = "#f"
        enfspe = "#t"
        mspc = 6
        maxvars = 8
        maxcjnts = 6
        surprise = "'nisurp"
        T = VariableNode("$T")
        ignore = SetLink(T)

        # Define initial pattern
        # TODO: support any lag and vardecl
        timed_clauses, _ = self.to_timed_clauses(lagged_antecedents_succedents,
                                                 T)
        agent_log.fine("timed_clauses = {}".format(timed_clauses))
        if not vardecl:
            variables = set([T])
            variables.update(get_free_variables_of_atoms(timed_clauses))
            vardecl = VariableSet(*variables)
        initpat = LambdaLink(vardecl, PresentLink(*timed_clauses))

        # Launch pattern miner
        # " #:ignore " + str(ignore) + \
        mine_query = "(cog-mine " + str(self.percepta_record) + \
            " #:minimum-support " + str(minsup) + \
            " #:initial-pattern " + str(initpat) + \
            " #:maximum-iterations " + str(maxiter) + \
            " #:conjunction-expansion " + cnjexp + \
            " #:enforce-specialization " + enfspe + \
            " #:maximum-variables " + str(maxvars) + \
            " #:maximum-conjuncts " + str(maxcjnts) + \
            " #:maximum-spcial-conjuncts " + str(mspc) + \
            " #:surprisingness " + surprise + ")"
        agent_log.fine("mine_query = {}".format(mine_query))
        surprises = scheme_eval_h(self.atomspace, "(List " + mine_query + ")")
        agent_log.fine("surprises = {}".format(surprises))

        return surprises.out
Exemple #8
0
    def to_predictive_implication_scope(self, pattern):
        """Turn a given pattern into a predictive implication scope with its TV.

        For instance if the pattern is

        Lambda
          Variable "$T"
          Present
            AtTime
              Execution
                Schema "Eat"
              Variable "$T"
            AtTime
              Evaluation
                Predicate "Reward"
                Number 1
              S
                Variable "$T"

        then the resulting predictive implication scope is

        PredictiveImplicationScope
          VariableList
          S Z
          Execution
            Schema "Eat"
          Evaluation
            Predicate "Reward"
            Number 1

        Note the empty variable declaration.

        However if the pattern is

        Lambda
          VariableList
            Variable "$T"
            Variable "$A"
          Present
            AtTime
              Evaluation
                Predicate "Eatable"
                Variable "$X"
              Variable "$T"
            AtTime
              Execution
                Schema "Eat"
              Variable "$T"
            AtTime
              Evaluation
                Predicate "Reward"
                Number 1
              S
                Variable "$T"

        then the resulting predictive implication scope is

        PredictiveImplicationScope
          Variable "$X"
          S Z
          And
            Evaluation
              Predicate "Eatable"
              Variable "$X"
            Execution
              Schema "Eat"
          Evaluation
            Predicate "Reward"
            Number 1

        TODO: for now if the succedent is

          Evaluation
            Predicate "Reward"
            Number 0

        then the resulting predictive implication (scope) is

        PredictiveImplication <1 - s, c>
          <antecedent>
          Evaluation
            Predicate "Reward"
            Number 1

        that is the negative goal is automatically converted into a
        positive goal with low strength on the predictive implication.

        """

        agent_log.fine(
            "to_predictive_implication_scope(pattern={})".format(pattern))

        # Get the predictive implication implicant and implicand
        # respectively
        pt = self.to_predictive_implicant(pattern)
        pd = self.to_predictive_implicand(pattern)

        agent_log.fine("pt = {}".format(pt))
        agent_log.fine("pd = {}".format(pd))

        # HACK: big hack, pd is turned into positive goal
        if pd == self.negative_goal:
            pd = self.positive_goal

        # Get lag, for now set to 1
        lag = SLink(ZLink())

        ntvardecl = self.get_nt_vardecl(pattern)
        # TODO: fix python PredictiveImplicationScopeLink binding!
        # preimp = PredictiveImplicationScopeLink(ntvardecl, lag, pt, pd)
        preimp = scheme_eval_h(
            self.atomspace, "(PredictiveImplicationScopeLink " +
            str(ntvardecl) + str(lag) + str(pt) + str(pd) + ")")
        # Make sure all variables are in the antecedent
        vardecl_vars = set(get_free_variables(ntvardecl))
        pt_vars = set(get_free_variables(pt))
        agent_log.fine("vardecl_vars = {}".format(vardecl_vars))
        agent_log.fine("pt_vars = {}".format(pt_vars))
        if vardecl_vars != pt_vars:
            return None

        agent_log.fine("preimp = {}".format(preimp))
        # Calculate the truth value of the predictive implication
        mi = 2
        return self.pln_bc(preimp, mi)[0]
Exemple #9
0
    def get_percepta(self):
        """Return the list of all percepta record members."""

        cmd = "(List (get-members " + str(self.percepta_record) + "))"
        return scheme_eval_h(self.atomspace, cmd).out
Exemple #10
0
    def mine_temporal_patterns(self,
                               lag=1,
                               prectxs=[],
                               postctxs=[],
                               vardecl=None):
        """Given a lag, pre and post contexts, mine temporal patterns.

        That is mine patterns specializing the following

        Present
          AtTime
            <prectx-1>
            T
          ...
          AtTime
            <prectx-n>
            T
          AtTime
            <postctx-1>
            T + <lag>
          ...
          AtTime
            <postctx-m>
            T + <lag>

        where
          prectxs = [prectx-1, ..., prectx-n]
          postctxs = [postctx-1, ..., postctx-n]

        If no vardecl is provided then it is assumed to be composed of
        all free variables in prectxs and postctxs.

        """

        agent_log.fine(
            "mine_temporal_patterns(lag={}, prectxs={}, postctxs={})".format(
                lag, prectxs, postctxs))

        # Set miner parameters
        minsup = 8
        maxiter = 1000
        cnjexp = "#f"
        enfspe = "#t"
        mspc = 4
        maxvars = 10
        maxcjnts = 4
        surprise = "'nisurp"

        # Define initial pattern
        # TODO: support any lag and vardecl
        T = VariableNode("$T")
        timed_prectxs = [AtTimeLink(prectx, T) for prectx in prectxs]
        timed_postctxs = [
            AtTimeLink(postctx, SLink(T)) for postctx in postctxs
        ]
        if not vardecl:
            variables = set([T])
            variables.update(get_free_variables_of_atoms(prectxs))
            variables.update(get_free_variables_of_atoms(postctxs))
            vardecl = VariableSet(*variables)
        if not vardecl:
            initpat = LambdaLink(PresentLink(*timed_prectxs, *timed_postctxs))
        else:
            initpat = LambdaLink(vardecl,
                                 PresentLink(*timed_prectxs, *timed_postctxs))

        # Launch pattern miner
        mine_query = "(cog-mine " + str(self.percepta_record) + \
            " #:minimum-support " + str(minsup) + \
            " #:initial-pattern " + str(initpat) + \
            " #:maximum-iterations " + str(maxiter) + \
            " #:conjunction-expansion " + cnjexp + \
            " #:enforce-specialization " + enfspe + \
            " #:maximum-variables " + str(maxvars) + \
            " #:maximum-conjuncts " + str(maxcjnts) + \
            " #:maximum-spcial-conjuncts " + str(mspc) + \
            " #:surprisingness " + surprise + ")"
        agent_log.fine("mine_query = {}".format(mine_query))
        surprises = scheme_eval_h(self.atomspace, "(List " + mine_query + ")")
        agent_log.fine("surprises = {}".format(surprises))

        return surprises.out