def test_stringio(): s = u"""MAP NAME "TEST" END""" ip = io.StringIO(s) d = mappyfile.load(ip) assert d["name"] == "TEST"
def test_include_from_filehandle(): fn = './tests/samples/include1.map' with open(fn) as f: d = mappyfile.load(f) assert d["name"] == "include_test" print(mappyfile.dumps(d))
def main(): parser = argparse.ArgumentParser() parser.add_argument("mapfile") args = parser.parse_args() mapfile = io.open(args.mapfile, "r", encoding="utf-8") mf = mappyfile.load(mapfile) if len(sys.argv) == 3: sys.stdout = open(sys.argv[2], 'w') json.dump(mf, sys.stdout, indent=4)
def test_dump(): s = """MAP NAME "TEST" END""" d = mappyfile.loads(s) with tempfile.NamedTemporaryFile(mode="w+", delete=False) as fp: mappyfile.dump(d, fp) with open(fp.name) as fp: d = mappyfile.load(fp) assert d["name"] == "TEST"
def test_save(): s = """MAP NAME "TEST" END""" d = mappyfile.loads(s) output_file = os.path.join(tempfile.mkdtemp(), 'test_mapfile.map') mappyfile.save(d, output_file) with open(output_file) as fp: d = mappyfile.load(fp) assert d["name"] == "TEST"
def main(): mf = "./docs/examples/geometry/geometry.map" mapfile = mappyfile.load(mf) mapfile["size"] = [600, 600] output_folder = os.path.join(os.getcwd(), "docs/images") dilated = dilation(mapfile) create_image("dilated", mapfile, output_folder=output_folder) erosion(mapfile, dilated) create_image("erosion", mapfile, output_folder=output_folder)
def test(): # START OF API EXAMPLE # load will accept a filename (loads will accept a string) mapfile = mappyfile.load("./docs/examples/raster.map") # search for a layer by name layer = mappyfile.find(mapfile['layers'], 'name', 'sea') print(layer['name']) # "sea" # search for all layers in a group for layer in mappyfile.findall(mapfile['layers'], 'group', 'my_group'): print(layer['name']) # END OF API EXAMPLE assert (layer['name'] == 'sea')
def test(): # START OF API EXAMPLE # load will accept a filename (loads will accept a string) mapfile = mappyfile.load("./docs/examples/raster.map") # print the map name print(mapfile["name"]) # "MyMap" # access layers layers = mapfile["layers"] layer2 = layers[1] # access by index # access classes in a layer classes = layer2["classes"] for c in classes: print(c["name"]) # END OF API EXAMPLE assert (mapfile["name"] == '"MyMap"')
def test(): mapfile = mappyfile.load("./docs/examples/raster.map") # START OF API EXAMPLE # update the map name mapfile["name"] = "MyNewMap" # update a layer name layers = mapfile["layers"] layer = layers[0] layer["name"] = "MyLayer" # update the error file path in the map config section # note key names currently need to be lower case mapfile["config"]["ms_errorfile"] = "/ms4w/tmp/ms_error.txt" mapfile["config"]["ON_MISSING_DATA"] = "IGNORE" # update the web metadata settings # currently we need to add quotes for non-keyword keys and values mapfile["web"]["metadata"]["'wms_format'"] = "'image/png'" print(mappyfile.dumps(mapfile["web"])) # print out just the WEB section # alternatively we can parse the Mapfile syntax and load it directly s = """ METADATA 'wms_enable_request' '*' 'wms_feature_info_mime_type' 'text/html' 'wms_format' 'image/jpg' END""" metadata = mappyfile.loads(s) mapfile["web"]["metadata"] = metadata print(mappyfile.dumps(mapfile)) # END OF API EXAMPLE assert(layer["name"] == "MyLayer") assert(mapfile["web"]["metadata"]["'wms_format'"] == "'image/jpg'")
def read_mapfile(fn, output_folder): mf = mappyfile.load(fn) quoter = Quoter() includes = [] for l in (mf["layers"]): layer_file = quoter.remove_quotes(l["name"]) + ".txt" ofn = os.path.join(output_folder, layer_file) mappyfile.write(l, ofn) includes.append(quoter.add_quotes(layer_file)) # now write the mapfile with includes ofn = os.path.join(output_folder, "_" + os.path.basename(fn)) del mf["layers"] existing_includes = mf["include"] if (len(existing_includes)) > 0: mf["include"] += includes else: mf["include"] = includes mappyfile.write(mf, ofn)
def main(): mf = "./docs/examples/animation/animated_buffer.map" mapfile = mappyfile.load(mf) img_files = create_frames(mapfile) create_animation(img_files)
def mapForDir(dir, dir_out): if not dir: dir = "." if not dir_out: dir_out = dir print('Creating a mapfile for dir ' + dir) # read (or create) root metadata file, todo: delegate to utils try: # Open the file and load the file with open(os.path.join(dir, 'index.yml'), mode="r", encoding="utf-8") as f: cnf = yaml.load(f, Loader=SafeLoader) print(cnf) except FileNotFoundError: cnf = { "name": os.path.basename(os.path.normpath(dir)), "abstract": "", "mode": "dir", "contact": { "name": "", "organisation": "", "email": "" }, "keywords": [""], "license": "", "mode": "index" } try: with open(os.path.join(dir, 'index.yml'), 'w') as f: yaml.dump(cnf, f) except Exception as e: print(e) except Exception as e: print(e) # initalise default mapfile tpl = pkg_resources.open_text(templates, 'default.map') mf = mappyfile.load(tpl) lyrs = mf['layers'] # set up header mf["name"] = cnf.get("name", "default") mf["web"]["metadata"]["ows_title"] = cnf.get("name", "default") mf["web"]["metadata"]["ows_abstract"] = cnf.get("abstract", "default") if ("abstract" in cnf): mf["web"]["metadata"]["ows_abstract"] = cnf.get("abstract") # if mode=tree/dir, build the index # todo: interate nested file structure # loop over index if 'index' not in cnf: print('No files in dir') else: for ly in cnf['index']: # fetch layer details sf = ly.get("path", '') base, ext = sf.rsplit('.', 1) if not sf.startswith("/"): sf = os.path.join(dir, sf) cnt = indexSpatialFile(sf, ext) if cnt: cnt['name'] = ly.get('name', cnt.get('name', 'unknown')) print("Processing layer {0}".format(cnt['name'])) cnt['title'] = ly.get('title', cnt.get('title', cnt['name'])) cnt['crs'] = ly.get('crs', cnt.get('crs', '')) if (cnt['crs'] == ''): cnt['crs'] = cnf.get("crs", 'epsg:4326') print("Original type is '{0}'".format(cnt['type'])) if (cnt['type'].lower() == "raster"): cnt['type'] = 'raster' elif (cnt['type'].lower() in [ "linestring", "line", "multiline", "polyline", "wkblinestring" ]): cnt['type'] = 'polygon' elif ( cnt['type'].lower() in ["point", "multipoint", "wkbpoint", "table"] ): # table is suggested for CSV, which is usually point (or none) cnt['type'] = 'point' else: cnt['type'] = 'polygon' try: cnt['extent'] = "{0} {1} {2} {3}".format( cnt['bounds'][0], cnt['bounds'][1], cnt['bounds'][2], cnt['bounds'][3]) except: cnt['extent'] = "-180 -90 180 90" cf = ly.get("style", '') if (cf == '' and cnt['type'] == 'raster'): # set colors for range rng = cnt.get('max', 0) - cnt.get('min', 0) if rng > 0: sgmt = rng / 8 cur = cnt.get('min', 0) new_class_string2 = "" for clr in [ "'#fcfdbf'", "'#fec085'", "'#fa825f'", "'#e14d67'", "'#ae347c'", "'#782282'", "'#440f76'", "'#150e37'" ]: new_class_string2 += "CLASS\nNAME '{0} - {1}'\nEXPRESSION ( [pixel] >= {0} AND [pixel] <= {1} )\nSTYLE\nCOLOR {2}\nEND\nEND\n\n".format( cur, cur + sgmt, clr) cur += sgmt print(new_class_string2) else: if not cf.startswith("/"): cf = os.path.join(dir, sf) try: with open(cf) as f1: new_class_string = f1.read() print( "Failed opening '{0}', use default style for '{1}'" .format(ly.get("style", ""), cnt['type'])) except: new_class_string2 = pkg_resources.read_text( templates, 'class-' + cnt['type'] + '.tpl') if (cnt['type'] == 'raster' ): # fetch nodata from meta in file properties new_class_string2 = 'PROCESSING "NODATA=' + str( cnt.get('meta', {}).get( 'nodata', -32768)) + '"\n' + new_class_string2 # prepare layer new_layer_string = pkg_resources.read_text( templates, 'layer.tpl') strLr = new_layer_string.format( name=cnt['name'], title=cnt['name'], abstract=ly.get('abstract', ''), type=cnt['type'], path=ly["path"], template=ly.get('template', 'info.html'), projection=cnt['crs'], projections=ly.get('projections', 'epsg:4326 epsg:3857'), extent=cnt['extent'], mdurl=cnf.get('mdUrlPattern', '').format(ly.get('uuid', '')), classes=new_class_string2) try: mslr = mappyfile.loads(strLr) lyrs.insert(len(lyrs) + 1, mslr) except Exception as e: print("Failed creation of layer {0}; {1}".format( cnt['name'], e)) # map should have initial layer, remove it lyrs.pop(0) # print(mappyfile.dumps(mf)) mappyfile.save(mf, os.path.join(dir_out, cnf['name'] + ".map"), indent=4, spacer=' ', quote='"', newlinechar='\n', end_comment=False, align_values=False)
import mappyfile import json mf = mappyfile.load("./docs/examples/after.map") with open("./docs/examples/sample.json", "w") as f: json.dump(mf, f, indent=4) s = """ MAP NAME "sample" STATUS ON SIZE 600 400 SYMBOLSET "../etc/symbols.txt" EXTENT -180 -90 180 90 UNITS DD SHAPEPATH "../data" IMAGECOLOR 255 255 255 FONTSET "../etc/fonts.txt" # # Start of web interface definition # WEB IMAGEPATH "/ms4w/tmp/ms_tmp/" IMAGEURL "/ms_tmp/" END # WEB # # Start of layer definitions # LAYER
import mappyfile mapfile = mappyfile.load("./docs/examples/raster.map") def test_layer(): # START OF ADD LAYER EXAMPLE layers = mapfile["layers"] new_layer_string = """ LAYER NAME 'land' TYPE POLYGON DATA '../data/vector/naturalearth/ne_110m_land' CLASS STYLE COLOR 107 208 107 OUTLINECOLOR 2 2 2 WIDTH 1 END END END """ new_layer = mappyfile.loads(new_layer_string) layers.insert(0, new_layer) # can insert the new layer at any index # END OF ADD LAYER EXAMPLE assert(layers[0]['name'] == "land") def test_class(): # START OF ADD CLASS EXAMPLE # find a layer using its name
import mappyfile_geojson import geojson gj = '''{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [30, 10], [40, 40], [20, 40], [10, 20], [30, 10] ] } }''' # load a string into a GeoJSON object gj = geojson.loads(gj) # convert it to a mappyfile layer dict layer = mappyfile_geojson.convert(gj, extent_buffer=10) # now load a Mapfile mf = mappyfile.load("example.map") # find an existing layer by name map_layer = mappyfile.find(mf["layers"], "name", "Polygon") # apply the FEATURES from GeoJSON to the layer map_layer.update(layer) # update the map extent to the extent of the features mf["extent"] = layer["extent"] # we now have a layer populated from the GeoJSON s = mappyfile.dumps(mf) print(s)
def test_unicode_map(): with open('./tests/samples/unicode.map', "r") as mf_file: mf = mappyfile.load(mf_file) print(mappyfile.dumps(mf))
import mappyfile mf = mappyfile.load("./docs/examples/before.map") mappyfile.write(mf, "./docs/examples/after.map")