relaton 3.1.21 → 3.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0c9551afdfdc2d8f92012753e88c013f94839b12617a9d8b4af5198876b7d7f7
4
- data.tar.gz: 9f1a4d389636ebe5ca843708e79483430ed89b875c58e7a96b754c6c712b187e
3
+ metadata.gz: 2bcb80bd767bab7dda24fcedc242136ae3670e4b7a2749987b6b801cb8ecf095
4
+ data.tar.gz: 55db364b609260b85658c79cf5f3c807796917aa97d0284f371e012f0691715c
5
5
  SHA512:
6
- metadata.gz: 6a20b14666e3b2fc1b9bc882d88d54fc86ef65056ce8c0961105ab13bc650683b2c22b6cb1936a686e15b1fc8d1bc1c28b48db86b82f99b5c6a7f3dd6b8bde9f
7
- data.tar.gz: ad192545ac71613715e881ec983c264856df19a3da30a415229a2c2b8e5f7991478757f4360cbde49a80e665eb04693078cd0f1fdb7a6a2dbcdce27e2005f453
6
+ metadata.gz: e45058a37231c4507c11f161223b1b3caa5bfc9f7b4ab7df85844864872eed5b5652482918ae5ccdf1ee6bb24e6db5aa3502e6f2937b035ee793cdd37d9b9467
7
+ data.tar.gz: f3c53ea5cba5cc3cc6e66d720b1695a60e8ce42ae923cae6b79708326f3bed9cd7aa00e9fed75e002cd4a845f30810b85715e72e872105d8660b46db21f0b341
@@ -0,0 +1,484 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+
5
+ module Relaton
6
+ module Org
7
+ # The index over a directory of unit records: every file under the
8
+ # directory and its subdirectories read once into memory (relaton/
9
+ # org-units-data holds one YAML file per unit), the records that resolve
10
+ # to one unit through a shared identifier grouped, and the maps the query
11
+ # surface reads from them, computed from the records and cached.
12
+ #
13
+ # index = Relaton::Org::Index.load("register")
14
+ # index.find("ISO/IEC JTC 1") # the canonical record of the unit
15
+ # index.records_of("ISO/IEC JTC 1").length # every record that states it
16
+ class Index
17
+ # The records of one unit: every record that states it, across registers
18
+ # where more than one holds it, and the canonical one, whose register
19
+ # mints the identifier the others refer to. The key is the canonical
20
+ # record's register URI.
21
+ Group = Struct.new(:records, :canonical, keyword_init: true) do
22
+ def key
23
+ canonical.id
24
+ end
25
+ end
26
+
27
+ EMPTY = [].freeze
28
+
29
+ attr_reader :dir, :records
30
+
31
+ class << self
32
+ # Reads every *.yaml file under the directory and its subdirectories
33
+ # as a unit record, and builds the index over them
34
+ #
35
+ # @param dir [String] the directory of unit records
36
+ # @return [Relaton::Org::Index]
37
+ # @raise [Relaton::Org::Error] when a file does not read as a unit
38
+ # record: the path is named, and nothing is skipped silently
39
+ def load(dir)
40
+ records = Dir[File.join(dir, "**", "*.yaml")].map do |path|
41
+ read(path)
42
+ end
43
+ new(records, dir: dir)
44
+ end
45
+
46
+ private
47
+
48
+ def read(path)
49
+ Unit.from_yaml(File.read(path, encoding: "UTF-8"))
50
+ rescue StandardError => e
51
+ raise Error, "#{path} does not read as a Relaton::Org::Unit: " \
52
+ "#{e.class}: #{e.message}"
53
+ end
54
+ end
55
+
56
+ # @param records [Array<Relaton::Org::Unit>]
57
+ # @param dir [String, nil] the directory the records were read from
58
+ def initialize(records, dir: nil)
59
+ @dir = dir
60
+ @records = records
61
+ @by_id = {}
62
+ @identities = Hash.new { |hash, key| hash[key] = [] }
63
+ file_records
64
+ resolve_groups
65
+ end
66
+
67
+ #
68
+ # The unit an identifier or a register URI names, as its canonical record
69
+ #
70
+ # @param id [String] a register URI, or an identifier notation of the
71
+ # unit, in the scheme any of its records states it in
72
+ # @return [Relaton::Org::Unit, nil]
73
+ # @raise [Relaton::Org::Error] when the identifier names several units
74
+ def find(id)
75
+ group_of(id)&.canonical
76
+ end
77
+
78
+ #
79
+ # Every record of the unit an identifier or a register URI names
80
+ #
81
+ # @param id [String]
82
+ # @return [Array<Relaton::Org::Unit>]
83
+ def records_of(id)
84
+ group = group_of(id)
85
+ group ? group.records : EMPTY
86
+ end
87
+
88
+ #
89
+ # The unit an identifier or a register URI names
90
+ #
91
+ # @param id [String]
92
+ # @return [Relaton::Org::Index::Group, nil]
93
+ def group_of(id)
94
+ group = @group_of_by_id[id]
95
+ return group if group
96
+
97
+ group_by_notation(id)
98
+ end
99
+
100
+ #
101
+ # The group a group key names, the reverse of Group#key
102
+ #
103
+ # @param key [String] the canonical record's register URI
104
+ # @return [Relaton::Org::Index::Group, nil]
105
+ def group_at(key)
106
+ @group_by_key[key]
107
+ end
108
+
109
+ #
110
+ # Every unit the index resolves, in the order its records were read
111
+ #
112
+ # @return [Array<Relaton::Org::Index::Group>]
113
+ def groups
114
+ @groups
115
+ end
116
+
117
+ #
118
+ # The units more than one register holds: those whose records carry
119
+ # different bodies in their register URIs
120
+ #
121
+ # @return [Integer]
122
+ def cross_register_units
123
+ @groups.count { |group| bodies_of(group).length > 1 }
124
+ end
125
+
126
+ #
127
+ # The group keys of the units a unit states as its parents, through every
128
+ # record of it; the parentage an organization states is no edge
129
+ #
130
+ # @param key [String]
131
+ # @return [Array<String>]
132
+ def parent_keys_of(key)
133
+ edges(:parent)[key] || EMPTY
134
+ end
135
+
136
+ #
137
+ # The group keys of the units a unit is a parent of
138
+ #
139
+ # @param key [String]
140
+ # @return [Array<String>]
141
+ def child_keys_of(key)
142
+ edges(:child)[key] || EMPTY
143
+ end
144
+
145
+ #
146
+ # The units a unit is under, computed from its parents through the
147
+ # records and cached
148
+ #
149
+ # @param key [String]
150
+ # @return [Array<String>]
151
+ def ancestor_keys_of(key)
152
+ @ancestors ||= {}
153
+ @ancestors[key] ||= reachable(key) { |k| parent_keys_of(k) }
154
+ end
155
+
156
+ #
157
+ # The units under a unit, the transitive closure of the reverse edge,
158
+ # computed and cached
159
+ #
160
+ # @param key [String]
161
+ # @return [Array<String>]
162
+ def descendant_keys_of(key)
163
+ @descendants ||= {}
164
+ @descendants[key] ||= reachable(key) { |k| child_keys_of(k) }
165
+ end
166
+
167
+ #
168
+ # The paths of a unit, one per parent: through the record the parentage
169
+ # resolves to where the index holds it, ending at the parentage as it is
170
+ # stated where it resolves to nothing, and at the unit where the
171
+ # parentage would return to a unit already on the path. Computed and
172
+ # cached; a path is an array of records and stated unit references.
173
+ #
174
+ # @param key [String]
175
+ # @return [Array<Array>]
176
+ def paths_of(key)
177
+ @paths ||= {}
178
+ @paths[key] ||= paths_from(key, { key => true })
179
+ end
180
+
181
+ #
182
+ # The units an unit's events state as its successors, and the units
183
+ # whose events state it as their predecessor. A successor the index
184
+ # resolves is given as its group; one it does not is given as the
185
+ # reference the event states it by.
186
+ #
187
+ # @param key [String]
188
+ # @return [Array]
189
+ def successor_nodes_of(key)
190
+ event_nodes(:successor)[key] || EMPTY
191
+ end
192
+
193
+ #
194
+ # The units an unit's events state as its predecessors, and the units
195
+ # whose events state it as their successor: the reverse edges
196
+ #
197
+ # @param key [String]
198
+ # @return [Array]
199
+ def predecessor_nodes_of(key)
200
+ event_nodes(:predecessor)[key] || EMPTY
201
+ end
202
+
203
+ private
204
+
205
+ def file_records
206
+ @records.each { |record| file_record(record) }
207
+ file_notations
208
+ end
209
+
210
+ def file_record(record)
211
+ if @by_id.key?(record.id)
212
+ raise Error, "the register holds #{record.id} twice"
213
+ end
214
+
215
+ @by_id[record.id] = record
216
+ file_identifiers(record)
217
+ end
218
+
219
+ def file_identifiers(record)
220
+ record.identifiers.each do |identifier|
221
+ next unless identifier.scheme && identifier.notation
222
+
223
+ @identities[identity_key(identifier.scheme, identifier.notation)] <<
224
+ record.id
225
+ end
226
+ end
227
+
228
+ def file_notations
229
+ @by_notation = {}
230
+ @identities.each do |(_, notation), ids|
231
+ (@by_notation[notation] ||= []).concat(ids)
232
+ end
233
+ end
234
+
235
+ # The records that share an identifier of the same scheme with the same
236
+ # notation are one unit, however many registers hold it: the ISO record
237
+ # and the IEC record of ISO/IEC JTC 1 both carry the ISO reference of
238
+ # the joint committee, so they resolve to one unit of two records. The
239
+ # identity is read case-insensitively, as a query names it.
240
+ def resolve_groups
241
+ parent = identity_parents
242
+ @group_of_by_id = {}
243
+ @group_by_key = {}
244
+ by_root = @records.group_by { |record| root_of(parent, record.id) }
245
+ @groups = by_root.values.map { |unit| group_of_records(unit) }
246
+ end
247
+
248
+ def identity_parents
249
+ parent = Hash.new { |hash, key| hash[key] = key }
250
+ @identities.each_value do |ids|
251
+ ids.each { |id| union(parent, ids.first, id) }
252
+ end
253
+ parent
254
+ end
255
+
256
+ def group_of_records(unit_records)
257
+ group = Group.new(records: unit_records,
258
+ canonical: canonical_of(unit_records))
259
+ unit_records.each { |record| @group_of_by_id[record.id] = group }
260
+ @group_by_key[group.key] = group
261
+ group
262
+ end
263
+
264
+ # The canonical record of a unit is the one whose register mints the
265
+ # identifier the other records refer to: the one that holds an
266
+ # identifier another record holds too as its canonical identifier. Where
267
+ # several records do, or none does, the record with the least register
268
+ # URI is canonical, so the answer never depends on the order the files
269
+ # were read in.
270
+ def canonical_of(unit_records)
271
+ minting = unit_records.select do |record|
272
+ record.identifiers.any? do |identifier|
273
+ identifier.canonical && shared_identifier?(identifier)
274
+ end
275
+ end
276
+ (minting.length == 1 ? minting : unit_records).min_by(&:id)
277
+ end
278
+
279
+ def shared_identifier?(identifier)
280
+ return false unless identifier.scheme && identifier.notation
281
+
282
+ @identities[identity_key(identifier.scheme,
283
+ identifier.notation)].length > 1
284
+ end
285
+
286
+ def identity_key(scheme, notation)
287
+ [scheme, notation.downcase]
288
+ end
289
+
290
+ def union(parent, one, other)
291
+ root_one = root_of(parent, one)
292
+ root_other = root_of(parent, other)
293
+ parent[root_other] = root_one if root_one != root_other
294
+ end
295
+
296
+ def root_of(parent, id)
297
+ while parent[id] != id
298
+ parent[id] = parent[parent[id]]
299
+ id = parent[id]
300
+ end
301
+ id
302
+ end
303
+
304
+ def bodies_of(group)
305
+ pattern = %r{\Ahttps://relaton\.org/units/([^/]+)}
306
+ group.records.map { |record| record.id[pattern, 1] }
307
+ end
308
+
309
+ def edges(direction)
310
+ build_edges unless @parent_edges
311
+ direction == :parent ? @parent_edges : @child_edges
312
+ end
313
+
314
+ # The parentage of every record, resolved to the group the parent's
315
+ # reference or identifier names; a parentage that names an organization,
316
+ # or a unit nothing states, is no edge between records
317
+ def build_edges
318
+ parents = Hash.new { |hash, key| hash[key] = [] }
319
+ children = Hash.new { |hash, key| hash[key] = [] }
320
+ @records.each { |record| parent_edges_of(record, parents, children) }
321
+ @parent_edges = sorted_edges(parents)
322
+ @child_edges = sorted_edges(children)
323
+ end
324
+
325
+ def parent_edges_of(record, parents, children)
326
+ from = @group_of_by_id[record.id].key
327
+ record.parents.each do |parentage|
328
+ next unless parentage.unit
329
+
330
+ edge_of(parentage, from, parents, children)
331
+ end
332
+ end
333
+
334
+ def edge_of(parentage, from, parents, children)
335
+ to = resolve_group(parentage.unit)
336
+ return if to.nil? || to.key == from
337
+
338
+ parents[from] << to.key
339
+ children[to.key] << from
340
+ end
341
+
342
+ def sorted_edges(node_keys)
343
+ node_keys.transform_values { |keys| keys.uniq.sort }
344
+ end
345
+
346
+ # The group a unit reference names: by the register URI it states, or by
347
+ # the scheme and notation an identifier of the index holds
348
+ def resolve_group(unit_ref)
349
+ return nil unless unit_ref
350
+
351
+ by_reference(unit_ref) || by_identity(unit_ref)
352
+ end
353
+
354
+ def by_reference(unit_ref)
355
+ @group_of_by_id[unit_ref.ref] if unit_ref.ref
356
+ end
357
+
358
+ def by_identity(unit_ref)
359
+ return nil unless unit_ref.scheme && unit_ref.notation
360
+
361
+ groups_of_identity(identity_key(unit_ref.scheme, unit_ref.notation))
362
+ end
363
+
364
+ def groups_of_identity(identity)
365
+ ids = @identities[identity]
366
+ return nil if ids.empty?
367
+
368
+ keys = ids.map { |record_id| @group_of_by_id[record_id].key }.uniq
369
+ @group_by_key[keys.first] if keys.length == 1
370
+ end
371
+
372
+ def group_by_notation(id)
373
+ ids = @by_notation[id.to_s.downcase]
374
+ return nil if ids.nil? || ids.empty?
375
+
376
+ keys = ids.uniq.map { |record_id| @group_of_by_id[record_id].key }
377
+ resolve_notation_group(id, keys.uniq)
378
+ end
379
+
380
+ def resolve_notation_group(id, keys)
381
+ if keys.length > 1
382
+ raise Error, "#{id} names several units: #{keys.join(', ')}"
383
+ end
384
+
385
+ @group_of_by_id[@by_notation[id.to_s.downcase].first]
386
+ end
387
+
388
+ def reachable(key)
389
+ seen = { key => true }
390
+ frontier = yield(key).dup
391
+ until frontier.empty?
392
+ next_key = frontier.pop
393
+ next if seen.key?(next_key)
394
+
395
+ seen[next_key] = true
396
+ frontier.push(*yield(next_key))
397
+ end
398
+ seen.keys - [key]
399
+ end
400
+
401
+ def paths_from(key, on_path)
402
+ node = @group_by_key[key].canonical
403
+ parents = parent_nodes_of(key)
404
+ return [[node]] if parents.empty?
405
+
406
+ parents.flat_map { |parent| path_branches(node, parent, on_path) }
407
+ end
408
+
409
+ def path_branches(node, parent, on_path)
410
+ return [[node, parent]] unless parent.is_a?(Group)
411
+ return [[node, parent.canonical]] if on_path.key?(parent.key)
412
+
413
+ paths_from(parent.key, on_path.merge(parent.key => true))
414
+ .map { |tail| [node, *tail] }
415
+ end
416
+
417
+ # The parents of a unit as paths state them: the group each parentage
418
+ # resolves to, and the parentage itself where it resolves to nothing
419
+ def parent_nodes_of(key)
420
+ group = @group_by_key[key]
421
+ refs = group.records.flat_map do |record|
422
+ record.parents.filter_map(&:unit)
423
+ end
424
+ refs.filter_map { |unit_ref| parent_node(unit_ref, key) }
425
+ end
426
+
427
+ def parent_node(unit_ref, key)
428
+ resolved = resolve_group(unit_ref)
429
+ if resolved
430
+ resolved unless resolved.key == key
431
+ else
432
+ unit_ref
433
+ end
434
+ end
435
+
436
+ def event_nodes(direction)
437
+ build_event_edges unless @successor_nodes
438
+ direction == :successor ? @successor_nodes : @predecessor_nodes
439
+ end
440
+
441
+ # The edges of the events: an event on a record that states successors
442
+ # runs from its unit to them, and one that states predecessors runs from
443
+ # them to its unit, so the timeline answers navigation in both
444
+ # directions from the events the records state. A unit an event names
445
+ # that resolves to nothing is kept as the reference the event states it
446
+ # by, on the side the edge runs from.
447
+ def build_event_edges
448
+ @successor_nodes = {}
449
+ @predecessor_nodes = {}
450
+ @records.each { |record| event_edges_of(record) }
451
+ @successor_nodes.transform_values!(&:uniq)
452
+ @predecessor_nodes.transform_values!(&:uniq)
453
+ end
454
+
455
+ def event_edges_of(record)
456
+ from = @group_of_by_id[record.id]
457
+ record.events.each do |event|
458
+ event.successors.each { |ref| link(from, resolve_group(ref) || ref) }
459
+ event.predecessors.each do |ref|
460
+ link(resolve_group(ref) || ref, from)
461
+ end
462
+ end
463
+ end
464
+
465
+ def link(from_node, to_node)
466
+ from_key = group_key_of(from_node)
467
+ to_key = group_key_of(to_node)
468
+ return if from_key && from_key == to_key
469
+
470
+ edge_map(:successor, from_key) << to_node if from_key
471
+ edge_map(:predecessor, to_key) << from_node if to_key
472
+ end
473
+
474
+ def edge_map(direction, key)
475
+ map = direction == :successor ? @successor_nodes : @predecessor_nodes
476
+ map[key] ||= []
477
+ end
478
+
479
+ def group_key_of(node)
480
+ node.is_a?(Group) ? node.key : nil
481
+ end
482
+ end
483
+ end
484
+ end
@@ -0,0 +1,559 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Relaton
6
+ module Org
7
+ # The query surface over an index of unit records (relaton/relaton#679):
8
+ # every method answers records and counts, never strings, so the API layer
9
+ # of an application mounts it. A unit is named by any identifier any of its
10
+ # records states it by, or by a register URI; where several registers hold
11
+ # one unit, every answer states the records the unit has and the one whose
12
+ # register mints the identifier the others refer to.
13
+ #
14
+ # query = Relaton::Org::Query.new(Relaton::Org::Index.load("register"))
15
+ # query.search(sdo: "ISO", kind: "technical-bodies", q: "screw threads")
16
+ # query.at("ISO/TC 1", "2019-06-01").status.certainty
17
+ # # => "stated", or "inferred"
18
+ class Query
19
+ # The answer to a list or a search: the records that match, the counts
20
+ # over them, and the status assignment each matched record is answered
21
+ # by, so whether the assignment is stated or inferred is never hidden.
22
+ Result = Struct.new(:records, :assignments, :facets,
23
+ keyword_init: true) do
24
+ def total
25
+ records.length
26
+ end
27
+ end
28
+
29
+ # One unit as it was at a date: the status assignment in force, the
30
+ # identifiers, names, abbreviations, memberships and posts whose
31
+ # validity covers the date, and the record whose register mints the
32
+ # unit's identifier.
33
+ State = Struct.new(:record, :date, :status, :identifiers, :names,
34
+ :abbreviations, :membership, :posts,
35
+ keyword_init: true)
36
+
37
+ # One record as a query reads it: the record, the status assignment the
38
+ # answer is about (the last one, or the one in force at the date the
39
+ # query states), the query and the filters of the query.
40
+ Match = Struct.new(:record, :status, :query, :filters)
41
+
42
+ # The filters of the surface, one entry each: a new filter is one entry
43
+ # here, never a branch in the search. status_at is the date the status
44
+ # and the certainty of an answer are read at, and requires an assignment
45
+ # in force at it; with_descendants widens parent and is no filter of its
46
+ # own.
47
+ FILTERS = {
48
+ sdo: ->(match, value) { Matching.agent?(match.record.sdo, value) },
49
+ kind: ->(match, value) { Matching.kind?(match.record, value) },
50
+ status: ->(match, value) { match.status&.status == value },
51
+ status_at: ->(match, _value) { !match.status.nil? },
52
+ certainty: ->(match, value) { match.status&.certainty == value },
53
+ parent: ->(match, value) do
54
+ match.query.under?(match.record, value,
55
+ match.filters[:with_descendants])
56
+ end,
57
+ member: ->(match, value) do
58
+ match.record.members.any? do |membership|
59
+ Matching.agent?(membership.member, value)
60
+ end
61
+ end,
62
+ secretariat: ->(match, value) do
63
+ match.record.secretariats.any? do |secretariat|
64
+ Matching.agent?(secretariat.organization, value)
65
+ end
66
+ end,
67
+ duration: ->(match, value) { Matching.duration?(match.record, value) },
68
+ period: ->(match, value) { Matching.period?(match.record, value) },
69
+ q: ->(match, value) { Matching.text?(match.record, value) },
70
+ }.freeze
71
+
72
+ MODIFIERS = %i[with_descendants].freeze
73
+
74
+ attr_reader :index
75
+
76
+ # @param index [Relaton::Org::Index]
77
+ def initialize(index)
78
+ @index = index
79
+ end
80
+
81
+ #
82
+ # The records that match the filters, with the counts over them; the
83
+ # entry of the surface that lists, where search is the entry that reads
84
+ # free text
85
+ #
86
+ # @param filters [Hash]
87
+ # @return [Relaton::Org::Query::Result]
88
+ # @raise [Relaton::Org::Error] when a filter is not one of the surface,
89
+ # or the date of status_at states no date the record's own pattern
90
+ # reads
91
+ def list(filters = {})
92
+ search(filters)
93
+ end
94
+
95
+ #
96
+ # The records that match the filters and the free text, with the counts
97
+ # over them. The free text q reads the names of every language, the
98
+ # abbreviations and the identifiers' notations, as a substring,
99
+ # case-insensitively; every other filter reads its value as the records
100
+ # state it, case-insensitively where a word is read.
101
+ #
102
+ # @param filters [Hash]
103
+ # @return [Relaton::Org::Query::Result]
104
+ def search(filters = {})
105
+ run(filters)
106
+ end
107
+
108
+ #
109
+ # The canonical record of the unit an identifier or a register URI names
110
+ #
111
+ # @param id [String]
112
+ # @return [Relaton::Org::Unit, nil]
113
+ def find(id)
114
+ @index.find(id)
115
+ end
116
+
117
+ #
118
+ # Every record of the unit an identifier or a register URI names
119
+ #
120
+ # @param id [String]
121
+ # @return [Array<Relaton::Org::Unit>]
122
+ def records_of(id)
123
+ @index.records_of(id)
124
+ end
125
+
126
+ #
127
+ # The paths of a unit, one per parent: a path is an array of the records
128
+ # the parentage resolves to, ending at the parentage as it is stated
129
+ # where nothing resolves to it
130
+ #
131
+ # @param id [String]
132
+ # @return [Array<Array>]
133
+ def paths(id)
134
+ group = @index.group_of(id)
135
+ group ? @index.paths_of(group.key) : []
136
+ end
137
+
138
+ #
139
+ # The units a unit states as its parents
140
+ #
141
+ # @param id [String]
142
+ # @return [Array]
143
+ def children(id)
144
+ keys_for(:child, id)
145
+ end
146
+
147
+ #
148
+ # The units a unit is under: every unit its paths pass through, beyond
149
+ # the unit itself
150
+ #
151
+ # @param id [String]
152
+ # @return [Array]
153
+ def ancestors(id)
154
+ nodes = paths(id).flat_map { |path| path.drop(1) }
155
+ nodes.uniq { |node| node_key(node) }
156
+ end
157
+
158
+ #
159
+ # The units under a unit
160
+ #
161
+ # @param id [String]
162
+ # @return [Array<Relaton::Org::Unit>]
163
+ def descendants(id)
164
+ keys_for(:descendant, id)
165
+ end
166
+
167
+ #
168
+ # The units an unit's events state as its successors, and the units
169
+ # whose events state it as their predecessor
170
+ #
171
+ # @param id [String]
172
+ # @return [Array]
173
+ def successors(id)
174
+ group = @index.group_of(id)
175
+ return [] unless group
176
+
177
+ @index.successor_nodes_of(group.key).map { |node| node_of(node) }
178
+ end
179
+
180
+ #
181
+ # The units an unit's events state as its predecessors, and the units
182
+ # whose events state it as their successor
183
+ #
184
+ # @param id [String]
185
+ # @return [Array]
186
+ def predecessors(id)
187
+ group = @index.group_of(id)
188
+ return [] unless group
189
+
190
+ @index.predecessor_nodes_of(group.key).map { |node| node_of(node) }
191
+ end
192
+
193
+ #
194
+ # The unit as it was at a date: the status assignment in force, the last
195
+ # stated one where several registers state one, and the identifiers,
196
+ # names, abbreviations, memberships and posts whose validity covers the
197
+ # date
198
+ #
199
+ # @param id [String]
200
+ # @param date [String] a date at the precision the records state theirs
201
+ # @return [Relaton::Org::Query::State, nil]
202
+ # @raise [Relaton::Org::Error] when the date states no date
203
+ def at(id, date)
204
+ assert_date(date)
205
+ group = @index.group_of(id)
206
+ return nil unless group
207
+
208
+ state_of(group, date)
209
+ end
210
+
211
+ #
212
+ # The events of a unit, of every record that states it, in the order of
213
+ # their dates, the undated ones last
214
+ #
215
+ # @param id [String]
216
+ # @return [Array<Relaton::Org::Unit::Event>]
217
+ def events(id)
218
+ group = @index.group_of(id)
219
+ return [] unless group
220
+
221
+ ordered = group.records.flat_map(&:events).each_with_index
222
+ .sort_by { |event, position| order_of(event, position) }
223
+ ordered.map(&:first)
224
+ end
225
+
226
+ #
227
+ # Whether a record is under a unit, directly where with_descendants is
228
+ # false and under it or one of its ancestors where it is true
229
+ #
230
+ # @param record [Relaton::Org::Unit]
231
+ # @param value [String] the unit, as an identifier or a register URI
232
+ # @param with_descendants [Boolean]
233
+ # @return [Boolean]
234
+ def under?(record, value, with_descendants)
235
+ group = @index.group_of(record.id)
236
+ target = @index.group_of(value.to_s)
237
+ return false if group.nil? || target.nil?
238
+
239
+ keys = if with_descendants
240
+ @index.ancestor_keys_of(group.key)
241
+ else
242
+ @index.parent_keys_of(group.key)
243
+ end
244
+ keys.include?(target.key)
245
+ end
246
+
247
+ #
248
+ # The duration of a unit's kind, as its record states it and as the kind
249
+ # scheme gives the concept where the record states none
250
+ #
251
+ # @param record [Relaton::Org::Unit]
252
+ # @return [String, nil]
253
+ def duration_of(record)
254
+ Matching.duration_of(record)
255
+ end
256
+
257
+ private
258
+
259
+ def run(filters)
260
+ assert_filters(filters)
261
+ date = filters[:status_at]
262
+ assert_date(date) if date
263
+ matches = matching_records(filters, date)
264
+ Result.new(
265
+ records: matches.map(&:record),
266
+ assignments: matches.to_h { |match| [match.record.id, match.status] },
267
+ facets: facets_of(matches),
268
+ )
269
+ end
270
+
271
+ def assert_filters(filters)
272
+ unknown = filters.keys - FILTERS.keys - MODIFIERS
273
+ return if unknown.empty?
274
+
275
+ raise Error,
276
+ "no filter #{unknown.join(', ')}: the surface reads " \
277
+ "#{FILTERS.keys.join(', ')} (with_descendants widens parent)"
278
+ end
279
+
280
+ def matching_records(filters, date)
281
+ stated = stated_filters(filters)
282
+ @index.records.filter_map do |record|
283
+ match = Match.new(record, assignment_in_force(record, date), self,
284
+ filters)
285
+ next unless matches_filters?(match, stated)
286
+
287
+ match
288
+ end
289
+ end
290
+
291
+ def stated_filters(filters)
292
+ filters.select { |name, value| FILTERS.key?(name) && !value.nil? }
293
+ end
294
+
295
+ def matches_filters?(match, stated)
296
+ stated.all? { |name, value| FILTERS[name].call(match, value) }
297
+ end
298
+
299
+ # The assignment the answer is about: the last one the record states
300
+ # where the query states no date, and the last one in force at the date
301
+ # where it does. Whether the assignment is stated or inferred is read
302
+ # from it, never guessed.
303
+ def assignment_in_force(record, date)
304
+ return record.status.last if date.nil?
305
+
306
+ record.status.select do |assignment|
307
+ Dates.cover?(assignment.valid, date)
308
+ end.last
309
+ end
310
+
311
+ def state_of(group, date)
312
+ State.new(
313
+ record: group.canonical,
314
+ date: date,
315
+ status: status_at_date(group, date),
316
+ identifiers: facts_at_date(group, date, &:identifiers),
317
+ names: facts_at_date(group, date, &:names),
318
+ abbreviations: facts_at_date(group, date, &:abbreviations),
319
+ membership: facts_at_date(group, date, &:members),
320
+ posts: facts_at_date(group, date, &:posts),
321
+ )
322
+ end
323
+
324
+ def status_at_date(group, date)
325
+ in_force = group.records.flat_map(&:status)
326
+ .select { |assignment| in_force?(assignment, date) }
327
+ stated_last(in_force)
328
+ end
329
+
330
+ def in_force?(assignment, date)
331
+ Dates.cover?(assignment.valid, date)
332
+ end
333
+
334
+ # The last stated assignment in force, where two registers state the
335
+ # unit; the last in force where neither states it
336
+ def stated_last(in_force)
337
+ stated = in_force.reverse.find do |assignment|
338
+ assignment.certainty == "stated"
339
+ end
340
+ stated || in_force.last
341
+ end
342
+
343
+ def facts_at_date(group, date, &)
344
+ facts = group.records.flat_map(&)
345
+ facts.select { |fact| Dates.cover?(fact_validity(fact), date) }
346
+ end
347
+
348
+ # A post carries its validity as its term; every other dated fact of the
349
+ # record carries it as valid
350
+ def fact_validity(fact)
351
+ fact.is_a?(Unit::Post) ? fact.term : fact.valid
352
+ end
353
+
354
+ def facets_of(matches)
355
+ {
356
+ "sdo" => counts(matches) { |match| facet_sdo(match.record) },
357
+ "kind" => counts(matches) { |match| facet_kind(match.record) },
358
+ "status" => counts(matches) do |match|
359
+ match.status&.status || "none"
360
+ end,
361
+ "secretariat" => facet_secretariats(matches),
362
+ }
363
+ end
364
+
365
+ def facet_sdo(record)
366
+ return "none" unless record.sdo
367
+
368
+ record.sdo.name || record.sdo.abbreviation || "none"
369
+ end
370
+
371
+ def facet_kind(record)
372
+ return "none" unless record.kind
373
+
374
+ record.kind.shared || record.kind.concept || "none"
375
+ end
376
+
377
+ def facet_secretariats(matches)
378
+ matches.each_with_object({}) do |match, counted|
379
+ secretariat_keys(match.record).each do |key|
380
+ counted[key] = counted.fetch(key, 0) + 1
381
+ end
382
+ end
383
+ end
384
+
385
+ def secretariat_keys(record)
386
+ keys = record.secretariats.map do |secretariat|
387
+ facet_agent(secretariat.organization)
388
+ end.uniq
389
+ keys.empty? ? ["none"] : keys
390
+ end
391
+
392
+ def facet_agent(organization)
393
+ return "none" unless organization
394
+
395
+ organization.abbreviation || organization.name || "none"
396
+ end
397
+
398
+ def counts(matches)
399
+ matches.each_with_object({}) do |match, counted|
400
+ key = yield(match)
401
+ counted[key] = counted.fetch(key, 0) + 1
402
+ end
403
+ end
404
+
405
+ def keys_for(kind, id)
406
+ group = @index.group_of(id)
407
+ return [] unless group
408
+
409
+ keys = if kind == :child
410
+ @index.child_keys_of(group.key)
411
+ else
412
+ @index.descendant_keys_of(group.key)
413
+ end
414
+ keys.map { |key| @index.group_at(key).canonical }
415
+ end
416
+
417
+ def node_of(node)
418
+ node.is_a?(Index::Group) ? node.canonical : node
419
+ end
420
+
421
+ def node_key(node)
422
+ if node.is_a?(Unit)
423
+ node.id
424
+ else
425
+ [node.ref, node.scheme, node.notation].compact.join("|")
426
+ end
427
+ end
428
+
429
+ def order_of(event, position)
430
+ [event.date ? 0 : 1, event.date.to_s, position]
431
+ end
432
+
433
+ def assert_date(date)
434
+ return if Dates.span(date)
435
+
436
+ raise Error, "#{date.inspect} states no date the records' own " \
437
+ "pattern reads: a year, a year and a month, a full date"
438
+ end
439
+
440
+ # The facts of the records the dates of the record model are read with:
441
+ # a year, a year and a month, a full date, or a full date with a time of
442
+ # day, at the precision the body states it at. A fact of no validity, or
443
+ # one whose validity states no bound, holds for every date.
444
+ module Dates
445
+ PATTERN = /
446
+ \A(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?(?:T\d{2}:\d{2}(?::\d{2})?Z)?\z
447
+ /x
448
+
449
+ class << self
450
+ #
451
+ # The range of days a stated date covers, at the precision it states
452
+ #
453
+ # @param stated [String]
454
+ # @return [Array<Integer, Integer>, nil] the first and the last day,
455
+ # as Julian day numbers, or nil where the date states none
456
+ def span(stated)
457
+ match = PATTERN.match(stated.to_s)
458
+ return unless match
459
+
460
+ from = day_start(match)
461
+ [from.jd, day_end(match, from).jd]
462
+ end
463
+
464
+ #
465
+ # Whether a fact's validity holds at a date
466
+ #
467
+ # @param valid [Relaton::Org::Unit::Validity, nil]
468
+ # @param date [String]
469
+ # @return [Boolean]
470
+ def cover?(valid, date)
471
+ return true unless valid
472
+
473
+ point = span(date).first
474
+ from = valid.from && span(valid.from)
475
+ to = valid.to && span(valid.to)
476
+ open_from?(from, point) && open_to?(to, point)
477
+ end
478
+
479
+ private
480
+
481
+ def day_start(match)
482
+ ::Date.new(match[1].to_i, match[2]&.to_i || 1, match[3]&.to_i || 1)
483
+ end
484
+
485
+ def day_end(match, from)
486
+ return from if match[3]
487
+ return ::Date.new(match[1].to_i, match[2].to_i, -1) if match[2]
488
+
489
+ ::Date.new(match[1].to_i, 12, -1)
490
+ end
491
+
492
+ def open_from?(from, point)
493
+ from.nil? || from.first <= point
494
+ end
495
+
496
+ def open_to?(to, point)
497
+ to.nil? || point <= to.last
498
+ end
499
+ end
500
+ end
501
+
502
+ # The readers the filters of the surface state their values with. Each
503
+ # reads what a record states, case-insensitively, and answers a boolean;
504
+ # a filter of the surface adds at most one reader here.
505
+ module Matching
506
+ module_function
507
+
508
+ def agent?(agent, value)
509
+ return false unless agent
510
+
511
+ [agent.ref, agent.name, agent.abbreviation].compact.any? do |stated|
512
+ stated.casecmp(value.to_s).zero?
513
+ end
514
+ end
515
+
516
+ def kind?(record, value)
517
+ kind = record.kind
518
+ return false unless kind
519
+
520
+ kind.shared == value ||
521
+ kind.concept.to_s.casecmp(value.to_s).zero? ||
522
+ Schemes.family_of(kind.shared) == value
523
+ end
524
+
525
+ def duration?(record, value)
526
+ duration_of(record) == value
527
+ end
528
+
529
+ def duration_of(record)
530
+ record.kind&.duration || Schemes.duration_of(record.kind&.shared)
531
+ end
532
+
533
+ def period?(record, value)
534
+ periods_of(record).any? do |stated|
535
+ stated.casecmp(value.to_s).zero?
536
+ end
537
+ end
538
+
539
+ def periods_of(record)
540
+ (record.status + record.members + record.posts + record.scope)
541
+ .filter_map(&:period)
542
+ end
543
+
544
+ def text?(record, value)
545
+ needle = value.to_s.downcase
546
+ texts_of(record).any? { |stated| stated.downcase.include?(needle) }
547
+ end
548
+
549
+ # The text of a record the free text reads: the names of every
550
+ # language, the abbreviations and the identifiers' notations
551
+ def texts_of(record)
552
+ record.names.filter_map(&:text) +
553
+ record.abbreviations.filter_map(&:text) +
554
+ record.identifiers.filter_map(&:notation)
555
+ end
556
+ end
557
+ end
558
+ end
559
+ end
data/lib/relaton/org.rb CHANGED
@@ -15,5 +15,7 @@ module Relaton
15
15
  autoload :Unit, "relaton/org/unit"
16
16
  autoload :Parsers, "relaton/org/parsers"
17
17
  autoload :Schema, "relaton/org/schema"
18
+ autoload :Index, "relaton/org/index"
19
+ autoload :Query, "relaton/org/query"
18
20
  end
19
21
  end
@@ -26,8 +26,7 @@ module Relaton
26
26
  def identifier_text
27
27
  return identifier_element.render unless @model.type.to_s == "standard"
28
28
 
29
- identifier_element.designation
30
- .map { |d| identifier_element.render_id(d) }.join(" | ")
29
+ identifier_element.designation_text
31
30
  end
32
31
 
33
32
  def identifier_element
@@ -15,8 +15,7 @@ module Relaton
15
15
  end
16
16
 
17
17
  def render
18
- identifiers.map { |d| identifier_element.render_id(d) }
19
- .join(" | ")
18
+ identifier_element.designation_text
20
19
  end
21
20
 
22
21
  private
@@ -41,6 +41,13 @@ module Relaton
41
41
  primary.empty? ? candidate_identifiers.first(1) : primary
42
42
  end
43
43
 
44
+ # The designation rendered through the pack's identifier kinds
45
+ # (ISO 690:2021 8.11.1.2). render_id runs on implicit self, so
46
+ # a pack may override it at any visibility.
47
+ def designation_text
48
+ designation.map { |d| render_id(d) }.join(" | ")
49
+ end
50
+
44
51
  private
45
52
 
46
53
  def identifiers
@@ -1,3 +1,3 @@
1
1
  module Relaton
2
- VERSION = "3.1.21".freeze
2
+ VERSION = "3.1.22".freeze
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: relaton
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.21
4
+ version: 3.1.22
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ribose Inc.
@@ -1331,6 +1331,7 @@ files:
1331
1331
  - lib/relaton/org/generated/unit.owl.ttl
1332
1332
  - lib/relaton/org/generated/unit.schema.json
1333
1333
  - lib/relaton/org/generated/unit.shacl.ttl
1334
+ - lib/relaton/org/index.rb
1334
1335
  - lib/relaton/org/parsers.rb
1335
1336
  - lib/relaton/org/parsers/cen.rb
1336
1337
  - lib/relaton/org/parsers/cen/record.rb
@@ -1353,6 +1354,7 @@ files:
1353
1354
  - lib/relaton/org/parsers/three_gpp.rb
1354
1355
  - lib/relaton/org/parsers/three_gpp/record.rb
1355
1356
  - lib/relaton/org/parsers/three_gpp/snapshot.rb
1357
+ - lib/relaton/org/query.rb
1356
1358
  - lib/relaton/org/schema.rb
1357
1359
  - lib/relaton/org/schema/context.rb
1358
1360
  - lib/relaton/org/schema/graph.rb