-
Notifications
You must be signed in to change notification settings - Fork 11
/
DrillManager.py
1407 lines (1194 loc) · 62.7 KB
/
DrillManager.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
DrillManager
-------------------
begin : 2018-04-13
git sha : $Format:%H$
copyright : (C) 2018 by Roland Hill / MMG
email : [email protected]
***************************************************************************/
"""
from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QVariant
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QDialog, QProgressBar, QProgressDialog, qApp
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
import numpy as np
from .quaternion import Quaternion
# Initialize Qt resources from file resources.py
from .resources import *
from .desurveyhole_dialog import DesurveyHoleDialog
from .downholepoints_dialog import DownholePointsDialog
from .downholedata_dialog import DownholeDataDialog
from .downholestructure_dialog import DownholeStructureDialog
from .sectionmanager_dialog import SectionManagerDialog
from .SectionManager import *
from .Utils import *
import os.path
import math
import platform
class Collar:
id = ''
east = 0.0
north = 0.0
elev = 0.0
depth = 0.0
az = 0.0
dip = 0.0
class Survey:
id = ''
depth = 0.0
az = 0.0
dip = 0.0
class Surveys:
depth = 0.0
az = 0.0
dip = 0.0
# The DrillManager class controls all drill related data and methods
class DrillManager:
def __init__(self):
self.sectionManager = SectionManager(self)
self.sectionManagerDlg = None
# Project data is normally read in response to a readProject signal.
# We also do it here for when the plugin is loaded other than at startup
self.readProjectData()
# Create a log file
self.openLogFile()
# Open a log file in the Collar Layer's directory
def openLogFile(self):
# Maintain a log file in case of data errors
if self.collarLayer and self.collarLayer.isValid():
path=self.collarLayer.dataProvider().dataSourceUri()
# fileName = uriToFile(os.path.join(os.path.split(path)[0], 'Geoscience_DrillManager_log.txt'))
# self.logFile = open(fileName,'w')
# if not self.logFile:
# self.logFile = open(os.path.join(os.path.expanduser("~"), "Geoscience_DrillManager_log.txt"),'w')
# self.logFile.write("Geoscience - DrillManager log file\n")
# self.logFile.write(" Note: This file is overwritten each time you run Geoscience.\n")
# self.logFile.write(" Make a copy if you want to keep the results.\n")
# # We flush the buffers in case the plugin crashes without writing the message to the file
# self.logFile.flush()
# Setup and run the Drill Setup dialog
def onDesurveyHole(self):
dlg = DesurveyHoleDialog(self)
result = dlg.exec_()
# If OK button clicked then retrieve and update values
if result:
self.downDipNegative = dlg.checkDownDipNegative.isChecked()
self.desurveyLength = float(dlg.leDesurveyLength.text())
# self.defaultSectionWidth = dlg.teDefaultSectionWidth.text()
# self.defaultSectionStep = dlg.teDefaultSectionStep.text()
self.collarLayer = dlg.lbCollarLayer.currentLayer()
self.surveyLayer = dlg.lbSurveyLayer.currentLayer()
self.collarId = dlg.fbCollarId.currentField()
self.collarDepth = dlg.fbCollarDepth.currentField()
self.collarEast = dlg.fbCollarEast.currentField()
self.collarNorth = dlg.fbCollarNorth.currentField()
self.collarElev = dlg.fbCollarElev.currentField()
self.collarAz = dlg.fbCollarAz.currentField()
self.collarDip = dlg.fbCollarDip.currentField()
self.surveyId = dlg.fbSurveyId.currentField()
self.surveyDepth = dlg.fbSurveyDepth.currentField()
self.surveyAz = dlg.fbSurveyAz.currentField()
self.surveyDip = dlg.fbSurveyDip.currentField()
# Save updated values to QGIS project file
self.writeProjectData()
# The collar layer might have changed, so re-open log file
# self.openLogFile()
dlg.close()
if result:
self.desurveyHole()
# Setup and run the Downhole Data dialog
def onDownholeData(self):
dlg = DownholeDataDialog(self)
result = dlg.exec_()
if result:
self.desurveyLayer = dlg.lbDesurveyLayer.currentLayer()
self.dataLayer = dlg.lbDataLayer.currentLayer()
self.dataId = dlg.fbDataId.currentField()
self.dataFrom = dlg.fbDataFrom.currentField()
self.dataTo = dlg.fbDataTo.currentField()
self.dataSuffix = dlg.teSuffix.text()
# Save the name of each checked attribute field in a list
self.dataFields = []
for index in range(dlg.listFields.count()):
if dlg.listFields.item(index).checkState():
self.dataFields.append(dlg.listFields.item(index).text())
self.writeProjectData()
dlg.close()
if result:
# Create the down hole traces
self.createDownholeData()
def onDownholePoints(self):
dlg = DownholePointsDialog(self)
result = dlg.exec_()
if result:
self.desurveyLayer = dlg.lbDesurveyLayer.currentLayer()
self.pointSeparation = float(dlg.lePointSeparation.text())
self.pointIncZero = dlg.cbIncZero.isChecked()
self.pointIncEOH = dlg.cbIncEOH.isChecked()
self.writeProjectData()
dlg.close()
if result:
# Create the down hole traces
self.createDownholePoints()
# Setup and run the Downhole Structure dialog
def onDownholeStructure(self):
dlg = DownholeStructureDialog(self)
result = dlg.exec_()
if result:
self.desurveyLayer = dlg.lbDesurveyLayer.currentLayer()
self.structureLayer = dlg.lbDataLayer.currentLayer()
self.structureId = dlg.fbDataId.currentField()
self.structureDepth = dlg.fbDataDepth.currentField()
self.structureAlpha = dlg.fbDataAlpha.currentField()
self.structureBeta = dlg.fbDataBeta.currentField()
self.structureScale = float(dlg.leSymbolSize.text())
# Save the name of each checked attribute field in a list
self.structureFields = []
for index in range(dlg.listFields.count()):
if dlg.listFields.item(index).checkState():
self.structureFields.append(dlg.listFields.item(index).text())
self.writeProjectData()
dlg.close()
if result:
# Create the down hole traces
self.createDownholeStructure()
# # Desurvey the data
# def onDesurveyHole(self):
# self.desurveyData()
#
# Create a section
def onDrillSectionManager(self):
if self.sectionManagerDlg is None:
self.sectionManagerDlg = SectionManagerDialog(self)
self.sectionManagerDlg.show()
self.sectionManagerDlg.activateWindow()
self.sectionManagerDlg.fillSectionList()
# Create the down hole data (interval) traces
def createDownholeData(self):
# self.logFile.write("\nCreating Downhole Data Layer.\n")
# self.logFile.flush()
# Check that desurvey layer is available
if not self.desurveyLayer.isValid() or not self.dataLayer.isValid():
return
# Set up a progress display
pd = QProgressDialog()
pd.setAutoReset(False)
pd.setWindowTitle("Build Downhole Data Layer")
pd.setMinimumWidth(500)
pd.setMinimum(0)
pd.setMaximum(self.dataLayer.featureCount())
pd.setValue(0)
# Get the fields from the data layer
dp = self.dataLayer.dataProvider()
idxId = dp.fieldNameIndex(self.dataId)
idxFrom = dp.fieldNameIndex(self.dataFrom)
# idxTo will be -1 if no field was chosen (ie point rather than interval data)
idxTo = dp.fieldNameIndex(self.dataTo)
# Create a list of attribute indices from the desired attribute field names
idxAttList = []
for name in self.dataFields:
idx = dp.fieldNameIndex(name)
idxAttList.append(idx)
# Create memory layer
if(idxTo > -1):
layer = self.createDownholeIntervalLayer()
else:
layer = self.createDownholePointLayer()
# Get the fields from the desurveyed trace layer
tdp = self.desurveyLayer.dataProvider()
idxTraceId = tdp.fieldNameIndex("CollarID")
idxTraceSegLength = tdp.fieldNameIndex("SegLength")
# Store the relevant desurveyed drill trace so that it's persistent between loops
# This way we should be able to re-use it instead of re-fetching it.
traceFeature = QgsFeature()
currentTraceCollar = ""
currentTraceSegLength = 1.0
currentTracePolyline = None
#Loop through downhole layer features
# Calculate an optimum update interval for the progress bar (updating gui items is expensive)
updateInt = max(100, long(self.dataLayer.featureCount()/100))
floatConvError = False
nullDataError = False
for index, df in enumerate(self.dataLayer.getFeatures()):
# Update the Progress bar
if index%updateInt == 0:
pd.setValue(index)
qApp.processEvents()
# Variable to hold a feature
feature = QgsFeature()
# get the feature's attributes
attrs = df.attributes()
# Check all the data is valid
dataId = str(attrs[idxId])
try:
dataFrom = float(attrs[idxFrom])
if (idxTo > -1):
dataTo = float(attrs[idxTo])
except:
floatConvError = True
if (dataId==NULL) or (dataFrom==NULL) or (idxTo > -1 and dataTo==NULL):
nullDataError = True
continue
dataId = dataId.strip()
# Get the desurvey drill trace relevant to this collar, checking first that we don't already have it
if not currentTraceCollar == dataId:
# Get the correct trace feature via a query
query = '''"CollarID" = '%s' ''' % (dataId)
selection = self.desurveyLayer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
# We have a selection of features
if selection.isValid():
# There should be just 1, so get the first feature
selection.nextFeature(traceFeature)
# Is the feature valid?
if traceFeature.isValid():
# Update information for the current feature
currentTraceCollar = dataId
currentTraceSegLength = traceFeature.attributes()[idxTraceSegLength]
# The normal asPolyline() function only returns QgsPointXY, yet we need the Z coordinate as well
# We therefore get a vertex iterator for the abstractGeometry and build our own list
currentTracePolyline = []
vi = traceFeature.geometry().vertices()
while vi.hasNext():
currentTracePolyline.append(vi.next())
else:
continue
else:
continue
if (floatConvError):
iface.messageBar().pushMessage("Warning", "Some 'From' or 'To' values are not numbers", level=Qgis.Warning)
if (nullDataError):
iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'From' or 'To' values are NULL. These have been skipped", level=Qgis.Warning)
# Calculate indices spanning the from and to depths, then linearly interpolate a position
try:
pFrom, iFrom = interpPolyline(dataFrom, currentTraceSegLength, currentTracePolyline)
except:
# self.logFile.write("Error interpolating from polyline for hole: %s From: %f in row: %d.\n" % (dataId, dataFrom, index))
continue
if (idxTo > -1):
try:
pTo, iTo = interpPolyline(dataTo, currentTraceSegLength, currentTracePolyline)
except:
# self.logFile.write("Error interpolating from polyline for hole: %s To: %f in row: %d.\n" % (dataId, dataTo, index))
continue
# Set the geometry for the new downhole feature
if (idxTo > -1):
# Create line representing the downhole value using From and To
pointList = []
# Add the first (From) point to the list
pointList.append(pFrom)
# Add intervening points and last point if this is an interval
if (idxTo > -1):
# Add all the intermediate points (so a long interval accurately reflects the bend of the hole)
if math.floor(iTo) - math.ceil(iFrom) > self.desurveyLength:
for i in range(math.ceil(iFrom), math.floor(iTo)):
pointList.append(currentTracePolyline[i])
# Add the last (To) point
pointList.append(pTo)
feature.setGeometry(QgsGeometry.fromPolyline(pointList))
else:
feature.setGeometry(QgsGeometry(QgsPoint(pFrom.x(), pFrom.y(), pFrom.z(), wkbType = QgsWkbTypes.PointZ)))
# Create a list of the attributes to be included in new file
# These are just copied from the original down hole layer
# according to whether the user selected the check boxes
attList = []
for idx in idxAttList:
attList.append(attrs[idx])
# Also append the 3D desurveyed From, To and Mid points
if (idxTo > -1):
idxLast = len(pointList) - 1
attList.append(pointList[0].x())
attList.append(pointList[0].y())
attList.append(pointList[0].z())
attList.append(pointList[idxLast].x())
attList.append(pointList[idxLast].y())
attList.append(pointList[idxLast].z())
attList.append((pointList[0].x()+pointList[idxLast].x())*0.5)
attList.append((pointList[0].y()+pointList[idxLast].y())*0.5)
attList.append((pointList[0].z()+pointList[idxLast].z())*0.5)
else:
attList.append(pFrom.x())
attList.append(pFrom.y())
attList.append(pFrom.z())
# Set the attributes for the new feature
feature.setAttributes(attList)
# Add the new feature to the new Trace_ layer
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
# Flush the log file in case anything was written
# self.logFile.flush()
# Build the new filename for saving to disk. We are using GeoPackages
path=self.desurveyLayer.dataProvider().dataSourceUri()
fileName=os.path.join(os.path.split(path)[0], self.desurveyLayer.name())
fileName = fileName.replace("_Desurvey","_Downhole")
fileName = uriToFile(fileName + "_%s" % (self.dataSuffix))
# Generate a layer label
label = os.path.splitext(os.path.basename(fileName))[0]
# Remove trace layer from project if it already exists
oldLayer = getLayerByName(label)
QgsProject.instance().removeMapLayer(oldLayer)
#Save memory layer to Geopackage file
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.includeZ = True
# options.overrideGeometryType = memLayer.wkbType()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
# error = QgsVectorFileWriter.writeAsVectorFormatV3(layer, fileName, QgsProject.instance().transformContext(), options)
error = QgsVectorFileWriter.writeAsVectorFormat(layer, fileName, "CP1250", self.desurveyLayer.crs(), layerOptions=['OVERWRITE=YES'])
# Load the one we just saved and add it to the map
layer = QgsVectorLayer(fileName+".gpkg", label)
QgsProject.instance().addMapLayer(layer)
# Create the down hole data (interval) traces
def createDownholePoints(self):
# Check that desurvey layer is available
if not self.desurveyLayer.isValid() or not self.dataLayer.isValid():
return
# Set up a progress display
pd = QProgressDialog()
pd.setAutoReset(False)
pd.setWindowTitle("Build Downhole Points Layer")
pd.setMinimumWidth(500)
pd.setMinimum(0)
pd.setMaximum(self.desurveyLayer.featureCount())
pd.setValue(0)
#Create a new memory layer
layer = QgsVectorLayer("PointZ?crs=EPSG:4326", "geoscience_Temp", "memory")
layer.setCrs(self.desurveyLayer.crs())
atts = []
# Also add fields for the desurveyed coordinates
atts.append(QgsField("CollarID", QVariant.String, "string", 16))
atts.append(QgsField("Depth", QVariant.Double, "double", 12, 3))
atts.append(QgsField("x", QVariant.Double, "double", 12, 3))
atts.append(QgsField("y", QVariant.Double, "double", 12, 3))
atts.append(QgsField("z", QVariant.Double, "double", 12, 3))
# Add all the attributes to the new layer
dp = layer.dataProvider()
dp.addAttributes(atts)
# Tell the vector layer to fetch changes from the provider
layer.updateFields()
# Get the fields from the desurveyed trace layer
tdp = self.desurveyLayer.dataProvider()
idxTraceId = tdp.fieldNameIndex("CollarID")
idxTraceSegLength = tdp.fieldNameIndex("SegLength")
updateInt = max(100, long(self.desurveyLayer.featureCount()/100))
for index, f in enumerate(self.desurveyLayer.getFeatures()):
# Update the Progress bar
if index%updateInt == 0:
pd.setValue(index)
qApp.processEvents()
# Is the feature valid?
if f.isValid():
collarId = str(f.attributes()[idxTraceId])
segLength = f.attributes()[idxTraceSegLength]
tracePolyline = []
vi = f.geometry().vertices()
while vi.hasNext():
tracePolyline.append(vi.next())
else:
continue
dist = 0.0
nodeDist = 0.0
node = 0
# Walk along the polyline
while node < len(tracePolyline) - 1:
p0 = tracePolyline[node]
p1 = tracePolyline[node + 1]
# Length of this segment. It can be different if it's the last segment
segl = segLength
if node < len(tracePolyline) - 2:
dx = p1.x() - p0.x();
dy = p1.y() - p0.y();
dz = p1.z() - p0.z();
segl = math.sqrt(dx * dx + dy * dy + dz * dz)
# What is the total distance along the line of the next node
nodeDist2 = nodeDist + segl
# If our required distance is less than the next node, then we need to insert points
# while dist < nodeDist2 or (self.pointIncEOH and (dist == nodeDist2)):
# while dist < nodeDist2 or (self.pointIncEOH and node == (len(tracePolyline) - 2) and dist == nodeDist2):
while dist < nodeDist2:
if dist > 0.0 or self.pointIncZero:
ratio = (dist - nodeDist) / segl
p = QgsPoint(p0.x() + (p1.x() - p0.x()) * ratio, p0.y() + (p1.y() - p0.y()) * ratio, p0.z() + (p1.z() - p0.z()) * ratio, wkbType = QgsWkbTypes.PointZ)
# insert the point
feature = QgsFeature()
feature.setGeometry(QgsGeometry(p))
attList = []
attList.append(collarId)
attList.append(dist)
attList.append(p.x())
attList.append(p.y())
attList.append(p.z())
# Set the attributes for the new feature
feature.setAttributes(attList)
# Add the new feature to the new Trace_ layer
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
# Increment the desired point distance
dist = dist + self.pointSeparation
# There are no more points to go in this segment, so increment the segment
node = node + 1
nodeDist = nodeDist + segl
if self.pointIncEOH and dist > nodeDist:
p0 = tracePolyline[-1]
p = QgsPoint(p0.x(), p0.y(), p0.z(), wkbType = QgsWkbTypes.PointZ)
# insert the point
feature = QgsFeature()
feature.setGeometry(QgsGeometry(p))
attList = []
attList.append(collarId)
attList.append(nodeDist)
attList.append(p.x())
attList.append(p.y())
attList.append(p.z())
# Set the attributes for the new feature
feature.setAttributes(attList)
# Add the new feature to the new Trace_ layer
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
# Build the new filename for saving to disk. We are using GeoPackages
path=self.desurveyLayer.dataProvider().dataSourceUri()
fileName=os.path.join(os.path.split(path)[0], self.desurveyLayer.name())
fileName = fileName.replace("_Desurvey","_DepthTicks")
fileName = uriToFile(fileName)
# Generate a layer label
label = os.path.splitext(os.path.basename(fileName))[0]
# Remove trace layer from project if it already exists
oldLayer = getLayerByName(label)
QgsProject.instance().removeMapLayer(oldLayer)
#Save memory layer to Geopackage file
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.includeZ = True
# options.overrideGeometryType = memLayer.wkbType()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
# error = QgsVectorFileWriter.writeAsVectorFormatV3(layer, fileName, QgsProject.instance().transformContext(), options)
error = QgsVectorFileWriter.writeAsVectorFormat(layer, fileName, "CP1250", self.desurveyLayer.crs(), layerOptions=['OVERWRITE=YES'])
# Load the one we just saved and add it to the map
layer = QgsVectorLayer(fileName+".gpkg", label)
QgsProject.instance().addMapLayer(layer)
# Create the down hole data (interval) traces
def createDownholeStructure(self):
# self.logFile.write("\nCreating Downhole Structure Layer.\n")
# self.logFile.flush()
# Check that desurvey layer is available
if not self.desurveyLayer.isValid() or not self.structureLayer.isValid():
return
# Set up a progress display
pd = QProgressDialog()
pd.setAutoReset(False)
pd.setWindowTitle("Build Downhole Structure Layer")
pd.setMinimumWidth(500)
pd.setMinimum(0)
pd.setMaximum(self.structureLayer.featureCount())
pd.setValue(0)
# Create memory layer
layer = self.createDownholeStructureLayer()
# Get the fields from the data layer
dp = self.structureLayer.dataProvider()
idxId = dp.fieldNameIndex(self.structureId)
idxDepth = dp.fieldNameIndex(self.structureDepth)
idxAlpha = dp.fieldNameIndex(self.structureAlpha)
idxBeta = dp.fieldNameIndex(self.structureBeta)
# Create a list of attribute indices from the desired attribute field names
idxAttList = []
for name in self.structureFields:
idx = dp.fieldNameIndex(name)
idxAttList.append(idx)
# Get the fields from the desurveyed trace layer
tdp = self.desurveyLayer.dataProvider()
idxTraceId = tdp.fieldNameIndex("CollarID")
idxTraceSegLength = tdp.fieldNameIndex("SegLength")
# Store the relevant desurveyed drill trace so that it's persistent between loops
# This way we should be able to re-use it instead of re-fetching it.
traceFeature = QgsFeature()
currentTraceCollar = ""
currentTraceSegLength = 1.0
currentTracePolyline = None
#Loop through downhole layer features
# Calculate an optimum update interval for the progress bar (updating gui items is expensive)
updateInt = max(100, long(self.structureLayer.featureCount()/100))
floatConvError = False
nullDataError = False
for index, df in enumerate(self.structureLayer.getFeatures()):
# Update the Progress bar
if index%updateInt == 0:
pd.setValue(index)
qApp.processEvents()
# Variable to hold a feature
feature = QgsFeature()
# get the feature's attributes
attrs = df.attributes()
# Check all the data is valid
dataId = str(attrs[idxId])
dataDepth = NULL
dataAlpha = NULL
dataBeta = NULL
try:
dataDepth = float(attrs[idxDepth])
dataAlpha = float(attrs[idxAlpha])
dataBeta = float(attrs[idxBeta])
except:
floatConvError = True
if (dataId==NULL) or (dataDepth==NULL) or (dataAlpha==NULL) or (dataBeta==NULL):
nullDataError = True
continue
dataId = dataId.strip()
# iface.messageBar().pushMessage("Debug", "%s %f %f %f"%(dataId, dataDepth, dataAlpha, dataBeta), level=Qgis.Info)
# Get the desurvey drill trace relevant to this collar, checking first that we don't already have it
if not currentTraceCollar == dataId:
# Get the correct trace feature via a query
query = '''"CollarID" = '%s' ''' % (dataId)
selection = self.desurveyLayer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
# We have a selection of features
if selection.isValid():
# There should be just 1, so get the first feature
selection.nextFeature(traceFeature)
# Is the feature valid?
if traceFeature.isValid():
# Update information for the current feature
currentTraceCollar = dataId
currentTraceSegLength = traceFeature.attributes()[idxTraceSegLength]
# The normal asPolyline() function only returns QgsPointXY, yet we need the Z coordinate as well
# We therefore get a vertex iterator for the abstractGeometry and build our own list
currentTracePolyline = []
vi = traceFeature.geometry().vertices()
while vi.hasNext():
currentTracePolyline.append(vi.next())
else:
continue
else:
continue
if (floatConvError):
iface.messageBar().pushMessage("Warning", "Some 'Depth', 'Alpha' or 'Beta' values are not numbers", level=Qgis.Warning)
if (nullDataError):
iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'Alpha' or 'Beta' values are NULL. These have been skipped", level=Qgis.Warning)
# Create line representing the downhole value using From and To
# pointList = []
# Calculate indices spanning the from and to depths, then linearly interpolate a position
try:
pDepth, iDepth = interpPolyline(dataDepth, currentTraceSegLength, currentTracePolyline)
except:
# self.logFile.write("Error interpolating from polyline for hole: %s From: %f in row: %d.\n" % (dataId, dataDepth, index))
continue
# Get the desurveyed core axis vector
vCore = np.array([0.0, 0.0, 1.0])
try:
vCore = coreVector(dataDepth, currentTraceSegLength, currentTracePolyline)
except:
# self.logFile.write("Error getting up vector: %s To: %f in row: %d.\n" % (dataId, dataDepth, index))
continue
# We can't work with vertical drill holes
if abs(np.dot(vCore, np.array([0.0, 0.0, 1.0]))) > 0.9999:
continue
# Create a quat to rotate an alpha = 0, beta = 0 plane normal into the measured plane normal
# We start with the measured plane being parallel with a vertical drill hole with the normal pointing north
n = np.array([0.0, 1.0, 0.0])
# Rotate the plane according to the alpha angle
q = Quaternion(axis=[-1.0, 0.0, 0.0], degrees=dataAlpha)
n = q.rotate(n)
# Rotate the plane according to the beta angle
q = Quaternion(axis=[0.0, 0.0, -1.0], degrees=dataBeta)
n = q.rotate(n)
# Calculate the dip angle of the desurveyed core by comparing its down vector with vertical
a = math.acos(np.dot(np.array([0.0, 0.0, -1.0]), vCore))
# Rotate the measured plane to account for the core's dip
q = Quaternion(axis=[1.0, 0.0, 0.0], radians=a)
n = q.rotate(n)
# Calculate the dip direction (azimuth) of the core by setting the z component to 0
dd = np.array([vCore[0], vCore[1], 0.0])
# and normalise
dd = dd/np.linalg.norm(dd)
# Calculate the angle in the horizontal plane between the core azimuth and north
a = math.acos(np.dot(np.array([0.0, 1.0, 0.0]), dd))
# Cos only covers 0 - 180 degrees, so check if should be in the -180 - 0 range
if vCore[0] < 0:
a = -a
# Rotate the measured plane by the core azimuth
q = Quaternion(axis=[0.0, 0.0, -1.0], radians=a)
n = q.rotate(n) # Final measured plane normal
#Dips are always measured from 0-90 degrees downwards, so lets check if the rotations
# have turned the plane upside down and flip it over if it has.
if n[2] < 0:
n = -n
# Calculate dip direction from the x & y components of the normal
dipdir = math.degrees(math.atan2(n[0], n[1]))
# And make it 0 - 360 instead of -180 - 180
if dipdir < 0:
dipdir = 360 + dipdir
# The dip is the angle between the normal and up vector
dip = math.degrees(math.acos(np.dot(np.array([0.0, 0.0, 1.0]), n)))
# We need to calculate two more vectors so that we can draw symbols
# The strike vector is horizontal and the dip vector is vertical
vstrike = np.cross(n, dd)
vdip = np.cross(n, vstrike)
# qpstrike = QgsPoint(vstrike[0], vstrike[1], vstrike[2])
# qpdip = QgsPoint(vdip[0], vdip[1], vdip[2])
# Set the geometry for the new downhole feature
scale = self.structureScale
p0 = QgsPoint(pDepth.x() + vstrike[0] * scale + vdip[0] * scale, pDepth.y() + vstrike[1] * scale + vdip[1] * scale, pDepth.z() + vstrike[2] * scale + vdip[2] * scale)
p1 = QgsPoint(pDepth.x() - vstrike[0] * scale + vdip[0] * scale, pDepth.y() - vstrike[1] * scale + vdip[1] * scale, pDepth.z() - vstrike[2] * scale + vdip[2] * scale)
p2 = QgsPoint(pDepth.x() - vstrike[0] * scale - vdip[0] * scale, pDepth.y() - vstrike[1] * scale - vdip[1] * scale, pDepth.z() - vstrike[2] * scale - vdip[2] * scale)
p3 = QgsPoint(pDepth.x() + vstrike[0] * scale - vdip[0] * scale, pDepth.y() + vstrike[1] * scale - vdip[1] * scale, pDepth.z() + vstrike[2] * scale - vdip[2] * scale)
# pointList = [p0, p1, p2, p3, p0]
# poly = QgsPolygon()
# poly.insertVertex(QgsVertexId(0, 0, 0), p0)
# poly.insertVertex(QgsVertexId(0, 0, 1), p1)
# poly.insertVertex(QgsVertexId(0, 0, 2), p2)
# poly.insertVertex(QgsVertexId(0, 0, 3), p3)
# poly.insertVertex(QgsVertexId(0, 0, 4), p0)
wkt = 'POLYGONZ (('
wkt = wkt + '%f %f %f, '%(p0.x(), p0.y(), p0.z())
wkt = wkt + '%f %f %f, '%(p1.x(), p1.y(), p1.z())
wkt = wkt + '%f %f %f, '%(p2.x(), p2.y(), p2.z())
wkt = wkt + '%f %f %f, '%(p3.x(), p3.y(), p3.z())
wkt = wkt + '%f %f %f'%(p0.x(), p0.y(), p0.z())
wkt = wkt + '))'
# iface.messageBar().pushMessage("WKT: %s"%(wkt), level=Qgis.Info)
poly = QgsGeometry.fromWkt(wkt)
feature.setGeometry(QgsGeometry(poly))
# Create a list of the attributes to be included in new file
# These are just copied from the original down hole layer
# according to whether the user selected the check boxes
attList = []
for idx in idxAttList:
attList.append(attrs[idx])
# Also append the 3D desurveyed From, To and Mid points
attList.append(pDepth.x())
attList.append(pDepth.y())
attList.append(pDepth.z())
# attList.append(float(n[0]))
# attList.append(float(n[1]))
# attList.append(float(n[2]))
attList.append(dipdir)
attList.append(dip)
# Placeholder for section dip
attList.append(0.0)
# Set the attributes for the new feature
feature.setAttributes(attList)
# Add the new feature to the new Trace_ layer
layer.startEditing()
layer.addFeature(feature)
layer.commitChanges()
# Flush the log file in case anything was written
# self.logFile.flush()
# Build the new filename for saving to disk. We are using GeoPackages
path=self.desurveyLayer.dataProvider().dataSourceUri()
fileName=os.path.join(os.path.split(path)[0], self.desurveyLayer.name())
fileName = fileName.replace("_Desurvey","_Structure")
# Generate a layer label
label = os.path.splitext(os.path.basename(fileName))[0]
# Remove trace layer from project if it already exists
oldLayer = getLayerByName(label)
QgsProject.instance().removeMapLayer(oldLayer)
#Save memory layer to Geopackage file
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.includeZ = True
# options.overrideGeometryType = memLayer.wkbType()
options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
# error = QgsVectorFileWriter.writeAsVectorFormatV3(layer, fileName, QgsProject.instance().transformContext(), options)
error = QgsVectorFileWriter.writeAsVectorFormat(layer, fileName, "CP1250", self.desurveyLayer.crs(), layerOptions=['OVERWRITE=YES'])
# Load the one we just saved and add it to the map
layer = QgsVectorLayer(fileName+".gpkg", label)
QgsProject.instance().addMapLayer(layer)
def desurveyHole(self):
# Write to the log file
# self.logFile.write("\nDesurveying data.\n")
# self.logFile.flush()
# Set up a progress bar
pd = QProgressDialog()
pd.setAutoReset(False)
pd.setMinimumWidth(500)
pd.setMinimum(0)
# Get the relevant attribute indices
dp = self.collarLayer.dataProvider()
idxCollarId = dp.fieldNameIndex(self.collarId)
idxCollarEast = dp.fieldNameIndex(self.collarEast)
idxCollarNorth = dp.fieldNameIndex(self.collarNorth)
idxCollarElev = dp.fieldNameIndex(self.collarElev)
idxCollarDepth = dp.fieldNameIndex(self.collarDepth)
idxCollarAz = dp.fieldNameIndex(self.collarAz)
idxCollarDip = dp.fieldNameIndex(self.collarDip)
# Are we using azimuths and dips from the collar file?
useCollarAzDip = (idxCollarAz > -1) and (idxCollarDip > -1)
# Build Collar array (Id, east, north, elev, eoh, az, dip)
numCollars = self.collarLayer.featureCount()
arrCollar = []
# Update the progress bar
pd.setWindowTitle("Build Collar Array")
pd.setMaximum(numCollars)
pd.setValue(0)
floatConvError = False
nullDataError = False
# Create a new Collar 3D layer to hold 3D points. This will be used for section creation.
collar3D = self.createCollarLayer()
# Loop through the collar layer and build list of collars
for index, feature in enumerate(self.collarLayer.getFeatures()):
# Update progress bar
pd.setValue(index)
# get the feature's attributes
attrs = feature.attributes()
c = Collar()
# Check all the data is valid
c.id = str(attrs[idxCollarId])
try:
c.east = float(attrs[idxCollarEast])
c.north = float(attrs[idxCollarNorth])
c.elev = float(attrs[idxCollarElev])
c.depth = float(attrs[idxCollarDepth])
except:
floatConvError = True
if (c.id==NULL) or (c.east==NULL) or (c.north==NULL) or (c.elev==NULL) or (c.depth==NULL):
nullDataError = True
continue
c.id = c.id.strip()
if useCollarAzDip:
c.az = attrs[idxCollarAz]
if c.az==NULL:
c.az = 0.0
c.dip = attrs[idxCollarDip]
if c.dip==NULL:
c.dip = -90.0 if self.downDipNegative else 90.0
arrCollar.append(c)
#Create a new 3D point feature and copy the attributes
f = QgsFeature()
# p = QPointF(c.east, c.north, c.elev)
f.setGeometry(QgsGeometry(QgsPoint(c.east, c.north, c.elev, wkbType = QgsWkbTypes.PointZ)))
# Add in the field attributes
f.setAttributes(attrs)
# Add the feature to the layer
collar3D.startEditing()
collar3D.addFeature(f)
collar3D.commitChanges()
if (floatConvError):
iface.messageBar().pushMessage("Warning", "Some 'East', 'North', 'Collar' or 'Depth' values are not numbers", level=Qgis.Warning)
if (nullDataError):
iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'East', 'North', 'Collar' or 'Depth' values are NULL. These have been skipped", level=Qgis.Warning)
# Build Survey array (Id, depth, az, dip)
arrSurvey = []
if self.surveyLayer is not None and self.surveyLayer.isValid():
numSurveys = self.surveyLayer.featureCount()
# Get the attribute indices
dp = self.surveyLayer.dataProvider()
idxSurveyId = dp.fieldNameIndex(self.surveyId)
idxSurveyDepth = dp.fieldNameIndex(self.surveyDepth)
idxSurveyAz = dp.fieldNameIndex(self.surveyAz)
idxSurveyDip = dp.fieldNameIndex(self.surveyDip)
# Update progress bar
pd.setWindowTitle("Build Survey Array")
pd.setMaximum(numSurveys)
pd.setValue(0)
floatConvError = False
nullDataError = False
#Loop through Survey layer and build list of surveys
for index, feature in enumerate(self.surveyLayer.getFeatures()):
pd.setValue(index)
ok = True
# get the feature's attributes
attrs = feature.attributes()
s = Survey()
s.id = str(attrs[idxSurveyId])
try:
s.depth = float(attrs[idxSurveyDepth])
s.az = float(attrs[idxSurveyAz])
s.dip = float(attrs[idxSurveyDip])
except:
ok = False
iface.messageBar().pushMessage("Warning", "HoleID %s Depth %f"%(s.id, s.depth), level=Qgis.Warning)
floatConvError = True
if (s.id==NULL) or (s.depth==NULL) or (s.az==NULL) or (s.dip==NULL):
ok = False
nullDataError = True
continue
if ok:
s.id = s.id.strip()
arrSurvey.append(s)
if (floatConvError):
iface.messageBar().pushMessage("Warning", "Some survey 'Depth', 'Azimuth' or 'Dip' values are not numbers", level=Qgis.Warning)
if (nullDataError):
iface.messageBar().pushMessage("Warning", "Some 'HoleId', 'Depth', 'Azimuth' or 'Dip' values are NULL. These have been skipped", level=Qgis.Warning)
# Create new layer for the desurveyed 3D coordinates. PolyLine, 1 row per collar, 2 attribute (Id, Segment Length)
self.createDesurveyLayer()
#Loop through collar list and desurvey each one
# Update Progress bar
pd.setWindowTitle("Desurvey Progress")
pd.setMaximum(len(arrCollar))
pd.setValue(0)
#Calculate optimum update interval
updateInt = max(100, int(len(arrCollar)/100))
# Enter collar loop
for index, collar in enumerate(arrCollar):
pd.setValue(index)
# Force update the progress bar visualisation every 1% as it normally only happens in idle time
if index%updateInt == 0:
qApp.processEvents()
# Check the id exists
if not collar.id:
continue
#Build array of surveys for this collar, including the top az and dip in collar layer. Repeat last survey at EOH.
surveys = []
zeroDepth = False;
if len(arrSurvey) > 0:
# Harvest surveys for this collar from Survey layer list