Commits

Santiago Payà Miralta committed 9b56023

More weekendWork.

  • Participants
  • Parent commits 7b7656b

Comments (0)

Files changed (22)

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.
-* 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.
-    
-    The the edge itself, 'idnA' and 'idnB' should be from the same level, 
-    this is resolved at execution time from an intelligent interface.
-
-    The 'iddown' object should be from the 'downlevel' level,
-    this is resolved at execution time from an intelligent interface.
-    """
-    def __init__(self, level, idnA, idnB, idparent, parentlevel, idtype):
-        self.id = None
-        self.level = level
-        self.idnA = idnA
-        self.idnB = idnB
-        self.idparent = idparent
-        self.parentlevel = parentlevel
-        self.idtype = idtype
-    
-    def store(self, db):
-        """
-        Stores data in db. 
-
-        Param: db is the database object.
-        Return: the SQL statement and node id.
-        """
-        if self.id:
-            st = "UPDATE gn_" + str(self.level) + "_edges SET " \
-                "idnA = " + str(self.idnA) + ", " \
-                "idnB" + str(self.idnB) + ", " \
-                "idtype = " + str(self.idtype) + " " \
-                "WHERE id = " + str(self.id) + ";"
-            db.query(st)
-            return st, self.id
-        # TODO UPDATE tree
-
-        else:
-            st1 = "INSERT INTO gn_" + str(self.level) + "_edges(idna, idnb, iddown, downlevel, idtype) " \
-                "VALUES(" \
-                + str(self.idnA) + ", " \
-                + str(self.idnB) + ", " \
-                + str(self.idtype) + ") " \
-                "RETURNING id;"
-            self.id = db.query(st1).getresult()[0][0]
-            st2 = "INSERT INTO gn____tree(idparent, idchild, parentlevel, childlevel) " \
-                "VALUES(" \
-                + str(self.idparent) + ", " \
-                + str(self.id) + ", " \
-                + str(self.parentlevel) + ", " \
-                + str(self.level) + ");" 
-            db.query(st2)
-            return st1, st2, 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.
-* idtype: what kind of element is.
-
-"""
-
-class node:
-    """
-    Simple class with basic attributes.
-
-    The 'iddown' object should be from the 'downlevel' level,
-    this is resolved at execution time from an intelligent interface.
-    """
-    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):
-        """
-        Stores data in db. 
-
-        Param: db is the database object.
-        Return: the SQL statement and node id.
-        """
-        if self.id:
-            st = "UPDATE gn_" + str(self.level) + "_nodes SET " \
-                "idtype = " + str(self.idtype) + " " \
-                "WHERE id = " + str(self.id) + ";"
-            db.query(st)
-        else:
-            st = "INSERT INTO gn_" + str(self.level) + "_nodes(iddown, downlevel, idtype) " \
-                "VALUES(" \
-                + str(self.idtype) + ") " \
-                "RETURNING id;"
-            self.id = db.query(st).getresult()[0][0]
-        return st, self.id

File control/__init__.py

Empty file added.

File control/genet_browser.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
+################################################################################
+"""
+Related to paths and interlevel chains.
+
+"""
+
+from model.db_connection import db
+
+def listLevels():
+    """
+    List levels from db.
+
+    @returns list the levels
+    """
+    st = "SELECT description, id FROM gn____levels;"
+    return db.query(st).getresult()

File control/genet_creator.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 model.class_edge import edge
+from model.class_node import node
+from model.db_connection import db
+from model.db_schema import *
+
+################################################################################
+# Create tables.
+# 
+def createLevel(description):
+    """
+    Create one level in the network data model. The level primary key is
+    created here with the sequence number padded on the left with zeros.
+
+    @param description of the level.
+    """
+    st = "INSERT INTO gn____levels(description) " \
+        "VALUES ('" + description + "') " \
+        "RETURNING id;"
+    level = db.query(st).getresult()[0][0]
+    level = str(level).zfill(2)
+    
+    # This should not be necessary.
+    ret = dropLevelTables(level)
+
+    # Create the layer tables.
+    ret = ret, createLevelTables(level)
+    return ret
+
+def createEdgeType(level, description):
+    """
+    Create one edge type. Gets the number of types in the 'edge_types'
+    table and adds one padding on the left with zeros. Construct the 
+    new tablename of type with the new type.
+
+    @param level in which the new type is added.
+    @param description of the type.
+    """
+    st= "SELECT count(type) FROM gn____edge_types;"
+    n = db.query(st).getresult()[0][0]
+    new_type = str(n + 1).zfill(2)
+    new_tablename = "gn_" + level + "_edge_type_" + new_type
+
+    st = "INSERT INTO gn____edge_types(type, level, tablename, description) " \
+        "VALUES ('" \
+        + new_type + "', '" \
+        + level + "', '" \
+        + new_tablename + "', '" \
+        + description + "');"
+    return st, db.query(st)
+
+def connectNodes(level, idnA, idnB):
+    """
+    TODO
+    """
+

File control/genet_global.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 model import db_schema
+
+#GN_DEBUG = True
+
+##
+# *** DANGER ***
+# startSchema() deletes db schema.
+def restartSchema():
+    """
+    *** DANGER ***
+    Deletes all the database.
+    """
+    db_schema.dropSchema()
+    db_schema.startSchema()
+

File control/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 model.class_edge import edge
+from model.class_node import node
+from model.db_connection import db
+from model.db_schema import *
+
+################################################################################
+# Insert tables.
+# 
+print insertNodeType('01', 'vaults', 'Vaults and manholes.')
+print insertNodeType('01', 'poles', 'Poles and towers.')
+print insertNodeType('02', 'closures', 'Splicing boxes.')
+print insertNodeType('03', 'splices', 'Splices.')
+
+print insertEdgeType('01', 'trails', 'Trenchs.')
+print insertEdgeType('02', 'cables', 'Cables.')
+print insertEdgeType('03', 'fibers', 'Fibers.')
+
+print dropLevelTables('00')
+print createLevelTables('00')
+
+print dropLevelTables('01')
+print createLevelTables('01')
+
+print dropLevelTables('02')
+print createLevelTables('02')
+
+print dropLevelTables('LL')
+print createLevelTables('LL')
+
+################################################################################
+# Insert data.
+#
+N001 = node('01', 0, 2323, 2)
+print N001.store(db)
+
+N002 = node('01', 0, 0, 1)
+print N002.store(db)
+
+N003 = node('01', 0, 0, 2)
+print N003.store(db)
+N003.idtype = 1
+print N003.store(db)
+
+E001 = edge('01', N001.id, N002.id, 0, 0, 2)
+print E001.store(db)
+
+for r in db.query("SELECT * FROM gn_01_nodes").dictresult():
+    print 'id: %(id)s - iddown: %(iddown)s - idtype: %(idtype)s' % r
+
+for r in db.query("SELECT * FROM gn_01_edges").dictresult():
+    print 'id: %(id)s - idnA: %(idna)s - idnB: %(idnb)s - iddown: %(iddown)s - idtype: %(idtype)s' % r

File control/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 pylab as P
+import networkx as NX
+from test_data import *
+
+################################################################################
+# Level 00
+#
+G00 = NX.XGraph(name='Level 00', multiedges=True, selfloops=True)
+
+for r in db.query("SELECT * FROM gn_00_edges").dictresult():
+    G00.add_edges_from([(r['idna'], r['idnb'], r['id'])])
+    
+# May be there are isolated nodes.
+for r in db.query("SELECT * FROM gn_00_nodes").dictresult():
+    G00.add_node(r['id'])
+
+print 'G00 nodes:', G00.nodes()
+print 'G00 edges:', G00.edges()
+
+pos = NX.spring_layout(G00)
+NX.draw_networkx(G00, 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 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____ids_seq" CASCADE;
-    CREATE SEQUENCE "gn____ids_seq" 
-      INCREMENT 1 
-      MINVALUE 100000000 
-      NO MAXVALUE 
-      NO CYCLE;
-    """
-    print st, db.query(st)
-    
-    ##
-    # The tree relates between levels.
-    # 
-    st = """
-    CREATE TABLE "gn____tree" (
-        "idparent" integer,
-        "idchild" integer,
-        "parentlevel" varchar(32),
-        "childlevel varchar(32)"
-    ) WITH (OIDS = FALSE);
-    ALTER TABLE "gn____tree" 
-        ADD CONSTRAINT "gn____tree_idchild" 
-        PRIMARY KEY("idchild");
-    """
-    print st, db.query(st)
-    
-    ##
-    # Levels directory.
-    # 
-    st = """
-    DROP TABLE IF EXISTS "gn____levels" CASCADE;
-    CREATE TABLE "gn____levels" (
-        "level" varchar(32) NOT NULL,
-        "description" varchar(126)
-    ) WITH (OIDS = FALSE);
-    ALTER TABLE "gn____levels" 
-        ADD CONSTRAINT "gn____levels_pk" 
-        PRIMARY KEY("level");
-    """
-    print st, db.query(st)
-
-    ##
-    # Out from basic schema all tables are referenced by this ones.
-    #
-    st = """
-    DROP TABLE IF EXISTS "gn____node_types" CASCADE;
-    CREATE TABLE "gn____node_types" (
-        "type" varchar(32) NOT NULL,
-        "level" varchar(32),
-        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
-        "description" varchar(126)
-    ) WITH (OIDS = FALSE);
-    ALTER TABLE "gn____node_types" 
-        ADD CONSTRAINT "gn____node_types_pk" 
-        PRIMARY KEY("type");
-    ALTER TABLE "gn____node_types" 
-        ADD CONSTRAINT "gn____node_types_level" 
-        FOREIGN KEY ("level")
-        REFERENCES "gn____levels"("level") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    
-    DROP TABLE IF EXISTS "gn____edge_types" CASCADE;
-    CREATE TABLE "gn____edge_types" (
-        "type" varchar(32) NOT NULL,
-        "level" varchar(32),
-        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
-        "description" varchar(126)
-    ) WITH (OIDS = FALSE);
-    ALTER TABLE "gn____edge_types" 
-        ADD CONSTRAINT "gn____edge_types_pk" 
-        PRIMARY KEY("type");
-    ALTER TABLE "gn____edge_types" 
-        ADD CONSTRAINT "gn____edge_types_level" 
-        FOREIGN KEY ("level")
-        REFERENCES "gn____levels"("level") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    """
-    print st, db.query(st)
-
-def dropSchema():
-    """
-    TODO
-    """
-
-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____ids_seq'),
-        "idtype" integer
-    ) WITH (OIDS = FALSE);
-    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____node_types"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    ALTER TABLE "gn_""" + level + """_nodes" 
-        ADD CONSTRAINT "gn_""" + level + """_nodes_fkey_level" 
-        FOREIGN KEY ("parentlevel")
-        REFERENCES "gn____levels"("level") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-
-    CREATE TABLE "gn_""" + level + """_edges" (
-        "id" integer NOT NULL DEFAULT nextval('gn____ids_seq'),
-        "idna" integer,
-        "idnb" integer,
-        "idtype" integer
-    ) WITH (OIDS = FALSE);
-    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____edge_types"("id") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    ALTER TABLE "gn_""" + level + """_edges" 
-        ADD CONSTRAINT "gn_""" + level + """_edges_fkey_level" 
-        FOREIGN KEY ("parentlevel")
-        REFERENCES "gn____levels"("level") 
-        ON UPDATE RESTRICT ON DELETE RESTRICT;
-    """
-    return 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;
-    """
-    return st, db.query(st)

File genet.glade

-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
-<!--*- mode: xml -*-->
-<glade-interface>
-  <widget class="GtkWindow" id="genet">
-    <property name="visible">True</property>
-    <property name="title" translatable="yes">genet</property>
-    <property name="resizable">False</property>
-    <signal name="destroy" handler="on_genet_destroy"/>
-    <child>
-      <widget class="GtkVBox" id="vbox">
-        <property name="visible">True</property>
-        <child>
-          <widget class="GtkMenuBar" id="menubar">
-            <property name="visible">True</property>
-            <child>
-              <widget class="GtkMenuItem" id="menuitem1">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">_File</property>
-                <property name="use_underline">True</property>
-                <child>
-                  <widget class="GtkMenu" id="menu1">
-                    <property name="visible">True</property>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem1">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-new</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem2">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-open</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem3">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-save</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem4">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-save-as</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkSeparatorMenuItem" id="separatormenuitem1">
-                        <property name="visible">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem5">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-quit</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                </child>
-              </widget>
-            </child>
-            <child>
-              <widget class="GtkMenuItem" id="menuitem2">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">_Edit</property>
-                <property name="use_underline">True</property>
-                <child>
-                  <widget class="GtkMenu" id="menu2">
-                    <property name="visible">True</property>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem6">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-cut</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem7">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-copy</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem8">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-paste</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem9">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-delete</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                </child>
-              </widget>
-            </child>
-            <child>
-              <widget class="GtkMenuItem" id="menuitem3">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">_View</property>
-                <property name="use_underline">True</property>
-              </widget>
-            </child>
-            <child>
-              <widget class="GtkMenuItem" id="menuitem4">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">_Help</property>
-                <property name="use_underline">True</property>
-                <child>
-                  <widget class="GtkMenu" id="menu3">
-                    <property name="visible">True</property>
-                    <child>
-                      <widget class="GtkImageMenuItem" id="imagemenuitem10">
-                        <property name="visible">True</property>
-                        <property name="label" translatable="yes">gtk-about</property>
-                        <property name="use_underline">True</property>
-                        <property name="use_stock">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                </child>
-              </widget>
-            </child>
-          </widget>
-          <packing>
-            <property name="expand">False</property>
-          </packing>
-        </child>
-        <child>
-          <widget class="GtkToolbar" id="toolbar">
-            <property name="visible">True</property>
-          </widget>
-          <packing>
-            <property name="expand">False</property>
-            <property name="position">1</property>
-          </packing>
-        </child>
-        <child>
-          <widget class="GtkNotebook" id="notebook">
-            <property name="visible">True</property>
-            <property name="can_focus">True</property>
-            <child>
-              <widget class="GtkTable" id="table_browser">
-                <property name="visible">True</property>
-                <property name="n_rows">3</property>
-                <property name="n_columns">3</property>
-                <child>
-                  <widget class="GtkComboBoxEntry" id="comboboxentry_browser_nB">
-                    <property name="visible">True</property>
-                    <child internal-child="entry">
-                      <widget class="GtkEntry" id="comboboxentry-entry_browser_nB">
-                        <property name="visible">True</property>
-                        <property name="can_focus">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">2</property>
-                    <property name="right_attach">3</property>
-                    <property name="top_attach">1</property>
-                    <property name="bottom_attach">2</property>
-                  </packing>
-                </child>
-                <child>
-                  <widget class="GtkComboBoxEntry" id="comboboxentry_browser_nA">
-                    <property name="visible">True</property>
-                    <child internal-child="entry">
-                      <widget class="GtkEntry" id="comboboxentry-entry_browser_nA">
-                        <property name="visible">True</property>
-                        <property name="can_focus">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                  <packing>
-                    <property name="top_attach">1</property>
-                    <property name="bottom_attach">2</property>
-                  </packing>
-                </child>
-                <child>
-                  <widget class="GtkComboBoxEntry" id="comboboxentry_browser_level">
-                    <property name="visible">True</property>
-                    <child internal-child="entry">
-                      <widget class="GtkEntry" id="comboboxentry-entry_browser_level">
-                        <property name="visible">True</property>
-                        <property name="can_focus">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">1</property>
-                    <property name="right_attach">2</property>
-                  </packing>
-                </child>
-                <child>
-                  <widget class="GtkLabel" id="label_browser_level">
-                    <property name="visible">True</property>
-                    <property name="label" translatable="yes">Level</property>
-                  </widget>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <widget class="GtkButton" id="button_connect_nodes">
-                    <property name="visible">True</property>
-                    <property name="can_focus">True</property>
-                    <property name="receives_default">True</property>
-                    <property name="label" translatable="yes">Connect</property>
-                    <property name="response_id">0</property>
-                    <signal name="clicked" handler="on_button_connect_nodes_clicked"/>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">1</property>
-                    <property name="right_attach">2</property>
-                    <property name="top_attach">1</property>
-                    <property name="bottom_attach">2</property>
-                  </packing>
-                </child>
-              </widget>
-            </child>
-            <child>
-              <widget class="GtkLabel" id="label_browser">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">Browse</property>
-              </widget>
-              <packing>
-                <property name="type">tab</property>
-                <property name="tab_fill">False</property>
-              </packing>
-            </child>
-            <child>
-              <widget class="GtkTable" id="table_creator">
-                <property name="visible">True</property>
-                <property name="n_rows">5</property>
-                <property name="n_columns">5</property>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <placeholder/>
-                </child>
-                <child>
-                  <widget class="GtkButton" id="button_create_level">
-                    <property name="visible">True</property>
-                    <property name="can_focus">True</property>
-                    <property name="receives_default">True</property>
-                    <property name="label" translatable="yes">Create</property>
-                    <property name="response_id">0</property>
-                    <signal name="clicked" handler="on_button_create_level_clicked"/>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">2</property>
-                    <property name="right_attach">3</property>
-                  </packing>
-                </child>
-                <child>
-                  <widget class="GtkLabel" id="label_creator_level">
-                    <property name="visible">True</property>
-                    <property name="label" translatable="yes">Level</property>
-                  </widget>
-                </child>
-                <child>
-                  <widget class="GtkEntry" id="entry_creator_level">
-                    <property name="visible">True</property>
-                    <property name="can_focus">True</property>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">1</property>
-                    <property name="right_attach">2</property>
-                  </packing>
-                </child>
-                <child>
-                  <widget class="GtkComboBoxEntry" id="comboboxentry_creator_levels">
-                    <property name="visible">True</property>
-                    <child internal-child="entry">
-                      <widget class="GtkEntry" id="comboboxentry-entry_creator_levels">
-                        <property name="visible">True</property>
-                        <property name="can_focus">True</property>
-                      </widget>
-                    </child>
-                  </widget>
-                  <packing>
-                    <property name="left_attach">1</property>
-                    <property name="right_attach">2</property>
-                    <property name="top_attach">1</property>
-                    <property name="bottom_attach">2</property>
-                  </packing>
-                </child>
-              </widget>
-              <packing>
-                <property name="position">1</property>
-              </packing>
-            </child>
-            <child>
-              <widget class="GtkLabel" id="label_creator">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">Create</property>
-              </widget>
-              <packing>
-                <property name="type">tab</property>
-                <property name="position">1</property>
-                <property name="tab_fill">False</property>
-              </packing>
-            </child>
-            <child>
-              <placeholder/>
-            </child>
-            <child>
-              <widget class="GtkLabel" id="label_admin">
-                <property name="visible">True</property>
-                <property name="label" translatable="yes">Admin</property>
-              </widget>
-              <packing>
-                <property name="type">tab</property>
-                <property name="position">2</property>
-                <property name="tab_fill">False</property>
-              </packing>
-            </child>
-          </widget>
-          <packing>
-            <property name="position">2</property>
-          </packing>
-        </child>
-        <child>
-          <widget class="GtkStatusbar" id="statusbar">
-            <property name="visible">True</property>
-            <property name="spacing">2</property>
-          </widget>
-          <packing>
-            <property name="expand">False</property>
-            <property name="position">3</property>
-          </packing>
-        </child>
-      </widget>
-    </child>
-  </widget>
-</glade-interface>

File genet_browser.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
-################################################################################
-"""
-Related to paths and interlevel chains.
-
-"""

File genet_creator.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 class_edge import edge
-from class_node import node
-from db_connection import db
-from db_schema import *
-
-################################################################################
-# Create tables.
-# 
-def createLevel(description):
-    """
-    Create one level in the network data model. Gets the number
-    of levels in the 'levels' table and adds one padding on the left
-    with zeros.
-
-    param: description of the level.
-    """
-    st= "SELECT count(level) FROM gn____levels;"
-    n = db.query(st).getresult()[0][0]
-    new_level = str(n + 1).zfill(2)
-
-    st = "INSERT INTO gn____levels(level, description) " \
-        "VALUES ('" \
-        + new_level + "', '" \
-        + description + "');"
-    print st, db.query(st)
-    
-    # This should not be necessary.
-    print dropLevelTables(new_level)
-
-    # Create the layer tables.
-    print createLevelTables(new_level)
-
-def createEdgeType(level, description):
-    """
-    Create one edge type. Gets the number of types in the 'edge_types'
-    table and adds one padding on the left with zeros. Construct the 
-    new tablename of type with the new type.
-
-    param: level in which the new type is added.
-    param: description of the type.
-    """
-    st= "SELECT count(type) FROM gn____edge_types;"
-    n = db.query(st).getresult()[0][0]
-    new_type = str(n + 1).zfill(2)
-    new_tablename = "gn_" + level + "_edge_type_" + new_type
-
-    st = "INSERT INTO gn____edge_types(type, level, tablename, description) " \
-        "VALUES ('" \
-        + new_type + "', '" \
-        + level + "', '" \
-        + new_tablename + "', '" \
-        + description + "');"
-    print st, db.query(st)
-
-def connectNodes(level, idnA, idnB):
-    """
-    TODO
-    """
-

File genet_global.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 db_connection
-import db_schema
-
-#GN_DEBUG = True
-
-##
-# *** DANGER ***
-# startSchema() deletes db schema.
-#
-##db_schema.startSchema()
-

File genet_window.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 gtk
-import gtk.glade
-import pygtk
-
-from genet_browser import *
-from genet_creator import * 
-
-class window:
-    def __init__(self):
-        """
-        Starting window.
-        
-        """
-        gladefile = "genet.glade"
-        windowname = "genet"
-        self.wTree = gtk.glade.XML (gladefile,windowname)
-
-        dic = {
-            "on_button_connect_nodes_clicked" : 
-            self.button_connect_nodes_clicked,
-            "on_button_create_level_clicked" : 
-            self.button_create_level_clicked,
-#            "on_comboboxentry_creator_levels_popdown" : 
-#            self.comboboxentry_creator_levels_popdown,
-#            "on_comboboxentry_creator_levels_popup" : 
-#            self.comboboxentry_creator_levels_popup,
-            "on_genet_destroy" : (gtk.main_quit) }
-        self.wTree.signal_autoconnect (dic)
-        return
-
-    def button_connect_nodes_clicked(self,widget):
-        print 'Clicked!'
-        
-    def button_create_level_clicked(self,widget):
-        description = self.wTree.get_widget("entry_creator_level").get_text()
-        createLevel(description)
-
-    def comboboxentry_levels_popdown(self,widget):
-        print 'Combo!' 
-        widget.items = 'aoe'
-
-    def comboboxentry_levels_popup(self,widget):
-        print 'Combo!' 
-        widget.items = 'aoe'
-
-    def main(self):
-        gtk.main()
-        
-app = window()
-app.main()

File model/__init__.py

Empty file added.

File model/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.
+* 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.
+    
+    The the edge itself, 'idnA' and 'idnB' should be from the same level, 
+    this is resolved at execution time from an intelligent interface.
+
+    """
+    def __init__(self, level, idnA, idnB, idparent, parentlevel, idtype):
+        self.id = None
+        self.level = level
+        self.idnA = idnA
+        self.idnB = idnB
+        self.idparent = idparent
+        self.parentlevel = parentlevel
+        self.idtype = idtype
+    
+    def store(self, db):
+        """
+        Stores data in db. 
+
+        @param db is the database object.
+        @eturns the SQL statement and node id.
+        """
+        if self.id:
+            st = "UPDATE gn_" + str(self.level) + "_edges SET " \
+                "idnA = " + str(self.idnA) + ", " \
+                "idnB" + str(self.idnB) + ", " \
+                "idtype = " + str(self.idtype) + " " \
+                "WHERE id = " + str(self.id) + ";"
+            db.query(st)
+            return st, self.id
+        # TODO UPDATE tree
+
+        else:
+            st1 = "INSERT INTO gn_" + str(self.level) + "_edges(idna, idnb, iddown, downlevel, idtype) " \
+                "VALUES(" \
+                + str(self.idnA) + ", " \
+                + str(self.idnB) + ", " \
+                + str(self.idtype) + ") " \
+                "RETURNING id;"
+            self.id = db.query(st1).getresult()[0][0]
+            st2 = "INSERT INTO gn____tree(idparent, idchild, parentlevel, childlevel) " \
+                "VALUES(" \
+                + str(self.idparent) + ", " \
+                + str(self.id) + ", " \
+                + str(self.parentlevel) + ", " \
+                + str(self.level) + ");" 
+            db.query(st2)
+            return st1, st2, self.id
+        

File model/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.
+* idtype: what kind of element is.
+
+"""
+
+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):
+        """
+        Stores data in db. 
+
+        @param db is the database object.
+        @returns the SQL statement and node id.
+        """
+        if self.id:
+            st = "UPDATE gn_" + str(self.level) + "_nodes SET " \
+                "idtype = " + str(self.idtype) + " " \
+                "WHERE id = " + str(self.id) + ";"
+            db.query(st)
+        else:
+            st = "INSERT INTO gn_" + str(self.level) + "_nodes(iddown, downlevel, idtype) " \
+                "VALUES(" \
+                + str(self.idtype) + ") " \
+                "RETURNING id;"
+            self.id = db.query(st).getresult()[0][0]
+        return st, self.id

File model/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 model/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 = """
+    CREATE SEQUENCE "gn____ids_seq" 
+      INCREMENT 1 
+      MINVALUE 100000000 
+      NO MAXVALUE 
+      NO CYCLE;
+    """
+    ret = st, db.query(st)
+    
+    ##
+    # All other elements, not in network, has another sequence source.
+    #
+    st = """
+    CREATE SEQUENCE "gn____aux_seq"
+      INCREMENT 1
+      MINVALUE 1
+      NO MAXVALUE
+      NO CYCLE;
+    """
+    ret = ret, st, db.query(st)
+    
+    ##
+    # Levels directory.
+    # 
+    st = """
+    CREATE TABLE "gn____levels" (
+        "id" integer NOT NULL DEFAULT nextval('gn____aux_seq'),
+        "description" varchar(126)
+    ) WITH (OIDS = FALSE);
+    ALTER TABLE "gn____levels" 
+        ADD CONSTRAINT "gn____levels_pk" 
+        PRIMARY KEY("id");
+    """
+    ret = ret, st, db.query(st)
+
+    ##
+    # Out from basic schema all tables are referenced by this ones.
+    #
+    st = """
+    CREATE TABLE "gn____node_types" (
+        "id" integer NOT NULL DEFAULT nextval('gn____aux_seq'),
+        "level" integer,
+        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
+        "description" varchar(126)
+    ) WITH (OIDS = FALSE);
+    ALTER TABLE "gn____node_types" 
+        ADD CONSTRAINT "gn____node_types_pk" 
+        PRIMARY KEY("id");
+    ALTER TABLE "gn____node_types" 
+        ADD CONSTRAINT "gn____node_types_level" 
+        FOREIGN KEY ("level")
+        REFERENCES "gn____levels"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    
+    CREATE TABLE "gn____edge_types" (
+        "id" integer NOT NULL DEFAULT nextval('gn____aux_seq'),
+        "level" integer,
+        "tablename" varchar(63), -- pg NAMEDATALEN is 63 currently.
+        "description" varchar(126)
+    ) WITH (OIDS = FALSE);
+    ALTER TABLE "gn____edge_types" 
+        ADD CONSTRAINT "gn____edge_types_pk" 
+        PRIMARY KEY("id");
+    ALTER TABLE "gn____edge_types" 
+        ADD CONSTRAINT "gn____edge_types_level" 
+        FOREIGN KEY ("level")
+        REFERENCES "gn____levels"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    """
+    ret = ret, st, db.query(st)
+
+    ##
+    # The tree relates between levels.
+    # 
+    st = """
+    CREATE TABLE "gn____tree" (
+        "idparent" integer,
+        "idchild" integer,
+        "parentlevel" varchar(32),
+        "childlevel" varchar(32)
+    ) WITH (OIDS = FALSE);
+    -- Child has only one parent.
+    ALTER TABLE "gn____tree" 
+        ADD CONSTRAINT "gn____tree_idchild" 
+        PRIMARY KEY("idchild");
+    """
+    ret = ret, st, db.query(st)
+    
+    # Return all outputs from queries.
+    return ret
+
+def dropSchema():
+    """
+    Deletes all schematic tables.
+
+    """
+    st = """
+    DROP SEQUENCE IF EXISTS "gn____ids_seq" CASCADE;
+    DROP SEQUENCE IF EXISTS "gn____aux_seq" CASCADE;
+    DROP TABLE IF EXISTS "gn____tree" CASCADE;
+    DROP TABLE IF EXISTS "gn____levels" CASCADE;
+    DROP TABLE IF EXISTS "gn____node_types" CASCADE;
+    DROP TABLE IF EXISTS "gn____edge_types" CASCADE;
+    """
+    return 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____ids_seq'),
+        "idtype" integer
+    ) WITH (OIDS = FALSE);
+    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____node_types"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+
+    CREATE TABLE "gn_""" + level + """_edges" (
+        "id" integer NOT NULL DEFAULT nextval('gn____ids_seq'),
+        "idna" integer,
+        "idnb" integer,
+        "idtype" integer
+    ) WITH (OIDS = FALSE);
+    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____edge_types"("id") 
+        ON UPDATE RESTRICT ON DELETE RESTRICT;
+    """
+    return 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;
+    """
+    return st, db.query(st)

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 class_edge import edge
-from class_node import node
-from db_connection import db
-from db_schema import *
-
-################################################################################
-# Insert tables.
-# 
-print insertNodeType('01', 'vaults', 'Vaults and manholes.')
-print insertNodeType('01', 'poles', 'Poles and towers.')
-print insertNodeType('02', 'closures', 'Splicing boxes.')
-print insertNodeType('03', 'splices', 'Splices.')
-
-print insertEdgeType('01', 'trails', 'Trenchs.')
-print insertEdgeType('02', 'cables', 'Cables.')
-print insertEdgeType('03', 'fibers', 'Fibers.')
-
-print dropLevelTables('00')
-print createLevelTables('00')
-
-print dropLevelTables('01')
-print createLevelTables('01')
-
-print dropLevelTables('02')
-print createLevelTables('02')
-
-print dropLevelTables('LL')
-print createLevelTables('LL')
-
-################################################################################
-# Insert data.
-#
-N001 = node('01', 0, 2323, 2)
-print N001.store(db)
-
-N002 = node('01', 0, 0, 1)
-print N002.store(db)
-
-N003 = node('01', 0, 0, 2)
-print N003.store(db)
-N003.idtype = 1
-print N003.store(db)
-
-E001 = edge('01', N001.id, N002.id, 0, 0, 2)
-print E001.store(db)
-
-for r in db.query("SELECT * FROM gn_01_nodes").dictresult():
-    print 'id: %(id)s - iddown: %(iddown)s - idtype: %(idtype)s' % r
-
-for r in db.query("SELECT * FROM gn_01_edges").dictresult():
-    print 'id: %(id)s - idnA: %(idna)s - idnB: %(idnb)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 pylab as P
-import networkx as NX
-from test_data import *
-
-################################################################################
-# Level 00
-#
-G00 = NX.XGraph(name='Level 00', multiedges=True, selfloops=True)
-
-for r in db.query("SELECT * FROM gn_00_edges").dictresult():
-    G00.add_edges_from([(r['idna'], r['idnb'], r['id'])])
-    
-# May be there are isolated nodes.
-for r in db.query("SELECT * FROM gn_00_nodes").dictresult():
-    G00.add_node(r['id'])
-
-print 'G00 nodes:', G00.nodes()
-print 'G00 edges:', G00.edges()
-
-pos = NX.spring_layout(G00)
-NX.draw_networkx(G00, 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
-