/[thuban]/branches/WIP-pyshapelib-bramz/Extensions/ogr/ogrshapes.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/Extensions/ogr/ogrshapes.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2493 by nhueffme, Mon Dec 20 14:13:57 2004 UTC revision 2549 by nhueffme, Wed Jan 26 09:17:01 2005 UTC
# Line 26  from Thuban.Model import table Line 26  from Thuban.Model import table
26  from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT  from Thuban.Model.data import SHAPETYPE_POLYGON, SHAPETYPE_ARC, SHAPETYPE_POINT
27  from Thuban.Model.data import RAW_PYTHON, RAW_SHAPEFILE, RAW_WKT  from Thuban.Model.data import RAW_PYTHON, RAW_SHAPEFILE, RAW_WKT
28    
29    SHAPETYPE_UNKNOWN = "unknown"
30    
31  def has_ogr_support():  def has_ogr_support():
32      """Return whether this Thuban instance supports ogr file formats      """Return whether this Thuban instance supports ogr file formats
# Line 39  if ogr is not None: Line 40  if ogr is not None:
40      # mapping from ogr-lib shapetype and table constants to our constants      # mapping from ogr-lib shapetype and table constants to our constants
41      ogrlib_shapetypes = {ogr.wkbPolygon: SHAPETYPE_POLYGON,      ogrlib_shapetypes = {ogr.wkbPolygon: SHAPETYPE_POLYGON,
42                  ogr.wkbLineString: SHAPETYPE_ARC,                  ogr.wkbLineString: SHAPETYPE_ARC,
43                  ogr.wkbPoint: SHAPETYPE_POINT}                  ogr.wkbPoint: SHAPETYPE_POINT,
44                    ogr.wkbUnknown: SHAPETYPE_UNKNOWN}
45    
46      fieldtype_map = {ogr.OFTString: table.FIELDTYPE_STRING,      fieldtype_map = {ogr.OFTString: table.FIELDTYPE_STRING,
47                  ogr.OFTInteger: table.FIELDTYPE_INT,                  ogr.OFTInteger: table.FIELDTYPE_INT,
# Line 66  class OGRShape: Line 68  class OGRShape:
68      def ShapeID(self):      def ShapeID(self):
69          return self.shapeid          return self.shapeid
70    
     # 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().---------  
71      def Points(self):      def Points(self):
72          """Return the coordinates of the shape as a list of lists of pairs"""          """Return the coordinates of the shape as a list of lists of pairs"""
73            print "FID: %s" %(self.shapeid)
74            shape = []
75            #spatialFilter = self.ogrlayer.GetSpatialFilter()
76            
77    #        if spatialFilter is not None:
78            self.ogrlayer.SetSpatialFilter(None)
79      #          feature = self.ogrlayer.GetFeature(self.shapeid)
80       #         self.ogrlayer.SetSpatialFilter(spatialFilter)
81        #    else:
82          feature = self.ogrlayer.GetFeature(self.shapeid)          feature = self.ogrlayer.GetFeature(self.shapeid)
83          
84            if feature is None:
85                print "feature is none.........................."
86                return shape.append([])
87          geom = feature.GetGeometryRef()          geom = feature.GetGeometryRef()
88          shape = []  
89            if geom is None:
90                print "geom is none................................"
91                return shape.append([])
92    
93          # if geometry object is of type point or line          # if geometry object is of type point or line
94          if geom.GetGeometryCount() == 0:          if geom.GetGeometryCount() == 0:
95              points =[]              points =[]
# Line 83  class OGRShape: Line 97  class OGRShape:
97                  x = geom.GetX(point)                  x = geom.GetX(point)
98                  y = geom.GetY(point)                  y = geom.GetY(point)
99                  points.append((x, y))                  points.append((x, y))
100                print points
101              return [points]              return [points]
102          # if geometry object is of type polygon or multipolygon          # if geometry object is of type polygon or multipolygon
103          for i in range(geom.GetGeometryCount()):          for i in range(geom.GetGeometryCount()):
104              points = []              points = []
105              geometry = geom.GetGeometryRef(i)              geometry = geom.GetGeometryRef(i)
106              # if geometry object is polygon              # if geometry object is polygon
107              if geometry.GetGeometryCount() == 0:              if geometry.GetGeometryCount() == 0:
108                  for point in range(geometry.GetPointCount()):                  for point in range(geometry.GetPointCount()):
109                      x = geometry.GetX(point)                      x = geometry.GetX(point)
# Line 96  class OGRShape: Line 111  class OGRShape:
111                      points.append((x, y))                      points.append((x, y))
112                  shape.append(points)                  shape.append(points)
113              # if geometry object is of type multipolygon              # if geometry object is of type multipolygon
114              else:              else:
115                  for j in range(geometry.GetGeometryCount()):                  for j in range(geometry.GetGeometryCount()):
116                      points = []                      points = []
117                      subgeom = geometry.GetGeometryRef(j)                      subgeom = geometry.GetGeometryRef(j)
# Line 105  class OGRShape: Line 120  class OGRShape:
120                          y = subgeom.GetY(point)                          y = subgeom.GetY(point)
121                          points.append((x, y))                          points.append((x, y))
122                      shape.append(points)                      shape.append(points)
123            print shape
124          return shape          return shape
125    
126      def RawData(self):      def RawData(self):
# Line 128  class OGRShapeStore: Line 144  class OGRShapeStore:
144          # session we need to compare absolute paths and it's usually          # session we need to compare absolute paths and it's usually
145          # safer to always work with absolute paths.          # safer to always work with absolute paths.
146    
147          self.filename = os.path.abspath(filename)          self.filename = filename
148          self.layername = layername          self.layername = layername
149    
150          self.ogrdatasource = ogr.Open(self.filename)          self.ogrdatasource = ogr.Open(filename)
151          self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)          self.ogrlayer = (self.ogrdatasource).GetLayerByName(layername)
152          self.table = OGRTable(self.ogrdatasource, self.ogrlayer)  
153            driver = self.ogrdatasource.GetDriver().GetName()
154            if driver == 'PostgreSQL':
155                self.id_column = 'gid'
156            else:
157                self.id_column = 'fid'
158    
159            self.table = OGRTable(self.ogrdatasource, self.ogrlayer, self.id_column)
160    
161          self._open_ogrlayer(layername)          self._open_ogrlayer(layername)
162    
163      def _open_ogrlayer(self, layername):      def _open_ogrlayer(self, layername):
164          self.numshapes = self.ogrlayer.GetFeatureCount()          self.numshapes = self.ogrlayer.GetFeatureCount()
165          self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()          self.shapetype = self.ogrlayer.GetLayerDefn().GetGeomType()
         extent = self.ogrlayer.GetExtent()  
166    
167            extent = self.ogrlayer.GetExtent()
168          if extent:          if extent:
169              self.bbox = [extent[0], extent[2], extent[1], extent[3]]              self.bbox = [extent[0], extent[2], extent[1], extent[3]]
170          else:          else:
171              self.bbox = None              self.bbox = None
172    
173          self.shapetype = ogrlib_shapetypes[self.shapetype]          if self.shapetype is not ogr.wkbUnknown:
174                self.shapetype = ogrlib_shapetypes[self.shapetype]
175            #else:
176                # this should be ogr.wkbUnknown, but Thuban does not know how
177                # to handle an unknown shapetype (e.g. Session Tree)
178                #self.shapetype = ogrlib_shapetypes[ogr.wkbPoint]
179    
180      def OGRLayer(self):      def OGRLayer(self):
181          """Return the OGRLayer object"""          """Return the OGRLayer object"""
# Line 195  class OGRShapeStore: Line 223  class OGRShapeStore:
223          ogrlayer = self.ogrlayer          ogrlayer = self.ogrlayer
224    
225          left, bottom, right, top = bbox          left, bottom, right, top = bbox
226            print "features in bbox: "
227            print ('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'
228                                     %(left, bottom, left, top, right, top,
229                                      right, bottom, left, bottom))
230          # create a geometry which can be passed to the layer as spatial filter          # create a geometry which can be passed to the layer as spatial filter
231          bboxpolygon = ogr.CreateGeometryFromWkt(          bboxpolygon = ogr.CreateGeometryFromWkt(
232                        ('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'                        ('Polygon((%s %s, %s %s, %s %s,%s %s, %s %s))'
# Line 206  class OGRShapeStore: Line 237  class OGRShapeStore:
237              bboxpolygon.AssignSpatialReference(ogrlayer.GetSpatialRef())              bboxpolygon.AssignSpatialReference(ogrlayer.GetSpatialRef())
238    
239          ogrlayer.ResetReading()          ogrlayer.ResetReading()
240            #ogrlayer.SetSpatialFilterRect(left, bottom, right, top)
241          ogrlayer.SetSpatialFilter(bboxpolygon)          ogrlayer.SetSpatialFilter(bboxpolygon)
242          numFeatures = ogrlayer.GetFeatureCount()          numFeatures = ogrlayer.GetFeatureCount()
243            print numFeatures
244          for feature in range(numFeatures):          for feature in range(numFeatures):
245              nextFeature = ogrlayer.GetNextFeature()              nextFeature = ogrlayer.GetNextFeature()
246              yield cls(ogrlayer, nextFeature.GetFID())              yield cls(ogrlayer, nextFeature.GetFID())
# Line 216  class OGRShapeStore: Line 249  class OGRShapeStore:
249    
250      def AllShapes(self):      def AllShapes(self):
251          """Return an iterable over the shapes in the shape store."""          """Return an iterable over the shapes in the shape store."""
252          for i in xrange(self.NumShapes()):          self.ogrlayer.ResetReading()
253              yield OGRShape(self.ogrlayer, i)          nextFeature = self.ogrlayer.GetNextFeature()
254            while nextFeature is not None:
255                yield OGRShape(self.ogrlayer, nextFeature.GetFID())
256                nextFeature = self.ogrlayer.GetNextFeature()
257    
258      def Shape(self, index):      def Shape(self, index):
259          """Return the shape with index index"""          """Return the shape with index index"""
# Line 241  class OGRTable: Line 277  class OGRTable:
277      """A Table for an ogr file      """A Table for an ogr file
278      """      """
279    
280      def __init__(self, ds, layer):      def __init__(self, ds, layer, id_column):
281          """Initialize the OGRTable.          """Initialize the OGRTable.
282    
283          ds should be an instance of OGRDatasource.          ds should be an instance of OGRDatasource.
# Line 251  class OGRTable: Line 287  class OGRTable:
287          self.datasource = ds          self.datasource = ds
288          self.layer = layer          self.layer = layer
289          self.tablename = layer.GetName()          self.tablename = layer.GetName()
290            self.id_column = id_column
291    
292          # Map column names and indices to column objects.          # Map column names and indices to column objects.
293          self.column_map = {}          self.column_map = {}
294    
295            # Map feature ids to ordinals.
296            self._map_ords_and_ids()
297    
298          self._fetch_table_information()          self._fetch_table_information()
299    
300      def _fetch_table_information(self):      def _fetch_table_information(self):
# Line 275  class OGRTable: Line 315  class OGRTable:
315              self.column_map[col.name] = col              self.column_map[col.name] = col
316              self.column_map[col.index] = col              self.column_map[col.index] = col
317    
318        def _map_ords_and_ids(self):
319            self.ordinals = {}
320            self.ids = {}
321    
322            lay = self.datasource.ExecuteSQL(
323                    "SELECT %s from %s"
324                    %(self.id_column, self.tablename))
325            lay.ResetReading()
326            nextFeature = lay.GetNextFeature()
327            ord = 0
328            while nextFeature is not None:
329                id = nextFeature.GetFID()
330                self.ordinals[ord] = id
331                self.ids[id] = ord
332                nextFeature = lay.GetNextFeature()
333                ord = ord + 1
334            self.datasource.ReleaseResultSet(lay)
335    
336      def TableName(self):      def TableName(self):
337          """Return the name of the table, which is the name of the layer"""          """Return the name of the table, which is the name of the layer"""
338          return self.tablename          return self.tablename
# Line 282  class OGRTable: Line 340  class OGRTable:
340      def Title(self):      def Title(self):
341          """Return the title of the table.          """Return the title of the table.
342    
343          The title is currently fixed and equal to the tablename          The title is currently
344          """          """
345          return self.tablename          return self.tablename
346    
# Line 316  class OGRTable: Line 374  class OGRTable:
374    
375      def RowIdToOrdinal(self, gid):      def RowIdToOrdinal(self, gid):
376          """Return the row ordinal given its id"""          """Return the row ordinal given its id"""
377          return self.layer.GetFeature(gid).GetFID()          if gid < 0:
378                return gid
379            else:
380                ord = self.ids[gid]
381                return ord
382    #        lay = self.datasource.ExecuteSQL(
383     #               "SELECT COUNT(%s) From %s where FID < %s"
384      #              %(self.id_column, self.tablename, gid))
385       #     ord = lay.GetFeature(0).GetField(0)
386        #    self.datasource.ReleaseResultSet(lay)
387     #       return ord
388    
389      def RowOrdinalToId(self, num):      def RowOrdinalToId(self, num):
390          """Return the rowid for given its ordinal"""          """Return the rowid for given its ordinal"""
391          return self.layer.GetFeature(num).GetFID()  #        lay = self.datasource.ExecuteSQL(
392     #               "SELECT FID From %s"
393      #              %(self.tablename))
394       #     for i in range(num):
395        #        lay.GetNextFeature()
396         #   id = lay.GetNextFeature().GetField(0)
397          #  self.datasource.ReleaseResultSet(lay)
398            if num >= 0:
399                id = self.ordinals[num]
400                return id
401            else:
402                return num
403    
404      def ReadRowAsDict(self, row, row_is_ordinal = 0):      def ReadRowAsDict(self, row, row_is_ordinal = 0):
405          """Return a dictionary which contains all the fields."""          """Return a dictionary which contains all the fields."""
406            if row_is_ordinal == 1:
407                rowId = self.RowOrdinalToId(row)
408            else:
409                rowId = row
410          layerdef = self.layer.GetLayerDefn()          layerdef = self.layer.GetLayerDefn()
411          feature = self.layer.GetFeature(row)          feature = self.layer.GetFeature(rowId)
412          result = {}          result = {}
413          for i in range(feature.GetFieldCount()):          for i in range(len(self.columns)):
414              fielddef = layerdef.GetFieldDefn(i)              fielddef = layerdef.GetFieldDefn(i)
415              result[fielddef.GetName()] = feature.GetField(i)              if feature is not None:
416                    result[self.columns[i].name] = feature.GetField(i)
417                else:
418                    result[fielddef.GetName()] = None
419          return result          return result
420    
421      def ReadValue(self, row, col, row_is_ordinal = 0):      def ReadValue(self, row, col, row_is_ordinal = 0):
# Line 383  class OGRTable: Line 469  class OGRTable:
469          else:          else:
470              right_template = right              right_template = right
471    
472          query = ("SELECT FID FROM %s WHERE '%s' %s %s ORDER BY FID"          query = ("SELECT %s FROM %s WHERE '%s' %s %s ORDER BY FID"
473                  % (self.tablename,left.name, comparison, right_template))                  % (self.id_column, self.tablename,left.name, comparison,
474                       right_template))
475    
476          lay = self.datasource.ExecuteSQL(query)          lay = self.datasource.ExecuteSQL(query)
477          result = []          result = []
# Line 393  class OGRTable: Line 480  class OGRTable:
480              if feature is None:              if feature is None:
481                  break                  break
482              result.append(feature.GetField(0))              result.append(feature.GetField(0))
483          self.datasource.ReleaseResultSet(lay)          if lay is not None:
484                self.datasource.ReleaseResultSet(lay)
485          return result          return result
486    
487    

Legend:
Removed from v.2493  
changed lines
  Added in v.2549

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26