-
Notifications
You must be signed in to change notification settings - Fork 4
/
parsers.py
217 lines (186 loc) · 6.85 KB
/
parsers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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
139
140
141
142
143
144
145
146
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import re
from enum import Enum
from defusedxml.ElementTree import parse
Section = Enum("Section", ["HEADER", "META", "DATA", "COVARIANCE"])
HS = r"(?:[ \t]|$)+"
"""Arbitrary Horizontal spacing or EOL"""
KEY_VAL = f"([A-Z_]+){HS}={HS}(.+)"
"""Key-value pair"""
COV_XML_KEYS = (
"CX_X",
"CY_X",
"CY_Y",
"CZ_X",
"CZ_Y",
"CZ_Z",
"CX_DOT_X",
"CX_DOT_Y",
"CX_DOT_Z",
"CX_DOT_X_DOT",
"CY_DOT_X",
"CY_DOT_Y",
"CY_DOT_Z",
"CY_DOT_X_DOT",
"CY_DOT_Y_DOT",
"CZ_DOT_X",
"CZ_DOT_Y",
"CZ_DOT_Z",
"CZ_DOT_X_DOT",
"CZ_DOT_Y_DOT",
"CZ_DOT_Z_DOT",
)
def err(line_number, message):
raise ValueError(f"Error on line {line_number + 2}: {message}")
def parse_kvn_oem(ephem_file):
section = Section.HEADER
header, segments = {}, []
covdata = None
data_length = None
match = re.match(KEY_VAL, ephem_file.readline())
if match:
header[match.group(1)] = match.group(2)
if "CCSDS_OEM_VERS" not in header:
err(line_number=0, message='OEM file must start with "CCSDS_OEM_VERS" keyword.')
for idx, line in enumerate(ephem_file):
line = line.strip()
if line == "" or line.startswith("COMMENT"):
continue # TODO: Preserve comments
elif section == Section.DATA:
if line == "META_START":
section = Section.META
segments.append({"header": {}, "data": [], "cov": []})
continue
elif line == "COVARIANCE_START":
section = Section.COVARIANCE
continue
date, *values = line.split()
if data_length is None:
data_length = len(values)
if data_length not in (6, 9):
err(idx, "Malformed data entry")
elif len(values) != data_length:
err(idx, "Data contains mix of data lengths.")
try:
values = tuple(float(entry) for entry in values)
except Exception:
err(idx, "Malformed data entry")
segments[-1]["data"].append((date, *values))
elif section == Section.COVARIANCE:
if line == "COVARIANCE_STOP":
covdata = None
continue
elif line == "META_START":
section = Section.META
segments.append({"header": {}, "data": [], "cov": []})
continue
if not covdata:
covdata = {
"frame": segments[-1]["header"]["REF_FRAME"],
"data": (),
}
in_header = True
if "=" in line:
if not in_header:
err(idx, "Malformed covariance")
match = re.match(KEY_VAL, line)
if match:
# TODO: Prevent repeats
if match.group(1) == "EPOCH":
covdata["epoch"] = match.group(2)
elif match.group(1) == "COV_REF_FRAME":
covdata["frame"] = match.group(2)
else:
err(idx, "Invalid covariance header")
else:
err(idx, "Invalid covariance header")
else:
if in_header:
in_header = False
cov_data_line = 1
covdata["data"] = covdata["data"] + (float(line),)
else:
cov_data_line += 1
raw_values = line.split()
if len(raw_values) != cov_data_line:
err(idx, "Malformed covariance shape")
covdata["data"] = covdata["data"] + tuple(
float(entry) for entry in raw_values
)
if cov_data_line == 6:
segments[-1]["cov"].append(
(
covdata["epoch"],
covdata["frame"],
*covdata["data"],
)
)
covdata = None
elif section == Section.HEADER:
if line == "META_START":
section = Section.META
segments.append({"header": {}, "data": [], "cov": []})
continue
match = re.match(KEY_VAL, line)
if match:
if match.group(1) in header:
err(idx, f"Duplicate header: {match.group(1)}")
header[match.group(1)] = match.group(2)
else:
err(idx, "Invalid header entry")
elif section == Section.META:
if line == "META_STOP":
section = Section.DATA
data_length = None
continue
match = re.match(KEY_VAL, line)
if match:
if match.group(1) in header:
err(idx, f"Duplicate entry: {match.group(1)}")
segments[-1]["header"][match.group(1)] = match.group(2)
else:
err(idx, "Invalid meta entry")
return header, segments
def parse_xml_oem(ephem_file):
parts = parse(ephem_file).getroot()
header = {
entry.tag.rpartition("}")[-1]: entry.text
for entry in parts[0]
if entry.tag.rpartition("}")[-1] != "COMMENT"
}
header["CCSDS_OEM_VERS"] = parts.attrib["version"]
segments = []
for raw_segment in parts[1]:
raw_metadata, raw_data = raw_segment
segment = {}
segment["header"] = {
entry.tag.rpartition("}")[-1]: entry.text
for entry in raw_metadata
if entry.tag.rpartition("}")[-1] != "COMMENT"
}
keys = ("X", "Y", "Z", "X_DOT", "Y_DOT", "Z_DOT")
try:
if raw_data.find("stateVector").find("X_DDOT") is not None:
keys = keys + ("X_DDOT", "Y_DDOT", "Z_DDOT")
segment["data"] = tuple(
(entry.find("EPOCH").text,)
+ tuple(float(entry.find(key).text) for key in keys)
for entry in raw_data
if entry.tag.rpartition("}")[-1] == "stateVector"
)
except Exception:
raise ValueError("Malformed data section")
ref_frame = raw_metadata.find("REF_FRAME")
try:
segment["cov"] = tuple(
(
entry.find("EPOCH").text,
(entry.find("COV_REF_FRAME") or ref_frame).text,
*(float(entry.find(key).text) for key in COV_XML_KEYS),
)
for entry in raw_data
if entry.tag.rpartition("}")[-1] == "covarianceMatrix"
)
except Exception:
raise ValueError("Malformed covariance section")
segments.append(segment)
return header, segments