seaports 1.8.0 → 1.9.0

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.
@@ -5,6 +5,7 @@ require "json"
5
5
 
6
6
  require_relative "../seaports"
7
7
  require_relative "alternate_names"
8
+ require_relative "timezones"
8
9
 
9
10
  module Seaports
10
11
  # Rebuilds the shipped sea-port table from a published UN/LOCODE code list.
@@ -24,7 +25,8 @@ module Seaports
24
25
  SOURCE_URL = "https://raw.githubusercontent.com/datasets/un-locode/main/data/code-list.csv"
25
26
  DATAPACKAGE_URL = "https://raw.githubusercontent.com/datasets/un-locode/main/datapackage.json"
26
27
 
27
- HEADERS = %w[locode name lat lng subdivision principal_subdivision subdivision_path subdivision_source coordinate_source alternate_names].freeze
28
+ HEADERS = %w[locode name lat lng subdivision principal_subdivision subdivision_path subdivision_source coordinate_source timezone timezone_source
29
+ alternate_names].freeze
28
30
 
29
31
  # Where a port's position came from, best first. "unlocode" is UN/LOCODE's
30
32
  # own and always wins; a later regeneration may replace any of the others.
@@ -199,6 +201,38 @@ module Seaports
199
201
  changed
200
202
  end
201
203
 
204
+ # Writes the ports' time zones into the table at +path+ (see
205
+ # Seaports::Timezones), without the rest of a refresh: how the zones reach
206
+ # the table after a reviewed override, or after apply_coordinates moved a
207
+ # position. Returns the locodes whose zone changed.
208
+ def self.apply_timezones(timezones, path = Seaports::TABLE_PATH, overrides: Timezones.overrides)
209
+ table = CSV.read(path, headers: true)
210
+ zones = timezones.assign(table.map { |row| timezone_port(*row.fields("locode", "lat", "lng", "subdivision_path")) }, overrides:)
211
+ changed = []
212
+ rows = table.map do |row|
213
+ was = row.fields("timezone", "timezone_source")
214
+ row["timezone"], row["timezone_source"] = zones.fetch(row["locode"])
215
+ changed << row["locode"] if was != row.fields("timezone", "timezone_source")
216
+ row.fields(*HEADERS)
217
+ end
218
+ CSV.open(path, "w") do |csv|
219
+ csv << HEADERS
220
+ rows.each { |row| csv << row }
221
+ end
222
+ changed
223
+ end
224
+
225
+ # Timezones#disagreements over the table at +path+, as written.
226
+ def self.timezone_disagreements(timezones, path = Seaports::TABLE_PATH)
227
+ table = CSV.read(path, headers: true)
228
+ ports = table.map { |row| timezone_port(*row.fields("locode", "lat", "lng", "subdivision_path")) }
229
+ timezones.disagreements(ports, table.to_h { |row| [row["locode"], row.fields("timezone", "timezone_source")] })
230
+ end
231
+
232
+ def self.timezone_port(locode, lat, lng, path)
233
+ Timezones::Port.new(locode:, lat: lat.to_s.empty? ? nil : lat.to_f, lng: lng.to_s.empty? ? nil : lng.to_f, path: path.to_s.split)
234
+ end
235
+
202
236
  # Writes the supplementary positions in +layers+ (see coordinate_layers; a
203
237
  # flat { locode => [lat, lng] } counts as the "override" layer) into the
204
238
  # table at +path+, without a download: how a reviewed row reaches the table
@@ -214,14 +248,14 @@ module Seaports
214
248
  layers = { "override" => layers } if layers.values.first.is_a?(Array)
215
249
  changed = []
216
250
  rows = CSV.read(path, headers: true).map do |row|
217
- next row.fields if row["coordinate_source"] == "unlocode" || (row["coordinate_source"].nil? && !row["lat"].to_s.empty?)
251
+ next row.fields(*HEADERS) if row["coordinate_source"] == "unlocode" || (row["coordinate_source"].nil? && !row["lat"].to_s.empty?)
218
252
 
219
253
  source, point = layers.lazy.filter_map { |name, points| [name, points[row["locode"]]] if points[row["locode"]] }.first
220
254
  was = [row["lat"].to_s, row["lng"].to_s]
221
255
  row["lat"], row["lng"] = point
222
256
  row["coordinate_source"] = point && source
223
257
  changed << row["locode"] if was != [row["lat"].to_s, row["lng"].to_s]
224
- row.fields
258
+ row.fields(*HEADERS)
225
259
  end
226
260
  CSV.open(path, "w") do |csv|
227
261
  csv << HEADERS
@@ -256,9 +290,16 @@ module Seaports
256
290
  #
257
291
  # +alternate_names+ is a list of { locode => [names] }, best first (see
258
292
  # Builder.alternate_name_layers).
293
+ #
294
+ # +timezones+ (Seaports::Timezones) places each port in a time zone, with
295
+ # +timezone_overrides+ ({ locode => zone }) first. Without it the
296
+ # timezone columns stay empty, like the subdivision ones without
297
+ # +subdivisions+.
259
298
  def initialize(source, subdivisions: nil, boundaries: nil, overrides: {}, coordinate_overrides: {}, fallback_coordinates: [],
260
- alternate_names: [], rejected_names: {})
299
+ alternate_names: [], rejected_names: {}, timezones: nil, timezone_overrides: {})
261
300
  @source = source
301
+ @timezones = timezones
302
+ @timezone_overrides = timezone_overrides
262
303
  @alternate_names = alternate_names
263
304
  @rejected_names = rejected_names
264
305
  @subdivisions = subdivisions
@@ -271,7 +312,8 @@ module Seaports
271
312
  end
272
313
 
273
314
  # [locode, name, lat, lng, subdivision, principal_subdivision,
274
- # subdivision_path, subdivision_source, coordinate_source, alternate_names] per port, deduplicated and sorted
315
+ # subdivision_path, subdivision_source, coordinate_source, timezone,
316
+ # timezone_source, alternate_names] per port, deduplicated and sorted
275
317
  # by locode. The path is the subdivision and everything above it, space
276
318
  # separated, most specific first (see Seaports::Subdivisions#path).
277
319
  # Sorted because the file is committed: a stable order means a refresh
@@ -286,7 +328,10 @@ module Seaports
286
328
  # The last cell is the port's candidate names until each has been
287
329
  # compared with the rest of its country.
288
330
  names = AlternateNames.resolve(rows.map { |locode, name, *, candidates| [locode, name, candidates] })
289
- rows.map { |row| [*row[0..-2], AlternateNames.dump(names.fetch(row.first, []))] }
331
+ # So is its time zone, since a port with no position can take the
332
+ # zone its subdivision's other ports agree on.
333
+ zones = timezones_for(rows)
334
+ rows.map { |row| [*row[0..-2], *zones.fetch(row.first, [nil, nil]), AlternateNames.dump(names.fetch(row.first, []))] }
290
335
  end
291
336
  end
292
337
 
@@ -328,11 +373,37 @@ module Seaports
328
373
  superseded_points = @coordinates_superseded.uniq.sort.map do |locode, own, override|
329
374
  "`#{locode}` now has UN/LOCODE coordinates (#{own.join(', ')}, not #{override.join(', ')}): its coordinate override can go."
330
375
  end
331
- stale + superseded + stale_points + superseded_points
376
+ stale + superseded + stale_points + superseded_points + timezone_override_report
332
377
  end
333
378
 
334
379
  private
335
380
 
381
+ # The rows still end in their candidate names here; the path is the
382
+ # seventh cell.
383
+ def timezones_for(rows)
384
+ return {} if @timezones.nil?
385
+
386
+ @timezones.assign(rows.map { |locode, _, lat, lng, _, _, path| self.class.timezone_port(locode, lat, lng, path) },
387
+ overrides: @timezone_overrides)
388
+ end
389
+
390
+ # A time zone override whose port left the table, or that says what the
391
+ # port's own facts already give, can go.
392
+ def timezone_override_report
393
+ return [] if @timezones.nil?
394
+
395
+ ports = rows.to_h { |row| [row.first, row] }
396
+ @timezone_overrides.sort.filter_map do |locode, zone|
397
+ row = ports[locode]
398
+ next "`#{locode}` has a timezone override but is no longer a UN/LOCODE sea port: remove its row." if row.nil?
399
+
400
+ own, source = @timezones.zone_for(locode[0, 2], row[2], row[3])
401
+ next unless own == zone
402
+
403
+ "`#{locode}` is overridden to #{zone}, which its #{source == 'country' ? 'country' : 'position'} gives anyway: its timezone override can go."
404
+ end
405
+ end
406
+
336
407
  # UNECE classifies every entry by function, and position 1 of that string
337
408
  # is "port" — the only one a vessel can call at. Keeping the other 98k
338
409
  # entries would mean a road terminal or a postal exchange could answer a
data/lib/seaports/diff.rb CHANGED
@@ -44,7 +44,7 @@ module Seaports
44
44
  next if locode.empty?
45
45
 
46
46
  ports[locode] = { name: row["name"].to_s.strip, point: point(row), path: path(row), source: row["coordinate_source"].to_s.strip,
47
- alternates: row["alternate_names"].to_s.split("|").map(&:strip).reject(&:empty?) }
47
+ alternates: row["alternate_names"].to_s.split("|").map(&:strip).reject(&:empty?), zone: row["timezone"].to_s.strip }
48
48
  end
49
49
  end
50
50
 
@@ -82,7 +82,7 @@ module Seaports
82
82
  end
83
83
 
84
84
  def changed?
85
- !(added.empty? && removed.empty? && renamed.empty? && repositioned.empty? && resubdivided.empty? && renamed_alternates.empty?)
85
+ !(added.empty? && removed.empty? && renamed.empty? && repositioned.empty? && resubdivided.empty? && renamed_alternates.empty? && rezoned.empty?)
86
86
  end
87
87
 
88
88
  # [locode, name, names added, names removed] for a port that kept its code
@@ -161,10 +161,22 @@ module Seaports
161
161
  end
162
162
  end
163
163
 
164
+ # [locode, name, was, now] for a port whose time zone changed, each zone
165
+ # a string ("" for none). A table from before the column existed has
166
+ # none, so every zone is new.
167
+ def rezoned
168
+ @rezoned ||= common.filter_map do |locode|
169
+ was = @before[locode][:zone].to_s
170
+ now = @after[locode][:zone].to_s
171
+ [locode, @after[locode][:name], was, now] if was != now
172
+ end
173
+ end
174
+
164
175
  # Empty means the refresh may ship. Anything here is a reason it may not,
165
176
  # written the way it should read in an issue.
166
177
  def failures
167
- [count_failure, shrinkage_failure, region_failure, reassignment_failure, moved_failure, positions_failure, *anchor_failures, *excluded_failures].compact
178
+ [count_failure, shrinkage_failure, region_failure, zone_failure, reassignment_failure, moved_failure, positions_failure, *anchor_failures,
179
+ *excluded_failures].compact
168
180
  end
169
181
 
170
182
  def ok?
@@ -181,7 +193,8 @@ module Seaports
181
193
  section("Names", renamed_alternates.map { |locode, name, gained, dropped| names_line(locode, name, gained, dropped) }),
182
194
  by_source_line,
183
195
  section("Coordinates", repositioned.map { |locode, name, kind| "`#{locode}` #{name} — #{POSITION_WORDS.fetch(kind)}" }),
184
- section("Subdivision", resubdivided.map { |locode, name, was, now| "`#{locode}` #{name}: #{path_words(was)} → #{path_words(now)}" })
196
+ section("Subdivision", resubdivided.map { |locode, name, was, now| "`#{locode}` #{name}: #{path_words(was)} → #{path_words(now)}" }),
197
+ section("Time zone", rezoned.map { |locode, name, was, now| "`#{locode}` #{name}: #{was.empty? ? 'none' : was} → #{now.empty? ? 'none' : now}" })
185
198
  ].compact.join("\n\n")
186
199
  end
187
200
 
@@ -197,7 +210,8 @@ module Seaports
197
210
  "#{@after.size} sea ports (#{@before.size} before): " \
198
211
  "#{added.size} added, #{removed.size} removed, " \
199
212
  "#{renamed.size} renamed, #{repositioned.size} repositioned, " \
200
- "#{resubdivided.size} with a new subdivision (#{reassigned.size} moved to another principal one)."
213
+ "#{resubdivided.size} with a new subdivision (#{reassigned.size} moved to another principal one), " \
214
+ "#{rezoned.size} with a new time zone."
201
215
  end
202
216
 
203
217
  # A real refresh moves a handful of ports between regions, when UNECE
@@ -302,6 +316,19 @@ module Seaports
302
316
  "Ports with a principal subdivision fell from #{was} to #{now}, past the #{(MAXIMUM_SHRINKAGE * 100).round}% limit."
303
317
  end
304
318
 
319
+ # The same for time zones: losing them in bulk means the map failed to
320
+ # load, not that ports changed clocks.
321
+ def zone_failure
322
+ was = @before.count { |_, port| !port[:zone].to_s.empty? }
323
+ return nil if was.zero?
324
+
325
+ now = @after.count { |_, port| !port[:zone].to_s.empty? }
326
+ shrinkage = (was - now).to_f / was
327
+ return nil if shrinkage <= MAXIMUM_SHRINKAGE
328
+
329
+ "Ports with a time zone fell from #{was} to #{now}, past the #{(MAXIMUM_SHRINKAGE * 100).round}% limit."
330
+ end
331
+
305
332
  def regioned_count(ports)
306
333
  ports.count { |_, port| !port[:path].to_s.empty? }
307
334
  end
data/lib/seaports/http.rb CHANGED
@@ -19,9 +19,9 @@ module Seaports
19
19
  USER_AGENT = "seaports-gem/#{VERSION} (https://github.com/Trackberry/seaports)"
20
20
  REDIRECTS = 5
21
21
 
22
- # The largest body read. The biggest thing fetched is Natural Earth's
23
- # 40 MB map; a body past this is the wrong document, and reading it all
24
- # would only fill the disk.
22
+ # The largest body read. The biggest things fetched are the time zone
23
+ # map, a 56 MB zip, and Natural Earth's 40 MB one; a body past this is
24
+ # the wrong document, and reading it all would only fill the disk.
25
25
  MAX_BYTES = 120 * 1024 * 1024
26
26
 
27
27
  class TooLarge < StandardError; end
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csv"
4
+ require "json"
5
+ require "set"
6
+
7
+ module Seaports
8
+ # Which IANA time zone a port keeps its clock in: "Europe/Madrid" for
9
+ # Valencia, "Atlantic/Canary" for Las Palmas.
10
+ #
11
+ # A tracking feed that sends a local time with no offset ("arrives 05:30"),
12
+ # or an offset taken in winter for a call made in summer, can only be read
13
+ # right with the port's zone, which gives the offset for any date. UN/LOCODE
14
+ # publishes none, so it is worked out here, best first:
15
+ #
16
+ # - override: a reviewed row in data/sources/timezone_overrides.csv;
17
+ # - country: the country's zone, when tzdata gives the country only one,
18
+ # which is most of them and needs no position. Every Dutch port is in
19
+ # Europe/Amsterdam, wherever UN/LOCODE put it;
20
+ # - map: the zone the port's position falls in on timezone-boundary-builder's
21
+ # map, when it is one of the country's;
22
+ # - nearest: else the nearest of the country's zones, within
23
+ # NEAREST_WITHIN_KM of a position on someone's land or territorial sea (a
24
+ # border port whose coarse position lands next door: Detroit, on the
25
+ # Canadian side of its river), or OFFSHORE_WITHIN_KM of one out at sea (an
26
+ # oil terminal on the North West Shelf);
27
+ # - subdivision: for a port nothing above places, the zone every port the
28
+ # map placed in the same subdivision is in, when at least
29
+ # SUBDIVISION_MINIMUM of them are and they all agree. Bavaria's are all in
30
+ # Europe/Berlin, so a Bavarian port with no position is too; Florida's are
31
+ # split between New York and Chicago, so one with no position gets none.
32
+ #
33
+ # A zone is only ever one tzdata lists for the port's country (zone.tab),
34
+ # so a Spanish port is in Europe/Madrid, Africa/Ceuta or Atlantic/Canary and
35
+ # nothing else. A country zone.tab does not list (XZ, installations in
36
+ # international waters) takes whatever zone the map has, the ocean's
37
+ # Etc/GMT ones included.
38
+ #
39
+ # Build-time only, like Seaports::Boundaries: the map is 176 MB and needs
40
+ # GEOS, through the rgeo gem. The zones it finds are written into the table,
41
+ # and the gem reads them as strings.
42
+ class Timezones
43
+ # Pinned, like the other sources, so the map only changes when someone
44
+ # moves this line, and with it zone.tab from the same tzdata release.
45
+ RELEASE = "2026f"
46
+ SOURCE_URL = "https://github.com/evansiroky/timezone-boundary-builder/releases/download/#{RELEASE}/timezones-with-oceans.geojson.zip"
47
+
48
+ # tzdata's zone.tab, vendored from the same release as the map: the zones
49
+ # each country uses. tzdata calls it deprecated in favour of
50
+ # zone1970.tab, which files several countries under one zone; zone.tab
51
+ # keeps one country per zone, with the names the map draws
52
+ # (Europe/Copenhagen, which tzdata has linked to Europe/Berlin since
53
+ # 2022b). Public domain.
54
+ ZONE_TAB_PATH = File.expand_path("../../data/sources/zone.tab", __dir__)
55
+ ZONE_TAB_URL = "https://raw.githubusercontent.com/eggert/tz/#{RELEASE}/zone.tab"
56
+
57
+ OVERRIDES_PATH = File.expand_path("../../data/sources/timezone_overrides.csv", __dir__)
58
+
59
+ NEAREST_WITHIN_KM = 50
60
+ OFFSHORE_WITHIN_KM = 250
61
+ SUBDIVISION_MINIMUM = 3
62
+
63
+ # A GEOS distance is in degrees, read here as degrees of latitude. A
64
+ # degree of longitude is shorter by the cosine of the latitude, so a
65
+ # distance read this way is never shorter than the true one, and the
66
+ # reach east-west is that much less than the figures above: 25 and 125 km
67
+ # at 60° N. Short of the reach, never past it.
68
+ KM_PER_DEGREE = 111.32
69
+
70
+ # The map's zones for the open sea, past every country's territorial
71
+ # waters: Etc/GMT+5, Etc/GMT-8 and so on.
72
+ OCEAN = %r{\AEtc/}
73
+
74
+ SOURCES = %w[override country map nearest subdivision].freeze
75
+ BY_POSITION = %w[map nearest].freeze
76
+
77
+ # { "ES" => ["Europe/Madrid", "Africa/Ceuta", "Atlantic/Canary"], ... }
78
+ # from zone.tab's text.
79
+ def self.countries(text = File.read(ZONE_TAB_PATH))
80
+ text.each_line.with_object({}) do |line, countries|
81
+ next if line.start_with?("#") || line.strip.empty?
82
+
83
+ country, _, zone = line.split("\t")
84
+ (countries[country] ||= []) << zone.strip
85
+ end.transform_values(&:freeze).freeze
86
+ end
87
+
88
+ # Reads OVERRIDES_PATH (or +path+) into { locode => zone }. Typed by
89
+ # people, so a malformed locode or zone, a missing note or a port listed
90
+ # twice stops the build with the line to fix. Whether the zone is one of
91
+ # the port's country is checked where the country is known: see #assign.
92
+ def self.overrides(path = OVERRIDES_PATH)
93
+ return {} unless File.exist?(path)
94
+
95
+ CSV.foreach(path, headers: true).with_index(2).each_with_object({}) do |(row, line), overrides|
96
+ locode = row["locode"].to_s.strip.upcase
97
+ zone = row["timezone"].to_s.strip
98
+ raise ArgumentError, "#{path}:#{line}: #{locode.inspect} is not a locode" unless locode.match?(/\A[A-Z]{2}[A-Z0-9]{3}\z/)
99
+ raise ArgumentError, "#{path}:#{line}: #{locode} has no valid timezone" unless zone.match?(%r{\A[A-Za-z_]+(/[A-Za-z0-9_+-]+)+\z})
100
+ raise ArgumentError, "#{path}:#{line}: #{locode} has no note" if row["note"].to_s.strip.empty?
101
+ raise ArgumentError, "#{path}:#{line}: #{locode} is listed twice" if overrides.key?(locode)
102
+
103
+ overrides[locode] = zone
104
+ end
105
+ end
106
+
107
+ # The map is a FeatureCollection with a "tzid" on each feature.
108
+ def self.parse(geojson, countries: self.countries)
109
+ load_geos!
110
+ factory = RGeo::Geos.factory(native_interface: :capi)
111
+ zones = JSON.parse(geojson).fetch("features").filter_map do |feature|
112
+ id = feature.dig("properties", "tzid")
113
+ text = wkt(feature["geometry"])
114
+ next if id.nil? || text.nil?
115
+
116
+ [id, factory.parse_wkt(text)]
117
+ end
118
+ new(zones, countries, factory)
119
+ end
120
+
121
+ # A Polygon or MultiPolygon as WKT, which GEOS reads without a Ruby
122
+ # object per vertex.
123
+ def self.wkt(geometry)
124
+ polygons =
125
+ case geometry&.fetch("type")
126
+ when "Polygon" then [geometry.fetch("coordinates")]
127
+ when "MultiPolygon" then geometry.fetch("coordinates")
128
+ end
129
+ return nil if polygons.nil? || polygons.empty?
130
+
131
+ text = polygons.map { |rings| "(#{rings.map { |ring| "(#{ring.map { |lng, lat| "#{lng} #{lat}" }.join(', ')})" }.join(', ')})" }
132
+ "MULTIPOLYGON (#{text.join(', ')})"
133
+ end
134
+
135
+ # The release's GeoJSON is a zip holding one file. Ruby has no zip reader
136
+ # of its own, so this asks unzip, which every machine that builds the
137
+ # table has.
138
+ def self.unzip(path)
139
+ require "open3"
140
+ text, error, status = Open3.capture3("unzip", "-p", path)
141
+ raise "unzip #{path} failed: #{error.strip}" unless status.success?
142
+
143
+ text
144
+ end
145
+
146
+ def self.load_geos!
147
+ require "rgeo"
148
+ return if RGeo::Geos.capi_supported?
149
+
150
+ raise LoadError, "timezones need GEOS at build time, and the rgeo gem was installed without it: " \
151
+ "brew install geos (or apt-get install libgeos-dev), then gem pristine rgeo"
152
+ end
153
+
154
+ Zone = Data.define(:id, :geometry, :bbox)
155
+
156
+ # One port, as #assign reads it. +path+ is its subdivision path, most
157
+ # specific first, as the table writes it.
158
+ Port = Data.define(:locode, :lat, :lng, :path) do
159
+ def country = locode[0, 2]
160
+ end
161
+
162
+ attr_reader :countries
163
+
164
+ # +zones+ is [[id, GEOS geometry], ...]; +countries+ as Timezones.countries.
165
+ def initialize(zones, countries, factory)
166
+ @factory = factory
167
+ @countries = countries
168
+ @zones = zones.map do |id, geometry|
169
+ geometry.prepare! if geometry.respond_to?(:prepare!)
170
+ Zone.new(id:, geometry:, bbox: bbox(geometry))
171
+ end
172
+ @ids = @zones.to_set(&:id)
173
+ end
174
+
175
+ # Whether +zone+ is one a port of +country+ may be in: one of its
176
+ # zone.tab zones, or, for a country zone.tab does not list, any zone the
177
+ # map draws.
178
+ def valid?(country, zone)
179
+ own = @countries[country]
180
+ own ? own.include?(zone) : @ids.include?(zone)
181
+ end
182
+
183
+ # { locode => [zone, source] } for +ports+ (Timezones::Port), every
184
+ # source one of SOURCES; [nil, nil] for a port nothing places.
185
+ # +overrides+ is { locode => zone }, and one that is not a zone of the
186
+ # port's country stops the build.
187
+ def assign(ports, overrides: {})
188
+ placed = ports.to_h do |port|
189
+ override = overrides[port.locode]
190
+ if override
191
+ raise ArgumentError, "#{port.locode}: override #{override} is not a time zone of #{port.country}" unless valid?(port.country, override)
192
+
193
+ next [port.locode, [override, "override"]]
194
+ end
195
+ [port.locode, zone_for(port.country, port.lat, port.lng)]
196
+ end
197
+ by_subdivision = subdivision_zones(ports, placed)
198
+ ports.each do |port|
199
+ next unless placed[port.locode].first.nil?
200
+
201
+ zone = port.path.lazy.map { |code| by_subdivision[code] }.find { |zones| zones }
202
+ placed[port.locode] = [zone.first, "subdivision"] if zone&.size == 1 && valid?(port.country, zone.first)
203
+ end
204
+ placed
205
+ end
206
+
207
+ # [zone, source] for one port from its own facts, the subdivision step
208
+ # aside (it needs the others), or [nil, nil].
209
+ def zone_for(country, lat, lng)
210
+ own = @countries[country]
211
+ return [own.first, "country"] if own&.size == 1
212
+ return [nil, nil] if lat.nil? || lng.nil?
213
+
214
+ found = zone_at(lat, lng)
215
+ return [found, "map"] if found && (own.nil? || own.include?(found))
216
+ return [nil, nil] if own.nil?
217
+
218
+ within = found.nil? || found.match?(OCEAN) ? OFFSHORE_WITHIN_KM : NEAREST_WITHIN_KM
219
+ near = nearest(own, lat, lng, within)
220
+ near ? [near, "nearest"] : [nil, nil]
221
+ end
222
+
223
+ # Ports placed by their position in another zone than every other port
224
+ # placed by position in one of their subdivisions, when there are at
225
+ # least SUBDIVISION_MINIMUM others: [locode, zone, subdivision, their
226
+ # zone]. Most are real exceptions (Fort Frances keeps Central time in
227
+ # Ontario, Easter Island its own in Valparaíso); the rest are positions
228
+ # in the wrong place, for a person to check and override. +placed+ is
229
+ # what #assign returned.
230
+ def disagreements(ports, placed)
231
+ counts = subdivision_counts(ports, placed)
232
+ ports.filter_map do |port|
233
+ zone, source = placed[port.locode]
234
+ next unless BY_POSITION.include?(source)
235
+
236
+ port.path.lazy.filter_map do |code|
237
+ others = counts[code].dup
238
+ others[zone] -= 1
239
+ others.delete_if { |_, count| count <= 0 }
240
+ [port.locode, zone, code, others.keys.first] if others.size == 1 && others.keys.first != zone && others.values.first >= SUBDIVISION_MINIMUM
241
+ end.first
242
+ end
243
+ end
244
+
245
+ # The id of the zone the map has the point in, or nil.
246
+ def zone_at(lat, lng)
247
+ point = @factory.point(lng, lat)
248
+ @zones.find { |zone| within_bbox?(zone, lat, lng, 0, 0) && zone.geometry.contains?(point) }&.id
249
+ end
250
+
251
+ private
252
+
253
+ # { subdivision code => { zone => ports } } over the ports placed by
254
+ # position, at every level of each one's path. Only map and nearest
255
+ # count: a country's single zone says nothing about where a subdivision
256
+ # is, and an override is one port's.
257
+ def subdivision_counts(ports, placed)
258
+ ports.each_with_object(Hash.new { |hash, code| hash[code] = Hash.new(0) }) do |port, counts|
259
+ zone, source = placed[port.locode]
260
+ next unless BY_POSITION.include?(source)
261
+
262
+ port.path.each { |code| counts[code][zone] += 1 }
263
+ end
264
+ end
265
+
266
+ # { subdivision code => [zones] }, for codes with at least
267
+ # SUBDIVISION_MINIMUM ports placed by position.
268
+ def subdivision_zones(ports, placed)
269
+ subdivision_counts(ports, placed).select { |_, zones| zones.values.sum >= SUBDIVISION_MINIMUM }.transform_values(&:keys)
270
+ end
271
+
272
+ def nearest(ids, lat, lng, within_km)
273
+ point = @factory.point(lng, lat)
274
+ lat_margin = within_km / KM_PER_DEGREE
275
+ lng_margin = lat_margin / [Math.cos(lat * Math::PI / 180), 0.01].max
276
+ best = @zones.select { |zone| ids.include?(zone.id) && within_bbox?(zone, lat, lng, lat_margin, lng_margin) }
277
+ .map { |zone| [zone.id, zone.geometry.distance(point) * KM_PER_DEGREE] }
278
+ .min_by(&:last)
279
+ best && best.last <= within_km ? best.first : nil
280
+ end
281
+
282
+ def within_bbox?(zone, lat, lng, lat_margin, lng_margin)
283
+ min_lng, min_lat, max_lng, max_lat = zone.bbox
284
+ lng.between?(min_lng - lng_margin, max_lng + lng_margin) && lat.between?(min_lat - lat_margin, max_lat + lat_margin)
285
+ end
286
+
287
+ def bbox(geometry)
288
+ envelope = geometry.envelope
289
+ points = envelope.respond_to?(:exterior_ring) ? envelope.exterior_ring.points : [envelope]
290
+ [points.map(&:x).min, points.map(&:y).min, points.map(&:x).max, points.map(&:y).max]
291
+ end
292
+ end
293
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Seaports
4
- VERSION = "1.8.0"
4
+ VERSION = "1.9.0"
5
5
 
6
6
  # The UN/LOCODE edition the shipped table was built from, when the source
7
7
  # names one: UNECE labels each release by year and half, so "2024-2" is the
data/lib/seaports.rb CHANGED
@@ -69,10 +69,23 @@ module Seaports
69
69
  # +name+ is "Antwerpen". Never the +name+ itself; [] when there are none.
70
70
  # Their sources are in the README. A name is never another port's own name
71
71
  # in the same country, and never one that several ports of a country share.
72
+ #
73
+ # +timezone+ (added in 1.9.0) is the IANA time zone the port keeps its
74
+ # clock in, as a string: "Europe/Madrid" for Valencia, "Atlantic/Canary"
75
+ # for Las Palmas, "America/Chicago" for the Louisiana Offshore Oil Port.
76
+ # Hand it to TZInfo (or ActiveSupport::TimeZone) for the offset on a given
77
+ # date, which a fixed offset from one feed message cannot give across a
78
+ # daylight saving change. Always one of the zones tzdata lists for the
79
+ # port's country, except in XZ and HM, which it lists none for: their
80
+ # ports take the map's zone where they are, often the open sea's Etc/GMT
81
+ # ones, whose sign is POSIX's (Etc/GMT-5 is UTC+5). Nil when nothing places the port: a port with no
82
+ # position in a country with several zones, unless the other ports of its
83
+ # subdivision agree on one. How each was found is in the README.
72
84
  NO_NAMES = [].freeze
73
85
 
74
- Port = Data.define(:locode, :name, :coordinates, :subdivision, :principal_subdivision, :subdivision_path, :alternate_names) do
75
- def initialize(locode:, name:, coordinates:, subdivision: nil, principal_subdivision: nil, subdivision_path: [], alternate_names: NO_NAMES)
86
+ Port = Data.define(:locode, :name, :coordinates, :subdivision, :principal_subdivision, :subdivision_path, :alternate_names, :timezone) do
87
+ def initialize(locode:, name:, coordinates:, subdivision: nil, principal_subdivision: nil, subdivision_path: [], alternate_names: NO_NAMES,
88
+ timezone: nil)
76
89
  super
77
90
  end
78
91
  end
@@ -122,6 +135,11 @@ module Seaports
122
135
  find(locode)&.alternate_names || NO_NAMES
123
136
  end
124
137
 
138
+ # "Europe/Madrid" for ESVLC, or nil. See Port.
139
+ def timezone(locode)
140
+ find(locode)&.timezone
141
+ end
142
+
125
143
  # The port's outline as GeoJSON: a deep-frozen FeatureCollection with
126
144
  # "locode", "quays" and "attribution" beside its features, ready for a
127
145
  # map. Nil for a port with no outline, which is most of them: see
@@ -269,7 +287,7 @@ module Seaports
269
287
  ports[locode] = Port.new(locode: locode, name: row["name"], coordinates: point(row),
270
288
  subdivision: presence(row["subdivision"]), principal_subdivision: presence(row["principal_subdivision"]),
271
289
  subdivision_path: row["subdivision_path"].to_s.split.freeze,
272
- alternate_names: names_of(row))
290
+ alternate_names: names_of(row), timezone: zone_of(row))
273
291
  end
274
292
  end
275
293
 
@@ -280,6 +298,13 @@ module Seaports
280
298
  names.empty? ? NO_NAMES : names.freeze
281
299
  end
282
300
 
301
+ # Interned: 17,000 ports name 360 zones, so they share one string per
302
+ # zone rather than holding one each.
303
+ def zone_of(row)
304
+ zone = presence(row["timezone"])
305
+ zone && -zone
306
+ end
307
+
283
308
  def point(row)
284
309
  return nil if blank?(row["lat"]) || blank?(row["lng"])
285
310
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: seaports
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.8.0
4
+ version: 1.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Édouard Brière
@@ -187,6 +187,7 @@ files:
187
187
  - lib/seaports/http.rb
188
188
  - lib/seaports/release.rb
189
189
  - lib/seaports/subdivisions.rb
190
+ - lib/seaports/timezones.rb
190
191
  - lib/seaports/version.rb
191
192
  - lib/seaports/wikidata.rb
192
193
  - lib/seaports/wpi.rb