-
Notifications
You must be signed in to change notification settings - Fork 4
/
topreader.py
executable file
·1335 lines (1037 loc) · 39 KB
/
topreader.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# PocketTopo file parser and converter
#
# Based on Andrew Atkinson's "TopParser"
#
# Copyright (C) 2018-2021 Thomas Holder
# Copyright (C) 2011-2012 Andrew Atkinson ("TopParser")
#
# --------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# --------------------------------------------------------------------
import io
import os
import re
import sys
import struct
import time
import calendar
import collections
import math
from html import escape
from lxml import etree
from typing import (
Any,
BinaryIO,
Callable,
Dict,
Iterable,
List,
Tuple,
)
EtreeElement = etree._Element
ShotDict = Dict[str, Any]
TopDict = Dict[str, Any]
CLARK_INKSCAPE_LABEL = "{http://www.inkscape.org/namespaces/inkscape}label"
CLARK_INKSCAPE_GROUPMODE = "{http://www.inkscape.org/namespaces/inkscape}groupmode"
COLOURS = (
'black',
'gray',
'brown',
'blue',
'red',
'green',
'orange',
)
KEY_TAPE = 'tape'
KEY_COLOR = 'colour'
KEY_DECLINATION = 'dec'
KEY_X = 0
KEY_Y = 1
KEY_EXTEND = 'direction'
KEY_XSEC_POS = "position"
KEY_XSEC_DIR = "compass"
KEY_XSEC_STN = "station"
KEY_REF_STN = 0
KEY_REF_X = 1
KEY_REF_Y = 2
KEY_REF_Z = 3
KEY_REF_COMMENT = 4
EXTEND_LEFT = "<"
EXTEND_RIGHT = ">"
def removesuffix(s: str, suffix: str) -> str:
'''Drop-in for Python 3.10's str.removesuffix
'''
assert isinstance(s, str)
return s[:-len(suffix)] if (s.endswith(suffix) and suffix) else s
def distmm(mm: int) -> float:
'''convert millimeters to meters'''
assert isinstance(mm, int)
return mm / 1000.0
def distmm_inv(m: float) -> int:
'''convert meters to millimeters'''
return round(m * 1000)
def adegrees(angle: int, divisor=0xFFFF) -> float:
'''convert angle from internal units to degrees'''
return float(angle) / divisor * 360.0
def adegrees_inv(degrees: float, divisor=0xFFFF) -> int:
'''convert angle from degrees to internal units'''
return round((degrees * divisor) / 360.0)
def posdeg(deg: float) -> float:
'''positive angle
:param deg: angle in degrees
:return: angle in [0, 360)'''
return deg % 360
def avgdeg(deg: List[float]) -> float:
'''average angle
:param deg: list of angles in degrees
:return: mean angle in [-180, 180]
'''
N = len(deg)
if N == 0:
return 0.0
mss = sum(math.sin(math.radians(a)) for a in deg) / N
msc = sum(math.cos(math.radians(a)) for a in deg) / N
return math.degrees(math.atan2(mss, msc))
def reverse_shot(s: ShotDict) -> ShotDict:
return s | {
'from': s['to'],
'to': s['from'],
'compass': s['compass'] + 180.0,
'clino': -s['clino'],
KEY_TAPE: s[KEY_TAPE],
}
def average_shots(shots: Iterable[ShotDict], ignore_splays=True):
'''Average duplicate legs and return a new set of legs. Ignores splay shots.
'''
duplicates: Dict[Tuple[str, str], List[ShotDict]] = collections.defaultdict(list)
order = []
for s in shots:
if not s['to']:
if not ignore_splays:
order.append((s, None))
continue
if (s['to'], s['from']) in duplicates:
s = reverse_shot(s)
key = (s['from'], s['to'])
dups = duplicates[key]
if not dups:
order.append(key)
dups.append(s)
for key in order:
if key[1] is None:
yield key[0]
continue
dups = duplicates[key]
yield {
'from': key[0],
'to': key[1],
'compass': posdeg(avgdeg([s['compass'] for s in dups])),
'clino': sum(s['clino'] for s in dups) / len(dups),
KEY_TAPE: sum(s[KEY_TAPE] for s in dups) / len(dups),
# copy from first
'trip': dups[0]['trip'],
'comment': dups[0].get('comment', ''),
KEY_EXTEND: dups[0][KEY_EXTEND],
}
def get_true_bearing(shot: ShotDict, top: TopDict) -> float:
"""Get the direction relative to geographic "true" north which is corrected
by magnetic declination.
"""
tripidx = shot["trip"]
if tripidx != -1:
decl = top["trips"][tripidx][KEY_DECLINATION]
else:
decl = 0
return shot["compass"] + decl
def is_consecutive_number(from_: str, to: str) -> bool:
"""Return true if both stations have the same survey prefix and are
consecutively numbered.
"""
p_from = from_.rpartition(".")
p_to = to.rpartition(".")
return p_from[0] == p_to[0] and abs(int(p_from[2]) - int(p_to[2])) == 1
def _make_Point(x: int, y: int) -> Tuple[float, float]:
return distmm(x), distmm(y)
def _make_Point_inv(x: float, y: float) -> Tuple[int, int]:
return distmm_inv(x), distmm_inv(y)
# Need to convert this date from .NET
NANOSEC = 10000000
# Number of python tick since 1/1/1 00:00
PTICKS = 62135596800
def _read_date(F: BinaryIO) -> time.struct_time:
ticks = struct.unpack('<Q', F.read(8))
tripdate = time.gmtime((ticks[0] / NANOSEC) - PTICKS)
return tripdate
def _write_date(tripdate: time.struct_time) -> Iterable[bytes]:
ticks = round((calendar.timegm(tripdate) + PTICKS) * NANOSEC)
yield struct.pack('<Q', ticks)
def _read_comments(F: BinaryIO) -> str:
commentlength = struct.unpack('<B', F.read(1))[0]
if commentlength >= 0x80:
commentlength2 = struct.unpack('<B', F.read(1))[0]
if commentlength2 >= 0x80:
raise NotImplementedError('comment is rediculously long')
commentlength += 0x80 * (commentlength2 - 1)
C = F.read(commentlength)
return C.decode('utf-8')
def _write_comment(comment: str) -> Iterable[bytes]:
bc = comment.encode("utf-8")
commentlength = len(bc)
if commentlength >= 0x80:
commentlength2 = commentlength // 0x80
commentlength -= 0x80 * (commentlength2 - 1)
assert commentlength2 < 0x100
yield struct.pack('<BB', commentlength, commentlength2)
else:
yield struct.pack('<B', commentlength)
yield bc
def _read_trip(F: BinaryIO):
# First 8 (int64) is the date in ticks
tdate = _read_date(F)
comment = _read_comments(F)
declination = struct.unpack('<H', F.read(2))[0]
return {
'date': tdate,
'comment': comment,
KEY_DECLINATION: adegrees(declination),
}
def _write_trip(trip) -> Iterable[bytes]:
yield from _write_date(trip["date"])
yield from _write_comment(trip["comment"])
yield struct.pack('<H', adegrees_inv(trip[KEY_DECLINATION]))
def _read_shot(F: BinaryIO):
shot: Dict[str, Any] = {'from': _read_station(F)}
shot['to'] = _read_station(F)
Dist = struct.unpack('<L', F.read(4))
shot[KEY_TAPE] = distmm(Dist[0])
azimuth = struct.unpack('<H', F.read(2))
shot['compass'] = adegrees(azimuth[0])
inclination = struct.unpack('<h', F.read(2))
shot['clino'] = adegrees(inclination[0])
flags = struct.unpack('<B', F.read(1))
rawroll = struct.unpack('<B', F.read(1))
shot['rollangle'] = adegrees(rawroll[0], 0xFF)
tripindex = struct.unpack('<h', F.read(2))
shot['trip'] = tripindex[0]
# bit 1 of flags is flip (left or right)
if flags[0] & 0b00000001:
shot[KEY_EXTEND] = EXTEND_LEFT
else:
shot[KEY_EXTEND] = EXTEND_RIGHT
# bit 2 of flags indicates a comment
if flags[0] & 0b00000010:
shot['comment'] = _read_comments(F)
return shot
def _write_shot(shot: dict) -> Iterable[bytes]:
yield from _write_station(shot["from"])
yield from _write_station(shot["to"])
Dist = distmm_inv(shot[KEY_TAPE])
yield struct.pack('<L', Dist)
azimuth = adegrees_inv(shot['compass'])
yield struct.pack('<H', azimuth)
inclination = adegrees_inv(shot['clino'])
yield struct.pack('<h', inclination)
flags = 0
if shot.get(KEY_EXTEND, EXTEND_RIGHT) == EXTEND_LEFT:
flags |= 0b00000001
comment = shot.get('comment', '')
if comment:
flags |= 0b00000010
yield struct.pack('<B', flags)
rawroll = adegrees_inv(shot['rollangle'], 0xFF)
yield struct.pack('<B', rawroll)
tripindex = shot['trip']
yield struct.pack('<h', tripindex)
if comment:
yield from _write_comment(comment)
def _read_reference(F: BinaryIO) -> list:
stnid = _read_station(F)
east, west, altitude = struct.unpack('<QQL', F.read(20))
comment = _read_comments(F)
return [
stnid,
distmm(east),
distmm(west),
distmm(altitude),
comment,
]
def _write_reference(ref: list) -> Iterable[bytes]:
yield from _write_station(ref[KEY_REF_STN])
yield struct.pack(
'<QQL',
distmm_inv(ref[KEY_REF_X]),
distmm_inv(ref[KEY_REF_Y]),
distmm_inv(ref[KEY_REF_Z]),
)
yield from _write_comment(ref[KEY_REF_COMMENT])
def _read_Point(F: BinaryIO):
x, y = struct.unpack('<ll', F.read(8))
return _make_Point(x, y)
def _write_Point(point: Tuple[float, float]) -> Iterable[bytes]:
yield struct.pack('<ll', *_make_Point_inv(*point))
def _read_Polygon(F: BinaryIO):
numpoints = struct.unpack('<L', F.read(4))[0]
poly = [_read_Point(F) for _ in range(numpoints)]
colour = struct.unpack('<B', F.read(1))[0]
return {
KEY_COLOR: COLOURS[colour - 1],
'coord': poly,
}
def _write_Polygon(poly: dict) -> Iterable[bytes]:
yield struct.pack('<L', len(poly["coord"]))
for point in poly["coord"]:
yield from _write_Point(point)
yield struct.pack('<B', COLOURS.index(poly[KEY_COLOR]) + 1)
def _read_station(F: BinaryIO) -> str:
# id's split into major.decimal(minor)
idd, idm = struct.unpack('<HH', F.read(4))
if idd == 0xffff:
# TODO Observed (0xffff, 0x800f), what does this mean?
print('unknown idd=0x{:04x} idm=0x{:04x}'.format(idd, idm),
file=sys.stderr)
return ""
if idm != 0x8000:
return str(idm) + "." + str(idd)
if idd != 0:
return str(idd - 1)
return ""
def _write_station(shot: str) -> Iterable[bytes]:
idm, dot, idd = shot.rpartition(".")
if dot:
iidd, iidm = int(idd), int(idm)
elif shot:
iidd, iidm = int(idd) + 1, 0x8000
else:
assert not (idd or idm)
iidd, iidm = 0, 0x8000
yield struct.pack('<HH', iidd, iidm)
def _read_xsection(F: BinaryIO) -> dict:
pnt = _read_Point(F)
stn = _read_station(F)
# Need to look up the coordinate of the station
direction = struct.unpack('<l', F.read(4))[0]
# -1: horizontal, >=0; projection azimuth (internal angle units)
if direction != -1:
direction = adegrees(direction)
return {
KEY_XSEC_POS: pnt,
KEY_XSEC_STN: stn,
KEY_XSEC_DIR: direction,
}
def _write_xsection(xsec: dict) -> Iterable[bytes]:
yield from _write_Point(xsec[KEY_XSEC_POS])
yield from _write_station(xsec[KEY_XSEC_STN])
direction = xsec[KEY_XSEC_DIR]
if direction != -1:
direction = adegrees_inv(direction)
yield struct.pack('<l', direction)
def _read_mapping(F: BinaryIO) -> dict:
x, y, scale = struct.unpack('<iii', F.read(12))
return {
'center': _make_Point(x, y),
'scale': scale,
}
def _write_mapping(mapping: dict) -> Iterable[bytes]:
x, y = _make_Point_inv(*mapping['center'])
yield struct.pack('<iii', x, y, mapping['scale'])
def _read_drawing(F: BinaryIO) -> dict:
transform = _read_mapping(F)
polys = []
xsec = []
while True:
element = struct.unpack('<B', F.read(1))[0]
if element == 0:
break
if element == 1:
# 1 is a standard line
polys.append(_read_Polygon(F))
elif element == 3:
# 3 is location and orientation of a xsection
xsec.append(_read_xsection(F))
else:
print('undefined object number: ', element, file=sys.stderr)
return {
'polys': polys,
'xsec': xsec,
'transform': transform,
}
def _write_drawing(drawing: dict) -> Iterable[bytes]:
yield from _write_mapping(drawing["transform"])
for poly in drawing["polys"]:
yield struct.pack('<B', 1)
yield from _write_Polygon(poly)
for xsec_ in drawing["xsec"]:
yield struct.pack('<B', 3)
yield from _write_xsection(xsec_)
yield struct.pack('<B', 0)
def _read_fsection(F: BinaryIO, readfun: Callable) -> list:
count = struct.unpack('<L', F.read(4))[0]
return [readfun(F) for _ in range(count)]
def _write_one(fp: BinaryIO, sec, writefunc: Callable):
for chunk in writefunc(sec):
fp.write(chunk)
def _write_fsection(fp: BinaryIO, section: list, writefunc: Callable):
fp.write(struct.pack('<L', len(section)))
for sec in section:
_write_one(fp, sec, writefunc)
def load(fp: BinaryIO) -> dict:
'''Read PocketTopo data from `fp` (readable binary-mode file-like object)
and return it as a dictionary.
'''
if fp.read(3) != b'Top':
raise ValueError('Not a top file')
top = {'version': struct.unpack('B', fp.read(1))[0]}
top['trips'] = _read_fsection(fp, _read_trip)
top['shots'] = _read_fsection(fp, _read_shot)
top['ref'] = _read_fsection(fp, _read_reference)
top['transform'] = _read_mapping(fp)
top['outline'] = _read_drawing(fp)
top['sideview'] = _read_drawing(fp)
remaining = fp.read()
assert remaining == b'\0\0\0\0'
# PocketTopo ignores these
top['shots'] = [s for s in top['shots'] if s['from']]
return top
def loads(content: bytes) -> dict:
'''Load PocketTopo data from byte string'''
return load(io.BytesIO(content))
def dump(top: dict, fp: BinaryIO):
'''Write PocketTopo data to file'''
fp.write(b"Top")
fp.write(struct.pack('B', top['version']))
_write_fsection(fp, top["trips"], _write_trip)
_write_fsection(fp, top["shots"], _write_shot)
_write_fsection(fp, top["ref"], _write_reference)
_write_one(fp, top["transform"], _write_mapping)
_write_one(fp, top["outline"], _write_drawing)
_write_one(fp, top["sideview"], _write_drawing)
fp.write(b'\x00\x00\x00\x00')
def dumps(top: dict) -> bytes:
'''Serialize PocketTopo data to byte string'''
fp = io.BytesIO()
dump(top, fp)
return fp.getvalue()
def dump_json(top, file=sys.stdout):
'''Dump JSON formatted data
'''
import json
json.dump(top, file, indent=2, sort_keys=True)
def dump_svx(top,
surveyname=None,
prefixadd='',
prefixstrip='',
doavg=True,
dosep=False,
therion=False,
dot='.',
file=sys.stdout,
end=os.linesep):
'''Write a Survex (.svx) or Therion (.th) data file
:param surveyname: Add *begin and *end with surveyname
:param prefixadd: Prefix to add
:param prefixstrip: Prefix to strip (e.g. "1.")
:param doavg: Average redundant shots
:param dosep: Separate blocks for legs and splays
:param therion: Use Therion format
:param dot: Character to use instead of '.' in station names
'''
if therion:
C = '#'
P = ''
splayname = '-'
else:
C = ';'
P = '*'
splayname = '..'
if 'filename' in top:
file.write(C + ' ' + os.path.basename(top['filename']))
file.write(end * 2)
if surveyname:
if therion:
file.write('survey ' + surveyname)
else:
file.write('*begin ' + surveyname)
file.write(end * 2)
skip_trip_date = False
# Grotte Asperge convention: Date in file name
if 'filename' in top:
m = re.search(r"[-_.](23-0\d-\d\d|2[3-5][01]\d\d\d)[-_.]", top['filename'])
if m is None:
m = re.search(r"_(23\.0\d\.\d\d)_", top['filename'])
if m is not None:
yymmdd = m.group(1).replace("-", "").replace(".", "")
file.write(P + f'date 20{yymmdd[0:2]}.{yymmdd[2:4]}.{yymmdd[4:6]}')
file.write(end * 2)
skip_trip_date = True
file.write(P + 'data normal from to tape compass clino')
file.write(end)
tripidx = [None] # list as mutable pointer in function scope
allhaveprefixstrip = prefixstrip and (
all(s['from'].startswith(prefixstrip) for s in top['shots']) and
all(s['to'].startswith(prefixstrip) for s in top['shots'] if s['to']))
nstrip = len(prefixstrip) if allhaveprefixstrip else 0
sname = lambda n: n.replace('.', dot)
def write_shot(s):
# ignore "1.0 .. 0.0 0.0 0.0" line
if not s[KEY_TAPE] and not s['to']:
return
if not skip_trip_date and tripidx[0] != s['trip'] and s['trip'] != -1:
tripidx[0] = s['trip']
trip = top['trips'][tripidx[0]]
file.write(end)
file.write(P + 'date {0.tm_year}.{0.tm_mon:02}.{0.tm_mday:02}'.format(trip['date']))
file.write(end)
file.write(P + 'declination {:.2f} degrees'.format(trip[KEY_DECLINATION]))
file.write(end * 2)
from_ = prefixadd + sname(s['from'][nstrip:])
to = (prefixadd + sname(s['to'][nstrip:])) if s['to'] else splayname
fmt = '{0}\t{1}\t{' + KEY_TAPE + ':6.3f} {compass:5.1f} {clino:5.1f}'
if not s[KEY_TAPE]:
fmt = P + 'equate {0} {1}'
file.write(fmt.format(from_, to, **s))
if s.get('comment'):
file.write(' {} {comment}'.format(C, **s))
file.write(end)
if doavg:
leg_iter = average_shots(top['shots'], dosep)
elif dosep:
leg_iter = (s for s in top['shots'] if s['to'])
else:
leg_iter = iter(top['shots'])
for s in leg_iter:
write_shot(s)
if dosep:
file.write(end + C + ' passage data' + end)
for s in top['shots']:
if not s['to']:
write_shot(s)
if surveyname:
file.write(end)
if therion:
file.write('endsurvey')
else:
file.write('*end ' + surveyname)
file.write(end)
def dump_tro(top,
file=sys.stdout,
end=os.linesep):
'''Write a Visual Topo (.tro) data file
'''
def write_shot(s):
# ignore "1.0 .. 0.0 0.0 0.0" line
if not s[KEY_TAPE] and not s['to']:
return
to = s['to'] if s['to'] else '*'
fmt = '{from:10} {0:10} {' + KEY_TAPE + ':19.2f} {compass:6.2f} {clino:7.2f}'
file.write(fmt.format(to, **s))
file.write(end)
# (dummy) entrance required for processing
entrance_name = top['shots'][0]['from']
entrance_shot = {
'from': entrance_name,
'to': entrance_name,
KEY_TAPE: 0,
'compass': 0,
'clino': 0
}
file.write('Entree ' + entrance_name + end)
file.write('Param Deca Degd Clino Degd 0.0000 Dir,Dir,Dir' + end)
write_shot(entrance_shot)
leg_iter = average_shots(top['shots'], False)
for s in leg_iter:
write_shot(s)
def get_bbox(polys):
return [
min(pnt[KEY_X] for poly in polys for pnt in poly['coord']),
min(pnt[KEY_Y] for poly in polys for pnt in poly['coord']),
max(pnt[KEY_X] for poly in polys for pnt in poly['coord']),
max(pnt[KEY_Y] for poly in polys for pnt in poly['coord']),
]
DumpTypePoint = Tuple[float, float]
DumpTypeLeg = Tuple[DumpTypePoint, DumpTypePoint]
class ShotPreprocessor:
def __init__(self, top: dict, sideview: bool):
self.top = top
self.sideview = sideview
self.frompoints: Dict[str, DumpTypePoint] = {}
self.legs: List[DumpTypeLeg] = []
self.splays: List[DumpTypeLeg] = []
self.defer: List[dict] = []
self.compass_from: Dict[str, List[float]] = collections.defaultdict(list)
self.compass_to: Dict[str, List[float]] = collections.defaultdict(list)
def get_sideview_compass_delta(self, shot: dict, true_bearing: float,
is_splay: bool):
compass_delta = 1.0
if not is_splay:
if shot[KEY_TAPE] and is_consecutive_number(shot["from"], shot["to"]):
self.compass_from[shot['from']].append(true_bearing)
if shot[KEY_TAPE]:
self.compass_to[shot['to']].append(true_bearing)
else:
assert shot[KEY_TAPE]
compass_out = self.compass_from.get(shot['from'])
compass_in = self.compass_to.get(shot['from'], compass_out)
if compass_in is None:
compass_out = []
compass_in = []
elif compass_out is None:
compass_out = compass_in
compass_in_avg_back = avgdeg(compass_in) + 180
compass_out_avg = avgdeg(compass_out)
compass_splay_rel = posdeg(true_bearing - compass_in_avg_back)
compass_out_rel = posdeg(compass_out_avg - compass_in_avg_back)
if compass_splay_rel > compass_out_rel:
compass_splay_rel = 360 - compass_splay_rel
compass_out_rel = 360 - compass_out_rel
if compass_out_rel:
compass_delta = compass_splay_rel / compass_out_rel * 2 - 1
# I would expect sin transformation, but looks like PocketTopo doesn't do that
# compass_delta = math.sin(math.radians(compass_delta * 90))
if shot[KEY_EXTEND] == EXTEND_LEFT:
compass_delta *= -1
return compass_delta
def process_shot(self, shot: dict, do_splays: bool):
is_splay = not shot['to']
if do_splays != is_splay:
return True
# ignore "1.0 .. 0.0 0.0 0.0" line
if not shot[KEY_TAPE] and is_splay:
return True
if shot['from'] not in self.frompoints:
if shot['to'] not in self.frompoints:
return False
shot = reverse_shot(shot)
length_proj = shot[KEY_TAPE] * math.cos(math.radians(shot['clino']))
true_bearing = get_true_bearing(shot, self.top)
if self.sideview:
compass_delta = self.get_sideview_compass_delta(
shot, true_bearing, is_splay)
delta_x = length_proj * compass_delta
delta_y = shot[KEY_TAPE] * math.sin(math.radians(shot['clino']))
else:
delta_x = length_proj * math.sin(math.radians(true_bearing))
delta_y = length_proj * math.cos(math.radians(true_bearing))
pnt_from = self.frompoints[shot['from']]
pnt_to = (pnt_from[0] + delta_x, pnt_from[1] - delta_y)
if not is_splay:
self.frompoints[shot['to']] = pnt_to
self.legs.append((pnt_from, pnt_to))
else:
self.splays.append((pnt_from, pnt_to))
return True
def process(self, leg_shots: List[dict]):
for s in self.top['shots']:
self.frompoints[s['from']] = (0, 0)
break
for s in leg_shots:
if not self.process_shot(s, False):
self.defer.append(s)
while self.defer:
for s in self.defer:
if self.process_shot(s, False):
self.defer.remove(s)
break
else:
print(f'{len(self.defer)} unconnected subsurveys', file=sys.stderr)
break
for s in self.top['shots']:
self.process_shot(s, True)
def dump_svg(top: dict,
*,
hidesideview: bool = False,
file=sys.stdout,
showbbox: bool = True,
scale: float = 200.0):
'''Dump drawing as SVG.
Plan and side views go into separate layers.
Args:
scale: Scale as 1:scale
'''
scale /= 100 # cm
default_stroke_width = scale * 0.05
font_size = scale * 1.27 / 3
leg_shots = list(average_shots(top['shots']))
def write_shots(parent: EtreeElement, shots, sideview=False) -> dict:
def write_legs(legs: list, style: str):
path_data = " ".join(
f"M{pnt_from[0]},{pnt_from[1]} {pnt_to[0]},{pnt_to[1]}"
for (pnt_from, pnt_to) in legs)
etree.SubElement(parent, "path", {
CLARK_INKSCAPE_LABEL: "line survey",
"style": style,
"d": path_data,
})
preprocessor = ShotPreprocessor(top, sideview)
preprocessor.process(leg_shots)
write_legs(preprocessor.splays, 'stroke:#fc0;stroke-width:0.02')
write_legs(preprocessor.legs, 'stroke:#f00;stroke-width:0.03')
return preprocessor.frompoints
def write_xsections(parent: EtreeElement, frompoints, drawing):
for xsec in drawing['xsec']:
pnt = xsec[KEY_XSEC_POS]
pnt_stn = frompoints[xsec[KEY_XSEC_STN]]
etree.SubElement(
parent, "path", {
CLARK_INKSCAPE_LABEL: "line section",
"style": "stroke:#bbb;stroke-dasharray:0.05 0.15",
"d": f"M{pnt_stn[0]} {pnt_stn[1]} {pnt[0]} {pnt[1]}",
})
def write_stationlabels(parent: EtreeElement, frompoints: dict):
for key, pnt in frompoints.items():
survey, _, station = key.rpartition(".")
name = "{}@{}".format(station, survey) if survey else key
assert name == escape(name)
elem_text = etree.SubElement(
parent, "text", {
"x": str(pnt[0]),
"y": str(pnt[1]),
CLARK_INKSCAPE_LABEL: f"point station -name {name}",
"style": "fill:#999",
})
elem_text.text = key
outer_padding = 5.0
def write_layer(parent: EtreeElement,
top: dict,
view: str,
label: str = "",
*,
xoffset: int = 0,
display: str = 'inline',
padding: float = 1.0) -> tuple:
"""
Returns:
Width and height of the bounding box
"""
drawing = top[view]
if not label:
label = view
try:
min_x, min_y, max_x, max_y = get_bbox(drawing['polys'])
except ValueError:
min_x, min_y, max_x, max_y = 0, 0, 0, 0
width = max_x - min_x
height = max_y - min_y
xoffset += -min_x + outer_padding
yoffset = -min_y + outer_padding
g_layer = etree.SubElement(
parent, "g", {
CLARK_INKSCAPE_GROUPMODE: "layer",
CLARK_INKSCAPE_LABEL: label,
"style": f"display:{display};font:{font_size} sans-serif;stroke-width:{default_stroke_width}",
"transform": f"translate({xoffset},{yoffset})",
})
g_drawing = etree.SubElement(g_layer, "g", {
CLARK_INKSCAPE_LABEL: "drawing",
})
for poly in drawing['polys']:
coord = poly['coord']
# repeat single points to make line visible
if len(coord) == 1:
coord = coord + coord
path_data = "M" + " ".join(f" {pnt[KEY_X]},{pnt[KEY_Y]}"
for pnt in coord)
etree.SubElement(g_drawing, "path", {
"style": f"stroke:{poly[KEY_COLOR]}",
"d": path_data,
})
g_shots = etree.SubElement(g_layer, "g", {
CLARK_INKSCAPE_LABEL: "shots",
})
stations = write_shots(g_shots, top, view == 'sideview')
write_xsections(g_shots, stations, drawing)
write_stationlabels(g_shots, stations)
if showbbox:
if width or height:
color = '#f0f'
etree.SubElement(
g_layer, "rect", {
"x": f"{min_x - padding}",
"y": f"{min_y - padding}",
"width": f"{width + padding * 2}",
"height": f"{height + padding * 2}",
"style": f"fill:none;stroke:{color};stroke-width:0.04",
})
if 'filename' in top:
elem_text = etree.SubElement(
g_layer, "text", {
"x": f"{min_x - 0.7}",
"y": f"{min_y - 0.2}",
"style": f"fill:{color}",
})
elem_text.text = f"{os.path.basename(top['filename'])} ({label})"
return width, height
root = etree.fromstring("""<?xml version="1.0" ?>
<svg
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns="http://www.w3.org/2000/svg">
<defs>
<style type="text/css">
path {