パイクラおじさんの日記

MinecraftでPythonを勉強するおじさんの日記です。

XMLを配列にする部分の関数化

XMLを配列にする部分を関数化するに当たって、関数内でエラーが発生した場合、どうすりゃいいの?

「例外とか投げるのかな?」とググったら見つかった。

8. エラーと例外 — Python 3.6.1 ドキュメント

XML内に<gml:tupleList>が無い場合にExceptionを投げて、例外があってもゼロで初期化した配列を用意することでそのまま処理を続行するように組んでみた。

# coding: utf-8

import xml.etree.ElementTree as ET
import numpy as np
import matplotlib.pyplot as plot
import sys

GEO_DIR = "FG-GML-{0:04d}-{1:02d}-DEM5A"
GEO_XML = "FG-GML-{0:04d}-{1:02d}-{2:02d}-DEM5A-20161001.xml"

def xml2array(mesh1, mesh2, mesh3):
    dir = GEO_DIR.format(mesh1, mesh2)
    fname = GEO_XML.format(mesh1, mesh2, mesh3)

    tree = ET.parse(dir+"/"+fname)
    root = tree.getroot()

    tl = root.find('./{http://fgd.gsi.go.jp/spec/2008/FGD_GMLSchema}DEM/{http://fgd.gsi.go.jp/spec/2008/FGD_GMLSchema}coverage/{http://www.opengis.net/gml/3.2}rangeSet/{http://www.opengis.net/gml/3.2}DataBlock/{http://www.opengis.net/gml/3.2}tupleList')
    if tl is None:
        raise Exception("{http://www.opengis.net/gml/3.2}tupleList is not found")

    lines = tl.text.split()
    array = np.zeros(len(lines))
    i = 0
    for l in lines:
        (t, h) = l.split(",")
        hval = float(h)
        if hval == -9999:
            array[i] = -9
        else:
            array[i] = hval
        i += 1

    return array.reshape((150, 225))


# ここからスタート

if len(sys.argv) < 3:
    print("plotall.py mesh1 mesh2")
    exit(-1)

mesh1 = int(sys.argv[1])
mesh2 = int(sys.argv[2])

yarray = None
for y in range(10):
    xarray = None
    for x in range(10):
        try:
            mesh3 = y * 10 + x
            array = xml2array(mesh1, mesh2, mesh3)
        except Exception as err:
            print(err)
            array = np.zeros((150, 225))
        finally:
            if xarray is None:
                xarray = array
            else:
                xarray = np.concatenate((xarray, array), axis=1)
        
    if yarray is None:
        yarray = xarray
    else:
        yarray = np.concatenate((xarray, yarray), axis=0)

print(yarray.shape)

plot.imshow(yarray)
plot.colorbar()
plot.show()

yarrayにxarrayを結合する際の順番に注意(下から上に積んでいくので)すれば、すぐにできた!

$ python plotall.py 5340 22
(1500, 2250)

f:id:pycra:20170917233738p:plain
Fig. 100

川もあるね。