app/django/contrib/gis/tests/test_gdal_geom.py
changeset 323 ff1a9aa48cfd
equal deleted inserted replaced
322:6641e941ef1e 323:ff1a9aa48cfd
       
     1 import unittest
       
     2 from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, \
       
     3     OGRException, OGRIndexError, SpatialReference, CoordTransform, \
       
     4     gdal_version
       
     5 from django.contrib.gis.tests.geometries import *
       
     6 
       
     7 class OGRGeomTest(unittest.TestCase):
       
     8     "This tests the OGR Geometry."
       
     9 
       
    10     def test00_geomtype(self):
       
    11         "Testing OGRGeomType object."
       
    12 
       
    13         # OGRGeomType should initialize on all these inputs.
       
    14         try:
       
    15             g = OGRGeomType(1)
       
    16             g = OGRGeomType(7)
       
    17             g = OGRGeomType('point')
       
    18             g = OGRGeomType('GeometrycollectioN')
       
    19             g = OGRGeomType('LINearrING')
       
    20             g = OGRGeomType('Unknown')
       
    21         except:
       
    22             self.fail('Could not create an OGRGeomType object!')
       
    23 
       
    24         # Should throw TypeError on this input
       
    25         self.assertRaises(TypeError, OGRGeomType.__init__, 23)
       
    26         self.assertRaises(TypeError, OGRGeomType.__init__, 'fooD')
       
    27         self.assertRaises(TypeError, OGRGeomType.__init__, 9)
       
    28 
       
    29         # Equivalence can take strings, ints, and other OGRGeomTypes
       
    30         self.assertEqual(True, OGRGeomType(1) == OGRGeomType(1))
       
    31         self.assertEqual(True, OGRGeomType(7) == 'GeometryCollection')
       
    32         self.assertEqual(True, OGRGeomType('point') == 'POINT')
       
    33         self.assertEqual(False, OGRGeomType('point') == 2)
       
    34         self.assertEqual(True, OGRGeomType('unknown') == 0)
       
    35         self.assertEqual(True, OGRGeomType(6) == 'MULtiPolyGON')
       
    36         self.assertEqual(False, OGRGeomType(1) != OGRGeomType('point'))
       
    37         self.assertEqual(True, OGRGeomType('POINT') != OGRGeomType(6))
       
    38 
       
    39         # Testing the Django field name equivalent property.
       
    40         self.assertEqual('PointField', OGRGeomType('Point').django)
       
    41         self.assertEqual(None, OGRGeomType('Unknown').django)
       
    42         self.assertEqual(None, OGRGeomType('none').django)
       
    43 
       
    44     def test01a_wkt(self):
       
    45         "Testing WKT output."
       
    46         for g in wkt_out:
       
    47             geom = OGRGeometry(g.wkt)
       
    48             self.assertEqual(g.wkt, geom.wkt)
       
    49 
       
    50     def test01b_gml(self):
       
    51         "Testing GML output."
       
    52         for g in wkt_out:
       
    53             geom = OGRGeometry(g.wkt)
       
    54             self.assertEqual(g.gml, geom.gml)
       
    55 
       
    56     def test01c_hex(self):
       
    57         "Testing HEX input/output."
       
    58         for g in hex_wkt:
       
    59             geom1 = OGRGeometry(g.wkt)
       
    60             self.assertEqual(g.hex, geom1.hex)
       
    61             # Constructing w/HEX
       
    62             geom2 = OGRGeometry(g.hex)
       
    63             self.assertEqual(geom1, geom2)
       
    64 
       
    65     def test01d_wkb(self):
       
    66         "Testing WKB input/output."
       
    67         from binascii import b2a_hex
       
    68         for g in hex_wkt:
       
    69             geom1 = OGRGeometry(g.wkt)
       
    70             wkb = geom1.wkb
       
    71             self.assertEqual(b2a_hex(wkb).upper(), g.hex)
       
    72             # Constructing w/WKB.
       
    73             geom2 = OGRGeometry(wkb)
       
    74             self.assertEqual(geom1, geom2)
       
    75 
       
    76     def test01e_json(self):
       
    77         "Testing GeoJSON input/output."
       
    78         from django.contrib.gis.gdal.prototypes.geom import GEOJSON
       
    79         if not GEOJSON: return
       
    80         for g in json_geoms:
       
    81             geom = OGRGeometry(g.wkt)
       
    82             self.assertEqual(g.json, geom.json)
       
    83             self.assertEqual(g.json, geom.geojson)
       
    84             self.assertEqual(OGRGeometry(g.wkt), OGRGeometry(geom.json))
       
    85 
       
    86     def test02_points(self):
       
    87         "Testing Point objects."
       
    88 
       
    89         prev = OGRGeometry('POINT(0 0)')
       
    90         for p in points:
       
    91             if not hasattr(p, 'z'): # No 3D
       
    92                 pnt = OGRGeometry(p.wkt)
       
    93                 self.assertEqual(1, pnt.geom_type)
       
    94                 self.assertEqual('POINT', pnt.geom_name)
       
    95                 self.assertEqual(p.x, pnt.x)
       
    96                 self.assertEqual(p.y, pnt.y)
       
    97                 self.assertEqual((p.x, p.y), pnt.tuple)
       
    98 
       
    99     def test03_multipoints(self):
       
   100         "Testing MultiPoint objects."
       
   101 
       
   102         for mp in multipoints:
       
   103             mgeom1 = OGRGeometry(mp.wkt) # First one from WKT
       
   104             self.assertEqual(4, mgeom1.geom_type)
       
   105             self.assertEqual('MULTIPOINT', mgeom1.geom_name)
       
   106             mgeom2 = OGRGeometry('MULTIPOINT') # Creating empty multipoint
       
   107             mgeom3 = OGRGeometry('MULTIPOINT')
       
   108             for g in mgeom1:
       
   109                 mgeom2.add(g) # adding each point from the multipoints
       
   110                 mgeom3.add(g.wkt) # should take WKT as well
       
   111             self.assertEqual(mgeom1, mgeom2) # they should equal
       
   112             self.assertEqual(mgeom1, mgeom3)
       
   113             self.assertEqual(mp.points, mgeom2.tuple)
       
   114             self.assertEqual(mp.n_p, mgeom2.point_count)
       
   115                                                                             
       
   116     def test04_linestring(self):
       
   117         "Testing LineString objects."
       
   118         prev = OGRGeometry('POINT(0 0)')
       
   119         for ls in linestrings:
       
   120             linestr = OGRGeometry(ls.wkt)
       
   121             self.assertEqual(2, linestr.geom_type)
       
   122             self.assertEqual('LINESTRING', linestr.geom_name)
       
   123             self.assertEqual(ls.n_p, linestr.point_count)
       
   124             self.assertEqual(ls.tup, linestr.tuple)
       
   125             self.assertEqual(True, linestr == OGRGeometry(ls.wkt))
       
   126             self.assertEqual(True, linestr != prev)
       
   127             self.assertRaises(OGRIndexError, linestr.__getitem__, len(linestr))
       
   128             prev = linestr
       
   129 
       
   130             # Testing the x, y properties.
       
   131             x = [tmpx for tmpx, tmpy in ls.tup]
       
   132             y = [tmpy for tmpx, tmpy in ls.tup]
       
   133             self.assertEqual(x, linestr.x)
       
   134             self.assertEqual(y, linestr.y)
       
   135 
       
   136     def test05_multilinestring(self):
       
   137         "Testing MultiLineString objects."
       
   138         prev = OGRGeometry('POINT(0 0)')
       
   139         for mls in multilinestrings:
       
   140             mlinestr = OGRGeometry(mls.wkt)
       
   141             self.assertEqual(5, mlinestr.geom_type)
       
   142             self.assertEqual('MULTILINESTRING', mlinestr.geom_name)
       
   143             self.assertEqual(mls.n_p, mlinestr.point_count)
       
   144             self.assertEqual(mls.tup, mlinestr.tuple)
       
   145             self.assertEqual(True, mlinestr == OGRGeometry(mls.wkt))
       
   146             self.assertEqual(True, mlinestr != prev)
       
   147             prev = mlinestr
       
   148             for ls in mlinestr:
       
   149                 self.assertEqual(2, ls.geom_type)
       
   150                 self.assertEqual('LINESTRING', ls.geom_name)
       
   151             self.assertRaises(OGRIndexError, mlinestr.__getitem__, len(mlinestr)) 
       
   152 
       
   153     def test06_linearring(self):
       
   154         "Testing LinearRing objects."
       
   155         prev = OGRGeometry('POINT(0 0)')
       
   156         for rr in linearrings:
       
   157             lr = OGRGeometry(rr.wkt)
       
   158             #self.assertEqual(101, lr.geom_type.num)
       
   159             self.assertEqual('LINEARRING', lr.geom_name)
       
   160             self.assertEqual(rr.n_p, len(lr))
       
   161             self.assertEqual(True, lr == OGRGeometry(rr.wkt))
       
   162             self.assertEqual(True, lr != prev)
       
   163             prev = lr
       
   164 
       
   165     def test07a_polygons(self):
       
   166         "Testing Polygon objects."
       
   167         prev = OGRGeometry('POINT(0 0)')
       
   168         for p in polygons:
       
   169             poly = OGRGeometry(p.wkt)
       
   170             self.assertEqual(3, poly.geom_type)
       
   171             self.assertEqual('POLYGON', poly.geom_name)
       
   172             self.assertEqual(p.n_p, poly.point_count)
       
   173             self.assertEqual(p.n_i + 1, len(poly))
       
   174 
       
   175             # Testing area & centroid.
       
   176             self.assertAlmostEqual(p.area, poly.area, 9)
       
   177             x, y = poly.centroid.tuple
       
   178             self.assertAlmostEqual(p.centroid[0], x, 9)
       
   179             self.assertAlmostEqual(p.centroid[1], y, 9)
       
   180 
       
   181             # Testing equivalence
       
   182             self.assertEqual(True, poly == OGRGeometry(p.wkt))
       
   183             self.assertEqual(True, poly != prev)
       
   184             
       
   185             if p.ext_ring_cs:
       
   186                 ring = poly[0]
       
   187                 self.assertEqual(p.ext_ring_cs, ring.tuple)
       
   188                 self.assertEqual(p.ext_ring_cs, poly[0].tuple)
       
   189                 self.assertEqual(len(p.ext_ring_cs), ring.point_count)
       
   190             
       
   191             for r in poly:
       
   192                 self.assertEqual('LINEARRING', r.geom_name)
       
   193 
       
   194     def test07b_closepolygons(self):
       
   195         "Testing closing Polygon objects."
       
   196         # Both rings in this geometry are not closed.
       
   197         poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
       
   198         self.assertEqual(8, poly.point_count)
       
   199         print "\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n"
       
   200         try:
       
   201             c = poly.centroid
       
   202         except OGRException:
       
   203             # Should raise an OGR exception, rings are not closed
       
   204             pass
       
   205         else:
       
   206             self.fail('Should have raised an OGRException!')
       
   207         print "\nEND - expecting IllegalArgumentException; safe to ignore.\n"
       
   208 
       
   209         # Closing the rings -- doesn't work on GDAL versions 1.4.1 and below:
       
   210         # http://trac.osgeo.org/gdal/ticket/1673
       
   211         major, minor1, minor2 = gdal_version().split('.')
       
   212         if major == '1':
       
   213             iminor1 = int(minor1)
       
   214             if iminor1 < 4 or (iminor1 == 4 and minor2.startswith('1')): return
       
   215         poly.close_rings()
       
   216         self.assertEqual(10, poly.point_count) # Two closing points should've been added
       
   217         self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid)
       
   218 
       
   219     def test08_multipolygons(self):
       
   220         "Testing MultiPolygon objects."
       
   221         prev = OGRGeometry('POINT(0 0)')
       
   222         for mp in multipolygons:
       
   223             mpoly = OGRGeometry(mp.wkt)
       
   224             self.assertEqual(6, mpoly.geom_type)
       
   225             self.assertEqual('MULTIPOLYGON', mpoly.geom_name)
       
   226             if mp.valid:
       
   227                 self.assertEqual(mp.n_p, mpoly.point_count)
       
   228                 self.assertEqual(mp.num_geom, len(mpoly))
       
   229                 self.assertRaises(OGRIndexError, mpoly.__getitem__, len(mpoly))
       
   230                 for p in mpoly:
       
   231                     self.assertEqual('POLYGON', p.geom_name)
       
   232                     self.assertEqual(3, p.geom_type)
       
   233             self.assertEqual(mpoly.wkt, OGRGeometry(mp.wkt).wkt)
       
   234 
       
   235     def test09a_srs(self):
       
   236         "Testing OGR Geometries with Spatial Reference objects."
       
   237         for mp in multipolygons:
       
   238             # Creating a geometry w/spatial reference
       
   239             sr = SpatialReference('WGS84')
       
   240             mpoly = OGRGeometry(mp.wkt, sr)
       
   241             self.assertEqual(sr.wkt, mpoly.srs.wkt)
       
   242           
       
   243             # Ensuring that SRS is propagated to clones.
       
   244             klone = mpoly.clone()
       
   245             self.assertEqual(sr.wkt, klone.srs.wkt)
       
   246   
       
   247             # Ensuring all children geometries (polygons and their rings) all
       
   248             # return the assigned spatial reference as well.
       
   249             for poly in mpoly:
       
   250                 self.assertEqual(sr.wkt, poly.srs.wkt)
       
   251                 for ring in poly:
       
   252                     self.assertEqual(sr.wkt, ring.srs.wkt)
       
   253 
       
   254             # Ensuring SRS propagate in topological ops.
       
   255             a, b = topology_geoms[0]
       
   256             a, b = OGRGeometry(a.wkt, sr), OGRGeometry(b.wkt, sr)
       
   257             diff = a.difference(b)
       
   258             union = a.union(b)
       
   259             self.assertEqual(sr.wkt, diff.srs.wkt)
       
   260             self.assertEqual(sr.srid, union.srs.srid)
       
   261 
       
   262             # Instantiating w/an integer SRID
       
   263             mpoly = OGRGeometry(mp.wkt, 4326)
       
   264             self.assertEqual(4326, mpoly.srid)
       
   265             mpoly.srs = SpatialReference(4269)
       
   266             self.assertEqual(4269, mpoly.srid)
       
   267             self.assertEqual('NAD83', mpoly.srs.name)
       
   268           
       
   269             # Incrementing through the multipolyogn after the spatial reference
       
   270             # has been re-assigned.
       
   271             for poly in mpoly:
       
   272                 self.assertEqual(mpoly.srs.wkt, poly.srs.wkt)
       
   273                 poly.srs = 32140
       
   274                 for ring in poly:
       
   275                     # Changing each ring in the polygon
       
   276                     self.assertEqual(32140, ring.srs.srid)
       
   277                     self.assertEqual('NAD83 / Texas South Central', ring.srs.name)
       
   278                     ring.srs = str(SpatialReference(4326)) # back to WGS84
       
   279                     self.assertEqual(4326, ring.srs.srid)
       
   280 
       
   281                     # Using the `srid` property.
       
   282                     ring.srid = 4322
       
   283                     self.assertEqual('WGS 72', ring.srs.name)
       
   284                     self.assertEqual(4322, ring.srid)
       
   285 
       
   286     def test09b_srs_transform(self):
       
   287         "Testing transform()."
       
   288         orig = OGRGeometry('POINT (-104.609 38.255)', 4326)
       
   289         trans = OGRGeometry('POINT (992385.4472045 481455.4944650)', 2774)
       
   290 
       
   291         # Using an srid, a SpatialReference object, and a CoordTransform object
       
   292         # or transformations.
       
   293         t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
       
   294         t1.transform(trans.srid)
       
   295         t2.transform(SpatialReference('EPSG:2774'))
       
   296         ct = CoordTransform(SpatialReference('WGS84'), SpatialReference(2774))
       
   297         t3.transform(ct)
       
   298 
       
   299         # Testing use of the `clone` keyword.
       
   300         k1 = orig.clone()
       
   301         k2 = k1.transform(trans.srid, clone=True)
       
   302         self.assertEqual(k1, orig)
       
   303         self.assertNotEqual(k1, k2)
       
   304 
       
   305         prec = 3
       
   306         for p in (t1, t2, t3, k2):
       
   307             self.assertAlmostEqual(trans.x, p.x, prec)
       
   308             self.assertAlmostEqual(trans.y, p.y, prec)
       
   309 
       
   310     def test10_difference(self):
       
   311         "Testing difference()."
       
   312         for i in xrange(len(topology_geoms)):
       
   313             g_tup = topology_geoms[i]
       
   314             a = OGRGeometry(g_tup[0].wkt)
       
   315             b = OGRGeometry(g_tup[1].wkt)
       
   316             d1 = OGRGeometry(diff_geoms[i].wkt)
       
   317             d2 = a.difference(b)
       
   318             self.assertEqual(d1, d2)
       
   319             self.assertEqual(d1, a - b) # __sub__ is difference operator
       
   320             a -= b # testing __isub__
       
   321             self.assertEqual(d1, a)
       
   322 
       
   323     def test11_intersection(self):
       
   324         "Testing intersects() and intersection()."
       
   325         for i in xrange(len(topology_geoms)):
       
   326             g_tup = topology_geoms[i]
       
   327             a = OGRGeometry(g_tup[0].wkt)
       
   328             b = OGRGeometry(g_tup[1].wkt)
       
   329             i1 = OGRGeometry(intersect_geoms[i].wkt)
       
   330             self.assertEqual(True, a.intersects(b))
       
   331             i2 = a.intersection(b)
       
   332             self.assertEqual(i1, i2)
       
   333             self.assertEqual(i1, a & b) # __and__ is intersection operator
       
   334             a &= b # testing __iand__
       
   335             self.assertEqual(i1, a)
       
   336 
       
   337     def test12_symdifference(self):
       
   338         "Testing sym_difference()."
       
   339         for i in xrange(len(topology_geoms)):
       
   340             g_tup = topology_geoms[i]
       
   341             a = OGRGeometry(g_tup[0].wkt)
       
   342             b = OGRGeometry(g_tup[1].wkt)
       
   343             d1 = OGRGeometry(sdiff_geoms[i].wkt)
       
   344             d2 = a.sym_difference(b)
       
   345             self.assertEqual(d1, d2)
       
   346             self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
       
   347             a ^= b # testing __ixor__
       
   348             self.assertEqual(d1, a)
       
   349             
       
   350     def test13_union(self):
       
   351         "Testing union()."
       
   352         for i in xrange(len(topology_geoms)):
       
   353             g_tup = topology_geoms[i]
       
   354             a = OGRGeometry(g_tup[0].wkt)
       
   355             b = OGRGeometry(g_tup[1].wkt)
       
   356             u1 = OGRGeometry(union_geoms[i].wkt)
       
   357             u2 = a.union(b)
       
   358             self.assertEqual(u1, u2)
       
   359             self.assertEqual(u1, a | b) # __or__ is union operator
       
   360             a |= b # testing __ior__
       
   361             self.assertEqual(u1, a)
       
   362 
       
   363     def test14_add(self):
       
   364         "Testing GeometryCollection.add()."
       
   365         # Can't insert a Point into a MultiPolygon.
       
   366         mp = OGRGeometry('MultiPolygon')
       
   367         pnt = OGRGeometry('POINT(5 23)')
       
   368         self.assertRaises(OGRException, mp.add, pnt)
       
   369 
       
   370         # GeometryCollection.add may take an OGRGeometry (if another collection
       
   371         # of the same type all child geoms will be added individually) or WKT.
       
   372         for mp in multipolygons:
       
   373             mpoly = OGRGeometry(mp.wkt)
       
   374             mp1 = OGRGeometry('MultiPolygon')
       
   375             mp2 = OGRGeometry('MultiPolygon')
       
   376             mp3 = OGRGeometry('MultiPolygon')
       
   377 
       
   378             for poly in mpoly:
       
   379                 mp1.add(poly) # Adding a geometry at a time
       
   380                 mp2.add(poly.wkt) # Adding WKT
       
   381             mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once.
       
   382             for tmp in (mp1, mp2, mp3): self.assertEqual(mpoly, tmp)
       
   383 
       
   384     def test15_extent(self):
       
   385         "Testing `extent` property."
       
   386         # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
       
   387         mp = OGRGeometry('MULTIPOINT(5 23, 0 0, 10 50)')
       
   388         self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
       
   389         # Testing on the 'real world' Polygon.
       
   390         poly = OGRGeometry(polygons[3].wkt)
       
   391         ring = poly.shell
       
   392         x, y = ring.x, ring.y
       
   393         xmin, ymin = min(x), min(y)
       
   394         xmax, ymax = max(x), max(y)
       
   395         self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
       
   396 
       
   397 def suite():
       
   398     s = unittest.TestSuite()
       
   399     s.addTest(unittest.makeSuite(OGRGeomTest))
       
   400     return s
       
   401 
       
   402 def run(verbosity=2):
       
   403     unittest.TextTestRunner(verbosity=verbosity).run(suite())