Source code for examples.graphs.directed_graph

  1. """a directed graph example."""
  2. from sqlalchemy import Column
  3. from sqlalchemy import create_engine
  4. from sqlalchemy import ForeignKey
  5. from sqlalchemy import Integer
  6. from sqlalchemy.ext.declarative import declarative_base
  7. from sqlalchemy.orm import relationship
  8. from sqlalchemy.orm import sessionmaker
  9. Base = declarative_base()
  10. class Node(Base):
  11. __tablename__ = "node"
  12. node_id = Column(Integer, primary_key=True)
  13. def higher_neighbors(self):
  14. return [x.higher_node for x in self.lower_edges]
  15. def lower_neighbors(self):
  16. return [x.lower_node for x in self.higher_edges]
  17. class Edge(Base):
  18. __tablename__ = "edge"
  19. lower_id = Column(Integer, ForeignKey("node.node_id"), primary_key=True)
  20. higher_id = Column(Integer, ForeignKey("node.node_id"), primary_key=True)
  21. lower_node = relationship(
  22. Node, primaryjoin=lower_id == Node.node_id, backref="lower_edges"
  23. )
  24. higher_node = relationship(
  25. Node, primaryjoin=higher_id == Node.node_id, backref="higher_edges"
  26. )
  27. def __init__(self, n1, n2):
  28. self.lower_node = n1
  29. self.higher_node = n2
  30. engine = create_engine("sqlite://", echo=True)
  31. Base.metadata.create_all(engine)
  32. session = sessionmaker(engine)()
  33. # create a directed graph like this:
  34. # n1 -> n2 -> n1
  35. # -> n5
  36. # -> n7
  37. # -> n3 -> n6
  38. n1 = Node()
  39. n2 = Node()
  40. n3 = Node()
  41. n4 = Node()
  42. n5 = Node()
  43. n6 = Node()
  44. n7 = Node()
  45. Edge(n1, n2)
  46. Edge(n1, n3)
  47. Edge(n2, n1)
  48. Edge(n2, n5)
  49. Edge(n2, n7)
  50. Edge(n3, n6)
  51. session.add_all([n1, n2, n3, n4, n5, n6, n7])
  52. session.commit()
  53. assert [x for x in n3.higher_neighbors()] == [n6]
  54. assert [x for x in n3.lower_neighbors()] == [n1]
  55. assert [x for x in n2.lower_neighbors()] == [n1]
  56. assert [x for x in n2.higher_neighbors()] == [n1, n5, n7]