gnsskit 0.6.0__tar.gz → 0.6.1__tar.gz
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.
- {gnsskit-0.6.0 → gnsskit-0.6.1}/PKG-INFO +1 -1
- {gnsskit-0.6.0 → gnsskit-0.6.1}/pyproject.toml +3 -2
- {gnsskit-0.6.0 → gnsskit-0.6.1}/pyproject.toml.orig +3 -2
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/__init__.py +12 -1
- gnsskit-0.6.1/src/gnsskit/interop/__init__.py +15 -0
- gnsskit-0.6.1/src/gnsskit/interop/_common.py +31 -0
- gnsskit-0.6.1/src/gnsskit/interop/geojson.py +69 -0
- gnsskit-0.6.1/src/gnsskit/interop/move3/__init__.py +6 -0
- gnsskit-0.6.1/src/gnsskit/interop/move3/report.py +289 -0
- gnsskit-0.6.0/src/gnsskit/export/move3.py → gnsskit-0.6.1/src/gnsskit/interop/move3/writer.py +32 -85
- gnsskit-0.6.1/src/gnsskit/interop/sinex.py +192 -0
- gnsskit-0.6.1/src/gnsskit/interop/starnet.py +70 -0
- gnsskit-0.6.0/src/gnsskit/export/__init__.py +0 -5
- {gnsskit-0.6.0 → gnsskit-0.6.1}/LICENSE +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/README.md +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/kinematic/__init__.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/kinematic/trajectory.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/plot/__init__.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/plot/_map.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/plot/occupations.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/plot/solutions.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/plot/visibility.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/ppp/__init__.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/py.typed +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/refsys.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/rinex.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/rtklib/__init__.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/rtklib/config.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/rtklib/pos.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/rtklib/runner.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/static/__init__.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/static/baseline.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/static/closure.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/static/network.py +0 -0
- {gnsskit-0.6.0 → gnsskit-0.6.1}/src/gnsskit/static/solve.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: gnsskit
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.1
|
|
4
4
|
Summary: RTKLIB-based GNSS post-processing toolkit: RINEX tools, RTKLIB wrappers, static baselines and network adjustment, kinematic trajectories
|
|
5
5
|
Keywords: gnss,gps,rtklib,ppk,surveying,least-squares
|
|
6
6
|
Author: Francesco Ioli
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "gnsskit"
|
|
3
|
-
version = "0.6.
|
|
3
|
+
version = "0.6.1"
|
|
4
4
|
description = "RTKLIB-based GNSS post-processing toolkit: RINEX tools, RTKLIB wrappers, static baselines and network adjustment, kinematic trajectories"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -47,7 +47,8 @@ all = [
|
|
|
47
47
|
]
|
|
48
48
|
|
|
49
49
|
[project.scripts]
|
|
50
|
-
gnsskit-move3 = "gnsskit.
|
|
50
|
+
gnsskit-move3 = "gnsskit.interop.move3.writer:main"
|
|
51
|
+
gnsskit-starnet = "gnsskit.interop.starnet:main"
|
|
51
52
|
|
|
52
53
|
[project.urls]
|
|
53
54
|
Repository = "https://github.com/franioli/gnsskit"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "gnsskit"
|
|
3
|
-
version = "0.6.
|
|
3
|
+
version = "0.6.1"
|
|
4
4
|
description = "RTKLIB-based GNSS post-processing toolkit: RINEX tools, RTKLIB wrappers, static baselines and network adjustment, kinematic trajectories"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -27,7 +27,8 @@ plot = ["matplotlib"]
|
|
|
27
27
|
all = ["scipy", "pyproj", "matplotlib"] # every extra above
|
|
28
28
|
|
|
29
29
|
[project.scripts]
|
|
30
|
-
gnsskit-move3 = "gnsskit.
|
|
30
|
+
gnsskit-move3 = "gnsskit.interop.move3.writer:main"
|
|
31
|
+
gnsskit-starnet = "gnsskit.interop.starnet:main"
|
|
31
32
|
|
|
32
33
|
[project.urls]
|
|
33
34
|
Repository = "https://github.com/franioli/gnsskit"
|
|
@@ -2,7 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
from importlib.metadata import version
|
|
4
4
|
|
|
5
|
-
from .
|
|
5
|
+
from .interop import (
|
|
6
|
+
read_move3_folder,
|
|
7
|
+
read_move3_report,
|
|
8
|
+
write_geojson,
|
|
9
|
+
write_move3,
|
|
10
|
+
write_sinex,
|
|
11
|
+
write_starnet,
|
|
12
|
+
)
|
|
6
13
|
from .kinematic import interpolate
|
|
7
14
|
from .plot import plot_baselines, plot_occupations, plot_pos, plot_visibility
|
|
8
15
|
from .refsys import (
|
|
@@ -74,6 +81,8 @@ __all__ = [
|
|
|
74
81
|
"plot_visibility",
|
|
75
82
|
"process_baseline",
|
|
76
83
|
"read_header",
|
|
84
|
+
"read_move3_folder",
|
|
85
|
+
"read_move3_report",
|
|
77
86
|
"read_occupations",
|
|
78
87
|
"read_pos",
|
|
79
88
|
"read_ref_pos",
|
|
@@ -87,6 +96,8 @@ __all__ = [
|
|
|
87
96
|
"to_gpst",
|
|
88
97
|
"trim_rinex",
|
|
89
98
|
"utc_to_gpst",
|
|
99
|
+
"write_geojson",
|
|
90
100
|
"write_move3",
|
|
101
|
+
"write_sinex",
|
|
91
102
|
"write_starnet",
|
|
92
103
|
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Interfaces to external software: MOVE3, StarNet, SINEX and GeoJSON."""
|
|
2
|
+
|
|
3
|
+
from .geojson import write_geojson
|
|
4
|
+
from .move3 import read_move3_folder, read_move3_report, write_move3
|
|
5
|
+
from .sinex import write_sinex
|
|
6
|
+
from .starnet import write_starnet
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"read_move3_folder",
|
|
10
|
+
"read_move3_report",
|
|
11
|
+
"write_geojson",
|
|
12
|
+
"write_move3",
|
|
13
|
+
"write_sinex",
|
|
14
|
+
"write_starnet",
|
|
15
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Helpers shared by the writers of the interop module."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ..static.baseline import BaselineResult, read_baselines
|
|
10
|
+
|
|
11
|
+
CRLF = "\r\n" # MOVE3 and StarNet are Windows programs: use CRLF line endings
|
|
12
|
+
MAX_NAME_LEN = 16 # station names (MOVE3 spec 1.1); applied to every writer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def prepare_baselines(
|
|
16
|
+
baselines: Sequence[BaselineResult] | Path | str, rename: Mapping[str, str] | None
|
|
17
|
+
) -> list[BaselineResult]:
|
|
18
|
+
"""Load baselines from a CSV if needed, rename stations and validate the names."""
|
|
19
|
+
bls = read_baselines(baselines) if isinstance(baselines, (str, Path)) else list(baselines)
|
|
20
|
+
if not bls:
|
|
21
|
+
raise ValueError("no baselines to export")
|
|
22
|
+
rename = rename or {}
|
|
23
|
+
bls = [
|
|
24
|
+
replace(b, base=rename.get(b.base, b.base), rover=rename.get(b.rover, b.rover)) for b in bls
|
|
25
|
+
]
|
|
26
|
+
for name in {n for b in bls for n in (b.base, b.rover)}:
|
|
27
|
+
if len(name) > MAX_NAME_LEN or " " in name or " " in name.strip():
|
|
28
|
+
raise ValueError(
|
|
29
|
+
f"invalid MOVE3 station name {name!r}: max {MAX_NAME_LEN} characters, no spaces"
|
|
30
|
+
)
|
|
31
|
+
return bls
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Export of a network adjustment to GeoJSON (RFC 7946), readable by QGIS and web maps.
|
|
2
|
+
|
|
3
|
+
One FeatureCollection with a Point per station (adjusted and held) and a LineString per
|
|
4
|
+
baseline. Coordinates are WGS84 [lon, lat, ellipsoidal height]. Standard library + numpy.
|
|
5
|
+
|
|
6
|
+
from gnsskit import write_geojson
|
|
7
|
+
write_geojson(adj, "network.geojson")
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from ..refsys import WGS84, ecef_to_enu_matrix, ecef_to_llh
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING: # the adjustment needs scipy: import it only for the annotations
|
|
21
|
+
from ..static.network import Adjustment
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _llh(xyz: np.ndarray) -> list[float]:
|
|
25
|
+
lat, lon, h = ecef_to_llh(*xyz, ellipsoid=WGS84)
|
|
26
|
+
return [round(float(lon), 9), round(float(lat), 9), round(float(h), 3)]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def write_geojson(adj: Adjustment, path: Path | str) -> Path:
|
|
30
|
+
"""Write the adjusted network as a GeoJSON FeatureCollection.
|
|
31
|
+
|
|
32
|
+
Point properties: `name`, `fixed`, ECEF `X`, `Y`, `Z` [m] and the standard deviations
|
|
33
|
+
`sd_E`, `sd_N`, `sd_U` [m] in the local east-north-up frame (0 for held points).
|
|
34
|
+
LineString properties: `kind` = "baseline", `session`, `from`, `to`, `length_m`.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
adj: Result of `adjust_network`.
|
|
38
|
+
path: Output file.
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
The written file.
|
|
42
|
+
"""
|
|
43
|
+
xyz = {**dict(zip(adj.unknowns, adj.xyz, strict=True)), **adj.fixed}
|
|
44
|
+
feats = []
|
|
45
|
+
for i, (name, p) in enumerate(xyz.items()):
|
|
46
|
+
lat, lon, _ = ecef_to_llh(*p, ellipsoid=WGS84)
|
|
47
|
+
if i < len(adj.unknowns): # propagate the 3x3 block to east-north-up
|
|
48
|
+
R = ecef_to_enu_matrix(float(lat), float(lon))
|
|
49
|
+
sd = np.sqrt(np.diag(R @ adj.Cxx[3 * i : 3 * i + 3, 3 * i : 3 * i + 3] @ R.T))
|
|
50
|
+
else:
|
|
51
|
+
sd = np.zeros(3)
|
|
52
|
+
props = {"name": name, "fixed": name in adj.fixed}
|
|
53
|
+
props |= dict(zip("XYZ", map(float, p), strict=True))
|
|
54
|
+
props |= {f"sd_{k}": round(float(s), 5) for k, s in zip("ENU", sd, strict=True)}
|
|
55
|
+
feats.append(_feature({"type": "Point", "coordinates": _llh(p)}, props))
|
|
56
|
+
for b in adj.baselines:
|
|
57
|
+
line = {"type": "LineString", "coordinates": [_llh(xyz[b.base]), _llh(xyz[b.rover])]}
|
|
58
|
+
length = float(np.linalg.norm(xyz[b.rover] - xyz[b.base]))
|
|
59
|
+
props = {"kind": "baseline", "session": b.session, "from": b.base, "to": b.rover}
|
|
60
|
+
props["length_m"] = round(length, 3)
|
|
61
|
+
feats.append(_feature(line, props))
|
|
62
|
+
out = Path(path)
|
|
63
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
64
|
+
out.write_text(json.dumps({"type": "FeatureCollection", "features": feats}, indent=1))
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _feature(geometry: dict, properties: dict) -> dict:
|
|
69
|
+
return {"type": "Feature", "geometry": geometry, "properties": properties}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Parse MOVE3 HTML adjustment reports (``*.out1.html``, ...) into tidy pandas tables.
|
|
2
|
+
|
|
3
|
+
Works for terrestrial, GNSS-only (DX/DY/DZ baselines) and combined networks, free or
|
|
4
|
+
constrained: the tables are read by section title and their columns follow what MOVE3 prints.
|
|
5
|
+
|
|
6
|
+
summary one row: counts, degrees of freedom, test settings, F and chi-square tests,
|
|
7
|
+
variance components
|
|
8
|
+
points adjusted coordinates, standard deviations, absolute standard ellipses (one row
|
|
9
|
+
per station; coordinate columns as printed: X/Y/Z or X/Y/H)
|
|
10
|
+
obs_tests one row per observation: reliability (MDB, redundancy, BNR), w-test, and the
|
|
11
|
+
residuals from the ADJUSTED OBSERVATIONS section when present
|
|
12
|
+
|
|
13
|
+
from gnsskit import read_move3_report
|
|
14
|
+
rep = read_move3_report("move3/project.out1.html")
|
|
15
|
+
rep["points"], rep["obs_tests"], rep["summary"]
|
|
16
|
+
|
|
17
|
+
Command line: ``gnsskit-move3 report folder [-o results]`` writes the CSVs of every report found.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from html.parser import HTMLParser
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import pandas as pd
|
|
27
|
+
|
|
28
|
+
Tables = list[tuple[str, list[list[str]]]]
|
|
29
|
+
|
|
30
|
+
# observation codes of the TEST OF OBSERVATIONS table (terrestrial and GNSS)
|
|
31
|
+
OBS_TYPES = {
|
|
32
|
+
"R0": "direction",
|
|
33
|
+
"S0": "distance",
|
|
34
|
+
"Z0": "zenith",
|
|
35
|
+
"A0": "azimuth",
|
|
36
|
+
"DX": "dX",
|
|
37
|
+
"DY": "dY",
|
|
38
|
+
"DZ": "dZ",
|
|
39
|
+
"DV": "baseline",
|
|
40
|
+
}
|
|
41
|
+
COORD_NAMES = {"X East": "X", "Y North": "Y", "Height": "H"}
|
|
42
|
+
|
|
43
|
+
# summary rows -> column names; unlisted rows of the count blocks are kept as n_<block>_<row>
|
|
44
|
+
SUMMARY_NAMES = {
|
|
45
|
+
"Number of (partly) known stations": "n_known_stations",
|
|
46
|
+
"Number of unknown stations": "n_unknown_stations",
|
|
47
|
+
"Directions": "n_directions",
|
|
48
|
+
"Distances": "n_distances",
|
|
49
|
+
"Zenith angles": "n_zenith",
|
|
50
|
+
"Azimuths": "n_azimuths",
|
|
51
|
+
"GNSS/GPS coordinate differences": "n_gnss_obs",
|
|
52
|
+
"Known coordinates": "n_known_coords",
|
|
53
|
+
"OBSERVATIONS total": "n_obs",
|
|
54
|
+
"Coordinates": "n_unk_coords",
|
|
55
|
+
"Orientations": "n_unk_orient",
|
|
56
|
+
"Scale factors": "n_unk_scale",
|
|
57
|
+
"UNKNOWNS total": "n_unknowns",
|
|
58
|
+
"Degrees of freedom": "dof",
|
|
59
|
+
"Number of iterations": "iterations",
|
|
60
|
+
"Max coord correction in last iteration": "max_corr",
|
|
61
|
+
"Alfa (multi dimensional)": "alpha_multi",
|
|
62
|
+
"Alfa 0 (one dimensional)": "alpha0",
|
|
63
|
+
"Beta": "beta",
|
|
64
|
+
"Critical value W-test": "w_crit",
|
|
65
|
+
"Critical value T-test (3 dimensional)": "t_crit_3d",
|
|
66
|
+
"Critical value T-test (2 dimensional)": "t_crit_2d",
|
|
67
|
+
"Critical value F-test": "F_crit",
|
|
68
|
+
"F-test": "F_test",
|
|
69
|
+
"Lower Bound": "chi2_lower",
|
|
70
|
+
"Upper Bound": "chi2_upper",
|
|
71
|
+
"Chi-Square Test": "chi2_test",
|
|
72
|
+
}
|
|
73
|
+
RESULTS = ("Accepted", "Rejected", "Passed", "Failed")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _Tables(HTMLParser):
|
|
77
|
+
"""Collect every <table> as rows of cell texts, tagged with the last section title."""
|
|
78
|
+
|
|
79
|
+
def __init__(self) -> None:
|
|
80
|
+
super().__init__()
|
|
81
|
+
self.tables: Tables = []
|
|
82
|
+
self._title, self._in_a, self._a_text = "", False, ""
|
|
83
|
+
self._rows: list[list[str]] | None = None
|
|
84
|
+
self._cell: list[str] | None = None
|
|
85
|
+
|
|
86
|
+
def handle_starttag(self, tag: str, attrs: list) -> None:
|
|
87
|
+
if tag == "a":
|
|
88
|
+
self._in_a, self._a_text = True, ""
|
|
89
|
+
elif tag == "table":
|
|
90
|
+
self._rows = []
|
|
91
|
+
elif tag == "tr" and self._rows is not None:
|
|
92
|
+
self._rows.append([])
|
|
93
|
+
elif tag in ("td", "th") and self._rows is not None:
|
|
94
|
+
self._cell = []
|
|
95
|
+
|
|
96
|
+
def handle_endtag(self, tag: str) -> None:
|
|
97
|
+
if tag == "a" and self._in_a:
|
|
98
|
+
self._in_a = False
|
|
99
|
+
if re.match(
|
|
100
|
+
r"[A-Z]{3,}( [A-Z]+)*", self._a_text.strip()
|
|
101
|
+
): # "ADJUSTED COORDINATES (...)"
|
|
102
|
+
self._title = self._a_text.strip()
|
|
103
|
+
elif tag in ("td", "th") and self._cell is not None and self._rows is not None:
|
|
104
|
+
if not self._rows:
|
|
105
|
+
self._rows.append([])
|
|
106
|
+
self._rows[-1].append(" ".join("".join(self._cell).split()))
|
|
107
|
+
self._cell = None
|
|
108
|
+
elif tag == "table" and self._rows is not None:
|
|
109
|
+
self.tables.append((self._title, [r for r in self._rows if any(r)]))
|
|
110
|
+
self._rows = None
|
|
111
|
+
|
|
112
|
+
def handle_data(self, data: str) -> None:
|
|
113
|
+
if self._in_a:
|
|
114
|
+
self._a_text += data
|
|
115
|
+
if self._cell is not None:
|
|
116
|
+
self._cell.append(data)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def read_html(path: Path | str) -> str:
|
|
120
|
+
"""Read a report, which MOVE3 writes in UTF-16."""
|
|
121
|
+
raw = Path(path).read_bytes()
|
|
122
|
+
enc = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8"
|
|
123
|
+
return raw.decode(enc, errors="replace")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _num(s: str) -> float | None:
|
|
127
|
+
try:
|
|
128
|
+
return float(s.replace(",", "."))
|
|
129
|
+
except (ValueError, AttributeError):
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _slug(s: str) -> str:
|
|
134
|
+
return re.sub(r"\W+", "_", s.lower()).strip("_")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _section(tables: Tables, title: str) -> list[list[str]]:
|
|
138
|
+
"""Rows of the first table whose section title starts with `title`."""
|
|
139
|
+
return next((rows for t, rows in tables if t.startswith(title)), [])
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def parse_summary(html: str, tables: Tables) -> dict:
|
|
143
|
+
"""Header block (counts, adjustment, testing) and variance component analysis."""
|
|
144
|
+
raw: dict[str, str] = {}
|
|
145
|
+
m = re.search(
|
|
146
|
+
r'class="MOVE3Header">([^<]+)<br>(\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2})</p>\s*<br>\s*<p>([^<]*)',
|
|
147
|
+
html,
|
|
148
|
+
)
|
|
149
|
+
summary: dict = {}
|
|
150
|
+
if m: # third line, e.g. "3D free network -- Projection : None -- Ellipsoid : WGS 84"
|
|
151
|
+
summary = {
|
|
152
|
+
"project": m.group(1).strip(),
|
|
153
|
+
"datetime": m.group(2),
|
|
154
|
+
"model": m.group(3).strip(),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
block, counts = "", {}
|
|
158
|
+
for title, rows in tables:
|
|
159
|
+
if title: # the header tables come before the first collapsible section
|
|
160
|
+
break
|
|
161
|
+
for r in rows:
|
|
162
|
+
if len(r) == 1 and r[0].isupper():
|
|
163
|
+
block = r[0]
|
|
164
|
+
elif len(r) >= 2 and r[0]:
|
|
165
|
+
key = f"{block} total" if r[0] == "Total" else r[0]
|
|
166
|
+
raw[key] = r[1]
|
|
167
|
+
if len(r) > 2 and r[2] in RESULTS:
|
|
168
|
+
raw[f"{key} result"] = r[2]
|
|
169
|
+
if block in ("STATIONS", "OBSERVATIONS", "UNKNOWNS"):
|
|
170
|
+
counts[key] = block
|
|
171
|
+
if m2 := re.match(r"\((\d+) baselines?\)", r[2] if len(r) > 2 else ""):
|
|
172
|
+
summary["n_baselines"] = int(m2.group(1))
|
|
173
|
+
|
|
174
|
+
for key, val in raw.items():
|
|
175
|
+
if key in SUMMARY_NAMES:
|
|
176
|
+
summary[SUMMARY_NAMES[key]] = _num(val)
|
|
177
|
+
elif key in counts and not key.endswith("total"):
|
|
178
|
+
summary[f"n_{_slug(counts[key])}_{_slug(key)}"] = _num(val)
|
|
179
|
+
for test, name in (("F-test", "F"), ("Chi-Square Test", "chi2")):
|
|
180
|
+
summary[f"{name}_result"] = raw.get(f"{test} result")
|
|
181
|
+
conf = next((k for k in raw if k.startswith("Chi-Square Test (")), None)
|
|
182
|
+
summary["chi2_confidence"] = _num(re.search(r"\(([\d.]+)%\)", conf)[1]) if conf else None
|
|
183
|
+
|
|
184
|
+
for r in _section(tables, "VARIANCE COMPONENT ANALYSIS")[1:]:
|
|
185
|
+
if len(r) >= 3:
|
|
186
|
+
summary[f"var_{_slug(r[0])}"], summary[f"red_{_slug(r[0])}"] = _num(r[1]), _num(r[2])
|
|
187
|
+
return summary
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def parse_points(tables: Tables) -> pd.DataFrame:
|
|
191
|
+
"""Adjusted coordinates with standard deviations, merged with the absolute standard ellipses."""
|
|
192
|
+
rows, station = [], None
|
|
193
|
+
for r in _section(tables, "ADJUSTED COORDINATES")[1:]:
|
|
194
|
+
if len(r) < 6:
|
|
195
|
+
continue
|
|
196
|
+
station = r[0] or station # the station name is blank after its first component
|
|
197
|
+
rows.append(
|
|
198
|
+
{"station": station, "comp": COORD_NAMES.get(r[1], _slug(r[1]).upper()),
|
|
199
|
+
"value": _num(r[2]), "known": r[3] == "*", "corr": _num(r[4]), "sd": _num(r[5])}
|
|
200
|
+
) # fmt: skip
|
|
201
|
+
if not rows:
|
|
202
|
+
return pd.DataFrame()
|
|
203
|
+
coords = pd.DataFrame(rows)
|
|
204
|
+
order = coords.station.unique()
|
|
205
|
+
wide = coords.pivot(index="station", columns="comp", values=["value", "sd", "corr"])
|
|
206
|
+
wide.columns = [c if v == "value" else f"{c}_{v}" for v, c in wide.columns]
|
|
207
|
+
wide["known"] = coords.groupby("station").known.any()
|
|
208
|
+
ell = [
|
|
209
|
+
{"station": r[0], "ell_A": _num(r[1]), "ell_B": _num(r[2]), "ell_AB": _num(r[4]),
|
|
210
|
+
"ell_phi_gon": _num(r[6]), "sd_H_ell": _num(r[7])}
|
|
211
|
+
for r in _section(tables, "ABSOLUTE STANDARD ELLIPSES")[1:]
|
|
212
|
+
if len(r) >= 8
|
|
213
|
+
] # fmt: skip
|
|
214
|
+
if ell:
|
|
215
|
+
wide = wide.join(pd.DataFrame(ell).set_index("station"))
|
|
216
|
+
return wide.loc[order].reset_index()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def parse_obs_tests(tables: Tables) -> pd.DataFrame:
|
|
220
|
+
"""TEST OF OBSERVATIONS (MDB, MDBn, redundancy [%], BNR, w-test) plus adjusted residuals."""
|
|
221
|
+
rows = []
|
|
222
|
+
for r in _section(tables, "TEST OF OBSERVATIONS")[1:]:
|
|
223
|
+
if len(r) < 9 or r[0] not in OBS_TYPES:
|
|
224
|
+
continue
|
|
225
|
+
rows.append(
|
|
226
|
+
{"code": r[0], "type": OBS_TYPES[r[0]], "station": r[1], "target": r[2],
|
|
227
|
+
"MDB": _num(r[3]), "MDB_unit": r[4], "MDBn": _num(r[5]), "red_pct": _num(r[6]),
|
|
228
|
+
"BNR": _num(r[7]), "w_test": _num(r[8]), "est_err": _num(r[9]) if len(r) > 9 else None,
|
|
229
|
+
"t_test": _num(r[10]) if len(r) > 10 else None}
|
|
230
|
+
) # fmt: skip
|
|
231
|
+
df = pd.DataFrame(rows)
|
|
232
|
+
if df.empty:
|
|
233
|
+
return df
|
|
234
|
+
# same observations, same order, in ADJUSTED OBSERVATIONS (repeated baselines get a counter)
|
|
235
|
+
adj = pd.DataFrame(
|
|
236
|
+
[
|
|
237
|
+
{"code": r[0], "station": r[1], "target": r[2], "adj_obs": _num(r[3]),
|
|
238
|
+
"resid": _num(r[4]), "resid_enh": _num(r[5]), "sd_adj": _num(r[6])}
|
|
239
|
+
for r in _section(tables, "ADJUSTED OBSERVATIONS")[1:]
|
|
240
|
+
if len(r) >= 7 and r[0] in OBS_TYPES
|
|
241
|
+
]
|
|
242
|
+
) # fmt: skip
|
|
243
|
+
if adj.empty:
|
|
244
|
+
return df
|
|
245
|
+
key = ["code", "station", "target"]
|
|
246
|
+
df["_n"], adj["_n"] = df.groupby(key).cumcount(), adj.groupby(key).cumcount()
|
|
247
|
+
return df.merge(adj, on=[*key, "_n"], how="left").drop(columns="_n")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def read_move3_report(path: Path | str) -> dict:
|
|
251
|
+
"""Parse one report into {'summary': dict, 'points': DataFrame, 'obs_tests': DataFrame}."""
|
|
252
|
+
html = read_html(path)
|
|
253
|
+
p = _Tables()
|
|
254
|
+
p.feed(html)
|
|
255
|
+
obs = parse_obs_tests(p.tables)
|
|
256
|
+
summary = parse_summary(html, p.tables)
|
|
257
|
+
if not obs.empty and summary.get("w_crit") is not None:
|
|
258
|
+
summary["n_rejected"] = int((obs.w_test.abs() > summary["w_crit"]).sum())
|
|
259
|
+
summary["max_abs_w"] = obs.w_test.abs().max()
|
|
260
|
+
summary["min_red_pct"] = obs.red_pct.min()
|
|
261
|
+
return {"summary": summary, "points": parse_points(p.tables), "obs_tests": obs}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def read_move3_folder(folder: Path | str) -> dict[str, pd.DataFrame]:
|
|
265
|
+
"""Parse every ``*.out*.html`` under `folder` into summary, points and obs_tests tables.
|
|
266
|
+
|
|
267
|
+
Each table has the columns ``file`` (relative path) and ``run`` (N of ``.outN.html``) first.
|
|
268
|
+
"""
|
|
269
|
+
folder = Path(folder)
|
|
270
|
+
summaries, points, tests = [], [], []
|
|
271
|
+
for f in sorted(folder.glob("**/*.out*.html")):
|
|
272
|
+
rep = read_move3_report(f)
|
|
273
|
+
run = re.search(r"\.out(\d+)\.html$", f.name, flags=re.IGNORECASE)
|
|
274
|
+
key = {"file": str(f.relative_to(folder)), "run": int(run[1]) if run else None}
|
|
275
|
+
summaries.append({**key, **rep["summary"]})
|
|
276
|
+
if not rep["points"].empty:
|
|
277
|
+
points.append(rep["points"].assign(**key))
|
|
278
|
+
if not rep["obs_tests"].empty:
|
|
279
|
+
tests.append(rep["obs_tests"].assign(**key))
|
|
280
|
+
out = {
|
|
281
|
+
"summary": pd.DataFrame(summaries),
|
|
282
|
+
"points": pd.concat(points, ignore_index=True) if points else pd.DataFrame(),
|
|
283
|
+
"obs_tests": pd.concat(tests, ignore_index=True) if tests else pd.DataFrame(),
|
|
284
|
+
}
|
|
285
|
+
first = ["file", "run"]
|
|
286
|
+
return {
|
|
287
|
+
k: df[first + [c for c in df.columns if c not in first]] if not df.empty else df
|
|
288
|
+
for k, df in out.items()
|
|
289
|
+
}
|
gnsskit-0.6.0/src/gnsskit/export/move3.py → gnsskit-0.6.1/src/gnsskit/interop/move3/writer.py
RENAMED
|
@@ -1,48 +1,28 @@
|
|
|
1
|
-
"""Export static baselines to
|
|
1
|
+
"""Export static baselines to a native MOVE3 project (.gco, .obs, .prj).
|
|
2
2
|
|
|
3
3
|
Pure numpy/stdlib: no extra dependencies. The input is the list of `BaselineResult` from
|
|
4
4
|
`process_baseline` / `read_baselines`, or the path of the CSV written by `write_baselines`.
|
|
5
5
|
Format reference: MOVE3 File Specification, section 1.1.
|
|
6
6
|
|
|
7
|
-
from gnsskit
|
|
7
|
+
from gnsskit import write_move3
|
|
8
8
|
write_move3("baselines.csv", "move3/", "myproject", origin=("MIL3", 4421979.9, 718518.4, 4524921.2),
|
|
9
9
|
rename={"mil": "MIL3"})
|
|
10
10
|
|
|
11
|
-
Command line: `gnsskit-move3 native
|
|
11
|
+
Command line: `gnsskit-move3 native baselines.csv ...` (see `-h`); the StarNet
|
|
12
|
+
file is in `gnsskit.interop.starnet`, the report parser in `gnsskit.interop.move3.report`.
|
|
12
13
|
"""
|
|
13
14
|
|
|
14
15
|
from __future__ import annotations
|
|
15
16
|
|
|
16
17
|
import argparse
|
|
17
18
|
from collections.abc import Mapping, Sequence
|
|
18
|
-
from dataclasses import replace
|
|
19
19
|
from pathlib import Path
|
|
20
20
|
|
|
21
21
|
import numpy as np
|
|
22
22
|
|
|
23
|
-
from
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
MAX_NAME_LEN = 16 # station names (spec 1.1)
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def _prepare(
|
|
30
|
-
baselines: Sequence[BaselineResult] | Path | str, rename: Mapping[str, str] | None
|
|
31
|
-
) -> list[BaselineResult]:
|
|
32
|
-
"""Load baselines from a CSV if needed, rename stations and validate the names."""
|
|
33
|
-
bls = read_baselines(baselines) if isinstance(baselines, (str, Path)) else list(baselines)
|
|
34
|
-
if not bls:
|
|
35
|
-
raise ValueError("no baselines to export")
|
|
36
|
-
rename = rename or {}
|
|
37
|
-
bls = [
|
|
38
|
-
replace(b, base=rename.get(b.base, b.base), rover=rename.get(b.rover, b.rover)) for b in bls
|
|
39
|
-
]
|
|
40
|
-
for name in {n for b in bls for n in (b.base, b.rover)}:
|
|
41
|
-
if len(name) > MAX_NAME_LEN or " " in name or " " in name.strip():
|
|
42
|
-
raise ValueError(
|
|
43
|
-
f"invalid MOVE3 station name {name!r}: max {MAX_NAME_LEN} characters, no spaces"
|
|
44
|
-
)
|
|
45
|
-
return bls
|
|
23
|
+
from ...static.baseline import BaselineResult
|
|
24
|
+
from .._common import CRLF, prepare_baselines
|
|
25
|
+
from .report import read_move3_folder
|
|
46
26
|
|
|
47
27
|
|
|
48
28
|
def approx_coords(
|
|
@@ -322,80 +302,47 @@ def write_move3(
|
|
|
322
302
|
Returns:
|
|
323
303
|
The written files [.gco, .obs, .prj].
|
|
324
304
|
"""
|
|
325
|
-
bls =
|
|
305
|
+
bls = prepare_baselines(baselines, rename)
|
|
326
306
|
out = Path(outdir)
|
|
327
307
|
out.mkdir(parents=True, exist_ok=True)
|
|
328
308
|
org = {origin[0]: np.array(origin[1:], dtype=float)}
|
|
329
309
|
return [*_write_native(bls, org, fix_origin, project, m0, out), _write_prj(project, out)]
|
|
330
310
|
|
|
331
311
|
|
|
332
|
-
def write_starnet(
|
|
333
|
-
baselines: Sequence[BaselineResult] | Path | str,
|
|
334
|
-
outdir: Path | str,
|
|
335
|
-
project: str = "project",
|
|
336
|
-
*,
|
|
337
|
-
m0: float = 10.0,
|
|
338
|
-
rename: Mapping[str, str] | None = None,
|
|
339
|
-
) -> Path:
|
|
340
|
-
"""Write a StarNet NAME.gps file, imported into MOVE3 with Import/export > GNSS/GPS.
|
|
341
|
-
|
|
342
|
-
G0 label, G1 from-to dXYZ, G2 variances, G3 covariances. The format has no M0 field, so
|
|
343
|
-
covariances are scaled by `m0`**2. No station coordinates: enter them in MOVE3 afterwards.
|
|
344
|
-
|
|
345
|
-
Returns:
|
|
346
|
-
The written file.
|
|
347
|
-
"""
|
|
348
|
-
bls = _prepare(baselines, rename)
|
|
349
|
-
out = Path(outdir)
|
|
350
|
-
out.mkdir(parents=True, exist_ok=True)
|
|
351
|
-
lines = [".GPS WEIGHT COVARIANCE"]
|
|
352
|
-
for b in bls:
|
|
353
|
-
c = b.cov * m0**2
|
|
354
|
-
lines += [
|
|
355
|
-
"G0 '" + f"{project} {b.session} {b.base}-{b.rover}".replace(" ", " "),
|
|
356
|
-
f"G1 {b.base}-{b.rover} " + " ".join(f"{v:.4f}" for v in b.dxyz),
|
|
357
|
-
f"G2 {c[0, 0]:.6E} {c[1, 1]:.6E} {c[2, 2]:.6E}",
|
|
358
|
-
f"G3 {c[0, 1]:.6E} {c[0, 2]:.6E} {c[1, 2]:.6E}",
|
|
359
|
-
]
|
|
360
|
-
path = out / f"{project}.gps"
|
|
361
|
-
path.write_text(CRLF.join(lines) + CRLF, newline="")
|
|
362
|
-
return path
|
|
363
|
-
|
|
364
|
-
|
|
365
312
|
def main(argv: Sequence[str] | None = None) -> None:
|
|
366
|
-
"""Command line: `gnsskit-move3 native
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
help="multiplication factor of the baseline standard deviations (default: %(default)s)",
|
|
373
|
-
) # fmt: skip
|
|
374
|
-
common.add_argument(
|
|
375
|
-
"--rename", nargs="*", default=[], metavar="OLD=NEW", help="rename stations, e.g. mil=MIL3"
|
|
376
|
-
)
|
|
377
|
-
ap = argparse.ArgumentParser(
|
|
378
|
-
description="Export RTKLIB baselines (ECEF + covariance) to MOVE3."
|
|
379
|
-
)
|
|
380
|
-
sub = ap.add_subparsers(dest="format", required=True, metavar="{native,starnet}")
|
|
381
|
-
nat = sub.add_parser("native", parents=[common], help="PROJECT.gco + .obs + .prj")
|
|
313
|
+
"""Command line: `gnsskit-move3 native baselines.csv ...` or `gnsskit-move3 report folder`."""
|
|
314
|
+
ap = argparse.ArgumentParser(description="MOVE3 project export and report parsing.")
|
|
315
|
+
sub = ap.add_subparsers(dest="cmd", required=True, metavar="{native,report}")
|
|
316
|
+
nat = sub.add_parser("native", help="PROJECT.gco + .obs + .prj from a baselines CSV")
|
|
317
|
+
nat.add_argument("csv", type=Path, help="baselines CSV written by write_baselines")
|
|
318
|
+
nat.add_argument("--outdir", type=Path, default=Path("."), help="output folder")
|
|
382
319
|
nat.add_argument("--project", required=True, metavar="NAME", help="project name")
|
|
383
320
|
nat.add_argument(
|
|
384
321
|
"--origin", required=True, nargs=4, metavar=("NAME", "X", "Y", "Z"),
|
|
385
322
|
help="station with known ECEF coordinates [m]",
|
|
386
323
|
) # fmt: skip
|
|
387
324
|
nat.add_argument("--fix_origin", action="store_true", help="write the origin as fixed")
|
|
388
|
-
|
|
389
|
-
|
|
325
|
+
nat.add_argument(
|
|
326
|
+
"--m0", type=float, default=10.0,
|
|
327
|
+
help="multiplication factor of the baseline standard deviations (default: %(default)s)",
|
|
328
|
+
) # fmt: skip
|
|
329
|
+
nat.add_argument("--rename", nargs="*", default=[], metavar="OLD=NEW", help="e.g. mil=MIL3")
|
|
330
|
+
rep = sub.add_parser("report", help="parse the HTML adjustment reports into CSV tables")
|
|
331
|
+
rep.add_argument("folder", type=Path, help="folder with the reports (searched recursively)")
|
|
332
|
+
rep.add_argument("-o", "--out", type=Path, help="output folder (default: FOLDER/move3_results)")
|
|
390
333
|
a = ap.parse_args(argv)
|
|
391
334
|
|
|
335
|
+
if a.cmd == "report":
|
|
336
|
+
out = a.out or a.folder / "move3_results"
|
|
337
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
338
|
+
for name, df in read_move3_folder(a.folder).items():
|
|
339
|
+
df.to_csv(out / f"{name}.csv", index=False)
|
|
340
|
+
print(f"{name}: {len(df)} rows -> {out / f'{name}.csv'}")
|
|
341
|
+
return
|
|
392
342
|
if any("=" not in r for r in a.rename):
|
|
393
343
|
ap.error("--rename expects OLD=NEW pairs, e.g. --rename mil=MIL3")
|
|
394
344
|
rename = dict(r.split("=", 1) for r in a.rename)
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
fix_origin=a.fix_origin, m0=a.m0, rename=rename) # fmt: skip
|
|
399
|
-
else:
|
|
400
|
-
paths = [write_starnet(a.csv, a.outdir, a.project, m0=a.m0, rename=rename)]
|
|
345
|
+
o = a.origin
|
|
346
|
+
paths = write_move3(a.csv, a.outdir, a.project, (o[0], *map(float, o[1:])),
|
|
347
|
+
fix_origin=a.fix_origin, m0=a.m0, rename=rename) # fmt: skip
|
|
401
348
|
print("wrote " + ", ".join(map(str, paths)))
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Export of a network adjustment to SINEX 2.02 (station coordinates + covariance).
|
|
2
|
+
|
|
3
|
+
SINEX is the IERS/IGS exchange format for station coordinates with their full covariance
|
|
4
|
+
matrix. Format reference: SINEX 2.02 (IERS, 2006-12-01), blocks FILE/REFERENCE, SITE/ID,
|
|
5
|
+
SOLUTION/EPOCHS, SOLUTION/STATISTICS, SOLUTION/ESTIMATE, SOLUTION/APRIORI and
|
|
6
|
+
SOLUTION/MATRIX_ESTIMATE (L COVA). Pure numpy/stdlib: no extra dependencies.
|
|
7
|
+
|
|
8
|
+
from gnsskit import write_sinex
|
|
9
|
+
write_sinex(adj, "network.snx", agency="POL", rename={"mil": "MIL3"})
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from importlib.metadata import version
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
from ..refsys import GPST_UTC_OFFSET_S, ecef_to_llh
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING: # the adjustment needs scipy: import it only for the annotations
|
|
26
|
+
from ..static.network import Adjustment
|
|
27
|
+
|
|
28
|
+
MAX_CODE_LEN = 4 # site code is A4 in SINEX
|
|
29
|
+
VERSION = "2.02"
|
|
30
|
+
UNDEF = "-"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _time(t: pd.Timestamp | datetime) -> str:
|
|
34
|
+
"""YY:DDD:SSSSS (year, day of year, seconds of day), 12 characters."""
|
|
35
|
+
t = pd.Timestamp(t)
|
|
36
|
+
sod = t.hour * 3600 + t.minute * 60 + int(t.second)
|
|
37
|
+
return f"{t.year % 100:02d}:{t.dayofyear:03d}:{sod:05d}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _fortran_e(v: float, width: int, decimals: int) -> str:
|
|
41
|
+
"""Fortran `E<width>.<decimals>`: 0.ddd...E+XX, leading zero dropped if it does not fit."""
|
|
42
|
+
mant, exp = f"{abs(v):.{decimals - 1}E}".split("E")
|
|
43
|
+
digits = mant.replace(".", "")
|
|
44
|
+
e = 0 if float(mant) == 0 else int(exp) + 1
|
|
45
|
+
s = f"{'-' if v < 0 else ''}0.{digits}E{e:+03d}"
|
|
46
|
+
if len(s) > width:
|
|
47
|
+
s = s.replace("0.", ".", 1)
|
|
48
|
+
return s.rjust(width)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dms(deg: float, signed: bool) -> str:
|
|
52
|
+
"""Degrees (I3), minutes (I2), seconds (F4.1); only the degrees carry the sign."""
|
|
53
|
+
tenths = round(abs(deg) * 36000) # work in 0.1" to avoid 60.0" after rounding
|
|
54
|
+
d, rest = divmod(tenths, 36000)
|
|
55
|
+
m, s10 = divmod(rest, 600)
|
|
56
|
+
d = -d if signed and deg < 0 else d
|
|
57
|
+
return f"{d:3d} {m:2d} {s10 / 10:4.1f}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _epochs(adj: Adjustment) -> tuple[str, str, str]:
|
|
61
|
+
"""Start, end and mean solution epochs from the baselines (GPST -> UTC)."""
|
|
62
|
+
t = pd.Series([pd.Timestamp(b.epoch) for b in adj.baselines])
|
|
63
|
+
t = t - pd.Timedelta(seconds=GPST_UTC_OFFSET_S)
|
|
64
|
+
return _time(t.min()), _time(t.max()), _time(t.min() + (t.max() - t.min()) / 2)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _codes(adj: Adjustment, rename: Mapping[str, str] | None) -> dict[str, str]:
|
|
68
|
+
"""Point name -> 4-character SINEX site code, for unknown then fixed points."""
|
|
69
|
+
rename = rename or {}
|
|
70
|
+
codes = {p: rename.get(p, p) for p in [*adj.unknowns, *adj.fixed]}
|
|
71
|
+
bad = [c for c in codes.values() if len(c) > MAX_CODE_LEN or not c or " " in c]
|
|
72
|
+
if bad:
|
|
73
|
+
raise ValueError(
|
|
74
|
+
f"invalid SINEX site code(s) {bad}: max {MAX_CODE_LEN} characters, no spaces "
|
|
75
|
+
"(use `rename`)"
|
|
76
|
+
)
|
|
77
|
+
if len(set(codes.values())) < len(codes):
|
|
78
|
+
raise ValueError("duplicate SINEX site codes after renaming")
|
|
79
|
+
return codes
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def write_sinex(
|
|
83
|
+
adj: Adjustment,
|
|
84
|
+
path: Path | str,
|
|
85
|
+
*,
|
|
86
|
+
agency: str = "XXX",
|
|
87
|
+
description: str = "gnsskit static network adjustment",
|
|
88
|
+
contact: str | None = None,
|
|
89
|
+
rename: Mapping[str, str] | None = None,
|
|
90
|
+
created: datetime | None = None,
|
|
91
|
+
) -> Path:
|
|
92
|
+
"""Write the adjusted coordinates and their covariance matrix as a SINEX 2.02 file.
|
|
93
|
+
|
|
94
|
+
The parameters are STAX/STAY/STAZ of the adjusted points (constraint code 2) followed
|
|
95
|
+
by the held points (code 0, standard deviation 0, listed in SOLUTION/APRIORI). The
|
|
96
|
+
covariance of `adj` is the cofactor matrix already scaled by the a-posteriori variance
|
|
97
|
+
factor, so VARIANCE FACTOR is written as 1 and the factor itself goes in a comment.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
adj: Result of `adjust_network`.
|
|
101
|
+
path: Output file.
|
|
102
|
+
agency: 3-character agency code of the file creator and the data provider.
|
|
103
|
+
description: Text of the DESCRIPTION record (60 characters).
|
|
104
|
+
contact: Optional e-mail written in a CONTACT record.
|
|
105
|
+
rename: Point renaming {old: new}: SINEX site codes have at most 4 characters.
|
|
106
|
+
created: Creation time in UTC. Default: now.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
The written file.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ValueError: If a site code is longer than 4 characters or duplicated.
|
|
113
|
+
"""
|
|
114
|
+
if len(agency) != 3:
|
|
115
|
+
raise ValueError(f"agency must have 3 characters, not {agency!r}")
|
|
116
|
+
codes = _codes(adj, rename)
|
|
117
|
+
names = [*adj.unknowns, *adj.fixed]
|
|
118
|
+
xyz = np.vstack([adj.xyz, *adj.fixed.values()]) if adj.fixed else adj.xyz
|
|
119
|
+
n_unk, n_par = len(adj.unknowns), 3 * len(names)
|
|
120
|
+
cov = np.zeros((n_par, n_par))
|
|
121
|
+
cov[: 3 * n_unk, : 3 * n_unk] = adj.Cxx
|
|
122
|
+
sd = np.sqrt(np.diag(cov))
|
|
123
|
+
start, end, mean = _epochs(adj)
|
|
124
|
+
now = _time(created or datetime.now(timezone.utc))
|
|
125
|
+
p = 3 * n_unk # parameters adjusted; the rest is fixed
|
|
126
|
+
|
|
127
|
+
def code(name: str) -> str:
|
|
128
|
+
return f"{codes[name]:<4}"
|
|
129
|
+
|
|
130
|
+
lines = [
|
|
131
|
+
f"%=SNX {VERSION} {agency} {now} {agency} {start} {end} P {n_par:05d} 0 S",
|
|
132
|
+
f"* a-posteriori variance factor already applied to the covariance: {adj.sigma_v_hat:.4f}",
|
|
133
|
+
"+FILE/REFERENCE",
|
|
134
|
+
f" {'DESCRIPTION':<18} {description:<60.60}".rstrip(),
|
|
135
|
+
f" {'OUTPUT':<18} {'station coordinates and covariance (ECEF)':<60}".rstrip(),
|
|
136
|
+
*([f" {'CONTACT':<18} {contact:<60.60}".rstrip()] if contact else []),
|
|
137
|
+
f" {'SOFTWARE':<18} {'gnsskit ' + version('gnsskit'):<60}".rstrip(),
|
|
138
|
+
f" {'INPUT':<18} {f'{len(adj.baselines)} GNSS baselines':<60}".rstrip(),
|
|
139
|
+
"-FILE/REFERENCE",
|
|
140
|
+
"+SITE/ID",
|
|
141
|
+
"*CODE PT __DOMES__ T _STATION DESCRIPTION__ APPROX_LON_ APPROX_LAT_ _APP_H_",
|
|
142
|
+
]
|
|
143
|
+
lat, lon, h = ecef_to_llh(*xyz.T)
|
|
144
|
+
for i, name in enumerate(names):
|
|
145
|
+
lines.append(
|
|
146
|
+
f" {code(name)} A {UNDEF * 9} P {name:<22.22} {_dms(lon[i] % 360, False)}"
|
|
147
|
+
f" {_dms(lat[i], True)} {h[i]:7.1f}"
|
|
148
|
+
)
|
|
149
|
+
lines += [
|
|
150
|
+
"-SITE/ID",
|
|
151
|
+
"+SOLUTION/EPOCHS",
|
|
152
|
+
"*CODE PT SOLN T _DATA_START_ __DATA_END__ _MEAN_EPOCH_",
|
|
153
|
+
*(f" {code(n)} A 1 P {start} {end} {mean}" for n in names),
|
|
154
|
+
"-SOLUTION/EPOCHS",
|
|
155
|
+
"+SOLUTION/STATISTICS",
|
|
156
|
+
f" {'NUMBER OF OBSERVATIONS':<30} {float(adj.n):22.15f}",
|
|
157
|
+
f" {'NUMBER OF UNKNOWNS':<30} {float(adj.m):22.15f}",
|
|
158
|
+
f" {'NUMBER OF DEGREES OF FREEDOM':<30} {float(adj.dof):22.15f}",
|
|
159
|
+
f" {'SQUARE SUM OF RESIDUALS (VTPV)':<30} {adj.sigma_v_hat * adj.dof:22.15f}",
|
|
160
|
+
f" {'VARIANCE FACTOR':<30} {1.0:22.15f}",
|
|
161
|
+
"-SOLUTION/STATISTICS",
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
est, apr = [], []
|
|
165
|
+
for k in range(n_par):
|
|
166
|
+
i = k // 3
|
|
167
|
+
t = f"STA{'XYZ'[k % 3]}"
|
|
168
|
+
fixed = k >= p
|
|
169
|
+
row = (
|
|
170
|
+
f" {k + 1:5d} {t:<6} {code(names[i])} A 1 {mean} m {'0' if fixed else '2'}"
|
|
171
|
+
f" {_fortran_e(xyz[i, k % 3], 21, 15)} {_fortran_e(sd[k], 11, 6)}"
|
|
172
|
+
)
|
|
173
|
+
est.append(row)
|
|
174
|
+
if fixed:
|
|
175
|
+
apr.append(row) # same layout; the apriori value of a held point is its estimate
|
|
176
|
+
lines += ["+SOLUTION/ESTIMATE", *est, "-SOLUTION/ESTIMATE"]
|
|
177
|
+
if apr:
|
|
178
|
+
lines += ["+SOLUTION/APRIORI", *apr, "-SOLUTION/APRIORI"]
|
|
179
|
+
|
|
180
|
+
lines.append("+SOLUTION/MATRIX_ESTIMATE L COVA")
|
|
181
|
+
for r in range(n_par): # lower triangle, three elements per line
|
|
182
|
+
for c0 in range(0, r + 1, 3):
|
|
183
|
+
vals = cov[r, c0 : min(c0 + 3, r + 1)]
|
|
184
|
+
lines.append(
|
|
185
|
+
f" {r + 1:5d} {c0 + 1:5d}" + "".join(f" {_fortran_e(v, 21, 14)}" for v in vals)
|
|
186
|
+
)
|
|
187
|
+
lines += ["-SOLUTION/MATRIX_ESTIMATE L COVA", "%ENDSNX"]
|
|
188
|
+
|
|
189
|
+
out = Path(path)
|
|
190
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
out.write_text("\n".join(lines) + "\n", newline="")
|
|
192
|
+
return out
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Export of static baselines to a StarNet GPS vector file (``NAME.gps``).
|
|
2
|
+
|
|
3
|
+
StarNet (MicroSurvey) reads it as its GPS vector input ("GPS Vector Data"); MOVE3 imports it
|
|
4
|
+
too (Import/export > Import GNSS/GPS file, Manufacturer Other, StarNet). Pure stdlib + numpy.
|
|
5
|
+
|
|
6
|
+
from gnsskit import write_starnet
|
|
7
|
+
write_starnet("baselines.csv", "out/", "MY", rename={"mil": "MIL3"})
|
|
8
|
+
|
|
9
|
+
Command line: ``gnsskit-starnet baselines.csv --outdir out``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
from collections.abc import Mapping, Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from ..static.baseline import BaselineResult
|
|
19
|
+
from ._common import CRLF, prepare_baselines
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def write_starnet(
|
|
23
|
+
baselines: Sequence[BaselineResult] | Path | str,
|
|
24
|
+
outdir: Path | str,
|
|
25
|
+
project: str = "project",
|
|
26
|
+
*,
|
|
27
|
+
m0: float = 10.0,
|
|
28
|
+
rename: Mapping[str, str] | None = None,
|
|
29
|
+
) -> Path:
|
|
30
|
+
"""Write a StarNet NAME.gps file, also importable in MOVE3 (Import/export > GNSS/GPS).
|
|
31
|
+
|
|
32
|
+
G0 label, G1 from-to dXYZ, G2 variances, G3 covariances. The format has no M0 field, so
|
|
33
|
+
covariances are scaled by `m0`**2. No station coordinates: enter them in MOVE3 afterwards.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The written file.
|
|
37
|
+
"""
|
|
38
|
+
bls = prepare_baselines(baselines, rename)
|
|
39
|
+
out = Path(outdir)
|
|
40
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
lines = [".GPS WEIGHT COVARIANCE"]
|
|
42
|
+
for b in bls:
|
|
43
|
+
c = b.cov * m0**2
|
|
44
|
+
lines += [
|
|
45
|
+
"G0 '" + f"{project} {b.session} {b.base}-{b.rover}".replace(" ", " "),
|
|
46
|
+
f"G1 {b.base}-{b.rover} " + " ".join(f"{v:.4f}" for v in b.dxyz),
|
|
47
|
+
f"G2 {c[0, 0]:.6E} {c[1, 1]:.6E} {c[2, 2]:.6E}",
|
|
48
|
+
f"G3 {c[0, 1]:.6E} {c[0, 2]:.6E} {c[1, 2]:.6E}",
|
|
49
|
+
]
|
|
50
|
+
path = out / f"{project}.gps"
|
|
51
|
+
path.write_text(CRLF.join(lines) + CRLF, newline="")
|
|
52
|
+
return path
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
56
|
+
"""Command line: `gnsskit-starnet baselines.csv ...`."""
|
|
57
|
+
ap = argparse.ArgumentParser(description="Export RTKLIB baselines to a StarNet .gps file.")
|
|
58
|
+
ap.add_argument("csv", type=Path, help="baselines CSV written by write_baselines")
|
|
59
|
+
ap.add_argument("--outdir", type=Path, default=Path("."), help="output folder")
|
|
60
|
+
ap.add_argument("--project", default="project", metavar="NAME", help="name of NAME.gps")
|
|
61
|
+
ap.add_argument(
|
|
62
|
+
"--m0", type=float, default=10.0,
|
|
63
|
+
help="multiplication factor of the baseline standard deviations (default: %(default)s)",
|
|
64
|
+
) # fmt: skip
|
|
65
|
+
ap.add_argument("--rename", nargs="*", default=[], metavar="OLD=NEW", help="e.g. mil=MIL3")
|
|
66
|
+
a = ap.parse_args(argv)
|
|
67
|
+
if any("=" not in r for r in a.rename):
|
|
68
|
+
ap.error("--rename expects OLD=NEW pairs, e.g. --rename mil=MIL3")
|
|
69
|
+
rename = dict(r.split("=", 1) for r in a.rename)
|
|
70
|
+
print(f"wrote {write_starnet(a.csv, a.outdir, a.project, m0=a.m0, rename=rename)}")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|