Commits

Santiago Payà Miralta  committed 9734463

Code ordered.

  • Participants
  • Parent commits 9e0abe8

Comments (0)

Files changed (15)

File class_edge.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+"""
+Define base class `edge' with the minimal attributes as abstract 
+attributes.
+
+Every element in the network has:
+
+* level: topological level, ISO level, layer, ...
+* id: its own identifier.
+* iddown: in which element is this element encapsulated into.
+* idtype: what kind of element is.
+
+And in linear (edges) elements that connects two puntual (nodes) elements
+there are:
+
+* idnA: one side connection point id.
+* idnB: other side id.
+
+"""
+
+class edge:
+    """Simple class with basic attributes."""
+    def __init__(self, level, idnA, idnB, iddown, downlevel, idtype):
+        self.id = None
+        self.level = level
+        self.idnA = idnA
+        self.idnB = idnB
+        self.iddown = iddown
+        self.downlevel = downlevel
+        self.idtype = idtype
+    
+    def store(self, db):
+        # TODO idnA and idnB should be from the same level. INTERFACE ??
+        # TODO iddown should be from downlevel level. INTERFACE ??
+        if self.id:
+            st = "UPDATE gn_" + str(self.level) + "_edges SET " \
+                "idnA = " + str(self.idnA) + ", " \
+                "idnB" + str(self.idnB) + ", " \
+                "iddown = " + str(self.iddown) + ", " \
+                "downlevel = " + str(self.downlevel) + ", " \
+                "idtype = " + str(self.idtype) + " " \
+                "WHERE id = " + str(self.id) + ";"
+            db.query(st)
+            return st
+        else:
+            st = "INSERT INTO gn_" + str(self.level) + "_edges(idna, idnb, iddown, downlevel, idtype) " \
+                "VALUES(" \
+                + str(self.idnA) + ", " \
+                + str(self.idnB) + ", " \
+                + str(self.iddown) + ", " \
+                + str(self.downlevel) + ", " \
+                + str(self.idtype) + ") " \
+                "RETURNING id;"
+            self.id = db.query(st).getresult()[0][0]
+            return self.id
+        

File class_node.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+"""
+Define base class `node' with the minimal attributes as abstract 
+attributes.
+
+Every element in the network has:
+
+* level: topological level, ISO level, layer, ...
+* id: its own identifier.
+* iddown: in which element is this element encapsulated into.
+* idtype: what kind of element is.
+
+Also every puntual element (node) has a topological description:
+
+* idtopo: may be end point, one to one connector or fork connector.
+
+"""
+
+class node:
+    """Simple class with basic attributes."""
+    def __init__(self, level, iddown, downlevel, idtype):
+        self.id = None
+        self.level = level
+        self.iddown = iddown
+        self.downlevel = downlevel
+        self.idtype = idtype
+    
+    def store(self, db):
+        # TODO iddown should be from downlevel level. INTERFACE ??
+        if self.id:
+            st = "UPDATE gn_" + str(self.level) + "_nodes SET " \
+                "iddown = " + str(self.iddown) + ", " \
+                "downlevel = " + str(self.downlevel) + ", " \
+                "idtype = " + str(self.idtype) + " " \
+                "WHERE id = " + str(self.id) + ";"
+            db.query(st)
+            return st
+        else:
+            st = "INSERT INTO gn_" + str(self.level) + "_nodes(iddown, downlevel, idtype) " \
+                "VALUES(" \
+                + str(self.iddown) + ", " \
+                + str(self.downlevel) + ", " \
+                + str(self.idtype) + ") " \
+                "RETURNING id;"
+            self.id = db.query(st).getresult()[0][0]
+            return self.id

File classes.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-"""
-Define base classes `node' and `edge' with the minimal attributes as abstract 
-attributes, and the stack of the network.
-
-Every element in the network has:
-
-* level: topological level, ISO level, layer, ...
-* id: its own identifier.
-* iddown: in which element is this element encapsulated into.
-* idtype: what kind of element is.
-
-Also every puntual element (node) has a topological description:
-
-* idtopo: may be end point, one to one connector or fork connector.
-
-And in linear (edges) elements that connects two puntual (nodes) elements
-there are:
-
-* idnA: one side connection point id.
-* idnB: other side id.
-
-TODO Should add graph treatement somewhere (networkx, ...) so 'idtopo'
-is not necessary.
-"""
-
-class node:
-    """Simple class with basic attributes."""
-    def __init__(self, level, id, iddown, idtype, idtopo):
-        self.level = level
-        self.id = id
-        self.iddown = iddown
-        self.idtype = idtype
-        self.idtopo = idtopo
-
-class edge:
-    """Simple class with basic attributes."""
-    def __init__(self, level, id, idnA, idnB, iddown, idtype):
-        self.level = level
-        self.id = id
-        self.idnA = idnA
-        self.idnB = idnB
-        self.iddown = iddown
-        self.idtype = idtype
-
-"""
-Bottom level - 00
-=================
-
-Geometry. Points and Arcs in geometry talking.
-
-TODO Should add real geometry somewhere (postgis, ...). 
-"""
-
-class node00(node):
-    """Geometric points has no attributes but the id."""
-    def __init__(self, id, iddown=None, idtype=None, idtopo=None):
-        node.__init__(self, '00', id, None, None, None)
-
-class edge00(edge):
-    """Geometric arcs has no attributes but the id. Do not like strict 
-drawing, so 'idnA' and 'idnB' should be 'None', but it's interesting make
-the schema standard."""
-    def __init__(self, id, idnA=None, idnB=None, iddown=None, idtype=None):
-        edge.__init__(self, '00', id, idnA, idnB, None, None)  
-
-    """The length of the arc is a derived attribute from its geomerty."""
-    len = 1.0    
-
-"""
-First level - 01
-================
-
-Here start the pyramid. First layer may be the infrastructure of the network. 
-
-Infrastructure layer are similar to vaults, poles, etc as nodes and trails, 
-tunnels, etc as edges.
-"""
-
-class node01(node):
-    """Vaults, poles, ..."""
-    def __init__(self, id, iddown, idtype, idtopo):
-        node.__init__(self, '01', id, iddown, idtype, idtopo)
-
-    """The owner of the element."""
-    owner = 'SPiM'
-
-class edge01(edge):
-    """Trails, tunnels, ..."""
-    def __init__(self, id, idnA, idnB, iddown, idtype):
-        edge.__init__(self, '01', id, idnA, idnB, iddown, idtype)
-
-    """The owner of the element."""
-    owner = 'SPiM'
-
-"""
-doctest it.
-"""
-def _test():
-    import doctest
-    doctest.testmod(verbose=True)
-            
-if __name__ == "__main__":
-    _test()

File classes_postgre.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-"""
-Define base classes `node' and `edge' with the minimal attributes as abstract 
-attributes, and the stack of the network.
-
-Every element in the network has:
-
-* level: topological level, ISO level, layer, ...
-* id: its own identifier.
-* iddown: in which element is this element encapsulated into.
-* idtype: what kind of element is.
-
-Also every puntual element (node) has a topological description:
-
-* idtopo: may be end point, one to one connector or fork connector.
-
-And in linear (edges) elements that connects two puntual (nodes) elements
-there are:
-
-* idnA: one side connection point id.
-* idnB: other side id.
-
-"""
-
-class node:
-    """Simple class with basic attributes."""
-    def __init__(self, level, iddown, downlevel, idtype):
-        self.id = None
-        self.level = level
-        self.iddown = iddown
-        self.downlevel = downlevel
-        self.idtype = idtype
-    
-    def store(self, db):
-        # TODO iddown should be from downlevel level. INTERFACE ??
-        if self.id:
-            st = "UPDATE gn_" + str(self.level) + "_nodes SET " \
-                "iddown = " + str(self.iddown) + ", " \
-                "downlevel = " + str(self.downlevel) + ", " \
-                "idtype = " + str(self.idtype) + " " \
-                "WHERE id = " + str(self.id) + ";"
-            db.query(st)
-            return st
-        else:
-            st = "INSERT INTO gn_" + str(self.level) + "_nodes(iddown, downlevel, idtype) " \
-                "VALUES(" \
-                + str(self.iddown) + ", " \
-                + str(self.downlevel) + ", " \
-                + str(self.idtype) + ") " \
-                "RETURNING id;"
-            self.id = db.query(st).getresult()[0][0]
-            return self.id
-
-class edge:
-    """Simple class with basic attributes."""
-    def __init__(self, level, idnA, idnB, iddown, downlevel, idtype):
-        self.id = None
-        self.level = level
-        self.idnA = idnA
-        self.idnB = idnB
-        self.iddown = iddown
-        self.downlevel = downlevel
-        self.idtype = idtype
-    
-    def store(self, db):
-        # TODO idnA and idnB should be from the same level. INTERFACE ??
-        # TODO iddown should be from downlevel level. INTERFACE ??
-        if self.id:
-            st = "UPDATE gn_" + str(self.level) + "_edges SET " \
-                "idnA = " + str(self.idnA) + ", " \
-                "idnB" + str(self.idnB) + ", " \
-                "iddown = " + str(self.iddown) + ", " \
-                "downlevel = " + str(self.downlevel) + ", " \
-                "idtype = " + str(self.idtype) + " " \
-                "WHERE id = " + str(self.id) + ";"
-            db.query(st)
-            return st
-        else:
-            st = "INSERT INTO gn_" + str(self.level) + "_edges(idna, idnb, iddown, downlevel, idtype) " \
-                "VALUES(" \
-                + str(self.idnA) + ", " \
-                + str(self.idnB) + ", " \
-                + str(self.iddown) + ", " \
-                + str(self.downlevel) + ", " \
-                + str(self.idtype) + ") " \
-                "RETURNING id;"
-            self.id = db.query(st).getresult()[0][0]
-            return self.id
-        

File db_connection.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+
+import pg
+import readline  # So raw_input() uses line editing and history.
+
+##
+# Connection. 
+#
+pwd = raw_input('Password: ')
+db = pg.DB('genet', 'localhost', 5432, None, None, 'santiago', pwd)

File db_schema.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+
+from db_connection import db
+
+def startSchema():
+    """
+    Start the db schema. Must be ran only once because restarts the master
+    sequence and the type tables.
+    """
+    
+    ##
+    # All identiers of networks elements has the same sequence source.
+    # 
+    st = """
+    DROP SEQUENCE IF EXISTS "gn_xx_ids_seq" CASCADE;
+    CREATE SEQUENCE "gn_xx_ids_seq" 
+      INCREMENT 1 
+      MINVALUE 100000000 
+      NO MAXVALUE 
+      NO CYCLE;
+    """
+    print st
+    db.query(st)
+    
+    ##
+    # Out from basic schema all tables are referenced by this ones.
+    #
+    st = """
+    DROP TABLE IF EXISTS "gn_xx_node_types" CASCADE;
+    CREATE SEQUENCE "gn_xx_node_types_seq";
+    CREATE TABLE "gn_xx_node_types" (
+        "id" integer NOT NULL DEFAULT nextval('gn_xx_node_types_seq'),
+        "level" varchar(32),
+        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
+        "description" varchar(126)
+    ) WITH OIDS;
+    ALTER TABLE "gn_xx_node_types" 
+        ADD CONSTRAINT "gn_xx_node_types_id" 
+        PRIMARY KEY("id");
+    ALTER SEQUENCE "gn_xx_node_types_seq" OWNED BY gn_xx_node_types.id;
+    
+    DROP TABLE IF EXISTS "gn_xx_edge_types" CASCADE;
+    CREATE SEQUENCE "gn_xx_edge_types_seq";
+    CREATE TABLE "gn_xx_edge_types" (
+        "id" integer NOT NULL DEFAULT nextval('gn_xx_edge_types_seq'),
+        "level" varchar(32),
+        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
+        "description" varchar(126)
+    ) WITH OIDS;
+    ALTER TABLE "gn_xx_edge_types" 
+        ADD CONSTRAINT "gn_xx_edge_types_id" 
+        PRIMARY KEY("id");
+    ALTER SEQUENCE "gn_xx_edge_types_seq" OWNED BY gn_xx_edge_types.id;
+    """
+    print st
+    db.query(st)
+
+def createLevelTables(level):
+    """
+    Tables schema. Create one level in datastore.
+
+    param: level is the level identifier string.
+    """
+    st = """
+    CREATE TABLE "gn_""" + level + """_nodes" (
+        "id" integer NOT NULL DEFAULT nextval('gn_xx_ids_seq'),
+        "iddown" integer,
+        "downlevel" varchar(32),
+        "idtype" integer
+    ) WITH OIDS;
+    ALTER TABLE "gn_""" + level + """_nodes" 
+        ADD CONSTRAINT "gn_""" + level + """_nodes_id" 
+        PRIMARY KEY("id");
+    ALTER TABLE "gn_""" + level + """_nodes" 
+        ADD CONSTRAINT "gn_""" + level + """_nodes_fkey_type" 
+        FOREIGN KEY ("idtype")
+        REFERENCES "gn_xx_node_types"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+
+    CREATE TABLE "gn_""" + level + """_edges" (
+        "id" integer NOT NULL DEFAULT nextval('gn_xx_ids_seq'),
+        "idna" integer,
+        "idnb" integer,
+        "iddown" integer,
+        "downlevel" varchar(32),
+        "idtype" integer
+    ) WITH OIDS;
+    ALTER TABLE "gn_""" + level + """_edges" 
+        ADD CONSTRAINT "gn_""" + level + """_edges_id" 
+        PRIMARY KEY("id");
+    ALTER TABLE "gn_""" + level + """_edges" 
+        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_topoA" 
+        FOREIGN KEY ("idna")
+        REFERENCES "gn_""" + level + """_nodes"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    ALTER TABLE "gn_""" + level + """_edges" 
+        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_topoB" 
+        FOREIGN KEY ("idnb") 
+        REFERENCES "gn_""" + level + """_nodes"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    ALTER TABLE "gn_""" + level + """_edges" 
+        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_type" 
+        FOREIGN KEY ("idtype")
+        REFERENCES "gn_xx_edge_types"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    """
+    print st
+    db.query(st)
+
+def dropLevelTables(level):
+    """
+    The level tables dropping deletes all network elements in the level.
+
+    param: level is the level identifier string.
+    """
+    st = """
+    DROP TABLE IF EXISTS "gn_""" + level + """_nodes" CASCADE;
+    DROP TABLE IF EXISTS "gn_""" + level + """_edges" CASCADE;
+    """
+    print st
+    db.query(st)
+
+################################################################################
+# Data procedures.
+################################################################################
+
+def insertNodeType(level, tablename, description):
+    st = "INSERT INTO gn_xx_node_types(level, tablename, description) " \
+        "VALUES ('" \
+        + level + "', '" \
+        + tablename + "', '" \
+        + description + "');"
+    print st
+    db.query(st)
+
+def insertEdgeType(level, tablename, description):
+    st = "INSERT INTO gn_xx_edge_types(level, tablename, description) " \
+        "VALUES ('" \
+        + level + "', '" \
+        + tablename + "', '" \
+        + description + "');"
+    print st
+    db.query(st)
+
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ################################################################################
-# Main window in the Python flavour.
-#
-################################################################################
-
-## TODO In emacs needed:
-import sys
-sys.path.append('/home/santiago/workspace/genet')
-##
-
-import classes
-
 """
-Sample data
-============
-
-Level 00:
-
-    N01------E01-----N02-----E02-----N03
-                      |               |
-                      |               |
-                     E03             E04
-                      |               |
-                      |               |
-    N06------E06-----N04-----E05-----N05
-
-Level 01:
-
-    N11------E11-----N12-----E12-----N13
-                     / \              |
-                    |  |              |
-                  E13  E14           E15
-                    |  |              |
-                    |  |              |
-                    | N14-----E16-----N16
-                   N15-----E17-----N17 
-
-Level 02:
-
-    N21------E21-----N22-----E22-----N23
-    /\               / \              |
-   /  |             |   |             |
-  |  E23           E24  E25          E26
-   \_/              |   |             |
-                     \ /              |
-                     N24-----E27-----N26
-                     N25-----E28-----N27
-                                     N28
-
 """
 
-N01 = classes.node00('N01')
-N02 = classes.node00('N02')
-N03 = classes.node00('N03')
-N04 = classes.node00('N04')
-N05 = classes.node00('N05')
-N06 = classes.node00('N06')
-NL00 = [N01, N02, N03, N04, N05, N06]
+import db_connection
+import db_schema
 
-E01 = classes.edge00('E01', N01, N02)
-E02 = classes.edge00('E02', N02, N03)
-E03 = classes.edge00('E03', N02, N04)
-E04 = classes.edge00('E04', N03, N05)
-E05 = classes.edge00('E05', N04, N05)
-E06 = classes.edge00('E06', N04, N06)
-EL00 = [E01, E02, E03, E04, E05, E06]
+##
+# *** DANGER ***
+# startSchema() deletes db schema.
+#
+#db_schema.startSchema()
 
-E05.len = 123.45
 
-N11 = classes.node01('N11', N01, 'T10', 'endp')
-N12 = classes.node01('N12', N02, 'T10', 'fork')
-N13 = classes.node01('N13', N03, 'T10', 'pass')
-N14 = classes.node01('N14', N04, 'T10', 'pass')
-N15 = classes.node01('N15', N04, 'T10', 'pass')
-N16 = classes.node01('N16', N05, 'T10', 'pass')
-N17 = classes.node01('N17', N05, 'T10', 'endp')
-NL01 = [N11, N12, N13, N14, N15, N16, N17]
-
-E11 = classes.edge01('E11', N11, N12, E01, 'T11')
-E12 = classes.edge01('E12', N12, N13, E02, 'T11')
-E13 = classes.edge01('E13', N12, N15, E03, 'T11')
-E14 = classes.edge01('E14', N12, N14, E03, 'T11')
-E15 = classes.edge01('E15', N13, N16, E04, 'T11')
-E16 = classes.edge01('E16', N14, N16, E05, 'T11')
-E17 = classes.edge01('E17', N15, N17, E05, 'T11')
-EL01 = [E11, E12, E13, E14, E15, E16, E17]
-
-# Show all
-for n in NL00:
-    print n.level, n.id, n.iddown, n.idtype, n.idtopo
-for e in EL00:
-    print e.level, e.id, e.idnA.id, e.idnB.id, e.iddown, e.idtype, e.len
-for n in NL01:
-    print n.level, n.id, n.iddown.id, n.idtype, n.idtopo, n.owner
-for e in EL01:
-    print e.level, e.id, e.idnA.id, e.idnB.id, e.iddown.id, e.idtype, e.owner
-

File genet_networkx.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-# Main window in the Python flavour.
-#
-################################################################################
-
-## TODO In emacs needed:
-import sys
-sys.path.append('/home/santiago/workspace/genet')
-##
-
-import genet
-import pylab as P
-import networkx as NX
-
-################################################################################
-# Level 0
-#
-G0 = NX.XGraph(name='Geometric', multiedges=True, selfloops=True)
-
-for e in genet.EL00:
-    G0.add_edges_from([(e.idnA.id, e.idnB.id, e.id)])
-
-# May be there are isolated nodes.
-for n in genet.NL00:
-    print n.id
-    G0.add_node(n.id)
-
-print 'G0 nodes:', G0.nodes()
-print 'G0 edges:', G0.edges()
-        
-pos = NX.spring_layout(G0)
-NX.draw_networkx(G0, pos)
-P.show()
-
-P.savefig("genet_L0.png")
-print "Wrote genet_L0.png"
-
-################################################################################
-# Level 1
-#
-G101 = NX.XGraph(name='Infrastructure', multiedges=True, selfloops=True)
-
-for e in genet.EL01:
-    print e.idnA.id, e.idnB.id, e.id
-    G101.add_edge(e.idnA.id, e.idnB.id, e.id)
-
-# May be there are isolated nodes.
-for n in genet.NL01:
-    print n.id
-    G101.add_node(n.id)
-
-print 'G101 nodes:', G101.nodes()
-print 'G101 edges:', G101.edges()
-
-pos = NX.spring_layout(G101)
-NX.draw_networkx(G101, pos)
-P.show()
-
-P.savefig("genet_L101.png")
-print "Wrote genet_L101.png"
-
-################################################################################
-# Fancy draw & DOT
-#
-G102 = NX.XGraph(name='Infrastructure', multiedges=True, selfloops=True)
-
-for e in genet.EL01:
-    print e.idnA.id, e.idnB.id, e.id
-    G102.add_edges_from([(e.idnA.id, e.idnB.id, e)])
-
-# May be there are isolated nodes.
-for n in genet.NL01:
-    print n.id
-    G102.add_node(n.id)
-
-pos = NX.spring_layout(G102)
-NX.draw_networkx_nodes(G102, pos, node_color='g', node_size=500)
-NX.draw_networkx_edges(G102, pos, width=8.0, alpha=0.5, edge_color='g')
-labels={}
-labels[G102.nodes()[0]]='$\pi$'
-labels[G102.nodes()[1]]='$\mu$'
-labels[G102.nodes()[2]]='$\epsilon$'
-NX.draw_networkx_labels(G102, pos, labels=labels, 
-                        font_color='w', font_family='sans-serif', 
-                        font_size=12)
-P.show()
-
-P.savefig("genet_L102.png")
-print "Wrote genet_L102.png"
-
-"""
-With the dot file can do in the system:
-$ neato -Tpng file.dot > file.png
-$ eog file.png
-"""
-NX.write_dot(G102,"genet_L102.dot")
-print "Wrote genet_L102.dot"
-
-################################################################################
-# Paths
-#
-"""
-The Dijkstra algorithms seems not to support multiedge graphs, because
-the NX._Graph.get_edge() function returns a list.
-
-Line 438 in /var/lib/python-support/python2.5/networkx/path.py, function
-single_source_dijkstra(G,source,target), should be:
-
-...
-if G.multiedges:
-    vw_dist = dist[v] + reduce(min, G.get_edge(v,w))
-else:
-    vw_dist = dist[v] + G.get_edge(v,w)
-...
-
-or may be defining an appropiate function get_edge(v, w) depending on
-the multiedges property before the loooop. 
-
-Example:
-
->>> l = [0.23, 7, 0.1]
->>> print reduce(min, l)
-0.1
-
-"""
-G103 = NX.XGraph(name='Infrastructure', multiedges=False, selfloops=True)
-
-for e in genet.EL01:
-    # When creating the graph with edges (dont worry about isolated nodes)
-    # the information passed is the edges' weight. 
-    print e.idnA.id, e.idnB.id, e.id
-    G103.add_edge(e.idnA.id, e.idnB.id, e.iddown.len)
-
-paths = NX.single_source_shortest_path_length(G103, G103.nodes()[0], 1000)
-print paths
-
-paths = NX.single_source_shortest_path(G103, G103.nodes()[0], 1000)
-print paths
-
-path = NX.shortest_path(G103, 
-                        G103.nodes()[0], 
-                        G103.nodes()[NX.number_of_nodes(G103)-1])
-print path
-
-paths = NX.single_source_dijkstra_path_length(G103, G103.nodes()[0])
-print paths
-print 'The', G103.edges()[0], 'weight is:', G103.edges()[0][2]
-
-paths = NX.single_source_dijkstra_path(G103, G103.nodes()[0])
-print paths
-

File genet_postgre.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-# Main window in the Python flavour.
-#
-################################################################################
-
-## TODO In emacs needed:
-import sys
-sys.path.append('/home/santiago/workspace/genet')
-##
-
-import pg
-import readline  # So raw_input() uses line editing and history.
-
-##
-# Connection. 
-#
-pwd = raw_input('Password: ')
-db = pg.DB('genet', 'localhost', 5432, None, None, 'santiago', pwd)
-
-##
-# All identiers of networks elements has the same sequence source.
-# 
-st = """
-DROP SEQUENCE IF EXISTS "gn_xx_ids_seq" CASCADE;
-CREATE SEQUENCE "gn_xx_ids_seq" 
-  INCREMENT 1 
-  MINVALUE 100000000 
-  NO MAXVALUE 
-  NO CYCLE;
-"""
-print st
-db.query(st)
-
-##
-# Out from basic schema all tables are referenced by this ones.
-#
-st = """
-DROP TABLE IF EXISTS "gn_xx_node_types" CASCADE;
-CREATE SEQUENCE "gn_xx_node_types_seq";
-CREATE TABLE "gn_xx_node_types" (
-    "id" integer NOT NULL DEFAULT nextval('gn_xx_node_types_seq'),
-    "level" varchar(32),
-    "tablename" varchar(63), -- NAMEDATALEN is 63 currently.
-    "description" varchar(126)
-) WITH OIDS;
-ALTER TABLE "gn_xx_node_types" 
-    ADD CONSTRAINT "gn_xx_node_types_id" 
-    PRIMARY KEY("id");
-ALTER SEQUENCE "gn_xx_node_types_seq" OWNED BY gn_xx_node_types.id;
-
-DROP TABLE IF EXISTS "gn_xx_edge_types" CASCADE;
-CREATE SEQUENCE "gn_xx_edge_types_seq";
-CREATE TABLE "gn_xx_edge_types" (
-    "id" integer NOT NULL DEFAULT nextval('gn_xx_edge_types_seq'),
-    "level" varchar(32),
-    "tablename" varchar(63), -- NAMEDATALEN is 63 currently.
-    "description" varchar(126)
-) WITH OIDS;
-ALTER TABLE "gn_xx_edge_types" 
-    ADD CONSTRAINT "gn_xx_edge_types_id" 
-    PRIMARY KEY("id");
-ALTER SEQUENCE "gn_xx_edge_types_seq" OWNED BY gn_xx_edge_types.id;
-"""
-print st
-db.query(st)
-
-##
-# Tables schema. Create one level.
-# 
-def createLevelTables(level):
-    st = """
-    DROP TABLE IF EXISTS "gn_""" + level + """_nodes" CASCADE;
-    CREATE TABLE "gn_""" + level + """_nodes" (
-        "id" integer NOT NULL DEFAULT nextval('gn_xx_ids_seq'),
-        "iddown" integer,
-        "downlevel" varchar(32),
-        "idtype" integer
-    ) WITH OIDS;
-    ALTER TABLE "gn_""" + level + """_nodes" 
-        ADD CONSTRAINT "gn_""" + level + """_nodes_id" 
-        PRIMARY KEY("id");
-    ALTER TABLE "gn_""" + level + """_nodes" 
-        ADD CONSTRAINT "gn_""" + level + """_nodes_fkey_type" 
-        FOREIGN KEY ("idtype")
-        REFERENCES "gn_xx_node_types"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-
-    DROP TABLE IF EXISTS "gn_""" + level + """_edges" CASCADE;
-    CREATE TABLE "gn_""" + level + """_edges" (
-        "id" integer NOT NULL DEFAULT nextval('gn_xx_ids_seq'),
-        "idna" integer,
-        "idnb" integer,
-        "iddown" integer,
-        "downlevel" varchar(32),
-        "idtype" integer
-    ) WITH OIDS;
-    ALTER TABLE "gn_""" + level + """_edges" 
-        ADD CONSTRAINT "gn_""" + level + """_edges_id" 
-        PRIMARY KEY("id");
-    ALTER TABLE "gn_""" + level + """_edges" 
-        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_topoA" 
-        FOREIGN KEY ("idna")
-        REFERENCES "gn_""" + level + """_nodes"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    ALTER TABLE "gn_""" + level + """_edges" 
-        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_topoB" 
-        FOREIGN KEY ("idnb") 
-        REFERENCES "gn_""" + level + """_nodes"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    ALTER TABLE "gn_""" + level + """_edges" 
-        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_type" 
-        FOREIGN KEY ("idtype")
-        REFERENCES "gn_xx_edge_types"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    """
-    print st
-    db.query(st)

File genet_sqlite.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-# Main window in the Python flavour.
-#
-################################################################################
-
-from pysqlite2 import dbapi2 as sqlite
-
-#con = sqlite.connect(":memory:")
-con = sqlite.connect("/tmp/genet.sqlite")
-cur = con.cursor()
-
-cur.execute("""create table nodes (id integer, name varchar(20));""")
-
-# Insert data
-cur.execute("""insert into nodes (id, name) values (10000, 'First Node')""")                         
-
-# Insert lot of data
-for n in [(x, 'Node ' + str(x)) for x in xrange(300)]:
-    cur.execute("""insert into nodes (id, name) values (?, ?)""", n)
-
-# Commit changes
-con.commit()
-
-# Select and show data
-cur.execute("""select * from nodes""")
-print cur.fetchall()
-
-# Select and show data
-cur.execute("""select * from nodes""")
-for row in cur:
-    print row
-
-# Print cursor schema
-print cur.description

File insert_test_data.py

-#!/usr/bin/env python
-################################################################################
-# $Id$
-################################################################################
-# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
-#
-# This file is part of mine.
-#
-# Mine is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-################################################################################
-# Main window in the Python flavour.
-#
-################################################################################
-
-## TODO In emacs needed:
-import sys
-sys.path.append('/home/santiago/workspace/genet')
-##
-
-import genet_postgre
-import classes_postgre
-
-##
-# Insert data procedures.
-#
-
-def insertNodeType(level, tablename, description):
-    st = "INSERT INTO gn_xx_node_types(level, tablename, description) " \
-        "VALUES ('" \
-        + level + "', '" \
-        + tablename + "', '" \
-        + description + "');"
-    db.query(st)
-
-def insertEdgeType(level, tablename, description):
-    st = "INSERT INTO gn_xx_edge_types(level, tablename, description) " \
-        "VALUES ('" \
-        + level + "', '" \
-        + tablename + "', '" \
-        + description + "');"
-    db.query(st)
-
-##
-# Insert data.
-# 
-
-insertNodeType('00', 'vaults', 'Vaults and manholes.')
-insertNodeType('00', 'poles', 'Poles and towers.')
-insertNodeType('01', 'closures', 'Splicing boxes.')
-insertNodeType('02', 'splices', 'Splices.')
-
-insertEdgeType('00', 'trails', 'Trenchs.')
-insertEdgeType('01', 'cables', 'Cables.')
-insertEdgeType('02', 'fibers', 'Fibers.')
-
-createLevelTables('00')
-createLevelTables('01')
-createLevelTables('02')
-createLevelTables('LL')
-
-N001 = classes_postgre.node('00', 0, 0, 1)
-print N001.store(db)
-N002 = classes_postgre.node('00', 0, 0, 1)
-print N002.store(db)
-N003 = classes_postgre.node('00', 0, 0, 2)
-print N003.store(db)
-
-N003.idtype = 1
-print N003.id
-print N003.store(db)
-
-E001 = classes_postgre.edge('00', 100000000, 100000001, 0, 0, 2)
-print E001.store(db)
-
-#print db.query("SELECT * FROM nodes")
-
-#print
-#for r in db.query("SELECT * FROM nodes").dictresult():
-#    print 'idn: %(idn)s - iddown: %(iddown)s - idtype: %(idtype)s' % r

File pggenet/genet.sql

-------------------------------
--- pgDesigner 1.2.7
---
--- Project    : genet
--- Date       : 10/04/2008 13:53:18.86
--- Description: genet, graphs and networks worker.
---
--- $Id$
---
--- Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es> 
--- 
--- This file is part of genet the graphs and networks worker. 
--- 
--- Genet is free software; you can redistribute it and/or modify 
--- it under the terms of the GNU General Public License as published by 
--- the Free Software Foundation; either version 2 of the License, or 
--- (at your option) any later version. 
--- 
--- This program is distributed in the hope that it will be useful, 
--- but WITHOUT ANY WARRANTY; without even the implied warranty of 
--- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
--- GNU General Public License for more details. 
--- 
--- You should have received a copy of the GNU General Public License 
--- along with this program; if not, write to the Free Software 
--- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-------------------------------
-
-
--- Start Sequence's declaration
-DROP SEQUENCE IF EXISTS "ids_seq" CASCADE;
-CREATE SEQUENCE "ids_seq" INCREMENT 1 MINVALUE 1000000 NO MAXVALUE NO CYCLE;
-
--- End Sequence's declaration
-
--- Start Table's declaration
-DROP TABLE IF EXISTS "edges" CASCADE;
-CREATE TABLE "edges" (
-"ide" integer NOT NULL DEFAULT nextval('ids_seq'),
-"idna" integer,
-"idnb" integer
-) WITH OIDS;
-ALTER TABLE "edges" ADD CONSTRAINT "ide" PRIMARY KEY("ide");
-
-DROP TABLE IF EXISTS "nodes" CASCADE;
-CREATE TABLE "nodes" (
-"idn" integer NOT NULL DEFAULT nextval('ids_seq')
-) WITH OIDS;
-ALTER TABLE "nodes" ADD CONSTRAINT "idn" PRIMARY KEY("idn");
-
--- End Table's declaration
-
--- Start Relation's declaration
---ALTER TABLE "edges" DROP CONSTRAINT "edges_fkey1" CASCADE;
-ALTER TABLE "edges" ADD CONSTRAINT "edges_fkey1" FOREIGN KEY ("idna") REFERENCES "nodes"("idn") ON UPDATE RESTRICT ON DELETE RESTRICT;
-
---ALTER TABLE "edges" DROP CONSTRAINT "edges_fkey2" CASCADE;
-ALTER TABLE "edges" ADD CONSTRAINT "edges_fkey2" FOREIGN KEY ("idnb") REFERENCES "nodes"("idn") ON UPDATE RESTRICT ON DELETE RESTRICT;
-
--- End Relation's declaration
-

File pggenet/genet.xml

-<?xml version="1.0" encoding="UTF8"?>
-<pgDesigner Version="1.1.1">
- <PROJECT Name="genet" PageFormat="A4" PageOrientation="0" Revision="10/03/2008 22:33:07" Description="genet, graphs and networks worker.#0A#--#0A#-- $Id$#0A#--#0A#-- Copyright (c) 2008 Santiago Paya Miralta #3C#santiagopm::wanadoo.es#3E# #0A#-- #0A#-- This file is part of genet the graphs and networks worker. #0A#-- #0A#-- Genet is free software; you can redistribute it and/or modify #0A#-- it under the terms of the GNU General Public License as published by #0A#-- the Free Software Foundation; either version 2 of the License, or #0A#-- (at your option) any later version. #0A#-- #0A#-- This program is distributed in the hope that it will be useful, #0A#-- but WITHOUT ANY WARRANTY; without even the implied warranty of #0A#-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the #0A#-- GNU General Public License for more details. #0A#-- #0A#-- You should have received a copy of the GNU General Public License #0A#-- along with this program; if not, write to the Free Software #0A#-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA" Driver="8.3" Author="santiago" Display="0"/>
- <TABLE Name="edges" X="535" Y="74" ColorBack="230,230,230" ColorText="0,0,0" ColorBackTitle="230,230,230" ColorBackTitleSelected="76,89,166" ColorForeTitle="0,0,0" ColorForeTitleSelected="255,255,255" Option="true" PrimaryKey="ide"/>
- <TABLEFIELD Name="ide" Table="edges" Length="0" NullCheck="true" Type1="integer" PrimaryKey="true"/>
- <TABLEFIELD Name="idna" Table="edges" Length="0" NullCheck="false" Type1="integer" PrimaryKey="false"/>
- <TABLEFIELD Name="idnb" Table="edges" Length="0" NullCheck="false" Type1="integer" PrimaryKey="false"/>
- <TABLE Name="nodes" X="193" Y="73" ColorBack="230,230,230" ColorText="0,0,0" ColorBackTitle="230,230,230" ColorBackTitleSelected="76,89,166" ColorForeTitle="0,0,0" ColorForeTitleSelected="255,255,255" Option="true" PrimaryKey="idn"/>
- <TABLEFIELD Name="idn" Table="nodes" Length="0" NullCheck="true" Type1="integer" PrimaryKey="true"/>
- <RELATION Name="edges_fkey1" X1="230" Y1="118" X2="574" Y2="74" ColorLine="192,192,192" ColorLineSelected="255,0,0" ColorStartPoint="255,0,0" ColorMiddlePoint="255,0,0" ColorEndPoint="0,255,0" OnUpdate="RESTRICT" OnDelete="RESTRICT" Table1="nodes" Table2="edges"/>
- <RELATIONFIELD Relation="edges_fkey1" Field1="idn" Field2="idna"/>
- <RELATION Name="edges_fkey2" X1="267" Y1="118" X2="614" Y2="74" ColorLine="192,192,192" ColorLineSelected="255,0,0" ColorStartPoint="255,0,0" ColorMiddlePoint="255,0,0" ColorEndPoint="0,255,0" OnUpdate="RESTRICT" OnDelete="RESTRICT" Table1="nodes" Table2="edges"/>
- <RELATIONFIELD Relation="edges_fkey2" Field1="idn" Field2="idnb"/>
-</pgDesigner>

File test_data.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+
+from db_connection import db
+from db_schema import *
+from class_edge import edge
+from class_node import node
+
+##
+# Insert data.
+# 
+
+insertNodeType('00', 'vaults', 'Vaults and manholes.')
+insertNodeType('00', 'poles', 'Poles and towers.')
+insertNodeType('01', 'closures', 'Splicing boxes.')
+insertNodeType('02', 'splices', 'Splices.')
+
+insertEdgeType('00', 'trails', 'Trenchs.')
+insertEdgeType('01', 'cables', 'Cables.')
+insertEdgeType('02', 'fibers', 'Fibers.')
+
+createLevelTables('00')
+createLevelTables('01')
+createLevelTables('02')
+createLevelTables('LL')
+
+N001 = node('00', 0, 0, 1)
+print N001.store(db)
+N002 = node('00', 0, 0, 1)
+print N002.store(db)
+N003 = node('00', 0, 0, 2)
+print N003.store(db)
+
+N003.idtype = 1
+print N003.id
+print N003.store(db)
+
+E001 = edge('00', 100000000, 100000001, 0, 0, 2)
+print E001.store(db)
+
+#print db.query("SELECT * FROM nodes")
+
+#print
+#for r in db.query("SELECT * FROM nodes").dictresult():
+#    print 'idn: %(idn)s - iddown: %(iddown)s - idtype: %(idtype)s' % r

File test_networkx.py

+#!/usr/bin/env python
+################################################################################
+# $Id$
+################################################################################
+# Copyright (c) 2008 Santiago Paya Miralta <santiagopm::wanadoo.es>
+#
+# This file is part of mine.
+#
+# Mine is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+################################################################################
+
+import genet
+import pylab as P
+import networkx as NX
+
+################################################################################
+# Level 0
+#
+G0 = NX.XGraph(name='Geometric', multiedges=True, selfloops=True)
+
+for e in genet.EL00:
+    G0.add_edges_from([(e.idnA.id, e.idnB.id, e.id)])
+
+# May be there are isolated nodes.
+for n in genet.NL00:
+    print n.id
+    G0.add_node(n.id)
+
+print 'G0 nodes:', G0.nodes()
+print 'G0 edges:', G0.edges()
+        
+pos = NX.spring_layout(G0)
+NX.draw_networkx(G0, pos)
+P.show()
+
+P.savefig("genet_L0.png")
+print "Wrote genet_L0.png"
+
+################################################################################
+# Level 1
+#
+G101 = NX.XGraph(name='Infrastructure', multiedges=True, selfloops=True)
+
+for e in genet.EL01:
+    print e.idnA.id, e.idnB.id, e.id
+    G101.add_edge(e.idnA.id, e.idnB.id, e.id)
+
+# May be there are isolated nodes.
+for n in genet.NL01:
+    print n.id
+    G101.add_node(n.id)
+
+print 'G101 nodes:', G101.nodes()
+print 'G101 edges:', G101.edges()
+
+pos = NX.spring_layout(G101)
+NX.draw_networkx(G101, pos)
+P.show()
+
+P.savefig("genet_L101.png")
+print "Wrote genet_L101.png"
+
+################################################################################
+# Fancy draw & DOT
+#
+G102 = NX.XGraph(name='Infrastructure', multiedges=True, selfloops=True)
+
+for e in genet.EL01:
+    print e.idnA.id, e.idnB.id, e.id
+    G102.add_edges_from([(e.idnA.id, e.idnB.id, e)])
+
+# May be there are isolated nodes.
+for n in genet.NL01:
+    print n.id
+    G102.add_node(n.id)
+
+pos = NX.spring_layout(G102)
+NX.draw_networkx_nodes(G102, pos, node_color='g', node_size=500)
+NX.draw_networkx_edges(G102, pos, width=8.0, alpha=0.5, edge_color='g')
+labels={}
+labels[G102.nodes()[0]]='$\pi$'
+labels[G102.nodes()[1]]='$\mu$'
+labels[G102.nodes()[2]]='$\epsilon$'
+NX.draw_networkx_labels(G102, pos, labels=labels, 
+                        font_color='w', font_family='sans-serif', 
+                        font_size=12)
+P.show()
+
+P.savefig("genet_L102.png")
+print "Wrote genet_L102.png"
+
+"""
+With the dot file can do in the system:
+$ neato -Tpng file.dot > file.png
+$ eog file.png
+"""
+NX.write_dot(G102,"genet_L102.dot")
+print "Wrote genet_L102.dot"
+
+################################################################################
+# Paths
+#
+"""
+The Dijkstra algorithms seems not to support multiedge graphs, because
+the NX._Graph.get_edge() function returns a list.
+
+Line 438 in /var/lib/python-support/python2.5/networkx/path.py, function
+single_source_dijkstra(G,source,target), should be:
+
+...
+if G.multiedges:
+    vw_dist = dist[v] + reduce(min, G.get_edge(v,w))
+else:
+    vw_dist = dist[v] + G.get_edge(v,w)
+...
+
+or may be defining an appropiate function get_edge(v, w) depending on
+the multiedges property before the loooop. 
+
+Example:
+
+>>> l = [0.23, 7, 0.1]
+>>> print reduce(min, l)
+0.1
+
+"""
+G103 = NX.XGraph(name='Infrastructure', multiedges=False, selfloops=True)
+
+for e in genet.EL01:
+    # When creating the graph with edges (dont worry about isolated nodes)
+    # the information passed is the edges' weight. 
+    print e.idnA.id, e.idnB.id, e.id
+    G103.add_edge(e.idnA.id, e.idnB.id, e.iddown.len)
+
+paths = NX.single_source_shortest_path_length(G103, G103.nodes()[0], 1000)
+print paths
+
+paths = NX.single_source_shortest_path(G103, G103.nodes()[0], 1000)
+print paths
+
+path = NX.shortest_path(G103, 
+                        G103.nodes()[0], 
+                        G103.nodes()[NX.number_of_nodes(G103)-1])
+print path
+
+paths = NX.single_source_dijkstra_path_length(G103, G103.nodes()[0])
+print paths
+print 'The', G103.edges()[0], 'weight is:', G103.edges()[0][2]
+
+paths = NX.single_source_dijkstra_path(G103, G103.nodes()[0])
+print paths
+