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 *
7 class GEOSTest(unittest.TestCase):
12 Returns the proper null SRID depending on the GEOS version.
13 See the comments in `test15_srid` for more details.
15 info = geos_version_info()
16 if info['version'] == '3.0.0' and info['release_candidate']:
21 def test01a_wkt(self):
25 self.assertEqual(g.ewkt, geom.wkt)
27 def test01b_hex(self):
31 self.assertEqual(g.hex, geom.hex)
33 def test01c_kml(self):
36 geom = fromstr(tg.wkt)
37 kml = getattr(tg, 'kml', False)
38 if kml: self.assertEqual(kml, geom.kml)
40 def test01d_errors(self):
41 "Testing the Error handlers."
43 print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n"
47 except (GEOSException, ValueError):
51 self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
53 print "\nEND - expecting GEOS_ERROR; safe to ignore.\n"
55 class NotAGeometry(object):
59 self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
61 self.assertRaises(TypeError, GEOSGeometry, None)
63 def test01e_wkb(self):
65 from binascii import b2a_hex
69 self.assertEqual(b2a_hex(wkb).upper(), g.hex)
71 def test01f_create_hex(self):
72 "Testing creation from HEX."
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)
79 def test01g_create_wkb(self):
80 "Testing creation from WKB."
81 from binascii import a2b_hex
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)
89 def test01h_ewkt(self):
93 ewkt = 'SRID=%d;%s' % (srid, p.wkt)
95 self.assertEqual(srid, poly.srid)
96 self.assertEqual(srid, poly.shell.srid)
97 self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
99 def test01i_json(self):
100 "Testing GeoJSON input/output (via GDAL)."
101 if not gdal or not gdal.GEOJSON: return
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))
109 def test01k_fromfile(self):
110 "Testing the fromfile() factory."
111 from StringIO import StringIO
112 ref_pnt = GEOSGeometry('POINT(5 23)')
115 wkt_f.write(ref_pnt.wkt)
117 wkb_f.write(str(ref_pnt.wkb))
119 # Other tests use `fromfile()` on string filenames so those
120 # aren't tested here.
121 for fh in (wkt_f, wkb_f):
124 self.assertEqual(ref_pnt, pnt)
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
137 self.assertNotEqual(g, None)
138 self.assertNotEqual(g, {'foo' : 'bar'})
139 self.assertNotEqual(g, False)
141 def test02a_points(self):
142 "Testing Point objects."
143 prev = fromstr('POINT(0 0)')
145 # Creating the point from the 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)
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)
158 # Testing the third dimension, and getting the tuple arguments
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)
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)
173 # Centroid operation on point should be point itself
174 self.assertEqual(p.centroid, pnt.centroid.tuple)
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)
182 # Now testing setting the x and y
185 self.assertEqual(3.14, pnt.y)
186 self.assertEqual(2.71, pnt.x)
188 # Setting via the tuple/coords property
190 self.assertEqual(set_tup1, pnt.tuple)
191 pnt.coords = set_tup2
192 self.assertEqual(set_tup2, pnt.coords)
194 prev = pnt # setting the previous geometry
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)
203 self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
204 self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
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))
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)
215 def test03a_linestring(self):
216 "Testing LineString objects."
217 prev = fromstr('POINT(0 0)')
218 for l in linestrings:
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)
229 self.assertEqual(True, ls == fromstr(l.wkt))
230 self.assertEqual(False, ls == prev)
231 self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
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
241 def test03b_multilinestring(self):
242 "Testing MultiLineString objects."
243 prev = fromstr('POINT(0 0)')
244 for l in multilinestrings:
246 self.assertEqual(ml.geom_type, 'MultiLineString')
247 self.assertEqual(ml.geom_typeid, 5)
249 self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
250 self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
252 self.assertEqual(True, ml == fromstr(l.wkt))
253 self.assertEqual(False, ml == prev)
257 self.assertEqual(ls.geom_type, 'LineString')
258 self.assertEqual(ls.geom_typeid, 1)
259 self.assertEqual(ls.empty, False)
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)))
265 def test04_linearring(self):
266 "Testing LinearRing objects."
267 for rr in linearrings:
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)
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)))
281 def test05a_polygons(self):
282 "Testing Polygon objects."
284 # Testing `from_bbox` class method
285 bbox = (-180, -90, 180, 90)
286 p = Polygon.from_bbox( bbox )
287 self.assertEqual(bbox, p.extent)
289 prev = fromstr('POINT(0 0)')
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)
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)
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)
311 # Testing the exterior ring
312 ring = poly.exterior_ring
313 self.assertEqual(ring.geom_type, 'LinearRing')
314 self.assertEqual(ring.geom_typeid, 2)
316 self.assertEqual(p.ext_ring_cs, ring.tuple)
317 self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
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)
326 self.assertEqual(r.geom_type, 'LinearRing')
327 self.assertEqual(r.geom_typeid, 2)
329 # Testing polygon construction.
330 self.assertRaises(TypeError, Polygon.__init__, 0, [1, 2, 3])
331 self.assertRaises(TypeError, Polygon.__init__, 'foo')
333 # Polygon(shell, (hole1, ... holeN))
334 rings = tuple(r for r in poly)
335 self.assertEqual(poly, Polygon(rings[0], rings[1:]))
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))
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)
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)
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))
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)
366 print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"
368 def test06a_memory_hijinks(self):
369 "Testing Geometry __del__() on rings and polygons."
370 #### Memory issues with rings and polygons
372 # These tests are needed to ensure sanity with writable geometries.
374 # Getting a polygon with interior rings, and pulling out the interior rings
375 poly = fromstr(polygons[1].wkt)
379 # These deletes should be 'harmless' since they are done on child geometries
385 # Deleting the polygon
388 # Access to these rings is OK since they are clones.
389 s1, s2 = str(ring1), str(ring2)
391 # The previous hijinks tests are now moot because only clones are
394 def test08_coord_seq(self):
395 "Testing Coordinate Sequence objects."
398 # Constructing the polygon and getting the coordinate sequence
399 poly = fromstr(p.wkt)
400 cs = poly.exterior_ring.coord_seq
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
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)
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)
416 # Making sure every set point matches what we expect
417 for j in range(len(tset)):
419 self.assertEqual(tset[j], cs[i][j])
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)
431 self.assertEqual(result, a.relate_pattern(b, pat))
432 self.assertEqual(pat, a.relate(b))
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)
448 def test11_union(self):
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)
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)
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)
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)
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)
487 def test14_buffer(self):
489 for i in xrange(len(buffer_geoms)):
490 g_tup = buffer_geoms[i]
491 g = fromstr(g_tup[0].wkt)
493 # The buffer we expect
494 exp_buf = fromstr(g_tup[1].wkt)
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]))
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))
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]
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)
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)
520 self.assertEqual(3084, pnt.srid)
521 self.assertRaises(ArgumentError, pnt.set_srid, '4326')
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)
528 self.assertEqual(4326, poly.shell.srid)
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)
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'
540 self.assertEqual(4326, p1.srid)
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
548 self.assertEqual(exp_srid, p2.srid)
549 p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
550 self.assertEqual(-1, p3.srid)
552 def test16_mutable_geometries(self):
553 "Testing the mutability of Polygons and Geometry Collections."
554 ### Testing the mutability of Polygons ###
556 poly = fromstr(p.wkt)
558 # Should only be able to use __setitem__ with LinearRing geometries.
559 self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
561 # Constructing the new shell by adding 500 to every point in the old shell.
562 shell_tup = poly.shell.tuple
564 for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
565 new_shell = LinearRing(*tuple(new_coords))
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)
573 ### Testing the mutability of Geometry Collections
574 for tg in multipoints:
576 for i in range(len(mp)):
577 # Creating a random point.
579 new = Point(random.randint(1, 100), random.randint(1, 100))
580 # Testing the assignment
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])
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)):
594 # Offsetting the each ring in the polygon by 500.
595 for j in xrange(len(poly)):
597 for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
600 self.assertNotEqual(mpoly[i], poly)
601 # Testing the assignment
603 s = str(poly) # Still accessible
604 self.assertEqual(mpoly[i], poly)
605 self.assertNotEqual(mpoly[i], old_poly)
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])
616 def test17_threed(self):
617 "Testing three-dimensional geometries."
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)
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.))
630 self.assertEqual((1.,2.,3.), ls[0])
632 def test18_distance(self):
633 "Testing the distance() function."
634 # Distance to self should be 0.
636 self.assertEqual(0.0, pnt.distance(Point(0, 0)))
638 # Distance should be 1
639 self.assertEqual(1.0, pnt.distance(Point(0, 1)))
641 # Distance should be ~ sqrt(2)
642 self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
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))
650 def test19_length(self):
651 "Testing the length property."
652 # Points have 0 length.
654 self.assertEqual(0.0, pnt.length)
656 # Should be ~ sqrt(2)
657 ls = LineString((0, 0), (1, 1))
658 self.assertAlmostEqual(1.41421356237, ls.length, 11)
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)
664 # Should be sum of each element's length in collection.
665 mpoly = MultiPolygon(poly.clone(), poly)
666 self.assertEqual(8.0, mpoly.length)
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(())
679 for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
680 self.assertEqual(True, g.empty)
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))
691 self.assertEqual(0, g.num_geom)
692 self.assertEqual(0, len(g))
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):
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)
704 self.assertRaises(GEOSIndexError, g.__getitem__, 0)
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)
716 # Should construct ok from WKT
717 gc1 = GEOSGeometry(gc_wkt)
719 # Should also construct ok from individual geometry arguments.
720 gc2 = GeometryCollection(*tuple(g for g in gc1))
722 # And, they should be equal.
723 self.assertEqual(gc1, gc2)
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)
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)
738 def test22_copy(self):
739 "Testing use with the Python `copy` module."
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)
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)
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))
761 # Testing use of the `clone` keyword.
763 k2 = k1.transform(trans.srid, clone=True)
764 self.assertEqual(k1, orig)
765 self.assertNotEqual(k1, k2)
768 for p in (t1, t2, t3, k2):
769 self.assertAlmostEqual(trans.x, p.x, prec)
770 self.assertAlmostEqual(trans.y, p.y, prec)
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)
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)
788 def test25_pickle(self):
789 "Testing pickling and unpickling support."
790 # Using both pickle and cPickle -- just 'cause.
791 import pickle, cPickle
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))
802 # The SRID won't be exported in GEOS 3.0 release candidates.
803 no_srid = self.null_srid == -1
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)
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
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))
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))'),
832 ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
833 fromstr('LINESTRING (1 1, 3 3, 4 2)'),
835 for geom, merged in zip(ref_geoms, ref_merged):
836 self.assertEqual(merged, geom.merged)
839 s = unittest.TestSuite()
840 s.addTest(unittest.makeSuite(GEOSTest))
843 def run(verbosity=2):
844 unittest.TextTestRunner(verbosity=verbosity).run(suite())