gnsswire-tro 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,44 @@
1
+ """SINEX_TRO troposphere files, versions 0.01 and 2.00: text to lines and fields, and back.
2
+
3
+ A SINEX_TRO file holds, per site and epoch, tropospheric parameters such as
4
+ the zenith total delay and its horizontal gradients (the troposphere
5
+ products of the IGS: one file per site and day, at 5-minute steps), with
6
+ the description of the solution, the station metadata and, in version
7
+ 2.00, slant delays and meteorological parameters. It is read whole with
8
+ :func:`read` and written with :func:`write`, and ``write(read(text)) ==
9
+ text`` for every file this module accepts. The file is its header and
10
+ footer lines and its blocks (:class:`Block`), each the text of its lines;
11
+ :class:`TroFile` reads the header line, TROP/DESCRIPTION, the solution
12
+ blocks (:class:`Row`) and the station coordinates (:class:`Coordinates`)
13
+ into fields, as text, and :func:`digits` gives a number as the integer of
14
+ its digits and its count of decimals. Nothing is scaled: values are in the
15
+ units the file gives (0.01: millimetres; 2.00: TROPO PARAMETER UNITS).
16
+
17
+ Sources: SINEX_TRO Version 2.00 (R. Pacione, J. Dousa, December 2020) and
18
+ Version 0.01 (G. Gendt, 1 March 1997); the readings taken are in ``_file``.
19
+
20
+ Errors: every exception this codec raises for a file it cannot read or
21
+ lines it cannot write is an :class:`Error` (a ``ValueError``):
22
+ :class:`Invalid`, :class:`Unsupported` (another format version), and the
23
+ error :func:`digits` raises for text that is not a number.
24
+ """
25
+
26
+ from ._file import (
27
+ VERSIONS,
28
+ Block,
29
+ Coordinates,
30
+ Epoch,
31
+ Error,
32
+ Header,
33
+ Invalid,
34
+ Row,
35
+ TroFile,
36
+ Unsupported,
37
+ digits,
38
+ epoch,
39
+ read,
40
+ write,
41
+ )
42
+
43
+ __all__ = ["VERSIONS", "Block", "Coordinates", "Epoch", "Error", "Header", "Invalid", "Row",
44
+ "TroFile", "Unsupported", "digits", "epoch", "read", "write"]
gnsswire/tro/_file.py ADDED
@@ -0,0 +1,531 @@
1
+ """SINEX_TRO files: :func:`read` and :func:`write`, and the blocks read into fields.
2
+
3
+ Sources: "SINEX_TRO - Solution (Software/Technique) INdependent EXchange
4
+ Format for TROpospheric and meteorological parameters, Version 2.00" (R.
5
+ Pacione, J. Dousa, December 2020), sections 3, 6 and 7 and Appendix I;
6
+ "SINEX_TRO - Solution (Software/technique) INdependent EXchange Format for
7
+ combination of TROpospheric estimates, Version 0.01" (G. Gendt, 1 March
8
+ 1997), Appendix I. The troposphere products of the IGS are written in
9
+ version 0.01; version 2.00 is "decoupled from the SINEX" and not compatible
10
+ with it ("it was decided to revise the format without keeping a full
11
+ compatibility with any previous SINEX_TRO unofficial version").
12
+
13
+ The structure both share (2.00 section 3; 0.01 by its examples): a header
14
+ line (``%=TRO``), then blocks, each from ``+TITLE`` to ``-TITLE``, and
15
+ comment lines (``*``), then the footer line (``%=ENDTRO``). Inside a block,
16
+ data lines start with a blank. "After a block has started (+) it must be
17
+ ended (-) before another block can begin." 2.00: "No other character is
18
+ allowed at the beginning of a line!"; "A SINEX_TRO file must start with a
19
+ header line and end with a footer line."
20
+
21
+ What is read into fields (everything else is kept as the text of its lines):
22
+
23
+ - the header line (:class:`Header`);
24
+ - TROP/DESCRIPTION, as keyword and value (``1X,A29`` then the value): the
25
+ names of the TROP/SOLUTION fields (0.01: SOLUTION_FIELDS_1,
26
+ SOLUTION_FIELDS_2, ...; 2.00: TROPO PARAMETER NAMES) and, in 2.00, their
27
+ units (TROPO PARAMETER UNITS), and those of SLANT/SOLUTION;
28
+ - TROP/SOLUTION and SLANT/SOLUTION, a :class:`Row` per data line: marker,
29
+ time tag (``YYYY:DDD:SSSSS``, 0.01 ``YY:DDD:SSSSS``) and the values, "Space
30
+ separated fields of variable length. Number and order of fields are given
31
+ in the block TROP/DESCRIPTION";
32
+ - the station coordinates, TROP/STA_COORDINATES (0.01) and SITE/COORDINATES
33
+ (2.00), a :class:`Coordinates` per data line.
34
+
35
+ What :func:`read` checks is the structure: the header line's ``%=TRO`` and
36
+ format version, the footer line, the first character of every line, blocks
37
+ begun and ended without nesting. The fields are checked when they are asked
38
+ for, each property raising :class:`Invalid` for lines it cannot read, so
39
+ that a file whose solution does not follow the document still reads, and
40
+ writes back, line for line.
41
+
42
+ Readings this codec makes where the documents leave room:
43
+
44
+ - Fields of a line are read as separated by blanks ("Elements within each
45
+ line are defined and separated by a blank character, at least", 2.00
46
+ section 3), not by the columns of the Fortran formats: the documents' own
47
+ examples do not keep those columns, and 2.00's header line adds up to
48
+ more than the 58 characters its table prints. The header line must have
49
+ nine fields.
50
+ - Values are kept as text; :func:`digits` gives a number's digits as an
51
+ integer and its power of ten. The missing value, "-999 (integer) or
52
+ -999.000 (float)", is kept like any other.
53
+ - The number of values of a TROP/SOLUTION (SLANT/SOLUTION) line must equal
54
+ the number of names; units, where given, must be as many as the names.
55
+ Each of the keywords that give names or units must come once, spelt as
56
+ the document spells it.
57
+ - 2.00 gives the slant names keyword as 'SLANT PARAMETERS ' in its table and
58
+ 'SLANT PARAMETER NAMES' in its example; both are read.
59
+ - Time tags: 0.01 writes the year in two digits (``I2.2``). 2.00 writes it
60
+ in four ("YYYY = 4- digit year", section 7) but prints the open time
61
+ ``00:000:00000`` in Appendix I, so a two-digit year is read too. The year
62
+ is kept as written: ``26`` is not turned into 2026. Time tags are read in
63
+ the header line and the solution blocks; the others are kept as text.
64
+ - Block titles are not limited to the documents' lists (2.00's examples
65
+ have FILE/COMMENT, 0.01 files of the IGS SITE/GPS_PHASE_CENTER); a title
66
+ must be capital letters, digits and ``/ _ -`` ("The block titles must be
67
+ in capital letters"). The line that ends a block is any ``-`` line, kept
68
+ as written: 2.00's example 3 ends ``+SITE//COORDINATES`` with
69
+ ``-SITE/COORDINATES``.
70
+ - Empty lines, which 0.01 files of the IGS have between blocks, are
71
+ accepted anywhere between the header and footer lines and kept; a line
72
+ of blanks only is read the same way. Any other line must start with one of
73
+ the five reserved characters.
74
+ - The footer line is ``%=ENDTRO`` (both tables and every example; 2.00's
75
+ structure diagram prints ``%ENDTRO``).
76
+ - Lines end in LF or CR LF, the same throughout a file; the file's line
77
+ ending and whether its last line has one are kept, so that ``write(read(
78
+ text)) == text``.
79
+ """
80
+
81
+ from __future__ import annotations
82
+
83
+ import re
84
+ from dataclasses import dataclass
85
+
86
+
87
+ class Error(ValueError):
88
+ """Base of every exception this codec raises for a file, a line or a field."""
89
+
90
+
91
+ class Invalid(Error):
92
+ """The text is not a SINEX_TRO file as its format documents describe it."""
93
+
94
+
95
+ class Unsupported(Error, LookupError):
96
+ """A SINEX_TRO file of a format version this codec has no rules for."""
97
+
98
+
99
+ # Format version: the digits a year of its time tags may have (0.01: I2.2; 2.00:
100
+ # section 7, and the 00:000:00000 of Appendix I).
101
+ VERSIONS = {"0.01": (2,), "2.00": (4, 2)}
102
+ HEADER = "%=TRO"
103
+ FOOTER = "%=ENDTRO"
104
+ DESCRIPTION = "TROP/DESCRIPTION"
105
+ SOLUTION = "TROP/SOLUTION"
106
+ SLANT = "SLANT/SOLUTION"
107
+ STA_COORDINATES = "TROP/STA_COORDINATES" # 0.01
108
+ SITE_COORDINATES = "SITE/COORDINATES" # 2.00
109
+ # TROP/DESCRIPTION keywords that give the fields of the solution blocks.
110
+ TROPO_NAMES = "TROPO PARAMETER NAMES"
111
+ TROPO_UNITS = "TROPO PARAMETER UNITS"
112
+ SLANT_NAMES = ("SLANT PARAMETER NAMES", "SLANT PARAMETERS")
113
+ SLANT_UNITS = "SLANT PARAMETER UNITS"
114
+ _FIELDS = re.compile(r"SOLUTION_FIELDS_(\d+)") # 0.01
115
+ _TITLE = re.compile(r"[A-Z0-9/_-]+")
116
+ _TIME = re.compile(r"(\d{2}|\d{4}):(\d{3}):(\d{5})")
117
+ _DIGITS = re.compile(r"([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?")
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class Epoch:
122
+ """A time tag, ``YYYY:DDD:SSSSS``: year, day of year and second of day, as written.
123
+
124
+ In version 0.01 the year has two digits and is kept so (``26``).
125
+ """
126
+
127
+ year: int
128
+ day: int
129
+ second: int
130
+
131
+
132
+ def epoch(text: str, year_digits: tuple[int, ...] = (4,)) -> Epoch:
133
+ """The time tag ``text``: ``epoch("2013:168:64500")``, ``epoch("97:033:18000", (2,))``.
134
+
135
+ ``year_digits`` are the lengths the year may have; ``VERSIONS`` gives
136
+ those of each format version.
137
+ """
138
+ m = _TIME.fullmatch(text)
139
+ if m is None or len(m[1]) not in year_digits:
140
+ raise Invalid(f"{text!r} is not a time tag YYYY:DDD:SSSSS with a year of "
141
+ f"{' or '.join(map(str, year_digits))} digits")
142
+ return Epoch(int(m[1]), int(m[2]), int(m[3]))
143
+
144
+
145
+ def digits(text: str) -> tuple[int, int]:
146
+ """A number as the integer of its digits and its count of decimals.
147
+
148
+ The value is ``integer * 10**-decimals``: ``digits("2192.4") == (21924,
149
+ 1)``, ``digits("-0.024") == (-24, 3)``, ``digits("-999") == (-999, 0)``,
150
+ and with an exponent, as units are written, ``digits("1e+03") == (1,
151
+ -3)``. No floating point is involved. Text that is not a number is
152
+ :class:`Error`.
153
+ """
154
+ m = _DIGITS.fullmatch(text.strip()) if isinstance(text, str) else None
155
+ if m is None or not (m[2] or m[3]):
156
+ raise Error(f"{text!r} is not a number")
157
+ sign, whole, frac, exp = m[1], m[2], m[3] or "", m[4]
158
+ value = int((whole or "0") + frac)
159
+ return (-value if sign == "-" else value), len(frac) - (int(exp) if exp else 0)
160
+
161
+
162
+ @dataclass(frozen=True, slots=True)
163
+ class Header:
164
+ """The fields of the header line, as written.
165
+
166
+ ``%=TRO 2.00 GOP 2017:157:61799 GOP 2013:168:64500 2013:168:86100 P MIX``:
167
+ format version, agency creating the file, creation time, agency
168
+ providing the data, start and end of the solution, observation code
169
+ (P for GNSS; C, D, R, W, S, F, N, M in 2.00) and solution contents (a
170
+ marker, or MIX for more than one site).
171
+ """
172
+
173
+ version: str
174
+ agency: str
175
+ created: str
176
+ data_agency: str
177
+ start: str
178
+ end: str
179
+ technique: str
180
+ contents: str
181
+
182
+
183
+ @dataclass(frozen=True, slots=True)
184
+ class Block:
185
+ """A block: its ``+TITLE`` line, the lines in it as written, its ``-TITLE`` line."""
186
+
187
+ start: str
188
+ lines: tuple[str, ...]
189
+ end: str
190
+
191
+ @property
192
+ def title(self) -> str:
193
+ """The block title, without the ``+`` and trailing blanks."""
194
+ return self.start[1:].rstrip()
195
+
196
+ @property
197
+ def data(self) -> tuple[str, ...]:
198
+ """The data lines: those that are not comments and not blank."""
199
+ return tuple(line for line in self.lines if line[:1] == " " and line.strip())
200
+
201
+
202
+ @dataclass(frozen=True, slots=True)
203
+ class Row:
204
+ """A data line of TROP/SOLUTION or SLANT/SOLUTION.
205
+
206
+ ``marker`` is the site, ``epoch`` the time tag ("Middle of data
207
+ Interval"), ``values`` the fields named by TROP/DESCRIPTION, in its
208
+ order, as written.
209
+ """
210
+
211
+ marker: str
212
+ epoch: Epoch
213
+ values: tuple[str, ...]
214
+
215
+
216
+ @dataclass(frozen=True, slots=True)
217
+ class Coordinates:
218
+ """A data line of TROP/STA_COORDINATES (0.01) or SITE/COORDINATES (2.00).
219
+
220
+ Site code, point code, solution number and observation code; ``start``
221
+ and ``end``, the time tags of the validity (2.00 only; ``None`` in
222
+ 0.01); ``x``, ``y``, ``z`` in metres; ``rest``: the fields after them,
223
+ as written (reference system, remark and, for a combined mean, the
224
+ standard deviations and the number of analysis centres).
225
+ """
226
+
227
+ site: str
228
+ point: str
229
+ solution: str
230
+ technique: str
231
+ start: str | None
232
+ end: str | None
233
+ x: str
234
+ y: str
235
+ z: str
236
+ rest: tuple[str, ...]
237
+
238
+
239
+ @dataclass(frozen=True, slots=True)
240
+ class TroFile:
241
+ """A whole SINEX_TRO file.
242
+
243
+ ``header`` and ``footer`` are the first and last lines; ``items`` the
244
+ lines between, as blocks (:class:`Block`) and the lines outside blocks
245
+ (comments and empty lines), in the file's order.
246
+ """
247
+
248
+ header: str
249
+ items: tuple[str | Block, ...]
250
+ footer: str = FOOTER
251
+ newline: str = "\n" # "\n" or "\r\n"
252
+ final_newline: bool = True # whether the footer ends with ``newline``
253
+
254
+ @property
255
+ def fields(self) -> Header:
256
+ """The fields of the header line."""
257
+ return _header(self.header)
258
+
259
+ @property
260
+ def version(self) -> str:
261
+ """The format version: ``0.01`` or ``2.00``."""
262
+ return _version(self.header)
263
+
264
+ @property
265
+ def blocks(self) -> tuple[Block, ...]:
266
+ """Every block, in the file's order."""
267
+ return tuple(b for b in self.items if isinstance(b, Block))
268
+
269
+ def block(self, title: str) -> Block | None:
270
+ """The first block of ``title`` (``"TROP/SOLUTION"``), or ``None``."""
271
+ for b in self.items:
272
+ if isinstance(b, Block) and b.title == title:
273
+ return b
274
+ return None
275
+
276
+ @property
277
+ def description(self) -> tuple[tuple[str, str], ...]:
278
+ """TROP/DESCRIPTION as (keyword, value) pairs, both stripped, in the file's order."""
279
+ b = self.block(DESCRIPTION)
280
+ return () if b is None else tuple((line[1:30].strip(), line[30:].strip())
281
+ for line in b.data)
282
+
283
+ @property
284
+ def parameters(self) -> tuple[str, ...]:
285
+ """The names of the TROP/SOLUTION values, in their order (``TROTOT``, ``STDDEV``, ...)."""
286
+ return _names(self)[0]
287
+
288
+ @property
289
+ def units(self) -> tuple[str, ...] | None:
290
+ """TROPO PARAMETER UNITS (2.00), one per parameter, as written; ``None`` without it.
291
+
292
+ "Values reported in TROP/SOLUTION Block should be divided by the
293
+ related TROPO UNITS to get the base units" (Tables 1 to 3).
294
+ """
295
+ return _names(self)[1]
296
+
297
+ @property
298
+ def slant_parameters(self) -> tuple[str, ...]:
299
+ """The names of the SLANT/SOLUTION values (2.00), in their order."""
300
+ return _names(self)[2]
301
+
302
+ @property
303
+ def slant_units(self) -> tuple[str, ...] | None:
304
+ """SLANT PARAMETER UNITS (2.00), as written; ``None`` without it."""
305
+ return _names(self)[3]
306
+
307
+ @property
308
+ def solution(self) -> tuple[Row, ...]:
309
+ """The lines of every TROP/SOLUTION block, in the file's order."""
310
+ return _rows(self, SOLUTION, self.parameters)
311
+
312
+ @property
313
+ def slant(self) -> tuple[Row, ...]:
314
+ """The lines of every SLANT/SOLUTION block, in the file's order."""
315
+ return _rows(self, SLANT, self.slant_parameters)
316
+
317
+ @property
318
+ def coordinates(self) -> tuple[Coordinates, ...]:
319
+ """The lines of TROP/STA_COORDINATES and SITE/COORDINATES, in the file's order."""
320
+ out = []
321
+ for b in self.blocks:
322
+ if b.title not in (STA_COORDINATES, SITE_COORDINATES):
323
+ continue
324
+ dated = b.title == SITE_COORDINATES
325
+ least = 9 if dated else 7
326
+ for line in b.data:
327
+ f = line.split()
328
+ if len(f) < least:
329
+ raise Invalid(f"{b.title}: {line!r} has {len(f)} fields, needs at least "
330
+ f"{least}")
331
+ if dated:
332
+ out.append(Coordinates(*f[:4], f[4], f[5], *f[6:9], tuple(f[9:])))
333
+ else:
334
+ out.append(Coordinates(*f[:4], None, None, *f[4:7], tuple(f[7:])))
335
+ return tuple(out)
336
+
337
+
338
+ def _version(line: str) -> str:
339
+ """The format version of the header line; what read checks of it."""
340
+ f = line.split()
341
+ if not f or f[0] != HEADER:
342
+ raise Invalid(f"line 1: a SINEX_TRO file starts with {HEADER}, found {line[:20]!r}")
343
+ if len(f) < 2 or f[1] not in VERSIONS:
344
+ if len(f) > 1 and re.fullmatch(r"\d\.\d\d", f[1]):
345
+ raise Unsupported(f"SINEX_TRO version {f[1]}: only "
346
+ f"{' and '.join(VERSIONS)} are implemented")
347
+ raise Invalid(f"line 1: format version {f[1] if len(f) > 1 else ''!r} is not F4.2")
348
+ return f[1]
349
+
350
+
351
+ def _header(line: str) -> Header:
352
+ version = _version(line)
353
+ f = line.split()
354
+ if len(f) != 9:
355
+ raise Invalid(f"line 1: the header line has {len(f)} fields, needs 9: {line!r}")
356
+ for name, at in (("creation time", 3), ("start", 5), ("end", 6)):
357
+ try:
358
+ epoch(f[at], VERSIONS[version])
359
+ except Invalid as e:
360
+ raise Invalid(f"line 1: {name}: {e}") from None
361
+ return Header(*f[1:])
362
+
363
+
364
+ def _once(pairs: tuple[tuple[str, str], ...], keys: tuple[str, ...]) -> str | None:
365
+ found = [value for key, value in pairs if key in keys]
366
+ if len(found) > 1:
367
+ raise Invalid(f"{DESCRIPTION}: {keys[0]} comes {len(found)} times")
368
+ return found[0] if found else None
369
+
370
+
371
+ def _names(file: TroFile) -> tuple[tuple[str, ...], tuple[str, ...] | None,
372
+ tuple[str, ...], tuple[str, ...] | None]:
373
+ """(parameters, units, slant parameters, slant units) from TROP/DESCRIPTION."""
374
+ pairs = file.description
375
+ if file.version == "0.01":
376
+ numbered: dict[int, str] = {}
377
+ for key, value in pairs:
378
+ m = _FIELDS.fullmatch(key)
379
+ if m:
380
+ if int(m[1]) in numbered:
381
+ raise Invalid(f"{DESCRIPTION}: {key} comes twice")
382
+ numbered[int(m[1])] = value
383
+ names = tuple(name for n in sorted(numbered) for name in numbered[n].split())
384
+ return names, None, (), None
385
+ out: list = []
386
+ for keys, units in (((TROPO_NAMES,), (TROPO_UNITS,)), (SLANT_NAMES, (SLANT_UNITS,))):
387
+ names_text, units_text = _once(pairs, keys), _once(pairs, units)
388
+ names = tuple(names_text.split()) if names_text is not None else ()
389
+ unit = tuple(units_text.split()) if units_text is not None else None
390
+ if unit is not None and len(unit) != len(names):
391
+ raise Invalid(f"{DESCRIPTION}: {len(unit)} {units[0]} for {len(names)} names")
392
+ out += [names, unit]
393
+ return out[0], out[1], out[2], out[3]
394
+
395
+
396
+ def _rows(file: TroFile, title: str, names: tuple[str, ...]) -> tuple[Row, ...]:
397
+ year = VERSIONS[file.version]
398
+ out = []
399
+ for b in file.blocks:
400
+ if b.title != title:
401
+ continue
402
+ if not names:
403
+ raise Invalid(f"{title} without the names of its fields in {DESCRIPTION}")
404
+ for line in b.data:
405
+ f = line.split()
406
+ if len(f) < 2:
407
+ raise Invalid(f"{title}: {line!r} has no time tag")
408
+ try:
409
+ when = epoch(f[1], year)
410
+ except Invalid as e:
411
+ raise Invalid(f"{title}: {line!r}: {e}") from None
412
+ if len(f) - 2 != len(names):
413
+ raise Invalid(f"{title}: {line!r} has {len(f) - 2} values for {len(names)} "
414
+ f"names ({' '.join(names)})")
415
+ out.append(Row(f[0], when, tuple(f[2:])))
416
+ return tuple(out)
417
+
418
+
419
+ def _split(text: str) -> tuple[list[str], str, bool]:
420
+ if not isinstance(text, str):
421
+ raise Invalid(f"read needs the file's text as a str, got {type(text).__name__}")
422
+ if not text:
423
+ raise Invalid("empty file")
424
+ lines = text.split("\n")
425
+ final = lines[-1] == ""
426
+ if final:
427
+ lines.pop()
428
+ ended = len(lines) if final else len(lines) - 1 # lines followed by LF
429
+ crlf = {line.endswith("\r") for line in lines[:ended]}
430
+ if len(crlf) > 1:
431
+ raise Invalid("lines end in both LF and CR LF")
432
+ newline = "\r\n" if crlf == {True} else "\n"
433
+ if newline == "\r\n":
434
+ lines[:ended] = [line[:-1] for line in lines[:ended]]
435
+ if "\r" in text:
436
+ for i, line in enumerate(lines):
437
+ if "\r" in line:
438
+ raise Invalid(f"line {i + 1}: a CR inside the line")
439
+ return lines, newline, final
440
+
441
+
442
+ def read(text: str) -> TroFile:
443
+ """The SINEX_TRO file in ``text``; raises :class:`Invalid` or :class:`Unsupported`.
444
+
445
+ The structure is checked here; the fields when they are asked for.
446
+ """
447
+ lines, newline, final = _split(text)
448
+ _version(lines[0])
449
+ if len(lines) < 2 or lines[-1].rstrip(" ") != FOOTER:
450
+ raise Invalid(f"line {len(lines)}: the last line must be the footer line {FOOTER}")
451
+ items: list[str | Block] = []
452
+ start: int | None = None # index of the open block's + line
453
+ body: list[str] = []
454
+ for i in range(1, len(lines) - 1):
455
+ line = lines[i]
456
+ c = line[:1]
457
+ where = f"line {i + 1}"
458
+ if c == "*" or not line.strip(" "):
459
+ (body if start is not None else items).append(line)
460
+ elif c == " ":
461
+ if start is None:
462
+ raise Invalid(f"{where}: a data line outside a block: {line!r}")
463
+ body.append(line)
464
+ elif c == "+":
465
+ title = line[1:].rstrip(" ")
466
+ if start is not None:
467
+ raise Invalid(f"{where}: +{title} begins inside the block "
468
+ f"{lines[start][1:].rstrip()} of line {start + 1}")
469
+ if not _TITLE.fullmatch(title):
470
+ raise Invalid(f"{where}: {title!r} is not a block title in capital letters")
471
+ start, body = i, []
472
+ elif c == "-":
473
+ if start is None:
474
+ raise Invalid(f"{where}: {line.rstrip()} ends no block")
475
+ items.append(Block(lines[start], tuple(body), line))
476
+ start = None
477
+ elif c == "%":
478
+ raise Invalid(f"{where}: {line[:30]!r}: the header line is the first and the "
479
+ "footer line the last")
480
+ else:
481
+ raise Invalid(f"{where}: a line must begin with '%', '*', '+', '-' or a blank, "
482
+ f"found {line[:30]!r}")
483
+ if start is not None:
484
+ raise Invalid(f"line {start + 1}: the block {lines[start][1:].rstrip()} is not ended")
485
+ return TroFile(lines[0], tuple(items), lines[-1], newline, final)
486
+
487
+
488
+ def _text(value: object, where: str) -> str:
489
+ if not isinstance(value, str):
490
+ raise Invalid(f"{where}: needs a str, got {value!r}")
491
+ return value
492
+
493
+
494
+ def write(file: TroFile) -> str:
495
+ """The text of ``file``; ``write(read(text)) == text``.
496
+
497
+ Lines that :func:`read` would not give back (a data line outside a
498
+ block, a line that is not text or holds a line break) are
499
+ :class:`Invalid`.
500
+ """
501
+ if not isinstance(file, TroFile):
502
+ raise Invalid(f"write needs a TroFile, got {type(file).__name__}")
503
+ if file.newline not in ("\n", "\r\n"):
504
+ raise Invalid(f"newline {file.newline!r}: LF or CR LF")
505
+ if not isinstance(file.items, tuple):
506
+ raise Invalid("the items of a TroFile must be a tuple")
507
+ lines = [_text(file.header, "header")]
508
+ for n, item in enumerate(file.items):
509
+ where = f"item {n}"
510
+ if isinstance(item, Block):
511
+ if not isinstance(item.lines, tuple):
512
+ raise Invalid(f"{where}: the lines of a Block must be a tuple")
513
+ lines.append(_text(item.start, where))
514
+ lines += [_text(line, where) for line in item.lines]
515
+ lines.append(_text(item.end, where))
516
+ else:
517
+ lines.append(_text(item, where))
518
+ lines.append(_text(file.footer, "footer"))
519
+ for line in lines:
520
+ if "\n" in line or "\r" in line:
521
+ raise Invalid(f"{line!r} holds a line break")
522
+ text = file.newline.join(lines) + (file.newline if file.final_newline else "")
523
+ # The rules are read's: what is written must read back as what was given.
524
+ try:
525
+ back = read(text)
526
+ except Invalid as e:
527
+ raise Invalid(f"these lines do not make a SINEX_TRO file: {e}") from None
528
+ if back != file:
529
+ raise Invalid("these lines do not read back as given: a block line is outside its "
530
+ "block's rules, or a line belongs to another part of the file")
531
+ return text
gnsswire/tro/py.typed ADDED
File without changes
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: gnsswire-tro
3
+ Version: 0.1.0
4
+ Summary: SINEX_TRO troposphere files (versions 0.01 and 2.00): zenith delays, gradients and their description, read and written losslessly as text fields.
5
+ Project-URL: Homepage, https://github.com/tracenav/gnsswire
6
+ Project-URL: Source, https://github.com/tracenav/gnsswire/tree/main/packages/tro
7
+ Project-URL: Changelog, https://github.com/tracenav/gnsswire/blob/main/RELEASES.md
8
+ Project-URL: Issues, https://github.com/tracenav/gnsswire/issues
9
+ Author: Trace Navigation
10
+ Maintainer-email: Jacob Armstrong <hi@jacobarm.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Scientific/Engineering :: GIS
24
+ Requires-Python: >=3.11
25
+ Description-Content-Type: text/markdown
26
+
27
+ # gnsswire-tro
28
+
29
+ SINEX_TRO troposphere files for Python
30
+
31
+ [![tests](https://github.com/tracenav/gnsswire/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/tracenav/gnsswire/actions/workflows/test.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/gnsswire-tro)](https://pypi.org/project/gnsswire-tro/)
33
+
34
+ gnsswire-tro reads and writes SINEX_TRO files, the text format in which
35
+ zenith tropospheric delays, their gradients and other tropospheric and
36
+ meteorological parameters are exchanged: version 2.00, and version 0.01,
37
+ in which the IGS writes its troposphere products
38
+ (`IGS0OPSFIN_..._TRO.TRO`). It gives you:
39
+
40
+ - the header line and every block, line by line;
41
+ - the solution (TROP/SOLUTION and SLANT/SOLUTION) as rows of marker, time
42
+ tag and values, named by TROP/DESCRIPTION, and the station coordinates;
43
+ - a lossless round trip: `write(read(text)) == text` for every file `read`
44
+ accepts;
45
+ - values as the text written, and as exact integers on request, without
46
+ floating point.
47
+
48
+ It is part of [gnsswire](https://pypi.org/project/gnsswire/), codecs for
49
+ GNSS wire formats.
50
+
51
+ ## Installation
52
+
53
+ ```sh
54
+ $ pip install gnsswire-tro
55
+ ```
56
+
57
+ gnsswire-tro requires Python 3.11+ and has no dependencies. `pip install
58
+ gnsswire` installs it with every other format.
59
+
60
+ ## Usage
61
+
62
+ ### Read a file
63
+
64
+ `read(text)` gives a `TroFile`: the header line, the blocks (`Block`: its
65
+ `+TITLE` line, its lines, its `-TITLE` line) and the comment and empty
66
+ lines between them, then the footer line. The text is the file's, decoded
67
+ (`encoding="latin-1"` reads any file); a `.gz` file is opened with
68
+ `gzip.open(path, "rt", encoding="latin-1", newline="")`:
69
+
70
+ ```python
71
+ from gnsswire import tro
72
+
73
+ text = (
74
+ "%=TRO 2.00 ABC 2026:281:03600 ABC 2026:280:00000 2026:280:86399 P MIX\n"
75
+ "+TROP/DESCRIPTION\n"
76
+ "*_________KEYWORD_____________ __VALUE(S)_______________________\n"
77
+ " TROPO SAMPLING INTERVAL 300\n"
78
+ " TROPO PARAMETER NAMES TROTOT STDDEV TGNTOT STDDEV TGETOT STDDEV\n"
79
+ " TROPO PARAMETER UNITS 1e+03 1e+03 1e+03 1e+03 1e+03 1e+03\n"
80
+ "-TROP/DESCRIPTION\n"
81
+ "+SITE/COORDINATES\n"
82
+ "*STATION__ PT SOLN T __DATA_START__ __DATA_END____ __STA_X_____ __STA_Y_____ __STA_Z_____ SYSTEM REMRK\n"
83
+ " ZIMM00CHE A 1 P 2026:280:00000 2026:280:86399 4331296.936 567556.035 4633134.023 IGS20 ABC\n"
84
+ "-SITE/COORDINATES\n"
85
+ "+TROP/SOLUTION\n"
86
+ "*STATION__ ____EPOCH_____ TROTOT STDDEV TGNTOT STDDEV TGETOT STDDEV\n"
87
+ " ZIMM00CHE 2026:280:00000 2187.1 1.2 0.31 0.10 -0.42 0.11\n"
88
+ " ZIMM00CHE 2026:280:00300 2187.4 1.2 0.30 0.10 -0.41 0.11\n"
89
+ "-TROP/SOLUTION\n"
90
+ "%=ENDTRO\n"
91
+ )
92
+ file = tro.read(text)
93
+ print(file.version, file.fields.agency, file.fields.contents) # 2.00 ABC MIX
94
+ print([b.title for b in file.blocks])
95
+ # ['TROP/DESCRIPTION', 'SITE/COORDINATES', 'TROP/SOLUTION']
96
+ print(file.description[0]) # ('TROPO SAMPLING INTERVAL', '300')
97
+ ```
98
+
99
+ ### The solution
100
+
101
+ TROP/SOLUTION lines are "space separated fields of variable length", their
102
+ number and order given in TROP/DESCRIPTION (TROPO PARAMETER NAMES in
103
+ 2.00, SOLUTION_FIELDS_1, _2, ... in 0.01). `file.solution` gives each
104
+ line as a `Row`, `file.parameters` the names and `file.units` their units
105
+ (2.00):
106
+
107
+ ```python
108
+ print(file.parameters) # ('TROTOT', 'STDDEV', 'TGNTOT', 'STDDEV', 'TGETOT', 'STDDEV')
109
+ for row in file.solution:
110
+ print(row.marker, row.epoch, row.values[0])
111
+ # ZIMM00CHE Epoch(year=2026, day=280, second=0) 2187.1
112
+ # ZIMM00CHE Epoch(year=2026, day=280, second=300) 2187.4
113
+ c = file.coordinates[0]
114
+ print(c.site, c.x, c.y, c.z, c.rest) # ZIMM00CHE 4331296.936 567556.035 4633134.023 ('IGS20', 'ABC')
115
+ ```
116
+
117
+ `file.slant`, `file.slant_parameters` and `file.slant_units` do the same
118
+ for SLANT/SOLUTION. A time tag's year is kept as written: two digits in
119
+ 0.01 files (`Epoch(year=26, ...)`).
120
+
121
+ ### Exact numbers
122
+
123
+ Values are kept as the text written. `digits(text)` gives a number as the
124
+ integer of its digits and its count of decimals, the value being
125
+ `integer * 10**-decimals`, without floating point:
126
+
127
+ ```python
128
+ print(tro.digits(file.solution[0].values[0])) # (21871, 1): 2187.1
129
+ print(tro.digits(file.units[0])) # (1, -3): 1e+03
130
+ ```
131
+
132
+ TROTOT 2187.1 in units of 1e+03 is 2.1871 m: "Values reported in
133
+ TROP/SOLUTION Block should be divided by the related TROPO UNITS to get
134
+ the base units".
135
+
136
+ ### Write it back
137
+
138
+ `write(file)` gives the text back, exactly as read:
139
+
140
+ ```python
141
+ print(tro.write(file) == text) # True
142
+ ```
143
+
144
+ `read` checks the structure: the header line's format version, blocks
145
+ begun and ended, the first character of every line, the footer line. The
146
+ fields are checked when they are asked for, so that a file whose
147
+ description or solution does not follow the document still reads and
148
+ writes back; the property raises `Invalid` then. A file of another format
149
+ version raises `Unsupported`. Both derive from `tro.Error`, a
150
+ `ValueError`.
151
+
152
+ ## Documentation
153
+
154
+ What gnsswire-tro checks and does not check, what its tests rest on and
155
+ the readings it takes where its specifications are ambiguous are under
156
+ [Limitations](https://github.com/tracenav/gnsswire#gnsswire-tro) in the
157
+ [repository README](https://github.com/tracenav/gnsswire#readme), with the
158
+ interface every gnsswire format shares and the version policy. Release
159
+ notes are in [RELEASES.md](https://github.com/tracenav/gnsswire/blob/main/RELEASES.md).
160
+
161
+ ## Contribute
162
+
163
+ Report bugs and request formats in the
164
+ [issue tracker](https://github.com/tracenav/gnsswire/issues).
165
+
166
+ ## Licence
167
+
168
+ MIT.
@@ -0,0 +1,7 @@
1
+ gnsswire/tro/__init__.py,sha256=pVz4vht7w2rlXAZyPxJbSoHt9ckmhv899WNHPFB1Hg8,1818
2
+ gnsswire/tro/_file.py,sha256=RlQc7u8HS-p_mJcFbN1h-mvHV1p7yGcWbFs8JftPybM,21779
3
+ gnsswire/tro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ gnsswire_tro-0.1.0.dist-info/METADATA,sha256=OSnMnAz3TeMidmBEusD9AJgROe85hOG6DFpHtHr0qdc,6762
5
+ gnsswire_tro-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ gnsswire_tro-0.1.0.dist-info/licenses/LICENSE,sha256=vTOffyQcCQ0mZGHa5HSChenFyOLGVN_enSQgEcwzMuM,1077
7
+ gnsswire_tro-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Trace Navigation LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.