# How to define a graph using Cartesian coordinates

I am trying to figure out (1) how to input a graph into Sage where the vertices are described as Cartesian coordinates (3-tuples), and then (2) for each pair of vertices, compute the Euclidean distance between the two and, if the Euclidean distance is some fixed value $d$, add an edge between these two vertices.

Specifically, here are my questions:

1. How do I input a graph into Sage where the vertices are described as Cartesian coordinates (3-tuples)?
2. Is there a pre-defined function in Sage for computing the Euclidean distance between two Cartesian coordinates?
edit retag close merge delete

Sort by » oldest newest most voted

For the first question, you can see the documentation of the Graph constructor by typing Graph?. You will see that it is possible to define a graph from its vertex set and a property defined by pairs of vertices that defines an edge if True:

  9. "Graph([V, f])" -- return a graph from a vertex set "V" and a *symmetric* function "f".
The graph contains an edge u,v whenever "f(u,v)" is "True"..
Example: "Graph([ [1..10], lambda x,y: abs(x-y).is_square()])"


For your second question, you can use the .norm() method of vectors (since the distance between two vectors is the norm of the difference of the vectors): you can transform a tuple into a vector as follows:

sage: t=(3,4,1)
sage: v = vector(RDF, t)
sage: v.norm()
5.0990195135927845


So, you can combine everything into a one-liner as follows:

sage: d = 3
sage: L = [(0,0,0), (1,2,3), (1,1,1), (1,0,1)]
sage: G = Graph([L, lambda u,v: (vector(RDF, u)-vector(RDF, v)).norm() <= d])
sage: G
Looped graph on 4 vertices
sage: G.plot()

more

This was very helpful. Thank you!

( 2016-05-27 19:00:45 -0500 )edit