示例#1
0
from xapian import InvalidOperationError

__author__ = 'Keyvan'

from opencog.atomspace import TruthValue
DEFAULT_TRUTH_VALUE = TruthValue(1, 1)


class Marker(object):  # Marker Class, usually used for marking!
    pass


class OtherThan(object):
    def __init__(self, seq):
        self.seq = seq

    def __eq__(self, other):
        for item in self.seq:
            if other == item:
                return False
        return True

    def __ne__(self, other):
        return not self.__eq__(other)


marker = Marker()  # A Marker


def subsets_of_len_two(seq):
    indexed_seq = list(seq)
示例#2
0
def look_at_face(face_id_node):
    face_id = int(float(face_id_node.name))
    # print "Python look at face id", face_id
    evl.look_at(face_id)
    return TruthValue(1, 1)
示例#3
0
def look_at_point(x_node, y_node, z_node):
    x = float(x_node.name)
    y = float(y_node.name)
    z = float(z_node.name)
    evl.look_at_point(x, y, z)
    return TruthValue(1, 1)
示例#4
0
def blink_rate(mean_node, var_node):
    mean = float(mean_node.name)
    var = float(var_node.name)
    # print "Python: blink-rate: ", mean, " variation ", var
    evl.blink_rate(mean, var)
    return TruthValue(1, 1)
示例#5
0
def do_wake_up():
    evl.wake_up()
    return TruthValue(1, 1)
示例#6
0
def test_add_nodes_large(atomspace, prep_atom):
    """Add n nodes in atomspace with python bindings"""
    n = 500000
    for i in xrange(n):
        atomspace.add_node(types.ConceptNode, str(i), TruthValue(.5, .5))
    return n
示例#7
0
def explore_saccade():
    # print "Python: Explore Saccade"
    evl.explore_saccade()
    return TruthValue(1, 1)
def notice_changes(atomspace):    
    tv_delta = 0.000001
    
    t = types
    
    times = atomspace.get_atoms_by_type(t.TimeNode)
    times = [f for f in times if f.name != "0"] # Related to a bug in the Psi Modulator system
    times = sorted(times, key= lambda t: int(t.name) )

    target_PredicateNodes = [x for x in atomspace.get_atoms_by_type(t.PredicateNode) if "DemandGoal" in x.name]

    for atom in target_PredicateNodes:
        target = T('EvaluationLink', [atom])

        # find all of the xDemandGoal AtTimeLinks in order, sort them, then check whether each one is higher/lower than the previous one.       
        
        atTimes = []
        times_with_update = []
        for time in times:
#            # Need to use unify because not sure what the arguments will be. But they must be the same...
#            template = Tree('AtTimeLink', target, time)
#            matches = find_conj( (template,) )
#            
#            # If this DemandGoal is in use there will be one value at each timestamp (otherwise none)
#            assert len(matches) < 2
#            matches[0].
            template = T('AtTimeLink', [target, time])
            a = atom_from_tree(template, atomspace)
            
            # Was the value updated at that timestamp? The PsiDemandUpdaterAgent is not run every cycle so many
            # timestamps will have no value recorded.
            if a.tv.count > 0:
                atTimes.append(a)
                times_with_update.append(time)
    
        if len(atTimes) < 2:
            continue
        
        for i, atTime in enumerate(atTimes[:-1]):
            atTime_next = atTimes[i+1]
            
            tv1 = atTime.tv.mean
            tv2 = atTime_next.tv.mean
            
            #print tv2-tv1
            
            if tv2 - tv1 > tv_delta:
                # increased
                pred = 'increased'
            elif tv1 - tv2 > tv_delta:
                # decreased
                pred = 'decreased'
            else:
                continue

            time2 = times_with_update[i+1]

            tv = TruthValue(1, 1.0e35)
            res = T('AtTimeLink',
                     T('EvaluationLink',
                                atomspace.add(t.PredicateNode, name=pred),
                                T('ListLink',
                                    target
                                )
                        ),
                     time2
                    )
            a = atom_from_tree(res, atomspace)
            a.tv = tv
            
            #print str(a)
            
            atTime.tv = TruthValue(0, 0)
def publish_behavior(event_node):
    # print "(Behavior event:", event_node.name, ")"
    evl.publish_behavior(event_node.name)
    return TruthValue(1, 1)
示例#10
0
    def initilization(self, atomspace):
        '''
        Initializes necessary variables. Loads rules.
        '''

        self.atomspace = atomspace

        self.PleonasticItNode = atomspace.add_node(types.AnchorNode,
                                                   'Pleonastic-it',
                                                   TruthValue(1.0, 100))
        self.currentPronounNode = atomspace.add_node(types.AnchorNode,
                                                     'CurrentPronoun',
                                                     TruthValue(1.0, 100))
        self.currentTarget = atomspace.add_node(types.AnchorNode,
                                                'CurrentTarget',
                                                TruthValue(1.0, 100))
        self.currentResult = atomspace.add_node(types.AnchorNode,
                                                'CurrentResult',
                                                TruthValue(1.0, 100))
        self.currentProposal = atomspace.add_node(types.AnchorNode,
                                                  'CurrentProposal',
                                                  TruthValue(1.0, 100))
        self.unresolvedReferences = atomspace.add_node(
            types.AnchorNode, 'Recent Unresolved references',
            TruthValue(1.0, 100))
        self.resolvedReferences = atomspace.add_node(types.AnchorNode,
                                                     'Resolved references',
                                                     TruthValue(1.0, 100))
        self.currentResolutionNode = atomspace.add_node(
            types.AnchorNode, 'CurrentResolution', TruthValue(1.0, 100))
        self.currentResolutionLink_proposal = self.atomspace.add_link(
            types.ListLink, [self.currentResolutionNode, self.currentProposal],
            TruthValue(1.0, 100))
        self.currentResolutionLink_pronoun = self.atomspace.add_link(
            types.ListLink,
            [self.currentResolutionNode, self.currentPronounNode],
            TruthValue(1.0, 100))
        self.pronounNumber = -1

        data = [
            "opencog/nlp/anaphora/rules/getChildren.scm",
            "opencog/nlp/anaphora/rules/getNumberNode_WordInstanceNode.scm",
            "opencog/nlp/anaphora/rules/getNumberNode_ParseNode.scm",
            "opencog/nlp/anaphora/rules/connectRootsToParseNodes.scm",
            "opencog/nlp/anaphora/rules/getAllNumberNodes.scm",
            "opencog/nlp/anaphora/rules/getAllParseNodes.scm",
            "opencog/nlp/anaphora/rules/getConjunction.scm",
            "opencog/nlp/anaphora/rules/getParseNode.scm",
            "opencog/nlp/anaphora/rules/getWords.scm",
            "opencog/nlp/anaphora/rules/isIt.scm",
            "opencog/nlp/anaphora/rules/filtersGenerator.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#1.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#2.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#3.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#4.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#5.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#6.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#7.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#8.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#9.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#10.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#11.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#12.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#13.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#14.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#15.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#16.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#17.scm",
            "opencog/nlp/anaphora/rules/filters/filter-#18.scm",
            "opencog/nlp/anaphora/rules/pre-process/pre-process-#1.scm",
            "opencog/nlp/anaphora/rules/pre-process/pre-process-#2.scm",
            "opencog/nlp/anaphora/rules/pre-process/pre-process-#3.scm",
            "opencog/nlp/anaphora/rules/pleonastic-it/pleonastic-it-#1.scm",
            "opencog/nlp/anaphora/rules/pleonastic-it/pleonastic-it-#2.scm",
            "opencog/nlp/anaphora/rules/pleonastic-it/pleonastic-it-#3.scm",
        ]

        self.numOfFilters = 20
        self.numOfPrePatterns = 3
        self.numOfPleonasticItPatterns = 3

        for item in data:
            load_scm(atomspace, item)

        self.getAllNumberNodes()
        self.pronouns = self.getTargets(self.getWords())
        self.roots = self.getRoots()
    def output_causal_implications_for_last_layer(self, layers):
        if len(layers) < 2:
            return
        layer = layers[-1]
        prev_layer = layers[-2]
        for (ptn, embs) in layer:
            conj = list(ptn.conj)
            seqs = list(ptn.seqs)
            
            if len(seqs) < 2:
                continue
            
            conclusion = seqs[-1]
            other = seqs[:-1]
            assert len(other)

            # Remove all of the AtTimeLinks from inside the sequence - just leave
            # the EvaluationLinks/ExecutionLinks. The AtTimeLinks are not
            # required/allowed if you have SequentialAndLinks etc. This won't change
            # the Pattern that Fishgram is storing - Fishgram's search does need
            # the AtTimeLinks.            
            conclusion_stripped = conclusion.args[1]
            other_stripped = [attime.args[1] for attime in other]
            
            # There are several special cases to simplify the Link produced.
            
            if len(other_stripped) > 1:
                # NOTE: this won't work if some of the things are simultaneous
                initial = Tree('SequentialAndLink',other_stripped)
            else:
                initial = other_stripped[0]
            
            predimp = T     ('PredictiveImplicationLink',
                                initial,
                                conclusion_stripped
                            )
            
            if len(conj) > 0:
                imp = T('ImplicationLink',
                        Tree('AndLink', conj),
                        predimp)
                payload = imp
            else:
                payload = predimp
            
            vars = get_varlist( conj + other_stripped + [conclusion_stripped] )
            assert len(vars)
            rule = T('AverageLink',
                     T('ListLink',vars),
                     payload
                    )

            # Calculate the frequency. Looking up embeddings only works if you keep the
            # AtTimeLinks.
            premises = conj + other
            premises_embs = self.forest.lookup_embeddings(premises)
            
            freq = len(embs) / len(premises_embs)
            
            a = atom_from_tree(rule, self.atomspace)
            self.rules_output.append(rule)
            
            a.tv = TruthValue(freq, len(embs))
示例#12
0
the ith accepted candidate will have confidence value of
(x^(i-1))(1-x)  i starts at 1.
'''

CONFIDENCE_DECREASING_RATE = 0.7
'''
Strength for accepted antecedents
'''

STRENGTH_FOR_ACCEPTED_ANTECEDENTS = 0.98
'''
Truth Value for antecendents which have been filtered out by filters.
'''

TV_FOR_FILTERED_OUT_ANTECEDENTS = TruthValue(
    0.02,
    TruthValue().confidence_to_count(0.9))
'''
========================================
'''


class BindLinkExecution():
    '''
    Executes a (cog-bind xxx) command and return the results of it
    '''
    def __init__(self, atomspace, anchorNode, target, command, resultNode,
                 atomType):
        '''
        Stores necessary information
        '''
示例#13
0
 def test_creation(self):
     a = Node("test1")
     self.assertEqual(a.name, "test1")
     self.assertEqual(a.tv,
                      TruthValue(1.0,
                                 0.0))  # default is true, no confidence
示例#14
0
 def test_creation(self):
     a = self.space.add_node(types.Node, "test1")
     self.assertEqual(a.name, "test1")
     self.assertEqual(a.tv, TruthValue(0.0, 0.0))
示例#15
0
def prep_traverse_1M(atomspace):
    """Add n nodes in atomspace with python bindings"""
    n = 1000000
    for i in xrange(n):
        atomspace.add_node(types.ConceptNode, str(i), TruthValue(.5, .5))
    return n, atomspace.get_atoms_by_type(types.ConceptNode)
示例#16
0
def listening_saccade():
    # print "Python: Listening Saccade"
    evl.listening_saccade()
    return TruthValue(1, 1)
示例#17
0
def prep_get_100K(atomspace):
    """Add n nodes in atomspace with python bindings"""
    n = 100000
    for i in xrange(n):
        atomspace.add_node(types.ConceptNode, str(i), TruthValue(.5, .5))
    return n
示例#18
0
def say_text(text_node):
    text = text_node.name
    evl.say_text(text)
    return TruthValue(1, 1)
示例#19
0
 def test_creation(self):
     a = self.space.add_node(types.Node, "test1")
     self.assertEqual(a.name, "test1")
     self.assertEqual(a.tv,
                      TruthValue(1.0,
                                 0.0))  # default is true, no confidence
示例#20
0
def bogus_tv(atom_one, atom_two) :
    return TruthValue(0.6, 0.234)
示例#21
0
def conversational_saccade():
    # print "Python: Conversational Saccade"
    evl.conversational_saccade()
    return TruthValue(1, 1)
示例#22
0
 def run(self,atomspace):
     attentional_focus = get_attentional_focus(atomspace)
     for node1 in attentional_focus:
         for node2 in attentional_focus:
             if node1 == node2:
                 continue
             print atomspace.add_edge(types.AsymmetricHebbianLink, [node1, node2], TruthValue(0.5,1))
示例#23
0
def ros_is_running():
    if (rospy.is_shutdown()):
        return TruthValue(0, 1)
    return TruthValue(1, 1)
示例#24
0
def load_scm_file(a, filename):
    log.info("loading...")
    tree = Viz_Graph()
    ident_stack = []
    atom_stack = []
    root = None
    define_dict = {}
    try:
        f = open(filename, "r")
        for line_no, line in enumerate(f.readlines()):
            # code...
            ## parase scheme file line by line
            ## parase "define"
            temp = line.strip('\n ()')
            if temp.startswith('define'):
                temp = temp.split(' ')
                define_dict[temp[1]] = temp[2]
                continue
                ##
            if line.startswith('('):
                if tree.number_of_nodes() > 0:
                    # deal with previous segment
                    add_tree_to_atomspace(a, tree, root)
                    tree.clear()
                    #
                ident_stack[:] = []
                atom_stack[:] = []
                ## parase a new segment
            name = ""
            t = ""
            stv = None
            av = {}
            ident = line.find("(")
            if ident != -1:
                #log.debug(line.strip('\n'))
                ident_stack.append(ident)
                # the first: type name
                # the second: stv or av
                # the third: stv or av
                l = line
                line = line.strip(' ')
                line = line.strip('\n')
                elms = line.split('(')
                first = elms[1]
                try:
                    second = elms[2]
                    second = second.split(')')[0]
                    second = dict_sub(second, define_dict)
                except Exception:
                    second = None

                try:
                    third = elms[3]
                    third = third.split(')')[0]
                    third = dict_sub(third, define_dict)
                except Exception:
                    third = None
                    #log.debug("********************" )
                #log.debug("first:%s*"%first)
                #log.debug("second:%s*"%second)
                #log.debug("third:%s*"%third)
                #log.debug("********************" )
                if second:
                    second = second.strip()
                    if second.find("av") != -1:
                        temp = second.split(" ")
                        av['sti'] = float(temp[1])
                        av['lti'] = float(temp[2])
                        av['vlti'] = float(temp[3])
                    elif second.find("stv") != -1:
                        temp = second.split(" ")
                        mean = float(temp[1])
                        confidence = float(temp[2])
                        # the value to stv!
                        stv = TruthValue(mean, confidence_to_count(confidence))

                if third:
                    third = third.strip()
                    if third.find("av") != -1:
                        temp = third.split(" ")
                        av['sti'] = float(temp[1])
                        av['lti'] = float(temp[2])
                        av['vlti'] = float(temp[3])
                    elif third.find("stv") != -1:
                        temp = third.split(" ")
                        mean = float(temp[1])
                        confidence = float(temp[2])
                        # the value to stv!
                        stv = TruthValue(mean, confidence_to_count(confidence))
                try:
                    t = first[0:first.index(' ')]
                    name = first[first.index(' ') + 1:-1].strip('"')
                    #log.debug("**********atom**************" )
                    #log.debug("type: %s"%t+"*" )
                    #log.debug("name: %s"%name+"*")
                    #log.debug("stv: %s"%stv)
                    #log.debug("av: %s"%av)
                    #log.debug("*****************************" )
                except Exception:
                    t = first.strip(' ')
                    ## add nodes to segment tree
                is_node = True if name else False
                if is_node:
                    # node
                    try:
                        node = FakeAtom(name_type_dict[t], name, stv, av)
                    except KeyError:
                        log.error(
                            "Unknown Atom type '%s' in line %s, pls add related type infomation to file 'types_inheritance.py' and OpenCog"
                            % (t, line_no))
                        raise KeyError
                    uni_node_id = tree.unique_id(name)
                    tree.add_node(uni_node_id, atom=node)
                    atom_stack.append(node)
                    if l.startswith('('):
                        root = uni_node_id
                else:
                    # link
                    uni_link_id = tree.unique_id(t)
                    #print "link:%s**"%t
                    try:
                        link = FakeAtom(name_type_dict[t], uni_link_id, stv,
                                        av)
                    except KeyError:
                        log.error("Unknown Atom type '%s' in line %s" %
                                  (t, line_no))
                        raise KeyError
                    atom_stack.append(link)
                    tree.add_node(uni_link_id, atom=link)
                    if l.startswith('('):
                        root = uni_link_id

                ## add an edge(between link and node, or link to sub_link) to the segment tree
                now = ident_stack[-1]
                for i, prev_ident in reversed(list(enumerate(ident_stack))):
                    if now > prev_ident:
                        ## the ith is parent, the link
                        if is_node:
                            log.debug("%s -> %s" %
                                      (atom_stack[i].name, uni_node_id))
                            tree.add_edge(atom_stack[i].name, uni_node_id)
                        else:
                            log.debug("%s -> %s" %
                                      (atom_stack[i].name, uni_link_id))
                            tree.add_edge(atom_stack[i].name, uni_link_id)
                            ## set the 'order' attribute
                        tree.get_node_attr(atom_stack[i].name).setdefault(
                            'order', -1)
                        tree.get_node_attr(atom_stack[i].name)['order'] += 1
                        order = tree.get_node_attr(atom_stack[i].name)['order']
                        if is_node:
                            tree.set_edge_attr(atom_stack[i].name,
                                               uni_node_id,
                                               order=order)
                        else:
                            tree.set_edge_attr(atom_stack[i].name,
                                               uni_link_id,
                                               order=order)
                        break

        ## deal with the last segment
        if tree.number_of_nodes() > 0:
            add_tree_to_atomspace(a, tree, root)
            tree.clear()
        log.info("loaded scm file sucessfully!")
    except IOError:
        log.error("failed to read file %s " % filename)
        raise IOError
    else:
        f.close()
示例#25
0
def do_go_sleep():
    evl.go_sleep()
    return TruthValue(1, 1)
def move_toward_block(block_atom):
    """
    Make bot move near the block. If there's no surrounding block info,
    the bot may find no place to stand on and stop moving.
    Also if there's no empty place near ( distance <= 2) the block,
    the bot will not move.
    Args:
        block_atom(opencog.atomspace.Atom): The atom representing block,
                towards which bot is made to move.

    Returns: TruthValue(1,1) if move success else TruthValue(0,1).

    TODO:
        Make it faster: the calculation of near place is slow.
        Add distance argument: make caller control the judgement of "near"
    """

    print 'move toward atom', block_atom

    # Get the block position info from the atomspace, to do this we query
    # spacemap.
    jump = False
    map_handle = (atomspace.get_atoms_by_name(
        types.SpaceMapNode, "MCmap")[0]).h
    cur_map = space_server.get_map(map_handle)
    cur_er = space_server.get_entity_recorder(map_handle)
    block_pos = cur_map.get_block_location(block_atom.h)

    # If we did not find the block in the spacemap than return false, otherwise
    # continue the function.
    if block_pos is None:
        print 'block position not found.', block_atom
        return TruthValue(0, 1)

    # Try to find an open block we can stand on near the target block.
    dest = get_near_free_point(
        atomspace, cur_map, block_pos, 2, (1, 0, 0), True)

    if dest is None:
        print 'get_no_free_point'

    print 'block_pos, dest', block_pos, dest

    # Get the position of the bot.
    self_handle = cur_er.get_self_agent_entity()
    self_pos = cur_er.get_last_appeared_location(self_handle)

    # Check to see if we are already standing where we want, if so then we are
    # done, otherwise actually pass the move call along to ROS.
    if (math.floor(self_pos[0]) == dest[0]
            and math.floor(self_pos[1]) == dest[1]
            and math.floor(self_pos[2]) == dest[2]):
        print 'has arrived there'
        return TruthValue(1, 1)
    else:
        # Pass the call to ROS and return its success value back to the caller of this function.
        # TODO: In Minecraft the up/down direction is y coord
        # but we should swap y and z in ros node, not here..
        response = _ros_set_move(block_pos[0], block_pos[1], jump)
        # TODO: The AI is expected to finish a full step in less than 1 second,
        # so we should figure out a better value for this wait timer.
        rospy.sleep(1)
        print 'action_schemas: abs_move response', response
        if response.state:
            print 'move success'
            return TruthValue(1, 1)
        else:
            print 'move fail'
            return TruthValue(0, 1)
示例#27
0
def gaze_at_face(face_id_node):
    face_id = int(float(face_id_node.name))
    print "Python gaze at face id", face_id
    evl.gaze_at(face_id)
    return TruthValue(1, 1)
示例#28
0
def _tv_from_dict(d):
    stv_dict = d['simple']
    return TruthValue(stv_dict['str'], stv_dict['count'])
示例#29
0
__author__ = 'keyvan&ramin'

from opencog.atomspace import AtomSpace, TruthValue
import quad_reader

DEFAULT_TV = TruthValue(1, 1)


def map_from_path(quad_dump_path, atomspace):
    quads = quad_reader.extract_quads(quad_dump_path)
    for quad in quads:
        try:
            value = int(quad.value)
            value_node_type = 'NumberNode'
        except:
            value_node_type = 'ConceptNode'

        if quad.value is None:
            atomspace.add_link('EvaluationLink', [
                atomspace.add_node('PredicateNode', quad.predicate,
                                   DEFAULT_TV),
                atomspace.add_link('ListLink', [
                    atomspace.add_node('ObjectEntityNode', quad.subject,
                                       DEFAULT_TV),
                    atomspace.add_node('ObjectEntityNode', quad.destination,
                                       DEFAULT_TV)
                ])
            ])
        elif quad.destination is None:
            atomspace.add_link('EvaluationLink', [
                atomspace.add_node('PredicateNode', quad.predicate,
示例#30
0
文件: utils.py 项目: raschild6/rocca
# OpenCog
from opencog.atomspace import AtomSpace, TruthValue
from opencog.atomspace import types
from opencog.atomspace import get_type, is_a
from opencog.exec import execute_atom
from opencog.type_constructors import *
from opencog.spacetime import *
from opencog.pln import *
from opencog.utilities import is_closed, get_free_variables
from opencog.logger import Logger, log, create_logger

#############
# Constants #
#############

TRUE_TV = TruthValue(1, 1)
DEFAULT_TV = TruthValue(1, 0)

#############
# Variables #
#############

agent_log = create_logger("opencog.log")
agent_log.set_component("Agent")

#############
# Functions #
#############


def has_non_null_confidence(atom):