django/contrib/gis/geos/tests/test_geos.py
author Justin Bronn <jbronn@geodjango.org>
Thu Mar 19 13:08:50 2009 -0500 (3 years ago)
branchtrunk
changeset 362 87b34dce202d
parent 354 3fcbf6e3e599
child 435 d75ff359e306
permissions -rw-r--r--
Added `merged` property to LineString & MultiLineString, which returns the output of the GEOS line merging operation.
     1 import random, unittest, sys
     2 from ctypes import ArgumentError
     3 from django.contrib.gis.geos import *
     4 from django.contrib.gis.geos.base import gdal, numpy
     5 from django.contrib.gis.tests.geometries import *
     6 
     7 class GEOSTest(unittest.TestCase):
     8 
     9     @property
    10     def null_srid(self):
    11         """
    12         Returns the proper null SRID depending on the GEOS version.
    13         See the comments in `test15_srid` for more details.
    14         """
    15         info = geos_version_info()
    16         if info['version'] == '3.0.0' and info['release_candidate']:
    17             return -1
    18         else:
    19             return None
    20 
    21     def test01a_wkt(self):
    22         "Testing WKT output."
    23         for g in wkt_out:
    24             geom = fromstr(g.wkt)
    25             self.assertEqual(g.ewkt, geom.wkt)
    26 
    27     def test01b_hex(self):
    28         "Testing HEX output."
    29         for g in hex_wkt:
    30             geom = fromstr(g.wkt)
    31             self.assertEqual(g.hex, geom.hex)
    32 
    33     def test01c_kml(self):
    34         "Testing KML output."
    35         for tg in wkt_out:
    36             geom = fromstr(tg.wkt)
    37             kml = getattr(tg, 'kml', False)
    38             if kml: self.assertEqual(kml, geom.kml)
    39 
    40     def test01d_errors(self):
    41         "Testing the Error handlers."
    42         # string-based
    43         print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n"
    44         for err in errors:
    45             try:
    46                 g = fromstr(err.wkt)
    47             except (GEOSException, ValueError):
    48                 pass
    49 
    50         # Bad WKB
    51         self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
    52 
    53         print "\nEND - expecting GEOS_ERROR; safe to ignore.\n"
    54 
    55         class NotAGeometry(object):
    56             pass
    57 
    58         # Some other object
    59         self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
    60         # None
    61         self.assertRaises(TypeError, GEOSGeometry, None)
    62 
    63     def test01e_wkb(self):
    64         "Testing WKB output."
    65         from binascii import b2a_hex
    66         for g in hex_wkt:
    67             geom = fromstr(g.wkt)
    68             wkb = geom.wkb
    69             self.assertEqual(b2a_hex(wkb).upper(), g.hex)
    70 
    71     def test01f_create_hex(self):
    72         "Testing creation from HEX."
    73         for g in hex_wkt:
    74             geom_h = GEOSGeometry(g.hex)
    75             # we need to do this so decimal places get normalised
    76             geom_t = fromstr(g.wkt)
    77             self.assertEqual(geom_t.wkt, geom_h.wkt)
    78 
    79     def test01g_create_wkb(self):
    80         "Testing creation from WKB."
    81         from binascii import a2b_hex
    82         for g in hex_wkt:
    83             wkb = buffer(a2b_hex(g.hex))
    84             geom_h = GEOSGeometry(wkb)
    85             # we need to do this so decimal places get normalised
    86             geom_t = fromstr(g.wkt)
    87             self.assertEqual(geom_t.wkt, geom_h.wkt)
    88 
    89     def test01h_ewkt(self):
    90         "Testing EWKT."
    91         srid = 32140
    92         for p in polygons:
    93             ewkt = 'SRID=%d;%s' % (srid, p.wkt)
    94             poly = fromstr(ewkt)
    95             self.assertEqual(srid, poly.srid)
    96             self.assertEqual(srid, poly.shell.srid)
    97             self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
    98 
    99     def test01i_json(self):
   100         "Testing GeoJSON input/output (via GDAL)."
   101         if not gdal or not gdal.GEOJSON: return
   102         for g in json_geoms:
   103             geom = GEOSGeometry(g.wkt)
   104             if not hasattr(g, 'not_equal'):
   105                 self.assertEqual(g.json, geom.json)
   106                 self.assertEqual(g.json, geom.geojson)
   107             self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
   108 
   109     def test01k_fromfile(self):
   110         "Testing the fromfile() factory."
   111         from StringIO import StringIO
   112         ref_pnt = GEOSGeometry('POINT(5 23)')
   113 
   114         wkt_f = StringIO()
   115         wkt_f.write(ref_pnt.wkt)
   116         wkb_f = StringIO()
   117         wkb_f.write(str(ref_pnt.wkb))
   118 
   119         # Other tests use `fromfile()` on string filenames so those
   120         # aren't tested here.
   121         for fh in (wkt_f, wkb_f):
   122             fh.seek(0)
   123             pnt = fromfile(fh)
   124             self.assertEqual(ref_pnt, pnt)
   125 
   126     def test01k_eq(self):
   127         "Testing equivalence."
   128         p = fromstr('POINT(5 23)')
   129         self.assertEqual(p, p.wkt)
   130         self.assertNotEqual(p, 'foo')
   131         ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
   132         self.assertEqual(ls, ls.wkt)
   133         self.assertNotEqual(p, 'bar')
   134         # Error shouldn't be raise on equivalence testing with
   135         # an invalid type.
   136         for g in (p, ls):
   137             self.assertNotEqual(g, None)
   138             self.assertNotEqual(g, {'foo' : 'bar'})
   139             self.assertNotEqual(g, False)
   140 
   141     def test02a_points(self):
   142         "Testing Point objects."
   143         prev = fromstr('POINT(0 0)')
   144         for p in points:
   145             # Creating the point from the WKT
   146             pnt = fromstr(p.wkt)
   147             self.assertEqual(pnt.geom_type, 'Point')
   148             self.assertEqual(pnt.geom_typeid, 0)
   149             self.assertEqual(p.x, pnt.x)
   150             self.assertEqual(p.y, pnt.y)
   151             self.assertEqual(True, pnt == fromstr(p.wkt))
   152             self.assertEqual(False, pnt == prev)
   153 
   154             # Making sure that the point's X, Y components are what we expect
   155             self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
   156             self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
   157 
   158             # Testing the third dimension, and getting the tuple arguments
   159             if hasattr(p, 'z'):
   160                 self.assertEqual(True, pnt.hasz)
   161                 self.assertEqual(p.z, pnt.z)
   162                 self.assertEqual(p.z, pnt.tuple[2], 9)
   163                 tup_args = (p.x, p.y, p.z)
   164                 set_tup1 = (2.71, 3.14, 5.23)
   165                 set_tup2 = (5.23, 2.71, 3.14)
   166             else:
   167                 self.assertEqual(False, pnt.hasz)
   168                 self.assertEqual(None, pnt.z)
   169                 tup_args = (p.x, p.y)
   170                 set_tup1 = (2.71, 3.14)
   171                 set_tup2 = (3.14, 2.71)
   172 
   173             # Centroid operation on point should be point itself
   174             self.assertEqual(p.centroid, pnt.centroid.tuple)
   175 
   176             # Now testing the different constructors
   177             pnt2 = Point(tup_args)  # e.g., Point((1, 2))
   178             pnt3 = Point(*tup_args) # e.g., Point(1, 2)
   179             self.assertEqual(True, pnt == pnt2)
   180             self.assertEqual(True, pnt == pnt3)
   181 
   182             # Now testing setting the x and y
   183             pnt.y = 3.14
   184             pnt.x = 2.71
   185             self.assertEqual(3.14, pnt.y)
   186             self.assertEqual(2.71, pnt.x)
   187 
   188             # Setting via the tuple/coords property
   189             pnt.tuple = set_tup1
   190             self.assertEqual(set_tup1, pnt.tuple)
   191             pnt.coords = set_tup2
   192             self.assertEqual(set_tup2, pnt.coords)
   193 
   194             prev = pnt # setting the previous geometry
   195 
   196     def test02b_multipoints(self):
   197         "Testing MultiPoint objects."
   198         for mp in multipoints:
   199             mpnt = fromstr(mp.wkt)
   200             self.assertEqual(mpnt.geom_type, 'MultiPoint')
   201             self.assertEqual(mpnt.geom_typeid, 4)
   202 
   203             self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
   204             self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
   205 
   206             self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt))
   207             self.assertEqual(mp.centroid, mpnt.centroid.tuple)
   208             self.assertEqual(mp.points, tuple(m.tuple for m in mpnt))
   209             for p in mpnt:
   210                 self.assertEqual(p.geom_type, 'Point')
   211                 self.assertEqual(p.geom_typeid, 0)
   212                 self.assertEqual(p.empty, False)
   213                 self.assertEqual(p.valid, True)
   214 
   215     def test03a_linestring(self):
   216         "Testing LineString objects."
   217         prev = fromstr('POINT(0 0)')
   218         for l in linestrings:
   219             ls = fromstr(l.wkt)
   220             self.assertEqual(ls.geom_type, 'LineString')
   221             self.assertEqual(ls.geom_typeid, 1)
   222             self.assertEqual(ls.empty, False)
   223             self.assertEqual(ls.ring, False)
   224             if hasattr(l, 'centroid'):
   225                 self.assertEqual(l.centroid, ls.centroid.tuple)
   226             if hasattr(l, 'tup'):
   227                 self.assertEqual(l.tup, ls.tuple)
   228 
   229             self.assertEqual(True, ls == fromstr(l.wkt))
   230             self.assertEqual(False, ls == prev)
   231             self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
   232             prev = ls
   233 
   234             # Creating a LineString from a tuple, list, and numpy array
   235             self.assertEqual(ls, LineString(ls.tuple))  # tuple
   236             self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
   237             self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
   238             self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
   239             if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
   240 
   241     def test03b_multilinestring(self):
   242         "Testing MultiLineString objects."
   243         prev = fromstr('POINT(0 0)')
   244         for l in multilinestrings:
   245             ml = fromstr(l.wkt)
   246             self.assertEqual(ml.geom_type, 'MultiLineString')
   247             self.assertEqual(ml.geom_typeid, 5)
   248 
   249             self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
   250             self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
   251 
   252             self.assertEqual(True, ml == fromstr(l.wkt))
   253             self.assertEqual(False, ml == prev)
   254             prev = ml
   255 
   256             for ls in ml:
   257                 self.assertEqual(ls.geom_type, 'LineString')
   258                 self.assertEqual(ls.geom_typeid, 1)
   259                 self.assertEqual(ls.empty, False)
   260 
   261             self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml))
   262             self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
   263             self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
   264 
   265     def test04_linearring(self):
   266         "Testing LinearRing objects."
   267         for rr in linearrings:
   268             lr = fromstr(rr.wkt)
   269             self.assertEqual(lr.geom_type, 'LinearRing')
   270             self.assertEqual(lr.geom_typeid, 2)
   271             self.assertEqual(rr.n_p, len(lr))
   272             self.assertEqual(True, lr.valid)
   273             self.assertEqual(False, lr.empty)
   274 
   275             # Creating a LinearRing from a tuple, list, and numpy array
   276             self.assertEqual(lr, LinearRing(lr.tuple))
   277             self.assertEqual(lr, LinearRing(*lr.tuple))
   278             self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
   279             if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
   280 
   281     def test05a_polygons(self):
   282         "Testing Polygon objects."
   283 
   284         # Testing `from_bbox` class method
   285         bbox = (-180, -90, 180, 90)
   286         p = Polygon.from_bbox( bbox )
   287         self.assertEqual(bbox, p.extent)
   288 
   289         prev = fromstr('POINT(0 0)')
   290         for p in polygons:
   291             # Creating the Polygon, testing its properties.
   292             poly = fromstr(p.wkt)
   293             self.assertEqual(poly.geom_type, 'Polygon')
   294             self.assertEqual(poly.geom_typeid, 3)
   295             self.assertEqual(poly.empty, False)
   296             self.assertEqual(poly.ring, False)
   297             self.assertEqual(p.n_i, poly.num_interior_rings)
   298             self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
   299             self.assertEqual(p.n_p, poly.num_points)
   300 
   301             # Area & Centroid
   302             self.assertAlmostEqual(p.area, poly.area, 9)
   303             self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
   304             self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
   305 
   306             # Testing the geometry equivalence
   307             self.assertEqual(True, poly == fromstr(p.wkt))
   308             self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
   309             self.assertEqual(True, poly != prev)
   310 
   311             # Testing the exterior ring
   312             ring = poly.exterior_ring
   313             self.assertEqual(ring.geom_type, 'LinearRing')
   314             self.assertEqual(ring.geom_typeid, 2)
   315             if p.ext_ring_cs:
   316                 self.assertEqual(p.ext_ring_cs, ring.tuple)
   317                 self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
   318 
   319             # Testing __getitem__ and __setitem__ on invalid indices
   320             self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
   321             self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False)
   322             self.assertRaises(GEOSIndexError, poly.__getitem__, -1 * len(poly) - 1)
   323 
   324             # Testing __iter__
   325             for r in poly:
   326                 self.assertEqual(r.geom_type, 'LinearRing')
   327                 self.assertEqual(r.geom_typeid, 2)
   328 
   329             # Testing polygon construction.
   330             self.assertRaises(TypeError, Polygon.__init__, 0, [1, 2, 3])
   331             self.assertRaises(TypeError, Polygon.__init__, 'foo')
   332 
   333             # Polygon(shell, (hole1, ... holeN))
   334             rings = tuple(r for r in poly)
   335             self.assertEqual(poly, Polygon(rings[0], rings[1:]))
   336 
   337             # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
   338             ring_tuples = tuple(r.tuple for r in poly)
   339             self.assertEqual(poly, Polygon(*ring_tuples))
   340 
   341             # Constructing with tuples of LinearRings.
   342             self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
   343             self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)
   344 
   345     def test05b_multipolygons(self):
   346         "Testing MultiPolygon objects."
   347         print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n"
   348         prev = fromstr('POINT (0 0)')
   349         for mp in multipolygons:
   350             mpoly = fromstr(mp.wkt)
   351             self.assertEqual(mpoly.geom_type, 'MultiPolygon')
   352             self.assertEqual(mpoly.geom_typeid, 6)
   353             self.assertEqual(mp.valid, mpoly.valid)
   354 
   355             if mp.valid:
   356                 self.assertEqual(mp.num_geom, mpoly.num_geom)
   357                 self.assertEqual(mp.n_p, mpoly.num_coords)
   358                 self.assertEqual(mp.num_geom, len(mpoly))
   359                 self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
   360                 for p in mpoly:
   361                     self.assertEqual(p.geom_type, 'Polygon')
   362                     self.assertEqual(p.geom_typeid, 3)
   363                     self.assertEqual(p.valid, True)
   364                 self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
   365 
   366         print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"
   367 
   368     def test06a_memory_hijinks(self):
   369         "Testing Geometry __del__() on rings and polygons."
   370         #### Memory issues with rings and polygons
   371 
   372         # These tests are needed to ensure sanity with writable geometries.
   373 
   374         # Getting a polygon with interior rings, and pulling out the interior rings
   375         poly = fromstr(polygons[1].wkt)
   376         ring1 = poly[0]
   377         ring2 = poly[1]
   378 
   379         # These deletes should be 'harmless' since they are done on child geometries
   380         del ring1
   381         del ring2
   382         ring1 = poly[0]
   383         ring2 = poly[1]
   384 
   385         # Deleting the polygon
   386         del poly
   387 
   388         # Access to these rings is OK since they are clones.
   389         s1, s2 = str(ring1), str(ring2)
   390 
   391         # The previous hijinks tests are now moot because only clones are
   392         # now used =)
   393 
   394     def test08_coord_seq(self):
   395         "Testing Coordinate Sequence objects."
   396         for p in polygons:
   397             if p.ext_ring_cs:
   398                 # Constructing the polygon and getting the coordinate sequence
   399                 poly = fromstr(p.wkt)
   400                 cs = poly.exterior_ring.coord_seq
   401 
   402                 self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
   403                 self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
   404 
   405                 # Checks __getitem__ and __setitem__
   406                 for i in xrange(len(p.ext_ring_cs)):
   407                     c1 = p.ext_ring_cs[i] # Expected value
   408                     c2 = cs[i] # Value from coordseq
   409                     self.assertEqual(c1, c2)
   410 
   411                     # Constructing the test value to set the coordinate sequence with
   412                     if len(c1) == 2: tset = (5, 23)
   413                     else: tset = (5, 23, 8)
   414                     cs[i] = tset
   415 
   416                     # Making sure every set point matches what we expect
   417                     for j in range(len(tset)):
   418                         cs[i] = tset
   419                         self.assertEqual(tset[j], cs[i][j])
   420 
   421     def test09_relate_pattern(self):
   422         "Testing relate() and relate_pattern()."
   423         g = fromstr('POINT (0 0)')
   424         self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo')
   425         for i in xrange(len(relate_geoms)):
   426             g_tup = relate_geoms[i]
   427             a = fromstr(g_tup[0].wkt)
   428             b = fromstr(g_tup[1].wkt)
   429             pat = g_tup[2]
   430             result = g_tup[3]
   431             self.assertEqual(result, a.relate_pattern(b, pat))
   432             self.assertEqual(pat, a.relate(b))
   433 
   434     def test10_intersection(self):
   435         "Testing intersects() and intersection()."
   436         for i in xrange(len(topology_geoms)):
   437             g_tup = topology_geoms[i]
   438             a = fromstr(g_tup[0].wkt)
   439             b = fromstr(g_tup[1].wkt)
   440             i1 = fromstr(intersect_geoms[i].wkt)
   441             self.assertEqual(True, a.intersects(b))
   442             i2 = a.intersection(b)
   443             self.assertEqual(i1, i2)
   444             self.assertEqual(i1, a & b) # __and__ is intersection operator
   445             a &= b # testing __iand__
   446             self.assertEqual(i1, a)
   447 
   448     def test11_union(self):
   449         "Testing union()."
   450         for i in xrange(len(topology_geoms)):
   451             g_tup = topology_geoms[i]
   452             a = fromstr(g_tup[0].wkt)
   453             b = fromstr(g_tup[1].wkt)
   454             u1 = fromstr(union_geoms[i].wkt)
   455             u2 = a.union(b)
   456             self.assertEqual(u1, u2)
   457             self.assertEqual(u1, a | b) # __or__ is union operator
   458             a |= b # testing __ior__
   459             self.assertEqual(u1, a)
   460 
   461     def test12_difference(self):
   462         "Testing difference()."
   463         for i in xrange(len(topology_geoms)):
   464             g_tup = topology_geoms[i]
   465             a = fromstr(g_tup[0].wkt)
   466             b = fromstr(g_tup[1].wkt)
   467             d1 = fromstr(diff_geoms[i].wkt)
   468             d2 = a.difference(b)
   469             self.assertEqual(d1, d2)
   470             self.assertEqual(d1, a - b) # __sub__ is difference operator
   471             a -= b # testing __isub__
   472             self.assertEqual(d1, a)
   473 
   474     def test13_symdifference(self):
   475         "Testing sym_difference()."
   476         for i in xrange(len(topology_geoms)):
   477             g_tup = topology_geoms[i]
   478             a = fromstr(g_tup[0].wkt)
   479             b = fromstr(g_tup[1].wkt)
   480             d1 = fromstr(sdiff_geoms[i].wkt)
   481             d2 = a.sym_difference(b)
   482             self.assertEqual(d1, d2)
   483             self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
   484             a ^= b # testing __ixor__
   485             self.assertEqual(d1, a)
   486 
   487     def test14_buffer(self):
   488         "Testing buffer()."
   489         for i in xrange(len(buffer_geoms)):
   490             g_tup = buffer_geoms[i]
   491             g = fromstr(g_tup[0].wkt)
   492 
   493             # The buffer we expect
   494             exp_buf = fromstr(g_tup[1].wkt)
   495 
   496             # Can't use a floating-point for the number of quadsegs.
   497             self.assertRaises(ArgumentError, g.buffer, g_tup[2], float(g_tup[3]))
   498 
   499             # Constructing our buffer
   500             buf = g.buffer(g_tup[2], g_tup[3])
   501             self.assertEqual(exp_buf.num_coords, buf.num_coords)
   502             self.assertEqual(len(exp_buf), len(buf))
   503 
   504             # Now assuring that each point in the buffer is almost equal
   505             for j in xrange(len(exp_buf)):
   506                 exp_ring = exp_buf[j]
   507                 buf_ring = buf[j]
   508                 self.assertEqual(len(exp_ring), len(buf_ring))
   509                 for k in xrange(len(exp_ring)):
   510                     # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
   511                     self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
   512                     self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
   513 
   514     def test15_srid(self):
   515         "Testing the SRID property and keyword."
   516         # Testing SRID keyword on Point
   517         pnt = Point(5, 23, srid=4326)
   518         self.assertEqual(4326, pnt.srid)
   519         pnt.srid = 3084
   520         self.assertEqual(3084, pnt.srid)
   521         self.assertRaises(ArgumentError, pnt.set_srid, '4326')
   522 
   523         # Testing SRID keyword on fromstr(), and on Polygon rings.
   524         poly = fromstr(polygons[1].wkt, srid=4269)
   525         self.assertEqual(4269, poly.srid)
   526         for ring in poly: self.assertEqual(4269, ring.srid)
   527         poly.srid = 4326
   528         self.assertEqual(4326, poly.shell.srid)
   529 
   530         # Testing SRID keyword on GeometryCollection
   531         gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
   532         self.assertEqual(32021, gc.srid)
   533         for i in range(len(gc)): self.assertEqual(32021, gc[i].srid)
   534 
   535         # GEOS may get the SRID from HEXEWKB
   536         # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
   537         # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
   538         hex = '0101000020E610000000000000000014400000000000003740'
   539         p1 = fromstr(hex)
   540         self.assertEqual(4326, p1.srid)
   541 
   542         # In GEOS 3.0.0rc1-4  when the EWKB and/or HEXEWKB is exported,
   543         # the SRID information is lost and set to -1 -- this is not a
   544         # problem on the 3.0.0 version (another reason to upgrade).
   545         exp_srid = self.null_srid
   546 
   547         p2 = fromstr(p1.hex)
   548         self.assertEqual(exp_srid, p2.srid)
   549         p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
   550         self.assertEqual(-1, p3.srid)
   551 
   552     def test16_mutable_geometries(self):
   553         "Testing the mutability of Polygons and Geometry Collections."
   554         ### Testing the mutability of Polygons ###
   555         for p in polygons:
   556             poly = fromstr(p.wkt)
   557 
   558             # Should only be able to use __setitem__ with LinearRing geometries.
   559             self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
   560 
   561             # Constructing the new shell by adding 500 to every point in the old shell.
   562             shell_tup = poly.shell.tuple
   563             new_coords = []
   564             for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
   565             new_shell = LinearRing(*tuple(new_coords))
   566 
   567             # Assigning polygon's exterior ring w/the new shell
   568             poly.exterior_ring = new_shell
   569             s = str(new_shell) # new shell is still accessible
   570             self.assertEqual(poly.exterior_ring, new_shell)
   571             self.assertEqual(poly[0], new_shell)
   572 
   573         ### Testing the mutability of Geometry Collections
   574         for tg in multipoints:
   575             mp = fromstr(tg.wkt)
   576             for i in range(len(mp)):
   577                 # Creating a random point.
   578                 pnt = mp[i]
   579                 new = Point(random.randint(1, 100), random.randint(1, 100))
   580                 # Testing the assignment
   581                 mp[i] = new
   582                 s = str(new) # what was used for the assignment is still accessible
   583                 self.assertEqual(mp[i], new)
   584                 self.assertEqual(mp[i].wkt, new.wkt)
   585                 self.assertNotEqual(pnt, mp[i])
   586 
   587         # MultiPolygons involve much more memory management because each
   588         # Polygon w/in the collection has its own rings.
   589         for tg in multipolygons:
   590             mpoly = fromstr(tg.wkt)
   591             for i in xrange(len(mpoly)):
   592                 poly = mpoly[i]
   593                 old_poly = mpoly[i]
   594                 # Offsetting the each ring in the polygon by 500.
   595                 for j in xrange(len(poly)):
   596                     r = poly[j]
   597                     for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
   598                     poly[j] = r
   599 
   600                 self.assertNotEqual(mpoly[i], poly)
   601                 # Testing the assignment
   602                 mpoly[i] = poly
   603                 s = str(poly) # Still accessible
   604                 self.assertEqual(mpoly[i], poly)
   605                 self.assertNotEqual(mpoly[i], old_poly)
   606 
   607         # Extreme (!!) __setitem__ -- no longer works, have to detect
   608         # in the first object that __setitem__ is called in the subsequent
   609         # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
   610         #mpoly[0][0][0] = (3.14, 2.71)
   611         #self.assertEqual((3.14, 2.71), mpoly[0][0][0])
   612         # Doing it more slowly..
   613         #self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
   614         #del mpoly
   615 
   616     def test17_threed(self):
   617         "Testing three-dimensional geometries."
   618         # Testing a 3D Point
   619         pnt = Point(2, 3, 8)
   620         self.assertEqual((2.,3.,8.), pnt.coords)
   621         self.assertRaises(TypeError, pnt.set_coords, (1.,2.))
   622         pnt.coords = (1.,2.,3.)
   623         self.assertEqual((1.,2.,3.), pnt.coords)
   624 
   625         # Testing a 3D LineString
   626         ls = LineString((2., 3., 8.), (50., 250., -117.))
   627         self.assertEqual(((2.,3.,8.), (50.,250.,-117.)), ls.tuple)
   628         self.assertRaises(TypeError, ls.__setitem__, 0, (1.,2.))
   629         ls[0] = (1.,2.,3.)
   630         self.assertEqual((1.,2.,3.), ls[0])
   631 
   632     def test18_distance(self):
   633         "Testing the distance() function."
   634         # Distance to self should be 0.
   635         pnt = Point(0, 0)
   636         self.assertEqual(0.0, pnt.distance(Point(0, 0)))
   637 
   638         # Distance should be 1
   639         self.assertEqual(1.0, pnt.distance(Point(0, 1)))
   640 
   641         # Distance should be ~ sqrt(2)
   642         self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
   643 
   644         # Distances are from the closest vertex in each geometry --
   645         #  should be 3 (distance from (2, 2) to (5, 2)).
   646         ls1 = LineString((0, 0), (1, 1), (2, 2))
   647         ls2 = LineString((5, 2), (6, 1), (7, 0))
   648         self.assertEqual(3, ls1.distance(ls2))
   649 
   650     def test19_length(self):
   651         "Testing the length property."
   652         # Points have 0 length.
   653         pnt = Point(0, 0)
   654         self.assertEqual(0.0, pnt.length)
   655 
   656         # Should be ~ sqrt(2)
   657         ls = LineString((0, 0), (1, 1))
   658         self.assertAlmostEqual(1.41421356237, ls.length, 11)
   659 
   660         # Should be circumfrence of Polygon
   661         poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
   662         self.assertEqual(4.0, poly.length)
   663 
   664         # Should be sum of each element's length in collection.
   665         mpoly = MultiPolygon(poly.clone(), poly)
   666         self.assertEqual(8.0, mpoly.length)
   667 
   668     def test20a_emptyCollections(self):
   669         "Testing empty geometries and collections."
   670         gc1 = GeometryCollection([])
   671         gc2 = fromstr('GEOMETRYCOLLECTION EMPTY')
   672         pnt = fromstr('POINT EMPTY')
   673         ls = fromstr('LINESTRING EMPTY')
   674         poly = fromstr('POLYGON EMPTY')
   675         mls = fromstr('MULTILINESTRING EMPTY')
   676         mpoly1 = fromstr('MULTIPOLYGON EMPTY')
   677         mpoly2 = MultiPolygon(())
   678 
   679         for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
   680             self.assertEqual(True, g.empty)
   681 
   682             # Testing len() and num_geom.
   683             if isinstance(g, Polygon):
   684                 self.assertEqual(1, len(g)) # Has one empty linear ring
   685                 self.assertEqual(1, g.num_geom)
   686                 self.assertEqual(0, len(g[0]))
   687             elif isinstance(g, (Point, LineString)):
   688                 self.assertEqual(1, g.num_geom)
   689                 self.assertEqual(0, len(g))
   690             else:
   691                 self.assertEqual(0, g.num_geom)
   692                 self.assertEqual(0, len(g))
   693 
   694             # Testing __getitem__ (doesn't work on Point or Polygon)
   695             if isinstance(g, Point):
   696                 self.assertRaises(GEOSIndexError, g.get_x)
   697             elif isinstance(g, Polygon):
   698                 lr = g.shell
   699                 self.assertEqual('LINEARRING EMPTY', lr.wkt)
   700                 self.assertEqual(0, len(lr))
   701                 self.assertEqual(True, lr.empty)
   702                 self.assertRaises(GEOSIndexError, lr.__getitem__, 0)
   703             else:
   704                 self.assertRaises(GEOSIndexError, g.__getitem__, 0)
   705 
   706     def test20b_collections_of_collections(self):
   707         "Testing GeometryCollection handling of other collections."
   708         # Creating a GeometryCollection WKT string composed of other
   709         # collections and polygons.
   710         coll = [mp.wkt for mp in multipolygons if mp.valid]
   711         coll.extend([mls.wkt for mls in multilinestrings])
   712         coll.extend([p.wkt for p in polygons])
   713         coll.extend([mp.wkt for mp in multipoints])
   714         gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
   715 
   716         # Should construct ok from WKT
   717         gc1 = GEOSGeometry(gc_wkt)
   718 
   719         # Should also construct ok from individual geometry arguments.
   720         gc2 = GeometryCollection(*tuple(g for g in gc1))
   721 
   722         # And, they should be equal.
   723         self.assertEqual(gc1, gc2)
   724 
   725     def test21_test_gdal(self):
   726         "Testing `ogr` and `srs` properties."
   727         if not gdal.HAS_GDAL: return
   728         g1 = fromstr('POINT(5 23)')
   729         self.assertEqual(True, isinstance(g1.ogr, gdal.OGRGeometry))
   730         self.assertEqual(g1.srs, None)
   731 
   732         g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
   733         self.assertEqual(True, isinstance(g2.ogr, gdal.OGRGeometry))
   734         self.assertEqual(True, isinstance(g2.srs, gdal.SpatialReference))
   735         self.assertEqual(g2.hex, g2.ogr.hex)
   736         self.assertEqual('WGS 84', g2.srs.name)
   737 
   738     def test22_copy(self):
   739         "Testing use with the Python `copy` module."
   740         import copy
   741         poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
   742         cpy1 = copy.copy(poly)
   743         cpy2 = copy.deepcopy(poly)
   744         self.assertNotEqual(poly._ptr, cpy1._ptr)
   745         self.assertNotEqual(poly._ptr, cpy2._ptr)
   746 
   747     def test23_transform(self):
   748         "Testing `transform` method."
   749         if not gdal.HAS_GDAL: return
   750         orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)
   751         trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)
   752 
   753         # Using a srid, a SpatialReference object, and a CoordTransform object
   754         # for transformations.
   755         t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
   756         t1.transform(trans.srid)
   757         t2.transform(gdal.SpatialReference('EPSG:2774'))
   758         ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))
   759         t3.transform(ct)
   760 
   761         # Testing use of the `clone` keyword.
   762         k1 = orig.clone()
   763         k2 = k1.transform(trans.srid, clone=True)
   764         self.assertEqual(k1, orig)
   765         self.assertNotEqual(k1, k2)
   766 
   767         prec = 3
   768         for p in (t1, t2, t3, k2):
   769             self.assertAlmostEqual(trans.x, p.x, prec)
   770             self.assertAlmostEqual(trans.y, p.y, prec)
   771 
   772     def test24_extent(self):
   773         "Testing `extent` method."
   774         # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
   775         mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
   776         self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
   777         pnt = Point(5.23, 17.8)
   778         # Extent of points is just the point itself repeated.
   779         self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
   780         # Testing on the 'real world' Polygon.
   781         poly = fromstr(polygons[3].wkt)
   782         ring = poly.shell
   783         x, y = ring.x, ring.y
   784         xmin, ymin = min(x), min(y)
   785         xmax, ymax = max(x), max(y)
   786         self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
   787 
   788     def test25_pickle(self):
   789         "Testing pickling and unpickling support."
   790         # Using both pickle and cPickle -- just 'cause.
   791         import pickle, cPickle
   792 
   793         # Creating a list of test geometries for pickling,
   794         # and setting the SRID on some of them.
   795         def get_geoms(lst, srid=None):
   796             return [GEOSGeometry(tg.wkt, srid) for tg in lst]
   797         tgeoms = get_geoms(points)
   798         tgeoms.extend(get_geoms(multilinestrings, 4326))
   799         tgeoms.extend(get_geoms(polygons, 3084))
   800         tgeoms.extend(get_geoms(multipolygons, 900913))
   801 
   802         # The SRID won't be exported in GEOS 3.0 release candidates.
   803         no_srid = self.null_srid == -1
   804         for geom in tgeoms:
   805             s1, s2 = cPickle.dumps(geom), pickle.dumps(geom)
   806             g1, g2 = cPickle.loads(s1), pickle.loads(s2)
   807             for tmpg in (g1, g2):
   808                 self.assertEqual(geom, tmpg)
   809                 if not no_srid: self.assertEqual(geom.srid, tmpg.srid)
   810 
   811     def test26_prepared(self):
   812         "Testing PreparedGeometry support."
   813         if not GEOS_PREPARE: return
   814         # Creating a simple multipolygon and getting a prepared version.
   815         mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
   816         prep = mpoly.prepared
   817 
   818         # A set of test points.
   819         pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
   820         covers = [True, True, False] # No `covers` op for regular GEOS geoms.
   821         for pnt, c in zip(pnts, covers):
   822             # Results should be the same (but faster)
   823             self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
   824             self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
   825             self.assertEqual(c, prep.covers(pnt))
   826 
   827     def test26_line_merge(self): 
   828         "Testing line merge support"
   829         ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'),
   830                      fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'),
   831                      )
   832         ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
   833                       fromstr('LINESTRING (1 1, 3 3, 4 2)'),
   834                       )
   835         for geom, merged in zip(ref_geoms, ref_merged):
   836             self.assertEqual(merged, geom.merged)
   837 
   838 def suite():
   839     s = unittest.TestSuite()
   840     s.addTest(unittest.makeSuite(GEOSTest))
   841     return s
   842 
   843 def run(verbosity=2):
   844     unittest.TextTestRunner(verbosity=verbosity).run(suite())