desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initializes the Google Zoom object.'
def __init__(self, num_zoom=19, tilesize=256):
self._tilesize = tilesize self._nzoom = num_zoom self._degpp = [] self._radpp = [] self._npix = [] z = tilesize for i in xrange(num_zoom): self._degpp.append((z / 360.0)) self._radpp.append((z / (2 * pi))) self._npix.append((z / 2)) z *= 2
'Returns the number of zoom levels.'
def __len__(self):
return self._nzoom
'Unpacks longitude, latitude from GEOS Points and 2-tuples.'
def get_lon_lat(self, lonlat):
if isinstance(lonlat, Point): (lon, lat) = lonlat.coords else: (lon, lat) = lonlat return (lon, lat)
'Converts a longitude, latitude coordinate pair for the given zoom level.'
def lonlat_to_pixel(self, lonlat, zoom):
(lon, lat) = self.get_lon_lat(lonlat) npix = self._npix[zoom] px_x = round((npix + (lon * self._degpp[zoom]))) fac = min(max(sin((DTOR * lat)), (-0.9999)), 0.9999) px_y = round((npix + ((0.5 * log(((1 + fac) / (1 - fac)))) * ((-1.0) * self._radpp[zoom])))) return (px_x, px_y)
'Converts a pixel to a longitude, latitude pair at the given zoom level.'
def pixel_to_lonlat(self, px, zoom):
if (len(px) != 2): raise TypeError('Pixel should be a sequence of two elements.') npix = self._npix[zoom] lon = ((px[0] - npix) / self._degpp[zoom]) lat = (RTOD * ((2 * atan(exp(((px[1] - npix) / ((-1.0) * self._radpp[zoom]))))) - (0.5 * pi))) return (lon, lat)
'Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point.'
def tile(self, lonlat, zoom):
delta = (self._tilesize / 2) px = self.lonlat_to_pixel(lonlat, zoom) ll = self.pixel_to_lonlat(((px[0] - delta), (px[1] - delta)), zoom) ur = self.pixel_to_lonlat(((px[0] + delta), (px[1] + delta)), zoom) return Polygon(LinearRing(ll, (ll[0], ur[1]), ur, (ur[0], ll[1]), ll), srid=4326)
'Returns the optimal Zoom level for the given geometry.'
def get_zoom(self, geom):
if ((not isinstance(geom, GEOSGeometry)) or (geom.srid != 4326)): raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') env = geom.envelope (env_w, env_h) = self.get_width_height(env.extent) center = env.centroid for z in xrange(self._nzoom): ...
'Returns the width and height for the given extent.'
def get_width_height(self, extent):
ll = Point(extent[:2]) ul = Point(extent[0], extent[3]) ur = Point(extent[2:]) height = ll.distance(ul) width = ul.distance(ur) return (width, height)
'Initializes a GEvent object. Parameters: event: string for the event, such as \'click\'. The event must be a valid event for the object in the Google Maps API. There is no validation of the event type within Django. action: string containing a Javascript function, such as \'function() { location.href = "newurl";}\' Th...
def __init__(self, event, action):
self.event = event self.action = action
'Returns the parameter part of a GEvent.'
def __unicode__(self):
return mark_safe(('"%s", %s' % (self.event, self.action)))
'Generates a JavaScript array of GLatLng objects for the given coordinates.'
def latlng_from_coords(self, coords):
return ('[%s]' % ','.join([('new GLatLng(%s,%s)' % (y, x)) for (x, y) in coords]))
'Attaches a GEvent to the overlay object.'
def add_event(self, event):
self.events.append(event)
'The string representation is the JavaScript API call.'
def __unicode__(self):
return mark_safe(('%s(%s)' % (self.__class__.__name__, self.js_params)))
'The GPolygon object initializes on a GEOS Polygon or a parameter that may be instantiated into GEOS Polygon. Please note that this will not depict a Polygon\'s internal rings. Keyword Options: stroke_color: The color of the polygon outline. Defaults to \'#0000ff\' (blue). stroke_weight: The width of the polygon outli...
def __init__(self, poly, stroke_color='#0000ff', stroke_weight=2, stroke_opacity=1, fill_color='#0000ff', fill_opacity=0.4):
if isinstance(poly, basestring): poly = fromstr(poly) if isinstance(poly, (tuple, list)): poly = Polygon(poly) if (not isinstance(poly, Polygon)): raise TypeError('GPolygon may only initialize on GEOS Polygons.') self.envelope = poly.envelope self.points = s...
'The GPolyline object may be initialized on GEOS LineStirng, LinearRing, and Polygon objects (internal rings not supported) or a parameter that may instantiated into one of the above geometries. Keyword Options: color: The color to use for the polyline. Defaults to \'#0000ff\' (blue). weight: The width of the polyline...
def __init__(self, geom, color='#0000ff', weight=2, opacity=1):
if isinstance(geom, basestring): geom = fromstr(geom) if isinstance(geom, (tuple, list)): geom = Polygon(geom) if isinstance(geom, (LineString, LinearRing)): self.latlngs = self.latlng_from_coords(geom.coords) elif isinstance(geom, Polygon): self.latlngs = self.latlng_fro...
'The GMarker object may initialize on GEOS Points or a parameter that may be instantiated into a GEOS point. Keyword options map to GMarkerOptions -- so far only the title option is supported. Keyword Options: title: Title option for GMarker, will be displayed as a tooltip. draggable: Draggable option for GMarker, dis...
def __init__(self, geom, title=None, draggable=False, icon=None):
if isinstance(geom, basestring): geom = fromstr(geom) if isinstance(geom, (tuple, list)): geom = Point(geom) if isinstance(geom, Point): self.latlng = self.latlng_from_coords(geom.coords) else: raise TypeError('GMarker may only initialize on GEOS Point ...
'Generates the JavaScript necessary for displaying this Google Map.'
def render(self):
params = {'calc_zoom': self.calc_zoom, 'center': self.center, 'dom_id': self.dom_id, 'js_module': self.js_module, 'kml_urls': self.kml_urls, 'zoom': self.zoom, 'polygons': self.polygons, 'polylines': self.polylines, 'icons': self.icons, 'markers': self.markers} params.update(self.extra_context) return rende...
'Returns HTML body tag for loading and unloading Google Maps javascript.'
@property def body(self):
return mark_safe(('<body %s %s>' % (self.onload, self.onunload)))
'Returns the `onload` HTML <body> attribute.'
@property def onload(self):
return mark_safe(('onload="%s.%s_load()"' % (self.js_module, self.dom_id)))
'Returns the <script> tag for the Google Maps API javascript.'
@property def api_script(self):
return mark_safe(('<script src="%s%s" type="text/javascript"></script>' % (self.api_url, self.key)))
'Returns only the generated Google Maps JavaScript (no <script> tags).'
@property def js(self):
return self.render()
'Returns all <script></script> tags required with Google Maps JavaScript.'
@property def scripts(self):
return mark_safe(('%s\n <script type="text/javascript">\n//<![CDATA[\n%s//]]>\n </script>' % (self.api_script, self.js)))
'Returns additional CSS styling needed for Google Maps on IE.'
@property def style(self):
return mark_safe(('<style type="text/css">%s</style>' % self.vml_css))
'Returns XHTML information needed for IE VML overlays.'
@property def xhtml(self):
return mark_safe(('<html xmlns="http://www.w3.org/1999/xhtml" %s>' % self.xmlns))
'Returns a sequence of GIcon objects in this map.'
@property def icons(self):
return set([marker.icon for marker in self.markers if marker.icon])
'A class for generating sets of Google Maps that will be shown on the same page together. Example: gmapset = GoogleMapSet( GoogleMap( ... ), GoogleMap( ... ) ) gmapset = GoogleMapSet( [ gmap1, gmap2] )'
def __init__(self, *args, **kwargs):
template = kwargs.pop('template', 'gis/google/google-multi.js') self.map_template = kwargs.pop('map_template', 'gis/google/google-single.js') super(GoogleMapSet, self).__init__(**kwargs) self.template = template if isinstance(args[0], (tuple, list)): self.maps = args[0] else: sel...
'Returns JavaScript containing all of the loading routines for each map in this set.'
def load_map_js(self):
result = [] for (dom_id, gmap) in zip(self.dom_ids, self.maps): tmp = (gmap.template, gmap.dom_id) gmap.template = self.map_template gmap.dom_id = dom_id result.append(gmap.js) (gmap.template, gmap.dom_id) = tmp return mark_safe(''.join(result))
'Generates the JavaScript for the collection of Google Maps in this set.'
def render(self):
params = {'js_module': self.js_module, 'dom_ids': self.dom_ids, 'load_map_js': self.load_map_js(), 'icons': self.icons} params.update(self.extra_context) return render_to_string(self.template, params)
'Returns the `onload` HTML <body> attribute.'
@property def onload(self):
return mark_safe(('onload="%s.load()"' % self.js_module))
'Returns a sequence of all icons in each map of the set.'
@property def icons(self):
icons = set() for map in self.maps: icons |= map.icons return icons
'Goes through the given sources and returns a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models.'
def _build_kml_sources(self, sources):
kml_sources = [] if (sources is None): sources = models.get_models() for source in sources: if isinstance(source, models.base.ModelBase): for field in source._meta.fields: if isinstance(field, GeometryField): kml_sources.append((source._meta.ap...
'This method is overrridden so the appropriate `geo_format` attribute is placed on each URL element.'
def get_urls(self, page=1, site=None):
urls = Sitemap.get_urls(self, page=page, site=site) for url in urls: url['geo_format'] = self.geo_format return urls
'This sitemap object initializes on a feed dictionary (as would be passed to `django.contrib.syndication.views.feed`) and a slug dictionary. If the slug dictionary is not defined, then it\'s assumed the keys provide the URL parameter to the feed. However, if you have a complex feed (e.g., you override `get_object`, th...
def __init__(self, feed_dict, slug_dict=None):
self.feed_dict = feed_dict self.locations = [] if (slug_dict is None): slug_dict = {} for section in feed_dict.keys(): if slug_dict.get(section, False): for slug in slug_dict[section]: self.locations.append(('%s/%s' % (section, slug))) else: ...
'This method is overrridden so the appropriate `geo_format` attribute is placed on each URL element.'
def get_urls(self, page=1, site=None):
urls = Sitemap.get_urls(self, page=page, site=site) for url in urls: url['geo_format'] = 'georss' return urls
'In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, this will return a unicode GeoRSS representation.'
def georss_coords(self, coords):
return u' '.join([(u'%f %f' % (coord[1], coord[0])) for coord in coords])
'Adds a GeoRSS point with the given coords using the given handler. Handles the differences between simple GeoRSS and the more pouplar W3C Geo specification.'
def add_georss_point(self, handler, coords, w3c_geo=False):
if w3c_geo: (lon, lat) = coords[:2] handler.addQuickElement(u'geo:lat', (u'%f' % lat)) handler.addQuickElement(u'geo:lon', (u'%f' % lon)) else: handler.addQuickElement(u'georss:point', self.georss_coords((coords,)))
'This routine adds a GeoRSS XML element using the given item and handler.'
def add_georss_element(self, handler, item, w3c_geo=False):
geom = item.get('geometry', None) if (not (geom is None)): if isinstance(geom, (list, tuple)): box_coords = None if isinstance(geom[0], (list, tuple)): if (len(geom) == 2): box_coords = geom else: raise Value...
'Figures out the correct OGR Type based upon the input.'
def __init__(self, type_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): ...
'Returns the value of the name property.'
def __str__(self):
return self.name
'Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.'
def __eq__(self, other):
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
'Returns a short-hand string form of the OGR Geometry type.'
@property def name(self):
return self._types[self.num]
'Returns the Django GeometryField for this OGR Type.'
@property def django(self):
s = self.name.replace('25D', '') if (s in ('LinearRing', 'None')): return None elif (s == 'Unknown'): s = 'Geometry' return (s + 'Field')
'Initializes an OGR driver on either a string or integer input.'
def __init__(self, dr_input):
if isinstance(dr_input, basestring): self._register() if (dr_input.lower() in self._alias): name = self._alias[dr_input.lower()] else: name = dr_input dr = capi.get_driver_by_name(name) elif isinstance(dr_input, int): self._register() dr = ...
'Returns the string name of the OGR Driver.'
def __str__(self):
return capi.get_driver_name(self.ptr)
'Attempts to register all the data source drivers.'
def _register(self):
if (not self.driver_count): capi.register_all()
'Returns the number of OGR data source drivers registered.'
@property def driver_count(self):
return capi.get_driver_count()
'Testing OGRGeomType object.'
def test00a_geomtype(self):
try: g = OGRGeomType(1) g = OGRGeomType(7) g = OGRGeomType('point') g = OGRGeomType('GeometrycollectioN') g = OGRGeomType('LINearrING') g = OGRGeomType('Unknown') except: self.fail('Could not create an OGRGeomType object!') self.assertRa...
'Testing OGRGeomType object with 25D types.'
def test00b_geomtype_25d(self):
wkb25bit = OGRGeomType.wkb25bit self.failUnless((OGRGeomType((wkb25bit + 1)) == 'Point25D')) self.failUnless((OGRGeomType('MultiLineString25D') == (5 + wkb25bit))) self.assertEqual('GeometryCollectionField', OGRGeomType('GeometryCollection25D').django)
'Testing WKT output.'
def test01a_wkt(self):
for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) self.assertEqual(g.wkt, geom.wkt)
'Testing EWKT input/output.'
def test01a_ewkt(self):
for ewkt_val in ('POINT (1 2 3)', 'LINEARRING (0 0,1 1,2 1,0 0)'): self.assertEqual(ewkt_val, OGRGeometry(ewkt_val).ewkt) ewkt_val = ('SRID=4326;%s' % ewkt_val) geom = OGRGeometry(ewkt_val) self.assertEqual(ewkt_val, geom.ewkt) self.assertEqual(4326, g...
'Testing GML output.'
def test01b_gml(self):
for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) self.assertEqual(g.gml, geom.gml)
'Testing HEX input/output.'
def test01c_hex(self):
for g in self.geometries.hex_wkt: geom1 = OGRGeometry(g.wkt) self.assertEqual(g.hex, geom1.hex) geom2 = OGRGeometry(g.hex) self.assertEqual(geom1, geom2)
'Testing WKB input/output.'
def test01d_wkb(self):
from binascii import b2a_hex for g in self.geometries.hex_wkt: geom1 = OGRGeometry(g.wkt) wkb = geom1.wkb self.assertEqual(b2a_hex(wkb).upper(), g.hex) geom2 = OGRGeometry(wkb) self.assertEqual(geom1, geom2)
'Testing GeoJSON input/output.'
def test01e_json(self):
from django.contrib.gis.gdal.prototypes.geom import GEOJSON if (not GEOJSON): return for g in self.geometries.json_geoms: geom = OGRGeometry(g.wkt) if (not hasattr(g, 'not_equal')): self.assertEqual(g.json, geom.json) self.assertEqual(g.json, geom.geojson) ...
'Testing Point objects.'
def test02_points(self):
prev = OGRGeometry('POINT(0 0)') for p in self.geometries.points: if (not hasattr(p, 'z')): pnt = OGRGeometry(p.wkt) self.assertEqual(1, pnt.geom_type) self.assertEqual('POINT', pnt.geom_name) self.assertEqual(p.x, pnt.x) self.assertEqual(p....
'Testing MultiPoint objects.'
def test03_multipoints(self):
for mp in self.geometries.multipoints: mgeom1 = OGRGeometry(mp.wkt) self.assertEqual(4, mgeom1.geom_type) self.assertEqual('MULTIPOINT', mgeom1.geom_name) mgeom2 = OGRGeometry('MULTIPOINT') mgeom3 = OGRGeometry('MULTIPOINT') for g in mgeom1: mgeom2.add(g) ...
'Testing LineString objects.'
def test04_linestring(self):
prev = OGRGeometry('POINT(0 0)') for ls in self.geometries.linestrings: linestr = OGRGeometry(ls.wkt) self.assertEqual(2, linestr.geom_type) self.assertEqual('LINESTRING', linestr.geom_name) self.assertEqual(ls.n_p, linestr.point_count) self.assertEqual(ls.coords, line...
'Testing MultiLineString objects.'
def test05_multilinestring(self):
prev = OGRGeometry('POINT(0 0)') for mls in self.geometries.multilinestrings: mlinestr = OGRGeometry(mls.wkt) self.assertEqual(5, mlinestr.geom_type) self.assertEqual('MULTILINESTRING', mlinestr.geom_name) self.assertEqual(mls.n_p, mlinestr.point_count) self.assertEqua...
'Testing LinearRing objects.'
def test06_linearring(self):
prev = OGRGeometry('POINT(0 0)') for rr in self.geometries.linearrings: lr = OGRGeometry(rr.wkt) self.assertEqual('LINEARRING', lr.geom_name) self.assertEqual(rr.n_p, len(lr)) self.assertEqual(True, (lr == OGRGeometry(rr.wkt))) self.assertEqual(True, (lr != prev)) ...
'Testing Polygon objects.'
def test07a_polygons(self):
bbox = ((-180), (-90), 180, 90) p = OGRGeometry.from_bbox(bbox) self.assertEqual(bbox, p.extent) prev = OGRGeometry('POINT(0 0)') for p in self.geometries.polygons: poly = OGRGeometry(p.wkt) self.assertEqual(3, poly.geom_type) self.assertEqual('POLYGON', poly.geom_name) ...
'Testing closing Polygon objects.'
def test07b_closepolygons(self):
poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))') self.assertEqual(8, poly.point_count) print '\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n' try: c = poly.centroid except OGRException: ...
'Testing MultiPolygon objects.'
def test08_multipolygons(self):
prev = OGRGeometry('POINT(0 0)') for mp in self.geometries.multipolygons: mpoly = OGRGeometry(mp.wkt) self.assertEqual(6, mpoly.geom_type) self.assertEqual('MULTIPOLYGON', mpoly.geom_name) if mp.valid: self.assertEqual(mp.n_p, mpoly.point_count) self.as...
'Testing OGR Geometries with Spatial Reference objects.'
def test09a_srs(self):
for mp in self.geometries.multipolygons: sr = SpatialReference('WGS84') mpoly = OGRGeometry(mp.wkt, sr) self.assertEqual(sr.wkt, mpoly.srs.wkt) klone = mpoly.clone() self.assertEqual(sr.wkt, klone.srs.wkt) for poly in mpoly: self.assertEqual(sr.wkt, poly.s...
'Testing transform().'
def test09b_srs_transform(self):
orig = OGRGeometry('POINT (-104.609 38.255)', 4326) trans = OGRGeometry('POINT (992385.4472045 481455.4944650)', 2774) (t1, t2, t3) = (orig.clone(), orig.clone(), orig.clone()) t1.transform(trans.srid) t2.transform(SpatialReference('EPSG:2774')) ct = CoordTransform(SpatialReference('...
'Testing coordinate dimension is the same on transformed geometries.'
def test09c_transform_dim(self):
ls_orig = OGRGeometry('LINESTRING(-104.609 38.255)', 4326) ls_trans = OGRGeometry('LINESTRING(992385.4472045 481455.4944650)', 2774) prec = 3 ls_orig.transform(ls_trans.srs) self.assertEqual(2, ls_orig.coord_dim) self.assertAlmostEqual(ls_trans.x[0], ls_orig.x[0], prec) self.assertAlmo...
'Testing difference().'
def test10_difference(self):
for i in xrange(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertEqual(d1, d2) se...
'Testing intersects() and intersection().'
def test11_intersection(self):
for i in xrange(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) i1 = OGRGeometry(self.geometries.intersect_geoms[i].wkt) self.assertEqual(True, a.intersects(b)) i2 = a.inte...
'Testing sym_difference().'
def test12_symdifference(self):
for i in xrange(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertEqual(d1, d2) ...
'Testing union().'
def test13_union(self):
for i in xrange(len(self.geometries.topology_geoms)): a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a) b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b) u1 = OGRGeometry(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertEqual(u1, u2) self.a...
'Testing GeometryCollection.add().'
def test14_add(self):
mp = OGRGeometry('MultiPolygon') pnt = OGRGeometry('POINT(5 23)') self.assertRaises(OGRException, mp.add, pnt) for mp in self.geometries.multipolygons: mpoly = OGRGeometry(mp.wkt) mp1 = OGRGeometry('MultiPolygon') mp2 = OGRGeometry('MultiPolygon') mp3 = OGRGeometry('Mu...
'Testing `extent` property.'
def test15_extent(self):
mp = OGRGeometry('MULTIPOINT(5 23, 0 0, 10 50)') self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) poly = OGRGeometry(self.geometries.polygons[3].wkt) ring = poly.shell (x, y) = (ring.x, ring.y) (xmin, ymin) = (min(x), min(y)) (xmax, ymax) = (max(x), max(y)) self.assertE...
'Testing 2.5D geometries.'
def test16_25D(self):
pnt_25d = OGRGeometry('POINT(1 2 3)') self.assertEqual('Point25D', pnt_25d.geom_type.name) self.assertEqual(3.0, pnt_25d.z) self.assertEqual(3, pnt_25d.coord_dim) ls_25d = OGRGeometry('LINESTRING(1 1 1,2 2 2,3 3 3)') self.assertEqual('LineString25D', ls_25d.geom_type.name...
'Testing pickle support.'
def test17_pickle(self):
import cPickle g1 = OGRGeometry('LINESTRING(1 1 1,2 2 2,3 3 3)', 'WGS84') g2 = cPickle.loads(cPickle.dumps(g1)) self.assertEqual(g1, g2) self.assertEqual(4326, g2.srs.srid) self.assertEqual(g1.srs.wkt, g2.srs.wkt)
'Testing coordinate dimensions on geometries after transformation.'
def test18_ogrgeometry_transform_workaround(self):
wkt_2d = 'MULTILINESTRING ((0 0,1 1,2 2))' wkt_3d = 'MULTILINESTRING ((0 0 0,1 1 1,2 2 2))' srid = 4326 geom = OGRGeometry(wkt_2d, srid) geom.transform(srid) self.assertEqual(2, geom.coord_dim) self.assertEqual(2, geom[0].coord_dim) self.assertEqual(wkt_2...
'Testing equivalence methods with non-OGRGeometry instances.'
def test19_equivalence_regression(self):
self.assertNotEqual(None, OGRGeometry('POINT(0 0)')) self.assertEqual(False, (OGRGeometry('LINESTRING(0 0, 1 1)') == 3))
'Testing initialization on valid OGC WKT.'
def test01_wkt(self):
for s in srlist: srs = SpatialReference(s.wkt)
'Testing initialization on invalid WKT.'
def test02_bad_wkt(self):
for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, OGRException): pass else: self.fail('Should not have initialized on bad WKT "%s"!')
'Testing getting the WKT.'
def test03_get_wkt(self):
for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.wkt, srs.wkt)
'Test PROJ.4 import and export.'
def test04_proj(self):
for s in srlist: if s.proj: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.proj) self.assertEqual(srs1.proj, srs2.proj)
'Test EPSG import.'
def test05_epsg(self):
for s in srlist: if s.epsg: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.epsg) srs3 = SpatialReference(str(s.epsg)) srs4 = SpatialReference(('EPSG:%d' % s.epsg)) for srs in (srs1, srs2, srs3, srs4): for (attr, expected) ...
'Testing the boolean properties.'
def test07_boolean_props(self):
for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.projected, srs.projected) self.assertEqual(s.geographic, srs.geographic)
'Testing the linear and angular units routines.'
def test08_angular_linear(self):
for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.ang_name, srs.angular_name) self.assertEqual(s.lin_name, srs.linear_name) self.assertAlmostEqual(s.ang_units, srs.angular_units, 9) self.assertAlmostEqual(s.lin_units, srs.linear_units, 9)
'Testing the authority name & code routines.'
def test09_authority(self):
for s in srlist: if hasattr(s, 'auth'): srs = SpatialReference(s.wkt) for (target, tup) in s.auth.items(): self.assertEqual(tup[0], srs.auth_name(target)) self.assertEqual(tup[1], srs.auth_code(target))
'Testing the attribute retrieval routines.'
def test10_attributes(self):
for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: att = tup[0] exp = tup[1] self.assertEqual(exp, srs[att])
'Testing Well Known Names of Spatial References.'
def test11_wellknown(self):
for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if (len(tup) == 2): key = tup[0] exp = tup[1] elif (len(tup) == 3): key = tup[:2] exp = tup[2] ...
'Testing initialization of a CoordTransform.'
def test12_coordtransform(self):
target = SpatialReference('WGS84') for s in srlist: if s.proj: ct = CoordTransform(SpatialReference(s.wkt), target)
'Testing the attr_value() method.'
def test13_attr_value(self):
s1 = SpatialReference('WGS84') self.assertRaises(TypeError, s1.__getitem__, 0) self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo')) self.assertEqual('WGS 84', s1['GEOGCS']) self.assertEqual('WGS_1984', s1['DATUM']) self.assertEqual('EPSG', s1['AUTHORITY']) self.assertEqual(4326...
'Testing valid SHP Data Source files.'
def test01_valid_shp(self):
for source in ds_list: ds = DataSource(source.ds) self.assertEqual(1, len(ds)) self.assertEqual(source.ds, ds.name) self.assertEqual(source.driver, str(ds.driver)) try: ds[len(ds)] except OGRIndexError: pass else: self.fail(...
'Testing invalid SHP files for the Data Source.'
def test02_invalid_shp(self):
for source in bad_ds: self.assertRaises(OGRException, DataSource, source.ds)
'Testing Data Source Layers.'
def test03a_layers(self):
print '\nBEGIN - expecting out of range feature id error; safe to ignore.\n' for source in ds_list: ds = DataSource(source.ds) for layer in ds: self.assertEqual(len(layer), source.nfeat) self.assertEqual(source.nfld, layer.num_fields) ...
'Test indexing and slicing on Layers.'
def test03b_layer_slice(self):
source = ds_list[0] ds = DataSource(source.ds) sl = slice(1, 3) feats = ds[0][sl] for fld_name in ds[0].fields: test_vals = [feat.get(fld_name) for feat in feats] control_vals = source.field_values[fld_name][sl] self.assertEqual(control_vals, test_vals)
'Test to make sure Layer access is still available without the DataSource.'
def test03c_layer_references(self):
source = ds_list[0] def get_layer(): ds = DataSource(source.ds) return ds[0] lyr = get_layer() self.assertEqual(source.nfeat, len(lyr)) self.assertEqual(source.gtype, lyr.geom_type.num)
'Testing Data Source Features.'
def test04_features(self):
for source in ds_list: ds = DataSource(source.ds) for layer in ds: for feat in layer: self.assertEqual(source.nfld, len(list(feat))) self.assertEqual(source.gtype, feat.geom_type) for (k, v) in source.fields.items(): sel...
'Testing Geometries from Data Source Features.'
def test05_geometries(self):
for source in ds_list: ds = DataSource(source.ds) for layer in ds: for feat in layer: g = feat.geom self.assertEqual(source.geom, g.geom_name) self.assertEqual(source.gtype, g.geom_type) if hasattr(source, 'srs_wkt'): ...
'Testing the Layer.spatial_filter property.'
def test06_spatial_filter(self):
ds = DataSource(get_ds_file('cities', 'shp')) lyr = ds[0] self.assertEqual(None, lyr.spatial_filter) self.assertRaises(TypeError, lyr._set_spatial_filter, 'foo') self.assertRaises(ValueError, lyr._set_spatial_filter, range(5)) filter_extent = ((-105.609252), 37.255001, (-103.609252), 39.255001) ...
'Testing valid OGR Data Source Drivers.'
def test01_valid_driver(self):
for d in valid_drivers: dr = Driver(d) self.assertEqual(d, str(dr))
'Testing invalid OGR Data Source Drivers.'
def test02_invalid_driver(self):
for i in invalid_drivers: self.assertRaises(OGRException, Driver, i)
'Testing driver aliases.'
def test03_aliases(self):
for (alias, full_name) in aliases.items(): dr = Driver(alias) self.assertEqual(full_name, str(dr))
'Testing Envelope initilization.'
def test01_init(self):
e1 = Envelope((0, 0, 5, 5)) e2 = Envelope(0, 0, 5, 5) e3 = Envelope(0, '0', '5', 5) e4 = Envelope(e1._envelope) self.assertRaises(OGRException, Envelope, (5, 5, 0, 0)) self.assertRaises(OGRException, Envelope, 5, 5, 0, 0) self.assertRaises(OGRException, Envelope, (0, 0, 5, 5, 3)) self.as...
'Testing Envelope properties.'
def test02_properties(self):
e = Envelope(0, 0, 2, 3) self.assertEqual(0, e.min_x) self.assertEqual(0, e.min_y) self.assertEqual(2, e.max_x) self.assertEqual(3, e.max_y) self.assertEqual((0, 0), e.ll) self.assertEqual((2, 3), e.ur) self.assertEqual((0, 0, 2, 3), e.tuple) self.assertEqual('POLYGON((0.0 0.0,0.0...