-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructpts_subsample.py
More file actions
1874 lines (1596 loc) · 74.4 KB
/
structpts_subsample.py
File metadata and controls
1874 lines (1596 loc) · 74.4 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
"""
Structural Subsampling Engine — Orientation Data Spatial Reduction
==================================================================
Version : 1.0.0
License : MIT
Overview
--------
Reduces spatial clustering in bedding and foliation point datasets while
preserving the statistical character of the orientations. Raw structural
shapefiles often contain mixed feature types (bedding, foliation, joints)
and non-standard column names; this module handles both through a two-stage
pipeline:
Stage 0 — Column standardisation and bedding filter
1. Optionally filters the raw shapefile to bedding-only records using
a user-specified attribute value (e.g. FEATURE == 'Bedding').
2. Renames source columns to four standard names used by all methods:
DIP - dip angle in degrees (0 = horizontal, 90 = vertical)
DIP_DIR - dip direction in degrees (0-360, clockwise from north)
EASTING - projected easting coordinate (metres)
NORTHING - projected northing coordinate (metres)
3. Converts strike to dip-direction if the source records strike
(right-hand rule: dip_direction = strike + 90).
4. Writes the standardised shapefile to input_beddings_only/ so all
subsampling methods read from one clean, consistently-named file.
Stage 1 — Subsampling
Applies the chosen algorithm(s) to the standardised bedding file.
Methods can be run individually or in combination. Each tolerance
parameter (grid_n, decimation_n, stoch_frac, dist_buffer, angle_tol)
accepts either a single value or a list of values; when a list is
supplied every value is run in turn and all outputs are saved.
Seven subsampling algorithms
-----------------------------
1. decimation - retain every nth point by digitisation order
2. stochastic - random-fraction sampling with a configurable seed
3. gridcell_average - grid-cell mean-vector averaging
4. spherical_kent - grid-cell Kent distribution statistics (kappa, beta)
5. outlier_removal - kappa-based single-outlier removal per cell
5b. outlier_carmichael - iterative delta-kappa-break algorithm (Carmichael 2016)
6. firstorder - proximity + angular alignment to geological contacts
Tolerance parameters (accept a single value or a list of values)
-----------------------------------------------------------------
decimation_n : step size for Method 1 (default 5)
stoch_frac : sampling fraction for Method 2 (default 0.5)
stoch_seed : random seed for Method 2 (default 42; set None for random)
grid_n : grid cell size in metres for Methods 3-5b (default 1000 m)
dist_buffer : contact proximity buffer for Method 6 in metres (default 500)
angle_tol : contact strike alignment tolerance for Method 6 (default 15 deg)
Other key parameters
--------------------
input_file : raw bedding shapefile (any column names, any feature mix)
output_dir : directory where subsampled shapefiles and CSVs are written
geology_file : geology polygon shapefile (required for Method 6)
methods : list of algorithm names to run, or 'all'
Quick-start example
-------------------
>>> from structpts_subsample import subsample_structures_file
>>> results = subsample_structures_file(
... input_file = 'inputs/bedding.shp',
... output_dir = 'outputs/',
... geology_file = 'inputs/geology.shp',
... dip_input_col = 'DIP',
... dipdir_input_col = 'DIP_DIR',
... dipdir_input_type = 'dip_direction',
... methods = ['gridcell_average', 'spherical_kent',
... 'outlier_removal', 'firstorder'],
... grid_n = [500, 1000, 2000],
... dist_buffer = [250, 500],
... angle_tol = [10, 15],
... )
>>> print(results)
References
----------
Carmichael, T. & Ailleres, L. (2016). Method and analysis for the upscaling
of structural data. Journal of Structural Geology, 83, 121-133.
Leong, L.S. & Carlile, J.C. (1998). A method for estimating the Kent
distribution parameters for orientation data. Mathematical Geology.
Kent, J.T. (1982). The Fisher-Bingham distribution on the sphere.
Journal of the Royal Statistical Society Series B, 44(1), 71-80.
"""
__version__ = '1.0.0'
__license__ = 'MIT'
import os
import math
import itertools
from math import sin, cos, asin, atan, atan2, degrees, radians, sqrt, acos, pi
import geopandas as gpd
import pandas as pd
import numpy as np
from pandas.errors import EmptyDataError
from shapely.geometry import Point, LineString
from shapely.ops import unary_union
# =============================================================================
# SUBSAMPLING ENGINE
# Encapsulates all seven subsampling algorithms together with their shared
# statistical machinery (direction cosines, mean orientation, Kent distribution).
# The engine is stateless between calls so a single instance can be reused
# across multiple datasets, methods, and tolerance sweeps.
# =============================================================================
class SubsamplingEngine:
"""
Core engine implementing all seven structural subsampling algorithms.
All algorithms operate on a GeoDataFrame whose columns have already been
standardised to DIP, DIP_DIR, EASTING, and NORTHING by Stage 0
(see :func:`prepare_bedding_inputs`). Statistical helpers for computing
direction cosines, mean orientations, and Kent distribution parameters
are implemented as private methods and shared across the grid-cell and
outlier algorithms.
Instantiate once and call individual method functions (e.g.
``engine.decimation()``) or use the unified ``engine.subsample()``
dispatcher to select a method by name.
Parameters
----------
dip : Column name for dip angle. Default ``'DIP'``.
dipdir : Column name for dip direction. Default ``'DIP_DIR'``.
easting : Column name for easting. Default ``'EASTING'``.
northing : Column name for northing. Default ``'NORTHING'``.
Examples
--------
>>> import geopandas as gpd
>>> from structpts_subsample import SubsamplingEngine
>>> gdf = gpd.read_file('inputs/bedding_standardised.shp')
>>> engine = SubsamplingEngine()
>>> result = engine.decimation(gdf, n=5, path_out='outputs/')
>>> print(f"Retained {len(result)} measurements")
"""
def __init__(self,
dip = 'DIP',
dipdir = 'DIP_DIR',
easting = 'EASTING',
northing = 'NORTHING'):
self.dip = dip
self.dipdir = dipdir
self.easting = easting
self.northing = northing
# =========================================================================
# UTILITY
# =========================================================================
@staticmethod
def _bounds(gdf):
"""Return integer bounding-box tuple (min_x, max_x, min_y, max_y)."""
b = gdf.total_bounds # [min_x, min_y, max_x, max_y]
return int(b[0]), int(b[2]) + 1, int(b[1]), int(b[3]) + 1
# =========================================================================
# STATISTICAL HELPERS
# Private methods used internally by the grid-cell and outlier algorithms.
# =========================================================================
def _add_direction_cosines(self, gpdataframe):
"""
Append a ``vector`` column of direction-cosine tuples to a DataFrame.
Each row receives a ``(l, m, n)`` tuple derived from its dip and
dip-direction values. The computation is fully vectorised using NumPy.
The pole to the plane (unit normal pointing downward into the plane)
is defined as::
l = sin(dip) × sin(dip_dir) [east component]
m = sin(dip) × cos(dip_dir) [north component]
n = cos(dip) [vertical component]
Parameters
----------
gpdataframe : Input GeoDataFrame or DataFrame.
Returns
-------
DataFrame with an additional column ``vector`` containing
``(l, m, n)`` tuples.
"""
df = pd.DataFrame(gpdataframe)
dip_r = np.radians(df[self.dip].astype(float))
dipdir_r = np.radians(df[self.dipdir].astype(float))
l_arr = np.sin(dip_r) * np.sin(dipdir_r) # east
m_arr = np.sin(dip_r) * np.cos(dipdir_r) # north
n_arr = np.cos(dip_r) # vertical (down)
df['vector'] = list(zip(l_arr, m_arr, n_arr))
return df
def _calc_mean_orientation(self, df):
"""
Compute the mean orientation of a group of structural measurements.
The mean is the normalised sum of the individual unit vectors
(direction cosines), converted back to dip / dip-direction.
Parameters
----------
df : DataFrame that **must** already contain a ``vector`` column of
``(l, m, n)`` tuples (added by :meth:`_add_direction_cosines`).
Returns
-------
Tuple ``(dip, dipdir)`` in degrees, or ``(nan, nan)`` if the resultant
vector length is near zero (antipodal vectors cancel).
"""
df = pd.DataFrame(df)
df[['l', 'm', 'n']] = pd.DataFrame(df['vector'].tolist(), index=df.index)
l_sum, m_sum, n_sum = df['l'].sum(), df['m'].sum(), df['n'].sum()
count = len(df.index)
r_bar = sqrt(float((l_sum / count)**2 + (m_sum / count)**2 +
(n_sum / count)**2))
if r_bar < 1e-12:
return (float('nan'), float('nan'))
l_unit = (l_sum / count) / r_bar
m_unit = (m_sum / count) / r_bar
n_unit = (n_sum / count) / r_bar
return dircos2ddd(l_unit, m_unit, n_unit)
def _calc_kent(self, gpdataframe):
"""
Estimate Kent distribution parameters for a cell of measurements.
The Kent (5-parameter Fisher-Bingham) distribution on the sphere is
characterised by:
- **kappa (kappa)** : concentration parameter (higher = tighter cluster)
- **beta (beta)** : ovalness / anisotropy parameter (0 = symmetric)
The estimation follows Leong & Carlile (1998) using the orientation
matrix T and rotation matrices H, S, G.
Parameters
----------
gpdataframe : DataFrame with a ``vector`` column of ``(l, m, n)`` tuples.
Returns
-------
Tuple ``(count, kappa, beta)``.
Notes
-----
Two known transcription errors in published sources are corrected:
*H-matrix fix* — position [2, 1] must be sin(theta) * sin(phi)
(not sin(theta) * cos(phi) as printed in Leong & Carlile 1998 and
Carmichael & Ailleres 2016).
*Sword-angle fix* — denominator must be B[0,0] - B[1,1] (diagonal
difference), not B[0,1] - B[1,1] (off-diagonal minus diagonal)
as printed in both sources.
"""
df = pd.DataFrame(gpdataframe)
df[['l', 'm', 'n']] = pd.DataFrame(df['vector'].tolist(), index=df.index)
l_sum, m_sum, n_sum = df['l'].sum(), df['m'].sum(), df['n'].sum()
count = len(df.index)
r = sqrt(float(l_sum**2 + m_sum**2 + n_sum**2))
if r < 1e-12:
return (count, float('nan'), float('nan'))
l_mean, m_mean, n_mean = l_sum / r, m_sum / r, n_sum / r
# --- Rotation matrix H (align z-axis with the mean direction) ---
theta = acos(max(-1.0, min(1.0, n_mean)))
phi = (atan(m_mean / l_mean) if abs(l_mean) > 1e-12
else (pi / 2 if m_mean >= 0 else -pi / 2))
# NOTE: H[2,1] = sin(theta)*sin(phi) (corrected from published sources)
H = np.array([
[cos(theta) * cos(phi), cos(theta) * sin(phi), -sin(theta)],
[-sin(phi), cos(phi), 0.0 ],
[sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta)],
])
# --- Orientation matrix T (second-moment matrix of direction cosines) ---
T = np.array([
[sum(df['l']**2), sum(df['l'] * df['m']), sum(df['l'] * df['n'])],
[sum(df['l'] * df['m']), sum(df['m']**2), sum(df['m'] * df['n'])],
[sum(df['l'] * df['n']), sum(df['m'] * df['n']), sum(df['n']**2) ],
])
# B = H^T (T/N) H
B = H.T @ (T / count) @ H
# --- Sword angle S ---
# NOTE: denominator = B[0,0] - B[1,1] (corrected from published sources)
b_diag_diff = B[0, 0] - B[1, 1]
sword = (0.5 * atan((2 * B[0, 1]) / b_diag_diff)
if abs(b_diag_diff) > 1e-12 else 0.0)
S = np.array([
[cos(sword), -sin(sword), 0.0],
[sin(sword), cos(sword), 0.0],
[0.0, 0.0, 1.0],
])
G = H @ S
V = G.T @ (T / count) @ G
Q = V[0, 0] - V[1, 1]
R = r
# --- Leong & Carlile (1998) moment estimator for kappa and beta ---
denom1 = 2 - 2 * R - Q
denom2 = 2 - 2 * R + Q
kappa_raw = (
(1 / denom1 if abs(denom1) > 1e-12 else float('inf')) +
(1 / denom2 if abs(denom2) > 1e-12 else float('inf'))
)
beta_raw = 0.5 * (
(1 / denom1 if abs(denom1) > 1e-12 else float('inf')) -
(1 / denom2 if abs(denom2) > 1e-12 else float('inf'))
)
# Enforce Kent validity constraints: kappa > 0, 0 <= 2*beta < kappa
kappa = max(1e-6, kappa_raw)
beta = max(0.0, min(beta_raw, kappa / 2.0 - 1e-9))
return (count, kappa, beta)
# =========================================================================
# METHOD 1: DECIMATION
# Retain every nth point by digitisation order.
# =========================================================================
def decimation(self, gpdataframe, n, path_out='outputs/'):
"""
Retain every nth point by digitisation order.
The simplest possible subsample: slice the dataset with a fixed step
so that evenly-spaced records are kept.
Parameters
----------
gpdataframe : Input GeoDataFrame of structural measurements.
n : Step size — keep every nth record (e.g. ``n=5`` keeps
records 0, 5, 10, ...).
path_out : Output directory path.
Returns
-------
GeoDataFrame of retained measurements with a point geometry column.
Examples
--------
>>> result = engine.decimation(gdf, n=5, path_out='outputs/')
>>> # Retains ~20% of the dataset
"""
df = pd.DataFrame(gpdataframe)
df_sub = df.iloc[::n].copy()
df_sub['geometry'] = df_sub.apply(
lambda row: Point(float(row[self.easting]),
float(row[self.northing])), axis=1)
df_sub = gpd.GeoDataFrame(df_sub, geometry='geometry')
if df_sub.empty:
print("DataFrame Empty")
else:
df_sub.to_file(
os.path.join(path_out, f"structure_file_decimation_{n}.shp"),
driver='ESRI Shapefile')
df_sub.to_csv(
os.path.join(path_out, f"structure_file_decimation_{n}.csv"))
return df_sub
# =========================================================================
# METHOD 2: STOCHASTIC SUBSAMPLING
# Randomly sample a fraction of the input dataset.
# =========================================================================
def stochastic(self, gpdataframe, frac=0.5, replace=False,
random_state=42, path_out='outputs/'):
"""
Randomly subsample a fraction of the input dataset.
Applies ``DataFrame.sample`` with the specified fraction and optional
random seed. Providing a fixed seed makes runs reproducible; passing
``random_state=None`` draws a new random sample each time.
Parameters
----------
gpdataframe : Input GeoDataFrame of structural measurements.
frac : Fraction of rows to retain, in the range (0, 1].
Default: 0.5 (50%).
replace : Whether to sample with replacement. Default: ``False``.
random_state : Integer seed for reproducibility, or ``None`` for a
fully random (non-reproducible) sample. Default: 42.
path_out : Output directory path.
Returns
-------
GeoDataFrame of sampled measurements with a point geometry column.
Examples
--------
>>> # Reproducible 30% sample
>>> result = engine.stochastic(gdf, frac=0.3, random_state=42)
>>> # Non-reproducible random sample
>>> result = engine.stochastic(gdf, frac=0.5, random_state=None)
"""
df = pd.DataFrame(gpdataframe)
df_sub = df.sample(frac=frac, replace=replace, random_state=random_state)
df_sub['geometry'] = df_sub.apply(
lambda row: Point(float(row[self.easting]),
float(row[self.northing])), axis=1)
df_sub = gpd.GeoDataFrame(df_sub, geometry='geometry')
if df_sub.empty:
print("DataFrame Empty")
else:
df_sub.to_file(
os.path.join(path_out, f"structure_file_stochastic_{frac}.shp"),
driver='ESRI Shapefile')
df_sub.to_csv(
os.path.join(path_out, f"structure_file_stochastic_{frac}.csv"))
return df_sub
# =========================================================================
# METHOD 3: GRID-CELL AVERAGING
# Compute the mean orientation vector for measurements within each cell.
# =========================================================================
def gridcell_average(self, gpdataframe, minx, maxx, miny, maxy,
n=1000, path_out='outputs/'):
"""
Compute the mean orientation vector for measurements within each grid cell.
The study area is divided into a regular grid of n x n metre cells.
All measurements that fall within a cell are combined into a single
representative orientation using the normalised vector mean. The
representative measurement is positioned at the geometric centre of
the grid cell. Cells with no measurements are omitted from the output.
Parameters
----------
gpdataframe : Input GeoDataFrame of structural measurements.
minx, maxx : Western and eastern study-area boundaries (metres).
miny, maxy : Southern and northern study-area boundaries (metres).
n : Grid cell size in metres. Default: 1000 m.
path_out : Output directory path.
Returns
-------
Filename stem (str) of the CSV written to ``path_out``. Pass this to
:func:`save_grid_to_shapefile` to produce a point shapefile.
Examples
--------
>>> bounds = gdf.total_bounds # [min_x, min_y, max_x, max_y]
>>> fname = engine.gridcell_average(gdf,
... minx=int(bounds[0]), maxx=int(bounds[2])+1,
... miny=int(bounds[1]), maxy=int(bounds[3])+1,
... n=1000, path_out='outputs/')
>>> result_gdf = save_grid_to_shapefile('outputs/', fname)
"""
df = self._add_direction_cosines(gpdataframe)
x = np.arange(minx, maxx, n, dtype=np.int64)
y = np.arange(miny, maxy, n, dtype=np.int64)
file = f"structure_file_gridcell_{n}"
fieldnames = ['EASTING', 'NORTHING', 'DIP', 'DIP_DIR']
with open(os.path.join(path_out, file + ".csv"), "w",
encoding="utf-8") as out:
out.write(','.join(fieldnames) + '\n')
for linex in x:
for liney in y:
grid = df.loc[
(df[self.northing] >= int(liney)) &
(df[self.northing] <= int(liney + n)) &
(df[self.easting] >= int(linex)) &
(df[self.easting] <= int(linex + n))
]
if grid.empty:
continue
centx = linex + (n / 2)
centy = liney + (n / 2)
dip_val, dipdir_val = self._calc_mean_orientation(grid)
dip_str = ('NaN' if math.isnan(dip_val)
else str(int(dip_val)))
dipdir_str = ('NaN' if math.isnan(dipdir_val)
else str(int(dipdir_val)))
out.write(f"{int(centx)},{int(centy)},"
f"{dip_str},{dipdir_str}\n")
return file
# =========================================================================
# METHOD 4: SPHERICAL STATISTICS (KENT DISTRIBUTION)
# Compute Kent distribution parameters (mean, kappa, beta) per grid cell.
# =========================================================================
def spherical_kent(self, gpdataframe, minx, maxx, miny, maxy,
n=1000, path_out='outputs/'):
"""
Compute Kent distribution statistics (mean orientation, kappa, beta) per cell.
In addition to the mean orientation provided by :meth:`gridcell_average`,
this method estimates the Kent distribution parameters:
- **kappa**: concentration — larger values indicate tighter clustering.
- **beta**: ovalness — zero means rotationally symmetric.
The Kent (5-parameter Fisher-Bingham) distribution is used because
kappa can be estimated even when orientation data are not rotationally
symmetric, which is typical for natural geological structures.
Empty cells are omitted from the output.
Parameters
----------
gpdataframe : Input GeoDataFrame of structural measurements.
minx, maxx : Western and eastern study-area boundaries (metres).
miny, maxy : Southern and northern study-area boundaries (metres).
n : Grid cell size in metres. Default: 1000 m.
path_out : Output directory path.
Returns
-------
Filename stem (str) of the CSV written to ``path_out``.
Examples
--------
>>> fname = engine.spherical_kent(gdf, minx, maxx, miny, maxy,
... n=1000, path_out='outputs/')
>>> result_gdf = save_grid_to_shapefile('outputs/', fname)
>>> print(result_gdf[['DIP', 'DIP_DIR', 'kappa', 'beta']].head())
"""
df = self._add_direction_cosines(gpdataframe)
x = np.arange(minx, maxx, n, dtype=np.int64)
y = np.arange(miny, maxy, n, dtype=np.int64)
file = f"structure_file_spherical_{n}"
fieldnames = ['EASTING', 'NORTHING', 'DIP', 'DIP_DIR',
'count', 'kappa', 'beta']
with open(os.path.join(path_out, file + ".csv"), "w",
encoding="utf-8") as out:
out.write(','.join(fieldnames) + '\n')
for linex in x:
for liney in y:
grid = df.loc[
(df[self.northing] >= int(liney)) &
(df[self.northing] <= int(liney + n)) &
(df[self.easting] >= int(linex)) &
(df[self.easting] <= int(linex + n))
]
if grid.empty:
continue
centx = linex + (n / 2)
centy = liney + (n / 2)
dip2, dipdir2 = self._calc_mean_orientation(grid)
count, kappa, beta = self._calc_kent(grid)
dip2_str = (
'-999' if (isinstance(dip2, float) and math.isnan(dip2))
else str(int(dip2))
)
dipdir2_str = (
'-999' if (isinstance(dipdir2, float) and
math.isnan(dipdir2))
else str(int(dipdir2))
)
out.write(f"{int(centx)},{int(centy)},"
f"{dip2_str},{dipdir2_str},"
f"{int(count)},{kappa},{beta}\n")
return file
# =========================================================================
# METHOD 5: OUTLIER REMOVAL (SINGLE-REMOVAL PER CELL)
# Remove the one measurement per cell whose removal most increases kappa.
# =========================================================================
def outlier_removal(self, gdf, minx, maxx, miny, maxy,
n=1000, path_out='outputs/'):
"""
Remove the single greatest outlier per grid cell using the max-delta-kappa criterion.
For each grid cell containing more than 3 measurements, every point is
tentatively removed in turn. The point whose removal produces the
greatest increase in kappa (max delta-kappa) is identified as the outlier
and permanently excluded. The remaining measurements are then averaged
using spherical statistics to produce a single representative orientation.
Cells with 3 or fewer measurements are excluded from the output, as
insufficient data remain for reliable statistical estimation.
Parameters
----------
gdf : Input GeoDataFrame of structural measurements.
minx, maxx : Western and eastern study-area boundaries (metres).
miny, maxy : Southern and northern study-area boundaries (metres).
n : Grid cell size in metres. Default: 1000 m.
path_out : Output directory path.
Returns
-------
Filename stem (str) of the cleaned CSV written to ``path_out``.
Examples
--------
>>> fname = engine.outlier_removal(gdf, minx, maxx, miny, maxy,
... n=1000, path_out='outputs/')
>>> result_gdf = save_grid_to_shapefile('outputs/', fname)
"""
df = self._add_direction_cosines(gdf)
x_coords = np.arange(minx, maxx, n)
y_coords = np.arange(miny, maxy, n)
file = f"structure_file_outlier_{n}"
csv_path = os.path.join(path_out, f"{file}.csv")
with open(csv_path, "w", encoding="utf-8") as out:
out.write("EASTING,NORTHING,DIP,DIP_DIR,"
"count,kappa,beta,REMOVED_INDEX\n")
for linex in x_coords:
for liney in y_coords:
grid = df[
(df[self.northing] >= liney) &
(df[self.northing] <= liney + n) &
(df[self.easting] >= linex) &
(df[self.easting] <= linex + n)
]
centx = int(linex + n / 2)
centy = int(liney + n / 2)
if len(grid) <= 3:
out.write(f"{centx},{centy},-999,-999,"
f"{len(grid)},-999,-999,-1\n")
continue
dip0, dipdir0 = self._calc_mean_orientation(grid)
_, k0, _ = self._calc_kent(grid)
delta_kappas = []
for idx in grid.index:
temp = grid.drop(index=idx)
_, k_t, _ = self._calc_kent(temp)
delta_kappas.append((idx, k_t - k0))
removed_idx, _ = max(delta_kappas, key=lambda x: x[1])
final_grid = grid.drop(index=removed_idx)
dip_f, dipdir_f = self._calc_mean_orientation(final_grid)
count, kappa, beta = self._calc_kent(final_grid)
out.write(f"{centx},{centy},{int(dip_f)},{int(dipdir_f)},"
f"{count},{kappa},{beta},{removed_idx}\n")
# Strip sentinel rows — final CSV contains only valid cells
df_clean = pd.read_csv(csv_path)
df_clean = df_clean[~(
(df_clean['DIP'] == -999) &
(df_clean['DIP_DIR'] == -999) &
(np.isclose(df_clean['kappa'].astype(float), -999)) &
(np.isclose(df_clean['beta'].astype(float), -999))
)]
df_clean.to_csv(csv_path, index=False)
return file
# =========================================================================
# METHOD 5b: CARMICHAEL ITERATIVE OUTLIER REMOVAL
# Remove multiple outliers per cell using the delta-kappa-break algorithm.
# =========================================================================
def outlier_carmichael(self, gdf, minx, maxx, miny, maxy,
n=1000, path_out='outputs/'):
"""
Remove multiple outliers per grid cell using the Carmichael (2016)
iterative delta-kappa-break algorithm.
For each grid cell, points are ranked by angular distance from the cell
mean direction (farthest first). They are then removed iteratively and
kappa is recomputed after each removal. The step with the largest
increase in kappa defines the outlier boundary: every point removed up
to and including that step is treated as an outlier. At most N // 2
points may be removed from any cell of N measurements.
If no removal step produces a positive delta-kappa, the cell is left
unchanged. Cells with 3 or fewer measurements are excluded.
Parameters
----------
gdf : Input GeoDataFrame of structural measurements.
minx, maxx : Western and eastern study-area boundaries (metres).
miny, maxy : Southern and northern study-area boundaries (metres).
n : Grid cell size in metres. Default: 1000 m.
path_out : Output directory path.
Returns
-------
Filename stem (str) of the cleaned CSV written to ``path_out``.
References
----------
Carmichael, T. & Ailleres, L. (2016). Method and analysis for the
upscaling of structural data. Journal of Structural Geology, 83, 121-133.
Examples
--------
>>> fname = engine.outlier_carmichael(gdf, minx, maxx, miny, maxy,
... n=1000, path_out='outputs/')
>>> result_gdf = save_grid_to_shapefile('outputs/', fname)
"""
df = self._add_direction_cosines(gdf)
df[['dc_l', 'dc_m', 'dc_n']] = pd.DataFrame(
df['vector'].tolist(), index=df.index)
x_coords = np.arange(minx, maxx, n)
y_coords = np.arange(miny, maxy, n)
file = f"structure_file_outlier_carmichael_{n}"
csv_path = os.path.join(path_out, f"{file}.csv")
with open(csv_path, "w", encoding="utf-8") as out:
out.write("EASTING,NORTHING,DIP,DIP_DIR,"
"count,kappa,beta,n_removed\n")
for linex in x_coords:
for liney in y_coords:
grid = df[
(df[self.northing] >= liney) &
(df[self.northing] <= liney + n) &
(df[self.easting] >= linex) &
(df[self.easting] <= linex + n)
]
centx = int(linex + n / 2)
centy = int(liney + n / 2)
N = len(grid)
if N <= 3:
out.write(f"{centx},{centy},-999,-999,"
f"{N},-999,-999,-1\n")
continue
# Compute cell mean direction as a unit vector
l_s = float(grid['dc_l'].sum())
m_s = float(grid['dc_m'].sum())
n_s = float(grid['dc_n'].sum())
g_len = sqrt(l_s**2 + m_s**2 + n_s**2)
if g_len < 1e-12:
out.write(f"{centx},{centy},-999,-999,"
f"{N},-999,-999,-1\n")
continue
mean_vec = np.array([l_s / g_len, m_s / g_len,
n_s / g_len])
# Rank points by angular distance from mean (farthest first)
vecs = grid[['dc_l', 'dc_m', 'dc_n']].values.astype(float)
dots = np.clip(vecs @ mean_vec, -1.0, 1.0)
ang_dists = np.degrees(np.arccos(dots))
ranked_indices = list(
grid.index[np.argsort(ang_dists)[::-1]])
# Build kappa sequence: remove one point at a time
_, k_prev, _ = self._calc_kent(grid)
max_remove = N // 2
delta_seq = []
remaining = list(grid.index)
for i in range(max_remove):
remaining.remove(ranked_indices[i])
temp = grid.loc[remaining]
_, k_t, _ = self._calc_kent(temp)
delta_seq.append(k_t - k_prev)
k_prev = k_t
# Find the delta-kappa break
best_i = int(np.argmax(delta_seq))
best_delta = delta_seq[best_i]
if best_delta <= 0:
# No removal improves concentration — retain all points
n_removed = 0
final_grid = grid
else:
n_removed = best_i + 1
outlier_set = set(ranked_indices[:n_removed])
kept = [idx for idx in grid.index
if idx not in outlier_set]
final_grid = grid.loc[kept]
dip_f, dipdir_f = self._calc_mean_orientation(final_grid)
if math.isnan(dip_f) or math.isnan(dipdir_f):
out.write(f"{centx},{centy},-999,-999,"
f"{N - n_removed},-999,-999,{n_removed}\n")
continue
count, kappa_f, beta_f = self._calc_kent(final_grid)
out.write(f"{centx},{centy},{int(dip_f)},{int(dipdir_f)},"
f"{count},{kappa_f},{beta_f},{n_removed}\n")
# Strip sentinel rows
df_clean = pd.read_csv(csv_path)
df_clean = df_clean[~(
(df_clean['DIP'] == -999) &
(df_clean['DIP_DIR'] == -999) &
(np.isclose(df_clean['kappa'].astype(float), -999)) &
(np.isclose(df_clean['beta'].astype(float), -999))
)]
df_clean.to_csv(csv_path, index=False)
return file
# =========================================================================
# METHOD 6: FIRST-ORDER SUBSAMPLING
# Filter by proximity to geological contacts and angular alignment.
# =========================================================================
def firstorder(self, gpdataframe, contact_gdf,
dist_buffer=500, angle_tol=15, path_out='outputs/'):
"""
Filter measurements by proximity to geological contacts and angular
alignment with them (first-order subsampling).
A measurement is retained only if **both** criteria are satisfied:
(a) **Proximity** — its distance to the nearest contact line is within
``dist_buffer`` metres.
(b) **Angular alignment** — the bedding strike differs from the contact
azimuth by no more than ``angle_tol`` degrees.
Contacts are supplied as a GeoDataFrame of contact lines, typically
derived from the boundaries of a geology polygon dataset.
Parameters
----------
gpdataframe : Input GeoDataFrame with point geometries.
contact_gdf : GeoDataFrame of geological contact lines
(LineString or MultiLineString geometries).
dist_buffer : Maximum distance from any contact (metres).
Default: 500 m.
angle_tol : Maximum allowable strike angular difference (degrees).
Default: 15 degrees.
path_out : Output directory path.
Returns
-------
GeoDataFrame of retained measurements passing both filters.
Examples
--------
>>> import geopandas as gpd
>>> geology = gpd.read_file('inputs/geology.shp')
>>> contacts = geology[['geometry']].copy()
>>> contacts['geometry'] = geology.boundary
>>> result = engine.firstorder(gdf, contacts,
... dist_buffer=500, angle_tol=15)
>>> print(f"Retained {len(result)} of {len(gdf)} measurements")
"""
gdf = gpd.GeoDataFrame(gpdataframe.copy())
if gdf.crs is not None and contact_gdf.crs is not None:
contact_gdf = contact_gdf.to_crs(gdf.crs)
contact_union = unary_union(contact_gdf.geometry)
# Step 1: Distance filter
dists = gdf.geometry.distance(contact_union)
candidates = gdf[dists <= dist_buffer].copy()
if candidates.empty:
print("DataFrame Empty - no measurements within the distance buffer.")
return candidates
# Step 2: Decompose contacts into per-segment azimuths
seg_gdf = _segment_azimuths(contact_gdf)
# Step 3: Nearest-segment join to get contact azimuth per point
cands_reset = candidates.reset_index(drop=False)
try:
joined = gpd.sjoin_nearest(
cands_reset[['index', 'geometry', self.dipdir]],
seg_gdf[['geometry', 'azimuth']],
how='left'
)
joined = joined.drop_duplicates(subset='index')
contact_az = joined['azimuth'].values
bedding_strike = (joined[self.dipdir].astype(float).values - 90) % 180
diff = np.abs(((contact_az - bedding_strike + 90) % 180) - 90)
keep_orig_idx = joined.loc[diff <= angle_tol, 'index'].values
df_sub = candidates.loc[keep_orig_idx].copy()
except AttributeError:
# Fallback for GeoPandas < 0.10 without sjoin_nearest
seg_geoms = seg_gdf.geometry.values
seg_az_arr = seg_gdf['azimuth'].values
contact_az = np.array([
seg_az_arr[np.argmin([pt.distance(s) for s in seg_geoms])]
for pt in candidates.geometry
])
bedding_strike = (candidates[self.dipdir].astype(float).values
- 90) % 180
diff = np.abs(((contact_az - bedding_strike + 90) % 180) - 90)
df_sub = candidates[diff <= angle_tol].copy()
# Write outputs
if df_sub.empty:
print("DataFrame Empty - no measurements pass the angle filter.")
else:
fname = (f"structure_file_firstorder"
f"_d{int(dist_buffer)}_a{int(angle_tol)}")
df_sub.to_file(os.path.join(path_out, fname + ".shp"),
driver='ESRI Shapefile')
df_sub.to_csv(os.path.join(path_out, fname + ".csv"))
return df_sub
# =========================================================================
# DISPATCH
# Unified interface: call any method by name.
# =========================================================================
def subsample(self, method, gpdataframe, path_out='outputs/', **kwargs):
"""
Run a named subsampling algorithm on the supplied dataset.
Parameters
----------
method : Algorithm name. One of:
``'decimation'``, ``'stochastic'``,
``'gridcell_average'``, ``'spherical_kent'``,
``'outlier_removal'``, ``'outlier_carmichael'``,
``'firstorder'``.
gpdataframe : Input GeoDataFrame of structural measurements.
path_out : Output directory path.
**kwargs : Method-specific keyword arguments forwarded to the
chosen algorithm (e.g. ``n=5`` for decimation,
``grid_n=1000`` for grid-cell methods).
Returns
-------
The return value of the selected algorithm (GeoDataFrame or filename
stem, depending on the method).
Raises
------
ValueError
If ``method`` is not a recognised algorithm name.
"""
valid = [
'decimation', 'stochastic',
'gridcell_average', 'spherical_kent',
'outlier_removal', 'outlier_carmichael',
'firstorder',
]
if method not in valid:
raise ValueError(
f"method must be one of: {', '.join(valid)}\n"
f" Got: '{method}'"
)
# Extract shared grid-cell bounds if supplied
minx = kwargs.pop('minx', None)
maxx = kwargs.pop('maxx', None)
miny = kwargs.pop('miny', None)
maxy = kwargs.pop('maxy', None)
grid_n = kwargs.pop('grid_n', 1000)
if method == 'decimation':
return self.decimation(
gpdataframe, n=kwargs.get('n', 5), path_out=path_out)
if method == 'stochastic':
return self.stochastic(
gpdataframe,
frac=kwargs.get('frac', 0.5),
replace=kwargs.get('replace', False),
random_state=kwargs.get('random_state', 42),
path_out=path_out)
if method == 'gridcell_average':
return self.gridcell_average(
gpdataframe, minx, maxx, miny, maxy,
n=grid_n, path_out=path_out)
if method == 'spherical_kent':
return self.spherical_kent(
gpdataframe, minx, maxx, miny, maxy,
n=grid_n, path_out=path_out)
if method == 'outlier_removal':
return self.outlier_removal(
gpdataframe, minx, maxx, miny, maxy,
n=grid_n, path_out=path_out)
if method == 'outlier_carmichael':
return self.outlier_carmichael(
gpdataframe, minx, maxx, miny, maxy,
n=grid_n, path_out=path_out)