code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
from django.contrib.gis.db import models from django.contrib.localflavor.us.models import USStateField class Location(models.Model): point = models.PointField() objects = models.GeoManager() def __unicode__(self): return self.point.wkt class City(models.Model): name = models.CharField(max_length=50) state = USStateField() location = models.ForeignKey(Location) objects = models.GeoManager() def __unicode__(self): return self.name class AugmentedLocation(Location): extra_text = models.TextField(blank=True) objects = models.GeoManager() class DirectoryEntry(models.Model): listing_text = models.CharField(max_length=50) location = models.ForeignKey(AugmentedLocation) objects = models.GeoManager() class Parcel(models.Model): name = models.CharField(max_length=30) city = models.ForeignKey(City) center1 = models.PointField() # Throwing a curveball w/`db_column` here. center2 = models.PointField(srid=2276, db_column='mycenter') border1 = models.PolygonField() border2 = models.PolygonField(srid=2276) objects = models.GeoManager() def __unicode__(self): return self.name # These use the GeoManager but do not have any geographic fields. class Author(models.Model): name = models.CharField(max_length=100) objects = models.GeoManager() class Article(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, unique=True) objects = models.GeoManager() class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name='books', null=True) objects = models.GeoManager()
[ [ 1, 0, 0.0204, 0.0204, 0, 0.66, 0, 964, 0, 1, 0, 0, 964, 0, 0 ], [ 1, 0, 0.0408, 0.0204, 0, 0.66, 0.1111, 676, 0, 1, 0, 0, 676, 0, 0 ], [ 3, 0, 0.1122, 0.0816, 0, ...
[ "from django.contrib.gis.db import models", "from django.contrib.localflavor.us.models import USStateField", "class Location(models.Model):\n point = models.PointField()\n objects = models.GeoManager()\n def __unicode__(self): return self.point.wkt", " point = models.PointField()", " objects ...
import os, unittest from django.contrib.gis.geos import * from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.tests.utils import mysql, oracle, postgis, spatialite, no_mysql, no_oracle, no_spatialite from django.conf import settings from models import City, Location, DirectoryEntry, Parcel, Book, Author, Article cities = (('Aurora', 'TX', -97.516111, 33.058333), ('Roswell', 'NM', -104.528056, 33.387222), ('Kecksburg', 'PA', -79.460734, 40.18476), ) class RelatedGeoModelTest(unittest.TestCase): def test01_setup(self): "Setting up for related model tests." for name, state, lon, lat in cities: loc = Location.objects.create(point=Point(lon, lat)) c = City.objects.create(name=name, state=state, location=loc) def test02_select_related(self): "Testing `select_related` on geographic models (see #7126)." qs1 = City.objects.all() qs2 = City.objects.select_related() qs3 = City.objects.select_related('location') for qs in (qs1, qs2, qs3): for ref, c in zip(cities, qs): nm, st, lon, lat = ref self.assertEqual(nm, c.name) self.assertEqual(st, c.state) self.assertEqual(Point(lon, lat), c.location.point) @no_mysql def test03_transform_related(self): "Testing the `transform` GeoQuerySet method on related geographic models." # All the transformations are to state plane coordinate systems using # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot). tol = 0 def check_pnt(ref, pnt): self.assertAlmostEqual(ref.x, pnt.x, tol) self.assertAlmostEqual(ref.y, pnt.y, tol) self.assertEqual(ref.srid, pnt.srid) # Each city transformed to the SRID of their state plane coordinate system. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'), ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'), ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'), ) for name, srid, wkt in transformed: # Doing this implicitly sets `select_related` select the location. # TODO: Fix why this breaks on Oracle. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point')) check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point) @no_mysql @no_spatialite def test04a_related_extent_aggregate(self): "Testing the `extent` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Extent('location__point')) # One for all locations, one that excludes Roswell. all_extent = (-104.528060913086, 33.0583305358887,-79.4607315063477, 40.1847610473633) txpa_extent = (-97.51611328125, 33.0583305358887,-79.4607315063477, 40.1847610473633) e1 = City.objects.extent(field_name='location__point') e2 = City.objects.exclude(name='Roswell').extent(field_name='location__point') e3 = aggs['location__point__extent'] # The tolerance value is to four decimal places because of differences # between the Oracle and PostGIS spatial backends on the extent calculation. tol = 4 for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol) @no_mysql def test04b_related_union_aggregate(self): "Testing the `unionagg` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) # Creating the reference union geometry depending on the spatial backend, # as Oracle will have a different internal ordering of the component # geometries than PostGIS. The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.unionagg()`). if oracle: ref_u1 = MultiPoint(p3, p1, p2, srid=4326) ref_u2 = MultiPoint(p3, p2, srid=4326) else: ref_u1 = MultiPoint(p1, p2, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.unionagg(field_name='location__point') u2 = City.objects.exclude(name='Roswell').unionagg(field_name='location__point') u3 = aggs['location__point__union'] self.assertEqual(ref_u1, u1) self.assertEqual(ref_u2, u2) self.assertEqual(ref_u1, u3) def test05_select_related_fk_to_subclass(self): "Testing that calling select_related on a query over a model with an FK to a model subclass works" # Regression test for #9752. l = list(DirectoryEntry.objects.all().select_related()) def test06_f_expressions(self): "Testing F() expressions on GeometryFields." # Constructing a dummy parcel border and getting the City instance for # assigning the FK. b1 = GEOSGeometry('POLYGON((-97.501205 33.052520,-97.501205 33.052576,-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326) pcity = City.objects.get(name='Aurora') # First parcel has incorrect center point that is equal to the City; # it also has a second border that is different from the first as a # 100ft buffer around the City. c1 = pcity.location.point c2 = c1.transform(2276, clone=True) b2 = c2.buffer(100) p1 = Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) # Now creating a second Parcel where the borders are the same, just # in different coordinate systems. The center points are also the # the same (but in different coordinate systems), and this time they # actually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) p2 = Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1) # Should return the second Parcel, which has the center within the # border. qs = Parcel.objects.filter(center1__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) if not mysql: # This time center2 is in a different coordinate system and needs # to be wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) # Should return the first Parcel, which has the center point equal # to the point in the City ForeignKey. qs = Parcel.objects.filter(center1=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) if not mysql: # This time the city column should be wrapped in transformation SQL. qs = Parcel.objects.filter(border2__contains=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) def test07_values(self): "Testing values() and values_list() and GeoQuerySets." # GeoQuerySet and GeoValuesQuerySet, and GeoValuesListQuerySet respectively. gqs = Location.objects.all() gvqs = Location.objects.values() gvlqs = Location.objects.values_list() # Incrementing through each of the models, dictionaries, and tuples # returned by the different types of GeoQuerySets. for m, d, t in zip(gqs, gvqs, gvlqs): # The values should be Geometry objects and not raw strings returned # by the spatial database. self.failUnless(isinstance(d['point'], Geometry)) self.failUnless(isinstance(t[1], Geometry)) self.assertEqual(m.point, d['point']) self.assertEqual(m.point, t[1]) def test08_defer_only(self): "Testing defer() and only() on Geographic models." qs = Location.objects.all() def_qs = Location.objects.defer('point') for loc, def_loc in zip(qs, def_qs): self.assertEqual(loc.point, def_loc.point) def test09_pk_relations(self): "Ensuring correct primary key column is selected across relations. See #10757." # Adding two more cities, but this time making sure that their location # ID values do not match their City ID values. loc1 = Location.objects.create(point='POINT (-95.363151 29.763374)') loc2 = Location.objects.create(point='POINT (-96.801611 32.782057)') dallas = City.objects.create(name='Dallas', state='TX', location=loc2) houston = City.objects.create(name='Houston', state='TX', location=loc1) # The expected ID values -- notice the last two location IDs # are out of order. We want to make sure that the related # location ID column is selected instead of ID column for # the city. city_ids = (1, 2, 3, 4, 5) loc_ids = (1, 2, 3, 5, 4) ids_qs = City.objects.order_by('id').values('id', 'location__id') for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): self.assertEqual(val_dict['id'], c_id) self.assertEqual(val_dict['location__id'], l_id) def test10_combine(self): "Testing the combination of two GeoQuerySets. See #10807." buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1) buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1) qs1 = City.objects.filter(location__point__within=buf1) qs2 = City.objects.filter(location__point__within=buf2) combined = qs1 | qs2 names = [c.name for c in combined] self.assertEqual(2, len(names)) self.failUnless('Aurora' in names) self.failUnless('Kecksburg' in names) def test11_geoquery_pickle(self): "Ensuring GeoQuery objects are unpickled correctly. See #10839." import pickle from django.contrib.gis.db.models.sql import GeoQuery qs = City.objects.all() q_str = pickle.dumps(qs.query) q = pickle.loads(q_str) self.assertEqual(GeoQuery, q.__class__) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test12a_count(self): "Testing `Count` aggregate use with the `GeoManager` on geo-fields." # Creating a new City, 'Fort Worth', that uses the same location # as Dallas. dallas = City.objects.get(name='Dallas') ftworth = City.objects.create(name='Fort Worth', state='TX', location=dallas.location) # Count annotation should be 2 for the Dallas location now. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id) self.assertEqual(2, loc.num_cities) def test12b_count(self): "Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087." # Creating some data for the Book/Author non-geo models that # use GeoManager. See #11087. tp = Author.objects.create(name='Trevor Paglen') Book.objects.create(title='Torture Taxi', author=tp) Book.objects.create(title='I Could Tell You But Then You Would Have to be Destroyed by Me', author=tp) Book.objects.create(title='Blank Spots on the Map', author=tp) wp = Author.objects.create(name='William Patry') Book.objects.create(title='Patry on Copyright', author=wp) # Should only be one author (Trevor Paglen) returned by this query, and # the annotation should have 3 for the number of books. Also testing # with a `GeoValuesQuerySet` (see #11489). qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1) vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1) self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) self.assertEqual(1, len(vqs)) self.assertEqual(3, vqs[0]['num_books']) # TODO: The phantom model does appear on Oracle. @no_oracle def test13_select_related_null_fk(self): "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381." no_author = Book.objects.create(title='Without Author') b = Book.objects.select_related('author').get(title='Without Author') # Should be `None`, and not a 'dummy' model. self.assertEqual(None, b.author) @no_mysql @no_oracle @no_spatialite def test14_collect(self): "Testing the `collect` GeoQuerySet method and `Collect` aggregate." # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id") # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = fromstr('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)') c1 = City.objects.filter(state='TX').collect(field_name='location__point') c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect'] for coll in (c1, c2): # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertEqual(ref_geom, coll) def test15_invalid_select_related(self): "Testing doing select_related on the related name manager of a unique FK. See #13934." qs = Article.objects.select_related('author__article') # This triggers TypeError when `get_default_columns` has no `local_only` # keyword. The TypeError is swallowed if QuerySet is actually # evaluated as list generation swallows TypeError in CPython. sql = str(qs.query) # TODO: Related tests for KML, GML, and distance lookups. def suite(): s = unittest.TestSuite() s.addTest(unittest.makeSuite(RelatedGeoModelTest)) return s
[ [ 1, 0, 0.0033, 0.0033, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0065, 0.0033, 0, 0.66, 0.1111, 886, 0, 1, 0, 0, 886, 0, 0 ], [ 1, 0, 0.0098, 0.0033, 0, ...
[ "import os, unittest", "from django.contrib.gis.geos import *", "from django.contrib.gis.db.models import Collect, Count, Extent, F, Union", "from django.contrib.gis.geometry.backend import Geometry", "from django.contrib.gis.tests.utils import mysql, oracle, postgis, spatialite, no_mysql, no_oracle, no_spa...
from django.conf import settings from django.db import DEFAULT_DB_ALIAS # function that will pass a test. def pass_test(*args): return def no_backend(test_func, backend): "Use this decorator to disable test on specified backend." if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].rsplit('.')[-1] == backend: return pass_test else: return test_func # Decorators to disable entire test functions for specific # spatial backends. def no_oracle(func): return no_backend(func, 'oracle') def no_postgis(func): return no_backend(func, 'postgis') def no_mysql(func): return no_backend(func, 'mysql') def no_spatialite(func): return no_backend(func, 'spatialite') # Shortcut booleans to omit only portions of tests. _default_db = settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].rsplit('.')[-1] oracle = _default_db == 'oracle' postgis = _default_db == 'postgis' mysql = _default_db == 'mysql' spatialite = _default_db == 'spatialite'
[ [ 1, 0, 0.0385, 0.0385, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0769, 0.0385, 0, 0.66, 0.0833, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 2, 0, 0.1923, 0.0385, 0, 0....
[ "from django.conf import settings", "from django.db import DEFAULT_DB_ALIAS", "def pass_test(*args): return", "def pass_test(*args): return", "def no_backend(test_func, backend):\n \"Use this decorator to disable test on specified backend.\"\n if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'].rsplit('...
import sys from django.conf import settings from django.db.models import get_app from django.test.simple import build_suite, DjangoTestSuiteRunner from django.utils import unittest def run_tests(*args, **kwargs): from django.test.simple import run_tests as base_run_tests return base_run_tests(*args, **kwargs) def run_gis_tests(test_labels, verbosity=1, interactive=True, failfast=False, extra_tests=None): import warnings warnings.warn( 'The run_gis_tests() test runner has been deprecated in favor of GeoDjangoTestSuiteRunner.', DeprecationWarning ) test_runner = GeoDjangoTestSuiteRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) return test_runner.run_tests(test_labels, extra_tests=extra_tests) class GeoDjangoTestSuiteRunner(DjangoTestSuiteRunner): def setup_test_environment(self, **kwargs): super(GeoDjangoTestSuiteRunner, self).setup_test_environment(**kwargs) from django.db import connection from django.contrib.gis.geos import GEOS_PREPARE from django.contrib.gis.gdal import HAS_GDAL # Getting and storing the original values of INSTALLED_APPS and # the ROOT_URLCONF. self.old_installed = settings.INSTALLED_APPS self.old_root_urlconf = settings.ROOT_URLCONF # Tests that require use of a spatial database (e.g., creation of models) self.geo_apps = ['geoapp', 'relatedapp'] if connection.ops.postgis and connection.ops.geography: # Test geography support with PostGIS 1.5+. self.geo_apps.append('geogapp') if HAS_GDAL: # The following GeoDjango test apps depend on GDAL support. if not connection.ops.mysql: self.geo_apps.append('distapp') # 3D apps use LayerMapping, which uses GDAL. if connection.ops.postgis and GEOS_PREPARE: self.geo_apps.append('geo3d') self.geo_apps.append('layermap') # Constructing the new INSTALLED_APPS, and including applications # within the GeoDjango test namespace (`self.geo_apps`). new_installed = ['django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.gis', ] new_installed.extend(['django.contrib.gis.tests.%s' % app for app in self.geo_apps]) settings.INSTALLED_APPS = new_installed # Setting the URLs. settings.ROOT_URLCONF = 'django.contrib.gis.tests.urls' def teardown_test_environment(self, **kwargs): super(GeoDjangoTestSuiteRunner, self).teardown_test_environment(**kwargs) settings.INSTALLED_APPS = self.old_installed settings.ROOT_URLCONF = self.old_root_urlconf def build_suite(self, test_labels, extra_tests=None, **kwargs): """ This method is overridden to construct a suite consisting only of tests for GeoDjango. """ suite = unittest.TestSuite() # Adding the GEOS tests. from django.contrib.gis.geos import tests as geos_tests suite.addTest(geos_tests.suite()) # Adding the measurment tests. from django.contrib.gis.tests import test_measure suite.addTest(test_measure.suite()) # Adding GDAL tests, and any test suite that depends on GDAL, to the # suite if GDAL is available. from django.contrib.gis.gdal import HAS_GDAL if HAS_GDAL: from django.contrib.gis.gdal import tests as gdal_tests suite.addTest(gdal_tests.suite()) from django.contrib.gis.tests import test_spatialrefsys, test_geoforms suite.addTest(test_spatialrefsys.suite()) suite.addTest(test_geoforms.suite()) else: sys.stderr.write('GDAL not available - no tests requiring GDAL will be run.\n') # Add GeoIP tests to the suite, if the library and data is available. from django.contrib.gis.utils import HAS_GEOIP if HAS_GEOIP and hasattr(settings, 'GEOIP_PATH'): from django.contrib.gis.tests import test_geoip suite.addTest(test_geoip.suite()) # Finally, adding the suites for each of the GeoDjango test apps. for app_name in self.geo_apps: suite.addTest(build_suite(get_app(app_name))) return suite
[ [ 1, 0, 0.0092, 0.0092, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0275, 0.0092, 0, 0.66, 0.1429, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0367, 0.0092, 0, ...
[ "import sys", "from django.conf import settings", "from django.db.models import get_app", "from django.test.simple import build_suite, DjangoTestSuiteRunner", "from django.utils import unittest", "def run_tests(*args, **kwargs):\n from django.test.simple import run_tests as base_run_tests\n return b...
# Copyright (c) 2007, Robert Coup <robert.coup@onetrackmind.co.nz> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of Distance nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ Distance and Area objects to allow for sensible and convienient calculation and conversions. Authors: Robert Coup, Justin Bronn Inspired by GeoPy (http://exogen.case.edu/projects/geopy/) and Geoff Biggs' PhD work on dimensioned units for robotics. """ __all__ = ['A', 'Area', 'D', 'Distance'] from decimal import Decimal class MeasureBase(object): def default_units(self, kwargs): """ Return the unit value and the default units specified from the given keyword arguments dictionary. """ val = 0.0 for unit, value in kwargs.iteritems(): if not isinstance(value, float): value = float(value) if unit in self.UNITS: val += self.UNITS[unit] * value default_unit = unit elif unit in self.ALIAS: u = self.ALIAS[unit] val += self.UNITS[u] * value default_unit = u else: lower = unit.lower() if lower in self.UNITS: val += self.UNITS[lower] * value default_unit = lower elif lower in self.LALIAS: u = self.LALIAS[lower] val += self.UNITS[u] * value default_unit = u else: raise AttributeError('Unknown unit type: %s' % unit) return val, default_unit @classmethod def unit_attname(cls, unit_str): """ Retrieves the unit attribute name for the given unit string. For example, if the given unit string is 'metre', 'm' would be returned. An exception is raised if an attribute cannot be found. """ lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) class Distance(MeasureBase): UNITS = { 'chain' : 20.1168, 'chain_benoit' : 20.116782, 'chain_sears' : 20.1167645, 'british_chain_benoit' : 20.1167824944, 'british_chain_sears' : 20.1167651216, 'british_chain_sears_truncated' : 20.116756, 'cm' : 0.01, 'british_ft' : 0.304799471539, 'british_yd' : 0.914398414616, 'clarke_ft' : 0.3047972654, 'clarke_link' : 0.201166195164, 'fathom' : 1.8288, 'ft': 0.3048, 'german_m' : 1.0000135965, 'gold_coast_ft' : 0.304799710181508, 'indian_yd' : 0.914398530744, 'inch' : 0.0254, 'km': 1000.0, 'link' : 0.201168, 'link_benoit' : 0.20116782, 'link_sears' : 0.20116765, 'm': 1.0, 'mi': 1609.344, 'mm' : 0.001, 'nm': 1852.0, 'nm_uk' : 1853.184, 'rod' : 5.0292, 'sears_yd' : 0.91439841, 'survey_ft' : 0.304800609601, 'um' : 0.000001, 'yd': 0.9144, } # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. ALIAS = { 'centimeter' : 'cm', 'foot' : 'ft', 'inches' : 'inch', 'kilometer' : 'km', 'kilometre' : 'km', 'meter' : 'm', 'metre' : 'm', 'micrometer' : 'um', 'micrometre' : 'um', 'millimeter' : 'mm', 'millimetre' : 'mm', 'mile' : 'mi', 'yard' : 'yd', 'British chain (Benoit 1895 B)' : 'british_chain_benoit', 'British chain (Sears 1922)' : 'british_chain_sears', 'British chain (Sears 1922 truncated)' : 'british_chain_sears_truncated', 'British foot (Sears 1922)' : 'british_ft', 'British foot' : 'british_ft', 'British yard (Sears 1922)' : 'british_yd', 'British yard' : 'british_yd', "Clarke's Foot" : 'clarke_ft', "Clarke's link" : 'clarke_link', 'Chain (Benoit)' : 'chain_benoit', 'Chain (Sears)' : 'chain_sears', 'Foot (International)' : 'ft', 'German legal metre' : 'german_m', 'Gold Coast foot' : 'gold_coast_ft', 'Indian yard' : 'indian_yd', 'Link (Benoit)': 'link_benoit', 'Link (Sears)': 'link_sears', 'Nautical Mile' : 'nm', 'Nautical Mile (UK)' : 'nm_uk', 'US survey foot' : 'survey_ft', 'U.S. Foot' : 'survey_ft', 'Yard (Indian)' : 'indian_yd', 'Yard (Sears)' : 'sears_yd' } LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()]) def __init__(self, default_unit=None, **kwargs): # The base unit is in meters. self.m, self._default_unit = self.default_units(kwargs) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit def __getattr__(self, name): if name in self.UNITS: return self.m / self.UNITS[name] else: raise AttributeError('Unknown unit type: %s' % name) def __repr__(self): return 'Distance(%s=%s)' % (self._default_unit, getattr(self, self._default_unit)) def __str__(self): return '%s %s' % (getattr(self, self._default_unit), self._default_unit) def __cmp__(self, other): if isinstance(other, Distance): return cmp(self.m, other.m) else: return NotImplemented def __add__(self, other): if isinstance(other, Distance): return Distance(default_unit=self._default_unit, m=(self.m + other.m)) else: raise TypeError('Distance must be added with Distance') def __iadd__(self, other): if isinstance(other, Distance): self.m += other.m return self else: raise TypeError('Distance must be added with Distance') def __sub__(self, other): if isinstance(other, Distance): return Distance(default_unit=self._default_unit, m=(self.m - other.m)) else: raise TypeError('Distance must be subtracted from Distance') def __isub__(self, other): if isinstance(other, Distance): self.m -= other.m return self else: raise TypeError('Distance must be subtracted from Distance') def __mul__(self, other): if isinstance(other, (int, float, long, Decimal)): return Distance(default_unit=self._default_unit, m=(self.m * float(other))) elif isinstance(other, Distance): return Area(default_unit='sq_' + self._default_unit, sq_m=(self.m * other.m)) else: raise TypeError('Distance must be multiplied with number or Distance') def __imul__(self, other): if isinstance(other, (int, float, long, Decimal)): self.m *= float(other) return self else: raise TypeError('Distance must be multiplied with number') def __rmul__(self, other): return self * other def __div__(self, other): if isinstance(other, (int, float, long, Decimal)): return Distance(default_unit=self._default_unit, m=(self.m / float(other))) else: raise TypeError('Distance must be divided with number') def __idiv__(self, other): if isinstance(other, (int, float, long, Decimal)): self.m /= float(other) return self else: raise TypeError('Distance must be divided with number') def __nonzero__(self): return bool(self.m) class Area(MeasureBase): # Getting the square units values and the alias dictionary. UNITS = dict([('sq_%s' % k, v ** 2) for k, v in Distance.UNITS.items()]) ALIAS = dict([(k, 'sq_%s' % v) for k, v in Distance.ALIAS.items()]) LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()]) def __init__(self, default_unit=None, **kwargs): self.sq_m, self._default_unit = self.default_units(kwargs) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit def __getattr__(self, name): if name in self.UNITS: return self.sq_m / self.UNITS[name] else: raise AttributeError('Unknown unit type: ' + name) def __repr__(self): return 'Area(%s=%s)' % (self._default_unit, getattr(self, self._default_unit)) def __str__(self): return '%s %s' % (getattr(self, self._default_unit), self._default_unit) def __cmp__(self, other): if isinstance(other, Area): return cmp(self.sq_m, other.sq_m) else: return NotImplemented def __add__(self, other): if isinstance(other, Area): return Area(default_unit=self._default_unit, sq_m=(self.sq_m + other.sq_m)) else: raise TypeError('Area must be added with Area') def __iadd__(self, other): if isinstance(other, Area): self.sq_m += other.sq_m return self else: raise TypeError('Area must be added with Area') def __sub__(self, other): if isinstance(other, Area): return Area(default_unit=self._default_unit, sq_m=(self.sq_m - other.sq_m)) else: raise TypeError('Area must be subtracted from Area') def __isub__(self, other): if isinstance(other, Area): self.sq_m -= other.sq_m return self else: raise TypeError('Area must be subtracted from Area') def __mul__(self, other): if isinstance(other, (int, float, long, Decimal)): return Area(default_unit=self._default_unit, sq_m=(self.sq_m * float(other))) else: raise TypeError('Area must be multiplied with number') def __imul__(self, other): if isinstance(other, (int, float, long, Decimal)): self.sq_m *= float(other) return self else: raise TypeError('Area must be multiplied with number') def __rmul__(self, other): return self * other def __div__(self, other): if isinstance(other, (int, float, long, Decimal)): return Area(default_unit=self._default_unit, sq_m=(self.sq_m / float(other))) else: raise TypeError('Area must be divided with number') def __idiv__(self, other): if isinstance(other, (int, float, long, Decimal)): self.sq_m /= float(other) return self else: raise TypeError('Area must be divided with number') def __nonzero__(self): return bool(self.sq_m) # Shortcuts D = Distance A = Area
[ [ 8, 0, 0.0982, 0.0268, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1131, 0.003, 0, 0.66, 0.1429, 272, 0, 0, 0, 0, 0, 5, 0 ], [ 1, 0, 0.1161, 0.003, 0, 0.66, ...
[ "\"\"\"\nDistance and Area objects to allow for sensible and convienient calculation\nand conversions.\n\nAuthors: Robert Coup, Justin Bronn\n\nInspired by GeoPy (http://exogen.case.edu/projects/geopy/)\nand Geoff Biggs' PhD work on dimensioned units for robotics.", "__all__ = ['A', 'Area', 'D', 'Distance']", "...
""" DataSource is a wrapper for the OGR Data Source object, which provides an interface for reading vector geometry data from many different file formats (including ESRI shapefiles). When instantiating a DataSource object, use the filename of a GDAL-supported data source. For example, a SHP file or a TIGER/Line file from the government. The ds_driver keyword is used internally when a ctypes pointer is passed in directly. Example: ds = DataSource('/home/foo/bar.shp') for layer in ds: for feature in layer: # Getting the geometry for the feature. g = feature.geom # Getting the 'description' field for the feature. desc = feature['description'] # We can also increment through all of the fields # attached to this feature. for field in feature: # Get the name of the field (e.g. 'description') nm = field.name # Get the type (integer) of the field, e.g. 0 => OFTInteger t = field.type # Returns the value the field; OFTIntegers return ints, # OFTReal returns floats, all else returns string. val = field.value """ # ctypes prerequisites. from ctypes import byref, c_void_p # The GDAL C library, OGR exceptions, and the Layer object. from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.error import OGRException, OGRIndexError from django.contrib.gis.gdal.layer import Layer # Getting the ctypes prototypes for the DataSource. from django.contrib.gis.gdal.prototypes import ds as capi # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_DS_* routines are relevant here. class DataSource(GDALBase): "Wraps an OGR Data Source object." #### Python 'magic' routines #### def __init__(self, ds_input, ds_driver=False, write=False): # The write flag. if write: self._write = 1 else: self._write = 0 # Registering all the drivers, this needs to be done # _before_ we try to open up a data source. if not capi.get_driver_count(): capi.register_all() if isinstance(ds_input, basestring): # The data source driver is a void pointer. ds_driver = Driver.ptr_type() try: # OGROpen will auto-detect the data source type. ds = capi.open_ds(ds_input, self._write, byref(ds_driver)) except OGRException: # Making the error message more clear rather than something # like "Invalid pointer returned from OGROpen". raise OGRException('Could not open the datasource at "%s"' % ds_input) elif isinstance(ds_input, self.ptr_type) and isinstance(ds_driver, Driver.ptr_type): ds = ds_input else: raise OGRException('Invalid data source input type: %s' % type(ds_input)) if bool(ds): self.ptr = ds self.driver = Driver(ds_driver) else: # Raise an exception if the returned pointer is NULL raise OGRException('Invalid data source file "%s"' % ds_input) def __del__(self): "Destroys this DataStructure object." if self._ptr: capi.destroy_ds(self._ptr) def __iter__(self): "Allows for iteration over the layers in a data source." for i in xrange(self.layer_count): yield self[i] def __getitem__(self, index): "Allows use of the index [] operator to get a layer at the index." if isinstance(index, basestring): l = capi.get_layer_by_name(self.ptr, index) if not l: raise OGRIndexError('invalid OGR Layer name given: "%s"' % index) elif isinstance(index, int): if index < 0 or index >= self.layer_count: raise OGRIndexError('index out of range') l = capi.get_layer(self._ptr, index) else: raise TypeError('Invalid index type: %s' % type(index)) return Layer(l, self) def __len__(self): "Returns the number of layers within the data source." return self.layer_count def __str__(self): "Returns OGR GetName and Driver for the Data Source." return '%s (%s)' % (self.name, str(self.driver)) @property def layer_count(self): "Returns the number of layers in the data source." return capi.get_layer_count(self._ptr) @property def name(self): "Returns the name of the data source." return capi.get_ds_name(self._ptr)
[ [ 8, 0, 0.1406, 0.2734, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2891, 0.0078, 0, 0.66, 0.1429, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.3125, 0.0078, 0, 0.66...
[ "\"\"\"\n DataSource is a wrapper for the OGR Data Source object, which provides\n an interface for reading vector geometry data from many different file\n formats (including ESRI shapefiles).\n\n When instantiating a DataSource object, use the filename of a\n GDAL-supported data source. For example, a SHP file or...
""" This module houses the OGR & SRS Exception objects, and the check_err() routine which checks the status code returned by OGR methods. """ #### OGR & SRS Exceptions #### class GDALException(Exception): pass class OGRException(Exception): pass class SRSException(Exception): pass class OGRIndexError(OGRException, KeyError): """ This exception is raised when an invalid index is encountered, and has the 'silent_variable_feature' attribute set to true. This ensures that django's templates proceed to use the next lookup type gracefully when an Exception is raised. Fixes ticket #4740. """ silent_variable_failure = True #### OGR error checking codes and routine #### # OGR Error Codes OGRERR_DICT = { 1 : (OGRException, 'Not enough data.'), 2 : (OGRException, 'Not enough memory.'), 3 : (OGRException, 'Unsupported geometry type.'), 4 : (OGRException, 'Unsupported operation.'), 5 : (OGRException, 'Corrupt data.'), 6 : (OGRException, 'OGR failure.'), 7 : (SRSException, 'Unsupported SRS.'), 8 : (OGRException, 'Invalid handle.'), } OGRERR_NONE = 0 def check_err(code): "Checks the given OGRERR, and raises an exception where appropriate." if code == OGRERR_NONE: return elif code in OGRERR_DICT: e, msg = OGRERR_DICT[code] raise e, msg else: raise OGRException('Unknown error code: "%s"' % code)
[ [ 8, 0, 0.0732, 0.122, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.1707, 0.0244, 0, 0.66, 0.1429, 355, 0, 0, 0, 0, 645, 0, 0 ], [ 3, 0, 0.1951, 0.0244, 0, 0.66,...
[ "\"\"\"\n This module houses the OGR & SRS Exception objects, and the\n check_err() routine which checks the status code returned by\n OGR methods.\n\"\"\"", "class GDALException(Exception): pass", "class OGRException(Exception): pass", "class SRSException(Exception): pass", "class OGRIndexError(OGRExceptio...
from ctypes import byref, c_int from datetime import date, datetime, time from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.prototypes import ds as capi # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_Fld_* routines are relevant here. class Field(GDALBase): "A class that wraps an OGR Field, needs to be instantiated from a Feature object." #### Python 'magic' routines #### def __init__(self, feat, index): """ Initializes on the feature pointer and the integer index of the field within the feature. """ # Setting the feature pointer and index. self._feat = feat self._index = index # Getting the pointer for this field. fld_ptr = capi.get_feat_field_defn(feat, index) if not fld_ptr: raise OGRException('Cannot create OGR Field, invalid pointer given.') self.ptr = fld_ptr # Setting the class depending upon the OGR Field Type (OFT) self.__class__ = OGRFieldTypes[self.type] # OFTReal with no precision should be an OFTInteger. if isinstance(self, OFTReal) and self.precision == 0: self.__class__ = OFTInteger def __str__(self): "Returns the string representation of the Field." return str(self.value).strip() #### Field Methods #### def as_double(self): "Retrieves the Field's value as a double (float)." return capi.get_field_as_double(self._feat, self._index) def as_int(self): "Retrieves the Field's value as an integer." return capi.get_field_as_integer(self._feat, self._index) def as_string(self): "Retrieves the Field's value as a string." return capi.get_field_as_string(self._feat, self._index) def as_datetime(self): "Retrieves the Field's value as a tuple of date & time components." yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)] status = capi.get_field_as_datetime(self._feat, self._index, byref(yy), byref(mm), byref(dd), byref(hh), byref(mn), byref(ss), byref(tz)) if status: return (yy, mm, dd, hh, mn, ss, tz) else: raise OGRException('Unable to retrieve date & time information from the field.') #### Field Properties #### @property def name(self): "Returns the name of this Field." return capi.get_field_name(self.ptr) @property def precision(self): "Returns the precision of this Field." return capi.get_field_precision(self.ptr) @property def type(self): "Returns the OGR type of this Field." return capi.get_field_type(self.ptr) @property def type_name(self): "Return the OGR field type name for this Field." return capi.get_field_type_name(self.type) @property def value(self): "Returns the value of this Field." # Default is to get the field as a string. return self.as_string() @property def width(self): "Returns the width of this Field." return capi.get_field_width(self.ptr) ### The Field sub-classes for each OGR Field type. ### class OFTInteger(Field): @property def value(self): "Returns an integer contained in this field." return self.as_int() @property def type(self): """ GDAL uses OFTReals to represent OFTIntegers in created shapefiles -- forcing the type here since the underlying field type may actually be OFTReal. """ return 0 class OFTReal(Field): @property def value(self): "Returns a float contained in this field." return self.as_double() # String & Binary fields, just subclasses class OFTString(Field): pass class OFTWideString(Field): pass class OFTBinary(Field): pass # OFTDate, OFTTime, OFTDateTime fields. class OFTDate(Field): @property def value(self): "Returns a Python `date` object for the OFTDate field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return date(yy.value, mm.value, dd.value) except (ValueError, OGRException): return None class OFTDateTime(Field): @property def value(self): "Returns a Python `datetime` object for this OFTDateTime field." # TODO: Adapt timezone information. # See http://lists.maptools.org/pipermail/gdal-dev/2006-February/007990.html # The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous), # 100=GMT, 104=GMT+1, 80=GMT-5, etc. try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return datetime(yy.value, mm.value, dd.value, hh.value, mn.value, ss.value) except (ValueError, OGRException): return None class OFTTime(Field): @property def value(self): "Returns a Python `time` object for this OFTTime field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return time(hh.value, mn.value, ss.value) except (ValueError, OGRException): return None # List fields are also just subclasses class OFTIntegerList(Field): pass class OFTRealList(Field): pass class OFTStringList(Field): pass class OFTWideStringList(Field): pass # Class mapping dictionary for OFT Types and reverse mapping. OGRFieldTypes = { 0 : OFTInteger, 1 : OFTIntegerList, 2 : OFTReal, 3 : OFTRealList, 4 : OFTString, 5 : OFTStringList, 6 : OFTWideString, 7 : OFTWideStringList, 8 : OFTBinary, 9 : OFTDate, 10 : OFTTime, 11 : OFTDateTime, } ROGRFieldTypes = dict([(cls, num) for num, cls in OGRFieldTypes.items()])
[ [ 1, 0, 0.0056, 0.0056, 0, 0.66, 0, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0112, 0.0056, 0, 0.66, 0.0526, 426, 0, 3, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0169, 0.0056, 0, ...
[ "from ctypes import byref, c_int", "from datetime import date, datetime, time", "from django.contrib.gis.gdal.base import GDALBase", "from django.contrib.gis.gdal.error import OGRException", "from django.contrib.gis.gdal.prototypes import ds as capi", "class Field(GDALBase):\n \"A class that wraps an O...
# Needed ctypes routines from ctypes import c_double, byref # Other GDAL imports. from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.feature import Feature from django.contrib.gis.gdal.field import OGRFieldTypes from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.geometries import OGRGeometry from django.contrib.gis.gdal.srs import SpatialReference # GDAL ctypes function prototypes. from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api, srs as srs_api # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_L_* routines are relevant here. class Layer(GDALBase): "A class that wraps an OGR Layer, needs to be instantiated from a DataSource object." #### Python 'magic' routines #### def __init__(self, layer_ptr, ds): """ Initializes on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise OGRException('Cannot create Layer, invalid pointer given') self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability('RandomRead') def __getitem__(self, index): "Gets the Feature at the specified index." if isinstance(index, (int, long)): # An integer index was given -- we cannot do a check based on the # number of features because the beginning and ending feature IDs # are not guaranteed to be 0 and len(layer)-1, respectively. if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.') return self._make_feature(index) elif isinstance(index, slice): # A slice was given start, stop, stride = index.indices(self.num_feat) return [self._make_feature(fid) for fid in xrange(start, stop, stride)] else: raise TypeError('Integers and slices may only be used when indexing OGR Layers.') def __iter__(self): "Iterates over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) for i in xrange(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self._ldefn) def __len__(self): "The length is the number of features." return self.num_feat def __str__(self): "The string name of the layer." return self.name def _make_feature(self, feat_id): """ Helper routine for __getitem__ that constructs a Feature from the given Feature ID. If the OGR Layer does not support random-access reading, then each feature of the layer will be incremented through until the a Feature is found matching the given feature ID. """ if self._random_read: # If the Layer supports random reading, return. try: return Feature(capi.get_feature(self.ptr, feat_id), self._ldefn) except OGRException: pass else: # Random access isn't supported, have to increment through # each feature until the given feature ID is encountered. for feat in self: if feat.fid == feat_id: return feat # Should have returned a Feature, raise an OGRIndexError. raise OGRIndexError('Invalid feature id: %s.' % feat_id) #### Layer properties #### @property def extent(self): "Returns the extent (an Envelope) of this layer." env = OGREnvelope() capi.get_extent(self.ptr, byref(env), 1) return Envelope(env) @property def name(self): "Returns the name of this layer in the Data Source." return capi.get_fd_name(self._ldefn) @property def num_feat(self, force=1): "Returns the number of features in the Layer." return capi.get_feature_count(self.ptr, force) @property def num_fields(self): "Returns the number of fields in the Layer." return capi.get_field_count(self._ldefn) @property def geom_type(self): "Returns the geometry type (OGRGeomType) of the Layer." return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) @property def srs(self): "Returns the Spatial Reference used in this Layer." try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None @property def fields(self): """ Returns a list of string names corresponding to each of the Fields available in this Layer. """ return [capi.get_field_name(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields) ] @property def field_types(self): """ Returns a list of the types of fields in this Layer. For example, the list [OFTInteger, OFTReal, OFTString] would be returned for an OGR layer that had an integer, a floating-point, and string fields. """ return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in xrange(self.num_fields)] @property def field_widths(self): "Returns a list of the maximum field widths for the features." return [capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)] @property def field_precisions(self): "Returns the field precisions for the features." return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in xrange(self.num_fields)] def _get_spatial_filter(self): try: return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr))) except OGRException: return None def _set_spatial_filter(self, filter): if isinstance(filter, OGRGeometry): capi.set_spatial_filter(self.ptr, filter.ptr) elif isinstance(filter, (tuple, list)): if not len(filter) == 4: raise ValueError('Spatial filter list/tuple must have 4 elements.') # Map c_double onto params -- if a bad type is passed in it # will be caught here. xmin, ymin, xmax, ymax = map(c_double, filter) capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax) elif filter is None: capi.set_spatial_filter(self.ptr, None) else: raise TypeError('Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None.') spatial_filter = property(_get_spatial_filter, _set_spatial_filter) #### Layer Methods #### def get_fields(self, field_name): """ Returns a list containing the given field name for every Feature in the Layer. """ if not field_name in self.fields: raise OGRException('invalid field name: %s' % field_name) return [feat.get(field_name) for feat in self] def get_geoms(self, geos=False): """ Returns a list containing the OGRGeometry for every Feature in the Layer. """ if geos: from django.contrib.gis.geos import GEOSGeometry return [GEOSGeometry(feat.geom.wkb) for feat in self] else: return [feat.geom for feat in self] def test_capability(self, capability): """ Returns a bool indicating whether the this Layer supports the given capability (a string). Valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'. """ return bool(capi.test_capability(self.ptr, capability))
[ [ 1, 0, 0.0094, 0.0047, 0, 0.66, 0, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0236, 0.0047, 0, 0.66, 0.1, 771, 0, 1, 0, 0, 771, 0, 0 ], [ 1, 0, 0.0283, 0.0047, 0, 0.6...
[ "from ctypes import c_double, byref", "from django.contrib.gis.gdal.base import GDALBase", "from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope", "from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException", "from django.contrib.gis.gdal.feature import Feature", "fr...
import re from datetime import date from ctypes import c_char, c_char_p, c_double, c_int, c_ubyte, c_void_p, POINTER from django.contrib.gis.gdal.envelope import OGREnvelope from django.contrib.gis.gdal.libgdal import lgdal, GEOJSON from django.contrib.gis.gdal.prototypes.errcheck import check_bool, check_envelope from django.contrib.gis.gdal.prototypes.generation import \ const_string_output, double_output, geom_output, int_output, \ srs_output, string_output, void_output ### Generation routines specific to this module ### def env_func(f, argtypes): "For getting OGREnvelopes." f.argtypes = argtypes f.restype = None f.errcheck = check_envelope return f def pnt_func(f): "For accessing point information." return double_output(f, [c_void_p, c_int]) def topology_func(f): f.argtypes = [c_void_p, c_void_p] f.restype = c_int f.errchck = check_bool return f ### OGR_G ctypes function prototypes ### # GeoJSON routines, if supported. if GEOJSON: from_json = geom_output(lgdal.OGR_G_CreateGeometryFromJson, [c_char_p]) to_json = string_output(lgdal.OGR_G_ExportToJson, [c_void_p], str_result=True) to_kml = string_output(lgdal.OGR_G_ExportToKML, [c_void_p, c_char_p], str_result=True) else: from_json = False to_json = False to_kml = False # GetX, GetY, GetZ all return doubles. getx = pnt_func(lgdal.OGR_G_GetX) gety = pnt_func(lgdal.OGR_G_GetY) getz = pnt_func(lgdal.OGR_G_GetZ) # Geometry creation routines. from_wkb = geom_output(lgdal.OGR_G_CreateFromWkb, [c_char_p, c_void_p, POINTER(c_void_p), c_int], offset=-2) from_wkt = geom_output(lgdal.OGR_G_CreateFromWkt, [POINTER(c_char_p), c_void_p, POINTER(c_void_p)], offset=-1) create_geom = geom_output(lgdal.OGR_G_CreateGeometry, [c_int]) clone_geom = geom_output(lgdal.OGR_G_Clone, [c_void_p]) get_geom_ref = geom_output(lgdal.OGR_G_GetGeometryRef, [c_void_p, c_int]) get_boundary = geom_output(lgdal.OGR_G_GetBoundary, [c_void_p]) geom_convex_hull = geom_output(lgdal.OGR_G_ConvexHull, [c_void_p]) geom_diff = geom_output(lgdal.OGR_G_Difference, [c_void_p, c_void_p]) geom_intersection = geom_output(lgdal.OGR_G_Intersection, [c_void_p, c_void_p]) geom_sym_diff = geom_output(lgdal.OGR_G_SymmetricDifference, [c_void_p, c_void_p]) geom_union = geom_output(lgdal.OGR_G_Union, [c_void_p, c_void_p]) # Geometry modification routines. add_geom = void_output(lgdal.OGR_G_AddGeometry, [c_void_p, c_void_p]) import_wkt = void_output(lgdal.OGR_G_ImportFromWkt, [c_void_p, POINTER(c_char_p)]) # Destroys a geometry destroy_geom = void_output(lgdal.OGR_G_DestroyGeometry, [c_void_p], errcheck=False) # Geometry export routines. to_wkb = void_output(lgdal.OGR_G_ExportToWkb, None, errcheck=True) # special handling for WKB. to_wkt = string_output(lgdal.OGR_G_ExportToWkt, [c_void_p, POINTER(c_char_p)]) to_gml = string_output(lgdal.OGR_G_ExportToGML, [c_void_p], str_result=True) get_wkbsize = int_output(lgdal.OGR_G_WkbSize, [c_void_p]) # Geometry spatial-reference related routines. assign_srs = void_output(lgdal.OGR_G_AssignSpatialReference, [c_void_p, c_void_p], errcheck=False) get_geom_srs = srs_output(lgdal.OGR_G_GetSpatialReference, [c_void_p]) # Geometry properties get_area = double_output(lgdal.OGR_G_GetArea, [c_void_p]) get_centroid = void_output(lgdal.OGR_G_Centroid, [c_void_p, c_void_p]) get_dims = int_output(lgdal.OGR_G_GetDimension, [c_void_p]) get_coord_dim = int_output(lgdal.OGR_G_GetCoordinateDimension, [c_void_p]) set_coord_dim = void_output(lgdal.OGR_G_SetCoordinateDimension, [c_void_p, c_int], errcheck=False) get_geom_count = int_output(lgdal.OGR_G_GetGeometryCount, [c_void_p]) get_geom_name = const_string_output(lgdal.OGR_G_GetGeometryName, [c_void_p]) get_geom_type = int_output(lgdal.OGR_G_GetGeometryType, [c_void_p]) get_point_count = int_output(lgdal.OGR_G_GetPointCount, [c_void_p]) get_point = void_output(lgdal.OGR_G_GetPoint, [c_void_p, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double)], errcheck=False) geom_close_rings = void_output(lgdal.OGR_G_CloseRings, [c_void_p], errcheck=False) # Topology routines. ogr_contains = topology_func(lgdal.OGR_G_Contains) ogr_crosses = topology_func(lgdal.OGR_G_Crosses) ogr_disjoint = topology_func(lgdal.OGR_G_Disjoint) ogr_equals = topology_func(lgdal.OGR_G_Equals) ogr_intersects = topology_func(lgdal.OGR_G_Intersects) ogr_overlaps = topology_func(lgdal.OGR_G_Overlaps) ogr_touches = topology_func(lgdal.OGR_G_Touches) ogr_within = topology_func(lgdal.OGR_G_Within) # Transformation routines. geom_transform = void_output(lgdal.OGR_G_Transform, [c_void_p, c_void_p]) geom_transform_to = void_output(lgdal.OGR_G_TransformTo, [c_void_p, c_void_p]) # For retrieving the envelope of the geometry. get_envelope = env_func(lgdal.OGR_G_GetEnvelope, [c_void_p, POINTER(OGREnvelope)])
[ [ 1, 0, 0.0094, 0.0094, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0189, 0.0094, 0, 0.66, 0.0182, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0283, 0.0094, 0, ...
[ "import re", "from datetime import date", "from ctypes import c_char, c_char_p, c_double, c_int, c_ubyte, c_void_p, POINTER", "from django.contrib.gis.gdal.envelope import OGREnvelope", "from django.contrib.gis.gdal.libgdal import lgdal, GEOJSON", "from django.contrib.gis.gdal.prototypes.errcheck import c...
""" This module houses the error-checking routines used by the GDAL ctypes prototypes. """ from ctypes import c_void_p, string_at from django.contrib.gis.gdal.error import check_err, OGRException, SRSException from django.contrib.gis.gdal.libgdal import lgdal # Helper routines for retrieving pointers and/or values from # arguments passed in by reference. def arg_byref(args, offset=-1): "Returns the pointer argument's by-refernece value." return args[offset]._obj.value def ptr_byref(args, offset=-1): "Returns the pointer argument passed in by-reference." return args[offset]._obj def check_bool(result, func, cargs): "Returns the boolean evaluation of the value." if bool(result): return True else: return False ### String checking Routines ### def check_const_string(result, func, cargs, offset=None): """ Similar functionality to `check_string`, but does not free the pointer. """ if offset: check_err(result) ptr = ptr_byref(cargs, offset) return ptr.value else: return result def check_string(result, func, cargs, offset=-1, str_result=False): """ Checks the string output returned from the given function, and frees the string pointer allocated by OGR. The `str_result` keyword may be used when the result is the string pointer, otherwise the OGR error code is assumed. The `offset` keyword may be used to extract the string pointer passed in by-reference at the given slice offset in the function arguments. """ if str_result: # For routines that return a string. ptr = result if not ptr: s = None else: s = string_at(result) else: # Error-code return specified. check_err(result) ptr = ptr_byref(cargs, offset) # Getting the string value s = ptr.value # Correctly freeing the allocated memory beind GDAL pointer # w/the VSIFree routine. if ptr: lgdal.VSIFree(ptr) return s ### DataSource, Layer error-checking ### ### Envelope checking ### def check_envelope(result, func, cargs, offset=-1): "Checks a function that returns an OGR Envelope by reference." env = ptr_byref(cargs, offset) return env ### Geometry error-checking routines ### def check_geom(result, func, cargs): "Checks a function that returns a geometry." # OGR_G_Clone may return an integer, even though the # restype is set to c_void_p if isinstance(result, (int, long)): result = c_void_p(result) if not result: raise OGRException('Invalid geometry pointer returned from "%s".' % func.__name__) return result def check_geom_offset(result, func, cargs, offset=-1): "Chcks the geometry at the given offset in the C parameter list." check_err(result) geom = ptr_byref(cargs, offset=offset) return check_geom(geom, func, cargs) ### Spatial Reference error-checking routines ### def check_srs(result, func, cargs): if isinstance(result, (int, long)): result = c_void_p(result) if not result: raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__) return result ### Other error-checking routines ### def check_arg_errcode(result, func, cargs): """ The error code is returned in the last argument, by reference. Check its value with `check_err` before returning the result. """ check_err(arg_byref(cargs)) return result def check_errcode(result, func, cargs): """ Check the error code returned (c_int). """ check_err(result) return def check_pointer(result, func, cargs): "Makes sure the result pointer is valid." if isinstance(result, (int, long)): result = c_void_p(result) if bool(result): return result else: raise OGRException('Invalid pointer returned from "%s"' % func.__name__) def check_str_arg(result, func, cargs): """ This is for the OSRGet[Angular|Linear]Units functions, which require that the returned string pointer not be freed. This returns both the double and tring values. """ dbl = result ptr = cargs[-1]._obj return dbl, ptr.value
[ [ 8, 0, 0.0197, 0.0315, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0394, 0.0079, 0, 0.66, 0.0625, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0472, 0.0079, 0, 0.66...
[ "\"\"\"\n This module houses the error-checking routines used by the GDAL\n ctypes prototypes.\n\"\"\"", "from ctypes import c_void_p, string_at", "from django.contrib.gis.gdal.error import check_err, OGRException, SRSException", "from django.contrib.gis.gdal.libgdal import lgdal", "def arg_byref(args, offs...
""" This module houses the ctypes function prototypes for OGR DataSource related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, OGR_Fld_* routines are relevant here. """ from ctypes import c_char_p, c_double, c_int, c_long, c_void_p, POINTER from django.contrib.gis.gdal.envelope import OGREnvelope from django.contrib.gis.gdal.libgdal import lgdal from django.contrib.gis.gdal.prototypes.generation import \ const_string_output, double_output, geom_output, int_output, \ srs_output, void_output, voidptr_output c_int_p = POINTER(c_int) # shortcut type ### Driver Routines ### register_all = void_output(lgdal.OGRRegisterAll, [], errcheck=False) cleanup_all = void_output(lgdal.OGRCleanupAll, [], errcheck=False) get_driver = voidptr_output(lgdal.OGRGetDriver, [c_int]) get_driver_by_name = voidptr_output(lgdal.OGRGetDriverByName, [c_char_p]) get_driver_count = int_output(lgdal.OGRGetDriverCount, []) get_driver_name = const_string_output(lgdal.OGR_Dr_GetName, [c_void_p]) ### DataSource ### open_ds = voidptr_output(lgdal.OGROpen, [c_char_p, c_int, POINTER(c_void_p)]) destroy_ds = void_output(lgdal.OGR_DS_Destroy, [c_void_p], errcheck=False) release_ds = void_output(lgdal.OGRReleaseDataSource, [c_void_p]) get_ds_name = const_string_output(lgdal.OGR_DS_GetName, [c_void_p]) get_layer = voidptr_output(lgdal.OGR_DS_GetLayer, [c_void_p, c_int]) get_layer_by_name = voidptr_output(lgdal.OGR_DS_GetLayerByName, [c_void_p, c_char_p]) get_layer_count = int_output(lgdal.OGR_DS_GetLayerCount, [c_void_p]) ### Layer Routines ### get_extent = void_output(lgdal.OGR_L_GetExtent, [c_void_p, POINTER(OGREnvelope), c_int]) get_feature = voidptr_output(lgdal.OGR_L_GetFeature, [c_void_p, c_long]) get_feature_count = int_output(lgdal.OGR_L_GetFeatureCount, [c_void_p, c_int]) get_layer_defn = voidptr_output(lgdal.OGR_L_GetLayerDefn, [c_void_p]) get_layer_srs = srs_output(lgdal.OGR_L_GetSpatialRef, [c_void_p]) get_next_feature = voidptr_output(lgdal.OGR_L_GetNextFeature, [c_void_p]) reset_reading = void_output(lgdal.OGR_L_ResetReading, [c_void_p], errcheck=False) test_capability = int_output(lgdal.OGR_L_TestCapability, [c_void_p, c_char_p]) get_spatial_filter = geom_output(lgdal.OGR_L_GetSpatialFilter, [c_void_p]) set_spatial_filter = void_output(lgdal.OGR_L_SetSpatialFilter, [c_void_p, c_void_p], errcheck=False) set_spatial_filter_rect = void_output(lgdal.OGR_L_SetSpatialFilterRect, [c_void_p, c_double, c_double, c_double, c_double], errcheck=False) ### Feature Definition Routines ### get_fd_geom_type = int_output(lgdal.OGR_FD_GetGeomType, [c_void_p]) get_fd_name = const_string_output(lgdal.OGR_FD_GetName, [c_void_p]) get_feat_name = const_string_output(lgdal.OGR_FD_GetName, [c_void_p]) get_field_count = int_output(lgdal.OGR_FD_GetFieldCount, [c_void_p]) get_field_defn = voidptr_output(lgdal.OGR_FD_GetFieldDefn, [c_void_p, c_int]) ### Feature Routines ### clone_feature = voidptr_output(lgdal.OGR_F_Clone, [c_void_p]) destroy_feature = void_output(lgdal.OGR_F_Destroy, [c_void_p], errcheck=False) feature_equal = int_output(lgdal.OGR_F_Equal, [c_void_p, c_void_p]) get_feat_geom_ref = geom_output(lgdal.OGR_F_GetGeometryRef, [c_void_p]) get_feat_field_count = int_output(lgdal.OGR_F_GetFieldCount, [c_void_p]) get_feat_field_defn = voidptr_output(lgdal.OGR_F_GetFieldDefnRef, [c_void_p, c_int]) get_fid = int_output(lgdal.OGR_F_GetFID, [c_void_p]) get_field_as_datetime = int_output(lgdal.OGR_F_GetFieldAsDateTime, [c_void_p, c_int, c_int_p, c_int_p, c_int_p, c_int_p, c_int_p, c_int_p]) get_field_as_double = double_output(lgdal.OGR_F_GetFieldAsDouble, [c_void_p, c_int]) get_field_as_integer = int_output(lgdal.OGR_F_GetFieldAsInteger, [c_void_p, c_int]) get_field_as_string = const_string_output(lgdal.OGR_F_GetFieldAsString, [c_void_p, c_int]) get_field_index = int_output(lgdal.OGR_F_GetFieldIndex, [c_void_p, c_char_p]) ### Field Routines ### get_field_name = const_string_output(lgdal.OGR_Fld_GetNameRef, [c_void_p]) get_field_precision = int_output(lgdal.OGR_Fld_GetPrecision, [c_void_p]) get_field_type = int_output(lgdal.OGR_Fld_GetType, [c_void_p]) get_field_type_name = const_string_output(lgdal.OGR_GetFieldTypeName, [c_int]) get_field_width = int_output(lgdal.OGR_Fld_GetWidth, [c_void_p])
[ [ 8, 0, 0.0423, 0.0704, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0845, 0.0141, 0, 0.66, 0.0196, 182, 0, 6, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0986, 0.0141, 0, 0.66...
[ "\"\"\"\n This module houses the ctypes function prototypes for OGR DataSource\n related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, \n OGR_Fld_* routines are relevant here.\n\"\"\"", "from ctypes import c_char_p, c_double, c_int, c_long, c_void_p, POINTER", "from django.contrib.gis.gdal.envelope imp...
""" This module contains functions that generate ctypes prototypes for the GDAL routines. """ from ctypes import c_char_p, c_double, c_int, c_void_p from django.contrib.gis.gdal.prototypes.errcheck import \ check_arg_errcode, check_errcode, check_geom, check_geom_offset, \ check_pointer, check_srs, check_str_arg, check_string, check_const_string class gdal_char_p(c_char_p): pass def double_output(func, argtypes, errcheck=False, strarg=False): "Generates a ctypes function that returns a double value." func.argtypes = argtypes func.restype = c_double if errcheck: func.errcheck = check_arg_errcode if strarg: func.errcheck = check_str_arg return func def geom_output(func, argtypes, offset=None): """ Generates a function that returns a Geometry either by reference or directly (if the return_geom keyword is set to True). """ # Setting the argument types func.argtypes = argtypes if not offset: # When a geometry pointer is directly returned. func.restype = c_void_p func.errcheck = check_geom else: # Error code returned, geometry is returned by-reference. func.restype = c_int def geomerrcheck(result, func, cargs): return check_geom_offset(result, func, cargs, offset) func.errcheck = geomerrcheck return func def int_output(func, argtypes): "Generates a ctypes function that returns an integer value." func.argtypes = argtypes func.restype = c_int return func def srs_output(func, argtypes): """ Generates a ctypes prototype for the given function with the given C arguments that returns a pointer to an OGR Spatial Reference System. """ func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_srs return func def const_string_output(func, argtypes, offset=None): func.argtypes = argtypes if offset: func.restype = c_int else: func.restype = c_char_p def _check_const(result, func, cargs): return check_const_string(result, func, cargs, offset=offset) func.errcheck = _check_const return func def string_output(func, argtypes, offset=-1, str_result=False): """ Generates a ctypes prototype for the given function with the given argument types that returns a string from a GDAL pointer. The `const` flag indicates whether the allocated pointer should be freed via the GDAL library routine VSIFree -- but only applies only when `str_result` is True. """ func.argtypes = argtypes if str_result: # Use subclass of c_char_p so the error checking routine # can free the memory at the pointer's address. func.restype = gdal_char_p else: # Error code is returned func.restype = c_int # Dynamically defining our error-checking function with the # given offset. def _check_str(result, func, cargs): return check_string(result, func, cargs, offset=offset, str_result=str_result) func.errcheck = _check_str return func def void_output(func, argtypes, errcheck=True): """ For functions that don't only return an error code that needs to be examined. """ if argtypes: func.argtypes = argtypes if errcheck: # `errcheck` keyword may be set to False for routines that # return void, rather than a status code. func.restype = c_int func.errcheck = check_errcode else: func.restype = None return func def voidptr_output(func, argtypes): "For functions that return c_void_p." func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_pointer return func
[ [ 8, 0, 0.021, 0.0336, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0504, 0.0084, 0, 0.66, 0.0909, 182, 0, 4, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0672, 0.0252, 0, 0.66,...
[ "\"\"\"\n This module contains functions that generate ctypes prototypes for the\n GDAL routines.\n\"\"\"", "from ctypes import c_char_p, c_double, c_int, c_void_p", "from django.contrib.gis.gdal.prototypes.errcheck import \\\n check_arg_errcode, check_errcode, check_geom, check_geom_offset, \\\n check_po...
from ctypes import c_char_p, c_int, c_void_p, POINTER from django.contrib.gis.gdal.libgdal import lgdal, std_call from django.contrib.gis.gdal.prototypes.generation import \ const_string_output, double_output, int_output, \ srs_output, string_output, void_output ## Shortcut generation for routines with known parameters. def srs_double(f): """ Creates a function prototype for the OSR routines that take the OSRSpatialReference object and """ return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True) def units_func(f): """ Creates a ctypes function prototype for OSR units functions, e.g., OSRGetAngularUnits, OSRGetLinearUnits. """ return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True) # Creation & destruction. clone_srs = srs_output(std_call('OSRClone'), [c_void_p]) new_srs = srs_output(std_call('OSRNewSpatialReference'), [c_char_p]) release_srs = void_output(lgdal.OSRRelease, [c_void_p], errcheck=False) destroy_srs = void_output(std_call('OSRDestroySpatialReference'), [c_void_p], errcheck=False) srs_validate = void_output(lgdal.OSRValidate, [c_void_p]) # Getting the semi_major, semi_minor, and flattening functions. semi_major = srs_double(lgdal.OSRGetSemiMajor) semi_minor = srs_double(lgdal.OSRGetSemiMinor) invflattening = srs_double(lgdal.OSRGetInvFlattening) # WKT, PROJ, EPSG, XML importation routines. from_wkt = void_output(lgdal.OSRImportFromWkt, [c_void_p, POINTER(c_char_p)]) from_proj = void_output(lgdal.OSRImportFromProj4, [c_void_p, c_char_p]) from_epsg = void_output(std_call('OSRImportFromEPSG'), [c_void_p, c_int]) from_xml = void_output(lgdal.OSRImportFromXML, [c_void_p, c_char_p]) from_user_input = void_output(std_call('OSRSetFromUserInput'), [c_void_p, c_char_p]) # Morphing to/from ESRI WKT. morph_to_esri = void_output(lgdal.OSRMorphToESRI, [c_void_p]) morph_from_esri = void_output(lgdal.OSRMorphFromESRI, [c_void_p]) # Identifying the EPSG identify_epsg = void_output(lgdal.OSRAutoIdentifyEPSG, [c_void_p]) # Getting the angular_units, linear_units functions linear_units = units_func(lgdal.OSRGetLinearUnits) angular_units = units_func(lgdal.OSRGetAngularUnits) # For exporting to WKT, PROJ.4, "Pretty" WKT, and XML. to_wkt = string_output(std_call('OSRExportToWkt'), [c_void_p, POINTER(c_char_p)]) to_proj = string_output(std_call('OSRExportToProj4'), [c_void_p, POINTER(c_char_p)]) to_pretty_wkt = string_output(std_call('OSRExportToPrettyWkt'), [c_void_p, POINTER(c_char_p), c_int], offset=-2) # Memory leak fixed in GDAL 1.5; still exists in 1.4. to_xml = string_output(lgdal.OSRExportToXML, [c_void_p, POINTER(c_char_p), c_char_p], offset=-2) # String attribute retrival routines. get_attr_value = const_string_output(std_call('OSRGetAttrValue'), [c_void_p, c_char_p, c_int]) get_auth_name = const_string_output(lgdal.OSRGetAuthorityName, [c_void_p, c_char_p]) get_auth_code = const_string_output(lgdal.OSRGetAuthorityCode, [c_void_p, c_char_p]) # SRS Properties isgeographic = int_output(lgdal.OSRIsGeographic, [c_void_p]) islocal = int_output(lgdal.OSRIsLocal, [c_void_p]) isprojected = int_output(lgdal.OSRIsProjected, [c_void_p]) # Coordinate transformation new_ct= srs_output(std_call('OCTNewCoordinateTransformation'), [c_void_p, c_void_p]) destroy_ct = void_output(std_call('OCTDestroyCoordinateTransformation'), [c_void_p], errcheck=False)
[ [ 1, 0, 0.0139, 0.0139, 0, 0.66, 0, 182, 0, 4, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0278, 0.0139, 0, 0.66, 0.0294, 460, 0, 2, 0, 0, 460, 0, 0 ], [ 1, 0, 0.0556, 0.0417, 0, ...
[ "from ctypes import c_char_p, c_int, c_void_p, POINTER", "from django.contrib.gis.gdal.libgdal import lgdal, std_call", "from django.contrib.gis.gdal.prototypes.generation import \\\n const_string_output, double_output, int_output, \\\n srs_output, string_output, void_output", "def srs_double(f):\n \...
from django.contrib.gis.gdal.error import OGRException #### OGRGeomType #### class OGRGeomType(object): "Encapulates OGR Geometry Types." wkb25bit = -2147483648 # Dictionary of acceptable OGRwkbGeometryType s and their string names. _types = {0 : 'Unknown', 1 : 'Point', 2 : 'LineString', 3 : 'Polygon', 4 : 'MultiPoint', 5 : 'MultiLineString', 6 : 'MultiPolygon', 7 : 'GeometryCollection', 100 : 'None', 101 : 'LinearRing', 1 + wkb25bit: 'Point25D', 2 + wkb25bit: 'LineString25D', 3 + wkb25bit: 'Polygon25D', 4 + wkb25bit: 'MultiPoint25D', 5 + wkb25bit : 'MultiLineString25D', 6 + wkb25bit : 'MultiPolygon25D', 7 + wkb25bit : 'GeometryCollection25D', } # Reverse type dictionary, keyed by lower-case of the name. _str_types = dict([(v.lower(), k) for k, v in _types.items()]) def __init__(self, type_input): "Figures out the correct OGR Type based upon the input." if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, basestring): type_input = type_input.lower() if type_input == 'geometry': type_input='unknown' num = self._str_types.get(type_input, None) if num is None: raise OGRException('Invalid OGR String Type "%s"' % type_input) elif isinstance(type_input, int): if not type_input in self._types: raise OGRException('Invalid OGR Integer Type: %d' % type_input) num = type_input else: raise TypeError('Invalid OGR input type given.') # Setting the OGR geometry type number. self.num = num def __str__(self): "Returns the value of the name property." return self.name def __eq__(self, other): """ Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer. """ if isinstance(other, OGRGeomType): return self.num == other.num elif isinstance(other, basestring): return self.name.lower() == other.lower() elif isinstance(other, int): return self.num == other else: return False def __ne__(self, other): return not (self == other) @property def name(self): "Returns a short-hand string form of the OGR Geometry type." return self._types[self.num] @property def django(self): "Returns the Django GeometryField for this OGR Type." s = self.name.replace('25D', '') if s in ('LinearRing', 'None'): return None elif s == 'Unknown': s = 'Geometry' return s + 'Field'
[ [ 1, 0, 0.0118, 0.0118, 0, 0.66, 0, 76, 0, 1, 0, 0, 76, 0, 0 ], [ 3, 0, 0.5235, 0.9647, 0, 0.66, 1, 85, 0, 6, 0, 0, 186, 0, 17 ], [ 8, 1, 0.0588, 0.0118, 1, 0.84, ...
[ "from django.contrib.gis.gdal.error import OGRException", "class OGRGeomType(object):\n \"Encapulates OGR Geometry Types.\"\n\n wkb25bit = -2147483648\n\n # Dictionary of acceptable OGRwkbGeometryType s and their string names.\n _types = {0 : 'Unknown',\n 1 : 'Point',", " \"Encapulat...
""" Module for executing all of the GDAL tests. None of these tests require the use of the database. """ from django.utils.unittest import TestSuite, TextTestRunner # Importing the GDAL test modules. import test_driver, test_ds, test_envelope, test_geom, test_srs test_suites = [test_driver.suite(), test_ds.suite(), test_envelope.suite(), test_geom.suite(), test_srs.suite(), ] def suite(): "Builds a test suite for the GDAL tests." s = TestSuite() map(s.addTest, test_suites) return s def run(verbosity=1): "Runs the GDAL tests." TextTestRunner(verbosity=verbosity).run(suite())
[ [ 8, 0, 0.1, 0.16, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.2, 0.04, 0, 0.66, 0.2, 270, 0, 2, 0, 0, 270, 0, 0 ], [ 1, 0, 0.32, 0.04, 0, 0.66, 0.4, 92...
[ "\"\"\"\nModule for executing all of the GDAL tests. None\nof these tests require the use of the database.\n\"\"\"", "from django.utils.unittest import TestSuite, TextTestRunner", "import test_driver, test_ds, test_envelope, test_geom, test_srs", "test_suites = [test_driver.suite(),\n test_ds.s...
# The GDAL C library, OGR exception, and the Field object from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import OGRException, OGRIndexError from django.contrib.gis.gdal.field import Field from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType from django.contrib.gis.gdal.srs import SpatialReference # ctypes function prototypes from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_F_* routines are relevant here. class Feature(GDALBase): "A class that wraps an OGR Feature, needs to be instantiated from a Layer object." #### Python 'magic' routines #### def __init__(self, feat, fdefn): "Initializes on the pointers for the feature and the layer definition." if not feat or not fdefn: raise OGRException('Cannot create OGR Feature, invalid pointer given.') self.ptr = feat self._fdefn = fdefn def __del__(self): "Releases a reference to this object." if self._ptr: capi.destroy_feature(self._ptr) def __getitem__(self, index): """ Gets the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a Field instance. """ if isinstance(index, basestring): i = self.index(index) else: if index < 0 or index > self.num_fields: raise OGRIndexError('index out of range') i = index return Field(self.ptr, i) def __iter__(self): "Iterates over each field in the Feature." for i in xrange(self.num_fields): yield self[i] def __len__(self): "Returns the count of fields in this feature." return self.num_fields def __str__(self): "The string name of the feature." return 'Feature FID %d in Layer<%s>' % (self.fid, self.layer_name) def __eq__(self, other): "Does equivalence testing on the features." return bool(capi.feature_equal(self.ptr, other._ptr)) #### Feature Properties #### @property def fid(self): "Returns the feature identifier." return capi.get_fid(self.ptr) @property def layer_name(self): "Returns the name of the layer for the feature." return capi.get_feat_name(self._fdefn) @property def num_fields(self): "Returns the number of fields in the Feature." return capi.get_feat_field_count(self.ptr) @property def fields(self): "Returns a list of fields in the Feature." return [capi.get_field_name(capi.get_field_defn(self._fdefn, i)) for i in xrange(self.num_fields)] @property def geom(self): "Returns the OGR Geometry for this Feature." # Retrieving the geometry pointer for the feature. geom_ptr = capi.get_feat_geom_ref(self.ptr) return OGRGeometry(geom_api.clone_geom(geom_ptr)) @property def geom_type(self): "Returns the OGR Geometry Type for this Feture." return OGRGeomType(capi.get_fd_geom_type(self._fdefn)) #### Feature Methods #### def get(self, field): """ Returns the value of the field, instead of an instance of the Field object. May take a string of the field name or a Field object as parameters. """ field_name = getattr(field, 'name', field) return self[field_name].value def index(self, field_name): "Returns the index of the given field name." i = capi.get_field_index(self.ptr, field_name) if i < 0: raise OGRIndexError('invalid OFT field name given: "%s"' % field_name) return i
[ [ 1, 0, 0.0182, 0.0091, 0, 0.66, 0, 771, 0, 1, 0, 0, 771, 0, 0 ], [ 1, 0, 0.0273, 0.0091, 0, 0.66, 0.1667, 76, 0, 2, 0, 0, 76, 0, 0 ], [ 1, 0, 0.0364, 0.0091, 0, 0....
[ "from django.contrib.gis.gdal.base import GDALBase", "from django.contrib.gis.gdal.error import OGRException, OGRIndexError", "from django.contrib.gis.gdal.field import Field", "from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType", "from django.contrib.gis.gdal.srs import SpatialReferenc...
""" The OGRGeometry is a wrapper for using the OGR Geometry class (see http://www.gdal.org/ogr/classOGRGeometry.html). OGRGeometry may be instantiated when reading geometries from OGR Data Sources (e.g. SHP files), or when given OGC WKT (a string). While the 'full' API is not present yet, the API is "pythonic" unlike the traditional and "next-generation" OGR Python bindings. One major advantage OGR Geometries have over their GEOS counterparts is support for spatial reference systems and their transformation. Example: >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)' >>> pnt = OGRGeometry(wkt1) >>> print pnt POINT (-90 30) >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84')) >>> mpnt.add(wkt1) >>> mpnt.add(wkt1) >>> print mpnt MULTIPOINT (-90 30,-90 30) >>> print mpnt.srs.name WGS 84 >>> print mpnt.srs.proj +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> mpnt.transform_to(SpatialReference('NAD27')) >>> print mpnt.proj +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs >>> print mpnt MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641) The OGRGeomType class is to make it easy to specify an OGR geometry type: >>> from django.contrib.gis.gdal import OGRGeomType >>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects True """ # Python library requisites. import sys from binascii import a2b_hex from ctypes import byref, string_at, c_char_p, c_double, c_ubyte, c_void_p # Getting GDAL prerequisites from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.libgdal import GEOJSON, GDAL_VERSION from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform # Getting the ctypes prototype functions that interface w/the GDAL C library. from django.contrib.gis.gdal.prototypes import geom as capi, srs as srs_api # For recognizing geometry input. from django.contrib.gis.geometry.regex import hex_regex, wkt_regex, json_regex # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_G_* routines are relevant here. #### OGRGeometry Class #### class OGRGeometry(GDALBase): "Generally encapsulates an OGR geometry." def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, basestring) # If HEX, unpack input to to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = buffer(a2b_hex(geom_input.upper())) str_instance = False # Constructing the geometry, if str_instance: # Checking if unicode if isinstance(geom_input, unicode): # Encoding to ASCII, WKT or HEX doesn't need any more. geom_input = geom_input.encode('ascii') wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt')))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt'))), None, byref(c_void_p())) elif json_m: if GEOJSON: g = capi.from_json(geom_input) else: raise NotImplementedError('GeoJSON input only supported on GDAL 1.5+.') else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, buffer): # WKB was passed in g = capi.from_wkb(str(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num] def __del__(self): "Deletes this Geometry." if self._ptr: capi.destroy_geom(self._ptr) # Pickle routines def __getstate__(self): srs = self.srs if srs: srs = srs.wkt else: srs = None return str(self.wkb), srs def __setstate__(self, state): wkb, srs = state ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb)) if not ptr: raise OGRException('Invalid OGRGeometry loaded from pickled state.') self.ptr = ptr self.srs = srs @classmethod def from_bbox(cls, bbox): "Constructs a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return OGRGeometry( 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % ( x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) ### Geometry set-like operations ### # g = g1 | g2 def __or__(self, other): "Returns the union of the two geometries." return self.union(other) # g = g1 & g2 def __and__(self, other): "Returns the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) def __eq__(self, other): "Is this Geometry equal to the other?" if isinstance(other, OGRGeometry): return self.equals(other) else: return False def __ne__(self, other): "Tests for inequality." return not (self == other) def __str__(self): "WKT is used for the string representation." return self.wkt #### Geometry Properties #### @property def dimension(self): "Returns 0 for points, 1 for lines, and 2 for surfaces." return capi.get_dims(self.ptr) def _get_coord_dim(self): "Returns the coordinate dimension of the Geometry." if isinstance(self, GeometryCollection) and GDAL_VERSION < (1, 5, 2): # On GDAL versions prior to 1.5.2, there exists a bug in which # the coordinate dimension of geometry collections is always 2: # http://trac.osgeo.org/gdal/ticket/2334 # Here we workaround by returning the coordinate dimension of the # first geometry in the collection instead. if len(self): return capi.get_coord_dim(capi.get_geom_ref(self.ptr, 0)) return capi.get_coord_dim(self.ptr) def _set_coord_dim(self, dim): "Sets the coordinate dimension of this Geometry." if not dim in (2, 3): raise ValueError('Geometry dimension must be either 2 or 3') capi.set_coord_dim(self.ptr, dim) coord_dim = property(_get_coord_dim, _set_coord_dim) @property def geom_count(self): "The number of elements in this Geometry." return capi.get_geom_count(self.ptr) @property def point_count(self): "Returns the number of Points in this Geometry." return capi.get_point_count(self.ptr) @property def num_points(self): "Alias for `point_count` (same name method in GEOS API.)" return self.point_count @property def num_coords(self): "Alais for `point_count`." return self.point_count @property def geom_type(self): "Returns the Type for this Geometry." return OGRGeomType(capi.get_geom_type(self.ptr)) @property def geom_name(self): "Returns the Name of this Geometry." return capi.get_geom_name(self.ptr) @property def area(self): "Returns the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise." return capi.get_area(self.ptr) @property def envelope(self): "Returns the envelope for this Geometry." # TODO: Fix Envelope() for Point geometries. return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope()))) @property def extent(self): "Returns the envelope as a 4-tuple, instead of as an Envelope object." return self.envelope.tuple #### SpatialReference-related Properties #### # The SRS property def _get_srs(self): "Returns the Spatial Reference for this Geometry." try: srs_ptr = capi.get_geom_srs(self.ptr) return SpatialReference(srs_api.clone_srs(srs_ptr)) except SRSException: return None def _set_srs(self, srs): "Sets the SpatialReference for this geometry." # Do not have to clone the `SpatialReference` object pointer because # when it is assigned to this `OGRGeometry` it's internal OGR # reference count is incremented, and will likewise be released # (decremented) when this geometry's destructor is called. if isinstance(srs, SpatialReference): srs_ptr = srs.ptr elif isinstance(srs, (int, long, basestring)): sr = SpatialReference(srs) srs_ptr = sr.ptr else: raise TypeError('Cannot assign spatial reference with object of type: %s' % type(srs)) capi.assign_srs(self.ptr, srs_ptr) srs = property(_get_srs, _set_srs) # The SRID property def _get_srid(self): srs = self.srs if srs: return srs.srid return None def _set_srid(self, srid): if isinstance(srid, (int, long)): self.srs = srid else: raise TypeError('SRID must be set with an integer.') srid = property(_get_srid, _set_srid) #### Output Methods #### @property def geos(self): "Returns a GEOSGeometry object from this OGRGeometry." from django.contrib.gis.geos import GEOSGeometry return GEOSGeometry(self.wkb, self.srid) @property def gml(self): "Returns the GML representation of the Geometry." return capi.to_gml(self.ptr) @property def hex(self): "Returns the hexadecimal representation of the WKB (a string)." return str(self.wkb).encode('hex').upper() #return b2a_hex(self.wkb).upper() @property def json(self): """ Returns the GeoJSON representation of this Geometry (requires GDAL 1.5+). """ if GEOJSON: return capi.to_json(self.ptr) else: raise NotImplementedError('GeoJSON output only supported on GDAL 1.5+.') geojson = json @property def kml(self): "Returns the KML representation of the Geometry." if GEOJSON: return capi.to_kml(self.ptr, None) else: raise NotImplementedError('KML output only supported on GDAL 1.5+.') @property def wkb_size(self): "Returns the size of the WKB buffer." return capi.get_wkbsize(self.ptr) @property def wkb(self): "Returns the WKB representation of the Geometry." if sys.byteorder == 'little': byteorder = 1 # wkbNDR (from ogr_core.h) else: byteorder = 0 # wkbXDR sz = self.wkb_size # Creating the unsigned character buffer, and passing it in by reference. buf = (c_ubyte * sz)() wkb = capi.to_wkb(self.ptr, byteorder, byref(buf)) # Returning a buffer of the string at the pointer. return buffer(string_at(buf, sz)) @property def wkt(self): "Returns the WKT representation of the Geometry." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def ewkt(self): "Returns the EWKT representation of the Geometry." srs = self.srs if srs and srs.srid: return 'SRID=%s;%s' % (srs.srid, self.wkt) else: return self.wkt #### Geometry Methods #### def clone(self): "Clones this OGR Geometry." return OGRGeometry(capi.clone_geom(self.ptr), self.srs) def close_rings(self): """ If there are any rings within this geometry that have not been closed, this routine will do so by adding the starting point at the end. """ # Closing the open rings. capi.geom_close_rings(self.ptr) def transform(self, coord_trans, clone=False): """ Transforms this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, string WKT or PROJ.4, and/or an integer SRID. By default nothing is returned and the geometry is transformed in-place. However, if the `clone` keyword is set, then a transformed clone of this geometry will be returned. """ if clone: klone = self.clone() klone.transform(coord_trans) return klone # Have to get the coordinate dimension of the original geometry # so it can be used to reset the transformed geometry's dimension # afterwards. This is done because of GDAL bug (in versions prior # to 1.7) that turns geometries 3D after transformation, see: # http://trac.osgeo.org/gdal/changeset/17792 if GDAL_VERSION < (1, 7): orig_dim = self.coord_dim # Depending on the input type, use the appropriate OGR routine # to perform the transformation. if isinstance(coord_trans, CoordTransform): capi.geom_transform(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, SpatialReference): capi.geom_transform_to(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, (int, long, basestring)): sr = SpatialReference(coord_trans) capi.geom_transform_to(self.ptr, sr.ptr) else: raise TypeError('Transform only accepts CoordTransform, ' 'SpatialReference, string, and integer objects.') # Setting with original dimension, see comment above. if GDAL_VERSION < (1, 7): if isinstance(self, GeometryCollection): # With geometry collections have to set dimension on # each internal geometry reference, as the collection # dimension isn't affected. for i in xrange(len(self)): internal_ptr = capi.get_geom_ref(self.ptr, i) if orig_dim != capi.get_coord_dim(internal_ptr): capi.set_coord_dim(internal_ptr, orig_dim) else: if self.coord_dim != orig_dim: self.coord_dim = orig_dim def transform_to(self, srs): "For backwards-compatibility." self.transform(srs) #### Topology Methods #### def _topology(self, func, other): """A generalized function for topology operations, takes a GDAL function and the other geometry to perform the operation on.""" if not isinstance(other, OGRGeometry): raise TypeError('Must use another OGRGeometry object for topology operations!') # Returning the output of the given function with the other geometry's # pointer. return func(self.ptr, other.ptr) def intersects(self, other): "Returns True if this geometry intersects with the other." return self._topology(capi.ogr_intersects, other) def equals(self, other): "Returns True if this geometry is equivalent to the other." return self._topology(capi.ogr_equals, other) def disjoint(self, other): "Returns True if this geometry and the other are spatially disjoint." return self._topology(capi.ogr_disjoint, other) def touches(self, other): "Returns True if this geometry touches the other." return self._topology(capi.ogr_touches, other) def crosses(self, other): "Returns True if this geometry crosses the other." return self._topology(capi.ogr_crosses, other) def within(self, other): "Returns True if this geometry is within the other." return self._topology(capi.ogr_within, other) def contains(self, other): "Returns True if this geometry contains the other." return self._topology(capi.ogr_contains, other) def overlaps(self, other): "Returns True if this geometry overlaps the other." return self._topology(capi.ogr_overlaps, other) #### Geometry-generation Methods #### def _geomgen(self, gen_func, other=None): "A helper routine for the OGR routines that generate geometries." if isinstance(other, OGRGeometry): return OGRGeometry(gen_func(self.ptr, other.ptr), self.srs) else: return OGRGeometry(gen_func(self.ptr), self.srs) @property def boundary(self): "Returns the boundary of this geometry." return self._geomgen(capi.get_boundary) @property def convex_hull(self): """ Returns the smallest convex Polygon that contains all the points in this Geometry. """ return self._geomgen(capi.geom_convex_hull) def difference(self, other): """ Returns a new geometry consisting of the region which is the difference of this geometry and the other. """ return self._geomgen(capi.geom_diff, other) def intersection(self, other): """ Returns a new geometry consisting of the region of intersection of this geometry and the other. """ return self._geomgen(capi.geom_intersection, other) def sym_difference(self, other): """ Returns a new geometry which is the symmetric difference of this geometry and the other. """ return self._geomgen(capi.geom_sym_diff, other) def union(self, other): """ Returns a new geometry consisting of the region which is the union of this geometry and the other. """ return self._geomgen(capi.geom_union, other) # The subclasses for OGR Geometry. class Point(OGRGeometry): @property def x(self): "Returns the X coordinate for this Point." return capi.getx(self.ptr, 0) @property def y(self): "Returns the Y coordinate for this Point." return capi.gety(self.ptr, 0) @property def z(self): "Returns the Z coordinate for this Point." if self.coord_dim == 3: return capi.getz(self.ptr, 0) @property def tuple(self): "Returns the tuple of this point." if self.coord_dim == 2: return (self.x, self.y) elif self.coord_dim == 3: return (self.x, self.y, self.z) coords = tuple class LineString(OGRGeometry): def __getitem__(self, index): "Returns the Point at the given index." if index >= 0 and index < self.point_count: x, y, z = c_double(), c_double(), c_double() capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) dim = self.coord_dim if dim == 1: return (x.value,) elif dim == 2: return (x.value, y.value) elif dim == 3: return (x.value, y.value, z.value) else: raise OGRIndexError('index out of range: %s' % str(index)) def __iter__(self): "Iterates over each point in the LineString." for i in xrange(self.point_count): yield self[i] def __len__(self): "The length returns the number of points in the LineString." return self.point_count @property def tuple(self): "Returns the tuple representation of this LineString." return tuple([self[i] for i in xrange(len(self))]) coords = tuple def _listarr(self, func): """ Internal routine that returns a sequence (list) corresponding with the given function. """ return [func(self.ptr, i) for i in xrange(len(self))] @property def x(self): "Returns the X coordinates in a list." return self._listarr(capi.getx) @property def y(self): "Returns the Y coordinates in a list." return self._listarr(capi.gety) @property def z(self): "Returns the Z coordinates in a list." if self.coord_dim == 3: return self._listarr(capi.getz) # LinearRings are used in Polygons. class LinearRing(LineString): pass class Polygon(OGRGeometry): def __len__(self): "The number of interior rings in this Polygon." return self.geom_count def __iter__(self): "Iterates through each ring in the Polygon." for i in xrange(self.geom_count): yield self[i] def __getitem__(self, index): "Gets the ring at the specified index." if index < 0 or index >= self.geom_count: raise OGRIndexError('index out of range: %s' % index) else: return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs) # Polygon Properties @property def shell(self): "Returns the shell of this Polygon." return self[0] # First ring is the shell exterior_ring = shell @property def tuple(self): "Returns a tuple of LinearRing coordinate tuples." return tuple([self[i].tuple for i in xrange(self.geom_count)]) coords = tuple @property def point_count(self): "The number of Points in this Polygon." # Summing up the number of points in each ring of the Polygon. return sum([self[i].point_count for i in xrange(self.geom_count)]) @property def centroid(self): "Returns the centroid (a Point) of this Polygon." # The centroid is a Point, create a geometry for this. p = OGRGeometry(OGRGeomType('Point')) capi.get_centroid(self.ptr, p.ptr) return p # Geometry Collection base class. class GeometryCollection(OGRGeometry): "The Geometry Collection class." def __getitem__(self, index): "Gets the Geometry at the specified index." if index < 0 or index >= self.geom_count: raise OGRIndexError('index out of range: %s' % index) else: return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs) def __iter__(self): "Iterates over each Geometry." for i in xrange(self.geom_count): yield self[i] def __len__(self): "The number of geometries in this Geometry Collection." return self.geom_count def add(self, geom): "Add the geometry to this Geometry Collection." if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: capi.add_geom(self.ptr, g.ptr) else: capi.add_geom(self.ptr, geom.ptr) elif isinstance(geom, basestring): tmp = OGRGeometry(geom) capi.add_geom(self.ptr, tmp.ptr) else: raise OGRException('Must add an OGRGeometry.') @property def point_count(self): "The number of Points in this Geometry Collection." # Summing up the number of points in each geometry in this collection return sum([self[i].point_count for i in xrange(self.geom_count)]) @property def tuple(self): "Returns a tuple representation of this Geometry Collection." return tuple([self[i].tuple for i in xrange(self.geom_count)]) coords = tuple # Multiple Geometry types. class MultiPoint(GeometryCollection): pass class MultiLineString(GeometryCollection): pass class MultiPolygon(GeometryCollection): pass # Class mapping dictionary (using the OGRwkbGeometryType as the key) GEO_CLASSES = {1 : Point, 2 : LineString, 3 : Polygon, 4 : MultiPoint, 5 : MultiLineString, 6 : MultiPolygon, 7 : GeometryCollection, 101: LinearRing, 1 + OGRGeomType.wkb25bit : Point, 2 + OGRGeomType.wkb25bit : LineString, 3 + OGRGeomType.wkb25bit : Polygon, 4 + OGRGeomType.wkb25bit : MultiPoint, 5 + OGRGeomType.wkb25bit : MultiLineString, 6 + OGRGeomType.wkb25bit : MultiPolygon, 7 + OGRGeomType.wkb25bit : GeometryCollection, }
[ [ 8, 0, 0.0278, 0.0543, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.057, 0.0014, 0, 0.66, 0.0476, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.0583, 0.0014, 0, 0.66,...
[ "\"\"\"\n The OGRGeometry is a wrapper for using the OGR Geometry class\n (see http://www.gdal.org/ogr/classOGRGeometry.html). OGRGeometry\n may be instantiated when reading geometries from OGR Data Sources\n (e.g. SHP files), or when given OGC WKT (a string).\n\n While the 'full' API is not present yet, the API i...
import os, re, sys from ctypes import c_char_p, CDLL from ctypes.util import find_library from django.contrib.gis.gdal.error import OGRException # Custom library path set? try: from django.conf import settings lib_path = settings.GDAL_LIBRARY_PATH except (AttributeError, EnvironmentError, ImportError): lib_path = None if lib_path: lib_names = None elif os.name == 'nt': # Windows NT shared library lib_names = ['gdal17', 'gdal16', 'gdal15'] elif os.name == 'posix': # *NIX library names. lib_names = ['gdal', 'GDAL', 'gdal1.7.0', 'gdal1.6.0', 'gdal1.5.0', 'gdal1.4.0'] else: raise OGRException('Unsupported OS "%s"' % os.name) # Using the ctypes `find_library` utility to find the # path to the GDAL library from the list of library names. if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if not lib_path is None: break if lib_path is None: raise OGRException('Could not find the GDAL library (tried "%s"). ' 'Try setting GDAL_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)) # This loads the GDAL/OGR C library lgdal = CDLL(lib_path) # On Windows, the GDAL binaries have some OSR routines exported with # STDCALL, while others are not. Thus, the library will also need to # be loaded up as WinDLL for said OSR functions that require the # different calling convention. if os.name == 'nt': from ctypes import WinDLL lwingdal = WinDLL(lib_path) def std_call(func): """ Returns the correct STDCALL function for certain OSR routines on Win32 platforms. """ if os.name == 'nt': return lwingdal[func] else: return lgdal[func] #### Version-information functions. #### # Returns GDAL library version information with the given key. _version_info = std_call('GDALVersionInfo') _version_info.argtypes = [c_char_p] _version_info.restype = c_char_p def gdal_version(): "Returns only the GDAL version number information." return _version_info('RELEASE_NAME') def gdal_full_version(): "Returns the full GDAL version information." return _version_info('') def gdal_release_date(date=False): """ Returns the release date in a string format, e.g, "2007/06/27". If the date keyword argument is set to True, a Python datetime object will be returned instead. """ from datetime import date as date_type rel = _version_info('RELEASE_DATE') yy, mm, dd = map(int, (rel[0:4], rel[4:6], rel[6:8])) d = date_type(yy, mm, dd) if date: return d else: return d.strftime('%Y/%m/%d') version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?') def gdal_version_info(): ver = gdal_version() m = version_regex.match(ver) if not m: raise OGRException('Could not parse GDAL version string "%s"' % ver) return dict([(key, m.group(key)) for key in ('major', 'minor', 'subminor')]) _verinfo = gdal_version_info() GDAL_MAJOR_VERSION = int(_verinfo['major']) GDAL_MINOR_VERSION = int(_verinfo['minor']) GDAL_SUBMINOR_VERSION = _verinfo['subminor'] and int(_verinfo['subminor']) GDAL_VERSION = (GDAL_MAJOR_VERSION, GDAL_MINOR_VERSION, GDAL_SUBMINOR_VERSION) del _verinfo # GeoJSON support is available only in GDAL 1.5+. if GDAL_VERSION >= (1, 5): GEOJSON = True else: GEOJSON = False
[ [ 1, 0, 0.0096, 0.0096, 0, 0.66, 0, 688, 0, 3, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0192, 0.0096, 0, 0.66, 0.0417, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0288, 0.0096, 0, ...
[ "import os, re, sys", "from ctypes import c_char_p, CDLL", "from ctypes.util import find_library", "from django.contrib.gis.gdal.error import OGRException", "try:\n from django.conf import settings\n lib_path = settings.GDAL_LIBRARY_PATH\nexcept (AttributeError, EnvironmentError, ImportError):\n li...
# prerequisites imports from ctypes import c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import OGRException from django.contrib.gis.gdal.prototypes import ds as capi # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_Dr_* routines are relevant here. class Driver(GDALBase): "Wraps an OGR Data Source Driver." # Case-insensitive aliases for OGR Drivers. _alias = {'esri' : 'ESRI Shapefile', 'shp' : 'ESRI Shapefile', 'shape' : 'ESRI Shapefile', 'tiger' : 'TIGER', 'tiger/line' : 'TIGER', } def __init__(self, dr_input): "Initializes an OGR driver on either a string or integer input." if isinstance(dr_input, basestring): # If a string name of the driver was passed in self._register() # Checking the alias dictionary (case-insensitive) to see if an alias # exists for the given driver. if dr_input.lower() in self._alias: name = self._alias[dr_input.lower()] else: name = dr_input # Attempting to get the OGR driver by the string name. dr = capi.get_driver_by_name(name) elif isinstance(dr_input, int): self._register() dr = capi.get_driver(dr_input) elif isinstance(dr_input, c_void_p): dr = dr_input else: raise OGRException('Unrecognized input type for OGR Driver: %s' % str(type(dr_input))) # Making sure we get a valid pointer to the OGR Driver if not dr: raise OGRException('Could not initialize OGR Driver on input: %s' % str(dr_input)) self.ptr = dr def __str__(self): "Returns the string name of the OGR Driver." return capi.get_driver_name(self.ptr) def _register(self): "Attempts to register all the data source drivers." # Only register all if the driver count is 0 (or else all drivers # will be registered over and over again) if not self.driver_count: capi.register_all() # Driver properties @property def driver_count(self): "Returns the number of OGR data source drivers registered." return capi.get_driver_count()
[ [ 1, 0, 0.0308, 0.0154, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0462, 0.0154, 0, 0.66, 0.25, 771, 0, 1, 0, 0, 771, 0, 0 ], [ 1, 0, 0.0615, 0.0154, 0, 0....
[ "from ctypes import c_void_p", "from django.contrib.gis.gdal.base import GDALBase", "from django.contrib.gis.gdal.error import OGRException", "from django.contrib.gis.gdal.prototypes import ds as capi", "class Driver(GDALBase):\n \"Wraps an OGR Data Source Driver.\"\n\n # Case-insensitive aliases for ...
""" The GDAL/OGR library uses an Envelope structure to hold the bounding box information for a geometry. The envelope (bounding box) contains two pairs of coordinates, one for the lower left coordinate and one for the upper right coordinate: +----------o Upper right; (max_x, max_y) | | | | | | Lower left (min_x, min_y) o----------+ """ from ctypes import Structure, c_double from django.contrib.gis.gdal.error import OGRException # The OGR definition of an Envelope is a C structure containing four doubles. # See the 'ogr_core.h' source file for more information: # http://www.gdal.org/ogr/ogr__core_8h-source.html class OGREnvelope(Structure): "Represents the OGREnvelope C Structure." _fields_ = [("MinX", c_double), ("MaxX", c_double), ("MinY", c_double), ("MaxY", c_double), ] class Envelope(object): """ The Envelope object is a C structure that contains the minimum and maximum X, Y coordinates for a rectangle bounding box. The naming of the variables is compatible with the OGR Envelope structure. """ def __init__(self, *args): """ The initialization function may take an OGREnvelope structure, 4-element tuple or list, or 4 individual arguments. """ if len(args) == 1: if isinstance(args[0], OGREnvelope): # OGREnvelope (a ctypes Structure) was passed in. self._envelope = args[0] elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) != 4: raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) else: self._from_sequence(args[0]) else: raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) elif len(args) == 4: # Individiual parameters passed in. # Thanks to ww for the help self._from_sequence(map(float, args)) else: raise OGRException('Incorrect number (%d) of arguments.' % len(args)) # Checking the x,y coordinates if self.min_x > self.max_x: raise OGRException('Envelope minimum X > maximum X.') if self.min_y > self.max_y: raise OGRException('Envelope minimum Y > maximum Y.') def __eq__(self, other): """ Returns True if the envelopes are equivalent; can compare against other Envelopes and 4-tuples. """ if isinstance(other, Envelope): return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ (self.max_x == other.max_x) and (self.max_y == other.max_y) elif isinstance(other, tuple) and len(other) == 4: return (self.min_x == other[0]) and (self.min_y == other[1]) and \ (self.max_x == other[2]) and (self.max_y == other[3]) else: raise OGRException('Equivalence testing only works with other Envelopes.') def __str__(self): "Returns a string representation of the tuple." return str(self.tuple) def _from_sequence(self, seq): "Initializes the C OGR Envelope structure from the given sequence." self._envelope = OGREnvelope() self._envelope.MinX = seq[0] self._envelope.MinY = seq[1] self._envelope.MaxX = seq[2] self._envelope.MaxY = seq[3] def expand_to_include(self, *args): """ Modifies the envelope to expand to include the boundaries of the passed-in 2-tuple (a point), 4-tuple (an extent) or envelope. """ # We provide a number of different signatures for this method, # and the logic here is all about converting them into a # 4-tuple single parameter which does the actual work of # expanding the envelope. if len(args) == 1: if isinstance(args[0], Envelope): return self.expand_to_include(args[0].tuple) elif hasattr(args[0], 'x') and hasattr(args[0], 'y'): return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y) elif isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) == 2: return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1])) elif len(args[0]) == 4: (minx, miny, maxx, maxy) = args[0] if minx < self._envelope.MinX: self._envelope.MinX = minx if miny < self._envelope.MinY: self._envelope.MinY = miny if maxx > self._envelope.MaxX: self._envelope.MaxX = maxx if maxy > self._envelope.MaxY: self._envelope.MaxY = maxy else: raise OGRException('Incorrect number of tuple elements (%d).' % len(args[0])) else: raise TypeError('Incorrect type of argument: %s' % str(type(args[0]))) elif len(args) == 2: # An x and an y parameter were passed in return self.expand_to_include((args[0], args[1], args[0], args[1])) elif len(args) == 4: # Individiual parameters passed in. return self.expand_to_include(args) else: raise OGRException('Incorrect number (%d) of arguments.' % len(args[0])) @property def min_x(self): "Returns the value of the minimum X coordinate." return self._envelope.MinX @property def min_y(self): "Returns the value of the minimum Y coordinate." return self._envelope.MinY @property def max_x(self): "Returns the value of the maximum X coordinate." return self._envelope.MaxX @property def max_y(self): "Returns the value of the maximum Y coordinate." return self._envelope.MaxY @property def ur(self): "Returns the upper-right coordinate." return (self.max_x, self.max_y) @property def ll(self): "Returns the lower-left coordinate." return (self.min_x, self.min_y) @property def tuple(self): "Returns a tuple representing the envelope." return (self.min_x, self.min_y, self.max_x, self.max_y) @property def wkt(self): "Returns WKT representing a Polygon for this envelope." # TODO: Fix significant figures. return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \ (self.min_x, self.min_y, self.min_x, self.max_y, self.max_x, self.max_y, self.max_x, self.min_y, self.min_x, self.min_y)
[ [ 8, 0, 0.0371, 0.0686, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0743, 0.0057, 0, 0.66, 0.25, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.08, 0.0057, 0, 0.66, ...
[ "\"\"\"\n The GDAL/OGR library uses an Envelope structure to hold the bounding\n box information for a geometry. The envelope (bounding box) contains\n two pairs of coordinates, one for the lower left coordinate and one\n for the upper right coordinate:\n\n +----------o Upper right; (max_...
from ctypes import c_void_p from types import NoneType from django.contrib.gis.gdal.error import GDALException class GDALBase(object): """ Base object for GDAL objects that has a pointer access property that controls access to the underlying C pointer. """ # Initially the pointer is NULL. _ptr = None # Default allowed pointer type. ptr_type = c_void_p # Pointer access property. def _get_ptr(self): # Raise an exception if the pointer isn't valid don't # want to be passing NULL pointers to routines -- # that's very bad. if self._ptr: return self._ptr else: raise GDALException('GDAL %s pointer no longer valid.' % self.__class__.__name__) def _set_ptr(self, ptr): # Only allow the pointer to be set with pointers of the # compatible type or None (NULL). if isinstance(ptr, (int, long)): self._ptr = self.ptr_type(ptr) elif isinstance(ptr, (self.ptr_type, NoneType)): self._ptr = ptr else: raise TypeError('Incompatible pointer type') ptr = property(_get_ptr, _set_ptr)
[ [ 1, 0, 0.0286, 0.0286, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0571, 0.0286, 0, 0.66, 0.3333, 209, 0, 1, 0, 0, 209, 0, 0 ], [ 1, 0, 0.0857, 0.0286, 0, ...
[ "from ctypes import c_void_p", "from types import NoneType", "from django.contrib.gis.gdal.error import GDALException", "class GDALBase(object):\n \"\"\"\n Base object for GDAL objects that has a pointer access property\n that controls access to the underlying C pointer.\n \"\"\"\n # Initially ...
""" This module houses ctypes interfaces for GDAL objects. The following GDAL objects are supported: CoordTransform: Used for coordinate transformations from one spatial reference system to another. Driver: Wraps an OGR data source driver. DataSource: Wrapper for the OGR data source object, supports OGR-supported data sources. Envelope: A ctypes structure for bounding boxes (GDAL library not required). OGRGeometry: Object for accessing OGR Geometry functionality. OGRGeomType: A class for representing the different OGR Geometry types (GDAL library not required). SpatialReference: Represents OSR Spatial Reference objects. The GDAL library will be imported from the system path using the default library name for the current OS. The default library path may be overridden by setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C library on your system. GDAL links to a large number of external libraries that consume RAM when loaded. Thus, it may desirable to disable GDAL on systems with limited RAM resources -- this may be accomplished by setting `GDAL_LIBRARY_PATH` to a non-existant file location (e.g., `GDAL_LIBRARY_PATH='/null/path'`; setting to None/False/'' will not work as a string must be given). """ # Attempting to import objects that depend on the GDAL library. The # HAS_GDAL flag will be set to True if the library is present on # the system. try: from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.datasource import DataSource from django.contrib.gis.gdal.libgdal import gdal_version, gdal_full_version, gdal_release_date, GEOJSON, GDAL_VERSION from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform from django.contrib.gis.gdal.geometries import OGRGeometry HAS_GDAL = True except: HAS_GDAL, GEOJSON = False, False try: from django.contrib.gis.gdal.envelope import Envelope except ImportError: # No ctypes, but don't raise an exception. pass from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.geomtype import OGRGeomType
[ [ 8, 0, 0.3148, 0.6111, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 7, 0, 0.7593, 0.1667, 0, 0.66, 0.25, 0, 0, 1, 0, 0, 0, 0, 0 ], [ 1, 1, 0.7037, 0.0185, 1, 0.81, ...
[ "\"\"\"\n This module houses ctypes interfaces for GDAL objects. The following GDAL\n objects are supported:\n\n CoordTransform: Used for coordinate transformations from one spatial\n reference system to another.\n\n Driver: Wraps an OGR data source driver.", "try:\n from django.contrib.gis.gdal.driver impor...
""" The Spatial Reference class, represensents OGR Spatial Reference objects. Example: >>> from django.contrib.gis.gdal import SpatialReference >>> srs = SpatialReference('WGS84') >>> print srs GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], TOWGS84[0,0,0,0,0,0,0], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] >>> print srs.proj +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> print srs.ellipsoid (6378137.0, 6356752.3142451793, 298.25722356300003) >>> print srs.projected, srs.geographic False True >>> srs.import_epsg(32140) >>> print srs.name NAD83 / Texas South Central """ import re from ctypes import byref, c_char_p, c_int, c_void_p # Getting the error checking routine and exceptions from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import OGRException, SRSException from django.contrib.gis.gdal.prototypes import srs as capi #### Spatial Reference class. #### class SpatialReference(GDALBase): """ A wrapper for the OGRSpatialReference object. According to the GDAL Web site, the SpatialReference object "provide[s] services to represent coordinate systems (projections and datums) and to transform between them." """ #### Python 'magic' routines #### def __init__(self, srs_input=''): """ Creates a GDAL OSR Spatial Reference object from the given input. The input may be string of OGC Well Known Text (WKT), an integer EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83'). """ buf = c_char_p('') srs_type = 'user' if isinstance(srs_input, basestring): # Encoding to ASCII if unicode passed in. if isinstance(srs_input, unicode): srs_input = srs_input.encode('ascii') try: # If SRID is a string, e.g., '4326', then make acceptable # as user input. srid = int(srs_input) srs_input = 'EPSG:%d' % srid except ValueError: pass elif isinstance(srs_input, (int, long)): # EPSG integer code was input. srs_type = 'epsg' elif isinstance(srs_input, self.ptr_type): srs = srs_input srs_type = 'ogr' else: raise TypeError('Invalid SRS type "%s"' % srs_type) if srs_type == 'ogr': # Input is already an SRS pointer. srs = srs_input else: # Creating a new SRS pointer, using the string buffer. srs = capi.new_srs(buf) # If the pointer is NULL, throw an exception. if not srs: raise SRSException('Could not create spatial reference from: %s' % srs_input) else: self.ptr = srs # Importing from either the user input string or an integer SRID. if srs_type == 'user': self.import_user_input(srs_input) elif srs_type == 'epsg': self.import_epsg(srs_input) def __del__(self): "Destroys this spatial reference." if self._ptr: capi.release_srs(self._ptr) def __getitem__(self, target): """ Returns the value of the given string attribute node, None if the node doesn't exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example: >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]') >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> print srs['GEOGCS'] WGS 84 >>> print srs['DATUM'] WGS_1984 >>> print srs['AUTHORITY'] EPSG >>> print srs['AUTHORITY', 1] # The authority value 4326 >>> print srs['TOWGS84', 4] # the fourth value in this wkt 0 >>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbole. EPSG >>> print srs['UNIT|AUTHORITY', 1] # The authority value for the untis 9122 """ if isinstance(target, tuple): return self.attr_value(*target) else: return self.attr_value(target) def __str__(self): "The string representation uses 'pretty' WKT." return self.pretty_wkt #### SpatialReference Methods #### def attr_value(self, target, index=0): """ The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return. """ if not isinstance(target, basestring) or not isinstance(index, int): raise TypeError return capi.get_attr_value(self.ptr, target, index) def auth_name(self, target): "Returns the authority name for the given string target node." return capi.get_auth_name(self.ptr, target) def auth_code(self, target): "Returns the authority code for the given string target node." return capi.get_auth_code(self.ptr, target) def clone(self): "Returns a clone of this SpatialReference object." return SpatialReference(capi.clone_srs(self.ptr)) def from_esri(self): "Morphs this SpatialReference from ESRI's format to EPSG." capi.morph_from_esri(self.ptr) def identify_epsg(self): """ This method inspects the WKT of this SpatialReference, and will add EPSG authority nodes where an EPSG identifier is applicable. """ capi.identify_epsg(self.ptr) def to_esri(self): "Morphs this SpatialReference to ESRI's format." capi.morph_to_esri(self.ptr) def validate(self): "Checks to see if the given spatial reference is valid." capi.srs_validate(self.ptr) #### Name & SRID properties #### @property def name(self): "Returns the name of this Spatial Reference." if self.projected: return self.attr_value('PROJCS') elif self.geographic: return self.attr_value('GEOGCS') elif self.local: return self.attr_value('LOCAL_CS') else: return None @property def srid(self): "Returns the SRID of top-level authority, or None if undefined." try: return int(self.attr_value('AUTHORITY', 1)) except (TypeError, ValueError): return None #### Unit Properties #### @property def linear_name(self): "Returns the name of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return name @property def linear_units(self): "Returns the value of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return units @property def angular_name(self): "Returns the name of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return name @property def angular_units(self): "Returns the value of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return units @property def units(self): """ Returns a 2-tuple of the units value and the units name, and will automatically determines whether to return the linear or angular units. """ if self.projected or self.local: return capi.linear_units(self.ptr, byref(c_char_p())) elif self.geographic: return capi.angular_units(self.ptr, byref(c_char_p())) else: return (None, None) #### Spheroid/Ellipsoid Properties #### @property def ellipsoid(self): """ Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening) """ return (self.semi_major, self.semi_minor, self.inverse_flattening) @property def semi_major(self): "Returns the Semi Major Axis for this Spatial Reference." return capi.semi_major(self.ptr, byref(c_int())) @property def semi_minor(self): "Returns the Semi Minor Axis for this Spatial Reference." return capi.semi_minor(self.ptr, byref(c_int())) @property def inverse_flattening(self): "Returns the Inverse Flattening for this Spatial Reference." return capi.invflattening(self.ptr, byref(c_int())) #### Boolean Properties #### @property def geographic(self): """ Returns True if this SpatialReference is geographic (root node is GEOGCS). """ return bool(capi.isgeographic(self.ptr)) @property def local(self): "Returns True if this SpatialReference is local (root node is LOCAL_CS)." return bool(capi.islocal(self.ptr)) @property def projected(self): """ Returns True if this SpatialReference is a projected coordinate system (root node is PROJCS). """ return bool(capi.isprojected(self.ptr)) #### Import Routines ##### def import_epsg(self, epsg): "Imports the Spatial Reference from the EPSG code (an integer)." capi.from_epsg(self.ptr, epsg) def import_proj(self, proj): "Imports the Spatial Reference from a PROJ.4 string." capi.from_proj(self.ptr, proj) def import_user_input(self, user_input): "Imports the Spatial Reference from the given user input string." capi.from_user_input(self.ptr, user_input) def import_wkt(self, wkt): "Imports the Spatial Reference from OGC WKT (string)" capi.from_wkt(self.ptr, byref(c_char_p(wkt))) def import_xml(self, xml): "Imports the Spatial Reference from an XML string." capi.from_xml(self.ptr, xml) #### Export Properties #### @property def wkt(self): "Returns the WKT representation of this Spatial Reference." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def pretty_wkt(self, simplify=0): "Returns the 'pretty' representation of the WKT." return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify) @property def proj(self): "Returns the PROJ.4 representation for this Spatial Reference." return capi.to_proj(self.ptr, byref(c_char_p())) @property def proj4(self): "Alias for proj()." return self.proj @property def xml(self, dialect=''): "Returns the XML representation of this Spatial Reference." return capi.to_xml(self.ptr, byref(c_char_p()), dialect) class CoordTransform(GDALBase): "The coordinate system transformation object." def __init__(self, source, target): "Initializes on a source and target SpatialReference objects." if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference): raise TypeError('source and target must be of type SpatialReference') self.ptr = capi.new_ct(source._ptr, target._ptr) self._srs1_name = source.name self._srs2_name = target.name def __del__(self): "Deletes this Coordinate Transformation object." if self._ptr: capi.destroy_ct(self._ptr) def __str__(self): return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)
[ [ 8, 0, 0.043, 0.0831, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0861, 0.003, 0, 0.66, 0.1429, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.089, 0.003, 0, 0.66, ...
[ "\"\"\"\n The Spatial Reference class, represensents OGR Spatial Reference objects.\n\n Example:\n >>> from django.contrib.gis.gdal import SpatialReference\n >>> srs = SpatialReference('WGS84')\n >>> print srs\n GEOGCS[\"WGS 84\",", "import re", "from ctypes import byref, c_char_p, c_int, c_void_p", "fr...
from django.conf import settings from django.contrib.admin import ModelAdmin from django.contrib.gis.admin.widgets import OpenLayersWidget from django.contrib.gis.gdal import OGRGeomType from django.contrib.gis.db import models class GeoModelAdmin(ModelAdmin): """ The administration options class for Geographic models. Map settings may be overloaded from their defaults to create custom maps. """ # The default map settings that may be overloaded -- still subject # to API changes. default_lon = 0 default_lat = 0 default_zoom = 4 display_wkt = False display_srid = False extra_js = [] num_zoom = 18 max_zoom = False min_zoom = False units = False max_resolution = False max_extent = False modifiable = True mouse_position = True scale_text = True layerswitcher = True scrollable = True map_width = 600 map_height = 400 map_srid = 4326 map_template = 'gis/admin/openlayers.html' openlayers_url = 'http://openlayers.org/api/2.10/OpenLayers.js' point_zoom = num_zoom - 6 wms_url = 'http://labs.metacarta.com/wms/vmap0' wms_layer = 'basic' wms_name = 'OpenLayers WMS' debug = False widget = OpenLayersWidget def _media(self): "Injects OpenLayers JavaScript into the admin." media = super(GeoModelAdmin, self)._media() media.add_js([self.openlayers_url]) media.add_js(self.extra_js) return media media = property(_media) def formfield_for_dbfield(self, db_field, **kwargs): """ Overloaded from ModelAdmin so that an OpenLayersWidget is used for viewing/editing GeometryFields. """ if isinstance(db_field, models.GeometryField): request = kwargs.pop('request', None) # Setting the widget with the newly defined widget. kwargs['widget'] = self.get_map_widget(db_field) return db_field.formfield(**kwargs) else: return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, **kwargs) def get_map_widget(self, db_field): """ Returns a subclass of the OpenLayersWidget (or whatever was specified in the `widget` attribute) using the settings from the attributes set in this class. """ is_collection = db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION') if is_collection: if db_field.geom_type == 'GEOMETRYCOLLECTION': collection_type = 'Any' else: collection_type = OGRGeomType(db_field.geom_type.replace('MULTI', '')) else: collection_type = 'None' class OLMap(self.widget): template = self.map_template geom_type = db_field.geom_type params = {'default_lon' : self.default_lon, 'default_lat' : self.default_lat, 'default_zoom' : self.default_zoom, 'display_wkt' : self.debug or self.display_wkt, 'geom_type' : OGRGeomType(db_field.geom_type), 'field_name' : db_field.name, 'is_collection' : is_collection, 'scrollable' : self.scrollable, 'layerswitcher' : self.layerswitcher, 'collection_type' : collection_type, 'is_linestring' : db_field.geom_type in ('LINESTRING', 'MULTILINESTRING'), 'is_polygon' : db_field.geom_type in ('POLYGON', 'MULTIPOLYGON'), 'is_point' : db_field.geom_type in ('POINT', 'MULTIPOINT'), 'num_zoom' : self.num_zoom, 'max_zoom' : self.max_zoom, 'min_zoom' : self.min_zoom, 'units' : self.units, #likely shoud get from object 'max_resolution' : self.max_resolution, 'max_extent' : self.max_extent, 'modifiable' : self.modifiable, 'mouse_position' : self.mouse_position, 'scale_text' : self.scale_text, 'map_width' : self.map_width, 'map_height' : self.map_height, 'point_zoom' : self.point_zoom, 'srid' : self.map_srid, 'display_srid' : self.display_srid, 'wms_url' : self.wms_url, 'wms_layer' : self.wms_layer, 'wms_name' : self.wms_name, 'debug' : self.debug, } return OLMap from django.contrib.gis import gdal if gdal.HAS_GDAL: class OSMGeoAdmin(GeoModelAdmin): map_template = 'gis/admin/osm.html' extra_js = ['http://www.openstreetmap.org/openlayers/OpenStreetMap.js'] num_zoom = 20 map_srid = 900913 max_extent = '-20037508,-20037508,20037508,20037508' max_resolution = '156543.0339' point_zoom = num_zoom - 6 units = 'm'
[ [ 1, 0, 0.0081, 0.0081, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0161, 0.0081, 0, 0.66, 0.1429, 703, 0, 1, 0, 0, 703, 0, 0 ], [ 1, 0, 0.0242, 0.0081, 0, ...
[ "from django.conf import settings", "from django.contrib.admin import ModelAdmin", "from django.contrib.gis.admin.widgets import OpenLayersWidget", "from django.contrib.gis.gdal import OGRGeomType", "from django.contrib.gis.db import models", "class GeoModelAdmin(ModelAdmin):\n \"\"\"\n The administ...
from django.conf import settings from django.contrib.gis.gdal import OGRException from django.contrib.gis.geos import GEOSGeometry, GEOSException from django.forms.widgets import Textarea from django.template import loader, Context from django.utils import translation # Creating a template context that contains Django settings # values needed by admin map templates. geo_context = Context({'ADMIN_MEDIA_PREFIX' : settings.ADMIN_MEDIA_PREFIX, 'LANGUAGE_BIDI' : translation.get_language_bidi(), }) class OpenLayersWidget(Textarea): """ Renders an OpenLayers map using the WKT of the geometry. """ def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) # Defaulting the WKT value to a blank string -- this # will be tested in the JavaScript and the appropriate # interface will be constructed. self.params['wkt'] = '' # If a string reaches here (via a validation error on another # field) then just reconstruct the Geometry. if isinstance(value, basestring): try: value = GEOSGeometry(value) except (GEOSException, ValueError): value = None if value and value.geom_type.upper() != self.geom_type: value = None # Constructing the dictionary of the map options. self.params['map_options'] = self.map_options() # Constructing the JavaScript module name using the name of # the GeometryField (passed in via the `attrs` keyword). # Use the 'name' attr for the field name (rather than 'field') self.params['name'] = name # note: we must switch out dashes for underscores since js # functions are created using the module variable js_safe_name = self.params['name'].replace('-','_') self.params['module'] = 'geodjango_%s' % js_safe_name if value: # Transforming the geometry to the projection used on the # OpenLayers map. srid = self.params['srid'] if value.srid != srid: try: ogr = value.ogr ogr.transform(srid) wkt = ogr.wkt except OGRException: wkt = '' else: wkt = value.wkt # Setting the parameter WKT with that of the transformed # geometry. self.params['wkt'] = wkt return loader.render_to_string(self.template, self.params, context_instance=geo_context) def map_options(self): "Builds the map options hash for the OpenLayers template." # JavaScript construction utilities for the Bounds and Projection. def ol_bounds(extent): return 'new OpenLayers.Bounds(%s)' % str(extent) def ol_projection(srid): return 'new OpenLayers.Projection("EPSG:%s")' % srid # An array of the parameter name, the name of their OpenLayers # counterpart, and the type of variable they are. map_types = [('srid', 'projection', 'srid'), ('display_srid', 'displayProjection', 'srid'), ('units', 'units', str), ('max_resolution', 'maxResolution', float), ('max_extent', 'maxExtent', 'bounds'), ('num_zoom', 'numZoomLevels', int), ('max_zoom', 'maxZoomLevels', int), ('min_zoom', 'minZoomLevel', int), ] # Building the map options hash. map_options = {} for param_name, js_name, option_type in map_types: if self.params.get(param_name, False): if option_type == 'srid': value = ol_projection(self.params[param_name]) elif option_type == 'bounds': value = ol_bounds(self.params[param_name]) elif option_type in (float, int): value = self.params[param_name] elif option_type in (str,): value = '"%s"' % self.params[param_name] else: raise TypeError map_options[js_name] = value return map_options
[ [ 1, 0, 0.0093, 0.0093, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0187, 0.0093, 0, 0.66, 0.1429, 793, 0, 1, 0, 0, 793, 0, 0 ], [ 1, 0, 0.028, 0.0093, 0, 0...
[ "from django.conf import settings", "from django.contrib.gis.gdal import OGRException", "from django.contrib.gis.geos import GEOSGeometry, GEOSException", "from django.forms.widgets import Textarea", "from django.template import loader, Context", "from django.utils import translation", "geo_context = Co...
# Getting the normal admin routines, classes, and `site` instance. from django.contrib.admin import autodiscover, site, AdminSite, ModelAdmin, StackedInline, TabularInline, HORIZONTAL, VERTICAL # Geographic admin options classes and widgets. from django.contrib.gis.admin.options import GeoModelAdmin from django.contrib.gis.admin.widgets import OpenLayersWidget try: from django.contrib.gis.admin.options import OSMGeoAdmin HAS_OSM = True except ImportError: HAS_OSM = False
[ [ 1, 0, 0.1667, 0.0833, 0, 0.66, 0, 703, 0, 8, 0, 0, 703, 0, 0 ], [ 1, 0, 0.4167, 0.0833, 0, 0.66, 0.3333, 833, 0, 1, 0, 0, 833, 0, 0 ], [ 1, 0, 0.5, 0.0833, 0, 0.6...
[ "from django.contrib.admin import autodiscover, site, AdminSite, ModelAdmin, StackedInline, TabularInline, HORIZONTAL, VERTICAL", "from django.contrib.gis.admin.options import GeoModelAdmin", "from django.contrib.gis.admin.widgets import OpenLayersWidget", "try:\n from django.contrib.gis.admin.options impo...
from django.contrib.gis.geos.base import numpy from django.contrib.gis.geos.coordseq import GEOSCoordSeq from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.point import Point from django.contrib.gis.geos import prototypes as capi class LineString(GEOSGeometry): _init_func = capi.create_linestring _minlength = 2 #### Python 'magic' routines #### def __init__(self, *args, **kwargs): """ Initializes on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object. Examples: ls = LineString((1, 1), (2, 2)) ls = LineString([(1, 1), (2, 2)]) ls = LineString(array([(1, 1), (2, 2)])) ls = LineString(Point(1, 1), Point(2, 2)) """ # If only one argument provided, set the coords array appropriately if len(args) == 1: coords = args[0] else: coords = args if isinstance(coords, (tuple, list)): # Getting the number of coords and the number of dimensions -- which # must stay the same, e.g., no LineString((1, 2), (1, 2, 3)). ncoords = len(coords) if coords: ndim = len(coords[0]) else: raise TypeError('Cannot initialize on empty sequence.') self._checkdim(ndim) # Incrementing through each of the coordinates and verifying for i in xrange(1, ncoords): if not isinstance(coords[i], (tuple, list, Point)): raise TypeError('each coordinate should be a sequence (list or tuple)') if len(coords[i]) != ndim: raise TypeError('Dimension mismatch.') numpy_coords = False elif numpy and isinstance(coords, numpy.ndarray): shape = coords.shape # Using numpy's shape. if len(shape) != 2: raise TypeError('Too many dimensions.') self._checkdim(shape[1]) ncoords = shape[0] ndim = shape[1] numpy_coords = True else: raise TypeError('Invalid initialization input for LineStrings.') # Creating a coordinate sequence object because it is easier to # set the points using GEOSCoordSeq.__setitem__(). cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim==3)) for i in xrange(ncoords): if numpy_coords: cs[i] = coords[i,:] elif isinstance(coords[i], Point): cs[i] = coords[i].tuple else: cs[i] = coords[i] # If SRID was passed in with the keyword arguments srid = kwargs.get('srid', None) # Calling the base geometry initialization with the returned pointer # from the function. super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid) def __iter__(self): "Allows iteration over this LineString." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of points in this LineString." return len(self._cs) def _get_single_external(self, index): return self._cs[index] _get_single_internal = _get_single_external def _set_list(self, length, items): ndim = self._cs.dims # hasz = self._cs.hasz # I don't understand why these are different # create a new coordinate sequence and populate accordingly cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz) for i, c in enumerate(items): cs[i] = c ptr = self._init_func(cs.ptr) if ptr: capi.destroy_geom(self.ptr) self.ptr = ptr self._post_init(self.srid) else: # can this happen? raise GEOSException('Geometry resulting from slice deletion was invalid.') def _set_single(self, index, value): self._checkindex(index) self._cs[index] = value def _checkdim(self, dim): if dim not in (2, 3): raise TypeError('Dimension mismatch.') #### Sequence Properties #### @property def tuple(self): "Returns a tuple version of the geometry from the coordinate sequence." return self._cs.tuple coords = tuple def _listarr(self, func): """ Internal routine that returns a sequence (list) corresponding with the given function. Will return a numpy array if possible. """ lst = [func(i) for i in xrange(len(self))] if numpy: return numpy.array(lst) # ARRRR! else: return lst @property def array(self): "Returns a numpy array for the LineString." return self._listarr(self._cs.__getitem__) @property def merged(self): "Returns the line merge of this LineString." return self._topology(capi.geos_linemerge(self.ptr)) @property def x(self): "Returns a list or numpy array of the X variable." return self._listarr(self._cs.getX) @property def y(self): "Returns a list or numpy array of the Y variable." return self._listarr(self._cs.getY) @property def z(self): "Returns a list or numpy array of the Z variable." if not self.hasz: return None else: return self._listarr(self._cs.getZ) # LinearRings are LineStrings used within Polygons. class LinearRing(LineString): _minLength = 4 _init_func = capi.create_linearring
[ [ 1, 0, 0.0066, 0.0066, 0, 0.66, 0, 386, 0, 1, 0, 0, 386, 0, 0 ], [ 1, 0, 0.0132, 0.0066, 0, 0.66, 0.1429, 849, 0, 1, 0, 0, 849, 0, 0 ], [ 1, 0, 0.0197, 0.0066, 0, ...
[ "from django.contrib.gis.geos.base import numpy", "from django.contrib.gis.geos.coordseq import GEOSCoordSeq", "from django.contrib.gis.geos.error import GEOSException", "from django.contrib.gis.geos.geometry import GEOSGeometry", "from django.contrib.gis.geos.point import Point", "from django.contrib.gis...
""" This module houses the GEOS exceptions, specifically, GEOSException and GEOSGeometryIndexError. """ class GEOSException(Exception): "The base GEOS exception, indicates a GEOS-related error." pass class GEOSIndexError(GEOSException, KeyError): """ This exception is raised when an invalid index is encountered, and has the 'silent_variable_feature' attribute set to true. This ensures that django's templates proceed to use the next lookup type gracefully when an Exception is raised. Fixes ticket #4740. """ # "If, during the method lookup, a method raises an exception, the exception # will be propagated, unless the exception has an attribute # `silent_variable_failure` whose value is True." -- Django template docs. silent_variable_failure = True
[ [ 8, 0, 0.125, 0.2, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.35, 0.15, 0, 0.66, 0.5, 290, 0, 0, 0, 0, 645, 0, 0 ], [ 8, 1, 0.35, 0.05, 1, 0.64, 0, 0,...
[ "\"\"\"\n This module houses the GEOS exceptions, specifically, GEOSException and\n GEOSGeometryIndexError.\n\"\"\"", "class GEOSException(Exception):\n \"The base GEOS exception, indicates a GEOS-related error.\"\n pass", " \"The base GEOS exception, indicates a GEOS-related error.\"", "class GEOSIn...
""" Module that holds classes for performing I/O operations on GEOS geometry objects. Specifically, this has Python implementations of WKB/WKT reader and writer classes. """ from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.prototypes.io import _WKTReader, _WKBReader, WKBWriter, WKTWriter # Public classes for (WKB|WKT)Reader, which return GEOSGeometry class WKBReader(_WKBReader): def read(self, wkb): "Returns a GEOSGeometry for the given WKB buffer." return GEOSGeometry(super(WKBReader, self).read(wkb)) class WKTReader(_WKTReader): def read(self, wkt): "Returns a GEOSGeometry for the given WKT string." return GEOSGeometry(super(WKTReader, self).read(wkt))
[ [ 8, 0, 0.15, 0.25, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3, 0.05, 0, 0.66, 0.25, 843, 0, 1, 0, 0, 843, 0, 0 ], [ 1, 0, 0.35, 0.05, 0, 0.66, 0.5, ...
[ "\"\"\"\nModule that holds classes for performing I/O operations on GEOS geometry\nobjects. Specifically, this has Python implementations of WKB/WKT\nreader and writer classes.\n\"\"\"", "from django.contrib.gis.geos.geometry import GEOSGeometry", "from django.contrib.gis.geos.prototypes.io import _WKTReader, ...
""" This module houses the Geometry Collection objects: GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon """ from ctypes import c_int, c_uint, byref from django.contrib.gis.geos.error import GEOSException, GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR, GEOS_PREPARE from django.contrib.gis.geos.linestring import LineString, LinearRing from django.contrib.gis.geos.point import Point from django.contrib.gis.geos.polygon import Polygon from django.contrib.gis.geos import prototypes as capi class GeometryCollection(GEOSGeometry): _typeid = 7 def __init__(self, *args, **kwargs): "Initializes a Geometry Collection from a sequence of Geometry objects." # Checking the arguments if not args: raise TypeError('Must provide at least one Geometry to initialize %s.' % self.__class__.__name__) if len(args) == 1: # If only one geometry provided or a list of geometries is provided # in the first argument. if isinstance(args[0], (tuple, list)): init_geoms = args[0] else: init_geoms = args else: init_geoms = args # Ensuring that only the permitted geometries are allowed in this collection # this is moved to list mixin super class self._check_allowed(init_geoms) # Creating the geometry pointer array. collection = self._create_collection(len(init_geoms), iter(init_geoms)) super(GeometryCollection, self).__init__(collection, **kwargs) def __iter__(self): "Iterates over each Geometry in the Collection." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of geometries in this Collection." return self.num_geom ### Methods for compatibility with ListMixin ### def _create_collection(self, length, items): # Creating the geometry pointer array. geoms = get_pointer_arr(length) for i, g in enumerate(items): # this is a little sloppy, but makes life easier # allow GEOSGeometry types (python wrappers) or pointer types geoms[i] = capi.geom_clone(getattr(g, 'ptr', g)) return capi.create_collection(c_int(self._typeid), byref(geoms), c_uint(length)) def _get_single_internal(self, index): return capi.get_geomn(self.ptr, index) def _get_single_external(self, index): "Returns the Geometry from this Collection at the given index (0-based)." # Checking the index and returning the corresponding GEOS geometry. return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid) def _set_list(self, length, items): "Create a new collection, and destroy the contents of the previous pointer." prev_ptr = self.ptr srid = self.srid self.ptr = self._create_collection(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) _set_single = GEOSGeometry._set_single_rebuild _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild @property def kml(self): "Returns the KML for this Geometry Collection." return '<MultiGeometry>%s</MultiGeometry>' % ''.join([g.kml for g in self]) @property def tuple(self): "Returns a tuple of all the coordinates in this Geometry Collection" return tuple([g.tuple for g in self]) coords = tuple # MultiPoint, MultiLineString, and MultiPolygon class definitions. class MultiPoint(GeometryCollection): _allowed = Point _typeid = 4 class MultiLineString(GeometryCollection): _allowed = (LineString, LinearRing) _typeid = 5 @property def merged(self): """ Returns a LineString representing the line merge of this MultiLineString. """ return self._topology(capi.geos_linemerge(self.ptr)) class MultiPolygon(GeometryCollection): _allowed = Polygon _typeid = 6 @property def cascaded_union(self): "Returns a cascaded union of this MultiPolygon." if GEOS_PREPARE: return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid) else: raise GEOSException('The cascaded union operation requires GEOS 3.1+.') # Setting the allowed types here since GeometryCollection is defined before # its subclasses. GeometryCollection._allowed = (Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon)
[ [ 8, 0, 0.0203, 0.0325, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0407, 0.0081, 0, 0.66, 0.0769, 182, 0, 3, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0488, 0.0081, 0, 0.66...
[ "\"\"\"\n This module houses the Geometry Collection objects:\n GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon\n\"\"\"", "from ctypes import c_int, c_uint, byref", "from django.contrib.gis.geos.error import GEOSException, GEOSIndexError", "from django.contrib.gis.geos.geometry import GEOSGe...
from ctypes import c_char_p, c_int, c_size_t, c_ubyte, c_uint, POINTER from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, PREPGEOM_PTR, GEOS_PREPARE from django.contrib.gis.geos.prototypes.errcheck import \ check_geom, check_minus_one, check_sized_string, check_string, check_zero from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc # This is the return type used by binary output (WKB, HEX) routines. c_uchar_p = POINTER(c_ubyte) # We create a simple subclass of c_char_p here because when the response # type is set to c_char_p, you get a _Python_ string and there's no way # to access the string's address inside the error checking function. # In other words, you can't free the memory allocated inside GEOS. Previously, # the return type would just be omitted and the integer address would be # used -- but this allows us to be specific in the function definition and # keeps the reference so it may be free'd. class geos_char_p(c_char_p): pass ### ctypes generation functions ### def bin_constructor(func): "Generates a prototype for binary construction (HEX, WKB) GEOS routines." func.argtypes = [c_char_p, c_size_t] func.restype = GEOM_PTR func.errcheck = check_geom return func # HEX & WKB output def bin_output(func): "Generates a prototype for the routines that return a a sized string." func.argtypes = [GEOM_PTR, POINTER(c_size_t)] func.errcheck = check_sized_string func.restype = c_uchar_p return func def geom_output(func, argtypes): "For GEOS routines that return a geometry." if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func def geom_index(func): "For GEOS routines that return geometries from an index." return geom_output(func, [GEOM_PTR, c_int]) def int_from_geom(func, zero=False): "Argument is a geometry, return type is an integer." func.argtypes = [GEOM_PTR] func.restype = c_int if zero: func.errcheck = check_zero else: func.errcheck = check_minus_one return func def string_from_geom(func): "Argument is a Geometry, return type is a string." func.argtypes = [GEOM_PTR] func.restype = geos_char_p func.errcheck = check_string return func ### ctypes prototypes ### # Deprecated creation routines from WKB, HEX, WKT from_hex = bin_constructor(GEOSFunc('GEOSGeomFromHEX_buf')) from_wkb = bin_constructor(GEOSFunc('GEOSGeomFromWKB_buf')) from_wkt = geom_output(GEOSFunc('GEOSGeomFromWKT'), [c_char_p]) # Deprecated output routines to_hex = bin_output(GEOSFunc('GEOSGeomToHEX_buf')) to_wkb = bin_output(GEOSFunc('GEOSGeomToWKB_buf')) to_wkt = string_from_geom(GEOSFunc('GEOSGeomToWKT')) # The GEOS geometry type, typeid, num_coordites and number of geometries geos_normalize = int_from_geom(GEOSFunc('GEOSNormalize')) geos_type = string_from_geom(GEOSFunc('GEOSGeomType')) geos_typeid = int_from_geom(GEOSFunc('GEOSGeomTypeId')) get_dims = int_from_geom(GEOSFunc('GEOSGeom_getDimensions'), zero=True) get_num_coords = int_from_geom(GEOSFunc('GEOSGetNumCoordinates')) get_num_geoms = int_from_geom(GEOSFunc('GEOSGetNumGeometries')) # Geometry creation factories create_point = geom_output(GEOSFunc('GEOSGeom_createPoint'), [CS_PTR]) create_linestring = geom_output(GEOSFunc('GEOSGeom_createLineString'), [CS_PTR]) create_linearring = geom_output(GEOSFunc('GEOSGeom_createLinearRing'), [CS_PTR]) # Polygon and collection creation routines are special and will not # have their argument types defined. create_polygon = geom_output(GEOSFunc('GEOSGeom_createPolygon'), None) create_collection = geom_output(GEOSFunc('GEOSGeom_createCollection'), None) # Ring routines get_extring = geom_output(GEOSFunc('GEOSGetExteriorRing'), [GEOM_PTR]) get_intring = geom_index(GEOSFunc('GEOSGetInteriorRingN')) get_nrings = int_from_geom(GEOSFunc('GEOSGetNumInteriorRings')) # Collection Routines get_geomn = geom_index(GEOSFunc('GEOSGetGeometryN')) # Cloning geom_clone = GEOSFunc('GEOSGeom_clone') geom_clone.argtypes = [GEOM_PTR] geom_clone.restype = GEOM_PTR # Destruction routine. destroy_geom = GEOSFunc('GEOSGeom_destroy') destroy_geom.argtypes = [GEOM_PTR] destroy_geom.restype = None # SRID routines geos_get_srid = GEOSFunc('GEOSGetSRID') geos_get_srid.argtypes = [GEOM_PTR] geos_get_srid.restype = c_int geos_set_srid = GEOSFunc('GEOSSetSRID') geos_set_srid.argtypes = [GEOM_PTR, c_int] geos_set_srid.restype = None
[ [ 1, 0, 0.0084, 0.0084, 0, 0.66, 0, 182, 0, 6, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0168, 0.0084, 0, 0.66, 0.0227, 64, 0, 4, 0, 0, 64, 0, 0 ], [ 1, 0, 0.0294, 0.0168, 0, 0....
[ "from ctypes import c_char_p, c_int, c_size_t, c_ubyte, c_uint, POINTER", "from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, PREPGEOM_PTR, GEOS_PREPARE", "from django.contrib.gis.geos.prototypes.errcheck import \\\n check_geom, check_minus_one, check_sized_string, check_string, check_zero", "fr...
import threading from ctypes import byref, c_char_p, c_int, c_char, c_size_t, Structure, POINTER from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_string, check_sized_string from django.contrib.gis.geos.prototypes.geom import c_uchar_p, geos_char_p from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc ### The WKB/WKT Reader/Writer structures and pointers ### class WKTReader_st(Structure): pass class WKTWriter_st(Structure): pass class WKBReader_st(Structure): pass class WKBWriter_st(Structure): pass WKT_READ_PTR = POINTER(WKTReader_st) WKT_WRITE_PTR = POINTER(WKTWriter_st) WKB_READ_PTR = POINTER(WKBReader_st) WKB_WRITE_PTR = POINTER(WKBReader_st) ### WKTReader routines ### wkt_reader_create = GEOSFunc('GEOSWKTReader_create') wkt_reader_create.restype = WKT_READ_PTR wkt_reader_destroy = GEOSFunc('GEOSWKTReader_destroy') wkt_reader_destroy.argtypes = [WKT_READ_PTR] wkt_reader_read = GEOSFunc('GEOSWKTReader_read') wkt_reader_read.argtypes = [WKT_READ_PTR, c_char_p] wkt_reader_read.restype = GEOM_PTR wkt_reader_read.errcheck = check_geom ### WKTWriter routines ### wkt_writer_create = GEOSFunc('GEOSWKTWriter_create') wkt_writer_create.restype = WKT_WRITE_PTR wkt_writer_destroy = GEOSFunc('GEOSWKTWriter_destroy') wkt_writer_destroy.argtypes = [WKT_WRITE_PTR] wkt_writer_write = GEOSFunc('GEOSWKTWriter_write') wkt_writer_write.argtypes = [WKT_WRITE_PTR, GEOM_PTR] wkt_writer_write.restype = geos_char_p wkt_writer_write.errcheck = check_string ### WKBReader routines ### wkb_reader_create = GEOSFunc('GEOSWKBReader_create') wkb_reader_create.restype = WKB_READ_PTR wkb_reader_destroy = GEOSFunc('GEOSWKBReader_destroy') wkb_reader_destroy.argtypes = [WKB_READ_PTR] def wkb_read_func(func): # Although the function definitions take `const unsigned char *` # as their parameter, we use c_char_p here so the function may # take Python strings directly as parameters. Inside Python there # is not a difference between signed and unsigned characters, so # it is not a problem. func.argtypes = [WKB_READ_PTR, c_char_p, c_size_t] func.restype = GEOM_PTR func.errcheck = check_geom return func wkb_reader_read = wkb_read_func(GEOSFunc('GEOSWKBReader_read')) wkb_reader_read_hex = wkb_read_func(GEOSFunc('GEOSWKBReader_readHEX')) ### WKBWriter routines ### wkb_writer_create = GEOSFunc('GEOSWKBWriter_create') wkb_writer_create.restype = WKB_WRITE_PTR wkb_writer_destroy = GEOSFunc('GEOSWKBWriter_destroy') wkb_writer_destroy.argtypes = [WKB_WRITE_PTR] # WKB Writing prototypes. def wkb_write_func(func): func.argtypes = [WKB_WRITE_PTR, GEOM_PTR, POINTER(c_size_t)] func.restype = c_uchar_p func.errcheck = check_sized_string return func wkb_writer_write = wkb_write_func(GEOSFunc('GEOSWKBWriter_write')) wkb_writer_write_hex = wkb_write_func(GEOSFunc('GEOSWKBWriter_writeHEX')) # WKBWriter property getter/setter prototypes. def wkb_writer_get(func, restype=c_int): func.argtypes = [WKB_WRITE_PTR] func.restype = restype return func def wkb_writer_set(func, argtype=c_int): func.argtypes = [WKB_WRITE_PTR, argtype] return func wkb_writer_get_byteorder = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getByteOrder')) wkb_writer_set_byteorder = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setByteOrder')) wkb_writer_get_outdim = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getOutputDimension')) wkb_writer_set_outdim = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setOutputDimension')) wkb_writer_get_include_srid = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getIncludeSRID'), restype=c_char) wkb_writer_set_include_srid = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setIncludeSRID'), argtype=c_char) ### Base I/O Class ### class IOBase(GEOSBase): "Base class for GEOS I/O objects." def __init__(self): # Getting the pointer with the constructor. self.ptr = self._constructor() def __del__(self): # Cleaning up with the appropriate destructor. if self._ptr: self._destructor(self._ptr) ### Base WKB/WKT Reading and Writing objects ### # Non-public WKB/WKT reader classes for internal use because # their `read` methods return _pointers_ instead of GEOSGeometry # objects. class _WKTReader(IOBase): _constructor = wkt_reader_create _destructor = wkt_reader_destroy ptr_type = WKT_READ_PTR def read(self, wkt): if not isinstance(wkt, basestring): raise TypeError return wkt_reader_read(self.ptr, wkt) class _WKBReader(IOBase): _constructor = wkb_reader_create _destructor = wkb_reader_destroy ptr_type = WKB_READ_PTR def read(self, wkb): "Returns a _pointer_ to C GEOS Geometry object from the given WKB." if isinstance(wkb, buffer): wkb_s = str(wkb) return wkb_reader_read(self.ptr, wkb_s, len(wkb_s)) elif isinstance(wkb, basestring): return wkb_reader_read_hex(self.ptr, wkb, len(wkb)) else: raise TypeError ### WKB/WKT Writer Classes ### class WKTWriter(IOBase): _constructor = wkt_writer_create _destructor = wkt_writer_destroy ptr_type = WKT_WRITE_PTR def write(self, geom): "Returns the WKT representation of the given geometry." return wkt_writer_write(self.ptr, geom.ptr) class WKBWriter(IOBase): _constructor = wkb_writer_create _destructor = wkb_writer_destroy ptr_type = WKB_WRITE_PTR def write(self, geom): "Returns the WKB representation of the given geometry." return buffer(wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t()))) def write_hex(self, geom): "Returns the HEXEWKB representation of the given geometry." return wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t())) ### WKBWriter Properties ### # Property for getting/setting the byteorder. def _get_byteorder(self): return wkb_writer_get_byteorder(self.ptr) def _set_byteorder(self, order): if not order in (0, 1): raise ValueError('Byte order parameter must be 0 (Big Endian) or 1 (Little Endian).') wkb_writer_set_byteorder(self.ptr, order) byteorder = property(_get_byteorder, _set_byteorder) # Property for getting/setting the output dimension. def _get_outdim(self): return wkb_writer_get_outdim(self.ptr) def _set_outdim(self, new_dim): if not new_dim in (2, 3): raise ValueError('WKB output dimension must be 2 or 3') wkb_writer_set_outdim(self.ptr, new_dim) outdim = property(_get_outdim, _set_outdim) # Property for getting/setting the include srid flag. def _get_include_srid(self): return bool(ord(wkb_writer_get_include_srid(self.ptr))) def _set_include_srid(self, include): if bool(include): flag = chr(1) else: flag = chr(0) wkb_writer_set_include_srid(self.ptr, flag) srid = property(_get_include_srid, _set_include_srid) # `ThreadLocalIO` object holds instances of the WKT and WKB reader/writer # objects that are local to the thread. The `GEOSGeometry` internals # access these instances by calling the module-level functions, defined # below. class ThreadLocalIO(threading.local): wkt_r = None wkt_w = None wkb_r = None wkb_w = None ewkb_w = None ewkb_w3d = None thread_context = ThreadLocalIO() # These module-level routines return the I/O object that is local to the # the thread. If the I/O object does not exist yet it will be initialized. def wkt_r(): if not thread_context.wkt_r: thread_context.wkt_r = _WKTReader() return thread_context.wkt_r def wkt_w(): if not thread_context.wkt_w: thread_context.wkt_w = WKTWriter() return thread_context.wkt_w def wkb_r(): if not thread_context.wkb_r: thread_context.wkb_r = _WKBReader() return thread_context.wkb_r def wkb_w(): if not thread_context.wkb_w: thread_context.wkb_w = WKBWriter() return thread_context.wkb_w def ewkb_w(): if not thread_context.ewkb_w: thread_context.ewkb_w = WKBWriter() thread_context.ewkb_w.srid = True return thread_context.ewkb_w def ewkb_w3d(): if not thread_context.ewkb_w3d: thread_context.ewkb_w3d = WKBWriter() thread_context.ewkb_w3d.srid = True thread_context.ewkb_w3d.outdim = 3 return thread_context.ewkb_w3d
[ [ 1, 0, 0.0041, 0.0041, 0, 0.66, 0, 83, 0, 1, 0, 0, 83, 0, 0 ], [ 1, 0, 0.0083, 0.0041, 0, 0.66, 0.0154, 182, 0, 7, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0124, 0.0041, 0, 0....
[ "import threading", "from ctypes import byref, c_char_p, c_int, c_char, c_size_t, Structure, POINTER", "from django.contrib.gis.geos.base import GEOSBase", "from django.contrib.gis.geos.libgeos import GEOM_PTR", "from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_string, check_sized_s...
""" Error checking functions for GEOS ctypes prototype functions. """ import os from ctypes import c_void_p, string_at, CDLL from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.libgeos import GEOS_VERSION from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc # Getting the `free` routine used to free the memory allocated for # string pointers returned by GEOS. if GEOS_VERSION >= (3, 1, 1): # In versions 3.1.1 and above, `GEOSFree` was added to the C API # because `free` isn't always available on all platforms. free = GEOSFunc('GEOSFree') free.argtypes = [c_void_p] free.restype = None else: # Getting the `free` routine from the C library of the platform. if os.name == 'nt': # On NT, use the MS C library. libc = CDLL('msvcrt') else: # On POSIX platforms C library is obtained by passing None into `CDLL`. libc = CDLL(None) free = libc.free ### ctypes error checking routines ### def last_arg_byref(args): "Returns the last C argument's value by reference." return args[-1]._obj.value def check_dbl(result, func, cargs): "Checks the status code and returns the double value passed in by reference." # Checking the status code if result != 1: return None # Double passed in by reference, return its value. return last_arg_byref(cargs) def check_geom(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__) return result def check_minus_one(result, func, cargs): "Error checking on routines that should not return -1." if result == -1: raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__) else: return result def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." val = ord(result) # getting the ordinal from the character if val == 1: return True elif val == 0: return False else: raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) def check_sized_string(result, func, cargs): """ Error checking for routines that return explicitly sized strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__) # A c_size_t object is passed in by reference for the second # argument on these routines, and its needed to determine the # correct size. s = string_at(result, last_arg_byref(cargs)) # Freeing the memory allocated within GEOS free(result) return s def check_string(result, func, cargs): """ Error checking for routines that return strings. This frees the memory allocated by GEOS at the result pointer. """ if not result: raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__) # Getting the string value at the pointer address. s = string_at(result) # Freeing the memory allocated within GEOS free(result) return s def check_zero(result, func, cargs): "Error checking on routines that should not return 0." if result == 0: raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__) else: return result
[ [ 8, 0, 0.0211, 0.0316, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0421, 0.0105, 0, 0.66, 0.0714, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0526, 0.0105, 0, 0.66...
[ "\"\"\"\n Error checking functions for GEOS ctypes prototype functions.\n\"\"\"", "import os", "from ctypes import c_void_p, string_at, CDLL", "from django.contrib.gis.geos.error import GEOSException", "from django.contrib.gis.geos.libgeos import GEOS_VERSION", "from django.contrib.gis.geos.prototypes.thr...
""" This module houses the GEOS ctypes prototype functions for the topological operations on geometries. """ __all__ = ['geos_boundary', 'geos_buffer', 'geos_centroid', 'geos_convexhull', 'geos_difference', 'geos_envelope', 'geos_intersection', 'geos_linemerge', 'geos_pointonsurface', 'geos_preservesimplify', 'geos_simplify', 'geos_symdifference', 'geos_union', 'geos_relate'] from ctypes import c_char_p, c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_string from django.contrib.gis.geos.prototypes.geom import geos_char_p from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc def topology(func, *args): "For GEOS unary topology functions." argtypes = [GEOM_PTR] if args: argtypes += args func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func ### Topology Routines ### geos_boundary = topology(GEOSFunc('GEOSBoundary')) geos_buffer = topology(GEOSFunc('GEOSBuffer'), c_double, c_int) geos_centroid = topology(GEOSFunc('GEOSGetCentroid')) geos_convexhull = topology(GEOSFunc('GEOSConvexHull')) geos_difference = topology(GEOSFunc('GEOSDifference'), GEOM_PTR) geos_envelope = topology(GEOSFunc('GEOSEnvelope')) geos_intersection = topology(GEOSFunc('GEOSIntersection'), GEOM_PTR) geos_linemerge = topology(GEOSFunc('GEOSLineMerge')) geos_pointonsurface = topology(GEOSFunc('GEOSPointOnSurface')) geos_preservesimplify = topology(GEOSFunc('GEOSTopologyPreserveSimplify'), c_double) geos_simplify = topology(GEOSFunc('GEOSSimplify'), c_double) geos_symdifference = topology(GEOSFunc('GEOSSymDifference'), GEOM_PTR) geos_union = topology(GEOSFunc('GEOSUnion'), GEOM_PTR) # GEOSRelate returns a string, not a geometry. geos_relate = GEOSFunc('GEOSRelate') geos_relate.argtypes = [GEOM_PTR, GEOM_PTR] geos_relate.restype = geos_char_p geos_relate.errcheck = check_string # Routines only in GEOS 3.1+ if GEOS_PREPARE: geos_cascaded_union = GEOSFunc('GEOSUnionCascaded') geos_cascaded_union.argtypes = [GEOM_PTR] geos_cascaded_union.restype = GEOM_PTR __all__.append('geos_cascaded_union')
[ [ 8, 0, 0.049, 0.0784, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 0, 0.1275, 0.0784, 0, 0.66, 0.04, 272, 0, 0, 0, 0, 0, 5, 0 ], [ 1, 0, 0.1961, 0.0196, 0, 0.66, ...
[ "\"\"\"\n This module houses the GEOS ctypes prototype functions for the\n topological operations on geometries.\n\"\"\"", "__all__ = ['geos_boundary', 'geos_buffer', 'geos_centroid', 'geos_convexhull',\n 'geos_difference', 'geos_envelope', 'geos_intersection', \n 'geos_linemerge', 'geos_point...
import threading from django.contrib.gis.geos.libgeos import lgeos, notice_h, error_h, CONTEXT_PTR class GEOSContextHandle(object): """ Python object representing a GEOS context handle. """ def __init__(self): # Initializing the context handler for this thread with # the notice and error handler. self.ptr = lgeos.initGEOS_r(notice_h, error_h) def __del__(self): if self.ptr: lgeos.finishGEOS_r(self.ptr) # Defining a thread-local object and creating an instance # to hold a reference to GEOSContextHandle for this thread. class GEOSContext(threading.local): handle = None thread_context = GEOSContext() def call_geos_threaded(cfunc, args): """ This module-level routine calls the specified GEOS C thread-safe function with the context for this current thread. """ # If a context handle does not exist for this thread, initialize one. if not thread_context.handle: thread_context.handle = GEOSContextHandle() # Call the threaded GEOS routine with pointer of the context handle # as the first argument. return cfunc(thread_context.handle.ptr, *args) class GEOSFunc(object): """ Class that serves as a wrapper for GEOS C Functions, and will use thread-safe function variants when available. """ def __init__(self, func_name): try: # GEOS thread-safe function signatures end with '_r', and # take an additional context handle parameter. self.cfunc = getattr(lgeos, func_name + '_r') self.threaded = True except AttributeError: # Otherwise, use usual function. self.cfunc = getattr(lgeos, func_name) self.threaded = False def __call__(self, *args): if self.threaded: return call_geos_threaded(self.cfunc, args) else: return self.cfunc(*args) def __str__(self): return self.cfunc.__name__ # argtypes property def _get_argtypes(self): return self.cfunc.argtypes def _set_argtypes(self, argtypes): if self.threaded: new_argtypes = [CONTEXT_PTR] new_argtypes.extend(argtypes) self.cfunc.argtypes = new_argtypes else: self.cfunc.argtypes = argtypes argtypes = property(_get_argtypes, _set_argtypes) # restype property def _get_restype(self): return self.cfunc.restype def _set_restype(self, restype): self.cfunc.restype = restype restype = property(_get_restype, _set_restype) # errcheck property def _get_errcheck(self): return self.cfunc.errcheck def _set_errcheck(self, errcheck): self.cfunc.errcheck = errcheck errcheck = property(_get_errcheck, _set_errcheck)
[ [ 1, 0, 0.0111, 0.0111, 0, 0.66, 0, 83, 0, 1, 0, 0, 83, 0, 0 ], [ 1, 0, 0.0222, 0.0111, 0, 0.66, 0.1667, 64, 0, 4, 0, 0, 64, 0, 0 ], [ 3, 0, 0.1, 0.1222, 0, 0.66, ...
[ "import threading", "from django.contrib.gis.geos.libgeos import lgeos, notice_h, error_h, CONTEXT_PTR", "class GEOSContextHandle(object):\n \"\"\"\n Python object representing a GEOS context handle.\n \"\"\"\n def __init__(self):\n # Initializing the context handler for this thread with\n ...
from ctypes import c_char from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import check_predicate from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc # Prepared geometry constructor and destructors. geos_prepare = GEOSFunc('GEOSPrepare') geos_prepare.argtypes = [GEOM_PTR] geos_prepare.restype = PREPGEOM_PTR prepared_destroy = GEOSFunc('GEOSPreparedGeom_destroy') prepared_destroy.argtpes = [PREPGEOM_PTR] prepared_destroy.restype = None # Prepared geometry binary predicate support. def prepared_predicate(func): func.argtypes= [PREPGEOM_PTR, GEOM_PTR] func.restype = c_char func.errcheck = check_predicate return func prepared_contains = prepared_predicate(GEOSFunc('GEOSPreparedContains')) prepared_contains_properly = prepared_predicate(GEOSFunc('GEOSPreparedContainsProperly')) prepared_covers = prepared_predicate(GEOSFunc('GEOSPreparedCovers')) prepared_intersects = prepared_predicate(GEOSFunc('GEOSPreparedIntersects'))
[ [ 1, 0, 0.04, 0.04, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.08, 0.04, 0, 0.66, 0.0714, 64, 0, 2, 0, 0, 64, 0, 0 ], [ 1, 0, 0.12, 0.04, 0, 0.66, 0.14...
[ "from ctypes import c_char", "from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR", "from django.contrib.gis.geos.prototypes.errcheck import check_predicate", "from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc", "geos_prepare = GEOSFunc('GEOSPrepare')", "geos_prepare.argtyp...
from ctypes import c_double, c_int, c_uint, POINTER from django.contrib.gis.geos.libgeos import GEOM_PTR, CS_PTR from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc ## Error-checking routines specific to coordinate sequences. ## def check_cs_ptr(result, func, cargs): "Error checking on routines that return Geometries." if not result: raise GEOSException('Error encountered checking Coordinate Sequence returned from GEOS C function "%s".' % func.__name__) return result def check_cs_op(result, func, cargs): "Checks the status code of a coordinate sequence operation." if result == 0: raise GEOSException('Could not set value on coordinate sequence') else: return result def check_cs_get(result, func, cargs): "Checking the coordinate sequence retrieval." check_cs_op(result, func, cargs) # Object in by reference, return its value. return last_arg_byref(cargs) ## Coordinate sequence prototype generation functions. ## def cs_int(func): "For coordinate sequence routines that return an integer." func.argtypes = [CS_PTR, POINTER(c_uint)] func.restype = c_int func.errcheck = check_cs_get return func def cs_operation(func, ordinate=False, get=False): "For coordinate sequence operations." if get: # Get routines get double parameter passed-in by reference. func.errcheck = check_cs_get dbl_param = POINTER(c_double) else: func.errcheck = check_cs_op dbl_param = c_double if ordinate: # Get/Set ordinate routines have an extra uint parameter. func.argtypes = [CS_PTR, c_uint, c_uint, dbl_param] else: func.argtypes = [CS_PTR, c_uint, dbl_param] func.restype = c_int return func def cs_output(func, argtypes): "For routines that return a coordinate sequence." func.argtypes = argtypes func.restype = CS_PTR func.errcheck = check_cs_ptr return func ## Coordinate Sequence ctypes prototypes ## # Coordinate Sequence constructors & cloning. cs_clone = cs_output(GEOSFunc('GEOSCoordSeq_clone'), [CS_PTR]) create_cs = cs_output(GEOSFunc('GEOSCoordSeq_create'), [c_uint, c_uint]) get_cs = cs_output(GEOSFunc('GEOSGeom_getCoordSeq'), [GEOM_PTR]) # Getting, setting ordinate cs_getordinate = cs_operation(GEOSFunc('GEOSCoordSeq_getOrdinate'), ordinate=True, get=True) cs_setordinate = cs_operation(GEOSFunc('GEOSCoordSeq_setOrdinate'), ordinate=True) # For getting, x, y, z cs_getx = cs_operation(GEOSFunc('GEOSCoordSeq_getX'), get=True) cs_gety = cs_operation(GEOSFunc('GEOSCoordSeq_getY'), get=True) cs_getz = cs_operation(GEOSFunc('GEOSCoordSeq_getZ'), get=True) # For setting, x, y, z cs_setx = cs_operation(GEOSFunc('GEOSCoordSeq_setX')) cs_sety = cs_operation(GEOSFunc('GEOSCoordSeq_setY')) cs_setz = cs_operation(GEOSFunc('GEOSCoordSeq_setZ')) # These routines return size & dimensions. cs_getsize = cs_int(GEOSFunc('GEOSCoordSeq_getSize')) cs_getdims = cs_int(GEOSFunc('GEOSCoordSeq_getDimensions'))
[ [ 1, 0, 0.012, 0.012, 0, 0.66, 0, 182, 0, 4, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0241, 0.012, 0, 0.66, 0.0455, 64, 0, 2, 0, 0, 64, 0, 0 ], [ 1, 0, 0.0361, 0.012, 0, 0.66, ...
[ "from ctypes import c_double, c_int, c_uint, POINTER", "from django.contrib.gis.geos.libgeos import GEOM_PTR, CS_PTR", "from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException", "from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc", "def check_cs_ptr(result, func...
""" This module is for the miscellaneous GEOS routines, particularly the ones that return the area, distance, and length. """ from ctypes import c_int, c_double, POINTER from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string from django.contrib.gis.geos.prototypes.geom import geos_char_p from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc __all__ = ['geos_area', 'geos_distance', 'geos_length'] ### ctypes generator function ### def dbl_from_geom(func, num_geom=1): """ Argument is a Geometry, return type is double that is passed in by reference as the last argument. """ argtypes = [GEOM_PTR for i in xrange(num_geom)] argtypes += [POINTER(c_double)] func.argtypes = argtypes func.restype = c_int # Status code returned func.errcheck = check_dbl return func ### ctypes prototypes ### # Area, distance, and length prototypes. geos_area = dbl_from_geom(GEOSFunc('GEOSArea')) geos_distance = dbl_from_geom(GEOSFunc('GEOSDistance'), num_geom=2) geos_length = dbl_from_geom(GEOSFunc('GEOSLength')) # Validity reason; only in GEOS 3.1+ if GEOS_PREPARE: geos_isvalidreason = GEOSFunc('GEOSisValidReason') geos_isvalidreason.argtypes = [GEOM_PTR] geos_isvalidreason.restype = geos_char_p geos_isvalidreason.errcheck = check_string __all__.append('geos_isvalidreason')
[ [ 8, 0, 0.0641, 0.1026, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1282, 0.0256, 0, 0.66, 0.0909, 182, 0, 3, 0, 0, 182, 0, 0 ], [ 1, 0, 0.1538, 0.0256, 0, 0.66...
[ "\"\"\"\n This module is for the miscellaneous GEOS routines, particularly the\n ones that return the area, distance, and length.\n\"\"\"", "from ctypes import c_int, c_double, POINTER", "from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE", "from django.contrib.gis.geos.prototypes.errcheck imp...
""" This module contains all of the GEOS ctypes function prototypes. Each prototype handles the interaction between the GEOS library and Python via ctypes. """ # Coordinate sequence routines. from django.contrib.gis.geos.prototypes.coordseq import create_cs, get_cs, \ cs_clone, cs_getordinate, cs_setordinate, cs_getx, cs_gety, cs_getz, \ cs_setx, cs_sety, cs_setz, cs_getsize, cs_getdims # Geometry routines. from django.contrib.gis.geos.prototypes.geom import from_hex, from_wkb, from_wkt, \ create_point, create_linestring, create_linearring, create_polygon, create_collection, \ destroy_geom, get_extring, get_intring, get_nrings, get_geomn, geom_clone, \ geos_normalize, geos_type, geos_typeid, geos_get_srid, geos_set_srid, \ get_dims, get_num_coords, get_num_geoms, \ to_hex, to_wkb, to_wkt # Miscellaneous routines. from django.contrib.gis.geos.prototypes.misc import * # Predicates from django.contrib.gis.geos.prototypes.predicates import geos_hasz, geos_isempty, \ geos_isring, geos_issimple, geos_isvalid, geos_contains, geos_crosses, \ geos_disjoint, geos_equals, geos_equalsexact, geos_intersects, \ geos_intersects, geos_overlaps, geos_relatepattern, geos_touches, geos_within # Topology routines from django.contrib.gis.geos.prototypes.topology import *
[ [ 8, 0, 0.1, 0.1667, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.3, 0.1, 0, 0.66, 0.2, 928, 0, 13, 0, 0, 928, 0, 0 ], [ 1, 0, 0.5167, 0.2, 0, 0.66, 0.4, ...
[ "\"\"\"\n This module contains all of the GEOS ctypes function prototypes. Each\n prototype handles the interaction between the GEOS library and Python\n via ctypes.\n\"\"\"", "from django.contrib.gis.geos.prototypes.coordseq import create_cs, get_cs, \\\n cs_clone, cs_getordinate, cs_setordinate, cs_getx, cs_...
""" This module houses the GEOS ctypes prototype functions for the unary and binary predicate operations on geometries. """ from ctypes import c_char, c_char_p, c_double from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import check_predicate from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc ## Binary & unary predicate functions ## def binary_predicate(func, *args): "For GEOS binary predicate functions." argtypes = [GEOM_PTR, GEOM_PTR] if args: argtypes += args func.argtypes = argtypes func.restype = c_char func.errcheck = check_predicate return func def unary_predicate(func): "For GEOS unary predicate functions." func.argtypes = [GEOM_PTR] func.restype = c_char func.errcheck = check_predicate return func ## Unary Predicates ## geos_hasz = unary_predicate(GEOSFunc('GEOSHasZ')) geos_isempty = unary_predicate(GEOSFunc('GEOSisEmpty')) geos_isring = unary_predicate(GEOSFunc('GEOSisRing')) geos_issimple = unary_predicate(GEOSFunc('GEOSisSimple')) geos_isvalid = unary_predicate(GEOSFunc('GEOSisValid')) ## Binary Predicates ## geos_contains = binary_predicate(GEOSFunc('GEOSContains')) geos_crosses = binary_predicate(GEOSFunc('GEOSCrosses')) geos_disjoint = binary_predicate(GEOSFunc('GEOSDisjoint')) geos_equals = binary_predicate(GEOSFunc('GEOSEquals')) geos_equalsexact = binary_predicate(GEOSFunc('GEOSEqualsExact'), c_double) geos_intersects = binary_predicate(GEOSFunc('GEOSIntersects')) geos_overlaps = binary_predicate(GEOSFunc('GEOSOverlaps')) geos_relatepattern = binary_predicate(GEOSFunc('GEOSRelatePattern'), c_char_p) geos_touches = binary_predicate(GEOSFunc('GEOSTouches')) geos_within = binary_predicate(GEOSFunc('GEOSWithin'))
[ [ 8, 0, 0.0568, 0.0909, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1136, 0.0227, 0, 0.66, 0.0476, 182, 0, 3, 0, 0, 182, 0, 0 ], [ 1, 0, 0.1364, 0.0227, 0, 0.66...
[ "\"\"\"\n This module houses the GEOS ctypes prototype functions for the\n unary and binary predicate operations on geometries.\n\"\"\"", "from ctypes import c_char, c_char_p, c_double", "from django.contrib.gis.geos.libgeos import GEOM_PTR", "from django.contrib.gis.geos.prototypes.errcheck import check_pred...
# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved. # Released under the New BSD license. """ This module contains a base type which provides list-style mutations without specific data storage methods. See also http://www.aryehleib.com/MutableLists.html Author: Aryeh Leib Taurog. """ class ListMixin(object): """ A base class which provides complete list interface. Derived classes must call ListMixin's __init__() function and implement the following: function _get_single_external(self, i): Return single item with index i for general use. The index i will always satisfy 0 <= i < len(self). function _get_single_internal(self, i): Same as above, but for use within the class [Optional] Note that if _get_single_internal and _get_single_internal return different types of objects, _set_list must distinguish between the two and handle each appropriately. function _set_list(self, length, items): Recreate the entire object. NOTE: items may be a generator which calls _get_single_internal. Therefore, it is necessary to cache the values in a temporary: temp = list(items) before clobbering the original storage. function _set_single(self, i, value): Set the single item at index i to value [Optional] If left undefined, all mutations will result in rebuilding the object using _set_list. function __len__(self): Return the length int _minlength: The minimum legal length [Optional] int _maxlength: The maximum legal length [Optional] type or tuple _allowed: A type or tuple of allowed item types [Optional] class _IndexError: The type of exception to be raise on invalid index [Optional] """ _minlength = 0 _maxlength = None _IndexError = IndexError ### Python initialization and special list interface methods ### def __init__(self, *args, **kwargs): if not hasattr(self, '_get_single_internal'): self._get_single_internal = self._get_single_external if not hasattr(self, '_set_single'): self._set_single = self._set_single_rebuild self._assign_extended_slice = self._assign_extended_slice_rebuild super(ListMixin, self).__init__(*args, **kwargs) def __getitem__(self, index): "Get the item(s) at the specified index/slice." if isinstance(index, slice): return [self._get_single_external(i) for i in xrange(*index.indices(len(self)))] else: index = self._checkindex(index) return self._get_single_external(index) def __delitem__(self, index): "Delete the item(s) at the specified index/slice." if not isinstance(index, (int, long, slice)): raise TypeError("%s is not a legal index" % index) # calculate new length and dimensions origLen = len(self) if isinstance(index, (int, long)): index = self._checkindex(index) indexRange = [index] else: indexRange = range(*index.indices(origLen)) newLen = origLen - len(indexRange) newItems = ( self._get_single_internal(i) for i in xrange(origLen) if i not in indexRange ) self._rebuild(newLen, newItems) def __setitem__(self, index, val): "Set the item(s) at the specified index/slice." if isinstance(index, slice): self._set_slice(index, val) else: index = self._checkindex(index) self._check_allowed((val,)) self._set_single(index, val) def __iter__(self): "Iterate over the items in the list" for i in xrange(len(self)): yield self[i] ### Special methods for arithmetic operations ### def __add__(self, other): 'add another list-like object' return self.__class__(list(self) + list(other)) def __radd__(self, other): 'add to another list-like object' return other.__class__(list(other) + list(self)) def __iadd__(self, other): 'add another list-like object to self' self.extend(list(other)) return self def __mul__(self, n): 'multiply' return self.__class__(list(self) * n) def __rmul__(self, n): 'multiply' return self.__class__(list(self) * n) def __imul__(self, n): 'multiply' if n <= 0: del self[:] else: cache = list(self) for i in range(n-1): self.extend(cache) return self def __cmp__(self, other): 'cmp' slen = len(self) for i in range(slen): try: c = cmp(self[i], other[i]) except IndexError: # must be other is shorter return 1 else: # elements not equal if c: return c return cmp(slen, len(other)) ### Public list interface Methods ### ## Non-mutating ## def count(self, val): "Standard list count method" count = 0 for i in self: if val == i: count += 1 return count def index(self, val): "Standard list index method" for i in xrange(0, len(self)): if self[i] == val: return i raise ValueError('%s not found in object' % str(val)) ## Mutating ## def append(self, val): "Standard list append method" self[len(self):] = [val] def extend(self, vals): "Standard list extend method" self[len(self):] = vals def insert(self, index, val): "Standard list insert method" if not isinstance(index, (int, long)): raise TypeError("%s is not a legal index" % index) self[index:index] = [val] def pop(self, index=-1): "Standard list pop method" result = self[index] del self[index] return result def remove(self, val): "Standard list remove method" del self[self.index(val)] def reverse(self): "Standard list reverse method" self[:] = self[-1::-1] def sort(self, cmp=cmp, key=None, reverse=False): "Standard list sort method" if key: temp = [(key(v),v) for v in self] temp.sort(cmp=cmp, key=lambda x: x[0], reverse=reverse) self[:] = [v[1] for v in temp] else: temp = list(self) temp.sort(cmp=cmp, reverse=reverse) self[:] = temp ### Private routines ### def _rebuild(self, newLen, newItems): if newLen < self._minlength: raise ValueError('Must have at least %d items' % self._minlength) if self._maxlength is not None and newLen > self._maxlength: raise ValueError('Cannot have more than %d items' % self._maxlength) self._set_list(newLen, newItems) def _set_single_rebuild(self, index, value): self._set_slice(slice(index, index + 1, 1), [value]) def _checkindex(self, index, correct=True): length = len(self) if 0 <= index < length: return index if correct and -length <= index < 0: return index + length raise self._IndexError('invalid index: %s' % str(index)) def _check_allowed(self, items): if hasattr(self, '_allowed'): if False in [isinstance(val, self._allowed) for val in items]: raise TypeError('Invalid type encountered in the arguments.') def _set_slice(self, index, values): "Assign values to a slice of the object" try: iter(values) except TypeError: raise TypeError('can only assign an iterable to a slice') self._check_allowed(values) origLen = len(self) valueList = list(values) start, stop, step = index.indices(origLen) # CAREFUL: index.step and step are not the same! # step will never be None if index.step is None: self._assign_simple_slice(start, stop, valueList) else: self._assign_extended_slice(start, stop, step, valueList) def _assign_extended_slice_rebuild(self, start, stop, step, valueList): 'Assign an extended slice by rebuilding entire list' indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError('attempt to assign sequence of size %d ' 'to extended slice of size %d' % (len(valueList), len(indexList))) # we're not changing the length of the sequence newLen = len(self) newVals = dict(zip(indexList, valueList)) def newItems(): for i in xrange(newLen): if i in newVals: yield newVals[i] else: yield self._get_single_internal(i) self._rebuild(newLen, newItems()) def _assign_extended_slice(self, start, stop, step, valueList): 'Assign an extended slice by re-assigning individual items' indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError('attempt to assign sequence of size %d ' 'to extended slice of size %d' % (len(valueList), len(indexList))) for i, val in zip(indexList, valueList): self._set_single(i, val) def _assign_simple_slice(self, start, stop, valueList): 'Assign a simple slice; Can assign slice of any length' origLen = len(self) stop = max(start, stop) newLen = origLen - stop + start + len(valueList) def newItems(): for i in xrange(origLen + 1): if i == start: for val in valueList: yield val if i < origLen: if i < start or i >= stop: yield self._get_single_internal(i) self._rebuild(newLen, newItems())
[ [ 8, 0, 0.021, 0.0259, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.5178, 0.9676, 0, 0.66, 1, 514, 0, 31, 0, 0, 186, 0, 99 ], [ 8, 1, 0.1068, 0.1392, 1, 0.4, ...
[ "\"\"\"\nThis module contains a base type which provides list-style mutations\nwithout specific data storage methods.\n\nSee also http://www.aryehleib.com/MutableLists.html\n\nAuthor: Aryeh Leib Taurog.\n\"\"\"", "class ListMixin(object):\n \"\"\"\n A base class which provides complete list interface.\n ...
""" This module houses the ctypes initialization procedures, as well as the notice and error handler function callbacks (get called when an error occurs in GEOS). This module also houses GEOS Pointer utilities, including get_pointer_arr(), and GEOM_PTR. """ import os, re, sys from ctypes import c_char_p, Structure, CDLL, CFUNCTYPE, POINTER from ctypes.util import find_library from django.contrib.gis.geos.error import GEOSException # Custom library path set? try: from django.conf import settings lib_path = settings.GEOS_LIBRARY_PATH except (AttributeError, EnvironmentError, ImportError): lib_path = None # Setting the appropriate names for the GEOS-C library. if lib_path: lib_names = None elif os.name == 'nt': # Windows NT libraries lib_names = ['libgeos_c-1'] elif os.name == 'posix': # *NIX libraries lib_names = ['geos_c', 'GEOS'] else: raise ImportError('Unsupported OS "%s"' % os.name) # Using the ctypes `find_library` utility to find the path to the GEOS # shared library. This is better than manually specifiying each library name # and extension (e.g., libgeos_c.[so|so.1|dylib].). if lib_names: for lib_name in lib_names: lib_path = find_library(lib_name) if not lib_path is None: break # No GEOS library could be found. if lib_path is None: raise ImportError('Could not find the GEOS library (tried "%s"). ' 'Try setting GEOS_LIBRARY_PATH in your settings.' % '", "'.join(lib_names)) # Getting the GEOS C library. The C interface (CDLL) is used for # both *NIX and Windows. # See the GEOS C API source code for more details on the library function calls: # http://geos.refractions.net/ro/doxygen_docs/html/geos__c_8h-source.html lgeos = CDLL(lib_path) # The notice and error handler C function callback definitions. # Supposed to mimic the GEOS message handler (C below): # typedef void (*GEOSMessageHandler)(const char *fmt, ...); NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p) def notice_h(fmt, lst, output_h=sys.stdout): try: warn_msg = fmt % lst except: warn_msg = fmt output_h.write('GEOS_NOTICE: %s\n' % warn_msg) notice_h = NOTICEFUNC(notice_h) ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p) def error_h(fmt, lst, output_h=sys.stderr): try: err_msg = fmt % lst except: err_msg = fmt output_h.write('GEOS_ERROR: %s\n' % err_msg) error_h = ERRORFUNC(error_h) #### GEOS Geometry C data structures, and utility functions. #### # Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR class GEOSGeom_t(Structure): pass class GEOSPrepGeom_t(Structure): pass class GEOSCoordSeq_t(Structure): pass class GEOSContextHandle_t(Structure): pass # Pointers to opaque GEOS geometry structures. GEOM_PTR = POINTER(GEOSGeom_t) PREPGEOM_PTR = POINTER(GEOSPrepGeom_t) CS_PTR = POINTER(GEOSCoordSeq_t) CONTEXT_PTR = POINTER(GEOSContextHandle_t) # Used specifically by the GEOSGeom_createPolygon and GEOSGeom_createCollection # GEOS routines def get_pointer_arr(n): "Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer." GeomArr = GEOM_PTR * n return GeomArr() # Returns the string version of the GEOS library. Have to set the restype # explicitly to c_char_p to ensure compatibility accross 32 and 64-bit platforms. geos_version = lgeos.GEOSversion geos_version.argtypes = None geos_version.restype = c_char_p # Regular expression should be able to parse version strings such as # '3.0.0rc4-CAPI-1.3.3', or '3.0.0-CAPI-1.4.1' version_regex = re.compile(r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))(rc(?P<release_candidate>\d+))?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)$') def geos_version_info(): """ Returns a dictionary containing the various version metadata parsed from the GEOS version string, including the version number, whether the version is a release candidate (and what number release candidate), and the C API version. """ ver = geos_version() m = version_regex.match(ver) if not m: raise GEOSException('Could not parse version info string "%s"' % ver) return dict((key, m.group(key)) for key in ('version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor')) # Version numbers and whether or not prepared geometry support is available. _verinfo = geos_version_info() GEOS_MAJOR_VERSION = int(_verinfo['major']) GEOS_MINOR_VERSION = int(_verinfo['minor']) GEOS_SUBMINOR_VERSION = int(_verinfo['subminor']) del _verinfo GEOS_VERSION = (GEOS_MAJOR_VERSION, GEOS_MINOR_VERSION, GEOS_SUBMINOR_VERSION) GEOS_PREPARE = GEOS_VERSION >= (3, 1, 0) if GEOS_PREPARE: # Here we set up the prototypes for the initGEOS_r and finishGEOS_r # routines. These functions aren't actually called until they are # attached to a GEOS context handle -- this actually occurs in # geos/prototypes/threadsafe.py. lgeos.initGEOS_r.restype = CONTEXT_PTR lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR] else: # When thread-safety isn't available, the initGEOS routine must be called # first. This function takes the notice and error functions, defined # as Python callbacks above, as parameters. Here is the C code that is # wrapped: # extern void GEOS_DLL initGEOS(GEOSMessageHandler notice_function, GEOSMessageHandler error_function); lgeos.initGEOS(notice_h, error_h) # Calling finishGEOS() upon exit of the interpreter. import atexit atexit.register(lgeos.finishGEOS)
[ [ 8, 0, 0.0319, 0.0567, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0638, 0.0071, 0, 0.66, 0.0278, 688, 0, 3, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0709, 0.0071, 0, 0.66...
[ "\"\"\"\n This module houses the ctypes initialization procedures, as well\n as the notice and error handler function callbacks (get called\n when an error occurs in GEOS).\n\n This module also houses GEOS Pointer utilities, including\n get_pointer_arr(), and GEOM_PTR.\n\"\"\"", "import os, re, sys", "from ctyp...
""" GEOS Testing module. """ from django.utils.unittest import TestSuite, TextTestRunner import test_geos, test_io, test_geos_mutation, test_mutable_list test_suites = [ test_geos.suite(), test_io.suite(), test_geos_mutation.suite(), test_mutable_list.suite(), ] def suite(): "Builds a test suite for the GEOS tests." s = TestSuite() map(s.addTest, test_suites) return s def run(verbosity=1): "Runs the GEOS tests." TextTestRunner(verbosity=verbosity).run(suite()) if __name__ == '__main__': run(2)
[ [ 8, 0, 0.08, 0.12, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.16, 0.04, 0, 0.66, 0.1667, 270, 0, 2, 0, 0, 270, 0, 0 ], [ 1, 0, 0.2, 0.04, 0, 0.66, 0.3333,...
[ "\"\"\"\nGEOS Testing module.\n\"\"\"", "from django.utils.unittest import TestSuite, TextTestRunner", "import test_geos, test_io, test_geos_mutation, test_mutable_list", "test_suites = [\n test_geos.suite(),\n test_io.suite(),\n test_geos_mutation.suite(),\n test_mutable_list.suite(),\n ]", ...
from ctypes import c_uint, byref from django.contrib.gis.geos.error import GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing from django.contrib.gis.geos import prototypes as capi class Polygon(GEOSGeometry): _minlength = 1 def __init__(self, *args, **kwargs): """ Initializes on an exterior ring and a sequence of holes (both instances may be either LinearRing instances, or a tuple/list that may be constructed into a LinearRing). Examples of initialization, where shell, hole1, and hole2 are valid LinearRing geometries: >>> poly = Polygon(shell, hole1, hole2) >>> poly = Polygon(shell, (hole1, hole2)) Example where a tuple parameters are used: >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)), ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4))) """ if not args: raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.') # Getting the ext_ring and init_holes parameters from the argument list ext_ring = args[0] init_holes = args[1:] n_holes = len(init_holes) # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if len(init_holes[0]) == 0: init_holes = () n_holes = 0 elif isinstance(init_holes[0][0], LinearRing): init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) super(Polygon, self).__init__(polygon, **kwargs) def __iter__(self): "Iterates over each ring in the polygon." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of rings in this Polygon." return self.num_interior_rings + 1 @classmethod def from_bbox(cls, bbox): "Constructs a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return GEOSGeometry( 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % ( x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) ### These routines are needed for list-like operation w/ListMixin ### def _create_polygon(self, length, items): # Instantiate LinearRing objects if necessary, but don't clone them yet # _construct_ring will throw a TypeError if a parameter isn't a valid ring # If we cloned the pointers here, we wouldn't be able to clean up # in case of error. rings = [] for r in items: if isinstance(r, GEOM_PTR): rings.append(r) else: rings.append(self._construct_ring(r)) shell = self._clone(rings.pop(0)) n_holes = length - 1 if n_holes: holes = get_pointer_arr(n_holes) for i, r in enumerate(rings): holes[i] = self._clone(r) holes_param = byref(holes) else: holes_param = None return capi.create_polygon(shell, holes_param, c_uint(n_holes)) def _clone(self, g): if isinstance(g, GEOM_PTR): return capi.geom_clone(g) else: return capi.geom_clone(g.ptr) def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'): "Helper routine for trying to construct a ring from the given parameter." if isinstance(param, LinearRing): return param try: ring = LinearRing(param) return ring except TypeError: raise TypeError(msg) def _set_list(self, length, items): # Getting the current pointer, replacing with the newly constructed # geometry, and destroying the old geometry. prev_ptr = self.ptr srid = self.srid self.ptr = self._create_polygon(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) def _get_single_internal(self, index): """ Returns the ring at the specified index. The first index, 0, will always return the exterior ring. Indices > 0 will return the interior ring at the given index (e.g., poly[1] and poly[2] would return the first and second interior ring, respectively). CAREFUL: Internal/External are not the same as Interior/Exterior! _get_single_internal returns a pointer from the existing geometries for use internally by the object's methods. _get_single_external returns a clone of the same geometry for use by external code. """ if index == 0: return capi.get_extring(self.ptr) else: # Getting the interior ring, have to subtract 1 from the index. return capi.get_intring(self.ptr, index-1) def _get_single_external(self, index): return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid) _set_single = GEOSGeometry._set_single_rebuild _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild #### Polygon Properties #### @property def num_interior_rings(self): "Returns the number of interior rings." # Getting the number of rings return capi.get_nrings(self.ptr) def _get_ext_ring(self): "Gets the exterior ring of the Polygon." return self[0] def _set_ext_ring(self, ring): "Sets the exterior ring of the Polygon." self[0] = ring # Properties for the exterior ring/shell. exterior_ring = property(_get_ext_ring, _set_ext_ring) shell = exterior_ring @property def tuple(self): "Gets the tuple for each ring in this Polygon." return tuple([self[i].tuple for i in xrange(len(self))]) coords = tuple @property def kml(self): "Returns the KML representation of this Polygon." inner_kml = ''.join(["<innerBoundaryIs>%s</innerBoundaryIs>" % self[i+1].kml for i in xrange(self.num_interior_rings)]) return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)
[ [ 1, 0, 0.006, 0.006, 0, 0.66, 0, 182, 0, 2, 0, 0, 182, 0, 0 ], [ 1, 0, 0.012, 0.006, 0, 0.66, 0.1667, 827, 0, 1, 0, 0, 827, 0, 0 ], [ 1, 0, 0.0181, 0.006, 0, 0.66,...
[ "from ctypes import c_uint, byref", "from django.contrib.gis.geos.error import GEOSIndexError", "from django.contrib.gis.geos.geometry import GEOSGeometry", "from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR", "from django.contrib.gis.geos.linestring import LinearRing", "from django.co...
from django.contrib.gis.geos.base import GEOSBase from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.prototypes import prepared as capi class PreparedGeometry(GEOSBase): """ A geometry that is prepared for performing certain operations. At the moment this includes the contains covers, and intersects operations. """ ptr_type = capi.PREPGEOM_PTR def __init__(self, geom): if not isinstance(geom, GEOSGeometry): raise TypeError self.ptr = capi.geos_prepare(geom.ptr) def __del__(self): if self._ptr: capi.prepared_destroy(self._ptr) def contains(self, other): return capi.prepared_contains(self.ptr, other.ptr) def contains_properly(self, other): return capi.prepared_contains_properly(self.ptr, other.ptr) def covers(self, other): return capi.prepared_covers(self.ptr, other.ptr) def intersects(self, other): return capi.prepared_intersects(self.ptr, other.ptr)
[ [ 1, 0, 0.0333, 0.0333, 0, 0.66, 0, 386, 0, 1, 0, 0, 386, 0, 0 ], [ 1, 0, 0.0667, 0.0333, 0, 0.66, 0.3333, 843, 0, 1, 0, 0, 843, 0, 0 ], [ 1, 0, 0.1, 0.0333, 0, 0.6...
[ "from django.contrib.gis.geos.base import GEOSBase", "from django.contrib.gis.geos.geometry import GEOSGeometry", "from django.contrib.gis.geos.prototypes import prepared as capi", "class PreparedGeometry(GEOSBase):\n \"\"\"\n A geometry that is prepared for performing certain operations.\n At the mo...
""" This module houses the GEOSCoordSeq object, which is used internally by GEOSGeometry to house the actual coordinates of the Point, LineString, and LinearRing geometries. """ from ctypes import c_double, c_uint, byref from django.contrib.gis.geos.base import GEOSBase, numpy from django.contrib.gis.geos.error import GEOSException, GEOSIndexError from django.contrib.gis.geos.libgeos import CS_PTR from django.contrib.gis.geos import prototypes as capi class GEOSCoordSeq(GEOSBase): "The internal representation of a list of coordinates inside a Geometry." ptr_type = CS_PTR #### Python 'magic' routines #### def __init__(self, ptr, z=False): "Initializes from a GEOS pointer." if not isinstance(ptr, CS_PTR): raise TypeError('Coordinate sequence should initialize with a CS_PTR.') self._ptr = ptr self._z = z def __iter__(self): "Iterates over each point in the coordinate sequence." for i in xrange(self.size): yield self[i] def __len__(self): "Returns the number of points in the coordinate sequence." return int(self.size) def __str__(self): "Returns the string representation of the coordinate sequence." return str(self.tuple) def __getitem__(self, index): "Returns the coordinate sequence value at the given index." coords = [self.getX(index), self.getY(index)] if self.dims == 3 and self._z: coords.append(self.getZ(index)) return tuple(coords) def __setitem__(self, index, value): "Sets the coordinate sequence value at the given index." # Checking the input value if isinstance(value, (list, tuple)): pass elif numpy and isinstance(value, numpy.ndarray): pass else: raise TypeError('Must set coordinate with a sequence (list, tuple, or numpy array).') # Checking the dims of the input if self.dims == 3 and self._z: n_args = 3 set_3d = True else: n_args = 2 set_3d = False if len(value) != n_args: raise TypeError('Dimension of value does not match.') # Setting the X, Y, Z self.setX(index, value[0]) self.setY(index, value[1]) if set_3d: self.setZ(index, value[2]) #### Internal Routines #### def _checkindex(self, index): "Checks the given index." sz = self.size if (sz < 1) or (index < 0) or (index >= sz): raise GEOSIndexError('invalid GEOS Geometry index: %s' % str(index)) def _checkdim(self, dim): "Checks the given dimension." if dim < 0 or dim > 2: raise GEOSException('invalid ordinate dimension "%d"' % dim) #### Ordinate getting and setting routines #### def getOrdinate(self, dimension, index): "Returns the value for the given dimension and index." self._checkindex(index) self._checkdim(dimension) return capi.cs_getordinate(self.ptr, index, dimension, byref(c_double())) def setOrdinate(self, dimension, index, value): "Sets the value for the given dimension and index." self._checkindex(index) self._checkdim(dimension) capi.cs_setordinate(self.ptr, index, dimension, value) def getX(self, index): "Get the X value at the index." return self.getOrdinate(0, index) def setX(self, index, value): "Set X with the value at the given index." self.setOrdinate(0, index, value) def getY(self, index): "Get the Y value at the given index." return self.getOrdinate(1, index) def setY(self, index, value): "Set Y with the value at the given index." self.setOrdinate(1, index, value) def getZ(self, index): "Get Z with the value at the given index." return self.getOrdinate(2, index) def setZ(self, index, value): "Set Z with the value at the given index." self.setOrdinate(2, index, value) ### Dimensions ### @property def size(self): "Returns the size of this coordinate sequence." return capi.cs_getsize(self.ptr, byref(c_uint())) @property def dims(self): "Returns the dimensions of this coordinate sequence." return capi.cs_getdims(self.ptr, byref(c_uint())) @property def hasz(self): """ Returns whether this coordinate sequence is 3D. This property value is inherited from the parent Geometry. """ return self._z ### Other Methods ### def clone(self): "Clones this coordinate sequence." return GEOSCoordSeq(capi.cs_clone(self.ptr), self.hasz) @property def kml(self): "Returns the KML representation for the coordinates." # Getting the substitution string depending on whether the coordinates have # a Z dimension. if self.hasz: substr = '%s,%s,%s ' else: substr = '%s,%s,0 ' return '<coordinates>%s</coordinates>' % \ ''.join([substr % self[i] for i in xrange(len(self))]).strip() @property def tuple(self): "Returns a tuple version of this coordinate sequence." n = self.size if n == 1: return self[0] else: return tuple([self[i] for i in xrange(n)])
[ [ 8, 0, 0.0192, 0.0321, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0385, 0.0064, 0, 0.66, 0.1667, 182, 0, 3, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0449, 0.0064, 0, 0.66...
[ "\"\"\"\n This module houses the GEOSCoordSeq object, which is used internally\n by GEOSGeometry to house the actual coordinates of the Point,\n LineString, and LinearRing geometries.\n\"\"\"", "from ctypes import c_double, c_uint, byref", "from django.contrib.gis.geos.base import GEOSBase, numpy", "from djan...
from ctypes import c_void_p from types import NoneType from django.contrib.gis.geos.error import GEOSException, GEOSIndexError # Trying to import GDAL libraries, if available. Have to place in # try/except since this package may be used outside GeoDjango. try: from django.contrib.gis import gdal except ImportError: # A 'dummy' gdal module. class GDALInfo(object): HAS_GDAL = False GEOJSON = False gdal = GDALInfo() # NumPy supported? try: import numpy except ImportError: numpy = False class GEOSBase(object): """ Base object for GEOS objects that has a pointer access property that controls access to the underlying C pointer. """ # Initially the pointer is NULL. _ptr = None # Default allowed pointer type. ptr_type = c_void_p # Pointer access property. def _get_ptr(self): # Raise an exception if the pointer isn't valid don't # want to be passing NULL pointers to routines -- # that's very bad. if self._ptr: return self._ptr else: raise GEOSException('NULL GEOS %s pointer encountered.' % self.__class__.__name__) def _set_ptr(self, ptr): # Only allow the pointer to be set with pointers of the # compatible type or None (NULL). if isinstance(ptr, (self.ptr_type, NoneType)): self._ptr = ptr else: raise TypeError('Incompatible pointer type') # Property for controlling access to the GEOS object pointers. Using # this raises an exception when the pointer is NULL, thus preventing # the C library from attempting to access an invalid memory location. ptr = property(_get_ptr, _set_ptr)
[ [ 1, 0, 0.0192, 0.0192, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0385, 0.0192, 0, 0.66, 0.2, 209, 0, 1, 0, 0, 209, 0, 0 ], [ 1, 0, 0.0577, 0.0192, 0, 0.6...
[ "from ctypes import c_void_p", "from types import NoneType", "from django.contrib.gis.geos.error import GEOSException, GEOSIndexError", "try:\n from django.contrib.gis import gdal\nexcept ImportError:\n # A 'dummy' gdal module.\n class GDALInfo(object):\n HAS_GDAL = False\n GEOJSON = Fa...
""" This module contains the 'base' GEOSGeometry object -- all GEOS Geometries inherit from this object. """ # Python, ctypes and types dependencies. import re from ctypes import addressof, byref, c_double, c_size_t # super-class for mutable list behavior from django.contrib.gis.geos.mutable_list import ListMixin # GEOS-related dependencies. from django.contrib.gis.geos.base import GEOSBase, gdal from django.contrib.gis.geos.coordseq import GEOSCoordSeq from django.contrib.gis.geos.error import GEOSException, GEOSIndexError from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE from django.contrib.gis.geos.mutable_list import ListMixin # All other functions in this module come from the ctypes # prototypes module -- which handles all interaction with # the underlying GEOS library. from django.contrib.gis.geos import prototypes as capi # These functions provide access to a thread-local instance # of their corresponding GEOS I/O class. from django.contrib.gis.geos.prototypes.io import wkt_r, wkt_w, wkb_r, wkb_w, ewkb_w, ewkb_w3d # For recognizing geometry input. from django.contrib.gis.geometry.regex import hex_regex, wkt_regex, json_regex class GEOSGeometry(GEOSBase, ListMixin): "A class that, generally, encapsulates a GEOS geometry." # Raise GEOSIndexError instead of plain IndexError # (see ticket #4740 and GEOSIndexError docstring) _IndexError = GEOSIndexError ptr_type = GEOM_PTR #### Python 'magic' routines #### def __init__(self, geo_input, srid=None): """ The base constructor for GEOS geometry objects, and may take the following inputs: * strings: - WKT - HEXEWKB (a PostGIS-specific canonical form) - GeoJSON (requires GDAL) * buffer: - WKB The `srid` keyword is used to specify the Source Reference Identifier (SRID) number for this Geometry. If not set, the SRID will be None. """ if isinstance(geo_input, basestring): if isinstance(geo_input, unicode): # Encoding to ASCII, WKT or HEXEWKB doesn't need any more. geo_input = geo_input.encode('ascii') wkt_m = wkt_regex.match(geo_input) if wkt_m: # Handling WKT input. if wkt_m.group('srid'): srid = int(wkt_m.group('srid')) g = wkt_r().read(wkt_m.group('wkt')) elif hex_regex.match(geo_input): # Handling HEXEWKB input. g = wkb_r().read(geo_input) elif gdal.GEOJSON and json_regex.match(geo_input): # Handling GeoJSON input. g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb) else: raise ValueError('String or unicode input unrecognized as WKT EWKT, and HEXEWKB.') elif isinstance(geo_input, GEOM_PTR): # When the input is a pointer to a geomtry (GEOM_PTR). g = geo_input elif isinstance(geo_input, buffer): # When the input is a buffer (WKB). g = wkb_r().read(geo_input) elif isinstance(geo_input, GEOSGeometry): g = capi.geom_clone(geo_input.ptr) else: # Invalid geometry type. raise TypeError('Improper geometry input type: %s' % str(type(geo_input))) if bool(g): # Setting the pointer object with a valid pointer. self.ptr = g else: raise GEOSException('Could not initialize GEOS Geometry with given input.') # Post-initialization setup. self._post_init(srid) def _post_init(self, srid): "Helper routine for performing post-initialization setup." # Setting the SRID, if given. if srid and isinstance(srid, int): self.srid = srid # Setting the class type (e.g., Point, Polygon, etc.) self.__class__ = GEOS_CLASSES[self.geom_typeid] # Setting the coordinate sequence for the geometry (will be None on # geometries that do not have coordinate sequences) self._set_cs() def __del__(self): """ Destroys this Geometry; in other words, frees the memory used by the GEOS C++ object. """ if self._ptr: capi.destroy_geom(self._ptr) def __copy__(self): """ Returns a clone because the copy of a GEOSGeometry may contain an invalid pointer location if the original is garbage collected. """ return self.clone() def __deepcopy__(self, memodict): """ The `deepcopy` routine is used by the `Node` class of django.utils.tree; thus, the protocol routine needs to be implemented to return correct copies (clones) of these GEOS objects, which use C pointers. """ return self.clone() def __str__(self): "WKT is used for the string representation." return self.wkt def __repr__(self): "Short-hand representation because WKT may be very large." return '<%s object at %s>' % (self.geom_type, hex(addressof(self.ptr))) # Pickling support def __getstate__(self): # The pickled state is simply a tuple of the WKB (in string form) # and the SRID. return str(self.wkb), self.srid def __setstate__(self, state): # Instantiating from the tuple state that was pickled. wkb, srid = state ptr = wkb_r().read(buffer(wkb)) if not ptr: raise GEOSException('Invalid Geometry loaded from pickled state.') self.ptr = ptr self._post_init(srid) # Comparison operators def __eq__(self, other): """ Equivalence testing, a Geometry may be compared with another Geometry or a WKT representation. """ if isinstance(other, basestring): return self.wkt == other elif isinstance(other, GEOSGeometry): return self.equals_exact(other) else: return False def __ne__(self, other): "The not equals operator." return not (self == other) ### Geometry set-like operations ### # Thanks to Sean Gillies for inspiration: # http://lists.gispython.org/pipermail/community/2007-July/001034.html # g = g1 | g2 def __or__(self, other): "Returns the union of this Geometry and the other." return self.union(other) # g = g1 & g2 def __and__(self, other): "Returns the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) #### Coordinate Sequence Routines #### @property def has_cs(self): "Returns True if this Geometry has a coordinate sequence, False if not." # Only these geometries are allowed to have coordinate sequences. if isinstance(self, (Point, LineString, LinearRing)): return True else: return False def _set_cs(self): "Sets the coordinate sequence for this Geometry." if self.has_cs: self._cs = GEOSCoordSeq(capi.get_cs(self.ptr), self.hasz) else: self._cs = None @property def coord_seq(self): "Returns a clone of the coordinate sequence for this Geometry." if self.has_cs: return self._cs.clone() #### Geometry Info #### @property def geom_type(self): "Returns a string representing the Geometry type, e.g. 'Polygon'" return capi.geos_type(self.ptr) @property def geom_typeid(self): "Returns an integer representing the Geometry type." return capi.geos_typeid(self.ptr) @property def num_geom(self): "Returns the number of geometries in the Geometry." return capi.get_num_geoms(self.ptr) @property def num_coords(self): "Returns the number of coordinates in the Geometry." return capi.get_num_coords(self.ptr) @property def num_points(self): "Returns the number points, or coordinates, in the Geometry." return self.num_coords @property def dims(self): "Returns the dimension of this Geometry (0=point, 1=line, 2=surface)." return capi.get_dims(self.ptr) def normalize(self): "Converts this Geometry to normal form (or canonical form)." return capi.geos_normalize(self.ptr) #### Unary predicates #### @property def empty(self): """ Returns a boolean indicating whether the set of points in this Geometry are empty. """ return capi.geos_isempty(self.ptr) @property def hasz(self): "Returns whether the geometry has a 3D dimension." return capi.geos_hasz(self.ptr) @property def ring(self): "Returns whether or not the geometry is a ring." return capi.geos_isring(self.ptr) @property def simple(self): "Returns false if the Geometry not simple." return capi.geos_issimple(self.ptr) @property def valid(self): "This property tests the validity of this Geometry." return capi.geos_isvalid(self.ptr) @property def valid_reason(self): """ Returns a string containing the reason for any invalidity. """ if not GEOS_PREPARE: raise GEOSException('Upgrade GEOS to 3.1 to get validity reason.') return capi.geos_isvalidreason(self.ptr) #### Binary predicates. #### def contains(self, other): "Returns true if other.within(this) returns true." return capi.geos_contains(self.ptr, other.ptr) def crosses(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is T*T****** (for a point and a curve,a point and an area or a line and an area) 0******** (for two curves). """ return capi.geos_crosses(self.ptr, other.ptr) def disjoint(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is FF*FF****. """ return capi.geos_disjoint(self.ptr, other.ptr) def equals(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is T*F**FFF*. """ return capi.geos_equals(self.ptr, other.ptr) def equals_exact(self, other, tolerance=0): """ Returns true if the two Geometries are exactly equal, up to a specified tolerance. """ return capi.geos_equalsexact(self.ptr, other.ptr, float(tolerance)) def intersects(self, other): "Returns true if disjoint returns false." return capi.geos_intersects(self.ptr, other.ptr) def overlaps(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves). """ return capi.geos_overlaps(self.ptr, other.ptr) def relate_pattern(self, other, pattern): """ Returns true if the elements in the DE-9IM intersection matrix for the two Geometries match the elements in pattern. """ if not isinstance(pattern, basestring) or len(pattern) > 9: raise GEOSException('invalid intersection matrix pattern') return capi.geos_relatepattern(self.ptr, other.ptr, pattern) def touches(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is FT*******, F**T***** or F***T****. """ return capi.geos_touches(self.ptr, other.ptr) def within(self, other): """ Returns true if the DE-9IM intersection matrix for the two Geometries is T*F**F***. """ return capi.geos_within(self.ptr, other.ptr) #### SRID Routines #### def get_srid(self): "Gets the SRID for the geometry, returns None if no SRID is set." s = capi.geos_get_srid(self.ptr) if s == 0: return None else: return s def set_srid(self, srid): "Sets the SRID for the geometry." capi.geos_set_srid(self.ptr, srid) srid = property(get_srid, set_srid) #### Output Routines #### @property def ewkt(self): """ Returns the EWKT (WKT + SRID) of the Geometry. Note that Z values are *not* included in this representation because GEOS does not yet support serializing them. """ if self.get_srid(): return 'SRID=%s;%s' % (self.srid, self.wkt) else: return self.wkt @property def wkt(self): "Returns the WKT (Well-Known Text) representation of this Geometry." return wkt_w().write(self) @property def hex(self): """ Returns the WKB of this Geometry in hexadecimal form. Please note that the SRID and Z values are not included in this representation because it is not a part of the OGC specification (use the `hexewkb` property instead). """ # A possible faster, all-python, implementation: # str(self.wkb).encode('hex') return wkb_w().write_hex(self) @property def hexewkb(self): """ Returns the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes SRID and Z values that are a part of this geometry. """ if self.hasz: if not GEOS_PREPARE: # See: http://trac.osgeo.org/geos/ticket/216 raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D HEXEWKB.') return ewkb_w3d().write_hex(self) else: return ewkb_w().write_hex(self) @property def json(self): """ Returns GeoJSON representation of this Geometry if GDAL 1.5+ is installed. """ if gdal.GEOJSON: return self.ogr.json else: raise GEOSException('GeoJSON output only supported on GDAL 1.5+.') geojson = json @property def wkb(self): """ Returns the WKB (Well-Known Binary) representation of this Geometry as a Python buffer. SRID and Z values are not included, use the `ewkb` property instead. """ return wkb_w().write(self) @property def ewkb(self): """ Return the EWKB representation of this Geometry as a Python buffer. This is an extension of the WKB specification that includes any SRID and Z values that are a part of this geometry. """ if self.hasz: if not GEOS_PREPARE: # See: http://trac.osgeo.org/geos/ticket/216 raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D EWKB.') return ewkb_w3d().write(self) else: return ewkb_w().write(self) @property def kml(self): "Returns the KML representation of this Geometry." gtype = self.geom_type return '<%s>%s</%s>' % (gtype, self.coord_seq.kml, gtype) @property def prepared(self): """ Returns a PreparedGeometry corresponding to this geometry -- it is optimized for the contains, intersects, and covers operations. """ if GEOS_PREPARE: return PreparedGeometry(self) else: raise GEOSException('GEOS 3.1+ required for prepared geometry support.') #### GDAL-specific output routines #### @property def ogr(self): "Returns the OGR Geometry for this Geometry." if gdal.HAS_GDAL: if self.srid: return gdal.OGRGeometry(self.wkb, self.srid) else: return gdal.OGRGeometry(self.wkb) else: raise GEOSException('GDAL required to convert to an OGRGeometry.') @property def srs(self): "Returns the OSR SpatialReference for SRID of this Geometry." if gdal.HAS_GDAL: if self.srid: return gdal.SpatialReference(self.srid) else: return None else: raise GEOSException('GDAL required to return a SpatialReference object.') @property def crs(self): "Alias for `srs` property." return self.srs def transform(self, ct, clone=False): """ Requires GDAL. Transforms the geometry according to the given transformation object, which may be an integer SRID, and WKT or PROJ.4 string. By default, the geometry is transformed in-place and nothing is returned. However if the `clone` keyword is set, then this geometry will not be modified and a transformed clone will be returned instead. """ srid = self.srid if gdal.HAS_GDAL and srid: # Creating an OGR Geometry, which is then transformed. g = gdal.OGRGeometry(self.wkb, srid) g.transform(ct) # Getting a new GEOS pointer ptr = wkb_r().read(g.wkb) if clone: # User wants a cloned transformed geometry returned. return GEOSGeometry(ptr, srid=g.srid) if ptr: # Reassigning pointer, and performing post-initialization setup # again due to the reassignment. capi.destroy_geom(self.ptr) self.ptr = ptr self._post_init(g.srid) else: raise GEOSException('Transformed WKB was invalid.') #### Topology Routines #### def _topology(self, gptr): "Helper routine to return Geometry from the given pointer." return GEOSGeometry(gptr, srid=self.srid) @property def boundary(self): "Returns the boundary as a newly allocated Geometry object." return self._topology(capi.geos_boundary(self.ptr)) def buffer(self, width, quadsegs=8): """ Returns a geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this Geometry. The optional third parameter sets the number of segment used to approximate a quarter circle (defaults to 8). (Text from PostGIS documentation at ch. 6.1.3) """ return self._topology(capi.geos_buffer(self.ptr, width, quadsegs)) @property def centroid(self): """ The centroid is equal to the centroid of the set of component Geometries of highest dimension (since the lower-dimension geometries contribute zero "weight" to the centroid). """ return self._topology(capi.geos_centroid(self.ptr)) @property def convex_hull(self): """ Returns the smallest convex Polygon that contains all the points in the Geometry. """ return self._topology(capi.geos_convexhull(self.ptr)) def difference(self, other): """ Returns a Geometry representing the points making up this Geometry that do not make up other. """ return self._topology(capi.geos_difference(self.ptr, other.ptr)) @property def envelope(self): "Return the envelope for this geometry (a polygon)." return self._topology(capi.geos_envelope(self.ptr)) def intersection(self, other): "Returns a Geometry representing the points shared by this Geometry and other." return self._topology(capi.geos_intersection(self.ptr, other.ptr)) @property def point_on_surface(self): "Computes an interior point of this Geometry." return self._topology(capi.geos_pointonsurface(self.ptr)) def relate(self, other): "Returns the DE-9IM intersection matrix for this Geometry and the other." return capi.geos_relate(self.ptr, other.ptr) def simplify(self, tolerance=0.0, preserve_topology=False): """ Returns the Geometry, simplified using the Douglas-Peucker algorithm to the specified tolerance (higher tolerance => less points). If no tolerance provided, defaults to 0. By default, this function does not preserve topology - e.g. polygons can be split, collapse to lines or disappear holes can be created or disappear, and lines can cross. By specifying preserve_topology=True, the result will have the same dimension and number of components as the input. This is significantly slower. """ if preserve_topology: return self._topology(capi.geos_preservesimplify(self.ptr, tolerance)) else: return self._topology(capi.geos_simplify(self.ptr, tolerance)) def sym_difference(self, other): """ Returns a set combining the points in this Geometry not in other, and the points in other not in this Geometry. """ return self._topology(capi.geos_symdifference(self.ptr, other.ptr)) def union(self, other): "Returns a Geometry representing all the points in this Geometry and other." return self._topology(capi.geos_union(self.ptr, other.ptr)) #### Other Routines #### @property def area(self): "Returns the area of the Geometry." return capi.geos_area(self.ptr, byref(c_double())) def distance(self, other): """ Returns the distance between the closest points on this Geometry and the other. Units will be in those of the coordinate system of the Geometry. """ if not isinstance(other, GEOSGeometry): raise TypeError('distance() works only on other GEOS Geometries.') return capi.geos_distance(self.ptr, other.ptr, byref(c_double())) @property def extent(self): """ Returns the extent of this geometry as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ env = self.envelope if isinstance(env, Point): xmin, ymin = env.tuple xmax, ymax = xmin, ymin else: xmin, ymin = env[0][0] xmax, ymax = env[0][2] return (xmin, ymin, xmax, ymax) @property def length(self): """ Returns the length of this Geometry (e.g., 0 for point, or the circumfrence of a Polygon). """ return capi.geos_length(self.ptr, byref(c_double())) def clone(self): "Clones this Geometry." return GEOSGeometry(capi.geom_clone(self.ptr), srid=self.srid) # Class mapping dictionary. Has to be at the end to avoid import # conflicts with GEOSGeometry. from django.contrib.gis.geos.linestring import LineString, LinearRing from django.contrib.gis.geos.point import Point from django.contrib.gis.geos.polygon import Polygon from django.contrib.gis.geos.collections import GeometryCollection, MultiPoint, MultiLineString, MultiPolygon GEOS_CLASSES = {0 : Point, 1 : LineString, 2 : LinearRing, 3 : Polygon, 4 : MultiPoint, 5 : MultiLineString, 6 : MultiPolygon, 7 : GeometryCollection, } # If supported, import the PreparedGeometry class. if GEOS_PREPARE: from django.contrib.gis.geos.prepared import PreparedGeometry
[ [ 8, 0, 0.0037, 0.006, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.009, 0.0015, 0, 0.66, 0.0556, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0104, 0.0015, 0, 0.66, ...
[ "\"\"\"\n This module contains the 'base' GEOSGeometry object -- all GEOS Geometries\n inherit from this object.\n\"\"\"", "import re", "from ctypes import addressof, byref, c_double, c_size_t", "from django.contrib.gis.geos.mutable_list import ListMixin", "from django.contrib.gis.geos.base import GEOSBase,...
from ctypes import c_uint from django.contrib.gis.geos.error import GEOSException from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos import prototypes as capi class Point(GEOSGeometry): _minlength = 2 _maxlength = 3 def __init__(self, x, y=None, z=None, srid=None): """ The Point object may be initialized with either a tuple, or individual parameters. For Example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters """ if isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. ndim = len(x) coords = x elif isinstance(x, (int, float, long)) and isinstance(y, (int, float, long)): # Here X, Y, and (optionally) Z were passed in individually, as parameters. if isinstance(z, (int, float, long)): ndim = 3 coords = [x, y, z] else: ndim = 2 coords = [x, y] else: raise TypeError('Invalid parameters given for Point initialization.') point = self._create_point(ndim, coords) # Initializing using the address returned from the GEOS # createPoint factory. super(Point, self).__init__(point, srid=srid) def _create_point(self, ndim, coords): """ Create a coordinate sequence, set X, Y, [Z], and create point """ if ndim < 2 or ndim > 3: raise TypeError('Invalid point dimension: %s' % str(ndim)) cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) capi.cs_setx(cs, 0, i.next()) capi.cs_sety(cs, 0, i.next()) if ndim == 3: capi.cs_setz(cs, 0, i.next()) return capi.create_point(cs) def _set_list(self, length, items): ptr = self._create_point(length, items) if ptr: capi.destroy_geom(self.ptr) self._ptr = ptr self._set_cs() else: # can this happen? raise GEOSException('Geometry resulting from slice deletion was invalid.') def _set_single(self, index, value): self._cs.setOrdinate(index, 0, value) def __iter__(self): "Allows iteration over coordinates of this Point." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of dimensions for this Point (either 0, 2 or 3)." if self.empty: return 0 if self.hasz: return 3 else: return 2 def _get_single_external(self, index): if index == 0: return self.x elif index == 1: return self.y elif index == 2: return self.z _get_single_internal = _get_single_external def get_x(self): "Returns the X component of the Point." return self._cs.getOrdinate(0, 0) def set_x(self, value): "Sets the X component of the Point." self._cs.setOrdinate(0, 0, value) def get_y(self): "Returns the Y component of the Point." return self._cs.getOrdinate(1, 0) def set_y(self, value): "Sets the Y component of the Point." self._cs.setOrdinate(1, 0, value) def get_z(self): "Returns the Z component of the Point." if self.hasz: return self._cs.getOrdinate(2, 0) else: return None def set_z(self, value): "Sets the Z component of the Point." if self.hasz: self._cs.setOrdinate(2, 0, value) else: raise GEOSException('Cannot set Z on 2D Point.') # X, Y, Z properties x = property(get_x, set_x) y = property(get_y, set_y) z = property(get_z, set_z) ### Tuple setting and retrieval routines. ### def get_coords(self): "Returns a tuple of the point." return self._cs.tuple def set_coords(self, tup): "Sets the coordinates of the point with the given tuple." self._cs[0] = tup # The tuple and coords properties tuple = property(get_coords, set_coords) coords = tuple
[ [ 1, 0, 0.0074, 0.0074, 0, 0.66, 0, 182, 0, 1, 0, 0, 182, 0, 0 ], [ 1, 0, 0.0148, 0.0074, 0, 0.66, 0.25, 827, 0, 1, 0, 0, 827, 0, 0 ], [ 1, 0, 0.0222, 0.0074, 0, 0....
[ "from ctypes import c_uint", "from django.contrib.gis.geos.error import GEOSException", "from django.contrib.gis.geos.geometry import GEOSGeometry", "from django.contrib.gis.geos import prototypes as capi", "class Point(GEOSGeometry):\n _minlength = 2\n _maxlength = 3\n\n def __init__(self, x, y=No...
""" The GeoDjango GEOS module. Please consult the GeoDjango documentation for more details: http://geodjango.org/docs/geos.html """ from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex from django.contrib.gis.geos.point import Point from django.contrib.gis.geos.linestring import LineString, LinearRing from django.contrib.gis.geos.polygon import Polygon from django.contrib.gis.geos.collections import GeometryCollection, MultiPoint, MultiLineString, MultiPolygon from django.contrib.gis.geos.error import GEOSException, GEOSIndexError from django.contrib.gis.geos.io import WKTReader, WKTWriter, WKBReader, WKBWriter from django.contrib.gis.geos.factory import fromfile, fromstr from django.contrib.gis.geos.libgeos import geos_version, geos_version_info, GEOS_PREPARE
[ [ 8, 0, 0.2143, 0.3571, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.4286, 0.0714, 0, 0.66, 0.1111, 843, 0, 3, 0, 0, 843, 0, 0 ], [ 1, 0, 0.5, 0.0714, 0, 0.66, ...
[ "\"\"\"\nThe GeoDjango GEOS module. Please consult the GeoDjango documentation\nfor more details: \n http://geodjango.org/docs/geos.html\n\"\"\"", "from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex", "from django.contrib.gis.geos.point import Point", "from django.contrib.gis.ge...
from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex def fromfile(file_h): """ Given a string file name, returns a GEOSGeometry. The file may contain WKB, WKT, or HEX. """ # If given a file name, get a real handle. if isinstance(file_h, basestring): file_h = open(file_h, 'rb') # Reading in the file's contents, buf = file_h.read() # If we get WKB need to wrap in buffer(), so run through regexes. if wkt_regex.match(buf) or hex_regex.match(buf): return GEOSGeometry(buf) else: return GEOSGeometry(buffer(buf)) def fromstr(string, **kwargs): "Given a string value, returns a GEOSGeometry object." return GEOSGeometry(string, **kwargs)
[ [ 1, 0, 0.0435, 0.0435, 0, 0.66, 0, 843, 0, 3, 0, 0, 843, 0, 0 ], [ 2, 0, 0.4783, 0.7391, 0, 0.66, 0.5, 768, 0, 1, 1, 0, 0, 0, 8 ], [ 8, 1, 0.2391, 0.1739, 1, 0.75,...
[ "from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex", "def fromfile(file_h):\n \"\"\"\n Given a string file name, returns a GEOSGeometry. The file may contain WKB,\n WKT, or HEX.\n \"\"\"\n # If given a file name, get a real handle.\n if isinstance(file_h, basestring...
from optparse import make_option from django.core.management.base import CommandError from django.core.management.commands.inspectdb import Command as InspectDBCommand class Command(InspectDBCommand): db_module = 'django.contrib.gis.db' gis_tables = {} def get_field_type(self, connection, table_name, row): field_type, field_params, field_notes = super(Command, self).get_field_type(connection, table_name, row) if field_type == 'GeometryField': geo_col = row[0] # Getting a more specific field type and any additional parameters # from the `get_geometry_type` routine for the spatial backend. field_type, geo_params = connection.introspection.get_geometry_type(table_name, geo_col) field_params.update(geo_params) # Adding the table name and column to the `gis_tables` dictionary, this # allows us to track which tables need a GeoManager. if table_name in self.gis_tables: self.gis_tables[table_name].append(geo_col) else: self.gis_tables[table_name] = [geo_col] return field_type, field_params, field_notes def get_meta(self, table_name): meta_lines = super(Command, self).get_meta(table_name) if table_name in self.gis_tables: # If the table is a geographic one, then we need make # GeoManager the default manager for the model. meta_lines.insert(0, ' objects = models.GeoManager()') return meta_lines
[ [ 1, 0, 0.0312, 0.0312, 0, 0.66, 0, 323, 0, 1, 0, 0, 323, 0, 0 ], [ 1, 0, 0.0938, 0.0312, 0, 0.66, 0.3333, 931, 0, 1, 0, 0, 931, 0, 0 ], [ 1, 0, 0.125, 0.0312, 0, 0...
[ "from optparse import make_option", "from django.core.management.base import CommandError", "from django.core.management.commands.inspectdb import Command as InspectDBCommand", "class Command(InspectDBCommand):\n db_module = 'django.contrib.gis.db'\n gis_tables = {}\n\n def get_field_type(self, conne...
from django.core.management.base import BaseCommand, CommandError class ArgsCommand(BaseCommand): """ Command class for commands that take multiple arguments. """ args = '<arg arg ...>' def handle(self, *args, **options): if not args: raise CommandError('Must provide the following arguments: %s' % self.args) return self.handle_args(*args, **options) def handle_args(self, *args, **options): raise NotImplementedError()
[ [ 1, 0, 0.0667, 0.0667, 0, 0.66, 0, 931, 0, 2, 0, 0, 931, 0, 0 ], [ 3, 0, 0.6, 0.8667, 0, 0.66, 1, 116, 0, 2, 0, 0, 564, 0, 3 ], [ 8, 1, 0.3333, 0.2, 1, 0.42, 0...
[ "from django.core.management.base import BaseCommand, CommandError", "class ArgsCommand(BaseCommand):\n \"\"\"\n Command class for commands that take multiple arguments.\n \"\"\"\n args = '<arg arg ...>'\n\n def handle(self, *args, **options):\n if not args:", " \"\"\"\n Command clas...
from django import forms from django.utils.translation import ugettext_lazy as _ # While this couples the geographic forms to the GEOS library, # it decouples from database (by not importing SpatialBackend). from django.contrib.gis.geos import GEOSGeometry class GeometryField(forms.Field): """ This is the basic form field for a Geometry. Any textual input that is accepted by GEOSGeometry is accepted by this form. By default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. """ widget = forms.Textarea default_error_messages = { 'no_geom' : _(u'No geometry value provided.'), 'invalid_geom' : _(u'Invalid geometry value.'), 'invalid_geom_type' : _(u'Invalid geometry type.'), 'transform_error' : _(u'An error occurred when transforming the geometry ' 'to the SRID of the geometry form field.'), } def __init__(self, **kwargs): # Pop out attributes from the database field, or use sensible # defaults (e.g., allow None). self.srid = kwargs.pop('srid', None) self.geom_type = kwargs.pop('geom_type', 'GEOMETRY') self.null = kwargs.pop('null', True) super(GeometryField, self).__init__(**kwargs) def clean(self, value): """ Validates that the input value can be converted to a Geometry object (which is returned). A ValidationError is raised if the value cannot be instantiated as a Geometry. """ if not value: if self.null and not self.required: # The geometry column allows NULL and is not required. return None else: raise forms.ValidationError(self.error_messages['no_geom']) # Trying to create a Geometry object from the form value. try: geom = GEOSGeometry(value) except: raise forms.ValidationError(self.error_messages['invalid_geom']) # Ensuring that the geometry is of the correct type (indicated # using the OGC string label). if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY': raise forms.ValidationError(self.error_messages['invalid_geom_type']) # Transforming the geometry if the SRID was set. if self.srid: if not geom.srid: # Should match that of the field if not given. geom.srid = self.srid elif self.srid != -1 and self.srid != geom.srid: try: geom.transform(self.srid) except: raise forms.ValidationError(self.error_messages['transform_error']) return geom
[ [ 1, 0, 0.0149, 0.0149, 0, 0.66, 0, 294, 0, 1, 0, 0, 294, 0, 0 ], [ 1, 0, 0.0299, 0.0149, 0, 0.66, 0.3333, 389, 0, 1, 0, 0, 389, 0, 0 ], [ 1, 0, 0.0896, 0.0149, 0, ...
[ "from django import forms", "from django.utils.translation import ugettext_lazy as _", "from django.contrib.gis.geos import GEOSGeometry", "class GeometryField(forms.Field):\n \"\"\"\n This is the basic form field for a Geometry. Any textual input that is\n accepted by GEOSGeometry is accepted by th...
from django.forms import * from django.contrib.gis.forms.fields import GeometryField
[ [ 1, 0, 0.5, 0.5, 0, 0.66, 0, 666, 0, 1, 0, 0, 666, 0, 0 ], [ 1, 0, 1, 0.5, 0, 0.66, 1, 391, 0, 1, 0, 0, 391, 0, 0 ] ]
[ "from django.forms import *", "from django.contrib.gis.forms.fields import GeometryField" ]
from django.db import connection if hasattr(connection.ops, 'spatial_version'): from warnings import warn warn('The `django.contrib.gis.db.backend` module was refactored and ' 'renamed to `django.contrib.gis.db.backends` in 1.2. ' 'All functionality of `SpatialBackend` ' 'has been moved to the `ops` attribute of the spatial database ' 'backend. A `SpatialBackend` alias is provided here for ' 'backwards-compatibility, but will be removed in 1.3.') SpatialBackend = connection.ops
[ [ 1, 0, 0.0909, 0.0909, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 4, 0, 0.6364, 0.8182, 0, 0.66, 1, 0, 3, 0, 0, 0, 0, 0, 2 ], [ 1, 1, 0.3636, 0.0909, 1, 0.91, 0...
[ "from django.db import connection", "if hasattr(connection.ops, 'spatial_version'):\n from warnings import warn\n warn('The `django.contrib.gis.db.backend` module was refactored and '\n 'renamed to `django.contrib.gis.db.backends` in 1.2. '\n 'All functionality of `SpatialBackend` '\n ...
from django.db import connections from django.db.models.query import QuerySet, Q, ValuesQuerySet, ValuesListQuerySet from django.contrib.gis.db.models import aggregates from django.contrib.gis.db.models.fields import get_srid_info, GeometryField, PointField, LineStringField from django.contrib.gis.db.models.sql import AreaField, DistanceField, GeomField, GeoQuery, GeoWhereNode from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance class GeoQuerySet(QuerySet): "The Geographic QuerySet." ### Methods overloaded from QuerySet ### def __init__(self, model=None, query=None, using=None): super(GeoQuerySet, self).__init__(model=model, query=query, using=using) self.query = query or GeoQuery(self.model) def values(self, *fields): return self._clone(klass=GeoValuesQuerySet, setup=True, _fields=fields) def values_list(self, *fields, **kwargs): flat = kwargs.pop('flat', False) if kwargs: raise TypeError('Unexpected keyword arguments to values_list: %s' % (kwargs.keys(),)) if flat and len(fields) > 1: raise TypeError("'flat' is not valid when values_list is called with more than one field.") return self._clone(klass=GeoValuesListQuerySet, setup=True, flat=flat, _fields=fields) ### GeoQuerySet Methods ### def area(self, tolerance=0.05, **kwargs): """ Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet. """ # Peforming setup here rather than in `_spatial_attribute` so that # we can get the units for `AreaField`. procedure_args, geo_field = self._spatial_setup('area', field_name=kwargs.get('field_name', None)) s = {'procedure_args' : procedure_args, 'geo_field' : geo_field, 'setup' : False, } connection = connections[self.db] backend = connection.ops if backend.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args']['tolerance'] = tolerance s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters. elif backend.postgis or backend.spatialite: if backend.geography: # Geography fields support area calculation, returns square meters. s['select_field'] = AreaField('sq_m') elif not geo_field.geodetic(connection): # Getting the area units of the geographic field. s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection))) else: # TODO: Do we want to support raw number areas for geodetic fields? raise Exception('Area on geodetic coordinate systems not supported.') return self._spatial_attribute('area', s, **kwargs) def centroid(self, **kwargs): """ Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet. """ return self._geom_attribute('centroid', **kwargs) def collect(self, **kwargs): """ Performs an aggregate collect operation on the given geometry field. This is analagous to a union operation, but much faster because boundaries are not dissolved. """ return self._spatial_aggregate(aggregates.Collect, **kwargs) def difference(self, geom, **kwargs): """ Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('difference', geom, **kwargs) def distance(self, geom, **kwargs): """ Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet. Keyword Arguments: `spheroid` => If the geometry field is geodetic and PostGIS is the spatial database, then the more accurate spheroid calculation will be used instead of the quicker sphere calculation. `tolerance` => Used only for Oracle. The tolerance is in meters -- a default of 5 centimeters (0.05) is used. """ return self._distance_attribute('distance', geom, **kwargs) def envelope(self, **kwargs): """ Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet. """ return self._geom_attribute('envelope', **kwargs) def extent(self, **kwargs): """ Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ return self._spatial_aggregate(aggregates.Extent, **kwargs) def extent3d(self, **kwargs): """ Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax). """ return self._spatial_aggregate(aggregates.Extent3D, **kwargs) def force_rhr(self, **kwargs): """ Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet. """ return self._geom_attribute('force_rhr', **kwargs) def geojson(self, precision=8, crs=False, bbox=False, **kwargs): """ Returns a GeoJSON representation of the geomtry field in a `geojson` attribute on each element of the GeoQuerySet. The `crs` and `bbox` keywords may be set to True if the users wants the coordinate reference system and the bounding box to be included in the GeoJSON representation of the geometry. """ backend = connections[self.db].ops if not backend.geojson: raise NotImplementedError('Only PostGIS 1.3.4+ supports GeoJSON serialization.') if not isinstance(precision, (int, long)): raise TypeError('Precision keyword must be set with an integer.') # Setting the options flag -- which depends on which version of # PostGIS we're using. if backend.spatial_version >= (1, 4, 0): options = 0 if crs and bbox: options = 3 elif bbox: options = 1 elif crs: options = 2 else: options = 0 if crs and bbox: options = 3 elif crs: options = 1 elif bbox: options = 2 s = {'desc' : 'GeoJSON', 'procedure_args' : {'precision' : precision, 'options' : options}, 'procedure_fmt' : '%(geo_col)s,%(precision)s,%(options)s', } return self._spatial_attribute('geojson', s, **kwargs) def geohash(self, precision=20, **kwargs): """ Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet. The `precision` keyword may be used to custom the number of _characters_ used in the output GeoHash, the default is 20. """ s = {'desc' : 'GeoHash', 'procedure_args': {'precision': precision}, 'procedure_fmt': '%(geo_col)s,%(precision)s', } return self._spatial_attribute('geohash', s, **kwargs) def gml(self, precision=8, version=2, **kwargs): """ Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet. """ backend = connections[self.db].ops s = {'desc' : 'GML', 'procedure_args' : {'precision' : precision}} if backend.postgis: # PostGIS AsGML() aggregate function parameter order depends on the # version -- uggh. if backend.spatial_version > (1, 3, 1): procedure_fmt = '%(version)s,%(geo_col)s,%(precision)s' else: procedure_fmt = '%(geo_col)s,%(precision)s,%(version)s' s['procedure_args'] = {'precision' : precision, 'version' : version} return self._spatial_attribute('gml', s, **kwargs) def intersection(self, geom, **kwargs): """ Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('intersection', geom, **kwargs) def kml(self, **kwargs): """ Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet. """ s = {'desc' : 'KML', 'procedure_fmt' : '%(geo_col)s,%(precision)s', 'procedure_args' : {'precision' : kwargs.pop('precision', 8)}, } return self._spatial_attribute('kml', s, **kwargs) def length(self, **kwargs): """ Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('length', None, **kwargs) def make_line(self, **kwargs): """ Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet. """ return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs) def mem_size(self, **kwargs): """ Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet. """ return self._spatial_attribute('mem_size', {}, **kwargs) def num_geom(self, **kwargs): """ Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None. """ return self._spatial_attribute('num_geom', {}, **kwargs) def num_points(self, **kwargs): """ Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._spatial_attribute('num_points', {}, **kwargs) def perimeter(self, **kwargs): """ Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('perimeter', None, **kwargs) def point_on_surface(self, **kwargs): """ Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._geom_attribute('point_on_surface', **kwargs) def reverse_geom(self, **kwargs): """ Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet. """ s = {'select_field' : GeomField(),} kwargs.setdefault('model_att', 'reverse_geom') if connections[self.db].ops.oracle: s['geo_field_type'] = LineStringField return self._spatial_attribute('reverse', s, **kwargs) def scale(self, x, y, z=0.0, **kwargs): """ Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not support 3D scaling.') s = {'procedure_fmt' : '%(geo_col)s,%(x)s,%(y)s', 'procedure_args' : {'x' : x, 'y' : y}, 'select_field' : GeomField(), } else: s = {'procedure_fmt' : '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args' : {'x' : x, 'y' : y, 'z' : z}, 'select_field' : GeomField(), } return self._spatial_attribute('scale', s, **kwargs) def snap_to_grid(self, *args, **kwargs): """ Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X, Y sizes and the X, Y origins. """ if False in [isinstance(arg, (float, int, long)) for arg in args]: raise TypeError('Size argument(s) for the grid must be a float or integer values.') nargs = len(args) if nargs == 1: size = args[0] procedure_fmt = '%(geo_col)s,%(size)s' procedure_args = {'size' : size} elif nargs == 2: xsize, ysize = args procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize' : xsize, 'ysize' : ysize} elif nargs == 4: xsize, ysize, xorigin, yorigin = args procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize' : xsize, 'ysize' : ysize, 'xorigin' : xorigin, 'yorigin' : yorigin} else: raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.') s = {'procedure_fmt' : procedure_fmt, 'procedure_args' : procedure_args, 'select_field' : GeomField(), } return self._spatial_attribute('snap_to_grid', s, **kwargs) def svg(self, relative=False, precision=8, **kwargs): """ Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms of relative moves (rather than absolute). `precision` => May be used to set the maximum number of decimal digits used in output (defaults to 8). """ relative = int(bool(relative)) if not isinstance(precision, (int, long)): raise TypeError('SVG precision keyword argument must be an integer.') s = {'desc' : 'SVG', 'procedure_fmt' : '%(geo_col)s,%(rel)s,%(precision)s', 'procedure_args' : {'rel' : relative, 'precision' : precision, } } return self._spatial_attribute('svg', s, **kwargs) def sym_difference(self, geom, **kwargs): """ Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('sym_difference', geom, **kwargs) def translate(self, x, y, z=0.0, **kwargs): """ Translates the geometry to a new location using the given numeric parameters as offsets. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not support 3D translation.') s = {'procedure_fmt' : '%(geo_col)s,%(x)s,%(y)s', 'procedure_args' : {'x' : x, 'y' : y}, 'select_field' : GeomField(), } else: s = {'procedure_fmt' : '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args' : {'x' : x, 'y' : y, 'z' : z}, 'select_field' : GeomField(), } return self._spatial_attribute('translate', s, **kwargs) def transform(self, srid=4326, **kwargs): """ Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84). """ if not isinstance(srid, (int, long)): raise TypeError('An integer SRID must be provided.') field_name = kwargs.get('field_name', None) tmp, geo_field = self._spatial_setup('transform', field_name=field_name) # Getting the selection SQL for the given geographic field. field_col = self._geocol_select(geo_field, field_name) # Why cascading substitutions? Because spatial backends like # Oracle and MySQL already require a function call to convert to text, thus # when there's also a transformation we need to cascade the substitutions. # For example, 'SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM( ... )' geo_col = self.query.custom_select.get(geo_field, field_col) # Setting the key for the field's column with the custom SELECT SQL to # override the geometry column returned from the database. custom_sel = '%s(%s, %s)' % (connections[self.db].ops.transform, geo_col, srid) # TODO: Should we have this as an alias? # custom_sel = '(%s(%s, %s)) AS %s' % (SpatialBackend.transform, geo_col, srid, qn(geo_field.name)) self.query.transformed_srid = srid # So other GeoQuerySet methods self.query.custom_select[geo_field] = custom_sel return self._clone() def union(self, geom, **kwargs): """ Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('union', geom, **kwargs) def unionagg(self, **kwargs): """ Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only. """ return self._spatial_aggregate(aggregates.Union, **kwargs) ### Private API -- Abstracted DRY routines. ### def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None): """ Performs set up for executing the spatial function. """ # Does the spatial backend support this? connection = connections[self.db] func = getattr(connection.ops, att, False) if desc is None: desc = att if not func: raise NotImplementedError('%s stored procedure not available on ' 'the %s backend.' % (desc, connection.ops.name)) # Initializing the procedure arguments. procedure_args = {'function' : func} # Is there a geographic field in the model to perform this # operation on? geo_field = self.query._geo_field(field_name) if not geo_field: raise TypeError('%s output only available on GeometryFields.' % func) # If the `geo_field_type` keyword was used, then enforce that # type limitation. if not geo_field_type is None and not isinstance(geo_field, geo_field_type): raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__)) # Setting the procedure args. procedure_args['geo_col'] = self._geocol_select(geo_field, field_name) return procedure_args, geo_field def _spatial_aggregate(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05): """ DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function. """ # Getting the field the geographic aggregate will be called on. geo_field = self.query._geo_field(field_name) if not geo_field: raise TypeError('%s aggregate only available on GeometryFields.' % aggregate.name) # Checking if there are any geo field type limitations on this # aggregate (e.g. ST_Makeline only operates on PointFields). if not geo_field_type is None and not isinstance(geo_field, geo_field_type): raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__)) # Getting the string expression of the field name, as this is the # argument taken by `Aggregate` objects. agg_col = field_name or geo_field.name # Adding any keyword parameters for the Aggregate object. Oracle backends # in particular need an additional `tolerance` parameter. agg_kwargs = {} if connections[self.db].ops.oracle: agg_kwargs['tolerance'] = tolerance # Calling the QuerySet.aggregate, and returning only the value of the aggregate. return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg'] def _spatial_attribute(self, att, settings, field_name=None, model_att=None): """ DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that holds the spatial SQL function to call. settings: Dictonary of internal settings to customize for the spatial procedure. Public Keyword Arguments: field_name: The name of the geographic field to call the spatial function on. May also be a lookup to a geometry field as part of a foreign key relation. model_att: The name of the model attribute to attach the output of the spatial function to. """ # Default settings. settings.setdefault('desc', None) settings.setdefault('geom_args', ()) settings.setdefault('geom_field', None) settings.setdefault('procedure_args', {}) settings.setdefault('procedure_fmt', '%(geo_col)s') settings.setdefault('select_params', []) connection = connections[self.db] backend = connection.ops # Performing setup for the spatial column, unless told not to. if settings.get('setup', True): default_args, geo_field = self._spatial_setup(att, desc=settings['desc'], field_name=field_name, geo_field_type=settings.get('geo_field_type', None)) for k, v in default_args.iteritems(): settings['procedure_args'].setdefault(k, v) else: geo_field = settings['geo_field'] # The attribute to attach to the model. if not isinstance(model_att, basestring): model_att = att # Special handling for any argument that is a geometry. for name in settings['geom_args']: # Using the field's get_placeholder() routine to get any needed # transformation SQL. geom = geo_field.get_prep_value(settings['procedure_args'][name]) params = geo_field.get_db_prep_lookup('contains', geom, connection=connection) geom_placeholder = geo_field.get_placeholder(geom, connection) # Replacing the procedure format with that of any needed # transformation SQL. old_fmt = '%%(%s)s' % name new_fmt = geom_placeholder % '%%s' settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt) settings['select_params'].extend(params) # Getting the format for the stored procedure. fmt = '%%(function)s(%s)' % settings['procedure_fmt'] # If the result of this function needs to be converted. if settings.get('select_field', False): sel_fld = settings['select_field'] if isinstance(sel_fld, GeomField) and backend.select: self.query.custom_select[model_att] = backend.select if connection.ops.oracle: sel_fld.empty_strings_allowed = False self.query.extra_select_fields[model_att] = sel_fld # Finally, setting the extra selection attribute with # the format string expanded with the stored procedure # arguments. return self.extra(select={model_att : fmt % settings['procedure_args']}, select_params=settings['select_params']) def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. connection = connections[self.db] geodetic = geo_field.geodetic(connection) geography = geo_field.geography if geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name(connection)) # Shortcut booleans for what distance function we're using and # whether the geometry field is 3D. distance = func == 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) geom_3d = geo_field.dim == 3 # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # Getting the spatial backend operations. backend = connection.ops # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (backend.postgis and geodetic and (not geography) and length): lookup_params.append('spheroid') lookup_params = geo_field.get_prep_value(lookup_params) params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if backend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. if self.query.transformed_srid: u, unit_name, s = get_srid_info(self.query.transformed_srid, connection) geodetic = unit_name in geo_field.geodetic_units if backend.spatialite and geodetic: raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (backend.transform, self.query.transformed_srid) if geom.srid is None or geom.srid == self.query.transformed_srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if backend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (backend.from_text, self.query.transformed_srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if backend.spatialite: procedure_fmt += ', %s(%s(%%%%s, %s), %s)' % (backend.transform, backend.from_text, geom.srid, self.query.transformed_srid) else: procedure_fmt += ', %s(%%%%s, %s)' % (backend.transform, self.query.transformed_srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if not geography and geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not backend.geography: if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(Geometry(buffer(params[0].ewkb)).geom_type) == 'Point': raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function' : backend.distance_spheroid, 'spheroid' : params[1]}) else: procedure_args.update({'function' : backend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if not geography and geodetic and length: # There's no `length_sphere`, and `length_spheroid` also # works on 3D geometries. procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function' : backend.length_spheroid, 'spheroid' : params[1]}) elif geom_3d and backend.postgis: # Use 3D variants of perimeter and length routines on PostGIS. if perimeter: procedure_args.update({'function' : backend.perimeter3d}) elif length: procedure_args.update({'function' : backend.length3d}) # Setting up the settings for `_spatial_attribute`. s = {'select_field' : DistanceField(dist_att), 'setup' : False, 'geo_field' : geo_field, 'procedure_args' : procedure_args, 'procedure_fmt' : procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [backend.Adapter(geom)] return self._spatial_attribute(func, s, **kwargs) def _geom_attribute(self, func, tolerance=0.05, **kwargs): """ DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute (e.g., `centroid`, `point_on_surface`). """ s = {'select_field' : GeomField(),} if connections[self.db].ops.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args'] = {'tolerance' : tolerance} return self._spatial_attribute(func, s, **kwargs) def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs): """ DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute and takes a Geoemtry parameter. This is used for geometry set-like operations (e.g., intersection, difference, union, sym_difference). """ s = {'geom_args' : ('geom',), 'select_field' : GeomField(), 'procedure_fmt' : '%(geo_col)s,%(geom)s', 'procedure_args' : {'geom' : geom}, } if connections[self.db].ops.oracle: s['procedure_fmt'] += ',%(tolerance)s' s['procedure_args']['tolerance'] = tolerance return self._spatial_attribute(func, s, **kwargs) def _geocol_select(self, geo_field, field_name): """ Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model. """ opts = self.model._meta if not geo_field in opts.fields: # Is this operation going to be on a related geographic field? # If so, it'll have to be added to the select related information # (e.g., if 'location__point' was given as the field name). self.query.add_select_related([field_name]) compiler = self.query.get_compiler(self.db) compiler.pre_sql_setup() rel_table, rel_col = self.query.related_select_cols[self.query.related_select_fields.index(geo_field)] return compiler._field_column(geo_field, rel_table) elif not geo_field in opts.local_fields: # This geographic field is inherited from another model, so we have to # use the db table for the _parent_ model instead. tmp_fld, parent_model, direct, m2m = opts.get_field_by_name(geo_field.name) return self.query.get_compiler(self.db)._field_column(geo_field, parent_model._meta.db_table) else: return self.query.get_compiler(self.db)._field_column(geo_field) class GeoValuesQuerySet(ValuesQuerySet): def __init__(self, *args, **kwargs): super(GeoValuesQuerySet, self).__init__(*args, **kwargs) # This flag tells `resolve_columns` to run the values through # `convert_values`. This ensures that Geometry objects instead # of string values are returned with `values()` or `values_list()`. self.query.geo_values = True class GeoValuesListQuerySet(GeoValuesQuerySet, ValuesListQuerySet): pass
[ [ 1, 0, 0.0013, 0.0013, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0026, 0.0013, 0, 0.66, 0.1111, 793, 0, 4, 0, 0, 793, 0, 0 ], [ 1, 0, 0.0051, 0.0013, 0, 0....
[ "from django.db import connections", "from django.db.models.query import QuerySet, Q, ValuesQuerySet, ValuesListQuerySet", "from django.contrib.gis.db.models import aggregates", "from django.contrib.gis.db.models.fields import get_srid_info, GeometryField, PointField, LineStringField", "from django.contrib....
from django.db.models.fields import Field from django.db.models.sql.expressions import SQLEvaluator from django.utils.translation import ugettext_lazy as _ from django.contrib.gis import forms from django.contrib.gis.db.models.proxy import GeometryProxy from django.contrib.gis.geometry.backend import Geometry, GeometryException # Local cache of the spatial_ref_sys table, which holds SRID data for each # spatial database alias. This cache exists so that the database isn't queried # for SRID info each time a distance query is constructed. _srid_cache = {} def get_srid_info(srid, connection): """ Returns the units, unit name, and spheroid WKT associated with the given SRID from the `spatial_ref_sys` (or equivalent) spatial database table for the given database connection. These results are cached. """ global _srid_cache try: # The SpatialRefSys model for the spatial backend. SpatialRefSys = connection.ops.spatial_ref_sys() except NotImplementedError: # No `spatial_ref_sys` table in spatial backend (e.g., MySQL). return None, None, None if not connection.alias in _srid_cache: # Initialize SRID dictionary for database if it doesn't exist. _srid_cache[connection.alias] = {} if not srid in _srid_cache[connection.alias]: # Use `SpatialRefSys` model to query for spatial reference info. sr = SpatialRefSys.objects.using(connection.alias).get(srid=srid) units, units_name = sr.units spheroid = SpatialRefSys.get_spheroid(sr.wkt) _srid_cache[connection.alias][srid] = (units, units_name, spheroid) return _srid_cache[connection.alias][srid] class GeometryField(Field): "The base GIS field -- maps to the OpenGIS Specification Geometry type." # The OpenGIS Geometry name. geom_type = 'GEOMETRY' # Geodetic units. geodetic_units = ('Decimal Degree', 'degree') description = _("The base GIS field -- maps to the OpenGIS Specification Geometry type.") def __init__(self, verbose_name=None, srid=4326, spatial_index=True, dim=2, geography=False, **kwargs): """ The initialization function for geometry fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns. dim: The number of dimensions for this geometry. Defaults to 2. extent: Customize the extent, in a 4-tuple of WGS 84 coordinates, for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to (-180.0, -90.0, 180.0, 90.0). tolerance: Define the tolerance, in meters, to use for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05. """ # Setting the index flag with the value of the `spatial_index` keyword. self.spatial_index = spatial_index # Setting the SRID and getting the units. Unit information must be # easily available in the field instance for distance queries. self.srid = srid # Setting the dimension of the geometry field. self.dim = dim # Setting the verbose_name keyword argument with the positional # first parameter, so this works like normal fields. kwargs['verbose_name'] = verbose_name # Is this a geography rather than a geometry column? self.geography = geography # Oracle-specific private attributes for creating the entrie in # `USER_SDO_GEOM_METADATA` self._extent = kwargs.pop('extent', (-180.0, -90.0, 180.0, 90.0)) self._tolerance = kwargs.pop('tolerance', 0.05) super(GeometryField, self).__init__(**kwargs) # The following functions are used to get the units, their name, and # the spheroid corresponding to the SRID of the GeometryField. def _get_srid_info(self, connection): # Get attributes from `get_srid_info`. self._units, self._units_name, self._spheroid = get_srid_info(self.srid, connection) def spheroid(self, connection): if not hasattr(self, '_spheroid'): self._get_srid_info(connection) return self._spheroid def units(self, connection): if not hasattr(self, '_units'): self._get_srid_info(connection) return self._units def units_name(self, connection): if not hasattr(self, '_units_name'): self._get_srid_info(connection) return self._units_name ### Routines specific to GeometryField ### def geodetic(self, connection): """ Returns true if this field's SRID corresponds with a coordinate system that uses non-projected units (e.g., latitude/longitude). """ return self.units_name(connection) in self.geodetic_units def get_distance(self, value, lookup_type, connection): """ Returns a distance number in units of the field. For example, if `D(km=1)` was passed in and the units of the field were in meters, then 1000 would be returned. """ return connection.ops.get_distance(self, value, lookup_type) def get_prep_value(self, value): """ Spatial lookup values are either a parameter that is (or may be converted to) a geometry, or a sequence of lookup values that begins with a geometry. This routine will setup the geometry value properly, and preserve any other lookup parameters before returning to the caller. """ if isinstance(value, SQLEvaluator): return value elif isinstance(value, (tuple, list)): geom = value[0] seq_value = True else: geom = value seq_value = False # When the input is not a GEOS geometry, attempt to construct one # from the given string input. if isinstance(geom, Geometry): pass elif isinstance(geom, basestring) or hasattr(geom, '__geo_interface__'): try: geom = Geometry(geom) except GeometryException: raise ValueError('Could not create geometry from lookup value.') else: raise ValueError('Cannot use object with type %s for a geometry lookup parameter.' % type(geom).__name__) # Assigning the SRID value. geom.srid = self.get_srid(geom) if seq_value: lookup_val = [geom] lookup_val.extend(value[1:]) return tuple(lookup_val) else: return geom def get_srid(self, geom): """ Returns the default SRID for the given geometry, taking into account the SRID set for the field. For example, if the input geometry has no SRID, then that of the field will be returned. """ gsrid = geom.srid # SRID of given geometry. if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1): return self.srid else: return gsrid ### Routines overloaded from Field ### def contribute_to_class(self, cls, name): super(GeometryField, self).contribute_to_class(cls, name) # Setup for lazy-instantiated Geometry object. setattr(cls, self.attname, GeometryProxy(Geometry, self)) def db_type(self, connection): return connection.ops.geo_db_type(self) def formfield(self, **kwargs): defaults = {'form_class' : forms.GeometryField, 'null' : self.null, 'geom_type' : self.geom_type, 'srid' : self.srid, } defaults.update(kwargs) return super(GeometryField, self).formfield(**defaults) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): """ Prepare for the database lookup, and return any spatial parameters necessary for the query. This includes wrapping any geometry parameters with a backend-specific adapter and formatting any distance parameters into the correct units for the coordinate system of the field. """ if lookup_type in connection.ops.gis_terms: # special case for isnull lookup if lookup_type == 'isnull': return [] # Populating the parameters list, and wrapping the Geometry # with the Adapter of the spatial backend. if isinstance(value, (tuple, list)): params = [connection.ops.Adapter(value[0])] if lookup_type in connection.ops.distance_functions: # Getting the distance parameter in the units of the field. params += self.get_distance(value[1:], lookup_type, connection) elif lookup_type in connection.ops.truncate_params: # Lookup is one where SQL parameters aren't needed from the # given lookup value. pass else: params += value[1:] elif isinstance(value, SQLEvaluator): params = [] else: params = [connection.ops.Adapter(value)] return params else: raise ValueError('%s is not a valid spatial lookup for %s.' % (lookup_type, self.__class__.__name__)) def get_prep_lookup(self, lookup_type, value): if lookup_type == 'isnull': return bool(value) else: return self.get_prep_value(value) def get_db_prep_save(self, value, connection): "Prepares the value for saving in the database." if value is None: return None else: return connection.ops.Adapter(self.get_prep_value(value)) def get_placeholder(self, value, connection): """ Returns the placeholder for the geometry column for the given value. """ return connection.ops.get_geom_placeholder(self, value) # The OpenGIS Geometry Type Fields class PointField(GeometryField): geom_type = 'POINT' description = _("Point") class LineStringField(GeometryField): geom_type = 'LINESTRING' description = _("Line string") class PolygonField(GeometryField): geom_type = 'POLYGON' description = _("Polygon") class MultiPointField(GeometryField): geom_type = 'MULTIPOINT' description = _("Multi-point") class MultiLineStringField(GeometryField): geom_type = 'MULTILINESTRING' description = _("Multi-line string") class MultiPolygonField(GeometryField): geom_type = 'MULTIPOLYGON' description = _("Multi polygon") class GeometryCollectionField(GeometryField): geom_type = 'GEOMETRYCOLLECTION' description = _("Geometry collection")
[ [ 1, 0, 0.0034, 0.0034, 0, 0.66, 0, 5, 0, 1, 0, 0, 5, 0, 0 ], [ 1, 0, 0.0068, 0.0034, 0, 0.66, 0.0667, 438, 0, 1, 0, 0, 438, 0, 0 ], [ 1, 0, 0.0102, 0.0034, 0, 0.66...
[ "from django.db.models.fields import Field", "from django.db.models.sql.expressions import SQLEvaluator", "from django.utils.translation import ugettext_lazy as _", "from django.contrib.gis import forms", "from django.contrib.gis.db.models.proxy import GeometryProxy", "from django.contrib.gis.geometry.bac...
""" The GeometryProxy object, allows for lazy-geometries. The proxy uses Python descriptors for instantiating and setting Geometry objects corresponding to geographic model fields. Thanks to Robert Coup for providing this functionality (see #4322). """ class GeometryProxy(object): def __init__(self, klass, field): """ Proxy initializes on the given Geometry class (not an instance) and the GeometryField. """ self._field = field self._klass = klass def __get__(self, obj, type=None): """ This accessor retrieves the geometry, initializing it using the geometry class specified during initialization and the HEXEWKB value of the field. Currently, only GEOS or OGR geometries are supported. """ if obj is None: # Accessed on a class, not an instance return self # Getting the value of the field. geom_value = obj.__dict__[self._field.attname] if isinstance(geom_value, self._klass): geom = geom_value elif (geom_value is None) or (geom_value==''): geom = None else: # Otherwise, a Geometry object is built using the field's contents, # and the model's corresponding attribute is set. geom = self._klass(geom_value) setattr(obj, self._field.attname, geom) return geom def __set__(self, obj, value): """ This accessor sets the proxied geometry with the geometry class specified during initialization. Values of None, HEXEWKB, or WKT may be used to set the geometry as well. """ # The OGC Geometry type of the field. gtype = self._field.geom_type # The geometry type must match that of the field -- unless the # general GeometryField is used. if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'): # Assigning the SRID to the geometry. if value.srid is None: value.srid = self._field.srid elif value is None or isinstance(value, (basestring, buffer)): # Set with None, WKT, HEX, or WKB pass else: raise TypeError('cannot set %s GeometryProxy with value of type: %s' % (obj.__class__.__name__, type(value))) # Setting the objects dictionary with the value, and returning. obj.__dict__[self._field.attname] = value return value
[ [ 8, 0, 0.0625, 0.1094, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.5703, 0.875, 0, 0.66, 1, 637, 0, 3, 0, 0, 186, 0, 9 ], [ 2, 1, 0.2031, 0.1094, 1, 0.3, 0...
[ "\"\"\"\nThe GeometryProxy object, allows for lazy-geometries. The proxy uses\nPython descriptors for instantiating and setting Geometry objects\ncorresponding to geographic model fields.\n\nThanks to Robert Coup for providing this functionality (see #4322).\n\"\"\"", "class GeometryProxy(object):\n def __ini...
from django.db import connections from django.db.models.query import sql from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql import aggregates as gis_aggregates from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField from django.contrib.gis.db.models.sql.where import GeoWhereNode from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance ALL_TERMS = dict([(x, None) for x in ( 'bbcontains', 'bboverlaps', 'contained', 'contains', 'contains_properly', 'coveredby', 'covers', 'crosses', 'disjoint', 'distance_gt', 'distance_gte', 'distance_lt', 'distance_lte', 'dwithin', 'equals', 'exact', 'intersects', 'overlaps', 'relate', 'same_as', 'touches', 'within', 'left', 'right', 'overlaps_left', 'overlaps_right', 'overlaps_above', 'overlaps_below', 'strictly_above', 'strictly_below' )]) ALL_TERMS.update(sql.constants.QUERY_TERMS) class GeoQuery(sql.Query): """ A single spatial SQL query. """ # Overridding the valid query terms. query_terms = ALL_TERMS aggregates_module = gis_aggregates compiler = 'GeoSQLCompiler' #### Methods overridden from the base Query class #### def __init__(self, model, where=GeoWhereNode): super(GeoQuery, self).__init__(model, where) # The following attributes are customized for the GeoQuerySet. # The GeoWhereNode and SpatialBackend classes contain backend-specific # routines and functions. self.custom_select = {} self.transformed_srid = None self.extra_select_fields = {} def clone(self, *args, **kwargs): obj = super(GeoQuery, self).clone(*args, **kwargs) # Customized selection dictionary and transformed srid flag have # to also be added to obj. obj.custom_select = self.custom_select.copy() obj.transformed_srid = self.transformed_srid obj.extra_select_fields = self.extra_select_fields.copy() return obj def convert_values(self, value, field, connection): """ Using the same routines that Oracle does we can convert our extra selection objects into Geometry and Distance objects. TODO: Make converted objects 'lazy' for less overhead. """ if connection.ops.oracle: # Running through Oracle's first. value = super(GeoQuery, self).convert_values(value, field or GeomField(), connection) if value is None: # Output from spatial function is NULL (e.g., called # function on a geometry field with NULL value). pass elif isinstance(field, DistanceField): # Using the field's distance attribute, can instantiate # `Distance` with the right context. value = Distance(**{field.distance_att : value}) elif isinstance(field, AreaField): value = Area(**{field.area_att : value}) elif isinstance(field, (GeomField, GeometryField)) and value: value = Geometry(value) return value def get_aggregation(self, using): # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. connection = connections[using] for alias, aggregate in self.aggregate_select.items(): if isinstance(aggregate, gis_aggregates.GeoAggregate): if not getattr(aggregate, 'is_extent', False) or connection.ops.oracle: self.extra_select_fields[alias] = GeomField() return super(GeoQuery, self).get_aggregation(using) def resolve_aggregate(self, value, aggregate, connection): """ Overridden from GeoQuery's normalize to handle the conversion of GeoAggregate objects. """ if isinstance(aggregate, self.aggregates_module.GeoAggregate): if aggregate.is_extent: if aggregate.is_extent == '3D': return connection.ops.convert_extent3d(value) else: return connection.ops.convert_extent(value) else: return connection.ops.convert_geom(value, aggregate.source) else: return super(GeoQuery, self).resolve_aggregate(value, aggregate, connection) # Private API utilities, subject to change. def _geo_field(self, field_name=None): """ Returns the first Geometry field encountered; or specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuery's model, or a lookup string to a geometry field via a ForeignKey relation. """ if field_name is None: # Incrementing until the first geographic field is found. for fld in self.model._meta.fields: if isinstance(fld, GeometryField): return fld return False else: # Otherwise, check by the given field name -- which may be # a lookup to a _related_ geographic field. return GeoWhereNode._check_geo_field(self.model._meta, field_name)
[ [ 1, 0, 0.0084, 0.0084, 0, 0.66, 0, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0168, 0.0084, 0, 0.66, 0.1, 793, 0, 1, 0, 0, 793, 0, 0 ], [ 1, 0, 0.0336, 0.0084, 0, 0.66,...
[ "from django.db import connections", "from django.db.models.query import sql", "from django.contrib.gis.db.models.fields import GeometryField", "from django.contrib.gis.db.models.sql import aggregates as gis_aggregates", "from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, Geom...
from itertools import izip from django.db.backends.util import truncate_name from django.db.models.sql import compiler from django.db.models.sql.constants import TABLE_NAME from django.db.models.sql.query import get_proxied_model SQLCompiler = compiler.SQLCompiler class GeoSQLCompiler(compiler.SQLCompiler): def get_columns(self, with_aliases=False): """ Return the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If 'with_aliases' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguitity with nested queries. This routine is overridden from Query to handle customized selection of geometry columns. """ qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = ['(%s) AS %s' % (self.get_extra_select_format(alias) % col[0], qn2(alias)) for alias, col in self.query.extra_select.iteritems()] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: col_aliases = set() if self.query.select: only_load = self.deferred_to_columns() # This loop customized for GeoQuery. for col, field in izip(self.query.select, self.query.select_fields): if isinstance(col, (list, tuple)): alias, column = col table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and col not in only_load[table]: continue r = self.get_field_select(field, alias, column) if with_aliases: if col[1] in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append('%s AS %s' % (r, qn2(col[1]))) aliases.add(r) col_aliases.add(col[1]) else: result.append(r) aliases.add(r) col_aliases.add(col[1]) else: result.append(col.as_sql(qn, self.connection)) if hasattr(col, 'alias'): aliases.add(col.alias) col_aliases.add(col.alias) elif self.query.default_cols: cols, new_aliases = self.get_default_columns(with_aliases, col_aliases) result.extend(cols) aliases.update(new_aliases) max_name_length = self.connection.ops.max_name_length() result.extend([ '%s%s' % ( self.get_extra_select_format(alias) % aggregate.as_sql(qn, self.connection), alias is not None and ' AS %s' % qn(truncate_name(alias, max_name_length)) or '' ) for alias, aggregate in self.query.aggregate_select.items() ]) # This loop customized for GeoQuery. for (table, col), field in izip(self.query.related_select_cols, self.query.related_select_fields): r = self.get_field_select(field, table, col) if with_aliases and col in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (r, c_alias)) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(r) aliases.add(r) col_aliases.add(col) self._select_aliases = aliases return result def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False): """ Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, returns a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). This routine is overridden from Query to handle customized selection of geometry columns. """ result = [] if opts is None: opts = self.query.model._meta aliases = set() only_load = self.deferred_to_columns() # Skip all proxy to the root proxied model proxied_model = get_proxied_model(opts) if start_alias: seen = {None: start_alias} for field, model in opts.get_fields_with_model(): if local_only and model is not None: continue if start_alias: try: alias = seen[model] except KeyError: if model is proxied_model: alias = start_alias else: link_field = opts.get_ancestor_link(model) alias = self.query.join((start_alias, model._meta.db_table, link_field.column, model._meta.pk.column)) seen[model] = alias else: # If we're starting from the base model of the queryset, the # aliases will have already been set up in pre_sql_setup(), so # we can save time here. alias = self.query.included_inherited_models[model] table = self.query.alias_map[alias][TABLE_NAME] if table in only_load and field.column not in only_load[table]: continue if as_pairs: result.append((alias, field.column)) aliases.add(alias) continue # This part of the function is customized for GeoQuery. We # see if there was any custom selection specified in the # dictionary, and set up the selection format appropriately. field_sel = self.get_field_select(field, alias) if with_aliases and field.column in col_aliases: c_alias = 'Col%d' % len(col_aliases) result.append('%s AS %s' % (field_sel, c_alias)) col_aliases.add(c_alias) aliases.add(c_alias) else: r = field_sel result.append(r) aliases.add(r) if with_aliases: col_aliases.add(field.column) return result, aliases def resolve_columns(self, row, fields=()): """ This routine is necessary so that distances and geometries returned from extra selection SQL get resolved appropriately into Python objects. """ values = [] aliases = self.query.extra_select.keys() if self.query.aggregates: # If we have an aggregate annotation, must extend the aliases # so their corresponding row values are included. aliases.extend([None for i in xrange(len(self.query.aggregates))]) # Have to set a starting row number offset that is used for # determining the correct starting row index -- needed for # doing pagination with Oracle. rn_offset = 0 if self.connection.ops.oracle: if self.query.high_mark is not None or self.query.low_mark: rn_offset = 1 index_start = rn_offset + len(aliases) # Converting any extra selection values (e.g., geometries and # distance objects added by GeoQuerySet methods). values = [self.query.convert_values(v, self.query.extra_select_fields.get(a, None), self.connection) for v, a in izip(row[rn_offset:index_start], aliases)] if self.connection.ops.oracle or getattr(self.query, 'geo_values', False): # We resolve the rest of the columns if we're on Oracle or if # the `geo_values` attribute is defined. for value, field in map(None, row[index_start:], fields): values.append(self.query.convert_values(value, field, connection=self.connection)) else: values.extend(row[index_start:]) return tuple(values) #### Routines unique to GeoQuery #### def get_extra_select_format(self, alias): sel_fmt = '%s' if alias in self.query.custom_select: sel_fmt = sel_fmt % self.query.custom_select[alias] return sel_fmt def get_field_select(self, field, alias=None, column=None): """ Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`. """ sel_fmt = self.get_select_format(field) if field in self.query.custom_select: field_sel = sel_fmt % self.query.custom_select[field] else: field_sel = sel_fmt % self._field_column(field, alias, column) return field_sel def get_select_format(self, fld): """ Returns the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKT. For all other fields a simple '%s' format string is returned. """ if self.connection.ops.select and hasattr(fld, 'geom_type'): # This allows operations to be done on fields in the SELECT, # overriding their values -- used by the Oracle and MySQL # spatial backends to get database values as WKT, and by the # `transform` method. sel_fmt = self.connection.ops.select # Because WKT doesn't contain spatial reference information, # the SRID is prefixed to the returned WKT to ensure that the # transformed geometries have an SRID different than that of the # field -- this is only used by `transform` for Oracle and # SpatiaLite backends. if self.query.transformed_srid and ( self.connection.ops.oracle or self.connection.ops.spatialite ): sel_fmt = "'SRID=%d;'||%s" % (self.query.transformed_srid, sel_fmt) else: sel_fmt = '%s' return sel_fmt # Private API utilities, subject to change. def _field_column(self, field, table_alias=None, column=None): """ Helper function that returns the database column for the given field. The table and column are returned (quoted) in the proper format, e.g., `"geoapp_city"."point"`. If `table_alias` is not specified, the database table associated with the model of this `GeoQuery` will be used. If `column` is specified, it will be used instead of the value in `field.column`. """ if table_alias is None: table_alias = self.query.model._meta.db_table return "%s.%s" % (self.quote_name_unless_alias(table_alias), self.connection.ops.quote_name(column or field.column)) class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQLCompiler): pass class SQLDeleteCompiler(compiler.SQLDeleteCompiler, GeoSQLCompiler): pass class SQLUpdateCompiler(compiler.SQLUpdateCompiler, GeoSQLCompiler): pass class SQLAggregateCompiler(compiler.SQLAggregateCompiler, GeoSQLCompiler): pass class SQLDateCompiler(compiler.SQLDateCompiler, GeoSQLCompiler): pass
[ [ 1, 0, 0.0036, 0.0036, 0, 0.66, 0, 808, 0, 1, 0, 0, 808, 0, 0 ], [ 1, 0, 0.0072, 0.0036, 0, 0.66, 0.0909, 446, 0, 1, 0, 0, 446, 0, 0 ], [ 1, 0, 0.0108, 0.0036, 0, ...
[ "from itertools import izip", "from django.db.backends.util import truncate_name", "from django.db.models.sql import compiler", "from django.db.models.sql.constants import TABLE_NAME", "from django.db.models.sql.query import get_proxied_model", "SQLCompiler = compiler.SQLCompiler", "class GeoSQLCompiler...
""" This module holds simple classes used by GeoQuery.convert_values to convert geospatial values from the database. """ class BaseField(object): empty_strings_allowed = True def get_internal_type(self): "Overloaded method so OracleQuery.convert_values doesn't balk." return None class AreaField(BaseField): "Wrapper for Area values." def __init__(self, area_att): self.area_att = area_att class DistanceField(BaseField): "Wrapper for Distance values." def __init__(self, distance_att): self.distance_att = distance_att class GeomField(BaseField): """ Wrapper for Geometry values. It is a lightweight alternative to using GeometryField (which requires a SQL query upon instantiation). """ pass
[ [ 8, 0, 0.0926, 0.1481, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 3, 0, 0.2963, 0.1852, 0, 0.66, 0.25, 638, 0, 1, 0, 0, 186, 0, 0 ], [ 14, 1, 0.2593, 0.037, 1, 0.98, ...
[ "\"\"\"\nThis module holds simple classes used by GeoQuery.convert_values\nto convert geospatial values from the database.\n\"\"\"", "class BaseField(object):\n empty_strings_allowed = True\n def get_internal_type(self):\n \"Overloaded method so OracleQuery.convert_values doesn't balk.\"\n ret...
from django.db.models.sql.aggregates import * from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql.conversion import GeomField class GeoAggregate(Aggregate): # Default SQL template for spatial aggregates. sql_template = '%(function)s(%(field)s)' # Conversion class, if necessary. conversion_class = None # Flags for indicating the type of the aggregate. is_extent = False def __init__(self, col, source=None, is_summary=False, tolerance=0.05, **extra): super(GeoAggregate, self).__init__(col, source, is_summary, **extra) # Required by some Oracle aggregates. self.tolerance = tolerance # Can't use geographic aggregates on non-geometry fields. if not isinstance(self.source, GeometryField): raise ValueError('Geospatial aggregates only allowed on geometry fields.') def as_sql(self, qn, connection): "Return the aggregate, rendered as SQL." if connection.ops.oracle: self.extra['tolerance'] = self.tolerance if hasattr(self.col, 'as_sql'): field_name = self.col.as_sql(qn, connection) elif isinstance(self.col, (list, tuple)): field_name = '.'.join([qn(c) for c in self.col]) else: field_name = self.col sql_template, sql_function = connection.ops.spatial_aggregate_sql(self) params = { 'function': sql_function, 'field': field_name } params.update(self.extra) return sql_template % params class Collect(GeoAggregate): pass class Extent(GeoAggregate): is_extent = '2D' class Extent3D(GeoAggregate): is_extent = '3D' class MakeLine(GeoAggregate): pass class Union(GeoAggregate): pass
[ [ 1, 0, 0.0164, 0.0164, 0, 0.66, 0, 101, 0, 1, 0, 0, 101, 0, 0 ], [ 1, 0, 0.0328, 0.0164, 0, 0.66, 0.125, 708, 0, 1, 0, 0, 708, 0, 0 ], [ 1, 0, 0.0492, 0.0164, 0, 0...
[ "from django.db.models.sql.aggregates import *", "from django.contrib.gis.db.models.fields import GeometryField", "from django.contrib.gis.db.models.sql.conversion import GeomField", "class GeoAggregate(Aggregate):\n # Default SQL template for spatial aggregates.\n sql_template = '%(function)s(%(field)s...
from django.db.models.fields import Field, FieldDoesNotExist from django.db.models.sql.constants import LOOKUP_SEP from django.db.models.sql.expressions import SQLEvaluator from django.db.models.sql.where import Constraint, WhereNode from django.contrib.gis.db.models.fields import GeometryField class GeoConstraint(Constraint): """ This subclass overrides `process` to better handle geographic SQL construction. """ def __init__(self, init_constraint): self.alias = init_constraint.alias self.col = init_constraint.col self.field = init_constraint.field def process(self, lookup_type, value, connection): if isinstance(value, SQLEvaluator): # Make sure the F Expression destination field exists, and # set an `srid` attribute with the same as that of the # destination. geo_fld = GeoWhereNode._check_geo_field(value.opts, value.expression.name) if not geo_fld: raise ValueError('No geographic field found in expression.') value.srid = geo_fld.srid db_type = self.field.db_type(connection=connection) params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection) return (self.alias, self.col, db_type), params class GeoWhereNode(WhereNode): """ Used to represent the SQL where-clause for spatial databases -- these are tied to the GeoQuery class that created it. """ def add(self, data, connector): if isinstance(data, (list, tuple)): obj, lookup_type, value = data if ( isinstance(obj, Constraint) and isinstance(obj.field, GeometryField) ): data = (GeoConstraint(obj), lookup_type, value) super(GeoWhereNode, self).add(data, connector) def make_atom(self, child, qn, connection): lvalue, lookup_type, value_annot, params_or_value = child if isinstance(lvalue, GeoConstraint): data, params = lvalue.process(lookup_type, params_or_value, connection) spatial_sql = connection.ops.spatial_lookup_sql(data, lookup_type, params_or_value, lvalue.field, qn) return spatial_sql, params else: return super(GeoWhereNode, self).make_atom(child, qn, connection) @classmethod def _check_geo_field(cls, opts, lookup): """ Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None. """ # This takes into account the situation where the lookup is a # lookup to a related geographic field, e.g., 'address__point'. field_list = lookup.split(LOOKUP_SEP) # Reversing so list operates like a queue of related lookups, # and popping the top lookup. field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) # If the field list is still around, then it means that the # lookup was for a geometry field across a relationship -- # thus we keep on getting the related model options and the # model field associated with the next field in the list # until there's no more left. while len(field_list): opts = geo_fld.rel.to._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeError): return False # Finally, make sure we got a Geographic field and return. if isinstance(geo_fld, GeometryField): return geo_fld else: return False
[ [ 1, 0, 0.0112, 0.0112, 0, 0.66, 0, 5, 0, 2, 0, 0, 5, 0, 0 ], [ 1, 0, 0.0225, 0.0112, 0, 0.66, 0.1667, 971, 0, 1, 0, 0, 971, 0, 0 ], [ 1, 0, 0.0337, 0.0112, 0, 0.66...
[ "from django.db.models.fields import Field, FieldDoesNotExist", "from django.db.models.sql.constants import LOOKUP_SEP", "from django.db.models.sql.expressions import SQLEvaluator", "from django.db.models.sql.where import Constraint, WhereNode", "from django.contrib.gis.db.models.fields import GeometryField...
from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField from django.contrib.gis.db.models.sql.query import GeoQuery from django.contrib.gis.db.models.sql.where import GeoWhereNode
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 100, 0, 3, 0, 0, 100, 0, 0 ], [ 1, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 223, 0, 1, 0, 0, 223, 0, 0 ], [ 1, 0, 1, 0.3333, 0, 0.66, ...
[ "from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField", "from django.contrib.gis.db.models.sql.query import GeoQuery", "from django.contrib.gis.db.models.sql.where import GeoWhereNode" ]
from django.db.models import Aggregate from django.contrib.gis.db.models.sql import GeomField class Collect(Aggregate): name = 'Collect' class Extent(Aggregate): name = 'Extent' class Extent3D(Aggregate): name = 'Extent3D' class MakeLine(Aggregate): name = 'MakeLine' class Union(Aggregate): name = 'Union'
[ [ 1, 0, 0.0588, 0.0588, 0, 0.66, 0, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 1, 0, 0.1176, 0.0588, 0, 0.66, 0.1667, 437, 0, 1, 0, 0, 437, 0, 0 ], [ 3, 0, 0.2647, 0.1176, 0, ...
[ "from django.db.models import Aggregate", "from django.contrib.gis.db.models.sql import GeomField", "class Collect(Aggregate):\n name = 'Collect'", " name = 'Collect'", "class Extent(Aggregate):\n name = 'Extent'", " name = 'Extent'", "class Extent3D(Aggregate):\n name = 'Extent3D'", " ...
# Want to get everything from the 'normal' models package. from django.db.models import * # Geographic aggregate functions from django.contrib.gis.db.models.aggregates import * # The GeoManager from django.contrib.gis.db.models.manager import GeoManager # The geographic-enabled fields. from django.contrib.gis.db.models.fields import \ GeometryField, PointField, LineStringField, PolygonField, \ MultiPointField, MultiLineStringField, MultiPolygonField, \ GeometryCollectionField
[ [ 1, 0, 0.1429, 0.0714, 0, 0.66, 0, 680, 0, 1, 0, 0, 680, 0, 0 ], [ 1, 0, 0.3571, 0.0714, 0, 0.66, 0.3333, 920, 0, 1, 0, 0, 920, 0, 0 ], [ 1, 0, 0.5714, 0.0714, 0, ...
[ "from django.db.models import *", "from django.contrib.gis.db.models.aggregates import *", "from django.contrib.gis.db.models.manager import GeoManager", "from django.contrib.gis.db.models.fields import \\\n GeometryField, PointField, LineStringField, PolygonField, \\\n MultiPointField, MultiLineStrin...
from django.db.models.manager import Manager from django.contrib.gis.db.models.query import GeoQuerySet class GeoManager(Manager): "Overrides Manager to return Geographic QuerySets." # This manager should be used for queries on related fields # so that geometry columns on Oracle and MySQL are selected # properly. use_for_related_fields = True def get_query_set(self): return GeoQuerySet(self.model, using=self._db) def area(self, *args, **kwargs): return self.get_query_set().area(*args, **kwargs) def centroid(self, *args, **kwargs): return self.get_query_set().centroid(*args, **kwargs) def collect(self, *args, **kwargs): return self.get_query_set().collect(*args, **kwargs) def difference(self, *args, **kwargs): return self.get_query_set().difference(*args, **kwargs) def distance(self, *args, **kwargs): return self.get_query_set().distance(*args, **kwargs) def envelope(self, *args, **kwargs): return self.get_query_set().envelope(*args, **kwargs) def extent(self, *args, **kwargs): return self.get_query_set().extent(*args, **kwargs) def extent3d(self, *args, **kwargs): return self.get_query_set().extent3d(*args, **kwargs) def force_rhr(self, *args, **kwargs): return self.get_query_set().force_rhr(*args, **kwargs) def geohash(self, *args, **kwargs): return self.get_query_set().geohash(*args, **kwargs) def geojson(self, *args, **kwargs): return self.get_query_set().geojson(*args, **kwargs) def gml(self, *args, **kwargs): return self.get_query_set().gml(*args, **kwargs) def intersection(self, *args, **kwargs): return self.get_query_set().intersection(*args, **kwargs) def kml(self, *args, **kwargs): return self.get_query_set().kml(*args, **kwargs) def length(self, *args, **kwargs): return self.get_query_set().length(*args, **kwargs) def make_line(self, *args, **kwargs): return self.get_query_set().make_line(*args, **kwargs) def mem_size(self, *args, **kwargs): return self.get_query_set().mem_size(*args, **kwargs) def num_geom(self, *args, **kwargs): return self.get_query_set().num_geom(*args, **kwargs) def num_points(self, *args, **kwargs): return self.get_query_set().num_points(*args, **kwargs) def perimeter(self, *args, **kwargs): return self.get_query_set().perimeter(*args, **kwargs) def point_on_surface(self, *args, **kwargs): return self.get_query_set().point_on_surface(*args, **kwargs) def reverse_geom(self, *args, **kwargs): return self.get_query_set().reverse_geom(*args, **kwargs) def scale(self, *args, **kwargs): return self.get_query_set().scale(*args, **kwargs) def snap_to_grid(self, *args, **kwargs): return self.get_query_set().snap_to_grid(*args, **kwargs) def svg(self, *args, **kwargs): return self.get_query_set().svg(*args, **kwargs) def sym_difference(self, *args, **kwargs): return self.get_query_set().sym_difference(*args, **kwargs) def transform(self, *args, **kwargs): return self.get_query_set().transform(*args, **kwargs) def translate(self, *args, **kwargs): return self.get_query_set().translate(*args, **kwargs) def union(self, *args, **kwargs): return self.get_query_set().union(*args, **kwargs) def unionagg(self, *args, **kwargs): return self.get_query_set().unionagg(*args, **kwargs)
[ [ 1, 0, 0.0097, 0.0097, 0, 0.66, 0, 59, 0, 1, 0, 0, 59, 0, 0 ], [ 1, 0, 0.0194, 0.0097, 0, 0.66, 0.5, 817, 0, 1, 0, 0, 817, 0, 0 ], [ 3, 0, 0.5194, 0.9709, 0, 0.66,...
[ "from django.db.models.manager import Manager", "from django.contrib.gis.db.models.query import GeoQuerySet", "class GeoManager(Manager):\n \"Overrides Manager to return Geographic QuerySets.\"\n\n # This manager should be used for queries on related fields\n # so that geometry columns on Oracle and My...
from MySQLdb.constants import FIELD_TYPE from django.contrib.gis.gdal import OGRGeomType from django.db.backends.mysql.introspection import DatabaseIntrospection class MySQLIntrospection(DatabaseIntrospection): # Updating the data_types_reverse dictionary with the appropriate # type for Geometry fields. data_types_reverse = DatabaseIntrospection.data_types_reverse.copy() data_types_reverse[FIELD_TYPE.GEOMETRY] = 'GeometryField' def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # In order to get the specific geometry type of the field, # we introspect on the table definition using `DESCRIBE`. cursor.execute('DESCRIBE %s' % self.connection.ops.quote_name(table_name)) # Increment over description info until we get to the geometry # column. for column, typ, null, key, default, extra in cursor.fetchall(): if column == geo_col: # Using OGRGeomType to convert from OGC name to Django field. # MySQL does not support 3D or SRIDs, so the field params # are empty. field_type = OGRGeomType(typ).django field_params = {} break finally: cursor.close() return field_type, field_params
[ [ 1, 0, 0.0312, 0.0312, 0, 0.66, 0, 412, 0, 1, 0, 0, 412, 0, 0 ], [ 1, 0, 0.0938, 0.0312, 0, 0.66, 0.3333, 793, 0, 1, 0, 0, 793, 0, 0 ], [ 1, 0, 0.125, 0.0312, 0, 0...
[ "from MySQLdb.constants import FIELD_TYPE", "from django.contrib.gis.gdal import OGRGeomType", "from django.db.backends.mysql.introspection import DatabaseIntrospection", "class MySQLIntrospection(DatabaseIntrospection):\n # Updating the data_types_reverse dictionary with the appropriate\n # type for Ge...
from django.db.backends.mysql.base import DatabaseOperations from django.contrib.gis.db.backends.adapter import WKTAdapter from django.contrib.gis.db.backends.base import BaseSpatialOperations class MySQLOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' mysql = True name = 'mysql' select = 'AsText(%s)' from_wkb = 'GeomFromWKB' from_text = 'GeomFromText' Adapter = WKTAdapter Adaptor = Adapter # Backwards-compatibility alias. geometry_functions = { 'bbcontains' : 'MBRContains', # For consistency w/PostGIS API 'bboverlaps' : 'MBROverlaps', # .. .. 'contained' : 'MBRWithin', # .. .. 'contains' : 'MBRContains', 'disjoint' : 'MBRDisjoint', 'equals' : 'MBREqual', 'exact' : 'MBREqual', 'intersects' : 'MBRIntersects', 'overlaps' : 'MBROverlaps', 'same_as' : 'MBREqual', 'touches' : 'MBRTouches', 'within' : 'MBRWithin', } gis_terms = dict([(term, None) for term in geometry_functions.keys() + ['isnull']]) def geo_db_type(self, f): return f.geom_type def get_geom_placeholder(self, value, srid): """ The placeholder here has to include MySQL's WKT constructor. Because MySQL does not support spatial transformations, there is no need to modify the placeholder based on the contents of the given value. """ if hasattr(value, 'expression'): placeholder = '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression])) else: placeholder = '%s(%%s)' % self.from_text return placeholder def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): alias, col, db_type = lvalue geo_col = '%s.%s' % (qn(alias), qn(col)) lookup_info = self.geometry_functions.get(lookup_type, False) if lookup_info: return "%s(%s, %s)" % (lookup_info, geo_col, self.get_geom_placeholder(value, field.srid)) # TODO: Is this really necessary? MySQL can't handle NULL geometries # in its spatial indexes anyways. if lookup_type == 'isnull': return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or '')) raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type))
[ [ 1, 0, 0.0154, 0.0154, 0, 0.66, 0, 150, 0, 1, 0, 0, 150, 0, 0 ], [ 1, 0, 0.0462, 0.0154, 0, 0.66, 0.3333, 423, 0, 1, 0, 0, 423, 0, 0 ], [ 1, 0, 0.0615, 0.0154, 0, ...
[ "from django.db.backends.mysql.base import DatabaseOperations", "from django.contrib.gis.db.backends.adapter import WKTAdapter", "from django.contrib.gis.db.backends.base import BaseSpatialOperations", "class MySQLOperations(DatabaseOperations, BaseSpatialOperations):\n\n compiler_module = 'django.contrib....
from django.db.backends.mysql.creation import DatabaseCreation class MySQLCreation(DatabaseCreation): def sql_indexes_for_field(self, model, f, style): from django.contrib.gis.db.models.fields import GeometryField output = super(MySQLCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField) and f.spatial_index: qn = self.connection.ops.quote_name db_table = model._meta.db_table idx_name = '%s_%s_id' % (db_table, f.column) output.append(style.SQL_KEYWORD('CREATE SPATIAL INDEX ') + style.SQL_TABLE(qn(idx_name)) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + '(' + style.SQL_FIELD(qn(f.column)) + ');') return output
[ [ 1, 0, 0.0556, 0.0556, 0, 0.66, 0, 326, 0, 1, 0, 0, 326, 0, 0 ], [ 3, 0, 0.5833, 0.8889, 0, 0.66, 1, 391, 0, 1, 0, 0, 625, 0, 12 ], [ 2, 1, 0.6389, 0.7778, 1, 0.37...
[ "from django.db.backends.mysql.creation import DatabaseCreation", "class MySQLCreation(DatabaseCreation):\n\n def sql_indexes_for_field(self, model, f, style):\n from django.contrib.gis.db.models.fields import GeometryField\n output = super(MySQLCreation, self).sql_indexes_for_field(model, f, sty...
from django.db.backends.mysql.base import * from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper from django.contrib.gis.db.backends.mysql.creation import MySQLCreation from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection from django.contrib.gis.db.backends.mysql.operations import MySQLOperations class DatabaseWrapper(MySQLDatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = MySQLCreation(self) self.ops = MySQLOperations() self.introspection = MySQLIntrospection(self)
[ [ 1, 0, 0.0769, 0.0769, 0, 0.66, 0, 150, 0, 1, 0, 0, 150, 0, 0 ], [ 1, 0, 0.1538, 0.0769, 0, 0.66, 0.2, 150, 0, 1, 0, 0, 150, 0, 0 ], [ 1, 0, 0.2308, 0.0769, 0, 0.6...
[ "from django.db.backends.mysql.base import *", "from django.db.backends.mysql.base import DatabaseWrapper as MySQLDatabaseWrapper", "from django.contrib.gis.db.backends.mysql.creation import MySQLCreation", "from django.contrib.gis.db.backends.mysql.introspection import MySQLIntrospection", "from django.con...
class WKTAdapter(object): """ This provides an adaptor for Geometries sent to the MySQL and Oracle database backends. """ def __init__(self, geom): self.wkt = geom.wkt self.srid = geom.srid def __eq__(self, other): return self.wkt == other.wkt and self.srid == other.srid def __str__(self): return self.wkt def prepare_database_save(self, unused): return self
[ [ 3, 0, 0.5294, 1, 0, 0.66, 0, 868, 0, 4, 0, 0, 186, 0, 0 ], [ 8, 1, 0.2059, 0.2353, 1, 0.52, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 1, 0.4118, 0.1765, 1, 0.52, 0.25...
[ "class WKTAdapter(object):\n \"\"\"\n This provides an adaptor for Geometries sent to the\n MySQL and Oracle database backends.\n \"\"\"\n def __init__(self, geom):\n self.wkt = geom.wkt\n self.srid = geom.srid", " \"\"\"\n This provides an adaptor for Geometries sent to the\n ...
from django.contrib.gis.gdal import OGRGeomType from django.db.backends.sqlite3.introspection import DatabaseIntrospection, FlexibleFieldLookupDict class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict): """ Sublcass that includes updates the `base_data_types_reverse` dict for geometry field types. """ base_data_types_reverse = FlexibleFieldLookupDict.base_data_types_reverse.copy() base_data_types_reverse.update( {'point' : 'GeometryField', 'linestring' : 'GeometryField', 'polygon' : 'GeometryField', 'multipoint' : 'GeometryField', 'multilinestring' : 'GeometryField', 'multipolygon' : 'GeometryField', 'geometrycollection' : 'GeometryField', }) class SpatiaLiteIntrospection(DatabaseIntrospection): data_types_reverse = GeoFlexibleFieldLookupDict() def get_geometry_type(self, table_name, geo_col): cursor = self.connection.cursor() try: # Querying the `geometry_columns` table to get additional metadata. cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geometry_columns" ' 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise Exception('Could not find a geometry column for "%s"."%s"' % (table_name, geo_col)) # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. field_type = OGRGeomType(row[2]).django # Getting any GeometryField keyword arguments that are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params['srid'] = srid if isinstance(dim, basestring) and 'Z' in dim: field_params['dim'] = 3 finally: cursor.close() return field_type, field_params
[ [ 1, 0, 0.0196, 0.0196, 0, 0.66, 0, 793, 0, 1, 0, 0, 793, 0, 0 ], [ 1, 0, 0.0392, 0.0196, 0, 0.66, 0.3333, 774, 0, 2, 0, 0, 774, 0, 0 ], [ 3, 0, 0.2157, 0.2941, 0, ...
[ "from django.contrib.gis.gdal import OGRGeomType", "from django.db.backends.sqlite3.introspection import DatabaseIntrospection, FlexibleFieldLookupDict", "class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):\n \"\"\"\n Sublcass that includes updates the `base_data_types_reverse` dict\n for geomet...
from django.db.backends.sqlite3.base import Database from django.contrib.gis.db.backends.adapter import WKTAdapter class SpatiaLiteAdapter(WKTAdapter): "SQLite adaptor for geometry objects." def __conform__(self, protocol): if protocol is Database.PrepareProtocol: return str(self)
[ [ 1, 0, 0.125, 0.125, 0, 0.66, 0, 460, 0, 1, 0, 0, 460, 0, 0 ], [ 1, 0, 0.25, 0.125, 0, 0.66, 0.5, 423, 0, 1, 0, 0, 423, 0, 0 ], [ 3, 0, 0.75, 0.625, 0, 0.66, 1...
[ "from django.db.backends.sqlite3.base import Database", "from django.contrib.gis.db.backends.adapter import WKTAdapter", "class SpatiaLiteAdapter(WKTAdapter):\n \"SQLite adaptor for geometry objects.\"\n def __conform__(self, protocol):\n if protocol is Database.PrepareProtocol:\n return...
from django.db.backends.sqlite3.client import DatabaseClient class SpatiaLiteClient(DatabaseClient): executable_name = 'spatialite'
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 3, 0, 0.7, 0.4, 0, 0.66, 1, 345, 0, 0, 0, 0, 207, 0, 0 ], [ 14, 1, 0.8, 0.2, 1, 0.63, 0, 723, ...
[ "from django.db.backends.sqlite3.client import DatabaseClient", "class SpatiaLiteClient(DatabaseClient):\n executable_name = 'spatialite'", " executable_name = 'spatialite'" ]
""" The GeometryColumns and SpatialRefSys models for the SpatiaLite backend. """ from django.db import models from django.contrib.gis.db.backends.base import SpatialRefSysMixin class GeometryColumns(models.Model): """ The 'geometry_columns' table from SpatiaLite. """ f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) type = models.CharField(max_length=30) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) spatial_index_enabled = models.IntegerField() class Meta: db_table = 'geometry_columns' managed = False @classmethod def table_name_col(cls): """ Returns the name of the metadata column used to store the the feature table name. """ return 'f_table_name' @classmethod def geom_col_name(cls): """ Returns the name of the metadata column used to store the the feature geometry column. """ return 'f_geometry_column' def __unicode__(self): return "%s.%s - %dD %s field (SRID: %d)" % \ (self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid) class SpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from SpatiaLite. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() ref_sys_name = models.CharField(max_length=256) proj4text = models.CharField(max_length=2048) @property def wkt(self): from django.contrib.gis.gdal import SpatialReference return SpatialReference(self.proj4text).wkt class Meta: db_table = 'spatial_ref_sys' managed = False
[ [ 8, 0, 0.0333, 0.05, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0667, 0.0167, 0, 0.66, 0.25, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0833, 0.0167, 0, 0.66, ...
[ "\"\"\"\n The GeometryColumns and SpatialRefSys models for the SpatiaLite backend.\n\"\"\"", "from django.db import models", "from django.contrib.gis.db.backends.base import SpatialRefSysMixin", "class GeometryColumns(models.Model):\n \"\"\"\n The 'geometry_columns' table from SpatiaLite.\n \"\"\"\n ...
import re from decimal import Decimal from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.base import DatabaseOperations from django.db.utils import DatabaseError class SpatiaLiteOperator(SpatialOperation): "For SpatiaLite operators (e.g. `&&`, `~`)." def __init__(self, operator): super(SpatiaLiteOperator, self).__init__(operator=operator) class SpatiaLiteFunction(SpatialFunction): "For SpatiaLite function calls." def __init__(self, function, **kwargs): super(SpatiaLiteFunction, self).__init__(function, **kwargs) class SpatiaLiteFunctionParam(SpatiaLiteFunction): "For SpatiaLite functions that take another parameter." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class SpatiaLiteDistance(SpatiaLiteFunction): "For SpatiaLite distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, operator): super(SpatiaLiteDistance, self).__init__(self.dist_func, operator=operator) class SpatiaLiteRelate(SpatiaLiteFunctionParam): "For SpatiaLite Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(SpatiaLiteRelate, self).__init__('Relate') # Valid distance types and substitutions dtypes = (Decimal, Distance, float, int, long) def get_dist_ops(operator): "Returns operations for regular distances; spherical distances are not currently supported." return (SpatiaLiteDistance(operator),) class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'spatialite' spatialite = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Extent', 'Union')]) Adapter = SpatiaLiteAdapter Adaptor = Adapter # Backwards-compatibility alias. area = 'Area' centroid = 'Centroid' contained = 'MbrWithin' difference = 'Difference' distance = 'Distance' envelope = 'Envelope' intersection = 'Intersection' length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword num_geom = 'NumGeometries' num_points = 'NumPoints' point_on_surface = 'PointOnSurface' scale = 'ScaleCoords' svg = 'AsSVG' sym_difference = 'SymDifference' transform = 'Transform' translate = 'ShiftCoords' union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword unionagg = 'GUnion' from_text = 'GeomFromText' from_wkb = 'GeomFromWKB' select = 'AsText(%s)' geometry_functions = { 'equals' : SpatiaLiteFunction('Equals'), 'disjoint' : SpatiaLiteFunction('Disjoint'), 'touches' : SpatiaLiteFunction('Touches'), 'crosses' : SpatiaLiteFunction('Crosses'), 'within' : SpatiaLiteFunction('Within'), 'overlaps' : SpatiaLiteFunction('Overlaps'), 'contains' : SpatiaLiteFunction('Contains'), 'intersects' : SpatiaLiteFunction('Intersects'), 'relate' : (SpatiaLiteRelate, basestring), # Retruns true if B's bounding box completely contains A's bounding box. 'contained' : SpatiaLiteFunction('MbrWithin'), # Returns true if A's bounding box completely contains B's bounding box. 'bbcontains' : SpatiaLiteFunction('MbrContains'), # Returns true if A's bounding box overlaps B's bounding box. 'bboverlaps' : SpatiaLiteFunction('MbrOverlaps'), # These are implemented here as synonyms for Equals 'same_as' : SpatiaLiteFunction('Equals'), 'exact' : SpatiaLiteFunction('Equals'), } distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), } geometry_functions.update(distance_functions) def __init__(self, connection): super(DatabaseOperations, self).__init__() self.connection = connection # Determine the version of the SpatiaLite library. try: vtup = self.spatialite_version_tuple() version = vtup[1:] if version < (2, 3, 0): raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions ' '2.3.0 and above') self.spatial_version = version except ImproperlyConfigured: raise except Exception, msg: raise ImproperlyConfigured('Cannot determine the SpatiaLite version for the "%s" ' 'database (error was "%s"). Was the SpatiaLite initialization ' 'SQL loaded on this database?' % (self.connection.settings_dict['NAME'], msg)) # Creating the GIS terms dictionary. gis_terms = ['isnull'] gis_terms += self.geometry_functions.keys() self.gis_terms = dict([(term, None) for term in gis_terms]) def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_geom(self, wkt, geo_field): """ Converts geometry WKT returned from a SpatiaLite aggregate. """ if wkt: return Geometry(wkt, geo_field.srid) else: return None def geo_db_type(self, f): """ Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None def get_distance(self, f, value, lookup_type): """ Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS). """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on ' 'geometry fields with a geodetic coordinate system. ' 'Distance objects; use a numeric value of your ' 'distance in degrees instead.') else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s). """ def transform_value(value, srid): return not (value is None or value.srid == srid) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = '%s(%%s, %s)' % (self.transform, f.srid) else: placeholder = '%s' # No geometry value used for F expression, substitue in # the column name instead. return placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression])) else: if transform_value(value, f.srid): # Adding Transform() to the SQL placeholder. return '%s(%s(%%s,%s), %s)' % (self.transform, self.from_text, value.srid, f.srid) else: return '%s(%%s,%s)' % (self.from_text, f.srid) def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. """ cursor = self.connection._cursor() try: try: cursor.execute('SELECT %s' % func) row = cursor.fetchone() except: # Responsibility of caller to perform error handling. raise finally: cursor.close() return row[0] def geos_version(self): "Returns the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func('geos_version()') def proj4_version(self): "Returns the version of the PROJ.4 library used by SpatiaLite." return self._get_spatialite_func('proj4_version()') def spatialite_version(self): "Returns the SpatiaLite library version as a string." return self._get_spatialite_func('spatialite_version()') def spatialite_version_tuple(self): """ Returns the SpatiaLite version as a tuple (version string, major, minor, subminor). """ # Getting the SpatiaLite version. try: version = self.spatialite_version() except DatabaseError: # The `spatialite_version` function first appeared in version 2.3.1 # of SpatiaLite, so doing a fallback test for 2.3.0 (which is # used by popular Debian/Ubuntu packages). version = None try: tmp = self._get_spatialite_func("X(GeomFromText('POINT(1 1)'))") if tmp == 1.0: version = '2.3.0' except DatabaseError: pass # If no version string defined, then just re-raise the original # exception. if version is None: raise m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse SpatiaLite version string: %s' % version) return (version, major, minor1, minor2) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = self.select % '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Returns the SpatiaLite-specific SQL for the given lookup value [a tuple of (alias, column, db_type)], lookup type, lookup value, the model field, and the quoting function. """ alias, col, db_type = lvalue # Getting the quoted field as `geo_col`. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_functions: # See if a SpatiaLite geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the SpatiaLiteOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. if len(value) != 2: raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(value[1]) elif lookup_type in self.distance_functions: op = op[0] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or '')) raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.spatialite.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.spatialite.models import SpatialRefSys return SpatialRefSys
[ [ 1, 0, 0.0029, 0.0029, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0058, 0.0029, 0, 0.66, 0.0588, 349, 0, 1, 0, 0, 349, 0, 0 ], [ 1, 0, 0.0117, 0.0029, 0, ...
[ "import re", "from decimal import Decimal", "from django.contrib.gis.db.backends.base import BaseSpatialOperations", "from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction", "from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter", "from django.contrib....
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.db.backends.sqlite3.creation import DatabaseCreation class SpatiaLiteCreation(DatabaseCreation): def create_test_db(self, verbosity=1, autoclobber=False): """ Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. This method is overloaded to load up the SpatiaLite initialization SQL prior to calling the `syncdb` command. """ if verbosity >= 1: print "Creating test database '%s'..." % self.connection.alias test_database_name = self._create_test_db(verbosity, autoclobber) self.connection.close() self.connection.settings_dict["NAME"] = test_database_name # Confirm the feature set of the test database self.connection.features.confirm() # Need to load the SpatiaLite initialization SQL before running `syncdb`. self.load_spatialite_sql() call_command('syncdb', verbosity=verbosity, interactive=False, database=self.connection.alias) if settings.CACHE_BACKEND.startswith('db://'): from django.core.cache import parse_backend_uri _, cache_name, _ = parse_backend_uri(settings.CACHE_BACKEND) call_command('createcachetable', cache_name) # Get a cursor (even though we don't need one yet). This has # the side effect of initializing the test database. cursor = self.connection.cursor() return test_database_name def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table output.append(style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn') + '(' + style.SQL_TABLE(gqn(db_table)) + ', ' + style.SQL_FIELD(gqn(f.column)) + ', ' + style.SQL_FIELD(str(f.srid)) + ', ' + style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' + style.SQL_KEYWORD(str(f.dim)) + ', ' + style.SQL_KEYWORD(str(int(not f.null))) + ');') if f.spatial_index: output.append(style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('CreateSpatialIndex') + '(' + style.SQL_TABLE(gqn(db_table)) + ', ' + style.SQL_FIELD(gqn(f.column)) + ');') return output def load_spatialite_sql(self): """ This routine loads up the SpatiaLite SQL file. """ # Getting the location of the SpatiaLite SQL file, and confirming # it exists. spatialite_sql = self.spatialite_init_file() if not os.path.isfile(spatialite_sql): raise ImproperlyConfigured('Could not find the required SpatiaLite initialization ' 'SQL file (necessary for testing): %s' % spatialite_sql) # Opening up the SpatiaLite SQL initialization file and executing # as a script. sql_fh = open(spatialite_sql, 'r') try: cur = self.connection._cursor() cur.executescript(sql_fh.read()) finally: sql_fh.close() def spatialite_init_file(self): # SPATIALITE_SQL may be placed in settings to tell GeoDjango # to use a specific path to the SpatiaLite initilization SQL. return getattr(settings, 'SPATIALITE_SQL', 'init_spatialite-%s.%s.sql' % self.connection.ops.spatial_version[:2])
[ [ 1, 0, 0.0104, 0.0104, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0208, 0.0104, 0, 0.66, 0.2, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0312, 0.0104, 0, 0.6...
[ "import os", "from django.conf import settings", "from django.core.exceptions import ImproperlyConfigured", "from django.core.management import call_command", "from django.db.backends.sqlite3.creation import DatabaseCreation", "class SpatiaLiteCreation(DatabaseCreation):\n\n def create_test_db(self, ve...
from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection from django.contrib.gis.gdal import OGRGeomType class GeoIntrospectionError(Exception): pass class PostGISIntrospection(DatabaseIntrospection): # Reverse dictionary for PostGIS geometry types not populated until # introspection is actually performed. postgis_types_reverse = {} def get_postgis_types(self): """ Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported). """ cursor = self.connection.cursor() # The OID integers associated with the geometry type may # be different across versions; hence, this is why we have # to query the PostgreSQL pg_type table corresponding to the # PostGIS custom data types. oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s' try: cursor.execute(oid_sql, ('geometry',)) GEOM_TYPE = cursor.fetchone()[0] postgis_types = { GEOM_TYPE : 'GeometryField' } if self.connection.ops.geography: cursor.execute(oid_sql, ('geography',)) GEOG_TYPE = cursor.fetchone()[0] # The value for the geography type is actually a tuple # to pass in the `geography=True` keyword to the field # definition. postgis_types[GEOG_TYPE] = ('GeometryField', {'geography' : True}) finally: cursor.close() return postgis_types def get_field_type(self, data_type, description): if not self.postgis_types_reverse: # If the PostGIS types reverse dictionary is not populated, do so # now. In order to prevent unnecessary requests upon connection # intialization, the `data_types_reverse` dictionary is not updated # with the PostGIS custom types until introspection is actually # performed -- in other words, when this function is called. self.postgis_types_reverse = self.get_postgis_types() self.data_types_reverse.update(self.postgis_types_reverse) return super(PostGISIntrospection, self).get_field_type(data_type, description) def get_geometry_type(self, table_name, geo_col): """ The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type, """ cursor = self.connection.cursor() try: try: # First seeing if this geometry column is in the `geometry_columns` cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geometry_columns" ' 'WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise GeoIntrospectionError except GeoIntrospectionError: if self.connection.ops.geography: cursor.execute('SELECT "coord_dimension", "srid", "type" ' 'FROM "geography_columns" ' 'WHERE "f_table_name"=%s AND "f_geography_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if not row: raise Exception('Could not find a geometry or geography column for "%s"."%s"' % (table_name, geo_col)) # OGRGeomType does not require GDAL and makes it easy to convert # from OGC geom type name to Django field. field_type = OGRGeomType(row[2]).django # Getting any GeometryField keyword arguments that are not the default. dim = row[0] srid = row[1] field_params = {} if srid != 4326: field_params['srid'] = srid if dim != 2: field_params['dim'] = dim finally: cursor.close() return field_type, field_params
[ [ 1, 0, 0.0105, 0.0105, 0, 0.66, 0, 862, 0, 1, 0, 0, 862, 0, 0 ], [ 1, 0, 0.0211, 0.0105, 0, 0.66, 0.3333, 793, 0, 1, 0, 0, 793, 0, 0 ], [ 3, 0, 0.0474, 0.0211, 0, ...
[ "from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection", "from django.contrib.gis.gdal import OGRGeomType", "class GeoIntrospectionError(Exception):\n pass", "class PostGISIntrospection(DatabaseIntrospection):\n # Reverse dictionary for PostGIS geometry types not populat...
""" This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. """ from psycopg2 import Binary from psycopg2.extensions import ISQLQuote class PostGISAdapter(object): def __init__(self, geom): "Initializes on the geometry." # Getting the WKB (in string form, to allow easy pickling of # the adaptor) and the SRID from the geometry. self.ewkb = str(geom.ewkb) self.srid = geom.srid def __conform__(self, proto): # Does the given protocol conform to what Psycopg2 expects? if proto == ISQLQuote: return self else: raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?') def __eq__(self, other): return (self.ewkb == other.ewkb) and (self.srid == other.srid) def __str__(self): return self.getquoted() def getquoted(self): "Returns a properly quoted string for use in PostgreSQL/PostGIS." # Want to use WKB, so wrap with psycopg2 Binary() to quote properly. return 'ST_GeomFromEWKB(E%s)' % Binary(self.ewkb) def prepare_database_save(self, unused): return self
[ [ 8, 0, 0.0571, 0.0857, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1429, 0.0286, 0, 0.66, 0.3333, 202, 0, 1, 0, 0, 202, 0, 0 ], [ 1, 0, 0.1714, 0.0286, 0, 0.66...
[ "\"\"\"\n This object provides quoting for GEOS geometries into PostgreSQL/PostGIS.\n\"\"\"", "from psycopg2 import Binary", "from psycopg2.extensions import ISQLQuote", "class PostGISAdapter(object):\n def __init__(self, geom):\n \"Initializes on the geometry.\"\n # Getting the WKB (in strin...
""" The GeometryColumns and SpatialRefSys models for the PostGIS backend. """ from django.db import models from django.contrib.gis.db.backends.base import SpatialRefSysMixin class GeometryColumns(models.Model): """ The 'geometry_columns' table from the PostGIS. See the PostGIS documentation at Ch. 4.2.2. """ f_table_catalog = models.CharField(max_length=256) f_table_schema = models.CharField(max_length=256) f_table_name = models.CharField(max_length=256) f_geometry_column = models.CharField(max_length=256) coord_dimension = models.IntegerField() srid = models.IntegerField(primary_key=True) type = models.CharField(max_length=30) class Meta: db_table = 'geometry_columns' managed = False @classmethod def table_name_col(cls): """ Returns the name of the metadata column used to store the the feature table name. """ return 'f_table_name' @classmethod def geom_col_name(cls): """ Returns the name of the metadata column used to store the the feature geometry column. """ return 'f_geometry_column' def __unicode__(self): return "%s.%s - %dD %s field (SRID: %d)" % \ (self.f_table_name, self.f_geometry_column, self.coord_dimension, self.type, self.srid) class SpatialRefSys(models.Model, SpatialRefSysMixin): """ The 'spatial_ref_sys' table from PostGIS. See the PostGIS documentaiton at Ch. 4.2.1. """ srid = models.IntegerField(primary_key=True) auth_name = models.CharField(max_length=256) auth_srid = models.IntegerField() srtext = models.CharField(max_length=2048) proj4text = models.CharField(max_length=2048) class Meta: db_table = 'spatial_ref_sys' managed = False @property def wkt(self): return self.srtext @classmethod def wkt_col(cls): return 'srtext'
[ [ 8, 0, 0.0303, 0.0455, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0606, 0.0152, 0, 0.66, 0.25, 40, 0, 1, 0, 0, 40, 0, 0 ], [ 1, 0, 0.0758, 0.0152, 0, 0.66, ...
[ "\"\"\"\n The GeometryColumns and SpatialRefSys models for the PostGIS backend.\n\"\"\"", "from django.db import models", "from django.contrib.gis.db.backends.base import SpatialRefSysMixin", "class GeometryColumns(models.Model):\n \"\"\"\n The 'geometry_columns' table from the PostGIS. See the PostGIS\...
import re from decimal import Decimal from django.conf import settings from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.postgresql_psycopg2.base import DatabaseOperations from django.db.utils import DatabaseError #### Classes used in constructing PostGIS spatial SQL #### class PostGISOperator(SpatialOperation): "For PostGIS operators (e.g. `&&`, `~`)." def __init__(self, operator): super(PostGISOperator, self).__init__(operator=operator) class PostGISFunction(SpatialFunction): "For PostGIS function calls (e.g., `ST_Contains(table, geom)`)." def __init__(self, prefix, function, **kwargs): super(PostGISFunction, self).__init__(prefix + function, **kwargs) class PostGISFunctionParam(PostGISFunction): "For PostGIS functions that take another parameter (e.g. DWithin, Relate)." sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s)' class PostGISDistance(PostGISFunction): "For PostGIS distance operations." dist_func = 'Distance' sql_template = '%(function)s(%(geo_col)s, %(geometry)s) %(operator)s %%s' def __init__(self, prefix, operator): super(PostGISDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSpheroidDistance(PostGISFunction): "For PostGIS spherical distance operations (using the spheroid)." dist_func = 'distance_spheroid' sql_template = '%(function)s(%(geo_col)s, %(geometry)s, %%s) %(operator)s %%s' def __init__(self, prefix, operator): # An extra parameter in `end_subst` is needed for the spheroid string. super(PostGISSpheroidDistance, self).__init__(prefix, self.dist_func, operator=operator) class PostGISSphereDistance(PostGISDistance): "For PostGIS spherical distance operations." dist_func = 'distance_sphere' class PostGISRelate(PostGISFunctionParam): "For PostGIS Relate(<geom>, <pattern>) calls." pattern_regex = re.compile(r'^[012TF\*]{9}$') def __init__(self, prefix, pattern): if not self.pattern_regex.match(pattern): raise ValueError('Invalid intersection matrix pattern "%s".' % pattern) super(PostGISRelate, self).__init__(prefix, 'Relate') class PostGISOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = 'django.contrib.gis.db.models.sql.compiler' name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) # Trying to get the PostGIS version because the function # signatures will depend on the version used. The cost # here is a database query to determine the version, which # can be mitigated by setting `POSTGIS_VERSION` with a 3-tuple # comprising user-supplied values for the major, minor, and # subminor revision of PostGIS. try: if hasattr(settings, 'POSTGIS_VERSION'): vtup = settings.POSTGIS_VERSION if len(vtup) == 3: # The user-supplied PostGIS version. version = vtup else: # This was the old documented way, but it's stupid to # include the string. version = vtup[1:4] else: vtup = self.postgis_version_tuple() version = vtup[1:] # Getting the prefix -- even though we don't officially support # PostGIS 1.2 anymore, keeping it anyway in case a prefix change # for something else is necessary. if version >= (1, 2, 2): prefix = 'ST_' else: prefix = '' self.geom_func_prefix = prefix self.spatial_version = version except DatabaseError: raise ImproperlyConfigured('Cannot determine PostGIS version for database "%s". ' 'GeoDjango requires at least PostGIS version 1.3. ' 'Was the database created from a spatial database ' 'template?' % self.connection.settings_dict['NAME'] ) except Exception, e: # TODO: Raise helpful exceptions as they become known. raise # PostGIS-specific operators. The commented descriptions of these # operators come from Section 7.6 of the PostGIS 1.4 documentation. self.geometry_operators = { # The "&<" operator returns true if A's bounding box overlaps or # is to the left of B's bounding box. 'overlaps_left' : PostGISOperator('&<'), # The "&>" operator returns true if A's bounding box overlaps or # is to the right of B's bounding box. 'overlaps_right' : PostGISOperator('&>'), # The "<<" operator returns true if A's bounding box is strictly # to the left of B's bounding box. 'left' : PostGISOperator('<<'), # The ">>" operator returns true if A's bounding box is strictly # to the right of B's bounding box. 'right' : PostGISOperator('>>'), # The "&<|" operator returns true if A's bounding box overlaps or # is below B's bounding box. 'overlaps_below' : PostGISOperator('&<|'), # The "|&>" operator returns true if A's bounding box overlaps or # is above B's bounding box. 'overlaps_above' : PostGISOperator('|&>'), # The "<<|" operator returns true if A's bounding box is strictly # below B's bounding box. 'strictly_below' : PostGISOperator('<<|'), # The "|>>" operator returns true if A's bounding box is strictly # above B's bounding box. 'strictly_above' : PostGISOperator('|>>'), # The "~=" operator is the "same as" operator. It tests actual # geometric equality of two features. So if A and B are the same feature, # vertex-by-vertex, the operator returns true. 'same_as' : PostGISOperator('~='), 'exact' : PostGISOperator('~='), # The "@" operator returns true if A's bounding box is completely contained # by B's bounding box. 'contained' : PostGISOperator('@'), # The "~" operator returns true if A's bounding box completely contains # by B's bounding box. 'bbcontains' : PostGISOperator('~'), # The "&&" operator returns true if A's bounding box overlaps # B's bounding box. 'bboverlaps' : PostGISOperator('&&'), } self.geometry_functions = { 'equals' : PostGISFunction(prefix, 'Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), 'contains' : PostGISFunction(prefix, 'Contains'), 'intersects' : PostGISFunction(prefix, 'Intersects'), 'relate' : (PostGISRelate, basestring), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float, int, long) def get_dist_ops(operator): "Returns operations for both regular and spherical distances." return {'cartesian' : PostGISDistance(prefix, operator), 'sphere' : PostGISSphereDistance(prefix, operator), 'spheroid' : PostGISSpheroidDistance(prefix, operator), } self.distance_functions = { 'distance_gt' : (get_dist_ops('>'), dtypes), 'distance_gte' : (get_dist_ops('>='), dtypes), 'distance_lt' : (get_dist_ops('<'), dtypes), 'distance_lte' : (get_dist_ops('<='), dtypes), } # Versions 1.2.2+ have KML serialization support. if version < (1, 2, 2): ASKML = False else: ASKML = 'ST_AsKML' self.geometry_functions.update( {'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), }) self.distance_functions['dwithin'] = (PostGISFunctionParam(prefix, 'DWithin'), dtypes) # Adding the distance functions to the geometries lookup. self.geometry_functions.update(self.distance_functions) # The union aggregate and topology operation use the same signature # in versions 1.3+. if version < (1, 3, 0): UNIONAGG = 'GeomUnion' UNION = 'Union' MAKELINE = False else: UNIONAGG = 'ST_Union' UNION = 'ST_Union' MAKELINE = 'ST_MakeLine' # Only PostGIS versions 1.3.4+ have GeoJSON serialization support. if version < (1, 3, 4): GEOJSON = False else: GEOJSON = prefix + 'AsGeoJson' # ST_ContainsProperly ST_MakeLine, and ST_GeoHash added in 1.4. if version >= (1, 4, 0): GEOHASH = 'ST_GeoHash' BOUNDINGCIRCLE = 'ST_MinimumBoundingCircle' self.geometry_functions['contains_properly'] = PostGISFunction(prefix, 'ContainsProperly') else: GEOHASH, BOUNDINGCIRCLE = False, False # Geography type support added in 1.5. if version >= (1, 5, 0): self.geography = True # Only a subset of the operators and functions are available # for the geography type. self.geography_functions = self.distance_functions.copy() self.geography_functions.update({ 'coveredby' : self.geometry_functions['coveredby'], 'covers' : self.geometry_functions['covers'], 'intersects' : self.geometry_functions['intersects'], }) self.geography_operators = { 'bboverlaps' : PostGISOperator('&&'), } # Creating a dictionary lookup of all GIS terms for PostGIS. gis_terms = ['isnull'] gis_terms += self.geometry_operators.keys() gis_terms += self.geometry_functions.keys() self.gis_terms = dict([(term, None) for term in gis_terms]) self.area = prefix + 'Area' self.bounding_circle = BOUNDINGCIRCLE self.centroid = prefix + 'Centroid' self.collect = prefix + 'Collect' self.difference = prefix + 'Difference' self.distance = prefix + 'Distance' self.distance_sphere = prefix + 'distance_sphere' self.distance_spheroid = prefix + 'distance_spheroid' self.envelope = prefix + 'Envelope' self.extent = prefix + 'Extent' self.extent3d = prefix + 'Extent3D' self.force_rhr = prefix + 'ForceRHR' self.geohash = GEOHASH self.geojson = GEOJSON self.gml = prefix + 'AsGML' self.intersection = prefix + 'Intersection' self.kml = ASKML self.length = prefix + 'Length' self.length3d = prefix + 'Length3D' self.length_spheroid = prefix + 'length_spheroid' self.makeline = MAKELINE self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points =prefix + 'npoints' self.perimeter = prefix + 'Perimeter' self.perimeter3d = prefix + 'Perimeter3D' self.point_on_surface = prefix + 'PointOnSurface' self.polygonize = prefix + 'Polygonize' self.reverse = prefix + 'Reverse' self.scale = prefix + 'Scale' self.snap_to_grid = prefix + 'SnapToGrid' self.svg = prefix + 'AsSVG' self.sym_difference = prefix + 'SymDifference' self.transform = prefix + 'Transform' self.translate = prefix + 'Translate' self.union = UNION self.unionagg = UNIONAGG def check_aggregate_support(self, aggregate): """ Checks if the given aggregate name is supported (that is, if it's in `self.valid_aggregates`). """ agg_name = aggregate.__class__.__name__ return agg_name in self.valid_aggregates def convert_extent(self, box): """ Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)". """ ll, ur = box[4:-1].split(',') xmin, ymin = map(float, ll.split()) xmax, ymax = map(float, ur.split()) return (xmin, ymin, xmax, ymax) def convert_extent3d(self, box3d): """ Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)". """ ll, ur = box3d[6:-1].split(',') xmin, ymin, zmin = map(float, ll.split()) xmax, ymax, zmax = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax) def convert_geom(self, hex, geo_field): """ Converts the geometry returned from PostGIS aggretates. """ if hex: return Geometry(hex) else: return None def geo_db_type(self, f): """ Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead. """ if f.geography: if not self.geography: raise NotImplementedError('PostGIS 1.5 required for geography column support.') if f.srid != 4326: raise NotImplementedError('PostGIS 1.5 supports geography columns ' 'only with an SRID of 4326.') return 'geography(%s,%d)'% (f.geom_type, f.srid) else: return None def get_distance(self, f, dist_val, lookup_type): """ Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what's available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5. """ # Getting the distance parameter and any options. if len(dist_val) == 1: value, option = dist_val[0], None else: value, option = dist_val # Shorthand boolean flags. geodetic = f.geodetic(self.connection) geography = f.geography and self.geography if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if lookup_type == 'dwithin': raise ValueError('Only numeric values of degree units are ' 'allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: # Assuming the distance is in the units of the field. dist_param = value if (not geography and geodetic and lookup_type != 'dwithin' and option == 'spheroid'): # using distance_spheroid requires the spheroid of the field as # a parameter. return [f._spheroid, dist_param] else: return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call. """ if value is None or value.srid == f.srid: placeholder = '%s' else: # Adding Transform() to the SQL placeholder. placeholder = '%s(%%s, %s)' % (self.transform, f.srid) if hasattr(value, 'expression'): # If this is an F expression, then we don't really want # a placeholder and instead substitute in the column # of the expression. placeholder = placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression])) return placeholder def _get_postgis_func(self, func): """ Helper routine for calling PostGIS functions and returning their result. """ cursor = self.connection._cursor() try: try: cursor.execute('SELECT %s()' % func) row = cursor.fetchone() except: # Responsibility of callers to perform error handling. raise finally: # Close out the connection. See #9437. self.connection.close() return row[0] def postgis_geos_version(self): "Returns the version of the GEOS library used with PostGIS." return self._get_postgis_func('postgis_geos_version') def postgis_lib_version(self): "Returns the version number of the PostGIS library used with PostgreSQL." return self._get_postgis_func('postgis_lib_version') def postgis_proj_version(self): "Returns the version of the PROJ.4 library used with PostGIS." return self._get_postgis_func('postgis_proj_version') def postgis_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_version') def postgis_full_version(self): "Returns PostGIS version number and compile-time options." return self._get_postgis_func('postgis_full_version') def postgis_version_tuple(self): """ Returns the PostGIS version as a tuple (version string, major, minor, subminor). """ # Getting the PostGIS version version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse PostGIS version string: %s' % version) return (version, major, minor1, minor2) def proj_version_tuple(self): """ Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers. """ proj_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.') def num_params(self, lookup_type, num_param): """ Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_type != 'dwithin'): return two_to_three(num_param) else: return exactly_two(num_param) def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): """ Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field. """ alias, col, db_type = lvalue # Getting the quoted geometry column. geo_col = '%s.%s' % (qn(alias), qn(col)) if lookup_type in self.geometry_operators: if field.geography and not lookup_type in self.geography_operators: raise ValueError('PostGIS geography does not support the ' '"%s" lookup.' % lookup_type) # Handling a PostGIS operator. op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type in self.geometry_functions: if field.geography and not lookup_type in self.geography_functions: raise ValueError('PostGIS geography type does not support the ' '"%s" lookup.' % lookup_type) # See if a PostGIS geometry function matches the lookup type. tmp = self.geometry_functions[lookup_type] # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # distance lookups. if isinstance(tmp, tuple): # First element of tuple is the PostGISOperation instance, and the # second element is either the type or a tuple of acceptable types # that may passed in as further parameters for the lookup type. op, arg_type = tmp # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, (tuple, list)): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) # Geometry is first element of lookup tuple. geom = value[0] # Number of valid tuple parameters depends on the lookup type. nparams = len(value) if not self.num_params(lookup_type, nparams): raise ValueError('Incorrect number of parameters given for `%s` lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) # For lookup type `relate`, the op instance is not yet created (has # to be instantiated here to check the pattern parameter). if lookup_type == 'relate': op = op(self.geom_func_prefix, value[1]) elif lookup_type in self.distance_functions and lookup_type != 'dwithin': if not field.geography and field.geodetic(self.connection): # Geodetic distances are only availble from Points to # PointFields on PostGIS 1.4 and below. if not self.connection.ops.geography: if field.geom_type != 'POINT': raise ValueError('PostGIS spherical operations are only valid on PointFields.') if str(geom.geom_type) != 'Point': raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') # Setting up the geodetic operation appropriately. if nparams == 3 and value[2] == 'spheroid': op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value # Calling the `as_sql` function on the operation instance. return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or '')) raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__ if not self.check_aggregate_support(agg): raise NotImplementedError('%s spatial aggregate is not implmented for this backend.' % agg_name) agg_name = agg_name.lower() if agg_name == 'union': agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.postgis.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.postgis.models import SpatialRefSys return SpatialRefSys
[ [ 1, 0, 0.0017, 0.0017, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0034, 0.0017, 0, 0.66, 0.0556, 349, 0, 1, 0, 0, 349, 0, 0 ], [ 1, 0, 0.0068, 0.0017, 0, ...
[ "import re", "from decimal import Decimal", "from django.conf import settings", "from django.contrib.gis.db.backends.base import BaseSpatialOperations", "from django.contrib.gis.db.backends.util import SpatialOperation, SpatialFunction", "from django.contrib.gis.db.backends.postgis.adapter import PostGISA...
from django.conf import settings from django.db.backends.postgresql.creation import DatabaseCreation class PostGISCreation(DatabaseCreation): geom_index_type = 'GIST' geom_index_opts = 'GIST_GEOMETRY_OPS' def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table if f.geography: # Geogrophy columns are created normally. pass else: # Geometry columns are created by `AddGeometryColumn` # stored procedure. output.append(style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn') + '(' + style.SQL_TABLE(gqn(db_table)) + ', ' + style.SQL_FIELD(gqn(f.column)) + ', ' + style.SQL_FIELD(str(f.srid)) + ', ' + style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' + style.SQL_KEYWORD(str(f.dim)) + ');') if not f.null: # Add a NOT NULL constraint to the field output.append(style.SQL_KEYWORD('ALTER TABLE ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' ALTER ') + style.SQL_FIELD(qn(f.column)) + style.SQL_KEYWORD(' SET NOT NULL') + ';') if f.spatial_index: # Spatial indexes created the same way for both Geometry and # Geography columns if f.geography: index_opts = '' else: index_opts = ' ' + style.SQL_KEYWORD(self.geom_index_opts) output.append(style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' USING ') + style.SQL_COLTYPE(self.geom_index_type) + ' ( ' + style.SQL_FIELD(qn(f.column)) + index_opts + ' );') return output def sql_table_creation_suffix(self): qn = self.connection.ops.quote_name return ' TEMPLATE %s' % qn(getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis'))
[ [ 1, 0, 0.0167, 0.0167, 0, 0.66, 0, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0333, 0.0167, 0, 0.66, 0.5, 575, 0, 1, 0, 0, 575, 0, 0 ], [ 3, 0, 0.5333, 0.95, 0, 0.66,...
[ "from django.conf import settings", "from django.db.backends.postgresql.creation import DatabaseCreation", "class PostGISCreation(DatabaseCreation):\n geom_index_type = 'GIST'\n geom_index_opts = 'GIST_GEOMETRY_OPS'\n\n def sql_indexes_for_field(self, model, f, style):\n \"Return any spatial ind...
from django.db.backends.postgresql_psycopg2.base import * from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops = PostGISOperations(self) self.introspection = PostGISIntrospection(self)
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 485, 0, 1, 0, 0, 485, 0, 0 ], [ 1, 0, 0.1667, 0.0833, 0, 0.66, 0.2, 485, 0, 1, 0, 0, 485, 0, 0 ], [ 1, 0, 0.25, 0.0833, 0, 0.66,...
[ "from django.db.backends.postgresql_psycopg2.base import *", "from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper", "from django.contrib.gis.db.backends.postgis.creation import PostGISCreation", "from django.contrib.gis.db.backends.postgis.introspection import Po...
""" A collection of utility routines and classes used by the spatial backends. """ def gqn(val): """ The geographic quote name function; used for quoting tables and geometries (they use single rather than the double quotes of the backend quotename function). """ if isinstance(val, basestring): if isinstance(val, unicode): val = val.encode('ascii') return "'%s'" % val else: return str(val) class SpatialOperation(object): """ Base class for generating spatial SQL. """ sql_template = '%(geo_col)s %(operator)s %(geometry)s' def __init__(self, function='', operator='', result='', **kwargs): self.function = function self.operator = operator self.result = result self.extra = kwargs def as_sql(self, geo_col, geometry='%s'): return self.sql_template % self.params(geo_col, geometry) def params(self, geo_col, geometry): params = {'function' : self.function, 'geo_col' : geo_col, 'geometry' : geometry, 'operator' : self.operator, 'result' : self.result, } params.update(self.extra) return params class SpatialFunction(SpatialOperation): """ Base class for generating spatial SQL related to a function. """ sql_template = '%(function)s(%(geo_col)s, %(geometry)s)' def __init__(self, func, result='', operator='', **kwargs): # Getting the function prefix. default = {'function' : func, 'operator' : operator, 'result' : result } kwargs.update(default) super(SpatialFunction, self).__init__(**kwargs)
[ [ 8, 0, 0.0446, 0.0714, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0.1964, 0.1964, 0, 0.66, 0.3333, 613, 0, 1, 1, 0, 0, 0, 4 ], [ 8, 1, 0.1607, 0.0893, 1, 0.62, ...
[ "\"\"\"\nA collection of utility routines and classes used by the spatial\nbackends.\n\"\"\"", "def gqn(val):\n \"\"\"\n The geographic quote name function; used for quoting tables and\n geometries (they use single rather than the double quotes of the\n backend quotename function).\n \"\"\"\n if...
from django.contrib.gis.db.models.sql.compiler import GeoSQLCompiler as BaseGeoSQLCompiler from django.db.backends.oracle import compiler SQLCompiler = compiler.SQLCompiler class GeoSQLCompiler(BaseGeoSQLCompiler, SQLCompiler): pass class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQLCompiler): def placeholder(self, field, val): if field is None: # A field value of None means the value is raw. return val elif hasattr(field, 'get_placeholder'): # Some fields (e.g. geo fields) need special munging before # they can be inserted. ph = field.get_placeholder(val, self.connection) if ph == 'NULL': # If the placeholder returned is 'NULL', then we need to # to remove None from the Query parameters. Specifically, # cx_Oracle will assume a CHAR type when a placeholder ('%s') # is used for columns of MDSYS.SDO_GEOMETRY. Thus, we use # 'NULL' for the value, and remove None from the query params. # See also #10888. param_idx = self.query.columns.index(field.column) params = list(self.query.params) params.pop(param_idx) self.query.params = tuple(params) return ph else: # Return the common case for the placeholder return '%s' class SQLDeleteCompiler(compiler.SQLDeleteCompiler, GeoSQLCompiler): pass class SQLUpdateCompiler(compiler.SQLUpdateCompiler, GeoSQLCompiler): pass class SQLAggregateCompiler(compiler.SQLAggregateCompiler, GeoSQLCompiler): pass class SQLDateCompiler(compiler.SQLDateCompiler, GeoSQLCompiler): pass
[ [ 1, 0, 0.0227, 0.0227, 0, 0.66, 0, 973, 0, 1, 0, 0, 973, 0, 0 ], [ 1, 0, 0.0455, 0.0227, 0, 0.66, 0.125, 772, 0, 1, 0, 0, 772, 0, 0 ], [ 14, 0, 0.0909, 0.0227, 0, ...
[ "from django.contrib.gis.db.models.sql.compiler import GeoSQLCompiler as BaseGeoSQLCompiler", "from django.db.backends.oracle import compiler", "SQLCompiler = compiler.SQLCompiler", "class GeoSQLCompiler(BaseGeoSQLCompiler, SQLCompiler):\n pass", "class SQLInsertCompiler(compiler.SQLInsertCompiler, GeoSQ...
from cx_Oracle import CLOB from django.contrib.gis.db.backends.adapter import WKTAdapter class OracleSpatialAdapter(WKTAdapter): input_size = CLOB
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 554, 0, 1, 0, 0, 554, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.5, 423, 0, 1, 0, 0, 423, 0, 0 ], [ 3, 0, 0.9, 0.4, 0, 0.66, 1, 930,...
[ "from cx_Oracle import CLOB", "from django.contrib.gis.db.backends.adapter import WKTAdapter", "class OracleSpatialAdapter(WKTAdapter):\n input_size = CLOB", " input_size = CLOB" ]
""" The GeometryColumns and SpatialRefSys models for the Oracle spatial backend. It should be noted that Oracle Spatial does not have database tables named according to the OGC standard, so the closest analogs are used. For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns model and the `SDO_COORD_REF_SYS` is used for the SpatialRefSys model. """ from django.contrib.gis.db import models from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.backends.base import SpatialRefSysMixin class GeometryColumns(models.Model): "Maps to the Oracle USER_SDO_GEOM_METADATA table." table_name = models.CharField(max_length=32) column_name = models.CharField(max_length=1024) srid = models.IntegerField(primary_key=True) # TODO: Add support for `diminfo` column (type MDSYS.SDO_DIM_ARRAY). class Meta: db_table = 'USER_SDO_GEOM_METADATA' managed = False @classmethod def table_name_col(cls): """ Returns the name of the metadata column used to store the the feature table name. """ return 'table_name' @classmethod def geom_col_name(cls): """ Returns the name of the metadata column used to store the the feature geometry column. """ return 'column_name' def __unicode__(self): return '%s - %s (SRID: %s)' % (self.table_name, self.column_name, self.srid) class SpatialRefSys(models.Model, SpatialRefSysMixin): "Maps to the Oracle MDSYS.CS_SRS table." cs_name = models.CharField(max_length=68) srid = models.IntegerField(primary_key=True) auth_srid = models.IntegerField() auth_name = models.CharField(max_length=256) wktext = models.CharField(max_length=2046) # Optional geometry representing the bounds of this coordinate # system. By default, all are NULL in the table. cs_bounds = models.PolygonField(null=True) objects = models.GeoManager() class Meta: db_table = 'CS_SRS' managed = False @property def wkt(self): return self.wktext @classmethod def wkt_col(cls): return 'wktext'
[ [ 8, 0, 0.0769, 0.1385, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1538, 0.0154, 0, 0.66, 0.2, 964, 0, 1, 0, 0, 964, 0, 0 ], [ 1, 0, 0.1692, 0.0154, 0, 0.66, ...
[ "\"\"\"\n The GeometryColumns and SpatialRefSys models for the Oracle spatial\n backend.\n\n It should be noted that Oracle Spatial does not have database tables\n named according to the OGC standard, so the closest analogs are used.\n For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns\n mode...
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use the WKT constructors. """ import re from decimal import Decimal from django.db.backends.oracle.base import DatabaseOperations from django.contrib.gis.db.backends.base import BaseSpatialOperations from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter from django.contrib.gis.db.backends.util import SpatialFunction from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance class SDOOperation(SpatialFunction): "Base class for SDO* Oracle operations." sql_template = "%(function)s(%(geo_col)s, %(geometry)s) %(operator)s '%(result)s'" def __init__(self, func, **kwargs): kwargs.setdefault('operator', '=') kwargs.setdefault('result', 'TRUE') super(SDOOperation, self).__init__(func, **kwargs) class SDODistance(SpatialFunction): "Class for Distance queries." sql_template = ('%(function)s(%(geo_col)s, %(geometry)s, %(tolerance)s) ' '%(operator)s %(result)s') dist_func = 'SDO_GEOM.SDO_DISTANCE' def __init__(self, op, tolerance=0.05): super(SDODistance, self).__init__(self.dist_func, tolerance=tolerance, operator=op, result='%s') class SDODWithin(SpatialFunction): dwithin_func = 'SDO_WITHIN_DISTANCE' sql_template = "%(function)s(%(geo_col)s, %(geometry)s, %%s) = 'TRUE'" def __init__(self): super(SDODWithin, self).__init__(self.dwithin_func) class SDOGeomRelate(SpatialFunction): "Class for using SDO_GEOM.RELATE." relate_func = 'SDO_GEOM.RELATE' sql_template = ("%(function)s(%(geo_col)s, '%(mask)s', %(geometry)s, " "%(tolerance)s) %(operator)s '%(mask)s'") def __init__(self, mask, tolerance=0.05): # SDO_GEOM.RELATE(...) has a peculiar argument order: column, mask, geom, tolerance. # Moreover, the runction result is the mask (e.g., 'DISJOINT' instead of 'TRUE'). super(SDOGeomRelate, self).__init__(self.relate_func, operator='=', mask=mask, tolerance=tolerance) class SDORelate(SpatialFunction): "Class for using SDO_RELATE." masks = 'TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|CONTAINS|COVERS|ANYINTERACT|ON' mask_regex = re.compile(r'^(%s)(\+(%s))*$' % (masks, masks), re.I) sql_template = "%(function)s(%(geo_col)s, %(geometry)s, 'mask=%(mask)s') = 'TRUE'" relate_func = 'SDO_RELATE' def __init__(self, mask): if not self.mask_regex.match(mask): raise ValueError('Invalid %s mask: "%s"' % (self.relate_func, mask)) super(SDORelate, self).__init__(self.relate_func, mask=mask) # Valid distance types and substitutions dtypes = (Decimal, Distance, float, int, long) class OracleOperations(DatabaseOperations, BaseSpatialOperations): compiler_module = "django.contrib.gis.db.backends.oracle.compiler" name = 'oracle' oracle = True valid_aggregates = dict([(a, None) for a in ('Union', 'Extent')]) Adapter = OracleSpatialAdapter Adaptor = Adapter # Backwards-compatibility alias. area = 'SDO_GEOM.SDO_AREA' gml= 'SDO_UTIL.TO_GMLGEOMETRY' centroid = 'SDO_GEOM.SDO_CENTROID' difference = 'SDO_GEOM.SDO_DIFFERENCE' distance = 'SDO_GEOM.SDO_DISTANCE' extent= 'SDO_AGGR_MBR' intersection= 'SDO_GEOM.SDO_INTERSECTION' length = 'SDO_GEOM.SDO_LENGTH' num_geom = 'SDO_UTIL.GETNUMELEM' num_points = 'SDO_UTIL.GETNUMVERTICES' perimeter = length point_on_surface = 'SDO_GEOM.SDO_POINTONSURFACE' reverse = 'SDO_UTIL.REVERSE_LINESTRING' sym_difference = 'SDO_GEOM.SDO_XOR' transform = 'SDO_CS.TRANSFORM' union = 'SDO_GEOM.SDO_UNION' unionagg = 'SDO_AGGR_UNION' # We want to get SDO Geometries as WKT because it is much easier to # instantiate GEOS proxies from WKT than SDO_GEOMETRY(...) strings. # However, this adversely affects performance (i.e., Java is called # to convert to WKT on every query). If someone wishes to write a # SDO_GEOMETRY(...) parser in Python, let me know =) select = 'SDO_UTIL.TO_WKTGEOMETRY(%s)' distance_functions = { 'distance_gt' : (SDODistance('>'), dtypes), 'distance_gte' : (SDODistance('>='), dtypes), 'distance_lt' : (SDODistance('<'), dtypes), 'distance_lte' : (SDODistance('<='), dtypes), 'dwithin' : (SDODWithin(), dtypes), } geometry_functions = { 'contains' : SDOOperation('SDO_CONTAINS'), 'coveredby' : SDOOperation('SDO_COVEREDBY'), 'covers' : SDOOperation('SDO_COVERS'), 'disjoint' : SDOGeomRelate('DISJOINT'), 'intersects' : SDOOperation('SDO_OVERLAPBDYINTERSECT'), # TODO: Is this really the same as ST_Intersects()? 'equals' : SDOOperation('SDO_EQUAL'), 'exact' : SDOOperation('SDO_EQUAL'), 'overlaps' : SDOOperation('SDO_OVERLAPS'), 'same_as' : SDOOperation('SDO_EQUAL'), 'relate' : (SDORelate, basestring), # Oracle uses a different syntax, e.g., 'mask=inside+touch' 'touches' : SDOOperation('SDO_TOUCH'), 'within' : SDOOperation('SDO_INSIDE'), } geometry_functions.update(distance_functions) gis_terms = ['isnull'] gis_terms += geometry_functions.keys() gis_terms = dict([(term, None) for term in gis_terms]) truncate_params = {'relate' : None} def __init__(self, connection): super(OracleOperations, self).__init__() self.connection = connection def convert_extent(self, clob): if clob: # Generally, Oracle returns a polygon for the extent -- however, # it can return a single point if there's only one Point in the # table. ext_geom = Geometry(clob.read()) gtype = str(ext_geom.geom_type) if gtype == 'Polygon': # Construct the 4-tuple from the coordinates in the polygon. shell = ext_geom.shell ll, ur = shell[0][:2], shell[2][:2] elif gtype == 'Point': ll = ext_geom.coords[:2] ur = ll else: raise Exception('Unexpected geometry type returned for extent: %s' % gtype) xmin, ymin = ll xmax, ymax = ur return (xmin, ymin, xmax, ymax) else: return None def convert_geom(self, clob, geo_field): if clob: return Geometry(clob.read(), geo_field.srid) else: return None def geo_db_type(self, f): """ Returns the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it's the same for all geometry types. """ return 'MDSYS.SDO_GEOMETRY' def get_distance(self, f, value, lookup_type): """ Returns the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value # dwithin lookups on oracle require a special string parameter # that starts with "distance=". if lookup_type == 'dwithin': dist_param = 'distance=%s' % dist_param return [dist_param] def get_geom_placeholder(self, f, value): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the SDO_CS.TRANSFORM() function call. """ if value is None: return 'NULL' def transform_value(val, srid): return val.srid != srid if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = '%s(%%s, %s)' % (self.transform, f.srid) else: placeholder = '%s' # No geometry value used for F expression, substitue in # the column name instead. return placeholder % '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression])) else: if transform_value(value, f.srid): return '%s(SDO_GEOMETRY(%%s, %s), %s)' % (self.transform, value.srid, f.srid) else: return 'SDO_GEOMETRY(%%s, %s)' % f.srid def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn): "Returns the SQL WHERE clause for use in Oracle spatial SQL construction." alias, col, db_type = lvalue # Getting the quoted table name as `geo_col`. geo_col = '%s.%s' % (qn(alias), qn(col)) # See if a Oracle Geometry function matches the lookup type next lookup_info = self.geometry_functions.get(lookup_type, False) if lookup_info: # Lookup types that are tuples take tuple arguments, e.g., 'relate' and # 'dwithin' lookup types. if isinstance(lookup_info, tuple): # First element of tuple is lookup type, second element is the type # of the expected argument (e.g., str, float) sdo_op, arg_type = lookup_info geom = value[0] # Ensuring that a tuple _value_ was passed in from the user if not isinstance(value, tuple): raise ValueError('Tuple required for `%s` lookup type.' % lookup_type) if len(value) != 2: raise ValueError('2-element tuple required for %s lookup type.' % lookup_type) # Ensuring the argument type matches what we expect. if not isinstance(value[1], arg_type): raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1]))) if lookup_type == 'relate': # The SDORelate class handles construction for these queries, # and verifies the mask argument. return sdo_op(value[1]).as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: # Otherwise, just call the `as_sql` method on the SDOOperation instance. return sdo_op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: # Lookup info is a SDOOperation instance, whose `as_sql` method returns # the SQL necessary for the geometry function call. For example: # SDO_CONTAINS("geoapp_country"."poly", SDO_GEOMTRY('POINT(5 23)', 4326)) = 'TRUE' return lookup_info.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif lookup_type == 'isnull': # Handling 'isnull' lookup type return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or '')) raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) def spatial_aggregate_sql(self, agg): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = agg.__class__.__name__.lower() if agg_name == 'union' : agg_name += 'agg' if agg.is_extent: sql_template = '%(function)s(%(field)s)' else: sql_template = '%(function)s(SDOAGGRTYPE(%(field)s,%(tolerance)s))' sql_function = getattr(self, agg_name) return self.select % sql_template, sql_function # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.oracle.models import GeometryColumns return GeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.oracle.models import SpatialRefSys return SpatialRefSys
[ [ 8, 0, 0.0171, 0.0307, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0341, 0.0034, 0, 0.66, 0.0667, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 1, 0, 0.0375, 0.0034, 0, 0.66...
[ "\"\"\"\n This module contains the spatial lookup types, and the `get_geo_where_clause`\n routine for Oracle Spatial.\n\n Please note that WKT support is broken on the XE version, and thus\n this backend will not work on such platforms. Specifically, XE lacks\n support for an internal JVM, and Java libraries are r...
from django.db.backends.oracle.creation import DatabaseCreation from django.db.backends.util import truncate_name class OracleCreation(DatabaseCreation): def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(OracleCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table output.append(style.SQL_KEYWORD('INSERT INTO ') + style.SQL_TABLE('USER_SDO_GEOM_METADATA') + ' (%s, %s, %s, %s)\n ' % tuple(map(qn, ['TABLE_NAME', 'COLUMN_NAME', 'DIMINFO', 'SRID'])) + style.SQL_KEYWORD(' VALUES ') + '(\n ' + style.SQL_TABLE(gqn(db_table)) + ',\n ' + style.SQL_FIELD(gqn(f.column)) + ',\n ' + style.SQL_KEYWORD("MDSYS.SDO_DIM_ARRAY") + '(\n ' + style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + ("('LONG', %s, %s, %s),\n " % (f._extent[0], f._extent[2], f._tolerance)) + style.SQL_KEYWORD("MDSYS.SDO_DIM_ELEMENT") + ("('LAT', %s, %s, %s)\n ),\n" % (f._extent[1], f._extent[3], f._tolerance)) + ' %s\n );' % f.srid) if f.spatial_index: # Getting the index name, Oracle doesn't allow object # names > 30 characters. idx_name = truncate_name('%s_%s_id' % (db_table, f.column), 30) output.append(style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn(idx_name)) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + '(' + style.SQL_FIELD(qn(f.column)) + ') ' + style.SQL_KEYWORD('INDEXTYPE IS ') + style.SQL_TABLE('MDSYS.SPATIAL_INDEX') + ';') return output
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 513, 0, 1, 0, 0, 513, 0, 0 ], [ 1, 0, 0.0476, 0.0238, 0, 0.66, 0.5, 446, 0, 1, 0, 0, 446, 0, 0 ], [ 3, 0, 0.5476, 0.9286, 0, 0.6...
[ "from django.db.backends.oracle.creation import DatabaseCreation", "from django.db.backends.util import truncate_name", "class OracleCreation(DatabaseCreation):\n\n def sql_indexes_for_field(self, model, f, style):\n \"Return any spatial index creation SQL for the field.\"\n from django.contrib...
from django.db.backends.oracle.base import * from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper from django.contrib.gis.db.backends.oracle.creation import OracleCreation from django.contrib.gis.db.backends.oracle.introspection import OracleIntrospection from django.contrib.gis.db.backends.oracle.operations import OracleOperations class DatabaseWrapper(OracleDatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.ops = OracleOperations(self) self.creation = OracleCreation(self) self.introspection = OracleIntrospection(self)
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 759, 0, 1, 0, 0, 759, 0, 0 ], [ 1, 0, 0.1667, 0.0833, 0, 0.66, 0.2, 759, 0, 1, 0, 0, 759, 0, 0 ], [ 1, 0, 0.25, 0.0833, 0, 0.66,...
[ "from django.db.backends.oracle.base import *", "from django.db.backends.oracle.base import DatabaseWrapper as OracleDatabaseWrapper", "from django.contrib.gis.db.backends.oracle.creation import OracleCreation", "from django.contrib.gis.db.backends.oracle.introspection import OracleIntrospection", "from dja...
""" Set of "markup" template filters for Django. These filters transform plain text markup syntaxes to HTML; currently there is support for: * Textile, which requires the PyTextile library available at http://loopcore.com/python-textile/ * Markdown, which requires the Python-markdown library from http://www.freewisdom.org/projects/python-markdown * reStructuredText, which requires docutils from http://docutils.sf.net/ """ from django import template from django.conf import settings from django.utils.encoding import smart_str, force_unicode from django.utils.safestring import mark_safe register = template.Library() def textile(value): try: import textile except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.") return force_unicode(value) else: return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))) textile.is_safe = True def markdown(value, arg=''): """ Runs Markdown over a given value, optionally using various extensions python-markdown supports. Syntax:: {{ value|markdown:"extension1_name,extension2_name..." }} To enable safe mode, which strips raw HTML and only returns HTML generated by actual Markdown syntax, pass "safe" as the first extension in the list. If the version of Markdown in use does not support extensions, they will be silently ignored. """ try: import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.") return force_unicode(value) else: # markdown.version was first added in 1.6b. The only version of markdown # to fully support extensions before 1.6b was the shortlived 1.6a. if hasattr(markdown, 'version'): extensions = [e for e in arg.split(",") if e] if len(extensions) > 0 and extensions[0] == "safe": extensions = extensions[1:] safe_mode = True else: safe_mode = False # Unicode support only in markdown v1.7 or above. Version_info # exist only in markdown v1.6.2rc-2 or above. if getattr(markdown, "version_info", None) < (1,7): return mark_safe(force_unicode(markdown.markdown(smart_str(value), extensions, safe_mode=safe_mode))) else: return mark_safe(markdown.markdown(force_unicode(value), extensions, safe_mode=safe_mode)) else: return mark_safe(force_unicode(markdown.markdown(smart_str(value)))) markdown.is_safe = True def restructuredtext(value): try: from docutils.core import publish_parts except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.") return force_unicode(value) else: docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {}) parts = publish_parts(source=smart_str(value), writer_name="html4css1", settings_overrides=docutils_settings) return mark_safe(force_unicode(parts["fragment"])) restructuredtext.is_safe = True register.filter(textile) register.filter(markdown) register.filter(restructuredtext)
[ [ 8, 0, 0.0714, 0.1319, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.1538, 0.011, 0, 0.66, 0.0714, 294, 0, 1, 0, 0, 294, 0, 0 ], [ 1, 0, 0.1648, 0.011, 0, 0.66, ...
[ "\"\"\"\nSet of \"markup\" template filters for Django. These filters transform plain text\nmarkup syntaxes to HTML; currently there is support for:\n\n * Textile, which requires the PyTextile library available at\n http://loopcore.com/python-textile/\n\n * Markdown, which requires the Python-markdown l...
import base64 import cPickle as pickle from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils.hashcompat import md5_constructor class SessionManager(models.Manager): def encode(self, session_dict): """ Returns the given session dictionary pickled and encoded as a string. """ pickled = pickle.dumps(session_dict) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) def save(self, session_key, session_dict, expire_date): s = self.model(session_key, self.encode(session_dict), expire_date) if session_dict: s.save() else: s.delete() # Clear sessions with no data. return s class Session(models.Model): """ Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID -- not the data itself. The Django sessions framework is entirely cookie-based. It does not fall back to putting session IDs in URLs. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the "Referer" header. For complete documentation on using Sessions in your code, consult the sessions documentation that is shipped with Django (also available on the Django Web site). """ session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) objects = SessionManager() class Meta: db_table = 'django_session' verbose_name = _('session') verbose_name_plural = _('sessions') def get_decoded(self): encoded_data = base64.decodestring(self.session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: from django.core.exceptions import SuspiciousOperation raise SuspiciousOperation("User tampered with session cookie.") try: return pickle.loads(pickled) # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). except: return {}
[ [ 1, 0, 0.0149, 0.0149, 0, 0.66, 0, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.0299, 0.0149, 0, 0.66, 0.1429, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 1, 0, 0.0597, 0.0149, 0, ...
[ "import base64", "import cPickle as pickle", "from django.db import models", "from django.utils.translation import ugettext_lazy as _", "from django.conf import settings", "from django.utils.hashcompat import md5_constructor", "class SessionManager(models.Manager):\n def encode(self, session_dict):\n...
import base64 from datetime import datetime, timedelta import pickle import shutil import tempfile from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import SessionStore as CacheDBSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.backends.base import SessionBase from django.contrib.sessions.models import Session from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.utils import unittest from django.utils.hashcompat import md5_constructor class SessionTestsMixin(object): # This does not inherit from TestCase to avoid any tests being run with this # class, which wouldn't work, and to allow different TestCase subclasses to # be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() def tearDown(self): # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.session.delete() def test_new_session(self): self.assertFalse(self.session.modified) self.assertFalse(self.session.accessed) def test_get_empty(self): self.assertEqual(self.session.get('cat'), None) def test_store(self): self.session['cat'] = "dog" self.assertTrue(self.session.modified) self.assertEqual(self.session.pop('cat'), 'dog') def test_pop(self): self.session['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('some key'), None) def test_pop_default(self): self.assertEqual(self.session.pop('some key', 'does not exist'), 'does not exist') self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_update(self): self.session.update({'update key': 1}) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get('update key', None), 1) def test_has_key(self): self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertTrue(self.session.has_key('some key')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_values(self): self.assertEqual(self.session.values(), []) self.assertTrue(self.session.accessed) self.session['some key'] = 1 self.assertEqual(self.session.values(), [1]) def test_iterkeys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.iterkeys() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), ['x']) def test_iterkeys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.itervalues() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [1]) def test_iteritems(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False i = self.session.iteritems() self.assertTrue(hasattr(i, '__iter__')) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), [('x',1)]) def test_clear(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(self.session.items(), [('x',1)]) self.session.clear() self.assertEqual(self.session.items(), []) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_save(self): self.session.save() self.assertTrue(self.session.exists(self.session.session_key)) def test_delete(self): self.session.delete(self.session.session_key) self.assertFalse(self.session.exists(self.session.session_key)) def test_flush(self): self.session['foo'] = 'bar' self.session.save() prev_key = self.session.session_key self.session.flush() self.assertFalse(self.session.exists(prev_key)) self.assertNotEqual(self.session.session_key, prev_key) self.assertTrue(self.session.modified) self.assertTrue(self.session.accessed) def test_cycle(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_key = self.session.session_key prev_data = self.session.items() self.session.cycle_key() self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(self.session.items(), prev_data) def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. session = self.backend('1') session.save() self.assertNotEqual(session.session_key, '1') self.assertEqual(session.get('cat'), None) session.delete() # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_custom_expiry_seconds(self): # Using seconds self.session.set_expiry(10) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_timedelta(self): # Using timedelta self.session.set_expiry(timedelta(seconds=10)) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_timedelta(self): # Using timedelta self.session.set_expiry(datetime.now() + timedelta(seconds=10)) delta = self.session.get_expiry_date() - datetime.now() self.assertTrue(delta.seconds in (9, 10)) age = self.session.get_expiry_age() self.assertTrue(age in (9, 10)) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls try: try: original_expire_at_browser_close = settings.SESSION_EXPIRE_AT_BROWSER_CLOSE settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertFalse(self.session.get_expire_at_browser_close()) settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True self.session.set_expiry(10) self.assertFalse(self.session.get_expire_at_browser_close()) self.session.set_expiry(0) self.assertTrue(self.session.get_expire_at_browser_close()) self.session.set_expiry(None) self.assertTrue(self.session.get_expire_at_browser_close()) except: raise finally: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = original_expire_at_browser_close def test_decode(self): # Ensure we can decode what we encode data = {'a test key': 'a test value'} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_django12(self): # Ensure we can decode values encoded using Django 1.2 # Hard code the Django 1.2 method here: def encode(session_dict): pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) pickled_md5 = md5_constructor(pickled + settings.SECRET_KEY).hexdigest() return base64.encodestring(pickled + pickled_md5) data = {'a test key': 'a test value'} encoded = encode(data) self.assertEqual(self.session.decode(encoded), data) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class FileSessionTests(SessionTestsMixin, unittest.TestCase): backend = FileSession def setUp(self): super(FileSessionTests, self).setUp() # Do file session tests in an isolated directory, and kill it after we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() def tearDown(self): settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) super(FileSessionTests, self).tearDown() def test_configuration_check(self): # Make sure the file backend checks for a good storage dir settings.SESSION_FILE_PATH = "/if/this/directory/exists/you/have/a/weird/computer" self.assertRaises(ImproperlyConfigured, self.backend) class CacheSessionTests(SessionTestsMixin, unittest.TestCase): backend = CacheSession
[ [ 1, 0, 0.0034, 0.0034, 0, 0.66, 0, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.0068, 0.0034, 0, 0.66, 0.05, 426, 0, 2, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0102, 0.0034, 0, 0....
[ "import base64", "from datetime import datetime, timedelta", "import pickle", "import shutil", "import tempfile", "from django.conf import settings", "from django.contrib.sessions.backends.db import SessionStore as DatabaseSession", "from django.contrib.sessions.backends.cache import SessionStore as C...
import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date from django.utils.importlib import import_module class SessionMiddleware(object): def process_request(self, request): engine = import_module(settings.SESSION_ENGINE) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) request.session = engine.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. request.session.save() response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None) return response
[ [ 1, 0, 0.0238, 0.0238, 0, 0.66, 0, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0714, 0.0238, 0, 0.66, 0.2, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0952, 0.0238, 0, 0.6...
[ "import time", "from django.conf import settings", "from django.utils.cache import patch_vary_headers", "from django.utils.http import cookie_date", "from django.utils.importlib import import_module", "class SessionMiddleware(object):\n def process_request(self, request):\n engine = import_modul...
import datetime from django.conf import settings from django.contrib.sessions.models import Session from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation from django.db import IntegrityError, transaction, router from django.utils.encoding import force_unicode class SessionStore(SessionBase): """ Implements database session store. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): try: s = Session.objects.get( session_key = self.session_key, expire_date__gt=datetime.datetime.now() ) return self.decode(force_unicode(s.session_data)) except (Session.DoesNotExist, SuspiciousOperation): self.create() return {} def exists(self, session_key): try: Session.objects.get(session_key=session_key) except Session.DoesNotExist: return False return True def create(self): while True: self.session_key = self._get_new_session_key() try: # Save immediately to ensure we have a unique entry in the # database. self.save(must_create=True) except CreateError: # Key wasn't unique. Try again. continue self.modified = True self._session_cache = {} return def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key = self.session_key, session_data = self.encode(self._get_session(no_load=must_create)), expire_date = self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) sid = transaction.savepoint(using=using) try: obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: transaction.savepoint_rollback(sid, using=using) raise CreateError raise def delete(self, session_key=None): if session_key is None: if self._session_key is None: return session_key = self._session_key try: Session.objects.get(session_key=session_key).delete() except Session.DoesNotExist: pass
[ [ 1, 0, 0.0128, 0.0128, 0, 0.66, 0, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0256, 0.0128, 0, 0.66, 0.1429, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.0385, 0.0128, 0, ...
[ "import datetime", "from django.conf import settings", "from django.contrib.sessions.models import Session", "from django.contrib.sessions.backends.base import SessionBase, CreateError", "from django.core.exceptions import SuspiciousOperation", "from django.db import IntegrityError, transaction, router", ...
import base64 import os import random import sys import time from datetime import datetime, timedelta try: import cPickle as pickle except ImportError: import pickle from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.utils.hashcompat import md5_constructor from django.utils.crypto import constant_time_compare, salted_hmac # Use the system (hardware-based) random number generator if it exists. if hasattr(random, 'SystemRandom'): randrange = random.SystemRandom().randrange else: randrange = random.randrange MAX_SESSION_KEY = 18446744073709551616L # 2 << 63 class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class SessionBase(object): """ Base class for all Session classes. """ TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, *args): self.modified = self.modified or key in self._session return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def _hash(self, value): key_salt = "django.contrib.sessions" + self.__class__.__name__ return salted_hmac(key_salt, value).hexdigest() def encode(self, session_dict): "Returns the given session dictionary pickled and encoded as a string." pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) hash = self._hash(pickled) return base64.encodestring(hash + ":" + pickled) def decode(self, session_data): encoded_data = base64.decodestring(session_data) try: # could produce ValueError if there is no ':' hash, pickled = encoded_data.split(':', 1) expected_hash = self._hash(pickled) if not constant_time_compare(hash, expected_hash): raise SuspiciousOperation("Session data corrupted") else: return pickle.loads(pickled) except Exception: # ValueError, SuspiciousOperation, unpickling exceptions # Fall back to Django 1.2 method # PendingDeprecationWarning <- here to remind us to # remove this fallback in Django 1.5 try: return self._decode_old(session_data) except Exception: # Unpickling can cause a variety of exceptions. If something happens, # just return an empty dictionary (an empty session). return {} def _decode_old(self, session_data): encoded_data = base64.decodestring(session_data) pickled, tamper_check = encoded_data[:-32], encoded_data[-32:] if not constant_time_compare(md5_constructor(pickled + settings.SECRET_KEY).hexdigest(), tamper_check): raise SuspiciousOperation("User tampered with session cookie.") return pickle.loads(pickled) def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return self._session.has_key(key) def values(self): return self._session.values() def iterkeys(self): return self._session.iterkeys() def itervalues(self): return self._session.itervalues() def iteritems(self): return self._session.iteritems() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def _get_new_session_key(self): "Returns session key that isn't being used." # The random module is seeded when this Apache child is created. # Use settings.SECRET_KEY as added salt. try: pid = os.getpid() except AttributeError: # No getpid() in Jython, for example pid = 1 while 1: session_key = md5_constructor("%s%s%s%s" % (randrange(0, MAX_SESSION_KEY), pid, time.time(), settings.SECRET_KEY)).hexdigest() if not self.exists(session_key): break return session_key def _get_session_key(self): if self._session_key: return self._session_key else: self._session_key = self._get_new_session_key() return self._session_key def _set_session_key(self, session_key): self._session_key = session_key session_key = property(_get_session_key, _set_session_key) def _get_session(self, no_load=False): """ Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self._session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_expiry_age(self): """Get the number of seconds until the session expires.""" expiry = self.get('_session_expiry') if not expiry: # Checks both None and 0 cases return settings.SESSION_COOKIE_AGE if not isinstance(expiry, datetime): return expiry delta = expiry - datetime.now() return delta.days * 86400 + delta.seconds def get_expiry_date(self): """Get session the expiry date (as a datetime object).""" expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if not expiry: # Checks both None and 0 cases expiry = settings.SESSION_COOKIE_AGE return datetime.now() + timedelta(seconds=expiry) def set_expiry(self, value): """ Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = datetime.now() + value self['_session_expiry'] = value def get_expire_at_browser_close(self): """ Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if self.get('_session_expiry') is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return self.get('_session_expiry') == 0 def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete() self.create() def cycle_key(self): """ Creates a new session key, whilst retaining the current session data. """ data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Returns True if the given session_key already exists. """ raise NotImplementedError def create(self): """ Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError def save(self, must_create=False): """ Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key. """ raise NotImplementedError def delete(self, session_key=None): """ Deletes the session data under this key. If the key is None, the current session key value is used. """ raise NotImplementedError def load(self): """ Loads the session data and returns a dictionary. """ raise NotImplementedError
[ [ 1, 0, 0.0032, 0.0032, 0, 0.66, 0, 177, 0, 1, 0, 0, 177, 0, 0 ], [ 1, 0, 0.0065, 0.0032, 0, 0.66, 0.0769, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.0097, 0.0032, 0, ...
[ "import base64", "import os", "import random", "import sys", "import time", "from datetime import datetime, timedelta", "try:\n import cPickle as pickle\nexcept ImportError:\n import pickle", " import cPickle as pickle", " import pickle", "from django.conf import settings", "from dja...
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache class SessionStore(DBStore): """ Implements cached, database backed sessions. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): data = cache.get(self.session_key, None) if data is None: data = super(SessionStore, self).load() cache.set(self.session_key, data, settings.SESSION_COOKIE_AGE) return data def exists(self, session_key): return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(session_key) cache.delete(session_key or self.session_key) def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete(self.session_key) self.create()
[ [ 8, 0, 0.0476, 0.0714, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.119, 0.0238, 0, 0.66, 0.25, 128, 0, 1, 0, 0, 128, 0, 0 ], [ 1, 0, 0.1429, 0.0238, 0, 0.66, ...
[ "\"\"\"\nCached, database-backed sessions.\n\"\"\"", "from django.conf import settings", "from django.contrib.sessions.backends.db import SessionStore as DBStore", "from django.core.cache import cache", "class SessionStore(DBStore):\n \"\"\"\n Implements cached, database backed sessions.\n \"\"\"\n...