-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsurvey2ssdm.py
1153 lines (961 loc) · 41.4 KB
/
survey2ssdm.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
#name: survey2ssdm.py
#created: Jan 2019
#by: paul.kennedy@guardiangeomatics.com
#description: python module to scan a folder structure and import various supported file formats and convert to a SSDM schema within the OGC SSDM schema
import sys
import time
import os
import tempfile
import ctypes
import fnmatch
import math
import json
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
from datetime import datetime
from datetime import timedelta
from glob import glob
import uuid
import multiprocessing as mp
import pyproj
from py7k import s7kreader
from pyjsf import jsfreader
from segyreader import segyreader
from pygsf import GSFREADER
import readkml
import kmraw
import sbd
# local from the shared area...
# sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'shared'))
import fileutils
import geodetic
import geopackage
import geopackage_ssdm
import ssdmfieldvalue
import kmall
import multiprocesshelper
##############################################################################
def main():
parser = ArgumentParser(description='Read any Survey folder and create a OGC compliant GEOPackage in the SSDM Schema summarising the survey. This is a distillation process extracting important spatial attributes from the survey in an automated and rigorous manner.',
epilog='Example: \n To process all files under a root folder use -i c:/foldername \n', formatter_class=RawTextHelpFormatter)
parser.add_argument('-i', action='store', default="", dest='inputfolder', help='input folder to process.')
parser.add_argument('-o', action='store', default="", dest='outputFilename', help='output GEOPACKAGE filename.')
parser.add_argument('-s', action='store', default="1", dest='step', help='decimate the data to reduce the output size. [Default: 1]')
parser.add_argument('-odir', action='store', default="", dest='odir', help='Specify a relative output folder e.g. -odir GIS')
parser.add_argument('-config', action='store_true', default=False, dest='config', help='Open the SSDM configuration file for editing e.g. -config')
parser.add_argument('-opath', action='store', default="", dest='opath', help='Specify an output path e.g. -opath c:/temp')
parser.add_argument('-odix', action='store', default="", dest='odix', help='Specify an output filename appendage e.g. -odix _coverage')
parser.add_argument('-epsg', action='store', default="4326", dest='epsg', help='Specify an output EPSG code for transforming from WGS84 to East,North,e.g. -epsg 4326')
parser.add_argument('-epsgsbd', action='store', default="0", dest='epsgsbd', help='Specify an output EPSG code for transforming SBD grid coordinates from East,North to WGS84,e.g. -epsg 32750')
parser.add_argument('-all', action='store_true', default=True, dest='all', help='extract all supported forms of data (ie do everything).')
parser.add_argument('-reprocess',action='store_true', default=False, dest='reprocess', help='reprocess the survey folders by re-reading input files and creating new GIS features, ignoring the cache files. (ie do everything).')
parser.add_argument('-cpu', action='store', default='0', dest='cpu', help='number of cpu processes to use in parallel. [Default: 0, all cpu]')
args = parser.parse_args()
# if len(sys.argv)==1:
# parser.print_help()
# sys.exit(1)
if args.config:
geopackage.openSSDMFieldValues()
geopackage.openSSDMFieldValues()
# user has not set any flags so do everything. better than doing nothing.
if args.all == False and \
args.auv == False and \
args.hipap == False and \
args.navlab == False and \
args.utp == False and \
args.mp == False and \
args.ctd == False and \
args.mbes == False and \
args.vessel == False:
args.all = True
if args.all:
args.auv = True
args.navlab = True
args.hipap = True
args.utp = True
args.qc = True
args.mp = True
args.ctd = True
args.vessel = True
args.mbes = True
if len(args.inputfolder) == 0:
args.inputfolder = os.getcwd() + args.inputfolder
if args.inputfolder == '.':
args.inputfolder = os.getcwd() + args.inputfolder
process(args)
###############################################################################
def process(args):
if not os.path.isdir(args.inputfolder):
print ("oops, input is not a folder. Please specify a survey folder.")
return
surveyname = os.path.basename(args.inputfolder) #this folder should be the Survey NAME
if args.opath == "":
args.opath = os.path.join(args.inputfolder, "GIS")
if len(args.outputFilename) == 0:
args.outputFilename = os.path.join(args.opath, args.odir, surveyname + "_SSDM.gpkg")
args.outputFilename = fileutils.addFileNameAppendage(args.outputFilename, args.odix)
args.outputFilename = fileutils.createOutputFileName(args.outputFilename)
# create the gpkg...
gpkg = geopackage.geopackage(args.outputFilename, int(args.epsg))
# pkpk this does not yet work...
# gpkg.addEPSG(args.epsg)
#load the python proj projection object library if the user has requested it
geo = geodetic.geodesy(args.epsg)
# process any and all .sbd files from EIVA
mp_processSBD(args, gpkg, geo)
# process any and all .raw files from KM
mp_processKMRAW(args, gpkg, geo)
# process any and all kmall files
mp_processKMALL(args, gpkg, geo)
# process any and all 7k files
mp_process7k(args, gpkg, geo)
# process any and all JSF files
mp_processjsf(args, gpkg, geo)
# process any and all SEGY files
mp_processsegy(args, gpkg, geo)
# process any and all GSF files
mp_processgsf(args, gpkg, geo)
print("Completed creation of SSDM tracks to: %s" %(args.outputFilename))
###############################################################################
def findsurveys(args):
'''high level funciton to recursively find all the surveys in all subfolders'''
surveys = []
#add the base folder as a candidate in case this is the folde rth euser specified.
if folderisasurvey(args.inputfolder):
surveys.append(args.inputfolder)
return surveys
#looks like the user has specificed a higher level folder such as a root drive or project folder so scan deeply
print("Scanning for surveys from root folder %s ...." % (args.inputfolder))
folders = fast_scandir(args.inputfolder)
for folder in folders:
if folderisasurvey(folder):
surveys.append(folder)
print("surveys to Process: %s " % (len(surveys)))
return surveys
###############################################################################
def folderisasurvey(dirname):
'''validate if this is a real survey by testing if there is a survey.mp file in the folder '''
# filename = os.path.join(dirname, "events.txt")
# if not os.path.exists(filename):
# return False
surveys = fileutils.findFiles2(False, dirname, "*survey.mp")
if len(surveys)==0:
# filename = os.path.join(dirname, "survey.mp")
# if not os.path.exists(filename):
return False
return True
###############################################################################
def fast_scandir(dirname):
subfolders = []
for root, dirs, files in os.walk(dirname, topdown=True):
# for name in files:
# print(os.path.join(root, name))
if root in subfolders:
continue
for name in dirs:
dirname = os.path.join(root, name)
print (dirname)
if folderisasurvey(dirname):
subfolders.append(dirname)
# dirs[:] = []
sys.stdout.write('.')
sys.stdout.flush()
# subfolders = [x[0] for x in os.walk(dirname)]
# subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]
# if subfolders is not None:
# for dirname in list(subfolders):
# subfolders.extend(fast_scandir(dirname))
# else:
# print("oops")
return subfolders
###############################################################################
def update_progress(job_title, progress):
length = 20 # modify this to change the length
block = int(round(length*progress))
msg = "\r{0}: [{1}] {2}%".format(job_title, "#"*block + "-"*(length-block), round(progress*100, 2))
if progress >= 1: msg += " DONE\r\n"
sys.stdout.write(msg)
sys.stdout.flush()
# ###############################################################################
def processsurveyPlan(args, surveyfolder, gpkg, geo):
'''import the survey.mp file into the geopackage'''
matches = fileutils.findFiles(True, args.inputfolder, "*.kml")
if len(matches) == 0:
print("No KML files found for importing to survey line plan, skipping")
return
#create the linestring table for the survey plan
type, fields = geopackage_ssdm.createProposed_Survey_Run_Lines()
linestringtable = geopackage.vectortable(gpkg.connection, "surveyPlan", gpkg.epsg, type, fields)
# table = vectortable (connection, tablename, epsg, type, fields)
# return table
for filename in matches:
reader = readkml.reader(filename)
print ("File: %s Survey lines found: %d" % (filename, len(reader.surveylines)))
createsurveyplan(reader, linestringtable, geo)
################################################################################
def processSBD(filename, outfilename, step, epsgsbd):
#now read the EIVA .sbd file and return the navigation table filename
# print("Loading KMALL Navigation...")
r = sbd.SBDReader(filename)
navigation, navigation2 = r.loadnavigation(step=1)
r.close()
#the sbd files are in east north rather than lat, long so we need to convert them here...
geo = geodetic.geodesy(epsgsbd)
navigation3 = []
for nav in navigation:
x, y = geo.convertToGeographicals(nav[1], nav[2])
navigation3.append([nav[0], x, y, nav[3]])
# if x > 90:
# print ("oops")
with open(outfilename,'w') as f:
json.dump(navigation3, f)
return(navigation3)
################################################################################
def processKMRAW(filename, outfilename, step):
#now read the km .raw file and return the navigation table filename
# print("Loading KMALL Navigation...")
r = kmraw.KMRAWreader(filename)
navigation = r.loadnavigation(step=1)
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def processKMALL(filename, outfilename, step):
#now read the kmall file and return the navigation table filename
# print("Loading KMALL Navigation...")
r = kmall.kmallreader(filename)
navigation = r.loadNavigation(step=1)
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def process7k(filename, outfilename, step):
#now read the kmall file and return the navigation table filename
# print("Loading 7K Navigation...")
r = s7kreader(filename)
navigation = r.loadNavigation(False)
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def processgsf(filename, outfilename, step):
#now read the kmall file and return the navigation table filename
navigation = []
# print("Loading sgy Navigation...")
r = GSFREADER(filename)
if (r.fileSize == 0):
# the file is a corrupt empty file so skip
return navigation
navigation = r.loadnavigation()
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def processsegy(filename, outfilename, step):
#now read the kmall file and return the navigation table filename
navigation = []
# print("Loading sgy Navigation...")
r = segyreader(filename)
if (r.fileSize == 0):
# the file is a corrupt empty file so skip
return navigation
r.readHeader()
navigation = r.loadNavigation()
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def processjsf(filename, outfilename, step):
#now read the kmall file and return the navigation table filename
# print("Loading jsf Navigation...")
r = jsfreader(filename)
navigation = r.loadNavigation(False)
r.close()
with open(outfilename,'w') as f:
json.dump(navigation, f)
return(navigation)
################################################################################
def mp_process7k(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.s7k")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
multiprocesshelper.log("New 7k Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting S7K Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
# poolresults = [pool.apply_async(processKMALL, (task[0], task[1], args.step)) for task in boundarytasks]
poolresults = [pool.apply_async(process7k, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processgsf(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.gsf")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the POINT table for the trackplot
tptype, tpfields = geopackage_ssdm.createTrackPoint()
pointtable = geopackage.vectortable(gpkg.connection, "SurveyTrackPoint", args.epsg, tptype, tpfields)
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
if args.cpu == '1':
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
result = processgsf(filename, outfilename, args.step)
results.append([filename, result])
else:
multiprocesshelper.log("New GSF Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting GSF Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
poolresults = [pool.apply_async(processgsf, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
createTrackPoint(result[0], result[1], pointtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processsegy(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.sgy")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
if args.cpu == '1':
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
result = processsegy(filename, outfilename, args.step)
results.append([filename, result])
else:
multiprocesshelper.log("New sgy Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting SGY Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
poolresults = [pool.apply_async(processsegy, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processjsf(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.jsf")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
multiprocesshelper.log("New jsf Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting JSF Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
# poolresults = [pool.apply_async(processKMALL, (task[0], task[1], args.step)) for task in boundarytasks]
poolresults = [pool.apply_async(processjsf, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processSBD(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.sbd")
# if args.epsgsbd == "0":
# reader = sbd.SBDReader(matches[0])
# timstamp, x, y, heading = reader.getfirstcoordinate()
# # args.epsgsbd = geo.getEPSGfromEN(x,y)
# args.epsgsbd = geodetic.getPRJFromEPSG(x,y)
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the POINT table for the trackplot
tptype, tpfields = geopackage_ssdm.createTrackPoint()
pointtable = geopackage.vectortable(gpkg.connection, "SurveyTrackPoint", args.epsg, tptype, tpfields)
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
if args.cpu == '1':
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if os.path.exists(outfilename):
continue
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
result = processSBD(filename, outfilename, args.step, args.epsgsbd)
results.append([filename, result])
else:
multiprocesshelper.log("New km .raw Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting KM .RAW Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
poolresults = [pool.apply_async(processSBD, (task[0], task[1], args.step, args.epsgsbd), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
createTrackPoint(result[0], result[1], pointtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processKMRAW(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.raw")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
if args.cpu == '1':
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
result = processKMRAW(filename, outfilename, args.step)
results.append([filename, result])
else:
multiprocesshelper.log("New km .raw Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting KM .RAW Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
poolresults = [pool.apply_async(processKMRAW, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
multiprocesshelper.mpresult("")
################################################################################
def mp_processKMALL(args, gpkg, geo):
# boundary = []
boundarytasks = []
results = []
rawfolder = os.path.join(args.inputfolder, ssdmfieldvalue.readvalue("MBES_RAW_FOLDER"))
if not os.path.isdir(rawfolder):
rawfolder = args.inputfolder
# rawfilename = ssdmfieldvalue.readvalue("MBES_RAW_FILENAME")
matches = fileutils.findFiles2(True, rawfolder, "*.kmall")
# surveyname = os.path.basename(args.inputfolder) #this folder should be the survey NAME
#create the linestring table for the trackplot
type, fields = geopackage_ssdm.createSurveyTracklineSSDM()
linestringtable = geopackage.vectortable(gpkg.connection, "SurveyTrackLine", args.epsg, type, fields)
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
# makedirs(outputfolder)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
if args.reprocess:
if os.path.exists(outfilename):
os.unlink(outfilename)
if os.path.exists(outfilename):
# the cache file exists so load it
with open(outfilename) as f:
# print("loading file %s" %(outfilename))
lst = json.load(f)
results.append([filename, lst])
else:
boundarytasks.append([filename, outfilename])
if args.cpu == '1':
for filename in matches:
root = os.path.splitext(filename)[0]
root = os.path.basename(filename)
outputfolder = os.path.join(os.path.dirname(args.outputFilename), "log")
os.makedirs(outputfolder, exist_ok=True)
outfilename = os.path.join(outputfolder, root+"_navigation.txt").replace('\\','/')
result = processKMALL(filename, outfilename, args.step)
results.append([filename, result])
else:
multiprocesshelper.log("New kmall Files to Import: %d" %(len(boundarytasks)))
cpu = multiprocesshelper.getcpucount(args.cpu)
multiprocesshelper.log("Extracting KMALL Navigation with %d CPU's" %(cpu))
pool = mp.Pool(cpu)
multiprocesshelper.g_procprogress.setmaximum(len(boundarytasks))
# poolresults = [pool.apply_async(processKMALL, (task[0], task[1], args.step)) for task in boundarytasks]
poolresults = [pool.apply_async(processKMALL, (task[0], task[1], args.step), callback=multiprocesshelper.mpresult) for task in boundarytasks]
pool.close()
pool.join()
for idx, result in enumerate (poolresults):
results.append([boundarytasks[idx][0], result._value])
# print (result._value)
# now we can read the results files and create the geometry into the SSDM table
multiprocesshelper.log("Files to Import to geopackage: %d" %(len(results)))
multiprocesshelper.g_procprogress.setmaximum(len(results))
for result in results:
createTrackLine(result[0], result[1], linestringtable, float(args.step), geo)
multiprocesshelper.mpresult("")
###############################################################################
def createTrackPoint(filename, navigation, pointtable, step, geo, surveyname=""):
'''create a point table into the SSDM which we can use to identify where we were and the time we were there'''
lastTimeStamp = 0
pointstring = []
timeIDX = 0
longitudeIDX = 1
latitudeIDX = 2
depthIDX = 3
rollIDX = 4
pitchIDX = 5
headingIDX = 6
deltatimeIDX = 7
pingflagIDX = 3
# navigation = reader.loadnavigation(step)
totalDistanceRun = 0
if navigation is None: #trap out empty files.
return
print(filename)
try:
if len(navigation) == 0: #trap out empty files.
print("file is empty: %s" % (filename))
return
except:
return
# prevX = navigation[0][longitudeIDX]
# prevY = navigation[0][latitudeIDX]
# for update in navigation:
# distance = geodetic.est_dist(update[latitudeIDX], update[longitudeIDX], prevY, prevX)
# totalDistanceRun += distance
# prevX = update[longitudeIDX]
# prevY = update[latitudeIDX]
# compute the brg1 line heading
# distance, brg1, brg2 = geodetic.calculateRangeBearingFromGeographicals(navigation[0][1], navigation[0][2], navigation[-1][1], navigation[-1][2])
# create the trackline shape file
for update in navigation:
x,y = geo.convertToGrid(update[longitudeIDX],update[latitudeIDX])
# linestring.append(x)
# linestring.append(y)
# lastTimeStamp = update[0]
# recDate = from_timestamp(navigation[0][timeIDX]).strftime("%Y%m%d")
###########################
# write out the FIELDS data
###########################
# write out the FIELDS data
fielddata = []
fielddata += setssdmarchivefields() # 2 fields
fielddata += setssdmobjectfields() # 4 fields
fielddata.append(ssdmfieldvalue.readvalue("LINE_ID"))
#LINE_NAME
fielddata.append(os.path.basename(filename))
#LAST_SEIS_PT_ID
fielddata.append(int(navigation[-1][timeIDX]))
#SYMBOLOGY_CODE
fielddata.append(ssdmfieldvalue.readvalue("TRACK_SYMBOLOGY_CODE"))
#DATA_SOURCE
fielddata.append(os.path.basename(filename))
#CONTRACTOR_NAME
fielddata.append(ssdmfieldvalue.readvalue("CONTRACTOR_NAME"))
#LINE_LENGTH
fielddata.append(totalDistanceRun)
#FIRST_SEIS_PT_ID
fielddata.append(int(navigation[0][timeIDX]))
#HIRES_SEISMIC_EQL_URL
fielddata.append(ssdmfieldvalue.readvalue("HIRES_SEISMIC_EQL_URL"))
#OTHER_DATA_URL
fielddata.append(ssdmfieldvalue.readvalue("OTHER_DATA_URL"))
# #HIRES_SEISMIC_RAP_URL
# fielddata.append(ssdmfieldvalue.readvalue("HIRES_SEISMIC_RAP_URL"))
#LAYER
fielddata.append(ssdmfieldvalue.readvalue("TRACK_LAYER"))
#SHAPE_Length
fielddata.append(totalDistanceRun)
##################################################
# fields.append(["SurveyTime", "TEXT"])
fielddata.append(from_timestamp(update[timeIDX]).strftime("%Y%m%d"))
# fields.append(["UNIXTime", "DOUBLE"])
fielddata.append(update[timeIDX])
# fields.append(["Longitude", "DOUBLE"])
fielddata.append(update[longitudeIDX])
# fields.append(["Latitude", "DOUBLE"])
fielddata.append(update[latitudeIDX])
# fields.append(["Depth", "DOUBLE"])
fielddata.append(update[depthIDX])
# fields.append(["Roll", "DOUBLE"])
fielddata.append(0.0)
# fields.append(["Pitch", "DOUBLE"])
fielddata.append(0.0)
# fields.append(["Heading", "DOUBLE"])
fielddata.append(0.0)
# fields.append(["PingFlag", "DOUBLE"])
# fielddata.append("%d" % (update[pingflagIDX]))
# now write the point to the table.
# linestringtable.addlinestringrecord(linestring, fielddata)
pointtable.addpointrecord(x, y, fielddata)
pointtable.close()
###############################################################################
def createTrackLine(filename, navigation, linestringtable, step, geo, surveyname=""):
#verified April 2021
lastTimeStamp = 0
linestring = []
timeIDX = 0
longitudeIDX = 1
latitudeIDX = 2
depthIDX = 3
headingIDX = 4
rollIDX = 5
pitchIDX = 6
# navigation = reader.loadnavigation(step)
totalDistanceRun = 0
if navigation is None: #trap out empty files.
return
print(filename)
try:
if len(navigation) == 0: #trap out empty files.
print("file is empty: %s" % (filename))
return
except:
return
prevX = navigation[0][longitudeIDX]
prevY = navigation[0][latitudeIDX]
for update in navigation:
distance = geodetic.est_dist(update[latitudeIDX], update[longitudeIDX], prevY, prevX)
totalDistanceRun += distance
prevX = update[longitudeIDX]
prevY = update[latitudeIDX]
# compute the brg1 line heading
# distance, brg1, brg2 = geodetic.calculateRangeBearingFromGeographicals(navigation[0][1], navigation[0][2], navigation[-1][1], navigation[-1][2])
# create the trackline shape file
for update in navigation:
if update[0] - lastTimeStamp >= step:
x,y = geo.convertToGrid(update[longitudeIDX],update[latitudeIDX])
linestring.append(x)
linestring.append(y)