compass-lib 0.0.8__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,291 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Formatting (serialization) for Compass .DAT survey files.
3
+
4
+ This module provides functions to convert survey data models back to
5
+ the Compass .DAT file format string representation.
6
+
7
+ All data is written in Compass's fixed internal units (feet, degrees)
8
+ and fixed column order. The FORMAT string is purely display metadata
9
+ for the Compass editor and is stored/output as a raw string.
10
+ """
11
+
12
+ from collections.abc import Callable
13
+
14
+ from compass_lib.constants import FLAG_CHARS
15
+ from compass_lib.constants import MISSING_VALUE_STRING
16
+ from compass_lib.constants import NUMBER_WIDTH
17
+ from compass_lib.constants import STATION_NAME_WIDTH
18
+ from compass_lib.survey.models import CompassShot
19
+ from compass_lib.survey.models import CompassSurvey
20
+ from compass_lib.survey.models import CompassSurveyHeader
21
+ from compass_lib.validation import validate_station_name
22
+
23
+ # Default FORMAT strings used when no format_string is stored on the header.
24
+ # These use degrees for all angles, decimal feet for lengths, standard LRUD
25
+ # order (LUDR), and standard shot order (LAD).
26
+ _DEFAULT_FORMAT_WITH_BACKSIGHTS = "DDDDLUDRLADadBF"
27
+ _DEFAULT_FORMAT_WITHOUT_BACKSIGHTS = "DDDDLUDRLAD"
28
+
29
+
30
+ def _cell(value: str, width: int) -> str:
31
+ """Format a value as a right-aligned cell.
32
+
33
+ Args:
34
+ value: String value
35
+ width: Minimum width (actual width may be larger if value is longer)
36
+
37
+ Returns:
38
+ Right-aligned, space-padded string (never truncated to preserve data)
39
+ """
40
+ # Never truncate - the parser is whitespace-delimited so longer values work fine
41
+ # Always ensure at least one leading space to separate from previous column
42
+ if len(value) >= width:
43
+ return " " + value
44
+ return value.rjust(width)
45
+
46
+
47
+ def _format_number(value: float | None, width: int = NUMBER_WIDTH) -> str:
48
+ """Format a number for output.
49
+
50
+ Args:
51
+ value: Numeric value (None for missing)
52
+ width: Column width
53
+
54
+ Returns:
55
+ Formatted string representation
56
+ """
57
+ if value is None:
58
+ return _cell(MISSING_VALUE_STRING, width)
59
+ # Check if value has more than 2 decimal places of precision
60
+ # by comparing rounded vs original
61
+ rounded_2 = round(value, 2)
62
+ if abs(value - rounded_2) > 1e-9:
63
+ # Value has more precision, use 3 decimal places
64
+ return _cell(f"{value:.3f}", width)
65
+ return _cell(f"{value:.2f}", width)
66
+
67
+
68
+ def format_shot(shot: CompassShot, header: CompassSurveyHeader) -> str:
69
+ """Format a single shot as a line of text.
70
+
71
+ All values are output in Compass's fixed internal units (feet, degrees)
72
+ in fixed column order:
73
+ FROM TO LENGTH AZIMUTH INCLINATION LEFT UP DOWN RIGHT [BS_AZ BS_INC] [FLAGS] [COMMENT]
74
+
75
+ Args:
76
+ shot: Shot data
77
+ header: Survey header (for has_backsights flag)
78
+
79
+ Returns:
80
+ Formatted shot line with CRLF
81
+ """ # noqa: E501
82
+ # Validate station names
83
+ validate_station_name(shot.from_station_name)
84
+ validate_station_name(shot.to_station_name)
85
+
86
+ columns = [
87
+ _cell(shot.from_station_name, STATION_NAME_WIDTH),
88
+ _cell(shot.to_station_name, STATION_NAME_WIDTH),
89
+ ]
90
+
91
+ # Shot measurements in FIXED order: LENGTH, AZIMUTH, INCLINATION
92
+ columns.append(_format_number(shot.length))
93
+ columns.append(_format_number(shot.frontsight_azimuth))
94
+ columns.append(_format_number(shot.frontsight_inclination))
95
+
96
+ # LRUD values in FIXED order: LEFT, UP, DOWN, RIGHT
97
+ columns.append(_format_number(shot.left))
98
+ columns.append(_format_number(shot.up))
99
+ columns.append(_format_number(shot.down))
100
+ columns.append(_format_number(shot.right))
101
+
102
+ # Add backsights if present (always after LRUD, before flags)
103
+ if header.has_backsights:
104
+ columns.append(_format_number(shot.backsight_azimuth))
105
+ columns.append(_format_number(shot.backsight_inclination))
106
+
107
+ # Build flags
108
+ flags = ""
109
+ if shot.excluded_from_length:
110
+ flags += FLAG_CHARS["exclude_distance"]
111
+ if shot.excluded_from_plotting:
112
+ flags += FLAG_CHARS["exclude_from_plotting"]
113
+ if shot.excluded_from_all_processing:
114
+ flags += FLAG_CHARS["exclude_from_all_processing"]
115
+ if shot.do_not_adjust:
116
+ flags += FLAG_CHARS["do_not_adjust"]
117
+
118
+ if flags:
119
+ columns.append(f" #|{flags}#")
120
+
121
+ # Add comment
122
+ if shot.comment:
123
+ # Clean comment: replace newlines with space (no truncation to preserve data)
124
+ clean_comment = shot.comment.replace("\r\n", " ").replace("\n", " ")
125
+ clean_comment = clean_comment.strip()
126
+ columns.append(" " + clean_comment)
127
+
128
+ columns.append("\r\n")
129
+ return "".join(columns)
130
+
131
+
132
+ def format_survey_header(
133
+ header: CompassSurveyHeader,
134
+ *,
135
+ include_column_headers: bool = True,
136
+ ) -> str:
137
+ """Format a survey header as text.
138
+
139
+ Args:
140
+ header: Survey header data
141
+ include_column_headers: Whether to include column header line
142
+
143
+ Returns:
144
+ Formatted header text with CRLF
145
+ """
146
+ lines = []
147
+
148
+ # Cave name (no truncation to preserve data)
149
+ lines.append(header.cave_name or "")
150
+
151
+ # Survey name (preserve full name for round-trip, Compass may use longer names)
152
+ survey_name = header.survey_name or ""
153
+ lines.append(f"SURVEY NAME: {survey_name}")
154
+
155
+ # Survey date and comment
156
+ if header.date:
157
+ date_str = f"{header.date.month} {header.date.day} {header.date.year}"
158
+ else:
159
+ date_str = "1 1 1"
160
+
161
+ date_line = f"SURVEY DATE: {date_str}"
162
+ if header.comment:
163
+ date_line += f" COMMENT:{header.comment}"
164
+ lines.append(date_line)
165
+
166
+ # Team (no truncation to preserve data)
167
+ lines.append("SURVEY TEAM:")
168
+ lines.append(header.team or "")
169
+
170
+ # FORMAT string -- use stored value or generate a sensible default
171
+ if header.format_string:
172
+ format_str = header.format_string
173
+ elif header.has_backsights:
174
+ format_str = _DEFAULT_FORMAT_WITH_BACKSIGHTS
175
+ else:
176
+ format_str = _DEFAULT_FORMAT_WITHOUT_BACKSIGHTS
177
+
178
+ declination = header.declination
179
+ decl_line = f"DECLINATION: {declination:.2f} FORMAT: {format_str}"
180
+
181
+ # Corrections
182
+ has_corrections = any(
183
+ [
184
+ header.length_correction,
185
+ header.frontsight_azimuth_correction,
186
+ header.frontsight_inclination_correction,
187
+ ]
188
+ )
189
+
190
+ if has_corrections:
191
+ corr_values = [
192
+ header.length_correction or 0.0,
193
+ header.frontsight_azimuth_correction or 0.0,
194
+ header.frontsight_inclination_correction or 0.0,
195
+ ]
196
+ corr_str = " ".join(f"{v:.2f}" for v in corr_values)
197
+ decl_line += f" CORRECTIONS: {corr_str}"
198
+
199
+ # Backsight corrections
200
+ has_bs_corrections = any(
201
+ [
202
+ header.backsight_azimuth_correction,
203
+ header.backsight_inclination_correction,
204
+ ]
205
+ )
206
+ if has_bs_corrections:
207
+ bs_values = [
208
+ header.backsight_azimuth_correction or 0.0,
209
+ header.backsight_inclination_correction or 0.0,
210
+ ]
211
+ bs_str = " ".join(f"{v:.2f}" for v in bs_values)
212
+ decl_line += f" CORRECTIONS2: {bs_str}"
213
+
214
+ lines.append(decl_line)
215
+
216
+ # Column headers
217
+ if include_column_headers:
218
+ lines.append("") # Blank line
219
+
220
+ col_headers = [
221
+ "FROM ",
222
+ "TO ",
223
+ "LEN ",
224
+ "BEAR ",
225
+ "INC ",
226
+ "LEFT ",
227
+ "UP ",
228
+ "DOWN ",
229
+ "RIGHT ",
230
+ ]
231
+ if header.has_backsights:
232
+ col_headers.append("AZM2 ")
233
+ col_headers.append("INC2 ")
234
+ col_headers.append("FLAGS ")
235
+ col_headers.append("COMMENTS")
236
+
237
+ lines.append("".join(col_headers))
238
+ lines.append("") # Blank line before data
239
+
240
+ # Join with CRLF
241
+ return "\r\n".join(lines) + "\r\n"
242
+
243
+
244
+ def format_survey(survey: CompassSurvey, *, include_column_headers: bool = True) -> str:
245
+ """Format a complete survey (header + shots).
246
+
247
+ Args:
248
+ survey: Survey data
249
+ include_column_headers: Whether to include column headers
250
+
251
+ Returns:
252
+ Formatted survey text
253
+ """
254
+ parts = [
255
+ format_survey_header(
256
+ survey.header, include_column_headers=include_column_headers
257
+ )
258
+ ]
259
+
260
+ parts.extend(format_shot(shot, survey.header) for shot in survey.shots)
261
+
262
+ return "".join(parts)
263
+
264
+
265
+ def format_dat_file(
266
+ surveys: list[CompassSurvey],
267
+ *,
268
+ write: Callable[[str], None] | None = None,
269
+ ) -> str | None:
270
+ """Format a complete DAT file from surveys.
271
+
272
+ Args:
273
+ surveys: List of surveys
274
+ write: Optional callback for streaming output. If provided,
275
+ chunks are written via this callback and None is returned.
276
+
277
+ Returns:
278
+ Formatted file content as string (if write is None),
279
+ or None (if write callback is provided)
280
+ """
281
+ if write is not None:
282
+ # Streaming mode
283
+ for survey in surveys:
284
+ write(format_survey(survey))
285
+ write("\f\r\n")
286
+ return None
287
+
288
+ # Return mode
289
+ chunks: list[str] = []
290
+ format_dat_file(surveys, write=chunks.append)
291
+ return "".join(chunks)
@@ -0,0 +1,126 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Survey data models for Compass .DAT files.
3
+
4
+ This module contains Pydantic models for representing survey data:
5
+ - CompassShot: A single shot between two stations
6
+ - CompassSurveyHeader: Metadata and settings for a survey
7
+ - CompassSurvey: A complete survey with header and shots
8
+ - CompassDatFile: A DAT file containing one or more surveys
9
+
10
+ All measurements are stored in Compass's fixed internal units:
11
+ - Length/LRUD: decimal feet
12
+ - Bearing/Inclination/Backsights: degrees
13
+
14
+ The FORMAT string from the DAT file is purely display metadata for the
15
+ Compass editor and is stored as a raw string on the header.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import datetime # noqa: TC003
21
+
22
+ from pydantic import BaseModel
23
+ from pydantic import ConfigDict
24
+ from pydantic import Field
25
+ from pydantic import field_serializer
26
+
27
+
28
+ class CompassShot(BaseModel):
29
+ """A single survey shot between two stations.
30
+
31
+ All measurements are stored in internal units (feet, degrees).
32
+ """
33
+
34
+ model_config = ConfigDict(
35
+ populate_by_name=True,
36
+ extra="ignore",
37
+ )
38
+
39
+ from_station_name: str = Field(alias="from_station")
40
+ to_station_name: str = Field(alias="to_station")
41
+ length: float | None = Field(default=None, alias="distance")
42
+ frontsight_azimuth: float | None = None
43
+ frontsight_inclination: float | None = None
44
+ backsight_azimuth: float | None = None
45
+ backsight_inclination: float | None = None
46
+ left: float | None = None
47
+ right: float | None = None
48
+ up: float | None = None
49
+ down: float | None = None
50
+ comment: str | None = None
51
+ excluded_from_length: bool = Field(default=False, alias="exclude_distance")
52
+ excluded_from_plotting: bool = False
53
+ excluded_from_all_processing: bool = False
54
+ do_not_adjust: bool = False
55
+
56
+ # NOTE: Validation is relaxed to allow real-world data with out-of-range values.
57
+ # The parser tracks these issues in its errors list.
58
+ # Strict validation can be performed separately if needed.
59
+
60
+
61
+ class CompassSurveyHeader(BaseModel):
62
+ """Metadata and settings for a survey.
63
+
64
+ The FORMAT string is stored as a raw string (``format_string``).
65
+ It is purely display metadata for the Compass editor -- it does NOT
66
+ affect how shot data is parsed or stored. All data in a .DAT file
67
+ uses fixed internal units (feet, degrees) and fixed column order.
68
+
69
+ The only structural information extracted from the FORMAT string is
70
+ ``has_backsights``, which determines whether backsight columns are
71
+ present in the shot data.
72
+ """
73
+
74
+ model_config = ConfigDict(populate_by_name=True)
75
+
76
+ cave_name: str | None = None
77
+ survey_name: str | None = None
78
+ date: datetime.date | None = None
79
+ comment: str | None = None
80
+ team: str | None = None
81
+ declination: float = 0.0
82
+ format_string: str | None = None
83
+ has_backsights: bool = True
84
+ length_correction: float = 0.0
85
+ frontsight_azimuth_correction: float = 0.0
86
+ frontsight_inclination_correction: float = 0.0
87
+ backsight_azimuth_correction: float = 0.0
88
+ backsight_inclination_correction: float = 0.0
89
+
90
+ @field_serializer("comment", "team")
91
+ @classmethod
92
+ def serialize_empty_as_none(cls, v: str | None) -> str | None:
93
+ return None if v == "" else v
94
+
95
+
96
+ class CompassSurvey(BaseModel):
97
+ """A complete survey with header and shots."""
98
+
99
+ model_config = ConfigDict(populate_by_name=True)
100
+
101
+ header: CompassSurveyHeader
102
+ shots: list[CompassShot] = Field(default_factory=list)
103
+
104
+
105
+ class CompassDatFile(BaseModel):
106
+ """A Compass .DAT file containing one or more surveys."""
107
+
108
+ model_config = ConfigDict(populate_by_name=True)
109
+
110
+ surveys: list[CompassSurvey] = Field(default_factory=list)
111
+
112
+ @property
113
+ def total_shots(self) -> int:
114
+ return sum(len(survey.shots) for survey in self.surveys)
115
+
116
+ @property
117
+ def survey_names(self) -> list[str]:
118
+ return [survey.header.survey_name or "<unnamed>" for survey in self.surveys]
119
+
120
+ def get_all_stations(self) -> set[str]:
121
+ stations: set[str] = set()
122
+ for survey in self.surveys:
123
+ for shot in survey.shots:
124
+ stations.add(shot.from_station_name)
125
+ stations.add(shot.to_station_name)
126
+ return stations