[Math] Sage Math: How to read input data for a graph from a file

graph theorymath-softwaresagemath

The help center seems to indicate that this topic is suited for here, as software that mathematicians use, apologies if this is incorrect.

So, I'm brand new to Sage, and I've only ever messed with a little Python. (I am an experienced programmer though.)

I'm trying to create a little example in Sage where I construct a graph (graph theory, not coordinate) by reading in a list of nodes and edges from a text file.

I'd like to take input in the following format, where every node name is given, followed by a space, the pipe character, a space, and then a comma spaced list of nodes to create edges to, e.g.:

A | B, C
B | A, J, G, K
C | A
...
J | B, Q

Acceptable methods would be either directly reading and parsing the input from a file stored somewhere, or pasting data from a text file into some kind of text box.

Best Answer

Basically this should be easy (given your programming background). Three steps.

  1. Make all your vertices into strings, "A" instead of A.
  2. Turn your list into a Python dictionary, where for each thing before the pipe you associate the list of connected vertices, e.g. {"A":["B","C"]} (except the dict should be all of these correspondences).
  3. Turn it into a graph by doing Graph(my_dict).

I think this should work, unless your connection lists are not consistent. See here.

Graph({"A":["B", "C"], "B":["A", "J", "G", "K"],"C":["A"]})

enter image description here

Related Question