Shapefile の座標変換

平面極核座標系 IX 系に座標変換した地

geotools.rb を使って Shapefile データの座標変換をする方法をまとめてみます。
お題は、

地球地図日本の茨城県の行政界データを平面直角座標系 IX 系に変換する。

というものです。行政界、というより行政区画データと言った方が正しいかもしれません。
このお題を解くために、geotools.rb のクラス Transform に以下のメソッドを追加しました。

Transform#transform(geom) 引数で与えられた幾何オブジェクトを座標変換して返す

材料

http://www.globalmap.org/download/kanni01.html から、地球地図日本バージョン 1.1 行政域 (行政区画のほうが良い名前かも) データ(http://www.globalmap.org/download/data/shp/1_1/bnda_1_1.zip)を入手しました。

調査ツール

Shapefile の内容を確認するには、

$ ogrinfo -al bnda_1_1.shp

なんかが便利です。可視化には QGISが便利。

アプリケーションコード実装

属性をコピーしないなら、こんな感じ:

require 'geotools'

t = Geo::Transform.new(
  Geo::import_epsg_crs(4326), Geo::import_epsg_crs(2451))

Geo::Writer.open('ibaraki_2451.shp') do |w|
  Geo::Reader.foreach('bnda_1_1.shp', {:whitelist => 'nam'}) do |geom, attrs|
    next unless attrs['nam'] == 'IBARAKI'
    w.write(t.transform(geom), {})
  end
end

属性をコピーするなら、こんな感じ:

require 'geotools'

t = Geo::Transform.new(
  Geo::import_epsg_crs(4326), Geo::import_epsg_crs(2451))

Geo::Writer.open('ibaraki_2451_attrs.shp') do |w|
  Geo::Reader.foreach('bnda_1_1.shp') do |geom, attrs|
    next unless attrs['nam'] == 'IBARAKI'
    w.write(t.transform(geom), attrs)
  end
end

これで座標変換された Shapefile データ、ibaraki_2451(_attrs).shp が手に入ります。GeoTools を裸で使うのと比べ、ずいぶんシンプルにできたと思っています。

アプリケーションコード実行時間

実行時間はこの程度です:

$ time ruby proj.rb
DEBUG: rjb primitive_conversion mode

real    0m2.224s
user    0m1.894s
sys     0m0.246s
$ time ruby proj_attrs.rb
DEBUG: rjb primitive_conversion mode

real    0m2.630s
user    0m2.367s
sys     0m0.246s

geotools.rb 実装

現時点の geotools.rb の実装はこのようになっています。

# this code is under development and subject to major change.
require 'iconv'

module Geo
  # Geo::Tools module, to include nesessary classes from Geotools
  module Tools
    QUALIFIED_NAMES = %w{java.lang.System java.lang.String java.lang.Integer java.lang.Double java.lang.Long java.io.File java.util.HashMap org.geotools.data.shapefile.ShapefileDataStore org.geotools.feature.AttributeTypeFactory org.geotools.feature.FeatureTypeBuilder org.geotools.feature.type.GeometricAttributeType com.vividsolutions.jts.io.WKTReader org.geotools.referencing.crs.EPSGCRSAuthorityFactory org.geotools.referencing.operation.DefaultCoordinateOperationFactory org.geotools.geometry.DirectPosition2D org.geotools.data.vpf.file.VPFFile org.geotools.data.vpf.VPFLibrary org.geotools.gce.geotiff.GeoTiffWriter org.geotools.coverage.grid.GridCoverageFactory com.vividsolutions.jts.geom.Envelope org.geotools.geometry.Envelope2D org.geotools.factory.Hints org.geotools.geometry.jts.JTS}
    begin
      require 'rjb'
      QUALIFIED_NAMES.each do |qn|
        sn = qn.split('.').last
        module_eval "#{sn} = Rjb::import('#{qn}')"
      end
      IMPLEMENTATION = 'rjb'
    rescue LoadError
      require 'java'
      QUALIFIED_NAMES.each do |qn|
        include_class qn
      end
      IMPLEMENTATION = 'java'
    end
  end

  # Geo module variables
  @@wkt_reader = nil
  @@epsg_crs_authority_factory = nil

  # Geo module 'good-wrapper' / 'Grossklasstum' classes
  class Reader
    if Tools::IMPLEMENTATION == 'java'
      print "DEBUG: jruby mode\n"
      def iterate
        while(@iter.hasNext)
          feat = @iter.next
          attrs = {}
          @attr_names.each do |attr_name|
            attrs[attr_name] = feat.getAttribute(attr_name)
          end
          yield feat.getDefaultGeometry, attrs
        end
      end
    else
      begin
        Rjb::primitive_conversion = true
        print "DEBUG: rjb primitive_conversion mode\n"
        def iterate
          while(@iter.hasNext)
            feat = @iter.next
            attrs = {}
            @attr_names.each do |attr_name|
              attr = feat.getAttribute(attr_name)
              attr = attr.toString if attr.getClass == Geo::Tools::String
              attrs[attr_name] = attr
            end
            yield feat.getDefaultGeometry, attrs
          end
        end
      rescue NoMethodError
        print "DEBUG: rjb conventional mode\n"
        def iterate
          while(@iter.hasNext)
            feat = @iter.next
            attrs = {}
            @attr_names.each do |attr_name|
              attr = feat.getAttribute(attr_name)
              if attr.getClass.equals(Tools::Integer)
                attr = attr.intValue
              elsif attr.getClass.equals(Tools::Double)
                attr = attr.doubleValue
              elsif attr.getClass.equals(Tools::String)
                if @sjis_workaround
                  attr = Iconv.conv('UTF-8', 'Shift_JIS', attr.getBytes('iso-8859-1'))
                else
                  attr = attr.toString
                end
              elsif attr.getClass.equals(Tools::Long)
                attr = attr.longValue
              end
              attrs[attr_name] = attr
            end
            yield feat.getDefaultGeometry, attrs
          end
        end
      end
    end

    # keys for options: :sjis_workaround (boolean), :whitelist (array)
    def Reader::foreach(shapefile, options = {})
      r = Reader.new(shapefile, options)
      r.iterate do |geom, attrs|
        yield geom, attrs
      end
      r.close
    end

    def initialize(shapefile, options = {})
      @sjis_workaround = options[:sjis_workaround]
      @sjis_workaround = false if @sjis_workaround == nil
      if(Tools::IMPLEMENTATION == 'java' && @sjis_workaround)
        raise "sjis_workaround for JRuby is not implemented."
      end
      store = Tools::ShapefileDataStore.new(Tools::File.new(shapefile).toURL)
      @iter = store.getFeatureSource.getFeatures.features
      feat_type = store.getFeatureSource.getSchema
      if options[:whitelist] == nil
        @attr_names = []
        feat_type.getAttributeCount.times do |i|
          name = feat_type.getAttributeType(i).getName
          @attr_names << name unless name == 'the_geom'
        end
      else
        @attr_names = options[:whitelist]
        #TODO: whitelist checking necessary?
      end
    end

    def close
      @iter.close
    end
  end

  class Writer
    def Writer::open(shapefile)
      w = Writer.new(shapefile)
      yield w
      w.close
    end

    def initialize(shapefile)
      @shapefile = shapefile
      @writer = nil
      @first = true
    end
    
    def setup(geom, attrs)
      attrs.delete('the_geom')
      ftb = Tools::FeatureTypeBuilder.newInstance(@shapefile)
      attrs.each do |key, value|
        if value.methods.include?('_classname')
          attr_class = value.getClass
        elsif value.class == String
          attr_class = Tools::String
        elsif value.class == Fixnum
          attr_class = Tools::Integer
        elsif value.class == Float
          attr_class = Tools::Double
        else
          raise "attribute #{key} has unrecognizable class #{value.class}"
        end
        ftb.addType(Tools::AttributeTypeFactory.newAttributeType(key, attr_class))
      end
      if geom.class == String
        geom = import_wkt_geometry(geom)
      end
      ftb.setDefaultGeometry(Tools::GeometricAttributeType.new('the_geom', geom.getClass, true, nil, nil, nil))
      ft = ftb.getFeatureType
      store = Tools::ShapefileDataStore.new(Tools::File.new(@shapefile).toURL)
      store.createSchema(ft)
      @writer = store.getFeatureWriter(@shapefile, store.getFeatureSource(@shapefile).getTransaction)
      @first = false
    end
    private :setup

    def write(geom, attrs)
      setup(geom, attrs) if @first
      feat = @writer.next
      if geom.class == String
        geom = import_wkt_geometry(geom)
      end
      feat.setDefaultGeometry(geom)
      attrs.each do |key, value|
        feat.setAttribute(key, value)
      end
      @writer.write
    end

    def close
      @writer.close unless @writer == nil
    end
  end

  class Transform
    def initialize(src_crs, dst_crs)
      cof = Geo::Tools::DefaultCoordinateOperationFactory.new
      @co = cof.createOperation(src_crs, dst_crs)
      @mt = @co.getMathTransform
    end

    def transform(x, y) # z?
      r = Geo::Tools::DirectPosition2D.new
      @mt.transform(Geo::Tools::DirectPosition2D.new(x, y), r)
      return r.x, r.y
    end

    def transform(geom)
      Geo::Tools::JTS::transform(geom, @mt)
    end

    ## TODO: accessor to @mt or @co
  end

  # Geo module convenient methods
  def Geo::import_wkt_geometry(wkt)
    @@wkt_reader = Geo::Tools::WKTReader.new if @@wkt_reader == nil
    @@wkt_reader.read(wkt)
  end

  def Geo::import_epsg_crs(epsg_code)
    @@epsg_crs_authority_factory = Geo::Tools::EPSGCRSAuthorityFactory.new if @@epsg_crs_authority_factory == nil
    if epsg_code.class == Fixnum
      return @@epsg_crs_authority_factory.createCoordinateReferenceSystem("EPSG:#{epsg_code}")
    elsif epsg_code.class == String
      return @@epsg_crs_authority_factory.createCoordinateReferenceSystem(epsg_code)
    else
      raise "Geo::import_epsg_crs: can not handle epsg_code = #{epsg_code}"
    end
  end

  def dms2dec(d, m, s)
    d + m / 60.0 + s / 3600.0
  end

  def dec2dms(dec)
    #TODO
    raise "not implemented."
  end
end

# ad hoc tests
if __FILE__ == $0
  ## TODO: better separate tests as unit tests.
  start_time = Time.now
  Geo::Writer.open('test.shp') do |w|
    Geo::Reader.foreach('transl_1_1.shp', {:whitelist => ['exs']}) do |geom, attrs|
      #print "#{attrs.inspect}\n"
      w.write(geom, attrs)
    end
  end
  print "#{Time.now - start_time} sec.\n"
  
  exit # ここから下は別の話題
  ix = Geo::import_epsg_crs(2451)       # EPSG:2451 - 平面直角座標系 IX 系
  wgs84 = Geo::import_epsg_crs(4326)    # EPSG:4326 - WGS84
  
  t = Geo::Transform.new(ix, wgs84)     # IX 系から WGS84 への座標変換器
  t_inv = Geo::Transform.new(wgs84, ix) # WGS84 から IX 系への座標変換器
  
  pt = t.transform(0, 0)                 # IX 系の原点を WGS84 に座標変換
  pt_inv = t_inv.transform(pt[0], pt[1]) # その点を IX 系に戻す。元に戻るか?
  
  print "IX origin is #{pt.inspect} in WGS84\n"
  print "#{pt_inv.inspect} must be (0, 0)\n"
end