0

I'd like to use the grim library to create and traverse graphs, but I don't understand how to access a graph having the label in a string.

import  grim
import sequtils


var g = newGraph("my graph")

let node = g.addNode("F4", %(Id: "none", desc: "OK"))
let dest = g.addNode("F8", %(Id: "dest"))

# get node knowing label?
let label1 = "F4"
echo g.node(label1)  # <--- this does not work:

This script returns:

unhandled exception: key not found: F4 [KeyError]

Can you tell me how to access a node having the label?

In my graph each label is unique, but it's not granted by the library so that can be the issue, so maybe I'm looking for a better attribute to use to uniquely identify a node.

Thanks for any advice!

Andrea T.
  • 920
  • 4
  • 15

1 Answers1

3

This library inserts the nodes with an oid. If you add a node without oid, it gets automatically generated, and it will be the index to look for in g.node(oid). But you can force a given oid, e.g.

import oids
import grim

var g = newGrap("my graph")
let myOid: string = $genOid()

let node = g.addNode("F4", %(Id: "none", desc: "OK"), oid=myOid)

echo g.node(myOid)

Remember to create a new oid for every node / edge you insert, or they would not get inserted:

let myoid = "dontdothis"

let node = g.addNode("F4", %(Id: "none", desc: "OK"), oid=myoid)
let dest = g.addNode("F8", %(Id: "dest"), oid=myoid) # Oh, no! Reusing myoid!

echo g
# <Graph "my graph" with 1 node(s) {"F4": 1} and 0 edge(s) {:}>
# Ops! dest node missing

Remember that g.addNode returns the oid corresponding to the inserted Node, so you can always do:

echo g.node(node)
echo g.node(dest)

The reason for this is that you can insert multiple nodes with the same label, but they are going to get a different oid. If you want to extract your nodes by label:

for node in g.nodes("F4"):
  echo node
  # Also available
  # node.label
  # node.oid

If you are 100% sure your labels are unique, just pass the label as oid:

let node = g.addNode("F4", %(Id: "none", desc: "OK"), oid="F4")
echo g.node("F4")
xbello
  • 7,223
  • 3
  • 28
  • 41
  • Thank you @xbello, this was exactly what I need as the file I parse is giving me unique ids for each node! I'm still checking if this library is suitable for my needs (probably), still looks the best candidate in Nim :) – Andrea T. Aug 20 '20 at 09:23