Class: TCD::Writer
- Inherits:
-
Object
- Object
- TCD::Writer
- Defined in:
- lib/tcd/writer.rb
Overview
Writes a TCD (Tidal Constituent Database) file in the layout libtcd 2.2.7 writes and reads (tide_db.c write_tide_db_header and pack_tide_record):
1. ASCII header ([KEY] = VALUE lines), padded with NULs to [HEADER SIZE]
2. CRC-32 of the padded header, 4 bytes big-endian
3. String tables: level units, direction units, restrictions, time zones,
countries, datums, legalese (the last five padded to 2^bits entries and
ended by "__END__"), constituent names
4. Speeds, equilibrium arguments, node factors (bit-packed, each table
starting on a byte boundary)
5. Station records (bit-packed, each a whole number of bytes)
Values use the same units as the reader: degrees, degrees per hour, time offsets in minutes, nil for "no direction" and "no slack time", station time zones with or without the leading ':' (a new table entry always gets it). Strings are stored as ISO-8859-1. A value that does not fit its field raises ArgumentError; nothing is truncated.
Checks follow libtcd's check_tide_record, so libtcd and XTide read the file as written:
-
zone_offset is a signed HHMM integer (-500 is UTC-5, 530 is UTC+5:30), not minutes; its minutes part must be under 60.
-
Epochs must be 0..360 degrees; dates must be 0 or YYYYMMDD.
-
Integer fields take an Integer or a whole Float (10.0), never a fraction.
-
Strings may not contain NUL; table entries may not be "END"; header text (version, last_modified) may not hold control characters or brackets.
-
Level units, direction units, restrictions and legalese hold at most 256 entries; time zones, countries and datums at most 32,768. The direction units table must hold "degrees true" after its first entry.
-
Every bit width is at most 31. When the speeds span too much for libtcd's speed scale of 10^7, the writer uses the largest power of ten that fits.
-
A subordinate's reference_station must index a reference record.
writer = TCD::Writer.new(constituents: [...], start_year: 2020, number_of_years: 3) writer.add_station(station) # a TCD::Station or a Hash with the same keys writer.write("out.tcd")
TCD::Writer.from_reader(reader).write("copy.tcd")
Defined Under Namespace
Classes: BitPacker
Constant Summary collapse
- LIBTCD_VERSION =
"PFM Software - libtcd v2.2.7 - 2015-08-09"- MAJOR_REV =
2- MINOR_REV =
2- ONELINER_LENGTH =
bytes, including the NUL
90- MONOLOGUE_LENGTH =
bytes, including the NUL
10_000- MAX_CONSTITUENTS =
255- AMPLITUDE_EPSILON =
0.00005- NULL_SLACK_OFFSET =
0xA00- NULL_DIRECTION =
361- END_MARKER =
"__END__"- INT32_MIN =
-(2**31)
- INT32_MAX =
2**31 - 1
- MAX_BITS =
libtcd packs every field from a signed 32-bit int
31- TABLE_LIMITS =
Most table entries libtcd can index (tcd.h TIDE_RECORD): level units, direction units, restrictions and legalese are NV_U_BYTE; time zones, countries and datums are NV_INT16, and libtcd asserts tzfile >= 0.
{ level_unit: 256, direction_unit: 256, restriction: 256, legalese: 256, tzfile: 32_768, country: 32_768, datum: 32_768 }.freeze
- DEFAULTS =
libtcd tide_db_default.h
{ header_size: 4096, speed_scale: 10_000_000, equilibrium_scale: 100, node_scale: 10_000, amplitude_bits: 19, amplitude_scale: 10_000, epoch_bits: 16, epoch_scale: 100, record_type_bits: 4, latitude_bits: 25, latitude_scale: 100_000, longitude_bits: 26, longitude_scale: 100_000, record_size_bits: 16, station_bits: 18, datum_offset_bits: 28, datum_offset_scale: 10_000, date_bits: 27, months_on_station_bits: 10, confidence_value_bits: 4, time_bits: 13, level_add_bits: 17, level_add_scale: 1000, level_multiply_bits: 16, level_multiply_scale: 1000, direction_bits: 9, constituent_size: 10, level_unit_size: 15, direction_unit_size: 15, restriction_bits: 4, restriction_size: 30, tzfile_bits: 10, tzfile_size: 30, country_bits: 9, country_size: 50, datum_bits: 7, datum_size: 70, legalese_bits: 4, legalese_size: 70 }.freeze
- PARAMETER_KEYS =
Header parameters a caller (or from_reader) may set. Counts and the bit widths that follow from counts are always derived from the data.
(DEFAULTS.keys + %i[ speed_bits speed_offset equilibrium_bits equilibrium_offset node_bits node_offset constituent_bits level_unit_bits direction_unit_bits ]).freeze
- DEFAULT_LEVEL_UNITS =
["Unknown", "feet", "meters", "knots", "knots^2"].freeze
- DEFAULT_DIRECTION_UNITS =
["Unknown", "degrees true", "degrees"].freeze
- DEFAULT_RESTRICTIONS =
["Public Domain", "DoD/DoD Contractors Only"].freeze
- DEFAULT_LEGALESES =
["NULL"].freeze
Instance Attribute Summary collapse
-
#constituents ⇒ Object
readonly
Returns the value of attribute constituents.
-
#params ⇒ Object
readonly
Returns the value of attribute params.
-
#stations ⇒ Object
readonly
Returns the value of attribute stations.
Class Method Summary collapse
-
.from_reader(reader) ⇒ Object
Builds a writer holding everything a Reader read: header parameters, tables, constituents and stations, in the same order.
Instance Method Summary collapse
-
#add_station(station) ⇒ Object
Adds a station record (TCD::Station or a Hash with the Station keys).
-
#initialize(constituents:, start_year:, number_of_years: nil, version: nil, last_modified: nil, params: {}, level_units: DEFAULT_LEVEL_UNITS, direction_units: DEFAULT_DIRECTION_UNITS, restrictions: DEFAULT_RESTRICTIONS, timezones: [], countries: ["Unknown"], datums: ["Unknown"], legaleses: DEFAULT_LEGALESES) ⇒ Writer
constructor
constituents: objects or Hashes with name, speed, equilibrium (one per year) and node_factors (one per year), e.g.
-
#to_bytes ⇒ Object
The whole file as a binary String.
-
#write(path) ⇒ Object
Writes the file and returns its size in bytes.
Constructor Details
#initialize(constituents:, start_year:, number_of_years: nil, version: nil, last_modified: nil, params: {}, level_units: DEFAULT_LEVEL_UNITS, direction_units: DEFAULT_DIRECTION_UNITS, restrictions: DEFAULT_RESTRICTIONS, timezones: [], countries: ["Unknown"], datums: ["Unknown"], legaleses: DEFAULT_LEGALESES) ⇒ Writer
constituents: objects or Hashes with name, speed, equilibrium (one per year) and node_factors (one per year), e.g. TCD::Constituent. params: header parameters (bit widths, scales, offsets, sizes); missing ones come from the libtcd defaults or, for speeds, equilibrium arguments and node factors, from the data range as libtcd computes them. level_units ... legaleses: the string tables. Stations may also name strings that are not in them; those are appended.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/tcd/writer.rb', line 147 def initialize(constituents:, start_year:, number_of_years: nil, version: nil, last_modified: nil, params: {}, level_units: DEFAULT_LEVEL_UNITS, direction_units: DEFAULT_DIRECTION_UNITS, restrictions: DEFAULT_RESTRICTIONS, timezones: [], countries: ["Unknown"], datums: ["Unknown"], legaleses: DEFAULT_LEGALESES) @constituents = constituents.map { |c| normalize_constituent(c) } raise ArgumentError, "at least one constituent is required" if @constituents.empty? if @constituents.size > MAX_CONSTITUENTS raise ArgumentError, "#{@constituents.size} constituents; libtcd allows at most #{MAX_CONSTITUENTS}" end @start_year = int_value(start_year, "start_year") unless @start_year.between?(INT32_MIN, INT32_MAX) raise ArgumentError, "start_year #{@start_year} is outside libtcd's 32-bit range" end @number_of_years = int_value(number_of_years || @constituents.first[:equilibrium].size, "number_of_years") unless @number_of_years.between?(1, INT32_MAX) raise ArgumentError, "number_of_years must be at least 1, got #{@number_of_years}" end @constituents.each do |c| [:equilibrium, :node_factors].each do |key| next if c[key].size == @number_of_years raise ArgumentError, "constituent #{c[:name]}: #{c[key].size} #{key} values for #{@number_of_years} years" end end @version = header_text(version || LIBTCD_VERSION, "version") @last_modified = last_modified && header_text(last_modified, "last_modified") @given_params = params.transform_keys(&:to_sym) unknown = @given_params.keys - PARAMETER_KEYS raise ArgumentError, "unknown header parameters: #{unknown.join(', ')}" unless unknown.empty? @multiply_scale = int_value(@given_params.fetch(:level_multiply_scale, DEFAULTS[:level_multiply_scale]), "header parameter level_multiply_scale") @tables = { level_unit: level_units.dup, direction_unit: direction_units.dup, restriction: restrictions.dup, tzfile: timezones.dup, country: countries.dup, datum: datums.dup, legalese: legaleses.dup } @stations = [] end |
Instance Attribute Details
#constituents ⇒ Object (readonly)
Returns the value of attribute constituents.
108 109 110 |
# File 'lib/tcd/writer.rb', line 108 def constituents @constituents end |
#params ⇒ Object (readonly)
Returns the value of attribute params.
108 109 110 |
# File 'lib/tcd/writer.rb', line 108 def params @params end |
#stations ⇒ Object (readonly)
Returns the value of attribute stations.
108 109 110 |
# File 'lib/tcd/writer.rb', line 108 def stations @stations end |
Class Method Details
.from_reader(reader) ⇒ Object
Builds a writer holding everything a Reader read: header parameters, tables, constituents and stations, in the same order.
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
# File 'lib/tcd/writer.rb', line 112 def self.from_reader(reader) lt = reader.lookup_tables h = reader.header writer = new( constituents: reader.constituents.to_a, start_year: h.start_year, number_of_years: h.number_of_years, version: h.version, last_modified: h.last_modified, params: h.params.select { |k, _| PARAMETER_KEYS.include?(k) }, level_units: lt.level_units, direction_units: lt.direction_units, restrictions: lt.restrictions, timezones: lt.timezones, countries: lt.countries, datums: lt.datums, legaleses: lt.legalese ) offset = lt.station_records_offset File.open(reader.path, "rb") do |io| reader.stations.each do |station| writer.add_station(writer.send(:restore_null_multipliers, station, io, offset)) offset += station.record_size end end writer end |
Instance Method Details
#add_station(station) ⇒ Object
Adds a station record (TCD::Station or a Hash with the Station keys). Subordinate stations name their reference by record index (reference_station), so add them in the order they will be numbered.
193 194 195 196 |
# File 'lib/tcd/writer.rb', line 193 def add_station(station) @stations << station self end |
#to_bytes ⇒ Object
The whole file as a binary String.
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/tcd/writer.rb', line 206 def to_bytes records = @stations.map { |s| index_strings(s) } @params = compute_params body = String.new(encoding: Encoding::BINARY) body << tables_bytes body << constituent_bytes records.each_with_index do |r, i| if r[:record_type] == 2 ref = r[:reference_station] unless ref.between?(0, records.size - 1) raise ArgumentError, "#{r[:name]}: reference_station #{ref} is not a record index (0..#{records.size - 1})" end # XTide asserts when a subordinate's reference is not a reference record unless records[ref][:record_type] == 1 raise ArgumentError, "#{r[:name]}: reference_station #{ref} is not a reference (type 1) record" end end body << pack_station(r, i).first end end_of_file = @params[:header_size] + 4 + body.bytesize raise ArgumentError, "file would be #{end_of_file} bytes, over libtcd's 32-bit limit" if end_of_file > INT32_MAX header = header_bytes(end_of_file) header + [Zlib.crc32(header)].pack("N") + body end |
#write(path) ⇒ Object
Writes the file and returns its size in bytes.
199 200 201 202 203 |
# File 'lib/tcd/writer.rb', line 199 def write(path) bytes = to_bytes File.binwrite(path, bytes) bytes.bytesize end |