Class: When::Events::DataSet

Inherits:
Object
  • Object
show all
Defined in:
lib/when_exe/events.rb

Overview

一言語対応データセット

特定の言語用データセットを保持する

Defined Under Namespace

Modules: ExternalRepository, SparqlRepository

Constant Summary collapse

Operations =

オブジェクト操作対応付け

Hash.new(nooperation).merge({
  URI               => to_uri,
  IRI               => to_uri,
  INTEGER           => to_i,
  FLOAT             => to_f,
  DOUBLE            => to_f,
  [:first, INTEGER] => first_to_i,
  [:first, FLOAT  ] => first_to_f,
  [:first, DOUBLE ] => first_to_f,
  [:last,  INTEGER] => last_to_i,
  [:last,  FLOAT  ] => last_to_f,
  [:last,  DOUBLE ] => last_to_f,
  RANGE             => to_range,
  DATE              => to_date,
  TIME              => to_time,
  DATETIME          => to_date_time,

  WEST              => to_long,
  EAST              => to_long,
  SOUTH             => to_lat,
  NORTH             => to_lat,
  BOTTOM            => to_alt,
  TOP               => to_alt
})

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(definitions, language = '', uri = '', parent = nil, &block) ⇒ DataSet

一言語対応データセットを生成する

Parameters:

  • definitions (Array<Array<Array<String>, String>>)

    定義行の情報

  • language (String) (defaults to: '')

    言語コード

  • uri (String) (defaults to: '')

    定義の所在のルート(ts:referenceが相対位置の場合に使用)

  • parent (When::Events::DataSets) (defaults to: nil)

    所属する多言語対応データセット

  • block (Block)

    キャッシュされたファイルパスの読み替え処理

Raises:

  • (IOError)


1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
# File 'lib/when_exe/events.rb', line 1279

def initialize(definitions, language='', uri='', parent=nil, &block)
  @language = language
  @parent   = parent
  @prefix   = {}
  @role     = {}
  @rdf      = {}
  @csv      = {}
  @l_to_i   = {}
  @i_to_l   = {}
  @role_for_dataset = {}
  @definitions = definitions
  @definitions.each do |definition, lang|
    parameters = definition[1..2].map {|item| item.strip}
    case definition.first
    when /\A(.+):\z/
      @prefix[$1] = parameters
    when /\A\[(.+)\]\z/
      key=extract($1)
      @csv[key ] = operation(key, parameters, lang)
    when /\A<(.+)>\z/
      key=extract($1)
      @rdf[key ] = operation(key, parameters, lang)
    when /\A\{(.+)\}\z/
      key=extract($1)
      (DataSet.for_dataset?(parameters.first, key) ? @role_for_dataset : @role)[key] = operation(key, parameters, lang)
    end
  end
  @prefix_description  = @prefix.values.reject {|value| value.size < 2}.sort_by {|value| -value.first.length}
  @namespace_to_prefix = @prefix.invert.sort.reverse
  @used_ns  = {}
  @resource = Hash.new {|hash,key|
    @namespace_to_prefix.each do |prefix|
      index = key.index(prefix.first.first)
      if index && index == 0
        @used_ns[prefix.last] = prefix.first.first
        break
      end
    end
    hash[key] = ::RDF::URI.new(key)
  }

  @events = []
  @index  = {}
  (@role.keys + @rdf.keys + @csv.keys).each {|item| @index[item] = Hash.new {|hash,key| hash[key]=[]}}
  target = @role_for_dataset[REFERENCE][:target]
  unless target =~ /:/ # Relative path
    path     = uri.split('/')
    path[-1] = target
    target   = path.join('/')
  end
  operation = @role_for_dataset[REFERENCE][:original]
  source    = extract(target)
  source    = yield(source) if block_given? && operation !~ /SPARQL|CalendarEra/i
  raise IOError, target + ': not ready' unless source
  for_each_record(source, operation) do |row|
    begin
      event = Event.new(self, @events.size+1, row)
      @events << event
  
      @role.keys.each do |item|
        case item
        when LABEL, REFERENCE
        when HAS_PART
          if event.role[HAS_PART].kind_of?(Array)
            event.role[HAS_PART].each do |word|
              @index[HAS_PART][word] << @events.size
            end
          else
            event.each_word do |word|
              @index[HAS_PART][word] << @events.size
            end
          end
        when WHAT_DAY
          date = event.role[WHAT_DAY]
          key = [date.class.to_s !~ /\AWhen/ ||
                 date.frame.kind_of?(When::CalendarTypes::Christian),
                 date.month * 1, date.day]
          @index[WHAT_DAY][key] << @events.size
        else
          add_index(:role, item)
        end
      end
  
      [:rdf, :csv].each do |method|
        send(method).keys.each do |item|
          add_index(method, item)
        end
      end
    rescue => exception
      puts "#{source}##{@events.size+1}: #{exception}"
    # puts exception.backtrace
    end
  end

  @order = {}
  [:role, :rdf, :csv].each do |method|
    send(method).each_pair do |item, definition|
      next unless definition[:index] == :order
      @order[item] = (1..@events.size).to_a.sort_by {|id| @events[id-1].send(method)[item]}
      @order[item].each_with_index do |id, index|
        @events[id-1].order[item] = index + 1
      end
    end
  end
  @index.each_value do |hash|
    hash.each_value do |value|
      value.uniq!
      value.sort_by! {|id| @events[id-1].order[START]} if @order.key?(START)
    end
  end

  @default_graph   = $1 if @role.key?(SUBJECT) && /\A(.+)<(.+)>\z/ =~ extract(@role[SUBJECT][:target])
  @default_graph ||= parent.iri if parent
end

Instance Attribute Details

#csvHash<String(prefix:name)=>Hash> (readonly)

CSV変数の定義

Returns:

  • (Hash<String(prefix:name)=>Hash>)


749
750
751
# File 'lib/when_exe/events.rb', line 749

def csv
  @csv
end

#default_graphString(URI) (readonly)

デフォルト Graph の URI

Returns:



714
715
716
# File 'lib/when_exe/events.rb', line 714

def default_graph
  @default_graph
end

#definitionsArray<String> (readonly)

定義行の元情報

Returns:



700
701
702
# File 'lib/when_exe/events.rb', line 700

def definitions
  @definitions
end

#eventsWhen::Events::Event (readonly)

時間座標を持つイベント

Returns:



707
708
709
# File 'lib/when_exe/events.rb', line 707

def events
  @events
end

#indexHash<String(prefix:name)=>Hash<String(key)=>Array>> (readonly)

一致キーのためのインデクス

Returns:



756
757
758
# File 'lib/when_exe/events.rb', line 756

def index
  @index
end

#languageString (readonly)

自身の言語

Returns:



686
687
688
# File 'lib/when_exe/events.rb', line 686

def language
  @language
end

#orderHash<String(prefix:name)=>Array> (readonly)

順序キーのためのインデクス

Returns:



763
764
765
# File 'lib/when_exe/events.rb', line 763

def order
  @order
end

#parentWhen::Events::DataSets (readonly)

所属する多言語対応データセット



693
694
695
# File 'lib/when_exe/events.rb', line 693

def parent
  @parent
end

#prefixHash<String(prefix)=>String(namespace)> (readonly)

名前空間

Returns:



721
722
723
# File 'lib/when_exe/events.rb', line 721

def prefix
  @prefix
end

#prefix_descriptionArray<Array<String(namespace), String(description)>> (readonly)

名前空間の説明

Returns:



728
729
730
# File 'lib/when_exe/events.rb', line 728

def prefix_description
  @prefix_description
end

#rdfHash<String(prefix:name)=>Hash> (readonly)

RDF変数の定義

Returns:

  • (Hash<String(prefix:name)=>Hash>)


742
743
744
# File 'lib/when_exe/events.rb', line 742

def rdf
  @rdf
end

#resourceHash<String(iri)=>::RDF::URI> (readonly)

データセットで使用しているRDF::URI リソース

Returns:

  • (Hash<String(iri)=>::RDF::URI>)


770
771
772
# File 'lib/when_exe/events.rb', line 770

def resource
  @resource
end

#roleHash<String(prefix:name)=>Hash> (readonly)

ロール変数の定義

Returns:

  • (Hash<String(prefix:name)=>Hash>)


735
736
737
# File 'lib/when_exe/events.rb', line 735

def role
  @role
end

#used_nsHash<String(prefix)=>String(namespace)> (readonly)

RDF::URI リソースで使用された prefix - namespace 対

Returns:



777
778
779
# File 'lib/when_exe/events.rb', line 777

def used_ns
  @used_ns
end

Instance Method Details

#edge_included(edge, range, method = :to_i) ⇒ Array<Integer>

順序キーによる検索

Parameters:

  • edge (String)

    順序キー(ts:start, ts:until, ts:west, ts:east, ts:south, ts:north, ts:bottom, ts:top)

  • range (Range)

    絞り込む範囲

  • method (Symbol) (defaults to: :to_i)

    スカラー化メソッドの指定 :to_i - 整数変数, :to_f - 実数変数

Returns:

  • (Array<Integer>)

    イベントのIDの配列



1216
1217
1218
# File 'lib/when_exe/events.rb', line 1216

def edge_included(edge, range, method=:to_i)
  _edge_included(edge, Range.new(*range_args(range, method)))
end

#event(uri, graph = nil) ⇒ Hash<String(GraphURI)=>RDF:Repository>

指定の URIまたはイベントの通し番号を主語とする Statement からなる RDF:Repository を生成する

Parameters:

  • uri (String)

    主語の URI

  • uri (Integer)

    主語のイベントの通し番号

  • graph (String) (defaults to: nil)

    検索対象のグラフ(ダミー)

Returns:

  • (Hash<String(GraphURI)=>RDF:Repository>)

    生成した Repository の Hash



808
809
810
811
812
813
814
815
816
817
# File 'lib/when_exe/events.rb', line 808

def event(uri, graph=nil)
  rep   = Hash.new {|hash,key| hash[key] = ::RDF::Repository.new}
  list  = uri.kind_of?(String) ? @index[SUBJECT][uri] : [uri]
  unless list.empty?
    event = @events[list.first-1]
    rep[''].insert(*event.statements)
    rep[event.role[GRAPH]].insert(*event.statements) if @role.key?(GRAPH)
  end
  rep
end

#extract(predicate) ⇒ String

プレフィクスを名前空間に展開する

Parameters:

  • predicate (String)

    プレフィクス付きの URI

Returns:

  • (String)

    プレフィクスを名前空間に展開した URI



1262
1263
1264
1265
1266
1267
1268
# File 'lib/when_exe/events.rb', line 1262

def extract(predicate)
  return predicate unless /\A(.+?):(.+)\z/ =~ predicate && @prefix.key?($1)
  prefix, body = $~[1..2]
  namespace = @prefix[prefix].first
  namespace = namespace.sub(/([a-z0-9])\z/i, '\1#')
  namespace + body
end

#intersection_events(options) ⇒ Array<When::Events::Event>

指定の条件を満たす Event の Array を返す

Parameters:

  • options (Hash)

    以下の通り

Options Hash (options):

  • 'date' (String)

    日付範囲

  • 'contributor' (String)

    情報提供者

  • 'graph' (String)

    グラフ

  • 'group' (String)

    グループ

  • 'location' (String)

    空間位置

  • 'day' (String)

    今日は何の日用の日付(共通)

  • 'lsday' (String)

    今日は何の日用の日付(エスニック)

  • 'keyword' (String)

    キーワード

Returns:



1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
# File 'lib/when_exe/events.rb', line 1117

def intersection_events(options)
  list = []

  # 日付範囲
  if @order.key?(START) && /./ =~ options['date']
    range = Range.convert_from(When.date_or_era(options['date']))
    list << (@order.key?(UNTIL) ?
               range_overlaped(START, UNTIL, range) :
               edge_included(START, range))
  end

  # キーワード
  if @index.key?(HAS_PART) && /./ =~ options['keyword']
    options['keyword'].split('*').each {|key| list << @index[HAS_PART][key]}
  end

  # 情報提供者
  if @index.key?(CONTRIBUTOR) && /\A(!)?(.+)/ =~ options['contributor']
    reverse, contributor = $1, $2
    sublist = @index[CONTRIBUTOR][contributor]
    if sublist
      sublist = (@order[START] || (1..@events.size).to_a) - sublist if reverse
      list << sublist
    end
  end

  # グループ
  if @index.key?(GROUP) && /./ =~ options['group']
    list << @index[GROUP][options['group']]
  end

  # 空間位置
  if /./ =~ options['location']
    if @order.key?(WEST) || @order.key?(SOUTH) || @order.key?(BOTTOM)
      range = When.where?(options['location'])
      range = When::Coordinates::Spatial::Range.new(range,range) unless range.kind_of?(When::Coordinates::Spatial::Range)
      [[WEST,   EAST,  :long],
       [SOUTH,  NORTH, :lat ],
       [BOTTOM, TOP,   :alt ]].each do |pattern|
         first, last, method = pattern
         if @order.key?(first)
           list << (@order.key?(last) ?
                      range_overlaped(first, last, range.send(method), :to_f) :
                      edge_included(first, range.send(method), :to_f))
         end
       end
     elsif @index.key?(SPATIAL)
       list << @index[SPATIAL][options['location']]
     end
  end

  # グラフ
  if @index.key?(GRAPH) && /./ =~ options['graph']
    list << @index[GRAPH][options['graph']]
  end

  # 今日は何の日
  if @index.key?(WHAT_DAY)
    list << @index[WHAT_DAY][[true,  $1.to_i,$2.to_i]] if /\A(\d{1,2})[-\/]?(\d{1,2})\z/ =~ options['day']
    list << @index[WHAT_DAY][[false, $1.to_i,$2.to_i]] if /\A(\d{1,2})[-\/]?(\d{1,2})\z/ =~ options['lsday']
  end

  # 共通集合
  list.compact!
  return list if list.empty?
  intersection = list.shift
  list.each {|s| intersection &= s}
  events = intersection.map {|id| @events[id-1]}
  return events unless range

  # 個別の絞込み
  narrowed_events = []
  sort_required = false
  events.each do |event|
    event_range = event.role[VALID]
    if event_range.kind_of?(Range) && event_range.is_complex?
      event_range.overlaped(range).each do |focused_date|
        sort_required = true
        focused_event = event.deep_copy
        focused_event.send(:date=, focused_date)
        narrowed_events << focused_event
      end
    else
      narrowed_events << event
    end
  end
  narrowed_events.sort_by! {|event| event.date} if sort_required
  narrowed_events
end

#range_overlaped(first_edge, last_edge, range, method = :to_i) ⇒ Array<Integer>

範囲の重なり

Parameters:

  • first_edge (String)

    順序キー(ts:start, ts:west, ts:south, ts:bottom)

  • last_edge (String)

    順序キー(ts:until, ts:east, ts:north, ts:top)

  • range (Range)

    絞り込む範囲

  • method (Symbol) (defaults to: :to_i)

    スカラー化メソッドの指定 :to_i - 整数変数, :to_f - 実数変数

Returns:

  • (Array<Integer>)

    イベントのIDの配列



1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/when_exe/events.rb', line 1230

def range_overlaped(first_edge, last_edge, range, method=:to_i)
  args  = range_args(range, method)
  upper = ::Range.new(args[0], +Float::MAX/4, false)
  lower = ::Range.new(-Float::MAX/4, args[1], args[2])
  ([first_edge, last_edge].map {|edge| [@order[edge].first, @order[edge].last]}.flatten.uniq.select {|id|
    lower.include?(@events[id-1].role[first_edge]) && upper.include?(@events[id-1].role[last_edge])
  } | (
    @order[last_edge][_start_edge(last_edge, upper, 0, @events.size-1)..-1] &
    @order[first_edge][0..._ended_edge(first_edge, lower, 0, @events.size-1)]
  )).sort_by {|id|
    @events[id-1].role[first_edge]
  }
end

#repository(events = nil) ⇒ Hash<String(GraphURI)=>RDF:Repository>

指定の Event を主語とする Statement からなる RDF:Repository を生成する

Parameters:

Returns:

  • (Hash<String(GraphURI)=>RDF:Repository>)

    生成した Repository の Hash



786
787
788
789
790
791
792
793
794
795
796
797
# File 'lib/when_exe/events.rb', line 786

def repository(events=nil)
  if events
    rep = Hash.new {|hash,key| hash[key] = ::RDF::Repository.new}
    events.each do |event|
      rep[''].insert(*event.statements)
      rep[event.role[GRAPH]].insert(*event.statements) if @role.key?(GRAPH)
    end
    rep
  else
    @repository ||= repository(@events)
  end
end