-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGeoSubSampler.py
More file actions
1720 lines (1514 loc) · 74.5 KB
/
Copy pathGeoSubSampler.py
File metadata and controls
1720 lines (1514 loc) · 74.5 KB
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 -*-
"""
/***************************************************************************
GeoSubSampler
A QGIS plugin
Subsamples geological orientations, faults and polygons
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2025-07-28
git sha : $Format:%H$
copyright : (C) 2025 by Ranee Joshi
email : raneejoshi@gmail.com
***************************************************************************/
/***************************************************************************
* *
* 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 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import QgsProject, QgsMapLayerProxyModel, Qgis
from qgis.core import QgsVectorLayer, QgsProject
from qgis.PyQt.QtWidgets import QDockWidget
from qgis.core import QgsMessageLog, Qgis
# Qt5/Qt6 Compatibility Layer
try:
# Try Qt6 style first
_test = Qt.DockWidgetArea.RightDockWidgetArea
# Qt6 detected
QT6 = True
# Qt6 style enums are already available
RightDockWidgetArea = Qt.DockWidgetArea.RightDockWidgetArea
except AttributeError:
# Qt5 detected
QT6 = False
# Qt5 style enums
RightDockWidgetArea = Qt.RightDockWidgetArea
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the DockWidget
from .GeoSubSampler_dockwidget import GeoSubSamplerDockWidget
import os.path
import tempfile
import shutil
from .calcs.StructuralPolygonSubSampler import StructuralPolygonSubSampler
from .calcs.PolygonTriangulator import PolygonTriangulator
from .calcs.FaultLineMerger import FaultLineMerger
from .calcs.FaultLengths import FaultLengths
from .calcs.FaultsGraph import FaultsGraph
from .calcs.FaultStratOffset import FaultStratOffset
from .calcs.FaultClusterOrientation import FaultsOrientations
from .calcs.FirstOrderOrientation import SubsamplingEngine, save_grid_to_shapefile
from .calcs.TopferPillewizer import topfer_count, scale_iterations, scale_points_tp, scale_lines_tp, scale_polygons_tp
from .calcs.PolygonSimplification import SimplificationEngine, vector_simplify_file_two_stage
import geopandas as gpd
import os
import random
import re
import time
import math
import pandas as pd
import numpy as np
class GeoSubSampler:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value("locale/userLocale")[0:2]
locale_path = os.path.join(
self.plugin_dir, "i18n", "GeoSubSampler_{}.qm".format(locale)
)
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr("&GeoSubSampler")
# TODO: We are going to let the user set this up in a future iteration
self.toolbar = self.iface.addToolBar("GeoSubSampler")
self.toolbar.setObjectName("GeoSubSampler")
# print "** INITIALIZING GeoSubSampler"
self.pluginIsActive = False
self.dockwidget = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate("GeoSubSampler", message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None,
):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPluginToMenu(self.menu, action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ":/plugins/GeoSubSampler/icon.png"
self.add_action(
icon_path,
text=self.tr("GeoSubSampler"),
callback=self.run,
parent=self.iface.mainWindow(),
)
# --------------------------------------------------------------------------
def onClosePlugin(self):
"""Cleanup necessary items here when plugin dockwidget is closed"""
# print "** CLOSING GeoSubSampler"
# disconnects
self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
# remove this statement if dockwidget is to remain
# for reuse if plugin is reopened
# Commented next statement since it causes QGIS crashe
# when closing the docked window:
# self.dockwidget = None
self.pluginIsActive = False
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
# print "** UNLOAD GeoSubSampler"
for action in self.actions:
self.iface.removePluginMenu(self.tr("&GeoSubSampler"), action)
self.iface.removeToolBarIcon(action)
# remove the toolbar
del self.toolbar
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
def removeAllLayersByName(self, layerName):
"""
Remove all layers with the given name
"""
layers = QgsProject.instance().mapLayersByName(layerName)
if layers:
for layer in layers:
QgsProject.instance().removeMapLayer(layer.id())
# print(f"Removed {len(layers)} layer(s) named '{layerName}'")
return len(layers)
else:
print(f"No layers found with name '{layerName}'")
return 0
@staticmethod
def _shapefile_safe_columns(columns):
"""
Map each column name to a shapefile/DBF-safe (<=10 char) name,
de-duplicating collisions with a numeric suffix. Applied ourselves
before writing, so the result is exactly known (rather than relying
on whatever the OGR shapefile driver would silently truncate names to).
"""
seen = {}
mapping = {}
for col in columns:
if col == 'geometry':
mapping[col] = col
continue
candidate = str(col)[:10]
n = 1
while candidate in seen and seen[candidate] != col:
suffix = f"_{n}"
candidate = str(col)[:10 - len(suffix)] + suffix
n += 1
seen[candidate] = col
mapping[col] = candidate
return mapping
def _resolved_source(self, layer):
"""
Return a .shp path for `layer`, usable with os.path.exists()/gpd.read_file().
Every tool in this plugin assumes a shapefile-backed source. A
GeoPackage layer's source string (e.g. "C:/foo.gpkg|layername=bar")
fails os.path.exists() outright, so such layers were silently
treated as missing and skipped. If the source isn't already a .shp,
export the layer's current features to a sibling .shp next to the
geopackage (never written back into it) and reuse that file on
repeat runs. Field names longer than the 10-char shapefile/DBF limit
are pre-truncated ourselves (see _shapefile_safe_columns) and the
original->truncated mapping is cached for _resolved_field() to use.
"""
source = layer.source()
path_part = source.split('|')[0]
if path_part.lower().endswith('.shp'):
return path_part
if not os.path.exists(path_part):
return source
out_dir = os.path.dirname(path_part)
base = os.path.splitext(os.path.basename(path_part))[0]
safe_name = re.sub(r'[^A-Za-z0-9_]+', '_', layer.name()).strip('_')
out_path = os.path.join(out_dir, f"{base}_{safe_name}.shp")
if not hasattr(self, '_field_name_maps'):
self._field_name_maps = {}
if not os.path.exists(out_path) or out_path not in self._field_name_maps:
match = re.search(r'layername=([^|]+)', source)
layername = match.group(1) if match else None
try:
gdf = (gpd.read_file(path_part, layer=layername) if layername
else gpd.read_file(path_part))
field_map = self._shapefile_safe_columns(gdf.columns)
self._field_name_maps[out_path] = field_map
if not os.path.exists(out_path):
if any(k != v for k, v in field_map.items()):
gdf = gdf.rename(columns=field_map)
gdf.to_file(out_path, driver='ESRI Shapefile')
except Exception as exc:
print(f"Could not export layer '{layer.name()}' to shapefile: {exc}")
return source
return out_path
def _resolved_field(self, layer, field_name):
"""
Translate a field combo-box selection into the column name actually
present in `layer`'s resolved/materialized data. Handles two
independent name changes:
1. QgsFieldComboBox displays a field's alias if one is set on the
layer, not its real name — resolved via QgsFields.lookupField(),
which is alias-aware (common on curated/compiled datasets where
friendly aliases are configured over cryptic real column names).
2. _resolved_source's shapefile export truncates real names longer
than 10 characters — resolved via its cached field-name map.
"""
if not field_name:
return field_name
real_name = field_name
try:
fields = layer.fields()
idx = fields.lookupField(field_name)
if idx >= 0:
real_name = fields.at(idx).name()
except Exception:
pass
out_path = self._resolved_source(layer)
field_map = getattr(self, '_field_name_maps', {}).get(out_path)
if field_map and real_name in field_map:
return field_map[real_name]
return real_name
def setUpPointSampler(self, checkFields=True):
layerName = self.dockwidget.mMapLayerComboBox_points.currentText()
dip_col = self.dockwidget.mFieldComboBox_dip.currentText()
dip_dir_col = self.dockwidget.mFieldComboBox_dip_dir.currentText()
if layerName == "":
return False
if os.path.exists(self._resolved_source(self.points_layer)):
gdf = gpd.read_file(self._resolved_source(self.points_layer))
if (dip_col == "" or dip_dir_col == "") and checkFields:
self.iface.messageBar().pushMessage(
"Please define dip & dip dir/strike fields before continuing!",
level=Qgis.Warning,
duration=15,
)
return False
elif dip_col == "" or dip_dir_col == "":
dip_col = gdf.columns[1]
dip_dir_col = gdf.columns[2]
else:
# Field combo boxes may show a field's alias rather than its
# real name, and/or the real name may have been shortened by
# _resolved_source's shapefile export (10-char DBF limit) —
# _resolved_field() untangles both.
dip_col = self._resolved_field(self.points_layer, dip_col)
dip_dir_col = self._resolved_field(self.points_layer, dip_dir_col)
missing = [c for c in (dip_col, dip_dir_col) if c not in gdf.columns]
if missing:
self.iface.messageBar().pushMessage(
f"T&P: field(s) {missing} not found in the loaded data. "
f"Available columns: {list(gdf.columns)}",
level=Qgis.Critical, duration=20)
return False
# Add coordinate columns from geometry (engine needs these for grid operations)
gdf = gdf.copy()
gdf['EASTING'] = gdf.geometry.x
gdf['NORTHING'] = gdf.geometry.y
# Drop features with nulls in dip/dip-dir before they reach the engine.
# Unfiltered nulls become NaN vector components; pandas' skipna sum then
# silently excludes them from their grid cell's mean/Kent calculation,
# which can make whole cells vanish from the subsampled output.
n_before = len(gdf)
gdf = gdf.dropna(subset=[dip_col, dip_dir_col, 'EASTING', 'NORTHING']).copy()
n_dropped = n_before - len(gdf)
if n_dropped:
self.iface.messageBar().pushMessage(
f"{n_dropped} point(s) with null dip/dip-dir/coordinates "
f"dropped before subsampling.",
level=Qgis.Warning, duration=10)
# If input is strike, convert to dip direction (dip_dir = strike - 90)
if not self.dockwidget.checkBox_dip_dir.isChecked():
gdf['_eff_dipdir'] = (gdf[dip_dir_col].astype(float) - 90) % 360
eff_dipdir_col = '_eff_dipdir'
else:
eff_dipdir_col = dip_dir_col
engine = SubsamplingEngine(
dip=dip_col, dipdir=eff_dipdir_col,
easting='EASTING', northing='NORTHING'
)
return (gdf, engine, dip_col, dip_dir_col)
else:
self.iface.messageBar().pushMessage(
"Sorry, only layers saved to disk as a shapefile can be processed!",
level=Qgis.Warning,
duration=15,
)
return False
def _add_layer_with_style(self, new_layer, source_layer, fail_msg=''):
"""Add new_layer to the project and copy style from source_layer."""
if not new_layer.isValid():
print(f"Failed to load layer: {fail_msg or new_layer.name()}")
return
try:
from qgis.PyQt.QtXml import QDomDocument
doc = QDomDocument()
source_layer.exportNamedStyle(doc)
new_layer.importNamedStyle(doc)
except Exception:
pass
QgsProject.instance().addMapLayer(new_layer)
def finalisePointSampler(self, gdf2, qgis_layer, name, param=0):
layer_path = os.path.dirname(self._resolved_source(qgis_layer))
if(param==0):
param2 = ''
else:
param2="_"+ str(int(param))
new_path = (
layer_path
+ "/"
+ qgis_layer.name()
+ "_"
+ name
+ param2
+ ".shp"
)
# print("new_path:", new_path)
if os.path.exists(new_path):
random_5_digit_integer = random.randint(10000, 99999)
new_path = (
layer_path
+ "/"
+ qgis_layer.name()
+ "_"
+ name
+ param2
+ "_"
+ str(random_5_digit_integer)
+ ".shp"
)
# print("new_path_2:", new_path)
# Write GeoPandas back to file
gdf2.to_file(new_path, driver="ESRI Shapefile")
# reload as layer
upscaled_layer = QgsVectorLayer(
new_path, qgis_layer.name() + "_" + name + str(param2), "ogr"
)
self._add_layer_with_style(upscaled_layer, qgis_layer,
qgis_layer.name() + "_" + name)
def decimation(self):
result = self.setUpPointSampler()
if not result:
return
gdf, engine, dip_col, dip_dir_col = result
n = int(self.dockwidget.lineEdit_rate.text())
tmpdir = tempfile.mkdtemp()
try:
gdf2 = engine.decimation(gdf, n=n, path_out=tmpdir)
gdf2 = gdf2.set_crs(gdf.crs, allow_override=True)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
gdf2 = gdf2.drop(columns=[c for c in ['EASTING', 'NORTHING', '_eff_dipdir'] if c in gdf2.columns])
self.finalisePointSampler(gdf2, self.points_layer, "decimate", n)
def stochastic(self):
result = self.setUpPointSampler(False)
if not result:
return
gdf, engine, dip_col, dip_dir_col = result
retain_percentage = float(self.dockwidget.mQgsDoubleSpinBox_percent.value())
frac = retain_percentage / 100.0
tmpdir = tempfile.mkdtemp()
try:
gdf2 = engine.stochastic(gdf, frac=frac, random_state=int(time.time()),
path_out=tmpdir)
gdf2 = gdf2.set_crs(gdf.crs, allow_override=True)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
gdf2 = gdf2.drop(columns=[c for c in ['EASTING', 'NORTHING', '_eff_dipdir'] if c in gdf2.columns])
self.finalisePointSampler(gdf2, self.points_layer, "stochastic", retain_percentage)
def _count_gridcell_output(self, run_fn, gdf, min_x, max_x, min_y, max_y, cs):
"""Run engine grid-cell method at cell size cs and return valid point count."""
tmpdir = tempfile.mkdtemp()
try:
file = run_fn(gdf, min_x, max_x, min_y, max_y, n=cs, path_out=tmpdir)
df = pd.read_csv(os.path.join(tmpdir, file + ".csv"))
return int((df['DIP'] != -999).sum()) if not df.empty else 0
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def _find_grid_size_for_target(self, run_fn, gdf, min_x, max_x, min_y, max_y, target_n):
"""
Find the grid cell size that produces approximately target_n output points.
Strategy (Option 3):
1. Analytical estimate: cell_size = sqrt(area / target_n)
2. Proportional correction using actual vs target count
3. Binary search if still outside 15% tolerance
Returns (cell_size_in_crs_units, actual_count).
"""
area = (max_x - min_x) * (max_y - min_y)
tol = 0.15
def count(cs):
n = self._count_gridcell_output(run_fn, gdf, min_x, max_x, min_y, max_y, cs)
print(f" [target N] cell={cs:.2f} → {n} points")
return n
# Step 1: analytical estimate
cs1 = math.sqrt(area / max(1, target_n))
n1 = count(cs1)
if n1 == target_n or abs(n1 - target_n) <= tol * target_n:
return cs1, n1
# Step 2: proportional correction (count ∝ 1/cell_size²)
cs2 = cs1 * math.sqrt(max(1, n1) / max(1, target_n))
n2 = count(cs2)
if n2 == target_n or abs(n2 - target_n) <= tol * target_n:
return cs2, n2
# Step 3: binary search
# lo (small cell) → many points, hi (large cell) → few points
if cs1 < cs2:
lo, lo_n, hi, hi_n = cs1, n1, cs2, n2
else:
lo, lo_n, hi, hi_n = cs2, n2, cs1, n1
for _ in range(8):
if lo_n >= target_n:
break
lo /= 2
lo_n = count(lo)
for _ in range(8):
if hi_n <= target_n:
break
hi *= 2
hi_n = count(hi)
best_cs = cs2 if abs(n2 - target_n) < abs(n1 - target_n) else cs1
best_n = n2 if abs(n2 - target_n) < abs(n1 - target_n) else n1
for _ in range(12):
if hi - lo < 0.1:
break
mid = (lo + hi) / 2
mid_n = count(mid)
if abs(mid_n - target_n) < abs(best_n - target_n):
best_cs, best_n = mid, mid_n
if abs(mid_n - target_n) <= tol * target_n or mid_n == target_n:
break
if mid_n > target_n:
lo = mid
else:
hi = mid
return best_cs, best_n
def gridCellAveraging(self):
result = self.setUpPointSampler()
if not result:
return
gdf, engine, dip_col, dip_dir_col = result
self.point_layer = self.dockwidget.mMapLayerComboBox_points.currentLayer()
is_geographic = self.point_layer.crs().isGeographic()
bounds = gdf.total_bounds
min_x, max_x = int(bounds[0]), int(bounds[2]) + 1
min_y, max_y = int(bounds[1]), int(bounds[3]) + 1
if self.dockwidget.checkBox_target_n.isChecked():
target_n = self.dockwidget.spinBox_target_n.value()
grid_size, _ = self._find_grid_size_for_target(
engine.gridcell_average, gdf, min_x, max_x, min_y, max_y, target_n)
display_size = grid_size * 110000 if is_geographic else grid_size
self.dockwidget.lineEdit_grid_size.setText(f"{display_size:.0f}")
else:
grid_size = float(self.dockwidget.lineEdit_grid_size.text())
display_size = grid_size
if is_geographic:
grid_size = grid_size / 110000
tmpdir = tempfile.mkdtemp()
try:
file = engine.gridcell_average(gdf, min_x, max_x, min_y, max_y,
n=grid_size, path_out=tmpdir)
gdf2 = save_grid_to_shapefile(tmpdir, file)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
if gdf2 is not None:
gdf2 = gdf2.set_crs(gdf.crs, allow_override=True)
gdf2 = gdf2.drop(columns=['EASTING', 'NORTHING'], errors='ignore').rename(
columns={'DIP': dip_col, 'DIP_DIR': dip_dir_col})
self.finalisePointSampler(gdf2, self.points_layer, "gridCellAveraging", display_size)
def kent(self):
result = self.setUpPointSampler()
if not result:
return
gdf, engine, dip_col, dip_dir_col = result
self.point_layer = self.dockwidget.mMapLayerComboBox_points.currentLayer()
is_geographic = self.point_layer.crs().isGeographic()
bounds = gdf.total_bounds
min_x, max_x = int(bounds[0]), int(bounds[2]) + 1
min_y, max_y = int(bounds[1]), int(bounds[3]) + 1
if self.dockwidget.checkBox_target_n.isChecked():
target_n = self.dockwidget.spinBox_target_n.value()
grid_size, _ = self._find_grid_size_for_target(
engine.spherical_kent, gdf, min_x, max_x, min_y, max_y, target_n)
display_size = grid_size * 110000 if is_geographic else grid_size
self.dockwidget.lineEdit_grid_size_kent.setText(f"{display_size:.0f}")
else:
grid_size = float(self.dockwidget.lineEdit_grid_size_kent.text())
display_size = grid_size
if is_geographic:
grid_size = grid_size / 110000
tmpdir = tempfile.mkdtemp()
try:
file = engine.spherical_kent(gdf, min_x, max_x, min_y, max_y,
n=grid_size, path_out=tmpdir)
gdf2 = save_grid_to_shapefile(tmpdir, file)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
if gdf2 is not None:
gdf2 = gdf2.set_crs(gdf.crs, allow_override=True)
gdf2 = gdf2.drop(columns=['EASTING', 'NORTHING'], errors='ignore').rename(
columns={'DIP': dip_col, 'DIP_DIR': dip_dir_col})
self.finalisePointSampler(gdf2, self.points_layer, "grid_cell_kent", display_size)
def kentOutlier(self):
result = self.setUpPointSampler()
if not result:
return
gdf, engine, dip_col, dip_dir_col = result
self.point_layer = self.dockwidget.mMapLayerComboBox_points.currentLayer()
is_geographic = self.point_layer.crs().isGeographic()
bounds = gdf.total_bounds
min_x, max_x = int(bounds[0]), int(bounds[2]) + 1
min_y, max_y = int(bounds[1]), int(bounds[3]) + 1
if self.dockwidget.checkBox_target_n.isChecked():
target_n = self.dockwidget.spinBox_target_n.value()
grid_size, _ = self._find_grid_size_for_target(
engine.outlier_removal, gdf, min_x, max_x, min_y, max_y, target_n)
display_size = grid_size * 110000 if is_geographic else grid_size
self.dockwidget.lineEdit_grid_size_kent_2.setText(f"{display_size:.0f}")
else:
grid_size = float(self.dockwidget.lineEdit_grid_size_kent_2.text())
display_size = grid_size
if is_geographic:
grid_size = grid_size / 110000
tmpdir = tempfile.mkdtemp()
try:
file = engine.outlier_removal(gdf, min_x, max_x, min_y, max_y,
n=grid_size, path_out=tmpdir)
gdf2 = save_grid_to_shapefile(tmpdir, file)
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
if gdf2 is not None:
gdf2 = gdf2.set_crs(gdf.crs, allow_override=True)
gdf2 = gdf2.drop(columns=['EASTING', 'NORTHING'], errors='ignore').rename(
columns={'DIP': dip_col, 'DIP_DIR': dip_dir_col})
self.finalisePointSampler(gdf2, self.points_layer, "grid_cell_kentOutlier", display_size)
def _validate_dip_fields(self, require_points_layer):
"""
Fail fast with a clear message if dip/dip-direction fields aren't
set, before any processing (GeoPackage materialization, baseline
output writes, etc.) has run.
require_points_layer=True: a points layer must also be selected
(used by the standalone point-subsampling tools, where points are
the whole point of the operation).
require_points_layer=False: a points layer is optional (used by
T&P, which can run on just faults/polygons) — dip/dip-direction are
only required if a points layer has actually been chosen.
"""
layer_name = self.dockwidget.mMapLayerComboBox_points.currentText()
if not layer_name:
if require_points_layer:
self.iface.messageBar().pushMessage(
"Please select a points layer before continuing!",
level=Qgis.Warning, duration=15)
return False
return True
dip_col = self.dockwidget.mFieldComboBox_dip.currentText()
dip_dir_col = self.dockwidget.mFieldComboBox_dip_dir.currentText()
if not dip_col or not dip_dir_col:
self.iface.messageBar().pushMessage(
"Please define dip & dip dir/strike fields before continuing!",
level=Qgis.Warning, duration=15)
return False
return True
def subsamplePoints(self):
if self.dockwidget.radioButton_stochastic.isChecked():
self.stochastic()
return
if not self._validate_dip_fields(require_points_layer=True):
return
if self.dockwidget.radioButton_gsa.isChecked():
self.gridCellAveraging()
elif self.dockwidget.radioButton_kent.isChecked():
self.kent()
elif self.dockwidget.radioButton_kent_outlier.isChecked():
self.kentOutlier()
def processFaults(self):
if self.dockwidget.radioButton_fault_length.isChecked():
self.fault_Lengths()
elif self.dockwidget.radioButton_fault_graph.isChecked():
self.fault_Graph()
elif self.dockwidget.radioButton_fault_strat_offset.isChecked():
self.fault_strat_offset()
elif self.dockwidget.radioButton_fault_clusters.isChecked():
self.fault_ClusterOrientations()
def _tp_prepare_fault_attrs(self, gdf, method, fault_layer, polygon_layer,
strat1, strat2, strat3, strat4):
"""
Ensure gdf has the attribute column(s) required by the chosen TP fault
method. Runs the relevant calculation automatically if the column is
absent. Returns the (possibly enriched) GeoDataFrame unchanged when
no pre-computation is needed or when it fails.
"""
if method == 'graph' and 'edge_type' not in gdf.columns:
tmpdir = tempfile.mkdtemp()
try:
tmp_in = os.path.join(tmpdir, 'tp_graph.shp')
gdf.to_file(tmp_in)
FaultsGraph().CalcFaultsGraph(tmp_in)
# save_graph_to_shapefile prepends prefix_ to the basename:
# tp_graph_edges.shp → simplified_full_tp_graph_edges.shp
tmp_edges = os.path.join(tmpdir, 'simplified_full_tp_graph_edges.shp')
if os.path.exists(tmp_edges):
return gpd.read_file(tmp_edges).set_crs(gdf.crs, allow_override=True)
except Exception as exc:
print(f"T&P: graph pre-compute failed: {exc}")
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
elif method == 'clusters' and not any('cluster' in c.lower() for c in gdf.columns):
tmpdir = tempfile.mkdtemp()
try:
tmp_in = os.path.join(tmpdir, 'tp_cl.shp')
tmp_az = os.path.join(tmpdir, 'tp_cl_az.shp')
gdf.to_file(tmp_in)
fo = FaultsOrientations()
fo.add_endpoint_azimuth(tmp_in, tmp_az, azimuth_field='endpt_az')
best_gdf, best_score = None, -1
for n in range(2, 8):
try:
res = fo.analyze_shapefile_trends(
shapefile_path=tmp_az,
trend_field='endpt_az',
n_clusters=n,
)
sc = res.get('silhouette_score', -1)
if sc > best_score:
best_score, best_gdf = sc, res.get('gdf_with_clusters')
except Exception:
pass
if best_gdf is not None:
return best_gdf.set_crs(gdf.crs, allow_override=True)
except Exception as exc:
print(f"T&P: cluster pre-compute failed: {exc}")
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
elif method == 'strat_offset':
has_strat = any('strat' in c.lower() or 'offset' in c.lower()
for c in gdf.columns)
strat_columns = [c for c in [strat1, strat2, strat3, strat4] if c]
if (not has_strat and strat_columns
and polygon_layer and os.path.exists(self._resolved_source(polygon_layer))):
tmpdir = tempfile.mkdtemp()
try:
tmp_in = os.path.join(tmpdir, 'tp_so.shp')
tmp_out = os.path.join(tmpdir, 'tp_so_out.shp')
gdf.to_file(tmp_in)
FaultStratOffset().CalcFaultStratOffset(
tmp_in, self._resolved_source(polygon_layer), tmp_out,
strat_columns, offset_distance=50)
if os.path.exists(tmp_out):
return gpd.read_file(tmp_out).set_crs(gdf.crs, allow_override=True)
except Exception as exc:
print(f"T&P: strat-offset pre-compute failed: {exc}")
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
return gdf
def topferPillewizer(self):
"""
Apply Töpfer & Pillewizer (1966) scaling to all available layers.
TN = ON * (OS/TS)^(x/2) x=1 points, x=2 lines, x=3 polygons
The OS/TS ratio and optional increment are read from the T&P group.
If increment < ratio the method iterates through intermediate ratios
with step sizes growing by 1.5× each time.
"""
if not self._validate_dip_fields(require_points_layer=False):
return
try:
ratio = float(self.dockwidget.lineEdit_tp_ratio.text())
increment = float(self.dockwidget.lineEdit_tp_increment.text())
except ValueError:
self.iface.messageBar().pushMessage(
"T&P Scaling: enter valid numbers for ratio and increment.",
level=Qgis.Warning, duration=10)
return
if ratio <= 0 or ratio > 1:
self.iface.messageBar().pushMessage(
"T&P Scaling: OS/TS ratio must be in the range (0, 1].",
level=Qgis.Warning, duration=10)
return
iterations = scale_iterations(ratio, increment)
# --- Determine selected orientation method -----------------------
if self.dockwidget.radioButton_stochastic.isChecked():
point_method = 'stochastic'
elif self.dockwidget.radioButton_gsa.isChecked():
point_method = 'gridcell_average'
elif self.dockwidget.radioButton_kent.isChecked():
point_method = 'spherical_kent'
else:
point_method = 'outlier_removal'
# --- Determine selected fault method -----------------------------
if self.dockwidget.radioButton_fault_length.isChecked():
fault_method = 'length'
elif self.dockwidget.radioButton_fault_graph.isChecked():
fault_method = 'graph'
elif self.dockwidget.radioButton_fault_strat_offset.isChecked():
fault_method = 'strat_offset'
else:
fault_method = 'clusters'
# --- Polygon parameters (shared with existing tools) -------------
strat1 = self.dockwidget.mFieldComboBox_priority_1.currentText()
strat2 = self.dockwidget.mFieldComboBox_priority_2.currentText()
strat3 = self.dockwidget.mFieldComboBox_priority_3.currentText()
strat4 = self.dockwidget.mFieldComboBox_priority_4.currentText()
lithoname = self.dockwidget.mFieldComboBox_priority_5.currentText()
dyke_field = self.dockwidget.mFieldComboBox_dyke.currentText()
dyke_codes = (
self.dockwidget.plainTextEdit_dyke_Codes.toPlainText()
.replace(" ", "").split(",")
)
try:
dist_thresh = float(self.dockwidget.lineEdit_node_tolerance.text())
except ValueError:
dist_thresh = 1.0
fault_layer = self.dockwidget.mMapLayerComboBox_fault_polylines.currentLayer()
polygon_layer = self.dockwidget.mMapLayerComboBox_maps_polygons.currentLayer()
# Field combo boxes reflect the original layer's field names, which may
# have been shortened by _resolved_source's shapefile export (DBF field
# names are capped at 10 characters).
if polygon_layer:
strat1 = self._resolved_field(polygon_layer, strat1)
strat2 = self._resolved_field(polygon_layer, strat2)
strat3 = self._resolved_field(polygon_layer, strat3)
strat4 = self._resolved_field(polygon_layer, strat4)
lithoname = self._resolved_field(polygon_layer, lithoname)
dyke_field = self._resolved_field(polygon_layer, dyke_field)
# Pre-load GeoDataFrames once; each iteration feeds into the next
current_fault_gdf = None
current_polygon_gdf = None
if fault_layer and os.path.exists(self._resolved_source(fault_layer)):
current_fault_gdf = gpd.read_file(self._resolved_source(fault_layer))
current_fault_gdf = self._tp_prepare_fault_attrs(
current_fault_gdf, fault_method, fault_layer, polygon_layer,
strat1, strat2, strat3, strat4)
if polygon_layer and os.path.exists(self._resolved_source(polygon_layer)):
current_polygon_gdf = gpd.read_file(self._resolved_source(polygon_layer))
crs = polygon_layer.crs()
if crs.isGeographic():
dist_thresh = dist_thresh / 110000
# Points: set up engine and columns once; chain the GDF across iterations
current_pt_gdf = None
pt_engine = None
pt_dip_col = None
pt_dip_dir_col = None
pt_result = self.setUpPointSampler()
if pt_result:
current_pt_gdf, pt_engine, pt_dip_col, pt_dip_dir_col = pt_result
try:
grid_sz = float(self.dockwidget.lineEdit_grid_size.text())
except ValueError:
grid_sz = 5000.0
# Points are always subsampled from the original full dataset using the
# absolute cumulative ratio, so results at each scale are independent.
# Lines and polygons chain incrementally (each step feeds the next).
original_pt_gdf = current_pt_gdf # never mutated
# --- Ratio=1 baseline: all layers at full extent ---
if original_pt_gdf is not None:
self.finalisePointSampler(original_pt_gdf, self.points_layer, "tp_1")
if current_fault_gdf is not None:
ln_full = scale_lines_tp(current_fault_gdf, 1.0, fault_method)
layer_path = os.path.dirname(self._resolved_source(fault_layer))
out_name = f"{fault_layer.name()}_tp_1.shp"
out_path = os.path.join(layer_path, out_name)
if os.path.exists(out_path):
out_path = out_path.replace(
'.shp', f"_{random.randint(10000,99999)}.shp")
ln_full.to_file(out_path, driver='ESRI Shapefile')
ln_layer = QgsVectorLayer(out_path, f"{fault_layer.name()}_tp_1", "ogr")
self._add_layer_with_style(ln_layer, fault_layer)
if current_polygon_gdf is not None:
layer_path = os.path.dirname(self._resolved_source(polygon_layer))
out_name = f"{polygon_layer.name()}_tp_1.shp"
out_path = os.path.join(layer_path, out_name)
if os.path.exists(out_path):
out_path = out_path.replace(
'.shp', f"_{random.randint(10000,99999)}.shp")
current_polygon_gdf.to_file(out_path, driver='ESRI Shapefile')
poly_layer = QgsVectorLayer(out_path, f"{polygon_layer.name()}_tp_1", "ogr")
self._add_layer_with_style(poly_layer, polygon_layer)
prev_ratio = 1.0
for iter_ratio in iterations:
step_ratio = iter_ratio / prev_ratio # still needed for lines/polygons
prev_ratio = iter_ratio
ratio_tag = f"{iter_ratio:.6f}".rstrip('0').rstrip('.')
if abs(iter_ratio - 1.0) < 1e-9:
continue # ratio=1 baseline already output above
# --- Points (always from original, absolute ratio) ---
if original_pt_gdf is not None: