Is there a way to traverse the atomspace using Python Bindings?

23 views
Skip to first unread message

Xabush Semrie

unread,
Jan 6, 2020, 6:20:05 AM1/6/20
to opencog

I want to traverse the whole atomspace loaded using Python API. So far I have tried this:


from opencog.atomspace import types

links = atomspace.get_atoms_by_type(types.Link)
#nodes = atomspace.get_atoms_by_type(types.Node)

def traverse_atomspace(lns):
  for link in lns:
    link_arr = []
    traverse_atomspace_helper(link, link_arr)
     
def traverse_atomspace_helper(link, container):
  if len(link.out) == 0:
    return  
  for atom  in link.out:
    if len(atom.out) != 0: # it is a link by itself
      traverse_atomspace_helper(atom, container)
    else:
      print(atom)
       
traverse_atomspace(links)

This prints the all the atoms as it traverses through each link. But I was wondering if there is a better way to do it? Can we use pattern matcher functions “natively”? i.e without going through scheme_eval madness?


Linas Vepstas

unread,
Jan 6, 2020, 3:51:54 PM1/6/20
to opencog
? There is no `scheme_eval` in the snippet of code that you just posted.

You can get all atoms (links and nodes, at the same time) by saying
atomspace.get_atoms_by_type(types.Atom)
which will return both.  That way, you don't need the call to `
traverse_atomspace_helper`

There are two bugs in
traverse_atomspace_helper
One bug is that it will print many atoms more than once (potentially duplicating thousands or millions of times).   The other bug is that there are links with no outgoing sets that are perfectly valid -- e.g. (TrueLink) or the empty set (SetLink) and so on. 

You don't need the pattern matcher to "traverse the whole atomspace". the get-atoms-by-type will return all of them, without any missing, without any duplicates.

(I mean, you can write a pattern matcher query that will run on the entire atomspace, but this is usually undesirable, since .. it eats cpu time.)

--linas

--
You received this message because you are subscribed to the Google Groups "opencog" group.
To unsubscribe from this group and stop receiving emails from it, send an email to opencog+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/opencog/CA%2B0j2108ZrGFwqrdZcuLAMwy0FDAbE18_ic67dk1WVgRmTiyxA%40mail.gmail.com.


--
cassette tapes - analog TV - film cameras - you

Vitaly Bogdanov

unread,
Jan 13, 2020, 4:43:45 AM1/13/20
to opencog
It depends on your goal, but the simplest way to iterate through all atoms in Python API is:
```
space = AtomSpace()
for atom in space:
    print('atom:', atom)
```

Best regards,
  Vitaly
To unsubscribe from this group and stop receiving emails from it, send an email to ope...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages