test_geos.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. from __future__ import unicode_literals
  2. import ctypes
  3. import json
  4. import random
  5. import unittest
  6. from unittest import skipUnless
  7. from binascii import a2b_hex, b2a_hex
  8. from io import BytesIO
  9. from django.contrib.gis.gdal import HAS_GDAL
  10. from django.contrib.gis import memoryview
  11. from django.contrib.gis.geometry.test_data import TestDataMixin
  12. from django.utils.encoding import force_bytes
  13. from django.utils import six
  14. from django.utils.six.moves import xrange
  15. from .. import HAS_GEOS
  16. if HAS_GEOS:
  17. from .. import (GEOSException, GEOSIndexError, GEOSGeometry,
  18. GeometryCollection, Point, MultiPoint, Polygon, MultiPolygon, LinearRing,
  19. LineString, MultiLineString, fromfile, fromstr, geos_version_info)
  20. from ..base import gdal, numpy, GEOSBase
  21. @skipUnless(HAS_GEOS, "Geos is required.")
  22. class GEOSTest(unittest.TestCase, TestDataMixin):
  23. @property
  24. def null_srid(self):
  25. """
  26. Returns the proper null SRID depending on the GEOS version.
  27. See the comments in `test_srid` for more details.
  28. """
  29. info = geos_version_info()
  30. if info['version'] == '3.0.0' and info['release_candidate']:
  31. return -1
  32. else:
  33. return None
  34. def test_base(self):
  35. "Tests out the GEOSBase class."
  36. # Testing out GEOSBase class, which provides a `ptr` property
  37. # that abstracts out access to underlying C pointers.
  38. class FakeGeom1(GEOSBase):
  39. pass
  40. # This one only accepts pointers to floats
  41. c_float_p = ctypes.POINTER(ctypes.c_float)
  42. class FakeGeom2(GEOSBase):
  43. ptr_type = c_float_p
  44. # Default ptr_type is `c_void_p`.
  45. fg1 = FakeGeom1()
  46. # Default ptr_type is C float pointer
  47. fg2 = FakeGeom2()
  48. # These assignments are OK -- None is allowed because
  49. # it's equivalent to the NULL pointer.
  50. fg1.ptr = ctypes.c_void_p()
  51. fg1.ptr = None
  52. fg2.ptr = c_float_p(ctypes.c_float(5.23))
  53. fg2.ptr = None
  54. # Because pointers have been set to NULL, an exception should be
  55. # raised when we try to access it. Raising an exception is
  56. # preferable to a segmentation fault that commonly occurs when
  57. # a C method is given a NULL memory reference.
  58. for fg in (fg1, fg2):
  59. # Equivalent to `fg.ptr`
  60. self.assertRaises(GEOSException, fg._get_ptr)
  61. # Anything that is either not None or the acceptable pointer type will
  62. # result in a TypeError when trying to assign it to the `ptr` property.
  63. # Thus, memmory addresses (integers) and pointers of the incorrect type
  64. # (in `bad_ptrs`) will not be allowed.
  65. bad_ptrs = (5, ctypes.c_char_p(b'foobar'))
  66. for bad_ptr in bad_ptrs:
  67. # Equivalent to `fg.ptr = bad_ptr`
  68. self.assertRaises(TypeError, fg1._set_ptr, bad_ptr)
  69. self.assertRaises(TypeError, fg2._set_ptr, bad_ptr)
  70. def test_wkt(self):
  71. "Testing WKT output."
  72. for g in self.geometries.wkt_out:
  73. geom = fromstr(g.wkt)
  74. if geom.hasz and geos_version_info()['version'] >= '3.3.0':
  75. self.assertEqual(g.ewkt, geom.wkt)
  76. def test_hex(self):
  77. "Testing HEX output."
  78. for g in self.geometries.hex_wkt:
  79. geom = fromstr(g.wkt)
  80. self.assertEqual(g.hex, geom.hex.decode())
  81. def test_hexewkb(self):
  82. "Testing (HEX)EWKB output."
  83. # For testing HEX(EWKB).
  84. ogc_hex = b'01010000000000000000000000000000000000F03F'
  85. ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040'
  86. # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
  87. hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F'
  88. # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
  89. hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040'
  90. pnt_2d = Point(0, 1, srid=4326)
  91. pnt_3d = Point(0, 1, 2, srid=4326)
  92. # OGC-compliant HEX will not have SRID value.
  93. self.assertEqual(ogc_hex, pnt_2d.hex)
  94. self.assertEqual(ogc_hex_3d, pnt_3d.hex)
  95. # HEXEWKB should be appropriate for its dimension -- have to use an
  96. # a WKBWriter w/dimension set accordingly, else GEOS will insert
  97. # garbage into 3D coordinate if there is none. Also, GEOS has a
  98. # a bug in versions prior to 3.1 that puts the X coordinate in
  99. # place of Z; an exception should be raised on those versions.
  100. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
  101. self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
  102. self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz)
  103. # Same for EWKB.
  104. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
  105. self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
  106. # Redundant sanity check.
  107. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
  108. def test_kml(self):
  109. "Testing KML output."
  110. for tg in self.geometries.wkt_out:
  111. geom = fromstr(tg.wkt)
  112. kml = getattr(tg, 'kml', False)
  113. if kml:
  114. self.assertEqual(kml, geom.kml)
  115. def test_errors(self):
  116. "Testing the Error handlers."
  117. # string-based
  118. for err in self.geometries.errors:
  119. with self.assertRaises((GEOSException, ValueError)):
  120. fromstr(err.wkt)
  121. # Bad WKB
  122. self.assertRaises(GEOSException, GEOSGeometry, memoryview(b'0'))
  123. class NotAGeometry(object):
  124. pass
  125. # Some other object
  126. self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
  127. # None
  128. self.assertRaises(TypeError, GEOSGeometry, None)
  129. def test_wkb(self):
  130. "Testing WKB output."
  131. for g in self.geometries.hex_wkt:
  132. geom = fromstr(g.wkt)
  133. wkb = geom.wkb
  134. self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)
  135. def test_create_hex(self):
  136. "Testing creation from HEX."
  137. for g in self.geometries.hex_wkt:
  138. geom_h = GEOSGeometry(g.hex)
  139. # we need to do this so decimal places get normalized
  140. geom_t = fromstr(g.wkt)
  141. self.assertEqual(geom_t.wkt, geom_h.wkt)
  142. def test_create_wkb(self):
  143. "Testing creation from WKB."
  144. for g in self.geometries.hex_wkt:
  145. wkb = memoryview(a2b_hex(g.hex.encode()))
  146. geom_h = GEOSGeometry(wkb)
  147. # we need to do this so decimal places get normalized
  148. geom_t = fromstr(g.wkt)
  149. self.assertEqual(geom_t.wkt, geom_h.wkt)
  150. def test_ewkt(self):
  151. "Testing EWKT."
  152. srids = (-1, 32140)
  153. for srid in srids:
  154. for p in self.geometries.polygons:
  155. ewkt = 'SRID=%d;%s' % (srid, p.wkt)
  156. poly = fromstr(ewkt)
  157. self.assertEqual(srid, poly.srid)
  158. self.assertEqual(srid, poly.shell.srid)
  159. self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
  160. @skipUnless(HAS_GDAL, "GDAL is required.")
  161. def test_json(self):
  162. "Testing GeoJSON input/output (via GDAL)."
  163. for g in self.geometries.json_geoms:
  164. geom = GEOSGeometry(g.wkt)
  165. if not hasattr(g, 'not_equal'):
  166. # Loading jsons to prevent decimal differences
  167. self.assertEqual(json.loads(g.json), json.loads(geom.json))
  168. self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
  169. self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
  170. def test_fromfile(self):
  171. "Testing the fromfile() factory."
  172. ref_pnt = GEOSGeometry('POINT(5 23)')
  173. wkt_f = BytesIO()
  174. wkt_f.write(force_bytes(ref_pnt.wkt))
  175. wkb_f = BytesIO()
  176. wkb_f.write(bytes(ref_pnt.wkb))
  177. # Other tests use `fromfile()` on string filenames so those
  178. # aren't tested here.
  179. for fh in (wkt_f, wkb_f):
  180. fh.seek(0)
  181. pnt = fromfile(fh)
  182. self.assertEqual(ref_pnt, pnt)
  183. def test_eq(self):
  184. "Testing equivalence."
  185. p = fromstr('POINT(5 23)')
  186. self.assertEqual(p, p.wkt)
  187. self.assertNotEqual(p, 'foo')
  188. ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
  189. self.assertEqual(ls, ls.wkt)
  190. self.assertNotEqual(p, 'bar')
  191. # Error shouldn't be raise on equivalence testing with
  192. # an invalid type.
  193. for g in (p, ls):
  194. self.assertNotEqual(g, None)
  195. self.assertNotEqual(g, {'foo': 'bar'})
  196. self.assertNotEqual(g, False)
  197. def test_points(self):
  198. "Testing Point objects."
  199. prev = fromstr('POINT(0 0)')
  200. for p in self.geometries.points:
  201. # Creating the point from the WKT
  202. pnt = fromstr(p.wkt)
  203. self.assertEqual(pnt.geom_type, 'Point')
  204. self.assertEqual(pnt.geom_typeid, 0)
  205. self.assertEqual(p.x, pnt.x)
  206. self.assertEqual(p.y, pnt.y)
  207. self.assertEqual(True, pnt == fromstr(p.wkt))
  208. self.assertEqual(False, pnt == prev)
  209. # Making sure that the point's X, Y components are what we expect
  210. self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
  211. self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
  212. # Testing the third dimension, and getting the tuple arguments
  213. if hasattr(p, 'z'):
  214. self.assertEqual(True, pnt.hasz)
  215. self.assertEqual(p.z, pnt.z)
  216. self.assertEqual(p.z, pnt.tuple[2], 9)
  217. tup_args = (p.x, p.y, p.z)
  218. set_tup1 = (2.71, 3.14, 5.23)
  219. set_tup2 = (5.23, 2.71, 3.14)
  220. else:
  221. self.assertEqual(False, pnt.hasz)
  222. self.assertEqual(None, pnt.z)
  223. tup_args = (p.x, p.y)
  224. set_tup1 = (2.71, 3.14)
  225. set_tup2 = (3.14, 2.71)
  226. # Centroid operation on point should be point itself
  227. self.assertEqual(p.centroid, pnt.centroid.tuple)
  228. # Now testing the different constructors
  229. pnt2 = Point(tup_args) # e.g., Point((1, 2))
  230. pnt3 = Point(*tup_args) # e.g., Point(1, 2)
  231. self.assertEqual(True, pnt == pnt2)
  232. self.assertEqual(True, pnt == pnt3)
  233. # Now testing setting the x and y
  234. pnt.y = 3.14
  235. pnt.x = 2.71
  236. self.assertEqual(3.14, pnt.y)
  237. self.assertEqual(2.71, pnt.x)
  238. # Setting via the tuple/coords property
  239. pnt.tuple = set_tup1
  240. self.assertEqual(set_tup1, pnt.tuple)
  241. pnt.coords = set_tup2
  242. self.assertEqual(set_tup2, pnt.coords)
  243. prev = pnt # setting the previous geometry
  244. def test_multipoints(self):
  245. "Testing MultiPoint objects."
  246. for mp in self.geometries.multipoints:
  247. mpnt = fromstr(mp.wkt)
  248. self.assertEqual(mpnt.geom_type, 'MultiPoint')
  249. self.assertEqual(mpnt.geom_typeid, 4)
  250. self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
  251. self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
  252. self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt))
  253. self.assertEqual(mp.centroid, mpnt.centroid.tuple)
  254. self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
  255. for p in mpnt:
  256. self.assertEqual(p.geom_type, 'Point')
  257. self.assertEqual(p.geom_typeid, 0)
  258. self.assertEqual(p.empty, False)
  259. self.assertEqual(p.valid, True)
  260. def test_linestring(self):
  261. "Testing LineString objects."
  262. prev = fromstr('POINT(0 0)')
  263. for l in self.geometries.linestrings:
  264. ls = fromstr(l.wkt)
  265. self.assertEqual(ls.geom_type, 'LineString')
  266. self.assertEqual(ls.geom_typeid, 1)
  267. self.assertEqual(ls.empty, False)
  268. self.assertEqual(ls.ring, False)
  269. if hasattr(l, 'centroid'):
  270. self.assertEqual(l.centroid, ls.centroid.tuple)
  271. if hasattr(l, 'tup'):
  272. self.assertEqual(l.tup, ls.tuple)
  273. self.assertEqual(True, ls == fromstr(l.wkt))
  274. self.assertEqual(False, ls == prev)
  275. self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
  276. prev = ls
  277. # Creating a LineString from a tuple, list, and numpy array
  278. self.assertEqual(ls, LineString(ls.tuple)) # tuple
  279. self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
  280. self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
  281. self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
  282. if numpy:
  283. self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
  284. def test_multilinestring(self):
  285. "Testing MultiLineString objects."
  286. prev = fromstr('POINT(0 0)')
  287. for l in self.geometries.multilinestrings:
  288. ml = fromstr(l.wkt)
  289. self.assertEqual(ml.geom_type, 'MultiLineString')
  290. self.assertEqual(ml.geom_typeid, 5)
  291. self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
  292. self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
  293. self.assertEqual(True, ml == fromstr(l.wkt))
  294. self.assertEqual(False, ml == prev)
  295. prev = ml
  296. for ls in ml:
  297. self.assertEqual(ls.geom_type, 'LineString')
  298. self.assertEqual(ls.geom_typeid, 1)
  299. self.assertEqual(ls.empty, False)
  300. self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml))
  301. self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
  302. self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
  303. def test_linearring(self):
  304. "Testing LinearRing objects."
  305. for rr in self.geometries.linearrings:
  306. lr = fromstr(rr.wkt)
  307. self.assertEqual(lr.geom_type, 'LinearRing')
  308. self.assertEqual(lr.geom_typeid, 2)
  309. self.assertEqual(rr.n_p, len(lr))
  310. self.assertEqual(True, lr.valid)
  311. self.assertEqual(False, lr.empty)
  312. # Creating a LinearRing from a tuple, list, and numpy array
  313. self.assertEqual(lr, LinearRing(lr.tuple))
  314. self.assertEqual(lr, LinearRing(*lr.tuple))
  315. self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
  316. if numpy:
  317. self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
  318. def test_polygons_from_bbox(self):
  319. "Testing `from_bbox` class method."
  320. bbox = (-180, -90, 180, 90)
  321. p = Polygon.from_bbox(bbox)
  322. self.assertEqual(bbox, p.extent)
  323. # Testing numerical precision
  324. x = 3.14159265358979323
  325. bbox = (0, 0, 1, x)
  326. p = Polygon.from_bbox(bbox)
  327. y = p.extent[-1]
  328. self.assertEqual(format(x, '.13f'), format(y, '.13f'))
  329. def test_polygons(self):
  330. "Testing Polygon objects."
  331. prev = fromstr('POINT(0 0)')
  332. for p in self.geometries.polygons:
  333. # Creating the Polygon, testing its properties.
  334. poly = fromstr(p.wkt)
  335. self.assertEqual(poly.geom_type, 'Polygon')
  336. self.assertEqual(poly.geom_typeid, 3)
  337. self.assertEqual(poly.empty, False)
  338. self.assertEqual(poly.ring, False)
  339. self.assertEqual(p.n_i, poly.num_interior_rings)
  340. self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
  341. self.assertEqual(p.n_p, poly.num_points)
  342. # Area & Centroid
  343. self.assertAlmostEqual(p.area, poly.area, 9)
  344. self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
  345. self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
  346. # Testing the geometry equivalence
  347. self.assertEqual(True, poly == fromstr(p.wkt))
  348. self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
  349. self.assertEqual(True, poly != prev)
  350. # Testing the exterior ring
  351. ring = poly.exterior_ring
  352. self.assertEqual(ring.geom_type, 'LinearRing')
  353. self.assertEqual(ring.geom_typeid, 2)
  354. if p.ext_ring_cs:
  355. self.assertEqual(p.ext_ring_cs, ring.tuple)
  356. self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
  357. # Testing __getitem__ and __setitem__ on invalid indices
  358. self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
  359. self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False)
  360. self.assertRaises(GEOSIndexError, poly.__getitem__, -1 * len(poly) - 1)
  361. # Testing __iter__
  362. for r in poly:
  363. self.assertEqual(r.geom_type, 'LinearRing')
  364. self.assertEqual(r.geom_typeid, 2)
  365. # Testing polygon construction.
  366. self.assertRaises(TypeError, Polygon, 0, [1, 2, 3])
  367. self.assertRaises(TypeError, Polygon, 'foo')
  368. # Polygon(shell, (hole1, ... holeN))
  369. rings = tuple(r for r in poly)
  370. self.assertEqual(poly, Polygon(rings[0], rings[1:]))
  371. # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
  372. ring_tuples = tuple(r.tuple for r in poly)
  373. self.assertEqual(poly, Polygon(*ring_tuples))
  374. # Constructing with tuples of LinearRings.
  375. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
  376. self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)
  377. def test_polygon_comparison(self):
  378. p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  379. p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
  380. self.assertTrue(p1 > p2)
  381. self.assertFalse(p1 < p2)
  382. self.assertFalse(p2 > p1)
  383. self.assertTrue(p2 < p1)
  384. p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
  385. p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
  386. self.assertFalse(p4 < p3)
  387. self.assertTrue(p3 < p4)
  388. self.assertTrue(p4 > p3)
  389. self.assertFalse(p3 > p4)
  390. def test_multipolygons(self):
  391. "Testing MultiPolygon objects."
  392. fromstr('POINT (0 0)')
  393. for mp in self.geometries.multipolygons:
  394. mpoly = fromstr(mp.wkt)
  395. self.assertEqual(mpoly.geom_type, 'MultiPolygon')
  396. self.assertEqual(mpoly.geom_typeid, 6)
  397. self.assertEqual(mp.valid, mpoly.valid)
  398. if mp.valid:
  399. self.assertEqual(mp.num_geom, mpoly.num_geom)
  400. self.assertEqual(mp.n_p, mpoly.num_coords)
  401. self.assertEqual(mp.num_geom, len(mpoly))
  402. self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
  403. for p in mpoly:
  404. self.assertEqual(p.geom_type, 'Polygon')
  405. self.assertEqual(p.geom_typeid, 3)
  406. self.assertEqual(p.valid, True)
  407. self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
  408. def test_memory_hijinks(self):
  409. "Testing Geometry __del__() on rings and polygons."
  410. #### Memory issues with rings and polygons
  411. # These tests are needed to ensure sanity with writable geometries.
  412. # Getting a polygon with interior rings, and pulling out the interior rings
  413. poly = fromstr(self.geometries.polygons[1].wkt)
  414. ring1 = poly[0]
  415. ring2 = poly[1]
  416. # These deletes should be 'harmless' since they are done on child geometries
  417. del ring1
  418. del ring2
  419. ring1 = poly[0]
  420. ring2 = poly[1]
  421. # Deleting the polygon
  422. del poly
  423. # Access to these rings is OK since they are clones.
  424. str(ring1)
  425. str(ring2)
  426. def test_coord_seq(self):
  427. "Testing Coordinate Sequence objects."
  428. for p in self.geometries.polygons:
  429. if p.ext_ring_cs:
  430. # Constructing the polygon and getting the coordinate sequence
  431. poly = fromstr(p.wkt)
  432. cs = poly.exterior_ring.coord_seq
  433. self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
  434. self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
  435. # Checks __getitem__ and __setitem__
  436. for i in xrange(len(p.ext_ring_cs)):
  437. c1 = p.ext_ring_cs[i] # Expected value
  438. c2 = cs[i] # Value from coordseq
  439. self.assertEqual(c1, c2)
  440. # Constructing the test value to set the coordinate sequence with
  441. if len(c1) == 2:
  442. tset = (5, 23)
  443. else:
  444. tset = (5, 23, 8)
  445. cs[i] = tset
  446. # Making sure every set point matches what we expect
  447. for j in range(len(tset)):
  448. cs[i] = tset
  449. self.assertEqual(tset[j], cs[i][j])
  450. def test_relate_pattern(self):
  451. "Testing relate() and relate_pattern()."
  452. g = fromstr('POINT (0 0)')
  453. self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo')
  454. for rg in self.geometries.relate_geoms:
  455. a = fromstr(rg.wkt_a)
  456. b = fromstr(rg.wkt_b)
  457. self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))
  458. self.assertEqual(rg.pattern, a.relate(b))
  459. def test_intersection(self):
  460. "Testing intersects() and intersection()."
  461. for i in xrange(len(self.geometries.topology_geoms)):
  462. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  463. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  464. i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
  465. self.assertEqual(True, a.intersects(b))
  466. i2 = a.intersection(b)
  467. self.assertEqual(i1, i2)
  468. self.assertEqual(i1, a & b) # __and__ is intersection operator
  469. a &= b # testing __iand__
  470. self.assertEqual(i1, a)
  471. def test_union(self):
  472. "Testing union()."
  473. for i in xrange(len(self.geometries.topology_geoms)):
  474. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  475. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  476. u1 = fromstr(self.geometries.union_geoms[i].wkt)
  477. u2 = a.union(b)
  478. self.assertEqual(u1, u2)
  479. self.assertEqual(u1, a | b) # __or__ is union operator
  480. a |= b # testing __ior__
  481. self.assertEqual(u1, a)
  482. def test_difference(self):
  483. "Testing difference()."
  484. for i in xrange(len(self.geometries.topology_geoms)):
  485. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  486. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  487. d1 = fromstr(self.geometries.diff_geoms[i].wkt)
  488. d2 = a.difference(b)
  489. self.assertEqual(d1, d2)
  490. self.assertEqual(d1, a - b) # __sub__ is difference operator
  491. a -= b # testing __isub__
  492. self.assertEqual(d1, a)
  493. def test_symdifference(self):
  494. "Testing sym_difference()."
  495. for i in xrange(len(self.geometries.topology_geoms)):
  496. a = fromstr(self.geometries.topology_geoms[i].wkt_a)
  497. b = fromstr(self.geometries.topology_geoms[i].wkt_b)
  498. d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
  499. d2 = a.sym_difference(b)
  500. self.assertEqual(d1, d2)
  501. self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
  502. a ^= b # testing __ixor__
  503. self.assertEqual(d1, a)
  504. def test_buffer(self):
  505. "Testing buffer()."
  506. for bg in self.geometries.buffer_geoms:
  507. g = fromstr(bg.wkt)
  508. # The buffer we expect
  509. exp_buf = fromstr(bg.buffer_wkt)
  510. quadsegs = bg.quadsegs
  511. width = bg.width
  512. # Can't use a floating-point for the number of quadsegs.
  513. self.assertRaises(ctypes.ArgumentError, g.buffer, width, float(quadsegs))
  514. # Constructing our buffer
  515. buf = g.buffer(width, quadsegs)
  516. self.assertEqual(exp_buf.num_coords, buf.num_coords)
  517. self.assertEqual(len(exp_buf), len(buf))
  518. # Now assuring that each point in the buffer is almost equal
  519. for j in xrange(len(exp_buf)):
  520. exp_ring = exp_buf[j]
  521. buf_ring = buf[j]
  522. self.assertEqual(len(exp_ring), len(buf_ring))
  523. for k in xrange(len(exp_ring)):
  524. # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
  525. self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
  526. self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
  527. def test_srid(self):
  528. "Testing the SRID property and keyword."
  529. # Testing SRID keyword on Point
  530. pnt = Point(5, 23, srid=4326)
  531. self.assertEqual(4326, pnt.srid)
  532. pnt.srid = 3084
  533. self.assertEqual(3084, pnt.srid)
  534. self.assertRaises(ctypes.ArgumentError, pnt.set_srid, '4326')
  535. # Testing SRID keyword on fromstr(), and on Polygon rings.
  536. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)
  537. self.assertEqual(4269, poly.srid)
  538. for ring in poly:
  539. self.assertEqual(4269, ring.srid)
  540. poly.srid = 4326
  541. self.assertEqual(4326, poly.shell.srid)
  542. # Testing SRID keyword on GeometryCollection
  543. gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
  544. self.assertEqual(32021, gc.srid)
  545. for i in range(len(gc)):
  546. self.assertEqual(32021, gc[i].srid)
  547. # GEOS may get the SRID from HEXEWKB
  548. # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
  549. # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
  550. hex = '0101000020E610000000000000000014400000000000003740'
  551. p1 = fromstr(hex)
  552. self.assertEqual(4326, p1.srid)
  553. # In GEOS 3.0.0rc1-4 when the EWKB and/or HEXEWKB is exported,
  554. # the SRID information is lost and set to -1 -- this is not a
  555. # problem on the 3.0.0 version (another reason to upgrade).
  556. exp_srid = self.null_srid
  557. p2 = fromstr(p1.hex)
  558. self.assertEqual(exp_srid, p2.srid)
  559. p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
  560. self.assertEqual(-1, p3.srid)
  561. @skipUnless(HAS_GDAL, "GDAL is required.")
  562. def test_custom_srid(self):
  563. """ Test with a srid unknown from GDAL """
  564. pnt = Point(111200, 220900, srid=999999)
  565. self.assertTrue(pnt.ewkt.startswith("SRID=999999;POINT (111200.0"))
  566. self.assertIsInstance(pnt.ogr, gdal.OGRGeometry)
  567. self.assertIsNone(pnt.srs)
  568. # Test conversion from custom to a known srid
  569. c2w = gdal.CoordTransform(
  570. gdal.SpatialReference('+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 +datum=WGS84 +units=m +no_defs'),
  571. gdal.SpatialReference(4326))
  572. new_pnt = pnt.transform(c2w, clone=True)
  573. self.assertEqual(new_pnt.srid, 4326)
  574. self.assertAlmostEqual(new_pnt.x, 1, 3)
  575. self.assertAlmostEqual(new_pnt.y, 2, 3)
  576. def test_mutable_geometries(self):
  577. "Testing the mutability of Polygons and Geometry Collections."
  578. ### Testing the mutability of Polygons ###
  579. for p in self.geometries.polygons:
  580. poly = fromstr(p.wkt)
  581. # Should only be able to use __setitem__ with LinearRing geometries.
  582. self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
  583. # Constructing the new shell by adding 500 to every point in the old shell.
  584. shell_tup = poly.shell.tuple
  585. new_coords = []
  586. for point in shell_tup:
  587. new_coords.append((point[0] + 500., point[1] + 500.))
  588. new_shell = LinearRing(*tuple(new_coords))
  589. # Assigning polygon's exterior ring w/the new shell
  590. poly.exterior_ring = new_shell
  591. str(new_shell) # new shell is still accessible
  592. self.assertEqual(poly.exterior_ring, new_shell)
  593. self.assertEqual(poly[0], new_shell)
  594. ### Testing the mutability of Geometry Collections
  595. for tg in self.geometries.multipoints:
  596. mp = fromstr(tg.wkt)
  597. for i in range(len(mp)):
  598. # Creating a random point.
  599. pnt = mp[i]
  600. new = Point(random.randint(21, 100), random.randint(21, 100))
  601. # Testing the assignment
  602. mp[i] = new
  603. str(new) # what was used for the assignment is still accessible
  604. self.assertEqual(mp[i], new)
  605. self.assertEqual(mp[i].wkt, new.wkt)
  606. self.assertNotEqual(pnt, mp[i])
  607. # MultiPolygons involve much more memory management because each
  608. # Polygon w/in the collection has its own rings.
  609. for tg in self.geometries.multipolygons:
  610. mpoly = fromstr(tg.wkt)
  611. for i in xrange(len(mpoly)):
  612. poly = mpoly[i]
  613. old_poly = mpoly[i]
  614. # Offsetting the each ring in the polygon by 500.
  615. for j in xrange(len(poly)):
  616. r = poly[j]
  617. for k in xrange(len(r)):
  618. r[k] = (r[k][0] + 500., r[k][1] + 500.)
  619. poly[j] = r
  620. self.assertNotEqual(mpoly[i], poly)
  621. # Testing the assignment
  622. mpoly[i] = poly
  623. str(poly) # Still accessible
  624. self.assertEqual(mpoly[i], poly)
  625. self.assertNotEqual(mpoly[i], old_poly)
  626. # Extreme (!!) __setitem__ -- no longer works, have to detect
  627. # in the first object that __setitem__ is called in the subsequent
  628. # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
  629. #mpoly[0][0][0] = (3.14, 2.71)
  630. #self.assertEqual((3.14, 2.71), mpoly[0][0][0])
  631. # Doing it more slowly..
  632. #self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
  633. #del mpoly
  634. def test_threed(self):
  635. "Testing three-dimensional geometries."
  636. # Testing a 3D Point
  637. pnt = Point(2, 3, 8)
  638. self.assertEqual((2., 3., 8.), pnt.coords)
  639. self.assertRaises(TypeError, pnt.set_coords, (1., 2.))
  640. pnt.coords = (1., 2., 3.)
  641. self.assertEqual((1., 2., 3.), pnt.coords)
  642. # Testing a 3D LineString
  643. ls = LineString((2., 3., 8.), (50., 250., -117.))
  644. self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple)
  645. self.assertRaises(TypeError, ls.__setitem__, 0, (1., 2.))
  646. ls[0] = (1., 2., 3.)
  647. self.assertEqual((1., 2., 3.), ls[0])
  648. def test_distance(self):
  649. "Testing the distance() function."
  650. # Distance to self should be 0.
  651. pnt = Point(0, 0)
  652. self.assertEqual(0.0, pnt.distance(Point(0, 0)))
  653. # Distance should be 1
  654. self.assertEqual(1.0, pnt.distance(Point(0, 1)))
  655. # Distance should be ~ sqrt(2)
  656. self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
  657. # Distances are from the closest vertex in each geometry --
  658. # should be 3 (distance from (2, 2) to (5, 2)).
  659. ls1 = LineString((0, 0), (1, 1), (2, 2))
  660. ls2 = LineString((5, 2), (6, 1), (7, 0))
  661. self.assertEqual(3, ls1.distance(ls2))
  662. def test_length(self):
  663. "Testing the length property."
  664. # Points have 0 length.
  665. pnt = Point(0, 0)
  666. self.assertEqual(0.0, pnt.length)
  667. # Should be ~ sqrt(2)
  668. ls = LineString((0, 0), (1, 1))
  669. self.assertAlmostEqual(1.41421356237, ls.length, 11)
  670. # Should be circumference of Polygon
  671. poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
  672. self.assertEqual(4.0, poly.length)
  673. # Should be sum of each element's length in collection.
  674. mpoly = MultiPolygon(poly.clone(), poly)
  675. self.assertEqual(8.0, mpoly.length)
  676. def test_emptyCollections(self):
  677. "Testing empty geometries and collections."
  678. gc1 = GeometryCollection([])
  679. gc2 = fromstr('GEOMETRYCOLLECTION EMPTY')
  680. pnt = fromstr('POINT EMPTY')
  681. ls = fromstr('LINESTRING EMPTY')
  682. poly = fromstr('POLYGON EMPTY')
  683. mls = fromstr('MULTILINESTRING EMPTY')
  684. mpoly1 = fromstr('MULTIPOLYGON EMPTY')
  685. mpoly2 = MultiPolygon(())
  686. for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
  687. self.assertEqual(True, g.empty)
  688. # Testing len() and num_geom.
  689. if isinstance(g, Polygon):
  690. self.assertEqual(1, len(g)) # Has one empty linear ring
  691. self.assertEqual(1, g.num_geom)
  692. self.assertEqual(0, len(g[0]))
  693. elif isinstance(g, (Point, LineString)):
  694. self.assertEqual(1, g.num_geom)
  695. self.assertEqual(0, len(g))
  696. else:
  697. self.assertEqual(0, g.num_geom)
  698. self.assertEqual(0, len(g))
  699. # Testing __getitem__ (doesn't work on Point or Polygon)
  700. if isinstance(g, Point):
  701. self.assertRaises(GEOSIndexError, g.get_x)
  702. elif isinstance(g, Polygon):
  703. lr = g.shell
  704. self.assertEqual('LINEARRING EMPTY', lr.wkt)
  705. self.assertEqual(0, len(lr))
  706. self.assertEqual(True, lr.empty)
  707. self.assertRaises(GEOSIndexError, lr.__getitem__, 0)
  708. else:
  709. self.assertRaises(GEOSIndexError, g.__getitem__, 0)
  710. def test_collections_of_collections(self):
  711. "Testing GeometryCollection handling of other collections."
  712. # Creating a GeometryCollection WKT string composed of other
  713. # collections and polygons.
  714. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]
  715. coll.extend(mls.wkt for mls in self.geometries.multilinestrings)
  716. coll.extend(p.wkt for p in self.geometries.polygons)
  717. coll.extend(mp.wkt for mp in self.geometries.multipoints)
  718. gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
  719. # Should construct ok from WKT
  720. gc1 = GEOSGeometry(gc_wkt)
  721. # Should also construct ok from individual geometry arguments.
  722. gc2 = GeometryCollection(*tuple(g for g in gc1))
  723. # And, they should be equal.
  724. self.assertEqual(gc1, gc2)
  725. @skipUnless(HAS_GDAL, "GDAL is required.")
  726. def test_gdal(self):
  727. "Testing `ogr` and `srs` properties."
  728. g1 = fromstr('POINT(5 23)')
  729. self.assertIsInstance(g1.ogr, gdal.OGRGeometry)
  730. self.assertIsNone(g1.srs)
  731. g1_3d = fromstr('POINT(5 23 8)')
  732. self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)
  733. self.assertEqual(g1_3d.ogr.z, 8)
  734. g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
  735. self.assertIsInstance(g2.ogr, gdal.OGRGeometry)
  736. self.assertIsInstance(g2.srs, gdal.SpatialReference)
  737. self.assertEqual(g2.hex, g2.ogr.hex)
  738. self.assertEqual('WGS 84', g2.srs.name)
  739. def test_copy(self):
  740. "Testing use with the Python `copy` module."
  741. import copy
  742. poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
  743. cpy1 = copy.copy(poly)
  744. cpy2 = copy.deepcopy(poly)
  745. self.assertNotEqual(poly._ptr, cpy1._ptr)
  746. self.assertNotEqual(poly._ptr, cpy2._ptr)
  747. @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
  748. def test_transform(self):
  749. "Testing `transform` method."
  750. orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  751. trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)
  752. # Using a srid, a SpatialReference object, and a CoordTransform object
  753. # for transformations.
  754. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
  755. t1.transform(trans.srid)
  756. t2.transform(gdal.SpatialReference('EPSG:2774'))
  757. ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))
  758. t3.transform(ct)
  759. # Testing use of the `clone` keyword.
  760. k1 = orig.clone()
  761. k2 = k1.transform(trans.srid, clone=True)
  762. self.assertEqual(k1, orig)
  763. self.assertNotEqual(k1, k2)
  764. prec = 3
  765. for p in (t1, t2, t3, k2):
  766. self.assertAlmostEqual(trans.x, p.x, prec)
  767. self.assertAlmostEqual(trans.y, p.y, prec)
  768. @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
  769. def test_transform_3d(self):
  770. p3d = GEOSGeometry('POINT (5 23 100)', 4326)
  771. p3d.transform(2774)
  772. self.assertEqual(p3d.z, 100)
  773. @skipUnless(HAS_GDAL, "GDAL is required.")
  774. def test_transform_noop(self):
  775. """ Testing `transform` method (SRID match) """
  776. # transform() should no-op if source & dest SRIDs match,
  777. # regardless of whether GDAL is available.
  778. if gdal.HAS_GDAL:
  779. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  780. gt = g.tuple
  781. g.transform(4326)
  782. self.assertEqual(g.tuple, gt)
  783. self.assertEqual(g.srid, 4326)
  784. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  785. g1 = g.transform(4326, clone=True)
  786. self.assertEqual(g1.tuple, g.tuple)
  787. self.assertEqual(g1.srid, 4326)
  788. self.assertTrue(g1 is not g, "Clone didn't happen")
  789. old_has_gdal = gdal.HAS_GDAL
  790. try:
  791. gdal.HAS_GDAL = False
  792. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  793. gt = g.tuple
  794. g.transform(4326)
  795. self.assertEqual(g.tuple, gt)
  796. self.assertEqual(g.srid, 4326)
  797. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  798. g1 = g.transform(4326, clone=True)
  799. self.assertEqual(g1.tuple, g.tuple)
  800. self.assertEqual(g1.srid, 4326)
  801. self.assertTrue(g1 is not g, "Clone didn't happen")
  802. finally:
  803. gdal.HAS_GDAL = old_has_gdal
  804. def test_transform_nosrid(self):
  805. """ Testing `transform` method (no SRID or negative SRID) """
  806. g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
  807. self.assertRaises(GEOSException, g.transform, 2774)
  808. g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
  809. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  810. g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
  811. self.assertRaises(GEOSException, g.transform, 2774)
  812. g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
  813. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  814. @skipUnless(HAS_GDAL, "GDAL is required.")
  815. def test_transform_nogdal(self):
  816. """ Testing `transform` method (GDAL not available) """
  817. old_has_gdal = gdal.HAS_GDAL
  818. try:
  819. gdal.HAS_GDAL = False
  820. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  821. self.assertRaises(GEOSException, g.transform, 2774)
  822. g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
  823. self.assertRaises(GEOSException, g.transform, 2774, clone=True)
  824. finally:
  825. gdal.HAS_GDAL = old_has_gdal
  826. def test_extent(self):
  827. "Testing `extent` method."
  828. # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
  829. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
  830. self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
  831. pnt = Point(5.23, 17.8)
  832. # Extent of points is just the point itself repeated.
  833. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
  834. # Testing on the 'real world' Polygon.
  835. poly = fromstr(self.geometries.polygons[3].wkt)
  836. ring = poly.shell
  837. x, y = ring.x, ring.y
  838. xmin, ymin = min(x), min(y)
  839. xmax, ymax = max(x), max(y)
  840. self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
  841. def test_pickle(self):
  842. "Testing pickling and unpickling support."
  843. # Using both pickle and cPickle -- just 'cause.
  844. from django.utils.six.moves import cPickle
  845. import pickle
  846. # Creating a list of test geometries for pickling,
  847. # and setting the SRID on some of them.
  848. def get_geoms(lst, srid=None):
  849. return [GEOSGeometry(tg.wkt, srid) for tg in lst]
  850. tgeoms = get_geoms(self.geometries.points)
  851. tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326))
  852. tgeoms.extend(get_geoms(self.geometries.polygons, 3084))
  853. tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857))
  854. # The SRID won't be exported in GEOS 3.0 release candidates.
  855. no_srid = self.null_srid == -1
  856. for geom in tgeoms:
  857. s1, s2 = cPickle.dumps(geom), pickle.dumps(geom)
  858. g1, g2 = cPickle.loads(s1), pickle.loads(s2)
  859. for tmpg in (g1, g2):
  860. self.assertEqual(geom, tmpg)
  861. if not no_srid:
  862. self.assertEqual(geom.srid, tmpg.srid)
  863. def test_prepared(self):
  864. "Testing PreparedGeometry support."
  865. # Creating a simple multipolygon and getting a prepared version.
  866. mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
  867. prep = mpoly.prepared
  868. # A set of test points.
  869. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
  870. covers = [True, True, False] # No `covers` op for regular GEOS geoms.
  871. for pnt, c in zip(pnts, covers):
  872. # Results should be the same (but faster)
  873. self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
  874. self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
  875. self.assertEqual(c, prep.covers(pnt))
  876. if geos_version_info()['version'] > '3.3.0':
  877. self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)')))
  878. self.assertTrue(prep.disjoint(Point(-5, -5)))
  879. poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
  880. self.assertTrue(prep.overlaps(poly))
  881. poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
  882. self.assertTrue(prep.touches(poly))
  883. poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
  884. self.assertTrue(prep.within(poly))
  885. # Original geometry deletion should not crash the prepared one (#21662)
  886. del mpoly
  887. self.assertTrue(prep.covers(Point(5, 5)))
  888. def test_line_merge(self):
  889. "Testing line merge support"
  890. ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'),
  891. fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'),
  892. )
  893. ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
  894. fromstr('LINESTRING (1 1, 3 3, 4 2)'),
  895. )
  896. for geom, merged in zip(ref_geoms, ref_merged):
  897. self.assertEqual(merged, geom.merged)
  898. def test_valid_reason(self):
  899. "Testing IsValidReason support"
  900. g = GEOSGeometry("POINT(0 0)")
  901. self.assertTrue(g.valid)
  902. self.assertIsInstance(g.valid_reason, six.string_types)
  903. self.assertEqual(g.valid_reason, "Valid Geometry")
  904. g = GEOSGeometry("LINESTRING(0 0, 0 0)")
  905. self.assertFalse(g.valid)
  906. self.assertIsInstance(g.valid_reason, six.string_types)
  907. self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
  908. @skipUnless(HAS_GEOS and geos_version_info()['version'] >= '3.2.0', "geos >= 3.2.0 is required")
  909. def test_linearref(self):
  910. "Testing linear referencing"
  911. ls = fromstr('LINESTRING(0 0, 0 10, 10 10, 10 0)')
  912. mls = fromstr('MULTILINESTRING((0 0, 0 10), (10 0, 10 10))')
  913. self.assertEqual(ls.project(Point(0, 20)), 10.0)
  914. self.assertEqual(ls.project(Point(7, 6)), 24)
  915. self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3)
  916. self.assertEqual(ls.interpolate(10), Point(0, 10))
  917. self.assertEqual(ls.interpolate(24), Point(10, 6))
  918. self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10))
  919. self.assertEqual(mls.project(Point(0, 20)), 10)
  920. self.assertEqual(mls.project(Point(7, 6)), 16)
  921. self.assertEqual(mls.interpolate(9), Point(0, 9))
  922. self.assertEqual(mls.interpolate(17), Point(10, 7))
  923. def test_geos_version(self):
  924. """Testing the GEOS version regular expression."""
  925. from django.contrib.gis.geos.libgeos import version_regex
  926. versions = [('3.0.0rc4-CAPI-1.3.3', '3.0.0', '1.3.3'),
  927. ('3.0.0-CAPI-1.4.1', '3.0.0', '1.4.1'),
  928. ('3.4.0dev-CAPI-1.8.0', '3.4.0', '1.8.0'),
  929. ('3.4.0dev-CAPI-1.8.0 r0', '3.4.0', '1.8.0')]
  930. for v_init, v_geos, v_capi in versions:
  931. m = version_regex.match(v_init)
  932. self.assertTrue(m, msg="Unable to parse the version string '%s'" % v_init)
  933. self.assertEqual(m.group('version'), v_geos)
  934. self.assertEqual(m.group('capi_version'), v_capi)