def test_feature_expression_evaluation_attr_with_spaces(): context = mapnik.Context() context.push('name with space') f = mapnik.Feature(context, 1) f['name with space'] = u'a' eq_(f['name with space'], u'a') expr = mapnik.Expression("[name with space]='a'") eq_(str(expr), "([name with space]='a')") eq_(expr.evaluate(f), True)
def test_division_by_zero(): expr = mapnik.Expression('[a]/[b]') c = mapnik.Context() c.push('a') c.push('b') f = mapnik.Feature(c, 0) f['a'] = 1 f['b'] = 0 eq_(expr.evaluate(f), None)
def test_feature_expression_evaluation_missing_attr(): f = mapnik.Feature(1) f['name'] = u'a' eq_(f['name'], u'a') expr = mapnik.Expression("[fielddoesnotexist]='a'") evaluated = expr.evaluate(f) eq_(evaluated, False) num_attributes = len(f) eq_(num_attributes, 1) eq_(f.id(), 1)
def test_feature_expression_evaluation(): f = mapnik.Feature(1) f['name'] = 'a' eq_(f['name'], u'a') expr = mapnik.Expression("[name]='a'") evaluated = expr.evaluate(f) eq_(evaluated, True) num_attributes = len(f) eq_(num_attributes, 1) eq_(f.id(), 1)
def test_truthyness_comparision(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = 1 eq_(mapnik.Expression("[prop]").to_bool(f), True) eq_(mapnik.Expression("[prop] = false").to_bool(f), False) eq_(mapnik.Expression("not [prop] != false").to_bool(f), False) eq_(mapnik.Expression("not [prop] = true").to_bool(f), False) eq_(mapnik.Expression("[prop] = true").to_bool(f), True) eq_(mapnik.Expression("[prop] != true").to_bool(f), False)
def test_geometry_index_error(): wkt = 'Point (0 0)' # easy api, but slower #paths = mapnik.Path.from_wkt(wkt) # fast api paths = reader.read(wkt); paths[3] f = mapnik.Feature(mapnik.Context(),1) f.add_geometries_from_wkt(wkt) f.geometries()[3]
def render_image(self, extent, img_size, settings): # Выбираем объекты по экстенту feature_query = self.layer.feature_query() feature_query.intersects(box(*extent, srid=self.layer.srs_id)) feature_query.geom() features = feature_query() ds = mapnik.MemoryDatasource() for (id, f) in enumerate(features): if mapnik.mapnik_version() < 200100: feature = mapnik.Feature(id) else: feature = mapnik.Feature(mapnik.Context(), id) feature.add_geometries_from_wkb(f.geom.wkb) ds.add_feature(feature) style_content = str(self.style_content) m = mapnik.Map(img_size[0], img_size[1]) mapnik.load_map_from_string(m, style_content) m.zoom_to_box(mapnik.Box2d(*extent)) layer = mapnik.Layer('main') layer.datasource = ds root = ET.fromstring(style_content) styles = [s.attrib.get('name') for s in root.iter('Style')] for s in styles: layer.styles.append(s) m.layers.append(layer) img = mapnik.Image(img_size[0], img_size[1]) mapnik.render(m, img) data = img.tostring('png') # Преобразуем изображение из PNG в объект PIL buf = StringIO() buf.write(data) buf.seek(0) img = Image.open(buf) return img
def test_creation_of_null_value(): context = mapnik.Context() context.push('nv') f = mapnik.Feature(context, 0) f["nv"] = None eq_(f["nv"], None) eq_(f["nv"] is None, True) # test boolean f["nv"] = 0 eq_(f["nv"], 0) eq_(f["nv"] is not None, True)
def render_png(tile, _zoom, xml, overscan): """ Render the tile as a .png TODO: Actually handling zoom levels. """ # mapnik is installed in a non-standard way. # It confuses pylint. # pylint: disable=no-member,too-many-locals map_tile_size = TILE_SIZE + (overscan * 2) logger = get_logger() ctx = mapnik.Context() map_tile = mapnik.Map(map_tile_size, map_tile_size) # scale_denom = 1 << (BASE_ZOOM - int(zoom or 1)) # scale_factor = scale_denom / map_tile.scale_denominator() # map_tile.zoom(scale_factor) # Is overriden by zoom_to_box. mapnik.load_map_from_string(map_tile, xml) box_min = -overscan box_max = TILE_SIZE + overscan - 1 map_tile.zoom_to_box(mapnik.Box2d(box_min, box_min, box_max, box_max)) for (name, features) in tile.items(): name = name.encode('ascii', 'ignore') source = mapnik.MemoryDatasource() map_layer = mapnik.Layer(name) map_layer.datasource = source for feature in features: feat = mapnik.Feature(ctx, 0) try: feat.geometry = mapnik.Geometry.from_wkb(feature) except RuntimeError: try: wkt = mapnik.Geometry.from_wkb(feature).to_wkt() logger.error('Invalid feature: %s', wkt) except RuntimeError: logger.error('Corrupt feature: %s', feature.encode('hex')) source.add_feature(feat) map_layer.styles.append(name) map_tile.layers.append(map_layer) image = mapnik.Image(TILE_SIZE, TILE_SIZE) # tile, image, scale, offset_x, offset_y mapnik.render(map_tile, image, 1, overscan, overscan) return image.tostring('png')
def test_float_precision(): context = mapnik.Context() context.push('num') f = mapnik.Feature(context, 0) f["num"] = 1.0000 eq_(f["num"], 1.0000) expr = mapnik.Expression("[num] = 1.0000") eq_(expr.evaluate(f), True) expr = mapnik.Expression("[num].match('.*0$')") eq_(expr.evaluate(f), True) expr = mapnik.Expression("[num].match('.*0$')") eq_(expr.evaluate(f), True)
def test_feature_expression_evaluation_missing_attr(): context = mapnik.Context() context.push('name') f = mapnik.Feature(context, 1) f['name'] = u'a' eq_(f['name'], u'a') expr = mapnik.Expression("[fielddoesnotexist]='a'") eq_(f.has_key('fielddoesnotexist'), False) try: expr.evaluate(f) except Exception, e: eq_("Key does not exist" in str(e), True)
def test_expressions_with_null_equality(): for eq in null_equality: context = mapnik.Context() f = mapnik.Feature(context,0) f["prop"] = eq[0] eq_(f["prop"],eq[0]) if eq[0] is None: eq_(f["prop"] is None, True) else: eq_(isinstance(f['prop'],eq[2]),True,'%s is not an instance of %s' % (f['prop'],eq[2])) expr = mapnik.Expression("[prop] = null") eq_(expr.evaluate(f),eq[1]) expr = mapnik.Expression("[prop] is null") eq_(expr.evaluate(f),eq[1])
def test_expressions_for_thruthyness(): context = mapnik.Context() for eq in truthyness: f = mapnik.Feature(context,0) f["prop"] = eq[0] eq_(f["prop"],eq[0]) if eq[0] is None: eq_(f["prop"] is None, True) else: eq_(isinstance(f['prop'],eq[2]),True,'%s is not an instance of %s' % (f['prop'],eq[2])) expr = mapnik.Expression("[prop]") eq_(expr.to_bool(f),eq[1]) expr = mapnik.Expression("not [prop]") eq_(expr.to_bool(f),not eq[1]) expr = mapnik.Expression("! [prop]") eq_(expr.to_bool(f),not eq[1]) # also test if feature does not have property at all f2 = mapnik.Feature(context,1) # no property existing will return value_null since # https://github.com/mapnik/mapnik/commit/562fada9d0f680f59b2d9f396c95320a0d753479#include/mapnik/feature.hpp eq_(f2["prop"] is None,True) expr = mapnik.Expression("[prop]") eq_(expr.evaluate(f2),None) eq_(expr.to_bool(f2),False)
def test_feature_expression_evaluation_missing_attr(): context = mapnik.Context() context.push('name') f = mapnik.Feature(context, 1) f['name'] = u'a' eq_(f['name'], u'a') expr = mapnik.Expression("[fielddoesnotexist]='a'") eq_('fielddoesnotexist' in f, False) try: expr.evaluate(f) except Exception as e: eq_("Key does not exist" in str(e), True) num_attributes = len(f) eq_(num_attributes, 1) eq_(f.id(), 1)
def test_if_null_and_empty_string_are_equal(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["empty"] = u"" f["null"] = None # ensure base assumptions are good eq_(mapnik.Expression("[empty] = ''").to_bool(f), True) eq_(mapnik.Expression("[null] = null").to_bool(f), True) eq_(mapnik.Expression("[empty] != ''").to_bool(f), False) eq_(mapnik.Expression("[null] != null").to_bool(f), False) # now test expected behavior eq_(mapnik.Expression("[null] = ''").to_bool(f), False) eq_(mapnik.Expression("[empty] = null").to_bool(f), False) eq_(mapnik.Expression("[empty] != null").to_bool(f), True) # this one is the back compatibility shim eq_(mapnik.Expression("[null] != ''").to_bool(f), False)
def test_float_precision(): context = mapnik.Context() context.push('num') f = mapnik.Feature(context, 0) f["num1"] = 1.0000 f["num2"] = 1.0001 eq_(f["num1"], 1.0000) eq_(f["num2"], 1.0001) expr = mapnik.Expression("[num1] = 1.0000") eq_(expr.evaluate(f), True) expr = mapnik.Expression("[num1].match('1')") eq_(expr.evaluate(f), True) expr = mapnik.Expression("[num2] = 1.0001") eq_(expr.evaluate(f), True) expr = mapnik.Expression("[num2].match('1.0001')") eq_(expr.evaluate(f), True)
def compare_wkb_from_wkt(wkt, num): f = mapnik.Feature(1) f.add_geometries_from_wkt(wkt) eq_(len(f.geometries()), num) paths = mapnik.Path.from_wkt(wkt) eq_(len(paths), num) eq_(f.geometries()[0].to_wkb(), paths[0].to_wkb()) paths2 = mapnik.Path() for path in paths: paths2.add_wkb(path.to_wkb()) eq_(len(paths2), num) eq_(f.geometries()[0].to_wkb(), paths2[0].to_wkb())
def test_add_geom_wkb(): # POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10)) wkb = '010300000001000000050000000000000000003e4000000000000024400000000000002440000000000000344000000000000034400000000000004440000000000000444000000000000044400000000000003e400000000000002440' context = mapnik.Context() f = mapnik.Feature(context, 1) eq_(len(f.geometries()), 0) f.add_geometries_from_wkb(unhexlify(wkb)) eq_(len(f.geometries()), 1) e = mapnik.Box2d() eq_(e.valid(), False) for g in f.geometries(): if not e.valid(): e = g.envelope() else: e += g.envelope() eq_(e, f.envelope())
def test_python_extended_constructor(): context = mapnik.Context() context.push('foo') context.push('foo') f = mapnik.Feature(context, 1) wkt = 'POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10),(20 30, 35 35, 30 20, 20 30))' f.geometry = mapnik.Geometry.from_wkt(wkt) f['foo'] = 'bar' eq_(f['foo'], 'bar') eq_(f.envelope(), mapnik.Box2d(10.0, 10.0, 45.0, 45.0)) # reset f['foo'] = u"avión" eq_(f['foo'], u"avión") f['foo'] = 1.4 eq_(f['foo'], 1.4) f['foo'] = True eq_(f['foo'], True)
def test_expressions_with_null_equality2(): for eq in null_equality: context = mapnik.Context() f = mapnik.Feature(context,0) f["prop"] = eq[0] eq_(f["prop"],eq[0]) if eq[0] is None: eq_(f["prop"] is None, True) else: eq_(isinstance(f['prop'],eq[2]),True,'%s is not an instance of %s' % (f['prop'],eq[2])) # TODO - support `is not` syntax: # https://github.com/mapnik/mapnik/issues/796 expr = mapnik.Expression("not [prop] is null") eq_(expr.evaluate(f),not eq[1]) # https://github.com/mapnik/mapnik/issues/1642 expr = mapnik.Expression("[prop] != null") eq_(expr.evaluate(f),not eq[1])
def test_char_escaping(): for char in chars: feat = mapnik.Feature(ctx,1) expected = char['test'] feat["name"] = expected eq_(feat["name"],expected) # confirm the python json module # is working as we would expect pyjson2 = json.loads(char['json']) eq_(pyjson2['properties']['name'],expected) # confirm our behavior is the same as python json module # for the original string geojson_feat_string = feat.to_geojson() eq_(geojson_feat_string,char['json'],"Mapnik's json escaping is not to spec: actual(%s) and expected(%s)" % (geojson_feat_string,char['json'])) # and the round tripped string pyjson = json.loads(geojson_feat_string) eq_(pyjson['properties']['name'],expected)
def test_creation_of_bool(): context = mapnik.Context() context.push('bool') f = mapnik.Feature(context, 0) f["bool"] = True eq_(f["bool"], True) # TODO - will become int of 1 do to built in boost python conversion # https://github.com/mapnik/mapnik/issues/1873 eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), True) f["bool"] = False eq_(f["bool"], False) eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), True) # test NoneType f["bool"] = None eq_(f["bool"], None) eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), False) # test integer f["bool"] = 0 eq_(f["bool"], 0)
def test_creation_of_bool(): context = mapnik.Context() context.push('bool') f = mapnik.Feature(context, 0) f["bool"] = True eq_(f["bool"], True) # TODO - will become int of 1 do to built in boost python conversion # is this fixable? eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], int), True) f["bool"] = False eq_(f["bool"], False) eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], int), True) # test NoneType f["bool"] = None eq_(f["bool"], None) eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], int), False) # test integer f["bool"] = 0 eq_(f["bool"], 0)
def test_geometry_type_eval(): # clashing field called 'mapnik::geometry' context2 = mapnik.Context() context2.push('mapnik::geometry_type') f = mapnik.Feature(context2, 0) f["mapnik::geometry_type"] = 'sneaky' expr = mapnik.Expression("[mapnik::geometry_type]") eq_(expr.evaluate(f), 0) expr = mapnik.Expression("[mapnik::geometry_type]") context = mapnik.Context() # no geometry f = mapnik.Feature(context, 0) eq_(expr.evaluate(f), 0) eq_(mapnik.Expression("[mapnik::geometry_type]=0").evaluate(f), True) # POINT = 1 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt('POINT(10 40)') eq_(expr.evaluate(f), 1) eq_(mapnik.Expression("[mapnik::geometry_type]=point").evaluate(f), True) # LINESTRING = 2 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt('LINESTRING (30 10, 10 30, 40 40)') eq_(expr.evaluate(f), 2) eq_( mapnik.Expression("[mapnik::geometry_type] = linestring").evaluate(f), True) # POLYGON = 3 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt( 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))') eq_(expr.evaluate(f), 3) eq_( mapnik.Expression("[mapnik::geometry_type] = polygon").evaluate(f), True) # COLLECTION = 4 f = mapnik.Feature(context, 0) geom = mapnik.Geometry.from_wkt( 'GEOMETRYCOLLECTION(POLYGON((1 1,2 1,2 2,1 2,1 1)),POINT(2 3),LINESTRING(2 3,3 4))' ) f.geometry = geom eq_(expr.evaluate(f), 4) eq_( mapnik.Expression("[mapnik::geometry_type] = collection").evaluate(f), True)
def make_tmp_map(): m = mapnik.Map(512,512) m.background_color = mapnik.Color('steelblue') ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') f = mapnik.Feature(context,1) f['Name'] = 'Hello' f.add_geometries_from_wkt('POINT (0 0)') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() sym = mapnik.MarkersSymbolizer() sym.allow_overlap = True r.symbols.append(sym) s.rules.append(r) lyr = mapnik.Layer('Layer') lyr.datasource = ds lyr.styles.append('style') m.append_style('style',s) m.layers.append(lyr) return m
def compare_wkb_from_wkt(wkt, num=None): # create a Path from geometry(s) # easy api, but slower #paths = mapnik.Path.from_wkt(wkt) # fast api paths = reader.read(wkt) # add geometry(s) to feature from wkt f = mapnik.Feature(mapnik.Context(), 1) f.add_geometries_from_wkt(wkt) # ensure both have same result # compare number of geometry parts if num: eq_(len(paths), num) eq_(len(f.geometries()), num) # compare collection off all geometries eq_(paths.to_wkb(mapnik.wkbByteOrder.XDR), f.geometries().to_wkb(mapnik.wkbByteOrder.XDR)) # compare all parts for idx, path in enumerate(paths): eq_(f.geometries()[idx].to_wkb(mapnik.wkbByteOrder.XDR), path.to_wkb(mapnik.wkbByteOrder.XDR)) # compare round trip paths2 = mapnik.Path() for path in paths: paths2.add_wkb(path.to_wkb(mapnik.wkbByteOrder.XDR)) # ensure result if num: eq_(len(paths2), num) eq_(paths2.to_wkb(mapnik.wkbByteOrder.XDR), paths.to_wkb(mapnik.wkbByteOrder.XDR)) for idx, path in enumerate(paths2): eq_(f.geometries()[idx].to_wkb(mapnik.wkbByteOrder.XDR), path.to_wkb(mapnik.wkbByteOrder.XDR))
def make_map(): ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') pixel_key = 1 f = mapnik.Feature(context, pixel_key) f['Name'] = str(pixel_key) f.add_geometries_from_wkt('POLYGON ((0 0, 0 256, 256 256, 256 0, 0 0))') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() symb = mapnik.PolygonSymbolizer() r.symbols.append(symb) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = ds lyr.styles.append('places_labels') width, height = 256, 256 m = mapnik.Map(width, height) m.append_style('places_labels', s) m.layers.append(lyr) m.zoom_all() return m
def compare_wkt_from_wkt(wkt, num=None): # create a Path from geometry(s) # easy api, but slower #paths = mapnik.Path.from_wkt(wkt) # fast api paths = reader.read(wkt) # add geometry(s) to feature from wkt f = mapnik.Feature(mapnik.Context(), 1) f.add_geometries_from_wkt(wkt) # compare to original, which may not have significant digits if '.' not in wkt: eq_(f.geometries().to_wkt().upper().replace('.0', ''), wkt) else: eq_(f.geometries().to_wkt().upper(), wkt) # ensure both have same result if num: eq_(len(paths), num) eq_(len(f.geometries()), num) eq_(paths.to_wkt(), f.geometries().to_wkt()) for idx, path in enumerate(paths): eq_(f.geometries()[idx].to_wkt(), path.to_wkt()) # compare round trip paths2 = mapnik.Path() for path in paths: paths2.add_wkt(path.to_wkt()) # ensure result if num: eq_(len(paths2), num) eq_(paths2.to_wkt(), paths.to_wkt()) for idx, path in enumerate(paths2): eq_(f.geometries()[idx].to_wkb(mapnik.wkbByteOrder.XDR), path.to_wkb(mapnik.wkbByteOrder.XDR))
def gen_grid_for_id(pixel_key): ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') f = mapnik.Feature(context,pixel_key) f['Name'] = str(pixel_key) f.add_geometries_from_wkt('POLYGON ((0 0, 0 256, 256 256, 256 0, 0 0))') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() symb = mapnik.PolygonSymbolizer() r.symbols.append(symb) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = ds lyr.styles.append('places_labels') width,height = 256,256 m = mapnik.Map(width,height) m.append_style('places_labels',s) m.layers.append(lyr) m.zoom_all() grid = mapnik.Grid(m.width,m.height,key='__id__') mapnik.render_layer(m,grid,layer=0,fields=['__id__','Name']) return grid
def test_render_layer_to_cairo_context(): ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') f = mapnik.Feature(context, 1) f['Name'] = 'poly' f.geometry = mapnik.Geometry.from_wkt( 'POLYGON ((1 1, -1 1, -1 -1, 1 -1, 1 1))') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() symb = mapnik.PolygonSymbolizer() symb.fill = mapnik.Color('red') r.symbols.append(symb) s.rules.append(r) lyr = mapnik.Layer('poly') lyr.datasource = ds lyr.styles.append('poly') m = mapnik.Map(256, 256) m.append_style('poly', s) m.layers.append(lyr) m.zoom_all() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, m.width, m.height) context = cairo.Context(surface) detector = mapnik.LabelCollisionDetector(m) mapnik.render_layer(m, context, detector, lyr) im = mapnik.Image.from_cairo(surface) eq_(im.is_solid(), True) c = im.get_pixel(0, 0, True) eq_(c.r, 255) eq_(c.g, 0) eq_(c.b, 0) eq_(c.a, 255)