Geo::Reader に属性ホワイトリストを実装

Geo::Reader に、Ruby レベルまで取り出す属性のホワイトリストを指定する機能を実装しました。Geo::Reader::foreach の引数を、open-uri の流儀を参考に、少し変更しています:

Geo::Reader::foreach(filename, options) {|geom, attrs|} filename で指定された Shapefile を開いて、その1レコードごとに、幾何属性を geom に、主題属性をハッシュ attrs に格納して渡します。第二引数 options はハッシュで渡します。

options に使えるキーとその値は、以下の通りです。

キー
:sjis_workaround true のとき、Shift_JIS の主題属性を (UTF-8)文字列として戻すようにします。
:whitelist Ruby レベルまで取り出す属性名を配列として渡します。例 {:whitelist => ['exs]}

属性によって取り出すレコードを制限するフィルタというのは一般的で、例えば GeoTools の org.geotools.filter まわりで、AttributeExpression などはそのあたりのために使うように記憶しています。しかし、取り出す「レコード」ではなくて取り出す「属性」を制限するというアイディアは、それほど見たことはありませんでした。
では、この属性ホワイトリスト機能、どの程度の効果があるのでしょうか。

ベンチマーク結果

まず、今回の更新で、the_geom 属性を取り出さないなどのちょっとした改良をしているので、ホワイトリストを使わない場合の、全レコード読み出し+書き込みの速度を比較してみました:

JRuby 184秒
Rjb primitive_conversion版 175秒
Rjb ユーザレベル型変換版 202秒

次に、属性ホワイトリストを利用し、

Geo::Reader.foreach('transl_1_1.shp', {:whitelist => ['exs']}) do |geom, attrs|

とした場合、このようになりました。

JRuby 37秒
Rjb primitive_conversion版 31秒
Rjb ユーザレベル型変換版 32秒

実は、たぶん OS レベルで IO をキャッシュしたりしてくれるかもしれないので、上記の数値の「有効数字」は、もっと少ない気もしています。
いずれにしても、属性ホワイトリストが効果的な場合がありそうだということは分かりました。

Rjb と JRuby の、java.lang.String の扱いの違い

エントリ化が遅れて申し訳ないのですが、現時点の primitive_conversion = true モードの Rjb と異なり、JRuby では java.lang.String も Ruby::String に自動変換されるようです。primitive_conversion = true のとき、プリミティブ型クラスの変換をしますが、String 型の変換はしないため、

  • Rjb は java.lang.String のオブジェクトを返す。
  • JRubyruby の String オブジェクトを返す。

という違いがあります。

現時点の 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.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}
    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 # same as the one for rjb 1.0.7 #TODO: DRY
        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 # same as the one for jruby #TODO: DRY
          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
      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

    ## TODO: def transform(geom)
    ## 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') 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