opentideconstants 0.0.0 → 0.1.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.
- checksums.yaml +4 -4
- data/README.md +132 -3
- data/lib/opentideconstants/bgzf.rb +436 -0
- data/lib/opentideconstants/cache.rb +559 -0
- data/lib/opentideconstants/cache_json.rb +67 -0
- data/lib/opentideconstants/canonical.rb +756 -0
- data/lib/opentideconstants/canonical_types.rb +2537 -0
- data/lib/opentideconstants/client.rb +1135 -0
- data/lib/opentideconstants/downloader.rb +400 -0
- data/lib/opentideconstants/errors.rb +210 -0
- data/lib/opentideconstants/fold.rb +24 -0
- data/lib/opentideconstants/historical_fingerprint.rb +58 -0
- data/lib/opentideconstants/http.rb +483 -0
- data/lib/opentideconstants/models.rb +635 -0
- data/lib/opentideconstants/name_fold.json +949 -0
- data/lib/opentideconstants/predict/astro.rb +85 -0
- data/lib/opentideconstants/predict/daily-facts.json +1 -0
- data/lib/opentideconstants/predict/daily.rb +62 -0
- data/lib/opentideconstants/predict/engine.rb +506 -0
- data/lib/opentideconstants/predict/harmonic.rb +228 -0
- data/lib/opentideconstants/predict/local.rb +49 -0
- data/lib/opentideconstants/predict/results.rb +357 -0
- data/lib/opentideconstants/predict/retained.rb +487 -0
- data/lib/opentideconstants/predict.rb +192 -0
- data/lib/opentideconstants/reader.rb +493 -0
- data/lib/opentideconstants/release.rb +1531 -0
- data/lib/opentideconstants/version.rb +15 -0
- data/lib/opentideconstants.rb +24 -3
- data/supported-formats.json +5 -0
- metadata +37 -5
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
require_relative "retained"
|
|
2
|
+
|
|
3
|
+
class OpenTideConstants
|
|
4
|
+
module Predict
|
|
5
|
+
Context = Struct.new(:station, :constants, :table, :method, :reference, :reference_bin, :bin_number, :offsets,
|
|
6
|
+
:selected_offset_id, :total, :minor, :current_bin, :sigma, :datum_name, :datum_kind, :datum_uncertainty,
|
|
7
|
+
:datum_method, :datum_flags, :omitted, :profile_info, :event_default, keyword_init: true)
|
|
8
|
+
module_function
|
|
9
|
+
def astro_table(release, id = nil)
|
|
10
|
+
release.send(:check_open!)
|
|
11
|
+
raise InvalidArgumentError, "astro table id must be a string" unless id.nil? || id.is_a?(String)
|
|
12
|
+
id ||= release.conventions.find { |c| c.raw["astro_table_id"] }&.raw&.fetch("astro_table_id")
|
|
13
|
+
return nil unless id
|
|
14
|
+
raw = Array(release.instance_variable_get(:@meta)["astro_tables"]).find { |t| t["astro_table_id"] == id }
|
|
15
|
+
raw && AstroTable.new(raw)
|
|
16
|
+
end
|
|
17
|
+
def station_for(release, station)
|
|
18
|
+
release.send(:check_open!)
|
|
19
|
+
return release.require_station(station) if station.is_a?(String)
|
|
20
|
+
raise InvalidArgumentError, "station must be a Station or station id" unless station.is_a?(Station)
|
|
21
|
+
release.send(:own_station!, station, "prediction")
|
|
22
|
+
release.require_station(station.station_id)
|
|
23
|
+
end
|
|
24
|
+
def options(set_id, datum = nil, bin_number = nil)
|
|
25
|
+
raise InvalidArgumentError, "set_id must be a string" unless set_id.nil? || set_id.is_a?(String)
|
|
26
|
+
raise InvalidArgumentError, "datum must be a string" unless datum.nil? || datum.is_a?(String)
|
|
27
|
+
unless bin_number.nil? || bin_number.is_a?(Integer) && bin_number.between?(1, 2**53 - 1)
|
|
28
|
+
raise InvalidArgumentError, "bin_number must be an integer from1to2^53-1"
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
def window(start, stop, step = nil)
|
|
32
|
+
first, last = instant(start), instant(stop)
|
|
33
|
+
raise InvalidArgumentError, "start must not be after stop" if first > last
|
|
34
|
+
raise InvalidArgumentError, "step_s must be a positive integer" unless step.nil? || step.is_a?(Integer) && step > 0
|
|
35
|
+
[first, last]
|
|
36
|
+
end
|
|
37
|
+
def chosen(release, station, set_id)
|
|
38
|
+
return station.__send__(:prediction_recommendation) if set_id.nil?
|
|
39
|
+
constants = station.constant_set(set_id)
|
|
40
|
+
raise InvalidArgumentError, "set_id #{set_id.inspect} is not a set of #{station.station_id}" unless constants
|
|
41
|
+
if release.instance_variable_get(:@commercial_only) && !release.send(:commercial_set?, constants.raw)
|
|
42
|
+
raise InvalidArgumentError, "commercial_only refuses set_id"
|
|
43
|
+
end
|
|
44
|
+
constants
|
|
45
|
+
end
|
|
46
|
+
def default_event_offset_id(release, station)
|
|
47
|
+
station = station_for(release, station)
|
|
48
|
+
return nil if station.raw["prediction_profiles"]&.key?("observed-best")
|
|
49
|
+
constants = chosen(release, station, nil)
|
|
50
|
+
return nil unless station.type == :subordinate && constants && constants.quantity == :water_level &&
|
|
51
|
+
constants.source == "fes2022" && constants.source_type == :model && constants.qc_status == :flagged &&
|
|
52
|
+
constants.fallback && station.recommended_is_fallback == true
|
|
53
|
+
offsets = station.raw["subordinate_offsets"]
|
|
54
|
+
return nil unless offsets && offsets["offset_id"].nil? && offsets["vintage"].nil?
|
|
55
|
+
station.subordinate_offsets.offset_id
|
|
56
|
+
end
|
|
57
|
+
def datum_declaration(source, candidate, field_path, scope: "station", set_id: nil)
|
|
58
|
+
DatumDeclaration.new(scope: scope, set_id: set_id, source: source["source"],
|
|
59
|
+
source_record_id: source["source_record_id"], source_version: source["source_version"],
|
|
60
|
+
disposition: source["disposition"], licence_id: source["licence_id"], upstream_licence_id: source["upstream_licence_id"],
|
|
61
|
+
published_set_ids: source["published_set_ids"] || [], field_path: field_path,
|
|
62
|
+
candidate: candidate, provenance: source["provenance"])
|
|
63
|
+
end
|
|
64
|
+
def datum_path(path, key)
|
|
65
|
+
path + "[#{JSON.generate(key)}]"
|
|
66
|
+
end
|
|
67
|
+
def datum_set_owner(station, model)
|
|
68
|
+
owners = Array(station.raw["source_records"]).each_with_index.select do |source, _|
|
|
69
|
+
normalized = {"gesla" => "gesla-fit", "ticon" => "ticon-4"}.fetch(source["source"], source["source"])
|
|
70
|
+
normalized == model["source"] && %w[source_record_id source_version source_model].all? { |key| source[key] == model[key] } &&
|
|
71
|
+
Array(source["published_set_ids"]).include?(model["set_id"])
|
|
72
|
+
end
|
|
73
|
+
owners.length == 1 ? owners.first : nil
|
|
74
|
+
end
|
|
75
|
+
def datum_qualifications(release, model, path, owner = nil)
|
|
76
|
+
qualifications = []
|
|
77
|
+
add = lambda do |field_path, value, nonempty = true|
|
|
78
|
+
qualifications << {"field_path" => field_path, "value" => value} unless value.nil? || nonempty && value.respond_to?(:empty?) && value.empty?
|
|
79
|
+
end
|
|
80
|
+
add.call(datum_path(path, "qc_status"), model["qc_status"], false) unless model["qc_status"] == "ok"
|
|
81
|
+
add.call(datum_path(path, "qc_flags"), model["qc_flags"])
|
|
82
|
+
%w[fallback vintage].each { |key| add.call(datum_path(path, key), model[key], false) }
|
|
83
|
+
datum = model["datum"] || {}
|
|
84
|
+
datum_prefix = datum_path(path, "datum")
|
|
85
|
+
%w[flags limitations reliability fallback].each { |key| add.call(datum_path(datum_prefix, key), datum[key]) }
|
|
86
|
+
(datum["basis"] || {}).keys.sort.each do |key|
|
|
87
|
+
basis = datum["basis"][key]
|
|
88
|
+
next unless basis.is_a?(Hash)
|
|
89
|
+
prefix = datum_path(datum_path(datum_prefix, "basis"), key)
|
|
90
|
+
add.call(datum_path(prefix, "kind"), basis["kind"], false) unless basis["kind"] == "published"
|
|
91
|
+
%w[flags limitations reliability fallback].each { |field| add.call(datum_path(prefix, field), basis[field]) }
|
|
92
|
+
end
|
|
93
|
+
if owner && owner.first["disposition"] != "retained"
|
|
94
|
+
add.call(datum_path("$[\"source_records\"][#{owner.last}]", "disposition"), owner.first["disposition"], false)
|
|
95
|
+
end
|
|
96
|
+
%w[licence_id upstream_licence_id].each do |key|
|
|
97
|
+
next unless model[key]
|
|
98
|
+
Array(release.instance_variable_get(:@meta)["licences"]).each_with_index do |licence, index|
|
|
99
|
+
if licence["licence_id"] == model[key] && licence.key?("commercial_use") && licence["commercial_use"] != true
|
|
100
|
+
qualifications << {"field_path" => "$release[\"licences\"][#{index}][\"commercial_use\"]", "value" => licence["commercial_use"]}
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
qualifications.uniq
|
|
105
|
+
end
|
|
106
|
+
def datum_metadata_value(value, keys)
|
|
107
|
+
keys.reduce(value) { |item, key| item.is_a?(Hash) ? item[key] : nil }
|
|
108
|
+
end
|
|
109
|
+
def datum_decoded(value, type)
|
|
110
|
+
return nil unless value.is_a?(String)
|
|
111
|
+
parsed = JSON.parse(value)
|
|
112
|
+
parsed if parsed.is_a?(type)
|
|
113
|
+
rescue JSON::ParserError
|
|
114
|
+
nil
|
|
115
|
+
end
|
|
116
|
+
def datum_metadata_declarations(source, path, declarations)
|
|
117
|
+
metadata = source["original_metadata"] || {}
|
|
118
|
+
add = lambda do |keys, root = metadata, prefix = path|
|
|
119
|
+
value = datum_metadata_value(root, keys)
|
|
120
|
+
field_path = keys.reduce(prefix) { |current, key| datum_path(current, key) }
|
|
121
|
+
declarations << datum_declaration(source, value, field_path) unless value.nil?
|
|
122
|
+
end
|
|
123
|
+
add.call(["DATUM INFORMATION"])
|
|
124
|
+
add.call(["source_header", "DATUM INFORMATION"])
|
|
125
|
+
row = datum_decoded(metadata["original_row_json"], Hash)
|
|
126
|
+
add.call(["DATUM INFORMATION"], row, datum_path(path, "original_row_json") + "::json") if row
|
|
127
|
+
%w[datum_elevation_cm msl_above_datum_cm msl_elevation_cm].each do |key|
|
|
128
|
+
add.call(["source_parsed_harmonics", "station", key])
|
|
129
|
+
end
|
|
130
|
+
models = datum_decoded(metadata["harmonic_models_json"], Array)
|
|
131
|
+
return unless models
|
|
132
|
+
[["datum"], %w[source_observations declared_input measurement datum]].each do |keys|
|
|
133
|
+
models.each_with_index do |model, index|
|
|
134
|
+
add.call(keys, model, datum_path(path, "harmonic_models_json") + "::json[#{index}]")
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
def datum_prediction_binding(constants, offsets)
|
|
139
|
+
datum = (constants ? constants.raw["datum"] : offsets && offsets["datum"]) || {}
|
|
140
|
+
chart = datum["chart_datum"]
|
|
141
|
+
chart = nil unless chart.is_a?(String) && !chart.empty?
|
|
142
|
+
finite = ->(value) { value.is_a?(Numeric) && value.finite? }
|
|
143
|
+
bound = if constants
|
|
144
|
+
chart && finite.call((datum["named"] || {})[chart]) && (finite.call(datum["msl_offset_m"]) || datum["zero"] == "harmonic_mean")
|
|
145
|
+
else
|
|
146
|
+
chart && datum["zero"] == "chart_datum"
|
|
147
|
+
end
|
|
148
|
+
limitations = []
|
|
149
|
+
[datum, (datum["basis"] || {})[chart] || {}].each_with_index do |entry, index|
|
|
150
|
+
limitations << entry["kind"] if index == 1 && entry["kind"] != "published"
|
|
151
|
+
%w[flags limitations].each { |key| limitations.concat(Array(entry[key])) }
|
|
152
|
+
limitations.concat(Array((entry["reliability"] || {})["limitations"]))
|
|
153
|
+
limitations << (entry["fallback"] || {})["reason"]
|
|
154
|
+
end
|
|
155
|
+
if !bound && constants && constants.source == "fes2022" && constants.source_type == :model
|
|
156
|
+
limitations << "model_zero_not_bound_to_chart_datum"
|
|
157
|
+
end
|
|
158
|
+
limitations = limitations.select { |value| value.is_a?(String) && !value.empty? }.uniq
|
|
159
|
+
DatumPredictionBinding.new(chart_datum: bound ? chart : nil, status: bound ? (limitations.empty? ? "bound" : "qualified") : "unbound", limitations: limitations)
|
|
160
|
+
end
|
|
161
|
+
def datum_sources(release, station, constants, requested_set_id)
|
|
162
|
+
declarations = []
|
|
163
|
+
raw_sets = Array(station.raw["constant_sets"])
|
|
164
|
+
Array(station.raw["source_records"]).each_with_index do |source, index|
|
|
165
|
+
Array(source["retained_datums"]).each_with_index do |candidate, candidate_index|
|
|
166
|
+
next if candidate.nil?
|
|
167
|
+
set_id = candidate.is_a?(Hash) ? candidate["set_id"] : nil
|
|
168
|
+
model = set_id.is_a?(String) && !set_id.empty? ? raw_sets.find { |item| item["set_id"] == set_id } : nil
|
|
169
|
+
owner = model && datum_set_owner(station, model)
|
|
170
|
+
bound = owner && owner.last == index && (!candidate.key?("source_record_id") || candidate["source_record_id"] == source["source_record_id"]) &&
|
|
171
|
+
(!(candidate["input_binding"] || {}).key?("set_id") || candidate["input_binding"]["set_id"] == set_id)
|
|
172
|
+
next if bound && requested_set_id && set_id != requested_set_id
|
|
173
|
+
declarations << datum_declaration(source, candidate, "$[\"source_records\"][#{index}][\"retained_datums\"][#{candidate_index}]",
|
|
174
|
+
scope: bound ? "set" : "station", set_id: bound ? set_id : nil)
|
|
175
|
+
end
|
|
176
|
+
datum_metadata_declarations(source, "$[\"source_records\"][#{index}][\"original_metadata\"]", declarations)
|
|
177
|
+
end
|
|
178
|
+
alternatives = raw_sets.each_with_index.map do |model, index|
|
|
179
|
+
datum = model["datum"]
|
|
180
|
+
path = "$[\"constant_sets\"][#{index}]"
|
|
181
|
+
owner = datum_set_owner(station, model)
|
|
182
|
+
if datum && (requested_set_id.nil? || requested_set_id == model["set_id"])
|
|
183
|
+
metadata = model.merge("disposition" => owner && owner.first["disposition"], "published_set_ids" => owner ? owner.first["published_set_ids"] : [])
|
|
184
|
+
metadata["provenance"] = owner.first["provenance"] if !model.key?("provenance") && owner
|
|
185
|
+
declarations << datum_declaration(metadata, datum, datum_path(path, "datum"), scope: "set", set_id: model["set_id"])
|
|
186
|
+
end
|
|
187
|
+
DatumAlternativePath.new(kind: "set", set_id: model["set_id"], chart_datum: datum && datum["chart_datum"],
|
|
188
|
+
datum: datum, qualifications: datum_qualifications(release, model, path, owner))
|
|
189
|
+
end
|
|
190
|
+
offsets = station.raw["subordinate_offsets"]
|
|
191
|
+
primary_id = offsets && (offsets["offset_id"] || (offsets["reference_station_id"] && station.subordinate_offsets.offset_id))
|
|
192
|
+
offset_routes = offsets ? [[offsets, primary_id, "$[\"subordinate_offsets\"]"]] : []
|
|
193
|
+
Array(station.raw["subordinate_offset_alternatives"]).each_with_index do |wrapper, index|
|
|
194
|
+
offset_routes << [wrapper["offsets"], wrapper["offset_id"], "$[\"subordinate_offset_alternatives\"][#{index}][\"offsets\"]"]
|
|
195
|
+
end
|
|
196
|
+
offset_routes.each do |route, identity, path|
|
|
197
|
+
datum = route["datum"]
|
|
198
|
+
declarations << datum_declaration(route, datum, datum_path(path, "datum"), scope: "offset") if datum && requested_set_id.nil?
|
|
199
|
+
alternatives << DatumAlternativePath.new(kind: "offset", offset_id: identity,
|
|
200
|
+
reference_station_id: route["reference_station_id"], chart_datum: datum && datum["chart_datum"], datum: datum,
|
|
201
|
+
qualifications: datum_qualifications(release, route, path))
|
|
202
|
+
end
|
|
203
|
+
DatumSources.new(station_id: station.station_id, selected_set_id: constants&.set_id, prediction_binding: datum_prediction_binding(constants, offsets),
|
|
204
|
+
declarations: declarations, alternative_paths: alternatives)
|
|
205
|
+
end
|
|
206
|
+
def validate_astronomy_correction(constants, quantity)
|
|
207
|
+
correction = constants.raw["astronomy_correction"]
|
|
208
|
+
if correction && (correction != "source_daily_utc_noon" || quantity != "water_level")
|
|
209
|
+
raise UnsupportedError, "unsupported astronomy correction #{correction}"
|
|
210
|
+
end
|
|
211
|
+
end
|
|
212
|
+
def table_for(release, constants)
|
|
213
|
+
convention = constants.convention
|
|
214
|
+
unless convention.v0_model == "schureman_tcd" && convention.nodal_handling == :f_u_at_prediction
|
|
215
|
+
raise UnsupportedConventionError, "unsupported convention #{convention.convention_id}"
|
|
216
|
+
end
|
|
217
|
+
ident = convention.raw["astro_table_id"] || ""
|
|
218
|
+
table = astro_table(release, ident) || (raise NoAstroTableError, "release #{release.datestamp} has no astro table \"#{ident}\" for convention \"#{convention.convention_id}\". Format 1.0 requires astro_tables when a convention uses f_u_at_prediction; this file was written before that revision or is invalid.")
|
|
219
|
+
raw = table.instance_variable_get(:@raw)
|
|
220
|
+
unless raw["v0_model"] == convention.v0_model && (convention.tables_sha256.nil? || raw["tables_sha256"] == convention.tables_sha256)
|
|
221
|
+
raise UnsupportedConventionError, "astro table #{ident} is incompatible with convention #{convention.convention_id}"
|
|
222
|
+
end
|
|
223
|
+
table
|
|
224
|
+
end
|
|
225
|
+
def unavailable(missing)
|
|
226
|
+
raise DatumUnavailableError.new("datum is missing #{missing}", missing: missing)
|
|
227
|
+
end
|
|
228
|
+
def datum_term(raw, datum, context, published: false)
|
|
229
|
+
datum ||= "mean_level"
|
|
230
|
+
if datum == "mean_level" && !published
|
|
231
|
+
context.datum_name = datum
|
|
232
|
+
return 0.0
|
|
233
|
+
end
|
|
234
|
+
d = raw || {}
|
|
235
|
+
named, basis = d["named"] || {}, d["basis"] || {}
|
|
236
|
+
if !published && named.key?(datum) && (basis[datum] || {})["_retained_mean"]
|
|
237
|
+
datum_metadata(context, datum, basis[datum])
|
|
238
|
+
return -named[datum]
|
|
239
|
+
end
|
|
240
|
+
mean = d["zero"] == "harmonic_mean" && !published ? 0.0 : d["msl_offset_m"]
|
|
241
|
+
unavailable("msl_offset_m") if mean.nil?
|
|
242
|
+
if datum == "zero" && !published
|
|
243
|
+
context.datum_name = d["zero_name"] || d["zero"] || "unknown"
|
|
244
|
+
return mean
|
|
245
|
+
end
|
|
246
|
+
key = datum == "chart" ? d["chart_datum"] : datum
|
|
247
|
+
unavailable("chart_datum") if datum == "chart" && key.nil?
|
|
248
|
+
unavailable(key) unless named.key?(key)
|
|
249
|
+
b = basis[key] || {}
|
|
250
|
+
unavailable("published chart datum") if published && b["kind"] != "published"
|
|
251
|
+
datum_metadata(context, key, b)
|
|
252
|
+
mean - named[key]
|
|
253
|
+
end
|
|
254
|
+
def subordinate_datum(offsets, datum, context)
|
|
255
|
+
d = offsets["datum"] || {}
|
|
256
|
+
named, basis = d["named"] || {}, d["basis"] || {}
|
|
257
|
+
chart = d["chart_datum"]
|
|
258
|
+
key = datum.nil? || datum == "chart" ? chart : datum
|
|
259
|
+
term = if datum.nil? || datum == "chart" then 0.0 elsif named.key?(key) then named.fetch(chart, 0.0) - named[key] else unavailable(datum) end
|
|
260
|
+
b = basis[key] || {}
|
|
261
|
+
datum_metadata(context, key, b)
|
|
262
|
+
term
|
|
263
|
+
end
|
|
264
|
+
def reference(release, offsets, quantity, bin_number = nil)
|
|
265
|
+
ident = offsets["reference_station_id"]
|
|
266
|
+
station = release.station(ident)
|
|
267
|
+
first_candidate = nil
|
|
268
|
+
constants = station&.__send__(:prediction_constant_sets)&.find do |s|
|
|
269
|
+
next false unless s.quantity == quantity.to_sym && %i[ok flagged].include?(s.qc_status) && (quantity == "water_level" ? s.source == "noaa" : Array(s.raw["current_bins"]).any? { |b| b["bin"] == bin_number })
|
|
270
|
+
first_candidate ||= s
|
|
271
|
+
!release.instance_variable_get(:@commercial_only) || release.instance_variable_get(:@commercial_basis) != "strict" || release.send(:commercial_set?, s.raw)
|
|
272
|
+
end
|
|
273
|
+
if constants.nil? && release.instance_variable_get(:@commercial_only) && first_candidate && first_candidate.licence.commercial_use != true
|
|
274
|
+
raise ReferenceUnavailableError.new("commercial_only refuses reference licence #{first_candidate.licence.licence_id}", reference_station_id: ident)
|
|
275
|
+
end
|
|
276
|
+
raise ReferenceUnavailableError.new("reference #{ident} has no usable set", reference_station_id: ident) unless constants
|
|
277
|
+
if release.instance_variable_get(:@commercial_only)
|
|
278
|
+
unless release.send(:commercial_set?, constants.raw)
|
|
279
|
+
raise ReferenceUnavailableError.new("commercial_only refuses reference set", reference_station_id: ident)
|
|
280
|
+
end
|
|
281
|
+
[offsets["licence_id"], constants.licence.licence_id].compact.each do |id|
|
|
282
|
+
unless release.licence(id)&.commercial_use == true
|
|
283
|
+
raise ReferenceUnavailableError.new("commercial_only refuses reference licence #{id}", reference_station_id: ident)
|
|
284
|
+
end
|
|
285
|
+
end
|
|
286
|
+
end
|
|
287
|
+
[station, constants]
|
|
288
|
+
end
|
|
289
|
+
def current_bin(station, bins, requested)
|
|
290
|
+
selected = requested || station.raw["default_current_bin"] || bins.map { |b| b["bin"] }.min
|
|
291
|
+
bins.find { |b| b["bin"] == selected } || (raise BinNotFoundError, "bin_number #{selected} not available")
|
|
292
|
+
end
|
|
293
|
+
def current_context(context, row)
|
|
294
|
+
context.current_bin = row
|
|
295
|
+
azimuth, flood = row.fetch("azimuth_deg", 0.0), row["mean_flood_dir_deg"]
|
|
296
|
+
context.sigma = flood.nil? || Math.cos((azimuth - flood) * RAD) >= 0 ? 1.0 : -1.0
|
|
297
|
+
context.total = Sum.new(context.table, row["constituents"] || [], amplitude: "major_amplitude_ms", phase: "major_phase_deg", mean: row.fetch("mean_major_ms", 0.0))
|
|
298
|
+
context.minor = Sum.new(context.table, row["constituents"] || [], amplitude: "minor_amplitude_ms", phase: "minor_phase_deg", mean: row.fetch("mean_minor_ms", 0.0))
|
|
299
|
+
end
|
|
300
|
+
def context(release, station, quantity, set_id, datum = nil, bin_number = nil, series: false, offset_id: nil)
|
|
301
|
+
station = station_for(release, station)
|
|
302
|
+
options(set_id, datum, bin_number)
|
|
303
|
+
raise InvalidArgumentError, "offset_id must be a string" unless offset_id.nil? || offset_id.is_a?(String)
|
|
304
|
+
raise InvalidArgumentError, "set_id and offset_id are mutually exclusive" if offset_id && set_id
|
|
305
|
+
constants = chosen(release, station, set_id)
|
|
306
|
+
monthly = nil
|
|
307
|
+
if offset_id&.start_with?(station.station_id + "/observed-monthly/")
|
|
308
|
+
monthly = observed_monthly_profiles(station).find { |profile| profile["offset_id"] == offset_id }
|
|
309
|
+
raise InvalidArgumentError, "offset_id not an authenticated monthly profile of station" unless monthly
|
|
310
|
+
raise QuantityMismatchError, "monthly observed offsets need water_level" unless quantity == "water_level"
|
|
311
|
+
constants = chosen(release, station, monthly["model"].set_id)
|
|
312
|
+
licence = release.licence(monthly["source"]["licence_id"])
|
|
313
|
+
raise InvalidArgumentError, "commercial_only refuses offset_id" if release.instance_variable_get(:@commercial_only) && (!licence || licence.commercial_use != true)
|
|
314
|
+
end
|
|
315
|
+
usable = constants && %i[ok flagged].include?(constants.qc_status)
|
|
316
|
+
tide, currents = station.raw.values_at("subordinate_offsets", "current_offsets")
|
|
317
|
+
if offset_id && monthly.nil?
|
|
318
|
+
tide = Release.subordinate_offset_models(station.raw)[offset_id]
|
|
319
|
+
raise InvalidArgumentError, "offset_id not a profile of station" unless tide
|
|
320
|
+
usable = false
|
|
321
|
+
end
|
|
322
|
+
historical = tide && tide["offset_id"]
|
|
323
|
+
e = release.instance_variable_get(:@by_id)[station.station_id]
|
|
324
|
+
better = historical && offset_id.nil? && (e.sets.any? { |cs| cs["set_id"] == e.eff_id && %w[ok flagged].include?(cs["qc_status"]) } || !release.send(:eligible_paths, e, false, false, historical: false).empty?)
|
|
325
|
+
mixed_current = false
|
|
326
|
+
if quantity == "current" && set_id.nil? && currents && !currents.empty?
|
|
327
|
+
harmonic_bins = usable && constants.quantity == :current ? constants.raw["current_bins"] || [] : []
|
|
328
|
+
effective_bin = bin_number || station.raw["default_current_bin"] || (harmonic_bins.empty? ? currents : harmonic_bins).map { |row| row["bin"] }.min
|
|
329
|
+
mixed_current = !harmonic_bins.any? { |row| row["bin"] == effective_bin } && currents.any? { |row| row["bin"] == effective_bin }
|
|
330
|
+
end
|
|
331
|
+
if quantity == "current" && set_id.nil? && offset_id.nil? && !(usable && constants.quantity == :current) && (currents.nil? || currents.empty?)
|
|
332
|
+
source = station.source_records.find do |record|
|
|
333
|
+
metadata = record.original_metadata
|
|
334
|
+
%w[chs-current-metadata chs-tide-current-tables].include?(record.source) && metadata["quantity"] == "current" &&
|
|
335
|
+
metadata["published_harmonics"] == false && metadata["runtime_provider"] == "CHS IWLS" &&
|
|
336
|
+
%w[available identity_unresolved].include?(metadata["runtime_status"])
|
|
337
|
+
end
|
|
338
|
+
if source
|
|
339
|
+
metadata = source.original_metadata
|
|
340
|
+
fields = %w[runtime_provider runtime_station_id runtime_provider_station_id historical_current_station_id runtime_status]
|
|
341
|
+
detail = fields.filter_map { |key| "#{key}=#{metadata[key]}" unless metadata[key].nil? }.join("; ")
|
|
342
|
+
raise NoConstantsError, "No bundled current constants; #{detail}. #{metadata['runtime_licence_note']}"
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
if mixed_current || set_id.nil? && !usable && (station.type == :subordinate || offset_id && monthly.nil?) && (tide && !better || currents && !currents.empty?)
|
|
346
|
+
if tide
|
|
347
|
+
raise QuantityMismatchError, "tide offsets need water_level" unless quantity == "water_level"
|
|
348
|
+
kind = tide["height_adjusted_type"]
|
|
349
|
+
raise InvalidArgumentError, "height_adjusted_type #{kind.inspect} must be R or A" unless %w[R A].include?(kind)
|
|
350
|
+
raise HistoricalOffsetsExcludedError, "historical_offsets_policy=exclude refuses historical prediction" if historical && release.historical_offsets_policy == :exclude
|
|
351
|
+
ref, constants = reference(release, tide, quantity)
|
|
352
|
+
require_historical(release, tide, constants) if historical
|
|
353
|
+
validate_astronomy_correction(constants, quantity)
|
|
354
|
+
table = table_for(release, constants)
|
|
355
|
+
c = Context.new(station: station, constants: constants, table: table, method: "harmonic", reference: ref, offsets: tide, selected_offset_id: offset_id)
|
|
356
|
+
daily = constants.raw["astronomy_correction"] == "source_daily_utc_noon"
|
|
357
|
+
Sum.new(table, constants.raw["constituents"] || [], daily: daily)
|
|
358
|
+
ref_term = datum_term(constants.raw["datum"], "chart", Context.new, published: true)
|
|
359
|
+
sub_term = subordinate_datum(tide.merge("datum" => retained_datum(release, station, offsets: tide)), datum, c)
|
|
360
|
+
if offset_id && !historical
|
|
361
|
+
basis = (((tide["datum"] || {})["basis"] || {})[c.datum_name] || {})
|
|
362
|
+
finding = (basis["fallback"] || {})["otc_finding"]
|
|
363
|
+
if finding
|
|
364
|
+
c.datum_method = basis["method"]
|
|
365
|
+
c.datum_flags = Array(c.datum_flags) + [finding]
|
|
366
|
+
end
|
|
367
|
+
end
|
|
368
|
+
high_t, low_t = %w[high low].map { |k| tide["time_offset_#{k}_min"] || 0.0 }
|
|
369
|
+
identity = kind == "R" ? 1.0 : 0.0
|
|
370
|
+
high_h, low_h = %w[high low].map { |k| tide["height_offset_#{k}"].nil? ? identity : tide["height_offset_#{k}"] }
|
|
371
|
+
raise InvalidArgumentError, "height_offset ratio must be positive" if kind == "R" && (high_h <= 0 || low_h <= 0)
|
|
372
|
+
if high_t == low_t && high_h == low_h
|
|
373
|
+
c.method = "folded_offsets"
|
|
374
|
+
multiplier, add = kind == "R" ? [high_h, 0.0] : [1.0, high_h]
|
|
375
|
+
c.total = Sum.new(table, constants.raw["constituents"] || [], mean: multiplier * ref_term + add + sub_term, multiplier: multiplier, shift_hours: high_t / 60.0, daily: daily)
|
|
376
|
+
else
|
|
377
|
+
c.method = "offsets"
|
|
378
|
+
c.total = Sum.new(table, constants.raw["constituents"] || [], mean: ref_term, daily: daily)
|
|
379
|
+
c.offsets = tide.merge("_subterm" => sub_term)
|
|
380
|
+
raise ExtremesOnlyError, "high and low offsets differ; no exact curve" if series
|
|
381
|
+
end
|
|
382
|
+
return c
|
|
383
|
+
end
|
|
384
|
+
raise QuantityMismatchError, "current offsets need current" unless quantity == "current"
|
|
385
|
+
entry = current_bin(station, currents, bin_number)
|
|
386
|
+
ref, constants = reference(release, entry, quantity, entry["reference_bin"])
|
|
387
|
+
validate_astronomy_correction(constants, quantity)
|
|
388
|
+
c = Context.new(station: station, constants: constants, table: table_for(release, constants), method: "offsets", reference: ref, reference_bin: entry["reference_bin"], bin_number: entry["bin"], offsets: entry)
|
|
389
|
+
current_context(c, current_bin(ref, constants.raw["current_bins"] || [], c.reference_bin))
|
|
390
|
+
raise ExtremesOnlyError, "subordinate currents provide events only" if series
|
|
391
|
+
return c
|
|
392
|
+
end
|
|
393
|
+
raise NoConstantsError, "no usable constants#{release.instance_variable_get(:@commercial_only) ? ' (commercial_only)' : ''}" unless usable
|
|
394
|
+
raise QuantityMismatchError, "#{quantity} requires that quantity" unless constants.quantity == quantity.to_sym
|
|
395
|
+
validate_astronomy_correction(constants, quantity)
|
|
396
|
+
c = Context.new(station: station, constants: constants, table: table_for(release, constants), method: "harmonic")
|
|
397
|
+
if quantity == "water_level"
|
|
398
|
+
c.total = Sum.new(c.table, constants.raw["constituents"] || [], daily: constants.raw["astronomy_correction"] == "source_daily_utc_noon")
|
|
399
|
+
if monthly.nil?
|
|
400
|
+
c.total.mean = datum_term(retained_datum(release, station, constants), datum, c)
|
|
401
|
+
else
|
|
402
|
+
candidate = monthly["candidate"]
|
|
403
|
+
window = candidate["window"]
|
|
404
|
+
flags = ["low", "model mean = this window’s MSL; window #{window['start']} to #{window['end']} disclosed; not a tidal-epoch datum",
|
|
405
|
+
"never default; explicit offset_id only", "offset_id " + monthly["offset_id"],
|
|
406
|
+
"source member SHA256 " + candidate["input_binding"]["member_sha256"],
|
|
407
|
+
"source fit SHA256 " + candidate["input_binding"]["fit_sha256"]] + Array((candidate["reliability"] || {})["limitations"])
|
|
408
|
+
provenance = {"kind" => "observed", "method" => "monthly_observed_msl_binding", "uncertainty_m" => nil,
|
|
409
|
+
"flags" => flags, "_retained" => true, "_retained_mean" => true}
|
|
410
|
+
named = (candidate["values"] || {}).filter_map { |key, value| [key, value - monthly["msl"]] if !%w[mn gt dhq dlq hwi lwi].include?(key) && finite_height?(value) }.to_h
|
|
411
|
+
c.selected_offset_id = monthly["offset_id"]
|
|
412
|
+
c.datum_method, c.datum_flags = provenance["method"], flags
|
|
413
|
+
c.total.mean = datum_term({"zero" => "harmonic_mean", "named" => named, "basis" => named.to_h { |key, _| [key, provenance] }}, datum, c)
|
|
414
|
+
end
|
|
415
|
+
else
|
|
416
|
+
row = current_bin(station, constants.raw["current_bins"] || [], bin_number)
|
|
417
|
+
c.bin_number = row["bin"]
|
|
418
|
+
current_context(c, row)
|
|
419
|
+
end
|
|
420
|
+
c
|
|
421
|
+
end
|
|
422
|
+
def require_historical(release, offsets, constants)
|
|
423
|
+
Release.check_historical_offsets!(offsets, "prediction")
|
|
424
|
+
binding = offsets.dig("provenance", "reference_binding")
|
|
425
|
+
eligible = constants.set_id.start_with?(offsets["reference_station_id"] + "/") && constants.source == "noaa" && constants.source_record_id == binding["noaa_id"] && constants.quantity == :water_level && constants.qc_status == :ok && constants.fallback.nil?
|
|
426
|
+
d = constants.raw["datum"] || {}
|
|
427
|
+
eligible &&= constants.convention.v0_model == "schureman_tcd" && constants.convention.nodal_handling == :f_u_at_prediction && d["chart_datum"] == "mllw" && !d["msl_offset_m"].nil? && d.dig("named", "mllw") == 0.0 && d.dig("basis", "mllw", "kind") == "published"
|
|
428
|
+
raise NoConstantsError, "historical offsets ineligible" unless eligible
|
|
429
|
+
end
|
|
430
|
+
def validate_units(units, default)
|
|
431
|
+
allowed = default == "meters" ? %w[meters feet] : ["m/s", "knots"]
|
|
432
|
+
raise InvalidArgumentError, "units must be #{allowed.join(' or ')}" unless allowed.include?(units)
|
|
433
|
+
end
|
|
434
|
+
def present_units(item, units)
|
|
435
|
+
fields = item.instance_variables.to_h { |field| [field.to_s.delete_prefix("@").to_sym, item.instance_variable_get(field)] }
|
|
436
|
+
item.class.new(**fields.merge(units: units))
|
|
437
|
+
end
|
|
438
|
+
def result(release, c, klass, items, datum = nil, units: nil)
|
|
439
|
+
units ||= [HeightSeries, ExtremeList].include?(klass) ? "meters" : "m/s"
|
|
440
|
+
items = items.map { |item| present_units(item, units) }
|
|
441
|
+
fields = {items: items, units: units, station_id: c.station.station_id, timezone: c.station.timezone, method: c.method.to_sym, set_id: c.constants.set_id, convention_id: c.constants.convention.convention_id, astro_table_id: c.table.instance_variable_get(:@raw)["astro_table_id"], reference_station_id: c.reference&.station_id, reference_bin: c.reference_bin, datum: datum, datum_name: c.datum_name, datum_kind: c.datum_kind, datum_uncertainty_m: c.datum_uncertainty, release: release.datestamp, algorithm: "otc-predict-1"}
|
|
442
|
+
model = c.station.constant_set(c.constants.set_id)
|
|
443
|
+
retained_id = c.selected_offset_id || (c.offsets && c.offsets["offset_id"])
|
|
444
|
+
retained = Release.subordinate_offset_models(c.station.raw)[retained_id]
|
|
445
|
+
if c.profile_info && (model || retained)
|
|
446
|
+
fields.merge!(c.profile_info)
|
|
447
|
+
end
|
|
448
|
+
fields[:source] = c.constants.source if c.constants
|
|
449
|
+
fields[:source] = retained["source"] || fields[:source] if retained
|
|
450
|
+
fields[:bin_number] = c.bin_number if [CurrentSeries, CurrentEventList].include?(klass)
|
|
451
|
+
fields[:omitted_event_types] = c.omitted if klass == CurrentEventList
|
|
452
|
+
if [HeightSeries, ExtremeList].include?(klass)
|
|
453
|
+
fields[:source_note] = (["Retained datum method: #{c.datum_method}"] + Array(c.datum_flags)).join("; ") if c.datum_method
|
|
454
|
+
fields[:offset_id] = c.selected_offset_id if c.selected_offset_id && c.offsets.nil?
|
|
455
|
+
if c.selected_offset_id && c.offsets && c.offsets["offset_id"].nil?
|
|
456
|
+
fields.merge!(set_id: nil, source: c.offsets["source"] || c.constants.source, offset_id: c.selected_offset_id,
|
|
457
|
+
reference_set_id: c.constants.set_id, reference_source_version: c.constants.source_version)
|
|
458
|
+
selection_note = c.event_default ? "automatically selected current NOAA offsets" : "explicitly selected preserved profile"
|
|
459
|
+
fields[:source_note] = [fields[:source_note], "OTC subordinate-offset calculation; #{selection_note}; no transfer to own harmonic model."].compact.reject(&:empty?).join("; ")
|
|
460
|
+
end
|
|
461
|
+
end
|
|
462
|
+
if [HeightSeries, ExtremeList].include?(klass) && c.offsets && c.offsets["offset_id"]
|
|
463
|
+
o, v = c.offsets, c.offsets["vintage"]
|
|
464
|
+
fields.merge!(set_id: nil, offset_id: o["offset_id"], offset_source: o["source"], offset_source_version: o["source_version"], historical_offsets: true, current_validity: v["current_validity"], current_accuracy: v["current_accuracy"], reference_set_id: c.constants.set_id, reference_source_version: c.constants.source_version, reference_2020_equivalence: v["reference_2020_equivalence"], source_note: "OTC historical-offset calculation using NOAA2020 parameters; retired NOAA profile; current validity unestablished; current accuracy unverified.")
|
|
465
|
+
end
|
|
466
|
+
klass.new(**fields)
|
|
467
|
+
end
|
|
468
|
+
end
|
|
469
|
+
end
|
|
470
|
+
class OpenTideConstants
|
|
471
|
+
module Predict
|
|
472
|
+
module_function
|
|
473
|
+
def current_events(c, start, stop)
|
|
474
|
+
current_event_candidates(c, start, stop, :events)
|
|
475
|
+
end
|
|
476
|
+
def unrounded_current_events(c, start, stop)
|
|
477
|
+
current_event_candidates(c, start, stop, :unrounded_events)
|
|
478
|
+
end
|
|
479
|
+
def current_event_candidates(c, start, stop, event_source)
|
|
480
|
+
total = Sum.new(c.table, c.current_bin["constituents"] || [], amplitude: "major_amplitude_ms", phase: "major_phase_deg", multiplier: c.sigma, mean: c.sigma * c.current_bin.fetch("mean_major_ms", 0.0))
|
|
481
|
+
candidates = __send__(event_source, total, start, stop).filter_map do |t, kind, value|
|
|
482
|
+
if kind == "high" && value > 0
|
|
483
|
+
[t, "max_flood", value, c.current_bin["mean_flood_dir_deg"]]
|
|
484
|
+
elsif kind == "low" && value < 0
|
|
485
|
+
[t, "max_ebb", value, c.current_bin["mean_ebb_dir_deg"]]
|
|
486
|
+
end
|
|
487
|
+
end
|
|
488
|
+
candidates.concat(__send__(event_source, total, start, stop, slack: true).map { |t, kind, _| [t, kind, 0.0, nil] })
|
|
489
|
+
candidates.sort_by(&:first)
|
|
490
|
+
end
|
|
491
|
+
private_class_method :unrounded_current_events, :current_event_candidates
|
|
492
|
+
def datum_info(set_id, raw)
|
|
493
|
+
d = raw || {}
|
|
494
|
+
named, basis = d["named"] || {}, d["basis"] || {}
|
|
495
|
+
chart = named[d["chart_datum"]]
|
|
496
|
+
levels = named.keys.sort.map do |key|
|
|
497
|
+
b = basis[key] || {}
|
|
498
|
+
control = b["control"] || {}
|
|
499
|
+
epoch = b["epoch"]
|
|
500
|
+
epoch = {"name" => epoch} if epoch.is_a?(String) && !epoch.empty?
|
|
501
|
+
DatumLevel.new(key: key, value_m: named[key], above_chart_m: chart.nil? ? nil : named[key] - chart, kind: b["kind"], method: b["method"], source_name: b["source_name"], epoch: epoch, data_span: b["data_span"], control_station_id: control["station_id"], control_set_id: control["set_id"], control_source_id: control["source_id"], uncertainty_m: b["uncertainty_m"], uncertainty_basis: b["uncertainty_basis"], flags: b["flags"] || [], fallback: b["fallback"])
|
|
502
|
+
end
|
|
503
|
+
DatumInfo.new(set_id: set_id, zero: d["zero"], zero_name: d["zero_name"], chart_datum: d["chart_datum"], msl_offset_m: d["msl_offset_m"], levels: levels)
|
|
504
|
+
end
|
|
505
|
+
end
|
|
506
|
+
end
|