/
data.py
2974 lines (2318 loc) · 113 KB
/
data.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
import re
import sys
import warnings
from typing import Union
import numpy as np
import pandas as pn
try:
import ipywidgets as widgets
ipywidgets_import = True
except ModuleNotFoundError:
VTK_IMPORT = False
# This is for sphenix to find the packages
from gempy.core.grid_modules import grid_types
from gempy.core.checkers import check_for_nans
from gempy.utils.meta import setdoc, setdoc_pro
import gempy.utils.docstring as ds
pn.options.mode.chained_assignment = None
class MetaData(object):
"""Class containing metadata of the project.
Set of attributes and methods that are not related directly with the geological model but more with the project
Args:
project_name (str): Name of the project. This is use as default value for some I/O actions
Attributes:
date (str): Time of the creations of the project
project_name (str): Name of the project. This is use as default value for some I/O actions
"""
def __init__(self, project_name='default_project'):
import datetime
now = datetime.datetime.now()
self.date = now.strftime(" %Y-%m-%d %H:%M")
if project_name is 'default_project':
project_name += self.date
self.project_name = project_name
@setdoc_pro([grid_types.RegularGrid.__doc__, grid_types.CustomGrid.__doc__])
class Grid(object):
""" Class to generate grids.
This class is used to create points where to
evaluate the geological model. This class serves a container which transmit the XYZ coordinates to the
interpolator. There are several type of grids objects will feed into the Grid class
Args:
**kwargs: See below
Keyword Args:
regular (:class:`gempy.core.grid_modules.grid_types.RegularGrid`): [s0]
custom (:class:`gempy.core.grid_modules.grid_types.CustomGrid`): [s1]
topography (:class:`gempy.core.grid_modules.grid_types.Topography`): [s2]
sections (:class:`gempy.core.grid_modules.grid_types.Sections`): [s3]
gravity (:class:`gempy.core.grid_modules.grid_types.Gravity`):
Attributes:
values (np.ndarray): coordinates where the model is going to be evaluated. This are the coordinates
concatenation of all active grids.
values_r (np.ndarray): rescaled coordinates where the model is going to be evaluated
length (np.ndarray):I a array which contain the slicing index for each grid type in order. The first element will
be 0, the second the length of the regular grid; the third custom and so on. This can be used to slice the
solutions correspondent to each of the grids
grid_types(np.ndarray[str]): names of the current grids of GemPy
active_grids(np.ndarray[bool]): boolean array which control which type of grid is going to be computed and
hence on the property `values`.
regular_grid (:class:`gempy.core.grid_modules.grid_types.RegularGrid`)
custom_grid (:class:`gempy.core.grid_modules.grid_types.CustomGrid`)
topography (:class:`gempy.core.grid_modules.grid_types.Topography`)
sections (:class:`gempy.core.grid_modules.grid_types.Sections`)
gravity_grid (:class:`gempy.core.grid_modules.grid_types.Gravity`)
"""
def __init__(self, **kwargs):
self.values = np.empty((0, 3))
self.values_r = np.empty((0, 3))
self.length = np.empty(0)
self.grid_types = np.array(['regular', 'custom', 'topography', 'sections', 'centered'])
self.active_grids = np.zeros(5, dtype=bool)
# All grid types must have values
# Init optional grids
self.custom_grid = None
self.custom_grid_grid_active = False
self.topography = None
self.topography_grid_active = False
self.sections_grid_active = False
self.centered_grid = None
self.centered_grid_active = False
# Init basic grid empty
self.regular_grid = self.create_regular_grid(set_active=False, **kwargs)
self.regular_grid_active = False
# Init optional sections
self.sections = grid_types.Sections(regular_grid=self.regular_grid)
self.update_grid_values()
def __str__(self):
return 'Grid Object. Values: \n' + np.array2string(self.values)
def __repr__(self):
return 'Grid Object. Values: \n' + np.array_repr(self.values)
@setdoc(grid_types.RegularGrid.__doc__)
def create_regular_grid(self, extent=None, resolution=None, set_active=True, *args, **kwargs):
"""
Set a new regular grid and activate it.
Args:
extent (np.ndarray): [x_min, x_max, y_min, y_max, z_min, z_max]
resolution (np.ndarray): [nx, ny, nz]
RegularGrid Docs
"""
self.regular_grid = grid_types.RegularGrid(extent, resolution, **kwargs)
if set_active is True:
self.set_active('regular')
return self.regular_grid
@setdoc_pro(ds.coord)
def create_custom_grid(self, custom_grid: np.ndarray):
"""
Set a new regular grid and activate it.
Args:
custom_grid (np.array): [s0]
"""
self.custom_grid = grid_types.CustomGrid(custom_grid)
self.set_active('custom')
def create_topography(self, source='random', **kwargs):
"""
Create a topography grid and activate it.
Args:
source:
'gdal': Load topography from a raster file.
'random': Generate random topography (based on a fractal grid).
'saved': Load topography that was saved with the topography.save() function.
This is useful after loading and saving a heavy raster file with gdal once or after saving a
random topography with the save() function. This .npy file can then be set as topography.
Kwargs:
if source = 'gdal:
filepath: path to raster file, e.g. '.tif', (for all file formats see https://gdal.org/drivers/raster/index.html)
if source = 'random':
fd: fractal dimension, defaults to 2.0
d_z: maximum height difference. If none, last 20% of the model in z direction
extent: extent in xy direction. If none, geo_model.grid.extent
resolution: desired resolution of the topography array. If none, geo_model.grid.resoution
if source = 'saved':
filepath: path to the .npy file that was created using the topography.save() function
Returns: :class:gempy.core.data.Topography
"""
self.topography = grid_types.Topography(self.regular_grid)
if source == 'random':
self.topography.load_random_hills(**kwargs)
elif source == 'gdal':
filepath = kwargs.get('filepath', None)
if filepath is not None:
self.topography.load_from_gdal(filepath)
else:
print('to load a raster file, a path to the file must be provided')
elif source == 'saved':
filepath = kwargs.get('filepath', None)
if filepath is not None:
self.topography.load_from_saved(filepath)
else:
print('path to .npy file must be provided')
else:
raise AttributeError('source must be random, gdal or saved')
self.topography.show()
self.set_active('topography')
@setdoc(grid_types.Sections.__doc__)
def create_section_grid(self, section_dict):
self.sections = grid_types.Sections(regular_grid=self.regular_grid, section_dict=section_dict)
self.set_active('sections')
return self.sections
@setdoc(grid_types.CenteredGrid.set_centered_grid.__doc__)
def create_centered_grid(self, centers, radius, resolution=None):
"""Initialize gravity grid. Deactivate the rest of the grids"""
self.centered_grid = grid_types.CenteredGrid(centers, radius, resolution)
# self.active_grids = np.zeros(4, dtype=bool)
self.set_active('centered')
def deactivate_all_grids(self):
"""
Deactivates the active grids array
:return:
"""
self.active_grids = np.zeros(5, dtype=bool)
self.update_grid_values()
return self.active_grids
def set_active(self, grid_name: Union[str, np.ndarray]):
"""
Set active a given or several grids
Args:
grid_name (str, list):
"""
where = self.grid_types == grid_name
self.active_grids[where] = True
self.update_grid_values()
return self.active_grids
def set_inactive(self, grid_name: str):
where = self.grid_types == grid_name
self.active_grids *= ~where
self.update_grid_values()
return self.active_grids
def update_grid_values(self):
"""
Copy XYZ coordinates from each specific grid to Grid.values for those which are active.
Returns:
values
"""
self.length = np.empty(0)
self.values = np.empty((0, 3))
lengths = [0]
try:
for e, grid_types in enumerate([self.regular_grid, self.custom_grid, self.topography, self.sections, self.centered_grid]):
if self.active_grids[e]:
self.values = np.vstack((self.values, grid_types.values))
lengths.append(grid_types.values.shape[0])
else:
lengths.append(0)
except AttributeError:
raise AttributeError('Grid type does not exist yet. Set the grid before activating it.')
self.length = np.array(lengths).cumsum()
return self.values
def get_grid_args(self, grid_name: str):
assert type(grid_name) is str, 'Only one grid type can be retrieved'
assert grid_name in self.grid_types, 'possible grid types are ' + str(self.grid_types)
where = np.where(self.grid_types == grid_name)[0][0]
return self.length[where], self.length[where+1]
def get_grid(self, grid_name: str):
assert type(grid_name) is str, 'Only one grid type can be retrieved'
l_0, l_1 = self.get_grid_args(grid_name)
return self.values[l_0:l_1]
def get_section_args(self, section_name: str):
#assert type(section_name) is str, 'Only one section type can be retrieved'
l0, l1 = self.get_grid_args('sections')
where = np.where(self.sections.names == section_name)[0][0]
return l0 + self.sections.length[where], l0 + self.sections.length[where+1]
class Faults(object):
"""
Class that encapsulate faulting related content. Mainly, which surfaces/surfaces are faults. The fault network
---i.e. which faults offset other faults---and fault types---finite vs infinite.
Args:
series_fault(str, list[str]): Name of the series which are faults
rel_matrix (numpy.array[bool]): 2D Boolean array with boolean logic. Rows affect (offset) columns
Attributes:
df (:class:`pn.core.frame.DataFrames`): Pandas data frame containing the series as index and if they are faults
or not (otherwise they are lithologies) and in case of being fault if is finite
faults_relations_df (:class:`pn.core.frame.DataFrames`): Pandas data frame containing the offsetting relations
between each fault and the rest of the series (either other faults or lithologies)
n_faults (int): Number of faults in the object
"""
def __init__(self, series_fault=None, rel_matrix=None):
self.df = pn.DataFrame(np.array([[False, False]]), index=pn.CategoricalIndex(['Default series']),
columns=['isFault', 'isFinite'], dtype=bool)
self.faults_relations_df = pn.DataFrame(index=pn.CategoricalIndex(['Default series']),
columns=pn.CategoricalIndex(['Default series', '']), dtype='bool')
self.set_is_fault(series_fault=series_fault)
self.set_fault_relation(rel_matrix=rel_matrix)
self.n_faults = 0
self._offset_faults = False
def __repr__(self):
return self.df.to_string()
def _repr_html_(self):
return self.df.to_html()
# def sort_faults(self):
# self.df.sort_index(inplace=True)
# self.faults_relations_df.sort_index(inplace=True)
# self.faults_relations_df.sort_index(axis=1, inplace=True)
def set_is_fault(self, series_fault: Union[str, list, np.ndarray] = None, toggle=False, offset_faults=False):
"""
Set a flag to the series that are faults.
Args:
series_fault(str, list[str]): Name of the series which are faults
toggle (bool): if True, passing a name which is already True will set it False.
offset_faults (bool): If True by default faults offset other faults
Returns:
Faults
"""
series_fault = np.atleast_1d(series_fault)
self.df['isFault'].fillna(False, inplace=True)
if series_fault is None:
series_fault = self.count_faults(self.df.index)
if series_fault[0] is not None:
assert np.isin(series_fault, self.df.index).all(), 'series_faults must already ' \
'exist in the the series df.'
if toggle is True:
self.df.loc[series_fault, 'isFault'] = self.df.loc[series_fault, 'isFault'] ^ True
else:
self.df.loc[series_fault, 'isFault'] = True
self.df['isFinite'] = np.bitwise_and(self.df['isFault'], self.df['isFinite'])
self.set_default_faults_relations(offset_faults)
# Update default fault relations
for a_series in series_fault:
col_pos = self.faults_relations_df.columns.get_loc(a_series)
# set the faults offset all younger
self.faults_relations_df.iloc[col_pos, col_pos + 1:] = True
if offset_faults is False:
# set the faults does not offset the younger faults
self.faults_relations_df.iloc[col_pos] = ~self.df['isFault'] & \
self.faults_relations_df.iloc[col_pos]
self.n_faults = self.df['isFault'].sum()
return self
def set_default_faults_relations(self, offset_faults:bool=None):
if offset_faults is not None:
self._offset_faults = offset_faults
offset_faults = self._offset_faults
try:
# Update default fault relations
for a_series in self.df.groupby('isFault').get_group(True).index:
col_pos = self.faults_relations_df.columns.get_loc(a_series)
# set the faults offset all younger
self.faults_relations_df.iloc[col_pos, col_pos + 1:] = True
if offset_faults is False:
# set the faults does not offset the younger faults
self.faults_relations_df.iloc[col_pos] = ~self.df['isFault'] & \
self.faults_relations_df.iloc[col_pos]
return True
except KeyError:
return False
def set_is_finite_fault(self, series_finite: Union[str, list, np.ndarray] = None, toggle=False):
"""
Toggles given series' finite fault property.
Args:
series_finite (str, list[str]): Name of the series which are finite
toggle (bool): if True, passing a name which is already True will set it False.
Returns:
Fault
"""
if series_finite[0] is not None:
# check if given series is/are in dataframe
assert np.isin(series_finite, self.df.index).all(), "series_fault must already exist" \
"in the series DataFrame."
assert self.df.loc[series_finite].isFault.all(), "series_fault contains non-fault series" \
", which can't be set as finite faults."
# if so, toggle True/False for given series or list of series
if toggle is True:
self.df.loc[series_finite, 'isFinite'] = self.df.loc[series_finite, 'isFinite'] ^ True
else:
self.df.loc[series_finite, 'isFinite'] = True
return self
def set_fault_relation(self, rel_matrix=None):
"""
Method to set the df that offset a given sequence and therefore also another fault.
Args:
rel_matrix (numpy.array[bool]): 2D Boolean array with boolean logic. Rows affect (offset) columns
"""
# TODO: block the lower triangular matrix of being changed
if rel_matrix is None:
rel_matrix = np.zeros((self.df.index.shape[0],
self.df.index.shape[0]))
else:
assert type(rel_matrix) is np.ndarray, 'rel_matrix muxt be a 2D numpy array'
self.faults_relations_df = pn.DataFrame(rel_matrix, index=self.df.index,
columns=self.df.index, dtype='bool')
self.faults_relations_df.iloc[np.tril(np.ones(self.df.index.shape[0])).astype(bool)] = False
return self.faults_relations_df
@staticmethod
def count_faults(list_of_names):
"""
Read the string names of the surfaces to detect automatically the number of df if the name
fault is on the name.
"""
faults_series = []
for i in list_of_names:
try:
if ('fault' in i or 'Fault' in i) and 'Default' not in i:
faults_series.append(i)
except TypeError:
pass
return faults_series
@setdoc_pro(Faults.__doc__)
class Series(object):
""" Class that contains the functionality and attributes related to the series. Notice that series does not only
refers to stratigraphic series but to any set of surfaces which will be interpolated together (comfortably).
Args:
faults (:class:`Faults`): [s0]
series_names(Optional[list]): name of the series. They are also ordered
Attributes:
df (:class:`pn.core.frame.DataFrames`): Pandas data frame containing the series and the surfaces contained
on them. TODO describe df columns
faults (:class:`Faults`)
"""
def __init__(self, faults, series_names: list = None):
self.faults = faults
if series_names is None:
series_names = ['Default series']
self.df = pn.DataFrame(np.array([[1, np.nan]]), index=pn.CategoricalIndex(series_names, ordered=False),
columns=['order_series', 'BottomRelation'])
self.df['order_series'] = self.df['order_series'].astype(int)
self.df['BottomRelation'] = pn.Categorical(['Erosion'], categories=['Erosion', 'Onlap', 'Fault'])
self.df['isActive'] = False
def __repr__(self):
return self.df.to_string()
def _repr_html_(self):
return self.df.to_html()
def reset_order_series(self):
"""
Reset the column order series to monotonic ascendant values.
"""
self.df.at[:, 'order_series'] = pn.RangeIndex(1, self.df.shape[0] + 1)
@setdoc_pro(reset_order_series.__doc__)
def set_series_index(self, series_order: Union[list, np.ndarray], reset_order_series=True):
"""
Rewrite the index of the series df
Args:
series_order (list, :class:`SurfacePoints`): List with names and order of series. If :class:`SurfacePoints`
is passed then the unique values will be taken.
reset_order_series (bool): if true [s0]
Returns:
:class:`Series`: Series
"""
if isinstance(series_order, SurfacePoints):
try:
list_of_series = series_order.df['series'].unique()
except KeyError:
raise KeyError('Interface does not have series attribute')
elif type(series_order) is list or type(series_order) is np.ndarray:
list_of_series = np.atleast_1d(series_order)
else:
raise AttributeError('series_order is not neither list or SurfacePoints object.')
series_idx = list_of_series
# Categorical index does not have inplace
# This update the categories
self.df.index = self.df.index.set_categories(series_idx, rename=True)
self.faults.df.index = self.faults.df.index.set_categories(series_idx, rename=True)
self.faults.faults_relations_df.index = self.faults.faults_relations_df.index.set_categories(
series_idx, rename=True)
self.faults.faults_relations_df.columns = self.faults.faults_relations_df.columns.set_categories(
series_idx, rename=True)
# But we need to update the values too
for c in series_order:
self.df.loc[c, 'BottomRelation'] = 'Erosion'
self.faults.df.loc[c] = [False, False]
self.faults.faults_relations_df.loc[c, c] = False
self.faults.faults_relations_df.fillna(False, inplace=True)
if reset_order_series is True:
self.reset_order_series()
return self
def set_bottom_relation(self, series_list: Union[str, list], bottom_relation: Union[str, list]):
"""Set the bottom relation between the series and the one below.
Args:
series_list (str, list): name or list of names of the series to apply the functionality
bottom_relation (str{Onlap, Erode, Fault}, list[str]):
Returns:
Series
"""
self.df.loc[series_list, 'BottomRelation'] = bottom_relation
if self.faults.df.loc[series_list, 'isFault'] is True:
self.faults.set_is_fault(series_list, toggle=True)
elif bottom_relation == 'Fault':
self.faults.df.loc[series_list, 'isFault'] = True
return self
@setdoc_pro(reset_order_series.__doc__)
def add_series(self, series_list: Union[str, list], reset_order_series=True):
""" Add series to the df
Args:
series_list (str, list): name or list of names of the series to apply the functionality
reset_order_series (bool): if true [s0]
Returns:
Series
"""
series_list = np.atleast_1d(series_list)
# Remove from the list categories that already exist
series_list = series_list[~np.in1d(series_list, self.df.index.categories)]
idx = self.df.index.add_categories(series_list)
self.df.index = idx
self.update_faults_index_rename()
for c in series_list:
self.df.loc[c, 'BottomRelation'] = 'Erosion'
self.faults.df.loc[c] = [False, False]
self.faults.faults_relations_df.loc[c, c] = False
self.faults.faults_relations_df.fillna(False, inplace=True)
if reset_order_series is True:
self.reset_order_series()
return self
@setdoc_pro([reset_order_series.__doc__, pn.DataFrame.drop.__doc__])
def delete_series(self, indices: Union[str, list], reset_order_series=True):
"""[s1]
Args:
indices (str, list): name or list of names of the series to apply the functionality
reset_order_series (bool): if true [s0]
Returns:
Series
"""
self.df.drop(indices, inplace=True)
self.faults.df.drop(indices, inplace=True)
self.faults.faults_relations_df.drop(indices, axis=0, inplace=True)
self.faults.faults_relations_df.drop(indices, axis=1, inplace=True)
idx = self.df.index.remove_unused_categories()
self.df.index = idx
self.update_faults_index_rename()
if reset_order_series is True:
self.reset_order_series()
return self
@setdoc_pro(pn.CategoricalIndex.rename_categories.__doc__)
def rename_series(self, new_categories: Union[dict, list]):
"""
[s0]
Args:
new_categories (list, dict):
* list-like: all items must be unique and the number of items in the new categories must match the
existing number of categories.
* dict-like: specifies a mapping from old categories to new. Categories not contained in the mapping are
passed through and extra categories in the mapping are ignored.
Returns:
"""
idx = self.df.index.rename_categories(new_categories)
self.df.index = idx
self.update_faults_index_rename()
return self
@setdoc_pro([pn.CategoricalIndex.reorder_categories.__doc__, pn.CategoricalIndex.sort_values.__doc__])
def reorder_series(self, new_categories: Union[list, np.ndarray]):
"""[s0] [s1]
Args:
new_categories (list): list with all series names in the desired order.
Returns:
Series
"""
idx = self.df.index.reorder_categories(new_categories).sort_values()
self.df = self.df.reindex(idx, copy=False)
self.reset_order_series()
self.update_faults_index_reorder()
return self
def modify_order_series(self, new_value: int, series_name: str):
"""
Replace to the new location the old series
Args:
new_value (int): New location
series_name (str): name of the series to be moved
Returns:
Series
"""
group = self.df['order_series']
assert np.isin(new_value, group), 'new_value must exist already in the order_surfaces group.'
old_value = group[series_name]
self.df['order_series'] = group.replace([new_value, old_value], [old_value, new_value])
self.sort_series()
self.update_faults_index_reorder()
return self
def sort_series(self):
self.df.sort_values(by='order_series', inplace=True)
self.df.index = self.df.index.reorder_categories(self.df.index.to_numpy())
def update_faults_index_rename(self):
idx = self.df.index
self.faults.df.index = idx
self.faults.faults_relations_df.index = idx
self.faults.faults_relations_df.columns = idx
# This is a hack for qgrid
# We need to add the qgrid special columns to categories
self.faults.faults_relations_df.columns = self.faults.faults_relations_df.columns.add_categories(
['index', 'qgrid_unfiltered_index'])
def update_faults_index_reorder(self):
idx = self.df.index
self.faults.df = self.faults.df.reindex(idx, copy=False)
self.faults.faults_relations_df = self.faults.faults_relations_df.reindex(idx, axis=0)
self.faults.faults_relations_df = self.faults.faults_relations_df.reindex(idx, axis=1)
self.faults.faults_relations_df.columns = self.faults.faults_relations_df.columns.add_categories(
['index', 'qgrid_unfiltered_index'])
self.faults.set_default_faults_relations()
class Colors:
"""
Object that handles the color management in the model.
"""
def __init__(self, surfaces):
self.surfaces = surfaces
def generate_colordict(self, out = False):
import seaborn as sns
"""generate colordict that assigns black to faults and random colors to surfaces"""
gp_defcols = ['#015482','#9f0052','#ffbe00','#728f02','#443988','#ff3f20','#5DA629']
# This can be the most horrible code of the whole package
for i in ['muted', 'pastel', 'deep', 'bright', 'dark', 'colorblind']:
s = sns.color_palette(i).as_hex()
gp_defcols += s
if len(gp_defcols) >= len(self.surfaces.df):
break
colordict = dict(zip(list(self.surfaces.df['surface']), gp_defcols[:len(self.surfaces.df)]))
self.colordict_default = colordict
if out:
return colordict
else:
self.colordict = colordict
def change_colors(self, cdict = None):
''' Updates the colors of the model.
Args:
cdict: dict with surface names mapped to hex color codes, e.g. {'layer1':'#6b0318'}
if None: opens jupyter widget to change colors interactively.
Returns: None
'''
assert ipywidgets_import, 'ipywidgets not imported. Make sure the library is installed.'
if cdict is not None:
self.update_colors(cdict)
return self.surfaces
else:
items = [widgets.ColorPicker(description=surface, value=color)
for surface, color in self.colordict.items()]
colbox = widgets.VBox(items)
print('Click to select new colors.')
display(colbox)
def on_change(v):
self.colordict[v['owner'].description] = v['new'] # update colordict
self._set_colors()
for cols in colbox.children:
cols.observe(on_change, 'value')
def update_colors(self, cdict=None):
''' Updates the colors in self.colordict and in surfaces_df.
Args:
cdict: dict with surface names mapped to hex color codes, e.g. {'layer1':'#6b0318'}
Returns: None
'''
if cdict is None:
# assert if one surface does not have color
try:
self._add_colors()
except AttributeError:
self.generate_colordict()
else:
for surf, color in cdict.items(): # map new colors to surfaces
# assert this because user can set it manually
assert surf in list(self.surfaces.df['surface']), str(surf) + ' is not a model surface'
assert re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color), str(color) + ' is not a HEX color code'
self.colordict[surf] = color
self._set_colors()
def _add_colors(self):
'''assign color to last entry of surfaces df or check isnull and assign color there'''
# can be done easier
new_colors = self.generate_colordict(out=True)
form2col = list(self.surfaces.df.loc[self.surfaces.df['color'].isnull(), 'surface'])
# this is the dict in-build function to update colors
self.colordict.update(dict(zip(form2col, [new_colors[x] for x in form2col])))
def _set_colors(self):
'''sets colordict in surfaces dataframe'''
for surf, color in self.colordict.items():
self.surfaces.df.loc[self.surfaces.df['surface'] == surf, 'color'] = color
def set_default_colors(self, surfaces = None):
if surfaces is not None:
self.colordict[surfaces] = self.colordict_default[surfaces]
self._set_colors()
def delete_colors(self, surfaces):
for surface in surfaces:
self.colordict.pop(surface, None)
self._set_colors()
def make_faults_black(self, series_fault):
faults_list = list(self.surfaces.df[self.surfaces.df.series.isin(series_fault)]['surface'])
for fault in faults_list:
if self.colordict[fault] == '#527682':
self.set_default_colors(fault)
else:
self.colordict[fault] = '#527682'
self._set_colors()
def reset_default_colors(self):
self.generate_colordict()
self._set_colors()
return self.surfaces
@setdoc_pro(Series.__doc__)
class Surfaces(object):
"""
Class that contains the surfaces of the model and the values of each of them.
Args:
surface_names (list or np.ndarray): list containing the names of the surfaces
series (:class:`Series`): [s0]
values_array (np.ndarray): 2D array with the values of each surface
properties names (list or np.ndarray): list containing the names of each properties
Attributes:
df (:class:`pn.core.frame.DataFrames`): Pandas data frame containing the surfaces names mapped to series and
the value used for each voxel in the final model.
series (:class:`Series`)
colors (:class:`Colors`)
"""
def __init__(self, series: Series, surface_names=None, values_array=None, properties_names=None):
self._columns = ['surface', 'series', 'order_surfaces', 'isBasement', 'isFault', 'isActive','color',
'vertices', 'edges', 'sfai', 'id']
self._columns_vis_drop = ['vertices', 'edges', 'sfai', 'isBasement', 'isFault']
self._n_properties = len(self._columns) - 1
self.series = series
self.colors = Colors(self)
df_ = pn.DataFrame(columns=self._columns)
self.df = df_.astype({'surface': str, 'series': 'category',
'order_surfaces': int, 'isBasement': bool, 'isFault': bool, 'isActive': bool,
'color': bool, 'id': int, 'vertices': object, 'edges': object})
if (np.array(sys.version_info[:2]) <= np.array([3, 6])).all():
self.df: pn.DataFrame
self.df['series'].cat.add_categories(['Default series'], inplace=True)
if surface_names is not None:
self.set_surfaces_names(surface_names)
if values_array is not None:
self.set_surfaces_values(values_array=values_array, properties_names=properties_names)
def __repr__(self):
c_ = self.df.columns[~(self.df.columns.isin(self._columns_vis_drop))]
return self.df[c_].to_string()
def _repr_html_(self):
c_ = self.df.columns[~(self.df.columns.isin(self._columns_vis_drop))]
return self.df[c_].style.applymap(self.background_color, subset=['color']).render()
def update_id(self, id_list: list = None):
"""
Set id of the layers (1 based)
Args:
id_list (list):
Returns:
:class:`Surfaces`:
"""
self.map_faults()
if id_list is None:
# This id is necessary for the faults
id_unique = self.df.reset_index().index + 1
self.df['id'] = id_unique
return self
def map_faults(self):
self.df['isFault'] = self.df['series'].map(self.series.faults.df['isFault'])
@staticmethod
def background_color(value):
if isinstance(value, str):
return "background-color: %s" % value
# region set formation names
def set_surfaces_names(self, surfaces_list: list, update_df=True):
"""
Method to set the names of the surfaces in order. This applies in the surface column of the df
Args:
surfaces_list (list[str]): list of names of surfaces. They are ordered.
update_df (bool): Update Surfaces.df columns with the default values
Returns:
:class:`Surfaces`:
"""
#if type(surfaces_list) is list or type(surfaces_list) is np.ndarray:
if isinstance(surfaces_list, (list, np.ndarray)):
surfaces_list = np.asarray(surfaces_list)
else:
raise AttributeError('list_names must be either array_like type')
# Deleting all columns if they exist
# TODO check if some of the names are in the df and not deleting them?
self.df.drop(self.df.index, inplace=True)
self.df['surface'] = surfaces_list
# Changing the name of the series is the only way to mutate the series object from surfaces
if update_df is True:
self.map_series()
self.update_id()
self.set_basement()
self.reset_order_surfaces()
self.colors.update_colors()
return self
def set_default_surface_name(self):
"""
Set the minimum number of surfaces to compute a model i.e. surfaces_names: surface1 and basement
Returns:
:class:`Surfaces`:
"""
if self.df.shape[0] == 0:
# TODO DEBUG: I am not sure that surfaces always has at least one entry. Check it
self.set_surfaces_names(['surface1', 'basement'])
return self
def set_surfaces_names_from_surface_points(self, surface_points):
"""
Set surfaces names from a :class:`Surface_points` object. This can be useful if the surface points are imported
from a table.
Args:
surface_points (:class:`Surface_points`):
Returns:
"""
self.set_surfaces_names(surface_points.df['surface'].unique())
return self
def add_surface(self, surface_list: Union[str, list], update_df=True):
""" Add surface to the df.
Args:
surface_list (str, list): name or list of names of the surfaces to apply the functionality
update_df (bool): Update Surfaces.df columns with the default values
Returns:
:class:`Surfaces`:
"""
surface_list = np.atleast_1d(surface_list)
# Remove from the list categories that already exist
surface_list = surface_list[~np.in1d(surface_list, self.df['surface'].values)]
for c in surface_list:
idx = self.df.index.max()
if idx is np.nan:
idx = -1
self.df.loc[idx + 1, 'surface'] = c
if update_df is True:
self.map_series()
self.update_id()
self.set_basement()
self.reset_order_surfaces()
self.colors.update_colors()
return self
@setdoc_pro([update_id.__doc__, pn.DataFrame.drop.__doc__])
def delete_surface(self, indices: Union[int, str, list, np.ndarray], update_id=True):
"""[s1]
Args:
indices (str, list): name or list of names of the series to apply the functionality
update_id (bool): if true [s0]
Returns:
:class:`Surfaces`:
"""
indices = np.atleast_1d(indices)
if indices.dtype == int:
self.df.drop(indices, inplace=True)
else:
self.df.drop(self.df.index[self.df['surface'].isin(indices)], inplace=True)
if update_id is True:
self.update_id()
self.set_basement()
self.reset_order_surfaces()
return self