-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy paththree_d_surfaces.py
2018 lines (1919 loc) · 93.6 KB
/
three_d_surfaces.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
"""three_d_surfaces.py
PZero© Andrea Bistacchi"""
from copy import deepcopy
from uuid import uuid4
from pyvista import PolyData as pv_PolyData
from numpy import abs as np_abs
from numpy import around as np_around
from numpy import cbrt as np_cbrt
from numpy import cos as np_cos
from numpy import flip as np_flip
from numpy import float32 as np_float32
from numpy import float64 as np_float64
from numpy import ndarray as np_ndarray
from numpy import pi as np_pi
from numpy import sin as np_sin
from numpy import sqrt as np_sqrt
from numpy import zeros as np_zeros
from pandas import DataFrame as pd_DataFrame
from pandas import concat as pd_concat
from scipy.interpolate import griddata as sp_griddata
from vtk import (vtkAppendPolyData,
vtkDelaunay2D,
vtkSurfaceReconstructionFilter,
vtkPoints,
vtkPolyData,
vtkContourFilter,
vtkSmoothPolyDataFilter,
vtkLinearExtrusionFilter,
vtkTransform,
vtkTransformPolyDataFilter,
vtkDecimatePro,
vtkQuadricDecimation,
vtkLinearSubdivisionFilter,
vtkButterflySubdivisionFilter,
vtkLoopSubdivisionFilter,
vtkStripper,
vtkCleanPolyData,
vtkTriangleFilter,
vtkImageData,
vtkCutter,
vtkPointInterpolator2D,
vtkVoronoiKernel,
vtkThresholdPoints,
vtkDataObject,
vtkPolyDataConnectivityFilter,
vtkClipPolyData,
)
from vtkmodules.util import numpy_support
from vtkmodules.vtkCommonDataModel import vtkBoundingBox
from LoopStructural import GeologicalModel
from pzero.helpers.helper_dialogs import (
multiple_input_dialog,
input_one_value_dialog,
input_text_dialog,
input_combo_dialog,
input_checkbox_dialog,
tic,
toc,
progress_dialog,
general_input_dialog,
)
from .entities_factory import (
TriSurf,
XsPolyLine,
PolyLine,
VertexSet,
Voxet,
XsVoxet,
XsVertexSet,
Attitude,
)
from .helpers.helper_functions import freeze_gui
@freeze_gui
def interpolation_delaunay_2d(self):
"""The vtkDelaunay2D object takes vtkPointSet (or any of its subclasses) as input and
generates a vtkPolyData on output - typically a triangle mesh if Alpha value is not defined.
Select the whole line of two or more vtkPointSet entities and start the algorithm.
"""
self.print_terminal("Delaunay2D: interpolation of Points, Lines and Surfaces")
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be interpolated -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal(" -- No input data selected -- ")
return
else:
"""Deep copy list of selected uids needed otherwise problems
can arise if the main geology table is deselected while the dataframe is being built
"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if (
isinstance(self.geol_coll.get_uid_vtk_obj(uid), PolyLine)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), XsPolyLine)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), VertexSet)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), XsVertexSet)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), TriSurf)
):
pass
else:
self.print_terminal(" -- Error input type -- ")
return
"""Create deepcopy of the geological entity dictionary."""
surf_dict = deepcopy(self.geol_coll.entity_dict)
input_dict = {
"name": [
"TriSurf name: ",
self.geol_coll.get_uid_name(input_uids[0]) + "_delaunay2d",
],
"role": [
"Role: ",
self.parent.geol_coll.valid_roles,
self.parent.geol_coll.get_uid_role(input_uids[0]),
],
"feature": [
"Feature: ",
self.geol_coll.get_uid_feature(input_uids[0]),
],
"scenario": ["Scenario: ", self.geol_coll.get_uid_scenario(input_uids[0])],
}
surf_dict_updt = multiple_input_dialog(
title="New Delaunay 2D interpolation", input_dict=input_dict
)
"""Check if the output of the widget is empty or not. If the Cancel button was clicked, the tool quits"""
if surf_dict_updt is None:
return
"""Ask for the Tolerance and Alpha values. Tolerance controls discarding of closely spaced points.
Alpha controls the 'size' of output primitivies - a 0 Alpha Value outputs a triangle mesh."""
tolerance_value = input_one_value_dialog(
title="Delaunay2D Parameters",
label="Tolerance Value. Discard points " "closer than the specified value",
default_value=0,
)
if tolerance_value is None:
tolerance_value = 0
alpha_value = input_one_value_dialog(
title="Delaunay2D Parameters",
label="Alpha Value. Discard triangles not contained "
"in a sphere of radius set "
"by the specified value ",
default_value=0,
)
if alpha_value is None:
alpha_value = 0
"""Getting the values that have been typed by the user through the multiple input widget"""
for key in surf_dict_updt:
surf_dict[key] = surf_dict_updt[key]
surf_dict["topology"] = "TriSurf"
surf_dict["vtk_obj"] = TriSurf()
"""Create a vtkAppendPolyData filter to merge all input vtk objects. Else, it does not seem possible to
input multiple objects into vtkDelaunay2D"""
vtkappend = vtkAppendPolyData()
for uid in input_uids:
vtkappend.AddInputData(self.geol_coll.get_uid_vtk_obj(uid))
vtkappend.Update()
bounding_box = vtkBoundingBox()
bounding_box.ComputeBounds(vtkappend.GetOutput().GetPoints())
diagonal = bounding_box.GetDiagonalLength()
tolerance_value_bounding = tolerance_value / diagonal
"""Create a new instance of the interpolation class"""
delaunay_2d = vtkDelaunay2D()
delaunay_2d.SetInputDataObject(vtkappend.GetOutput())
delaunay_2d.SetProjectionPlaneMode(1)
trans = delaunay_2d.ComputeBestFittingPlane(vtkappend.GetOutput())
delaunay_2d.SetTransform(trans)
delaunay_2d.SetTolerance(tolerance_value_bounding)
delaunay_2d.SetAlpha(alpha_value)
delaunay_2d.Update() # executes the interpolation
"""ShallowCopy is the way to copy the new interpolated surface into the TriSurf instance created at the beginning"""
surf_dict["vtk_obj"].ShallowCopy(delaunay_2d.GetOutput())
surf_dict["vtk_obj"].Modified()
"""Add new entity from surf_dict. Function add_entity_from_dict creates a new uid"""
if surf_dict["vtk_obj"].points_number > 0:
self.geol_coll.add_entity_from_dict(surf_dict)
else:
self.print_terminal(" -- empty object -- ")
@freeze_gui
def poisson_interpolation(self):
"""vtkSurfaceReconstructionFilter can be used to reconstruct surfaces from point clouds. Input is a vtkDataSet
defining points assumed to lie on the surface of a 3D object."""
self.print_terminal("Interpolation from point cloud: build surface from interpolation")
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be interpolated -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deseselcted while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if (
isinstance(self.geol_coll.get_uid_vtk_obj(uid), PolyLine)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), XsPolyLine)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), VertexSet)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), XsVertexSet)
or isinstance(self.geol_coll.get_uid_vtk_obj(uid), TriSurf)
):
pass
else:
self.print_terminal(" -- Error input type -- ")
return
"""Create deepcopy of the geological entity dictionary."""
surf_dict = deepcopy(self.geol_coll.entity_dict)
input_dict = {
"name": [
"TriSurf name: ",
self.geol_coll.get_uid_name(input_uids[0]) + "_cloud",
],
"role": [
"Role: ",
self.parent.geol_coll.valid_roles,
],
"feature": [
"Feature: ",
self.geol_coll.get_uid_feature(input_uids[0]),
],
"scenario": ["Scenario: ", self.geol_coll.get_uid_scenario(input_uids[0])],
}
surf_dict_updt = multiple_input_dialog(
title="Surface interpolation from point cloud", input_dict=input_dict
)
"""Check if the output of the widget is empty or not. If the Cancel button was clicked, the tool quits"""
if surf_dict_updt is None:
return
"""Getting the values that have been typed by the user through the multiple input widget"""
for key in surf_dict_updt:
surf_dict[key] = surf_dict_updt[key]
surf_dict["topology"] = "TriSurf"
surf_dict["vtk_obj"] = TriSurf()
"""Create a new instance of the interpolation class"""
surf_from_points = vtkSurfaceReconstructionFilter()
sample_spacing = input_one_value_dialog(
title="Surface interpolation from point cloud",
label="Sample Spacing",
default_value=-1.0,
)
if sample_spacing is None:
pass
else:
surf_from_points.SetSampleSpacing(sample_spacing)
neighborhood_size = input_one_value_dialog(
title="Surface interpolation from point cloud",
label="Neighborhood Size",
default_value=20,
)
if neighborhood_size is None:
pass
else:
surf_from_points.SetNeighborhoodSize(int(neighborhood_size))
"""Create a vtkAppendPolyData filter to merge all input vtk objects."""
vtkappend = vtkAppendPolyData()
for uid in input_uids:
if (
self.geol_coll.get_uid_topology(input_uids[0]) == "XsPolyLine"
or self.geol_coll.get_uid_topology(input_uids[0]) == "PolyLine"
or self.geol_coll.get_uid_topology(input_uids[0]) == "TriSurf"
):
"""Extract points from vtkpolydata"""
point_coord = self.geol_coll.get_uid_vtk_obj(uid).points
points = vtkPoints()
x = 0
for row in point_coord:
points.InsertPoint(
x, point_coord[x, 0], point_coord[x, 1], point_coord[x, 2]
)
x += 1
polydata = vtkPolyData()
polydata.SetPoints(points)
vtkappend.AddInputData(polydata)
elif self.geol_coll.get_uid_topology(input_uids[0]) == "VertexSet":
vtkappend.AddInputData(self.geol_coll.get_uid_vtk_obj(uid))
vtkappend.Update()
"""The created vtkPolyData is used as the input for vtkSurfaceReconstructionFilter"""
surf_from_points.SetInputDataObject(vtkappend.GetOutput())
surf_from_points.Update() # executes the interpolation. Output is vtkImageData
"""Contour the grid at zero to extract the surface"""
contour_surface = vtkContourFilter()
contour_surface.SetInputData(surf_from_points.GetOutput())
contour_surface.SetValue(0, 0.0)
contour_surface.Update()
"""ShallowCopy is the way to copy the new interpolated surface into the TriSurf instance created at the beginning"""
surf_dict["vtk_obj"].ShallowCopy(contour_surface.GetOutput())
surf_dict["vtk_obj"].Modified()
"""Add new entity from surf_dict. Function add_entity_from_dict creates a new uid"""
if surf_dict["vtk_obj"].points_number > 0:
self.geol_coll.add_entity_from_dict(surf_dict)
else:
self.print_terminal(" -- empty object -- ")
@freeze_gui
def implicit_model_loop_structural(self):
"""Function to call LoopStructural's implicit modelling algorithms.
Input Data is organized as the following columns:
X - x component of the cartesian coordinates
Y - y component of the cartesian coordinates
Z - z component of the cartesian coordinates
feature_name - unique name of the geological feature being modelled - this is not the feature generally defined in geological_collection.py, but the sequence defined in legend_manager.py
val - value observations of the scalar field - this is the time defined in legend_manager.py
interface - unique identifier for an interface containing similar scalar field values
nx - x component of the gradient norm
ny - y component of the gradient norm
nz - z component of the gradient norm
gx - x component of a gradient constraint
gy - y component of a gradient constraint
gz - z component of a gradient constraint
tx - x component of a gradient tangent constraint
ty - y component of a gradient tangent constraint
tz - z component of a gradient tangent constraint
coord - coordinate of the structural frame data point is used for ???
"""
self.print_terminal("LoopStructural implicit geomodeller\ngithub.com/Loop3D/LoopStructural")
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be interpolated -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deseselcted while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
"Dictionary used to define the fields of the Loop input data Pandas dataframe."
loop_input_dict = {
"X": None,
"Y": None,
"Z": None,
"feature_name": None,
"val": None,
"interface": None,
"nx": None,
"ny": None,
"nz": None,
"gx": None,
"gy": None,
"gz": None,
"tx": None,
"ty": None,
"tz": None,
"coord": None,
}
"""Create empty dataframe to collect all input data."""
self.print_terminal("-> creating input dataframe...")
tic(parent=self)
all_input_data_df = pd_DataFrame(columns=list(loop_input_dict.keys()))
"""For every selected item extract interesting data: XYZ, feature_name, val, etc."""
prgs_bar = progress_dialog(
max_value=len(input_uids),
title_txt="Input dataframe",
label_txt="Adding geological objects to input dataframe...",
cancel_txt=None,
parent=self,
)
for uid in input_uids:
"""Create empty dataframe to collect input data for this object."""
entity_input_data_df = pd_DataFrame(columns=list(loop_input_dict.keys()))
"""XYZ data for every selected entity.
Adding all columns at once is about 10% faster than adding them separately, but still slow."""
entity_input_data_df[["X", "Y", "Z"]] = self.geol_coll.get_uid_vtk_obj(uid).points
if "Normals" in self.geol_coll.get_uid_properties_names(uid):
entity_input_data_df[["nx", "ny", "nz"]] = self.geol_coll.get_uid_property(uid=uid, property_name="Normals")
"""feature_name value"""
featname_single = self.geol_coll.legend_df.loc[
(self.geol_coll.legend_df["role"] == self.geol_coll.get_uid_role(uid))
& (self.geol_coll.legend_df["feature"] == self.geol_coll.get_uid_feature(uid))
& (self.geol_coll.legend_df["scenario"] == self.geol_coll.get_uid_scenario(uid)),
"sequence",
].values[0]
entity_input_data_df["feature_name"] = featname_single
"""val value"""
val_single = self.geol_coll.legend_df.loc[
(self.geol_coll.legend_df["role"] == self.geol_coll.get_uid_role(uid))
& (self.geol_coll.legend_df["feature"] == self.geol_coll.get_uid_feature(uid))
& (self.geol_coll.legend_df["scenario"] == self.geol_coll.get_uid_scenario(uid)),
"time",
].values[0]
if val_single == -999999.0:
val_single = float("nan")
entity_input_data_df["val"] = val_single
# nx, ny and nz: TO BE IMPLEMENTED
# gx, gy and gz: TO BE IMPLEMENTED
# Append dataframe for this input entity to the general input dataframe.
# Old Pandas <= 1.5.3
# all_input_data_df = all_input_data_df.append(
# entity_input_data_df, ignore_index=True
# )
# New Pandas >= 2.0.0
all_input_data_df = pd_concat([all_input_data_df, entity_input_data_df], ignore_index=True)
prgs_bar.add_one()
toc(parent=self)
prgs_bar.close()
"""Drop columns with no valid value (i.e. all NaNs)."""
self.print_terminal("-> drop empty columns...")
tic(parent=self)
all_input_data_df.dropna(axis=1, how="all", inplace=True)
toc(parent=self)
self.print_terminal(f"all_input_data_df:\n{all_input_data_df}")
"""Ask for bounding box for the model"""
input_dict = {
"boundary": ["Boundary: ", self.boundary_coll.get_names],
"method": ["Interpolation method: ", ["PLI", "FDI", "surfe"]],
}
options_dict = multiple_input_dialog(title="Implicit Modelling - LoopStructural algorithms", input_dict=input_dict)
if options_dict is None:
options_dict["boundary"] = self.boundary_coll.get_names[0]
options_dict["method"] = "PLI"
boundary_uid = self.boundary_coll.df.loc[self.boundary_coll.df["name"] == options_dict["boundary"], "uid"].values[0]
origin_x = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[0]
origin_y = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[2]
maximum_x = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[1]
maximum_y = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[3]
if (
self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[4]
== self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[5]
):
"""Boundary with no vertical dimension has been chosen. A dialog that asks for max and min Z is needed"""
vertical_extension_in = {
"message": [
"Model vertical extension",
"Define MAX and MIN vertical extension of the 3D implicit model.",
"QLabel",
],
"top": ["Insert top", 1000.0, "QLineEdit"],
"bottom": ["Insert bottom", -1000.0, "QLineEdit"],
}
vertical_extension_updt = general_input_dialog(
title="Implicit Modelling - LoopStructural algorithms",
input_dict=vertical_extension_in,
)
if vertical_extension_updt["top"] is None:
vertical_extension_updt["top"] = 1000.0
if vertical_extension_updt["bottom"] is None:
vertical_extension_updt["bottom"] = -1000.0
if vertical_extension_updt["bottom"] > vertical_extension_updt["top"]:
"""Manages the case where mistakenly bottom > top"""
origin_z = vertical_extension_updt["top"]
maximum_z = vertical_extension_updt["bottom"]
elif vertical_extension_updt["bottom"] == vertical_extension_updt["top"]:
origin_z = vertical_extension_updt["bottom"] - 25.0 # arbitrary value
maximum_z = vertical_extension_updt["bottom"] + 25.0 # arbitrary value
else:
origin_z = vertical_extension_updt["bottom"]
maximum_z = vertical_extension_updt["top"]
else:
"""Collect information on the vertical extension of the model from the Boundary vtk obj"""
origin_z = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[4]
maximum_z = self.boundary_coll.get_uid_vtk_obj(boundary_uid).GetBounds()[5]
edge_x = maximum_x - origin_x
edge_y = maximum_y - origin_y
edge_z = maximum_z - origin_z
"""Define origin and maximum extension of modelling domain"""
origin = [origin_x, origin_y, origin_z]
maximum = [maximum_x, maximum_y, maximum_z]
self.print_terminal(f"origin: {origin}")
self.print_terminal(f"origin: {maximum}")
"""Check if Input Data and Bounding Box overlaps. If so, gives warning and exists the tool."""
if (
(all_input_data_df["X"].min() > maximum_x)
or (all_input_data_df["X"].max() < origin_x)
or (all_input_data_df["Y"].min() > maximum_y)
or (all_input_data_df["Y"].max() < origin_y)
or (all_input_data_df["Z"].min() > maximum_z)
or (all_input_data_df["Z"].max() < origin_z)
):
self.print_terminal("Exit tool: Bounding Box does not intersect input data")
return
default_spacing = np_cbrt(
edge_x * edge_y * edge_z / (50 * 50 * 25)
) # default dimension in Loop is 50 x 50 x 25
target_spacing = input_one_value_dialog(
title="Implicit Modelling - LoopStructural algorithms",
label="Grid target spacing in model units\n (yields a 62500 cells model)",
default_value=default_spacing,
)
if target_spacing is None or target_spacing <= 0:
target_spacing = default_spacing
dimension_x = int(np_around(edge_x / target_spacing))
if dimension_x == 0:
dimension_x = 1
dimension_y = int(np_around(edge_y / target_spacing))
if dimension_y == 0:
dimension_y = 1
dimension_z = int(np_around(edge_z / target_spacing))
if dimension_z == 0:
dimension_z = 1
dimensions = [dimension_x, dimension_y, dimension_z]
spacing_x = edge_x / dimension_x
spacing_y = edge_y / dimension_y
spacing_z = edge_z / dimension_z
spacing = [spacing_x, spacing_y, spacing_z]
self.print_terminal(f"dimensions: {dimensions}")
self.print_terminal(f"spacing: {spacing}")
"""Create model as instance of Loop GeologicalModel with limits given by origin and maximum.
Keep rescale=True (default) for performance and precision.
THIS SHOULD BE CHANGED IN FUTURE TO BETTER DEAL WITH IRREGULARLY DISTRIBUTED INPUT DATA.
* ``interpolatortype`` - we can either use a PiecewiseLinearInterpolator ``PLI``, a FiniteDifferenceInterpolator ``FDI`` or a radial basis interpolator ``surfe``
* ``nelements - int`` is the how many elements are used to discretize the resulting solution
* ``buffer - float`` buffer percentage around the model area
* ``solver`` - the algorithm to solve the least squares problem e.g. ``lu`` for lower upper decomposition, ``cg`` for conjugate gradient, ``pyamg`` for an algorithmic multigrid solver
* ``damp - bool`` - whether to add a small number to the diagonal of the interpolation matrix for discrete interpolators - this can help speed up the solver and makes the solution more stable for some interpolators"""
self.print_terminal("-> create model...")
tic(parent=self)
model = GeologicalModel(origin, maximum)
toc(parent=self)
"""Link the input data dataframe to the model."""
self.print_terminal("-> set_model_data...")
tic(parent=self)
model.set_model_data(all_input_data_df)
toc(parent=self)
"""Add a foliation to the model"""
self.print_terminal("-> create_and_add_foliation...")
tic(parent=self)
# interpolator_type can be 'PLI', 'FDI' or 'surfe'
model.create_and_add_foliation(
"strati_0",
interpolator_type=options_dict["method"],
nelements=(dimensions[0] * dimensions[1] * dimensions[2]),
)
"""In version 1.1+ the implicit function representing a geological feature does not have to be solved to generate the model object.
The scalar field is solved on demand when the geological features are evaluated. This means that parts of the geological model
can be modified and only the older (features lower in the feature list) are updated.
All features in the model can be updated with model.update(verbose=True)."""
# model.update(verbose=True) # This will solve the implicit function for all features in the model and provide a progress bar -- causes crash
"""A GeologicalFeature can be extracted from the model either by name..."""
# my_feature = model[feature_name_value] # useful?
"""A regular grid inside the model bounding box can be retrieved in the following way:
- nsteps defines how many points in x, y and z
- shuffle defines whether the points should be ordered by axis x, y, z (False?) or random (True?).
- rescale defines whether the returned points should be in model coordinates or real world coordinates."""
"""Set calculation grid resolution. Default resolution is set as to obtain a model close to 10000 cells.
FOR THE FUTURE: anisotropic resolution?"""
# rescale is True by default
regular_grid = model.regular_grid(nsteps=dimensions, shuffle=False, rescale=False)
toc(parent=self)
"""Evaluate scalar field."""
self.print_terminal("-> evaluate_feature_value...")
tic(parent=self)
scalar_field = model.evaluate_feature_value("strati_0", regular_grid, scale=False)
scalar_field = scalar_field.reshape((dimension_x, dimension_y, dimension_z))
# OLD ----------------
# VTK image data is ordered (z,y,x) in memory, while the Loop Structural output
# Numpy array is ordered as regular_grid, so (x,y,-z). See explanations on VTK here:
# https://discourse.vtk.org/t/numpy-tensor-to-vtkimagedata/5154/3
# https://discourse.vtk.org/t/the-direction-of-vtkimagedata-make-something-wrong/4997
# scalar_field = scalar_field[:, :, ::-1]
# scalar_field = np_flip(scalar_field, 2)
# OLD ----------------
# NEW ----------------
# It looks like that the Numpy output from LoopStructural now is
# ordered as (x,y,z), so inverting the 'z' is no more required.
# NEW ----------------
scalar_field = scalar_field.transpose(2, 1, 0)
scalar_field = scalar_field.ravel() # flatten returns a copy
# """Evaluate scalar field gradient."""
# print("-> evaluate_feature_gradient...")
# scalar_field_gradient = model.evaluate_feature_gradient("strati_0", regular_grid, scale=False)
toc(parent=self)
"""Create deepcopy of the Mesh3D entity dictionary."""
self.print_terminal("-> create Voxet...")
tic(parent=self)
voxet_dict = deepcopy(self.mesh3d_coll.entity_dict)
"""Get output Voxet name."""
model_name = input_text_dialog(
title="Implicit Modelling - LoopStructural algorithms",
label="Name of the output Voxet",
default_text="Loop_model",
)
if model_name is None:
model_name = "Loop_model"
print(model_name)
voxet_dict["name"] = model_name
voxet_dict["topology"] = "Voxet"
voxet_dict["properties_names"] = ["strati_0"]
voxet_dict["properties_components"] = [1]
"""Create new instance of Voxet() class"""
voxet_dict["vtk_obj"] = Voxet()
"""Set origin, dimensions and spacing of the output Voxet."""
voxet_dict["vtk_obj"].origin = [
origin_x + spacing_x / 2,
origin_y + spacing_y / 2,
origin_z + spacing_z / 2,
]
voxet_dict["vtk_obj"].dimensions = dimensions
voxet_dict["vtk_obj"].spacing = spacing
print(voxet_dict)
toc(parent=self)
"""Pass calculated values of the LoopStructural model to the Voxet, as scalar fields"""
self.print_terminal("-> populate Voxet...")
tic(parent=self)
voxet_dict["vtk_obj"].set_point_data(data_key="strati_0", attribute_matrix=scalar_field)
"""Create new entity in mesh3d_coll from the populated voxet dictionary"""
if voxet_dict["vtk_obj"].points_number > 0:
self.mesh3d_coll.add_entity_from_dict(voxet_dict)
else:
self.print_terminal(" -- empty object -- ")
return
voxet_dict["vtk_obj"].Modified()
toc(parent=self)
"""Extract isosurfaces with vtkFlyingEdges3D. Documentation in:
https://vtk.org/doc/nightly/html/classvtkFlyingEdges3D.html
https://python.hotexamples.com/examples/vtk/-/vtkFlyingEdges3D/python-vtkflyingedges3d-function-examples.html"""
self.print_terminal("-> extract isosurfaces...")
tic(parent=self)
for value in all_input_data_df["val"].dropna().unique():
value = float(value)
voxet_dict["vtk_obj"].GetPointData().SetActiveScalars("strati_0")
self.print_terminal(f"-> extract iso-surface at value = {value}")
"""Get metadata of first geological feature of this time"""
role = self.geol_coll.legend_df.loc[
self.geol_coll.legend_df["time"] == value, "role"
].values[0]
feature = self.geol_coll.legend_df.loc[
self.geol_coll.legend_df["time"] == value, "feature"
].values[0]
scenario = self.geol_coll.legend_df.loc[
self.geol_coll.legend_df["time"] == value, "scenario"
].values[0]
"""Iso-surface algorithm"""
iso_surface = vtkContourFilter()
# iso_surface = vtkFlyingEdges3D()
# iso_surface = vtkMarchingCubes()
iso_surface.SetInputData(voxet_dict["vtk_obj"])
iso_surface.ComputeScalarsOn()
iso_surface.ComputeGradientsOn()
iso_surface.SetArrayComponent(0)
iso_surface.GenerateTrianglesOn()
iso_surface.UseScalarTreeOn()
iso_surface.SetValue(0, value)
iso_surface.Update()
"""Create new TriSurf and populate with iso-surface"""
surf_dict = deepcopy(self.geol_coll.entity_dict)
surf_dict["name"] = feature + "_from_" + model_name
surf_dict["topology"] = "TriSurf"
surf_dict["role"] = role
surf_dict["feature"] = feature
surf_dict["scenario"] = scenario
surf_dict["vtk_obj"] = TriSurf()
surf_dict["vtk_obj"].ShallowCopy(iso_surface.GetOutput())
surf_dict["vtk_obj"].Modified()
if isinstance(surf_dict["vtk_obj"].points, np_ndarray):
if len(surf_dict["vtk_obj"].points) > 0:
"""Add entity to geological collection only if it is not empty"""
self.geol_coll.add_entity_from_dict(surf_dict)
self.print_terminal(f"-> iso-surface at value = {value} has been created")
else:
self.print_terminal(" -- empty object -- ")
toc(parent=self)
self.print_terminal("Loop interpolation completed.")
@freeze_gui
def surface_smoothing(
self, mode=0, convergence_value=1, boundary_smoothing=False, edge_smoothing=False
):
"""Smoothing tools adjust the positions of points to reduce the noise content in the surface."""
self.print_terminal("Surface Smoothing: reduce the noise of the surface")
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be modified -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deseselcted while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if isinstance(self.geol_coll.get_uid_vtk_obj(uid), TriSurf):
smoother = vtkSmoothPolyDataFilter()
smoother.SetInputData(self.geol_coll.get_uid_vtk_obj(uid))
if convergence_value is None:
convergence_value = 1
smoother.SetConvergence(float(convergence_value))
smoother.SetBoundarySmoothing(boundary_smoothing)
smoother.SetFeatureEdgeSmoothing(edge_smoothing)
smoother.Update()
if mode:
return smoother.GetOutput()
else:
"""Create deepcopy of the geological entity dictionary."""
surf_dict = deepcopy(self.geol_coll.entity_dict)
surf_dict["name"] = self.geol_coll.get_uid_name(uid) + "_smoothed"
surf_dict[
"feature"
] = self.geol_coll.get_uid_feature(uid)
surf_dict["scenario"] = self.geol_coll.get_uid_scenario(uid)
surf_dict["role"] = self.geol_coll.get_uid_role(
uid
)
surf_dict["topology"] = "TriSurf"
surf_dict["vtk_obj"] = TriSurf()
surf_dict["vtk_obj"].ShallowCopy(smoother.GetOutput())
surf_dict["vtk_obj"].Modified()
if surf_dict["vtk_obj"].points_number > 0:
self.geol_coll.add_entity_from_dict(surf_dict)
else:
self.print_terminal(" -- empty object -- ")
else:
self.print_terminal(" -- Error input type: only TriSurf type -- ")
return
# """Create deepcopy of the geological entity dictionary."""
# surf_dict = deepcopy(self.geol_coll.entity_dict)
# input_dict = {'name': ['TriSurf name: ', self.geol_coll.get_uid_name(input_uids[0]) + '_smooth'], 'role': ['Role: ', self.parent.geol_coll.valid_roles], 'feature': ['Feature: ', self.geol_coll.get_uid_feature(input_uids[0])], 'scenario': ['Scenario: ', self.geol_coll.get_uid_scenario(input_uids[0])]}
# surf_dict_updt = multiple_input_dialog(title='Surface smoothing', input_dict=input_dict)
# """Check if the output of the widget is empty or not. If the Cancel button was clicked, the tool quits"""
# if surf_dict_updt is None:
# return
# """Getting the values that have been typed by the user through the multiple input widget"""
# for key in surf_dict_updt:
# surf_dict[key] = surf_dict_updt[key]
# surf_dict['topology'] = 'TriSurf'
# surf_dict['vtk_obj'] = TriSurf()
# """Create a new instance of the interpolation class"""
# smoother = vtkSmoothPolyDataFilter()
# smoother.SetInputData(self.geol_coll.get_uid_vtk_obj(input_uids[0]))
# """Ask for the Convergence value (smaller numbers result in more smoothing iterations)."""
# convergence_value = input_one_value_dialog(title='Surface smoothing parameters', label='Convergence Value (small values result in more smoothing)', default_value=1)
# if convergence_value is None:
# convergence_value = 1
# smoother.SetConvergence(convergence_value)
# """Ask for BoundarySmoothing (smoothing of vertices on the boundary of the mesh) and FeatureEdgeSmoothing
# (smoothing along sharp interior edges)."""
# boundary_smoothing = input_text_dialog(title='Surface smoothing parameters', label='Boundary Smoothing (ON/OFF)', default_text='OFF')
# if boundary_smoothing is None:
# pass
# elif boundary_smoothing == 'ON' or boundary_smoothing == 'on':
# smoother.SetBoundarySmoothing(True)
# elif boundary_smoothing == 'OFF' or boundary_smoothing == 'off':
# smoother.SetBoundarySmoothing(False)
# edge_smooth_switch = input_text_dialog(title='Surface smoothing parameters', label='Feature Edge Smoothing (ON/OFF)', default_text='OFF')
# if edge_smooth_switch is None:
# pass
# elif edge_smooth_switch == 'ON' or edge_smooth_switch == 'on':
# smoother.SetBoundarySmoothing(True)
# elif edge_smooth_switch == 'OFF' or edge_smooth_switch == 'off':
# smoother.SetFeatureEdgeSmoothing(False)
# smoother.Update()
# """ShallowCopy is the way to copy the new interpolated surface into the TriSurf instance created at the beginning"""
# surf_dict['vtk_obj'].ShallowCopy(smoother.GetOutput())
# surf_dict['vtk_obj'].Modified()
# """Add new entity from surf_dict. Function add_entity_from_dict creates a new uid"""
# if surf_dict['vtk_obj'].points_number > 0:
# self.geol_coll.add_entity_from_dict(surf_dict)
# else:
# print(" -- empty object -- ")
@freeze_gui
def linear_extrusion(self):
"""vtkLinearExtrusionFilter sweeps the generating primitives along a straight line path. This tool is here
used to create fault surfaces from faults traces."""
self.print_terminal(
"Linear extrusion: create surface by projecting target linear object along a straight line path"
)
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be projected -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deselected while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if isinstance(self.geol_coll.get_uid_vtk_obj(uid), PolyLine) or isinstance(
self.geol_coll.get_uid_vtk_obj(uid), XsPolyLine
):
pass
else:
self.print_terminal(" -- Error input type: only PolyLine and XsPolyLine type -- ")
return
"""Create deepcopy of the geological entity dictionary."""
surf_dict = deepcopy(self.geol_coll.entity_dict)
input_dict = {
"name": [
"TriSurf name: ",
self.geol_coll.get_uid_name(input_uids[0]) + "_extruded",
],
"role": [
"Role: ",
self.parent.geol_coll.valid_roles,
],
"feature": [
"Feature: ",
self.geol_coll.get_uid_feature(input_uids[0]),
],
"scenario": ["Scenario: ", self.geol_coll.get_uid_scenario(input_uids[0])],
}
surf_dict_updt = multiple_input_dialog(
title="Linear Extrusion", input_dict=input_dict
)
"""Check if the output of the widget is empty or not. If the Cancel button was clicked, the tool quits"""
if surf_dict_updt is None:
return
"""Getting the values that have been typed by the user through the multiple input widget"""
for key in surf_dict_updt:
surf_dict[key] = surf_dict_updt[key]
surf_dict["topology"] = "TriSurf"
surf_dict["vtk_obj"] = TriSurf()
"""Check if the output of the widget is empty or not. If the Cancel button was clicked, the tool quits"""
if surf_dict_updt is None:
return
"""Ask for trend/plunge of the vector to use for the linear extrusion"""
trend = input_one_value_dialog(
title="Linear Extrusion", label="Trend Value", default_value=90.0
)
if trend is None:
trend = 90.00
plunge = input_one_value_dialog(
title="Linear Extrusion", label="Plunge Value", default_value=30.0
)
if plunge is None:
plunge = 30.0
"""Ask for vertical extrusion: how extruded will the surface be?"""
extrusion_par = {"bottom": ["Lower limit:", -1000], "top": ["Higher limit", 1000]}
vertical_extrusion = multiple_input_dialog(
title="Vertical Extrusion", input_dict=extrusion_par
)
if vertical_extrusion is None:
self.print_terminal("Wrong extrusion parameters, please check the top and bottom values")
return
total_extrusion = vertical_extrusion["top"] + np_abs(vertical_extrusion["bottom"])
linear_extrusion = vtkLinearExtrusionFilter()
linear_extrusion.CappingOn() # yes or no?
linear_extrusion.SetExtrusionTypeToVectorExtrusion()
"""Direction cosines"""
x_vector = -(np_cos((trend - 90) * np_pi / 180) * np_cos(plunge * np_pi / 180))
y_vector = np_sin((trend - 90) * np_pi / 180) * np_cos(plunge * np_pi / 180)
z_vector = np_sin(plunge * np_pi / 180)
linear_extrusion.SetVector(
x_vector, y_vector, z_vector
) # double,double,double format
linear_extrusion.SetScaleFactor(total_extrusion) # double format
linear_extrusion.SetInputData(self.geol_coll.get_uid_vtk_obj(input_uids[0]))
linear_extrusion.Update()
# [Gabriele] The output of vtkLinearExtrusionFilter() are triangle strips we convert them to triangles with vtkTriangleFilter
triangle_filt = vtkTriangleFilter()
triangle_filt.SetInputConnection(linear_extrusion.GetOutputPort())
triangle_filt.Update()
# [Gabriele] translate the plane using the xyz vector with intensity = negative extrusion value.
translate = vtkTransform()
translate.Translate(
x_vector * vertical_extrusion["bottom"],
y_vector * vertical_extrusion["bottom"],
z_vector * vertical_extrusion["bottom"],
)
transform_filter = vtkTransformPolyDataFilter()
transform_filter.SetTransform(translate)
transform_filter.SetInputConnection(triangle_filt.GetOutputPort())
transform_filter.Update()
out_polydata = transform_filter.GetOutput()
"""ShallowCopy is the way to copy the new interpolated surface into the TriSurf instance created at the beginning"""
surf_dict["vtk_obj"].ShallowCopy(out_polydata)
surf_dict["vtk_obj"].Modified()
"""Add new entity from surf_dict. Function add_entity_from_dict creates a new uid"""
if surf_dict["vtk_obj"].points_number > 0:
self.geol_coll.add_entity_from_dict(surf_dict)
else:
self.print_terminal(" -- empty object -- ")
@freeze_gui
def decimation_pro_resampling(self):
"""Decimation reduces the number of triangles in a triangle mesh while maintaining a faithful approximation to
the original mesh."""
self.print_terminal(
"Decimation Pro: resample target surface and reduce number of triangles of the mesh"
)
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be resampled -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deseselcted while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if isinstance(self.geol_coll.get_uid_vtk_obj(uid), TriSurf):
pass
else:
self.print_terminal(" -- Error input type: only TriSurf type -- ")
return
"""Create deepcopy of the geological entity dictionary."""
surf_dict = deepcopy(self.geol_coll.entity_dict)
surf_dict["name"] = self.geol_coll.get_uid_name(input_uids[0]) + "_decimated"
surf_dict["feature"] = self.geol_coll.get_uid_feature(
input_uids[0]
)
surf_dict["scenario"] = self.geol_coll.get_uid_scenario(input_uids[0])
surf_dict["role"] = self.geol_coll.get_uid_role(input_uids[0])
surf_dict["topology"] = "TriSurf"
surf_dict["vtk_obj"] = TriSurf()
"""Create a new instance of the decimation class"""
deci = vtkDecimatePro()
deci.SetInputData(self.geol_coll.get_uid_vtk_obj(input_uids[0]))
"""Target Reduction value. Specify the desired reduction in the total number of polygons (e.g., when
Target Reduction is set to 0.9, this filter will try to reduce the data set to 10% of its original size)."""
tar_reduct = input_one_value_dialog(
title="Decimation Resampling parameters",
label="Target Reduction Value",
default_value=0.5,
)
if tar_reduct is None:
tar_reduct = 0.5
deci.SetTargetReduction(tar_reduct)
"""Preserve Topology switch. Turn on/off whether to preserve the topology of the original mesh."""
preserve_topology = input_text_dialog(
title="Decimation Resampling parameters",
label="Preserve Topology (ON/OFF)",
default_text="ON",
)
if preserve_topology is None:
pass
elif preserve_topology == "ON" or preserve_topology == "on":
deci.PreserveTopologyOn()
elif preserve_topology == "OFF" or preserve_topology == "off":
deci.PreserveTopologyOff()
"""Boundary Vertex Deletion switch. Turn on/off the deletion of vertices on the boundary of a mesh."""
bound_vert_del = input_text_dialog(
title="Decimation Resampling parameters",
label="Boundary Vertex Deletion (ON/OFF)",
default_text="OFF",
)
if bound_vert_del is None:
pass
elif bound_vert_del == "ON" or bound_vert_del == "on":
deci.BoundaryVertexDeletionOn()
elif bound_vert_del == "OFF" or bound_vert_del == "off":
deci.BoundaryVertexDeletionOff()
"""Splitting switch. Turn on/off the splitting of the mesh at corners, along edges, at non-manifold points, or
anywhere else a split is required."""
splitting = input_text_dialog(
title="Decimation Resampling parameters",
label="Splitting (ON to preserve original topology/OFF)",
default_text="ON",
)
if splitting is None:
pass
elif splitting == "ON" or splitting == "on":
deci.SplittingOn()
elif splitting == "OFF" or splitting == "off":
deci.SplittingOff()
deci.Update()
"""ShallowCopy is the way to copy the new interpolated surface into the TriSurf instance created at the beginning"""
surf_dict["vtk_obj"].ShallowCopy(deci.GetOutput())
surf_dict["vtk_obj"].Modified()
"""Add new entity from surf_dict. Function add_entity_from_dict creates a new uid"""
if surf_dict["vtk_obj"].points_number > 0:
self.geol_coll.add_entity_from_dict(surf_dict)
else:
self.print_terminal(" -- empty object -- ")
@freeze_gui
def decimation_quadric_resampling(self):
"""Decimation reduces the number of triangles in a triangle mesh while maintaining a faithful approximation to
the original mesh."""
self.print_terminal(
"Decimation Quadric: resample target surface and reduce number of triangles of the mesh"
)
if self.shown_table != "tabGeology":
self.print_terminal(" -- Only geological objects can be resampled -- ")
return
"""Check if some vtkPolyData is selected"""
if not self.selected_uids:
self.print_terminal("No input data selected.")
return
else:
"""Deep copy list of selected uids needed otherwise problems can arise if the main geology table is deseselcted while the dataframe is being built"""
input_uids = deepcopy(self.selected_uids)
for uid in input_uids:
if isinstance(self.geol_coll.get_uid_vtk_obj(uid), TriSurf):
pass
else: