nhueffme: thuban/Extensions/ogr ogrshapes.py, 1.2, 1.3 ogrstart.py, 1.1, 1.2

cvs@intevation.de cvs at intevation.de
Mon Dec 20 15:13:59 CET 2004


Author: nhueffme

Update of /thubanrepository/thuban/Extensions/ogr
In directory doto:/tmp/cvs-serv29961/Extensions/ogr

Modified Files:
	ogrshapes.py ogrstart.py 
Log Message:
Fixed some issues from Bernhard.



Index: ogrshapes.py
===================================================================
RCS file: /thubanrepository/thuban/Extensions/ogr/ogrshapes.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -d -r1.2 -r1.3
--- ogrshapes.py	8 Dec 2004 17:37:30 -0000	1.2
+++ ogrshapes.py	20 Dec 2004 14:13:57 -0000	1.3
@@ -1,6 +1,6 @@
 # Copyright (C) 2004 by Intevation GmbH
 # Authors:
-# Nina Hüffmeyer <nhueffme at intevation.de>
+# Nina Hueffmeyer <nhueffme at intevation.de>
 #
 # This program is free software under the GPL (>=v2)
 # Read the file COPYING coming with the software for details.
@@ -26,10 +26,6 @@
 from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT
 from Thuban.Model.data import RAW_PYTHON, RAW_SHAPEFILE, RAW_WKT
 
-# Raw data in ogr format
-RAW_OGRSHAPES = "RAW_OGRSHAPES"
-
-
 
 def has_ogr_support():
     """Return whether this Thuban instance supports ogr file formats
@@ -42,12 +38,12 @@
 if ogr is not None:
     # mapping from ogr-lib shapetype and table constants to our constants
     ogrlib_shapetypes = {ogr.wkbPolygon: SHAPETYPE_POLYGON,
-                       ogr.wkbLineString: SHAPETYPE_ARC,
-                       ogr.wkbPoint: SHAPETYPE_POINT}
+                ogr.wkbLineString: SHAPETYPE_ARC,
+                ogr.wkbPoint: SHAPETYPE_POINT}
 
     fieldtype_map = {ogr.OFTString: table.FIELDTYPE_STRING,
-	ogr.OFTInteger: table.FIELDTYPE_INT,
-	ogr.OFTReal: table.FIELDTYPE_DOUBLE}
+                ogr.OFTInteger: table.FIELDTYPE_INT,
+                ogr.OFTReal: table.FIELDTYPE_DOUBLE}
 
 
 class OGRShape:
@@ -62,30 +58,54 @@
         """
         Return the bounding box of the shape as a tuple (minx,miny,maxx,maxy)
         """
-	shape = self.ogrlayer.GetFeature(self.shapeid)
-	geom = shape.GetGeometryRef()
-	minx, maxx, miny, maxy = geom.GetEnvelope()
-	return (minx, miny, maxx, maxy)
+        shape = self.ogrlayer.GetFeature(self.shapeid)
+        geom = shape.GetGeometryRef()
+        minx, maxx, miny, maxy = geom.GetEnvelope()
+        return (minx, miny, maxx, maxy)
 
     def ShapeID(self):
         return self.shapeid
 
-    # diese Methode funktioniert vielleicht noch nicht für andere Formate als shp
+    # diese Methode funktioniert vielleicht noch nicht für andere Formate 
+    #als shp
     #(wenn ein polygon aus mehreren
-    # Ringen besteht o.ä., hat ein Geometry-Objekt mehr als einen GeometryRef().----------------------------
+    # Ringen besteht o.ä., hat ein Geometry-Objekt mehr als einen 
+    #GeometryRef().---------
     def Points(self):
         """Return the coordinates of the shape as a list of lists of pairs"""
         feature = self.ogrlayer.GetFeature(self.shapeid)
-	geometry = feature.GetGeometryRef()
-	while geometry.GetGeometryCount() != 0:
-		geometry = geometry.GetGeometryRef(0)
-        points = []
-	for point in range(geometry.GetPointCount()):
-		x = geometry.GetX(point)
-		y = geometry.GetY(point)
-		points.append((x, y))
-        points = [points]
-        return points
+        geom = feature.GetGeometryRef()
+        shape = []
+        # if geometry object is of type point or line
+        if geom.GetGeometryCount() == 0:
+            points =[]
+            for point in range(geom.GetPointCount()):
+                x = geom.GetX(point)
+                y = geom.GetY(point)
+                points.append((x, y))
+            return [points]
+        # if geometry object is of type polygon or multipolygon
+        for i in range(geom.GetGeometryCount()):
+            points = []
+	    geometry = geom.GetGeometryRef(i)
+	    # if geometry object is polygon
+            if geometry.GetGeometryCount() == 0:
+                for point in range(geometry.GetPointCount()):
+                    x = geometry.GetX(point)
+                    y = geometry.GetY(point)
+                    points.append((x, y))
+                shape.append(points)
+            # if geometry object is of type multipolygon
+	    else:
+                for j in range(geometry.GetGeometryCount()):
+                    points = []
+                    subgeom = geometry.GetGeometryRef(j)
+                    for point in range(subgeom.GetPointCount()):
+                        x = subgeom.GetX(point)
+                        y = subgeom.GetY(point)
+                        points.append((x, y))
+                    shape.append(points)
+        return shape
 
     def RawData(self):
         """Return the shape id to use with the shapestore"""
@@ -98,8 +118,9 @@
 
 class OGRShapeStore:
 
-    """Corresponds to an OGRLayer object, containing features/shapes and providing all methods Thuban
-       needs."""
+    """Corresponds to an OGRLayer object, containing features/shapes and 
+       providing all methods Thuban needs.
+    """
 
     def __init__(self, session, filename, layername):
         # Make the filename absolute. The filename will be
@@ -107,26 +128,26 @@
         # session we need to compare absolute paths and it's usually
         # safer to always work with absolute paths.
 
-	self.filename = os.path.abspath(filename)
-	self.layername = layername
+        self.filename = os.path.abspath(filename)
+        self.layername = layername
 
-	self.ogrdatasource = ogr.Open(self.filename)
-	self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)
-	self.table = OGRTable(self.ogrdatasource, self.ogrlayer)
+        self.ogrdatasource = ogr.Open(self.filename)
+        self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)
+        self.table = OGRTable(self.ogrdatasource, self.ogrlayer)
 
         self._open_ogrlayer(layername)
 
     def _open_ogrlayer(self, layername):
-	self.numshapes = self.ogrlayer.GetFeatureCount()
-	self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()
-	extent = self.ogrlayer.GetExtent()
+        self.numshapes = self.ogrlayer.GetFeatureCount()
+        self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()
+        extent = self.ogrlayer.GetExtent()
 
-	if extent:
-		self.bbox = [extent[0], extent[2], extent[1], extent[3]]
-	else:
-		self.bbox = None
+        if extent:
+            self.bbox = [extent[0], extent[2], extent[1], extent[3]]
+        else:
+            self.bbox = None
 
-	self.shapetype = ogrlib_shapetypes[self.shapetype]
+        self.shapetype = ogrlib_shapetypes[self.shapetype]
 
     def OGRLayer(self):
         """Return the OGRLayer object"""
@@ -148,8 +169,8 @@
         return self.shapetype
 
     def RawShapeFormat(self):
-        """Return the raw data format of the shape data, i.e. RAW_OGRSHAPES"""
-        return RAW_OGRSHAPES
+        """Return the raw data format of the shape data, i.e. RAW_PYTHON"""
+        return RAW_PYTHON
 
     def NumShapes(self):
         """Return the number of shapes in the shape store"""
@@ -167,7 +188,7 @@
         form (minx, miny, maxx, maxy) in the coordinate system of the
         shape store.
 
-	The method GetFID() returns feature IDs starting from 0. In Thuban feature IDs start with 1.
+        The method GetFID() returns feature IDs starting from 0.
         """
         # Bind a few globals to locals to make it a bit faster
         cls = OGRShape
@@ -175,21 +196,23 @@
 
         left, bottom, right, top = bbox
 
-	# create a geometry which can be passed to the layer as spatial filter
-	bboxpolygon = ogr.CreateGeometryFromWkt('Polygon((%s %s, %s %s, %s %s, %s %s, %s %s))'
-		%(left, bottom, left, top, right, top, right, bottom, left, bottom))
+        # create a geometry which can be passed to the layer as spatial filter
+        bboxpolygon = ogr.CreateGeometryFromWkt(
+                      ('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'
+                                 %(left, bottom, left, top, right, top, 
+                                  right, bottom, left, bottom)))
 
-	if ogrlayer.GetSpatialRef():
-		bboxpolygon.AssignSpatialReference(ogrlayer.GetSpatialRef())
+        if ogrlayer.GetSpatialRef():
+            bboxpolygon.AssignSpatialReference(ogrlayer.GetSpatialRef())
 
-	ogrlayer.ResetReading()
-	ogrlayer.SetSpatialFilter(bboxpolygon)
-	numFeatures = ogrlayer.GetFeatureCount()
-	for feature in range(numFeatures):
-		nextFeature = ogrlayer.GetNextFeature()
-		yield cls(ogrlayer, nextFeature.GetFID())
-	ogrlayer.SetSpatialFilter(None)
-	bboxpolygon.Destroy()
+        ogrlayer.ResetReading()
+        ogrlayer.SetSpatialFilter(bboxpolygon)
+        numFeatures = ogrlayer.GetFeatureCount()
+        for feature in range(numFeatures):
+            nextFeature = ogrlayer.GetNextFeature()
+            yield cls(ogrlayer, nextFeature.GetFID())
+        ogrlayer.SetSpatialFilter(None)
+        bboxpolygon.Destroy()
 
     def AllShapes(self):
         """Return an iterable over the shapes in the shape store."""
@@ -221,13 +244,13 @@
     def __init__(self, ds, layer):
         """Initialize the OGRTable.
 
-	   ds should be an instance of OGRDatasource.
-	   layer should be an instance of OGRLayer.
+        ds should be an instance of OGRDatasource.
+        layer should be an instance of OGRLayer.
         """
 
         self.datasource = ds
         self.layer = layer
-	self.tablename = layer.GetName()
+        self.tablename = layer.GetName()
 
         # Map column names and indices to column objects.
         self.column_map = {}
@@ -238,15 +261,15 @@
         """Internal: Update information about the table"""
         self.columns = []
 
-	layerdefn = self.layer.GetLayerDefn()
-	for i in range(layerdefn.GetFieldCount()):
-		fielddef = layerdefn.GetFieldDefn(i)
-		fieldname = fielddef.GetName()
-		fieldtype = fieldtype_map[fielddef.GetType()]
-		fieldindex = layerdefn.GetFieldIndex(fieldname)
-		col = OGRColumn(fieldname, fieldtype, fieldindex)
-		if col is not None:
-			self.columns.append(col)
+        layerdefn = self.layer.GetLayerDefn()
+        for i in range(layerdefn.GetFieldCount()):
+            fielddef = layerdefn.GetFieldDefn(i)
+            fieldname = fielddef.GetName()
+            fieldtype = fieldtype_map[fielddef.GetType()]
+            fieldindex = layerdefn.GetFieldIndex(fieldname)
+            col = OGRColumn(fieldname, fieldtype, fieldindex)
+            if col is not None:
+                self.columns.append(col)
 
         for col in self.columns:
             self.column_map[col.name] = col
@@ -268,82 +291,89 @@
         return ()
 
     def NumColumns(self):
-    	"""Return the number of columns."""
+        """Return the number of columns."""
         return len(self.columns)
 
     def Columns(self):
-    	"""Return all columns."""
+        """Return all columns."""
         return self.columns
 
     def Column(self, col):
-    	"""Return the column col. col can be either a string or an integer."""
+        """Return the column col. col can be either a string or an integer."""
         return self.column_map[col]
 
     def HasColumn(self, col):
-    	"""Return if column col exists. col can be either a string or an integer."""
+        """Return if column col exists. col can be either a string or an 
+        integer.
+        """
         return self.column_map.has_key(col)
 
     def NumRows(self):
-    	"""Return the number of rows in the table, which equals the number of features in the layer."""
-	return self.layer.GetFeatureCount()
+        """Return the number of rows in the table, which equals the number of 
+        features in the layer.
+        """
+        return self.layer.GetFeatureCount()
 
     def RowIdToOrdinal(self, gid):
         """Return the row ordinal given its id"""
-	return self.layer.GetFeature(gid).GetFID()
+        return self.layer.GetFeature(gid).GetFID()
 
     def RowOrdinalToId(self, num):
         """Return the rowid for given its ordinal"""
-	return self.layer.GetFeature(num).GetFID()
+        return self.layer.GetFeature(num).GetFID()
 
     def ReadRowAsDict(self, row, row_is_ordinal = 0):
-    	"""Return a dictionary which contains all the fields."""
-    	layerdef = self.layer.GetLayerDefn()
-    	feature = self.layer.GetFeature(row)
-	result = {}
-	for i in range(feature.GetFieldCount()):
-		fielddef = layerdef.GetFieldDefn(i)
-		result[fielddef.GetName()] = feature.GetField(i)
+        """Return a dictionary which contains all the fields."""
+        layerdef = self.layer.GetLayerDefn()
+        feature = self.layer.GetFeature(row)
+        result = {}
+        for i in range(feature.GetFieldCount()):
+            fielddef = layerdef.GetFieldDefn(i)
+            result[fielddef.GetName()] = feature.GetField(i)
         return result
 
     def ReadValue(self, row, col, row_is_ordinal = 0):
-    	"""Return the requested value."""
-	if col is None:
-		return None
-	else:
-		feature = self.layer.GetFeature(row)
-		return feature.GetField(col)
+        """Return the requested value."""
+        if col is None:
+            return None
+        else:
+            feature = self.layer.GetFeature(row)
+        return feature.GetField(col)
 
     def ValueRange(self, col):
-    	"""Return the value range of the given column (given as string)."""
-    	result = self.datasource.ExecuteSQL("SELECT min(%s), max(%s) FROM %s"
-		%(col, col, self.layer.GetName()))
-	result.ResetReading()
-	feature = result.GetNextFeature()
-	try:
-		min = feature.GetField(0)
-		max = feature.GetField(1)
-	except:
-		min = 0
-		max = 0
-	self.datasource.ReleaseResultSet(result)
+        """Return the value range of the given column (given as string)."""
+        result = self.datasource.ExecuteSQL("SELECT min(%s), max(%s) FROM %s"
+                %(col, col, self.layer.GetName()))
+        result.ResetReading()
+        feature = result.GetNextFeature()
+        try:
+            min = feature.GetField(0)
+            max = feature.GetField(1)
+        except:
+            min = 0
+            max = 0
+        self.datasource.ReleaseResultSet(result)
         return (min, max)
 
     def UniqueValues(self, col):
-    	"""Return all the values being found in the column (given as string)."""
-	result = self.datasource.ExecuteSQL("SELECT DISTINCT %s FROM %s ORDER BY %s" %(col, self.layer.GetName(),col))
-	values = []
-	while 1:
-		feature = result.GetNextFeature()
-		if feature is None:
-			break
-		values.append(feature.GetField(0))
-	self.datasource.ReleaseResultSet(result)
+        """Return all the values being found in the column (given as string).
+        """
+        result = self.datasource.ExecuteSQL((
+                    "SELECT DISTINCT %s FROM %s ORDER BY %s"
+                     %(col,self.layer.GetName(),col)))
+        values = []
+        while 1:
+            feature = result.GetNextFeature()
+            if feature is None:
+                break
+            values.append(feature.GetField(0))
+        self.datasource.ReleaseResultSet(result)
         return values
 
     def SimpleQuery(self, left, comparison, right):
-    	"""Return the FIDs resulting from the given query."""
+        """Return the FIDs resulting from the given query."""
         if comparison not in ("==", "!=", "<", "<=", ">=", ">"):
-            raise ValueError("Comparison operator %r not allowed" % comparison)
+            raise ValueError("Comparison operator %r not allowed" %comparison)
 
         if comparison == "==":
             comparison = "="
@@ -353,16 +383,17 @@
         else:
             right_template = right
 
-        query = "SELECT FID FROM %s WHERE '%s' %s %s ORDER BY FID" %(self.tablename, left.name, comparison, right_template)
+        query = ("SELECT FID FROM %s WHERE '%s' %s %s ORDER BY FID"
+                % (self.tablename,left.name, comparison, right_template))
 
         lay = self.datasource.ExecuteSQL(query)
-	result = []
-        while 1:
+        result = []
+        while lay is not None:
             feature = lay.GetNextFeature()
             if feature is None:
                 break
             result.append(feature.GetField(0))
-	self.datasource.ReleaseResultSet(lay)
+        self.datasource.ReleaseResultSet(lay)
         return result
 
 

Index: ogrstart.py
===================================================================
RCS file: /thubanrepository/thuban/Extensions/ogr/ogrstart.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -d -r1.1 -r1.2
--- ogrstart.py	7 Dec 2004 16:44:51 -0000	1.1
+++ ogrstart.py	20 Dec 2004 14:13:57 -0000	1.2
@@ -22,50 +22,46 @@
 from Thuban.Model.layer import Layer
 
 # Import ogr related classes
-from Extensions.ogr import ogrshapes
+from Extensions.ogr import ogrshapes, ogrdialog
 
 def open_with_ogr(context):
-	'''Export data depending on the set properties.
+    '''Export data depending on the set properties.
 
-    	This is the main export funcation.
-    	'''
-    	canvas = context.mainwindow.canvas
-    	file = None
-    	map = canvas.Map()
+    This is the main export funcation.
+    '''
+    canvas = context.mainwindow.canvas
+    file = None
+    map = canvas.Map()
 
-    	if hasattr(canvas, "export_path"):
-	        export_path = canvas.export_path
-    	else:
-	        export_path="."
-    	# Get the file to be opened
-	dlg = wxFileDialog(canvas, _("Select a data file"),
-                           export_path, "",
+    # Get the file to be opened
+    dlg = wxFileDialog(canvas, _("Select a data file"),
+                           ".", "",
                            _("Shapefiles (*.shp)") + "|*.shp;*.SHP|" +
                            _("All Files (*.*)") + "|*.*",
                            wxOPEN | wxMULTIPLE)
 
-	if dlg.ShowModal() == wxID_OK:
-	    filenames = dlg.GetPaths()
-	    for filename in filenames:
-		title = os.path.splitext(os.path.basename(filename))[0]
-		has_layers = map.HasLayers()
-		layername = title
-		try:
-		    session = context.application.Session()
-		    store = ogrshapes.OGRShapeStore(session, filename, layername)
-                    session.AddShapeStore(store)
-                except IOError:
-                    # the layer couldn't be opened
-                    self.RunMessageBox(_("Add Layer"),
-                                       _("Can't open the file '%s'.")%filename)
-                else:
-                    layer = Layer(title, store)
-                    map.AddLayer(layer)
-                    if not has_layers:
-                        # if we're adding a layer to an empty map, fit the
-                        # new map to the window
-                        canvas.FitMapToWindow()
-                    context.application.SetPath("data",filename)
+    if dlg.ShowModal() == wxID_OK:
+        filenames = dlg.GetPaths()
+        for filename in filenames:
+            title = os.path.splitext(os.path.basename(filename))[0]
+            has_layers = map.HasLayers()
+            layername = title
+            try:
+                session = context.application.Session()
+                store = ogrshapes.OGRShapeStore(session, filename, layername)
+                session.AddShapeStore(store)
+            except IOError:
+                # the layer couldn't be opened
+                self.RunMessageBox(("Add Layer"),
+                                ("Can't open the file '%s'.")%filename)
+            else:
+                layer = Layer(title, store)
+                map.AddLayer(layer)
+                if not has_layers:
+                    # if we're adding a layer to an empty map, fit the
+                    # new map to the window
+                    canvas.FitMapToWindow()
+                context.application.SetPath("data",filename)
         dlg.Destroy()
 
 
@@ -78,12 +74,13 @@
 # See Thuban/UI/menu.py for the API of the Menu class
 from Thuban.UI.mainwindow import main_menu
 
-# create a new command and register it
-registry.Add(Command('open_ogr_files', _('Open an ogr-file'), open_with_ogr,
-                     helptext = _('Open a file supported from ogr')))
+# create new commands and register them
+registry.Add(Command('open_ogr_files', 'Open an ogr-file', open_with_ogr,
+                     helptext = 'Open a file supported from ogr'))
 
 # find the ogr menu (create it a new if not found)
 ogr_menu = main_menu.FindOrInsertMenu('ogr', _('OGR'))
 
 # finally bind the new command with an entry in the extensions menu
 ogr_menu.InsertItem('open_ogr_files')
+





More information about the Thuban-devel mailing list

This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)