/
DataManagement.py
1571 lines (1285 loc) · 68.9 KB
/
DataManagement.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
"""
This file is part of gempy.
gempy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gempy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gempy. If not, see <http://www.gnu.org/licenses/>.
"""
import os
from os import path
import sys
# This is for sphenix to find the packages
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
import copy
import numpy as np
import pandas as pn
from gempy import theanograf
import theano
pn.options.mode.chained_assignment = None #
class InputData(object):
"""
Class to import the raw data of the model and set data classifications into formations and series.
This objects will contain the main information of the model.
Args:
extent (list): [x_min, x_max, y_min, y_max, z_min, z_max]
Resolution ((Optional[list])): [nx, ny, nz]. Defaults to 50
path_i: Path to the data bases of interfaces. Default os.getcwd(),
path_f: Path to the data bases of foliations. Default os.getcwd()
Attributes:
extent(list): [x_min, x_max, y_min, y_max, z_min, z_max]
resolution ((Optional[list])): [nx, ny, nz]
Foliations(pandas.core.frame.DataFrame): Pandas data frame with the foliations data
Interfaces(pandas.core.frame.DataFrame): Pandas data frame with the interfaces data
series(pandas.core.frame.DataFrame): Pandas data frame which contains every formation within each series
"""
def __init__(self,
extent,
resolution=[50, 50, 50],
path_i=None, path_f=None,
**kwargs):
# Set extent and resolution
self.extent = np.array(extent)
self.resolution = np.array(resolution)
# Init number of faults
self.n_faults = 0
# TODO choose the default source of data. So far only csv
# Create the pandas dataframes
# if we dont read a csv we create an empty dataframe with the columns that have to be filled
self.foliations = pn.DataFrame(columns=['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity',
'formation', 'series', 'X_std', 'Y_std', 'Z_std',
'dip_std', 'azimuth_std'])
self.interfaces = pn.DataFrame(columns=['X', 'Y', 'Z', 'formation', 'series',
'X_std', 'Y_std', 'Z_std'])
if path_f or path_i:
self.import_data_csv(path_i=path_i, path_f=path_f)
# DEP-
# self._set_formations()
# If not provided set default series
self.series = self.set_series()
# DEP- self.set_formation_number()
# Compute gradients given azimuth and dips to plot data
self.calculate_gradient()
# Create default grid object. TODO: (Is this necessary now?)
self.grid = self.set_grid(extent=None, resolution=None, grid_type="regular_3D", **kwargs)
self.order_table()
# DEP
#self.geo_data_type = 'InputData'
self.potential_at_interfaces = 0
def import_data_csv(self, path_i, path_f, **kwargs):
"""
Method to import interfaces and foliations from csv. The format is the same as the export 3D model data of
GeoModeller (check in the input data folder for an example).
Args:
path_i (str): path to the csv table
path_f (str): path to the csv table
**kwargs: kwargs of Pandas load_csv
Attributes:
Foliations(pandas.core.frame.DataFrame): Pandas data frame with the foliations data
Interfaces(pandas.core.frame.DataFrame): Pandas data frame with the interfaces data
"""
if path_f:
self.foliations = self.load_data_csv(data_type="foliations", path=path_f, **kwargs)
assert set(['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation']).issubset(self.foliations.columns), \
"One or more columns do not match with the expected values " + str(self.foliations.columns)
if path_i:
self.interfaces = self.load_data_csv(data_type="interfaces", path=path_i, **kwargs)
assert set(['X', 'Y', 'Z', 'formation']).issubset(self.interfaces.columns), \
"One or more columns do not match with the expected values " + str(self.interfaces.columns)
def get_formations(self):
"""
Returns:
pandas.core.frame.DataFrame: Returns a list of formations
"""
return self.interfaces["formation"].unique()
def calculate_gradient(self):
"""
Calculate the gradient vector of module 1 given dip and azimuth to be able to plot the foliations
Attributes:
foliations: extra columns with components xyz of the unity vector.
"""
self.foliations['G_x'] = np.sin(np.deg2rad(self.foliations["dip"].astype('float'))) * \
np.sin(np.deg2rad(self.foliations["azimuth"].astype('float'))) * \
self.foliations["polarity"].astype('float')
self.foliations['G_y'] = np.sin(np.deg2rad(self.foliations["dip"].astype('float'))) * \
np.cos(np.deg2rad(self.foliations["azimuth"].astype('float'))) *\
self.foliations["polarity"].astype('float')
self.foliations['G_z'] = np.cos(np.deg2rad(self.foliations["dip"].astype('float'))) *\
self.foliations["polarity"].astype('float')
def calculate_orientations(self):
pass
# # DEP?
# def create_grid(self, extent=None, resolution=None, grid_type="regular_3D", **kwargs):
# """
# Method to initialize the class grid. So far is really simple and only has the regular grid type
#
# Args:
# grid_type (str): regular_3D or regular_2D (I am not even sure if regular 2D still working)
# **kwargs: Arbitrary keyword arguments.
#
# Returns:
# self.grid(GeMpy_core.grid): Object that contain different grids
# """
#
# if not extent:
# extent = self.extent
# if not resolution:
# resolution = self.resolution
#
# return self.GridClass(extent, resolution, grid_type=grid_type, **kwargs)
def set_grid(self, new_grid=None, extent=None, resolution=None, grid_type="regular_3D", **kwargs):
"""
Method to initialize the class new_grid. So far is really simple and only has the regular new_grid type
Args:
grid_type (str): regular_3D or regular_2D (I am not even sure if regular 2D still working)
**kwargs: Arbitrary keyword arguments.
Returns:
self.new_grid(GeMpy_core.new_grid): Object that contain different grids
"""
if new_grid is not None:
assert new_grid.shape[1] is 3, 'The shape of new grid must be (n,3) where n is' \
'the number of points of the grid'
self.grid.grid = new_grid
else:
if not extent:
extent = self.extent
if not resolution:
resolution = self.resolution
return GridClass(extent, resolution, grid_type=grid_type, **kwargs)
def data_to_pickle(self, path=False):
"""
Save InputData object to a python pickle (serialization of python). Be aware that if the dependencies
versions used to export and import the pickle differ it may give problems
Args:
path (str): path where save the pickle
Returns:
None
"""
if not path:
path = './geo_data'
import pickle
with open(path+'.pickle', 'wb') as f:
# Pickle the 'data' dictionary using the highest protocol available.
pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)
def get_data(self, itype='all', numeric=False, verbosity=0):
"""
Method that returns the interfaces and foliations pandas Dataframes. Can return both at the same time or only
one of the two
Args:
itype: input data type, either 'foliations', 'interfaces' or 'all' for both.
verbosity (int): Number of properties shown
Returns:
pandas.core.frame.DataFrame: Data frame with the raw data
"""
import pandas as pn
dtype = 'object'
if verbosity == 0:
show_par_f = ['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation', 'series']
show_par_i = ['X', 'Y', 'Z', 'formation', 'series']
else:
show_par_f = self.foliations.columns
show_par_i = self.interfaces.columns
if numeric:
show_par_f = ['X', 'Y', 'Z', 'G_x', 'G_y', 'G_z', 'dip', 'azimuth', 'polarity']
show_par_i = ['X', 'Y', 'Z']
dtype = 'float'
if itype == 'foliations':
raw_data = self.foliations[show_par_f].astype(dtype)
elif itype == 'interfaces':
raw_data = self.interfaces[show_par_i].astype(dtype)
elif itype == 'all':
raw_data = pn.concat([self.interfaces[show_par_i].astype(dtype),
self.foliations[show_par_f].astype(dtype)],
keys=['interfaces', 'foliations'])
else:
raise AttributeError('itype has to be: \'foliations\', \'interfaces\', or \'all\'')
return raw_data
def i_open_set_data(self, itype="foliations"):
"""
Method to have interactive pandas tables in jupyter notebooks. The idea is to use this method to interact with
the table and i_close_set_data to recompute the parameters that depend on the changes made. I did not find a
easier solution than calling two different methods.
Args:
itype: input data type, either 'foliations' or 'interfaces'
Returns:
pandas.core.frame.DataFrame: Data frame with the changed data on real time
"""
try:
import qgrid
except:
raise ModuleNotFoundError('It is necessary to instal qgrid to have interactive tables')
# if the data frame is empty the interactive table is bugged. Therefore I create a default raw when the method
# is called
if self.foliations.empty:
self.foliations = pn.DataFrame(
np.array([0., 0., 0., 0., 0., 1., 'Default Formation', 'Default series']).reshape(1, 8),
columns=['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation', 'series']).\
convert_objects(convert_numeric=True)
if self.interfaces.empty:
self.interfaces = pn.DataFrame(
np.array([0, 0, 0, 'Default Formation', 'Default series']).reshape(1, 5),
columns=['X', 'Y', 'Z', 'formation', 'series']).convert_objects(convert_numeric=True)
# Setting some options
qgrid.nbinstall(overwrite=True)
qgrid.set_defaults(show_toolbar=True)
assert itype is 'foliations' or itype is 'interfaces', 'itype must be either foliations or interfaces'
import warnings
warnings.warn('Remember to call i_close_set_data after the editing.')
# We kind of set the show grid to a variable so we can close it afterwards
self.pandas_frame = qgrid.show_grid(self.get_data(itype=itype))
def i_close_set_data(self):
"""
Method to have interactive pandas tables in jupyter notebooks. The idea is to use this method to interact with
the table and i_close_set_data to recompute the parameters that depend on the changes made. I did not find a
easier solution than calling two different methods.
Args:
itype: input data type, either 'foliations' or 'interfaces'
Returns:
pandas.core.frame.DataFrame: Data frame with the changed data on real time
"""
# We close it to guarantee that after this method it is not possible further modifications
self.pandas_frame.close()
# Set parameters
self.series = self.set_series()
self.calculate_gradient()
self.order_table()
@staticmethod
def load_data_csv(data_type, path=os.getcwd(), **kwargs):
"""
Method to load either interface or foliations data csv files. Normally this is in which GeoModeller exports it
Args:
data_type (str): 'interfaces' or 'foliations'
path (str): path to the files. Default os.getcwd()
**kwargs: Arbitrary keyword arguments.
Returns:
pandas.core.frame.DataFrame: Data frame with the raw data
"""
# TODO: in case that the columns have a different name specify in pandas which columns are interfaces /
# coordinates, dips and so on.
# TODO: use pandas to read any format file not only csv
if data_type == "foliations":
return pn.read_csv(path, **kwargs)
elif data_type == 'interfaces':
return pn.read_csv(path, **kwargs)
else:
raise NameError('Data type not understood. Try interfaces or foliations')
# TODO if we load different data the Interpolator parameters must be also updated. Prob call gradients and
# series
def set_interfaces(self, interf_Dataframe, append=False):
"""
Method to change or append a Dataframe to interfaces in place. A equivalent Pandas Dataframe with
['X', 'Y', 'Z', 'formation'] has to be passed.
Args:
interf_Dataframe: pandas.core.frame.DataFrame with the data
append: Bool: if you want to append the new data frame or substitute it
"""
assert set(['X', 'Y', 'Z', 'formation']).issubset(interf_Dataframe.columns), \
"One or more columns do not match with the expected values " + str(interf_Dataframe.columns)
if append:
self.interfaces = self.interfaces.append(interf_Dataframe)
else:
self.interfaces = interf_Dataframe
self.set_series()
self.order_table()
# self.interfaces.reset_index(drop=True, inplace=True)
def set_foliations(self, foliat_Dataframe, append=False):
"""
Method to change or append a Dataframe to foliations in place. A equivalent Pandas Dataframe with
['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation'] has to be passed.
Args:
interf_Dataframe: pandas.core.frame.DataFrame with the data
append: Bool: if you want to append the new data frame or substitute it
"""
assert set(['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation']).issubset(
foliat_Dataframe.columns), "One or more columns do not match with the expected values " +\
str(foliat_Dataframe.columns)
if append:
self.foliations = self.foliations.append(foliat_Dataframe)
else:
self.foliations = foliat_Dataframe
self.set_series()
self.order_table()
self.calculate_gradient()
# self.foliations.reset_index(drop=True, inplace=True)
def set_series(self, series_distribution=None, order=None):
"""
Method to define the different series of the project.
Args:
series_distribution (dict): with the name of the serie as key and the name of the formations as values.
order(Optional[list]): order of the series by default takes the dictionary keys which until python 3.6 are
random. This is important to set the erosion relations between the different series
Returns:
self.series: A pandas DataFrame with the series and formations relations
self.interfaces: one extra column with the given series
self.foliations: one extra column with the given series
"""
if series_distribution is None:
# set to default series
# TODO see if some of the formations have already a series and not overwrite
_series = {"Default serie": self.interfaces["formation"].unique()}
else:
assert type(series_distribution) is dict, "series_distribution must be a dictionary, " \
"see Docstring for more information"
# TODO if self.series exist already maybe we should append instead of overwrite
_series = series_distribution
# The order of the series is very important since it dictates which one is on top of the stratigraphic pile
# If it is not given we take the dictionaries keys. NOTICE that until python 3.6 these keys are pretty much
# random
if order is None:
order = _series.keys()
# TODO assert len order is equal to len of the dictionary
# We create a dataframe with the links
#_series = pn.DataFrame(data=_series) #columns=order)
_series = pn.DataFrame(dict([ (k,pn.Series(v)) for k,v in _series.items() ]), columns=order)
# Now we fill the column series in the interfaces and foliations tables with the correspondant series and
# assigned number to the series
self.interfaces["series"] = [(i == _series).sum().argmax() for i in self.interfaces["formation"]]
self.interfaces["order_series"] = [(i == _series).sum().as_matrix().argmax() + 1
for i in self.interfaces["formation"]]
self.foliations["series"] = [(i == _series).sum().argmax() for i in self.foliations["formation"]]
self.foliations["order_series"] = [(i == _series).sum().as_matrix().argmax() + 1
for i in self.foliations["formation"]]
# We sort the series altough is only important for the computation (we will do it again just before computing)
self.interfaces.sort_values(by='order_series', inplace=True)
self.foliations.sort_values(by='order_series', inplace=True)
# Save the dataframe in a property. This is used in the pile
self.series = _series
# Set default faults
# faults_series = []
# for i in self.series.columns:
# if ('fault' in i or 'Fault' in i) and 'Default' not in i:
# faults_series.append(i)
faults_series = self.count_faults()
self.set_faults(faults_series)
self.reset_indices()
self.set_formation_number()
self.order_table()
return _series
def count_faults(self):
# Set default faults
faults_series = []
for i in self.interfaces['series'].unique():
if ('fault' in i or 'Fault' in i) and 'Default' not in i:
faults_series.append(i)
return faults_series
def set_faults(self, series_name):
"""
Set a flag to the series that are faults.
Args:
series_name(list or array_like): Name of the series which are faults
"""
# if not len(series_name) == 0:
self.interfaces.loc[:, 'isFault'] = self.interfaces['series'].isin(series_name)
self.foliations.loc[:, 'isFault'] = self.foliations['series'].isin(series_name)
self.n_faults = len(series_name)
def order_table(self):
"""
First we sort the dataframes by the series age. Then we set a unique number for every formation and resort
the formations. All inplace
"""
# We order the pandas table by series
self.interfaces.sort_values(by=['order_series'], # , 'formation number'],
ascending=True, kind='mergesort',
inplace=True)
self.foliations.sort_values(by=['order_series'], # , 'formation number'],
ascending=True, kind='mergesort',
inplace=True)
# Give formation number
if not 'formation number' in self.interfaces.columns or not 'formation number' in self.foliations.columns:
# print('I am here')
self.set_formation_number()
# We order the pandas table by formation (also by series in case something weird happened)
self.interfaces.sort_values(by=['order_series', 'formation number'],
ascending=True, kind='mergesort',
inplace=True)
self.foliations.sort_values(by=['order_series', 'formation number'],
ascending=True, kind='mergesort',
inplace=True)
# Pandas dataframe set an index to every row when the dataframe is created. Sorting the table does not reset
# the index. For some of the methods (pn.drop) we have to apply afterwards we need to reset these indeces
self.interfaces.reset_index(drop=True, inplace=True)
# Update labels for anotations
self.set_annotations()
def set_formation_number(self, formation_order=None):
"""
Set a unique number to each formation. NOTE: this method is getting deprecated since the user does not need
to know it and also now the numbers must be set in the order of the series as well. Therefore this method
has been moved to the interpolator class as preprocessing
Returns:
Column in the interfaces and foliations dataframes
"""
if formation_order is None:
formation_order = self.interfaces["formation"].unique()
else:
assert self.interfaces['formation'].isin(formation_order).all(), 'Some of the formations given are not in '\
'the formations data frame. Check misspell'
try:
ip_addresses = formation_order
ip_dict = dict(zip(ip_addresses, range(1, len(ip_addresses)+1)))
self.interfaces.loc[:, 'formation number'] = self.interfaces['formation'].replace(ip_dict)
self.foliations.loc[:, 'formation number'] = self.foliations['formation'].replace(ip_dict)
except ValueError:
pass
self.order_table()
def set_annotations(self):
point_num = self.interfaces.groupby('formation number').cumcount()
point_l = [r'${\bf{x}}_{\alpha \,{\bf{' + str(f) + '}},' + str(p) + '}$'
for p, f in zip(point_num, self.interfaces['formation number'])]
foliation_num = self.foliations.groupby('formation number').cumcount()
foli_l = [r'${\bf{x}}_{\beta \,{\bf{' + str(f) + '}},' + str(p) + '}$'
for p, f in zip(foliation_num, self.foliations['formation number'])]
self.interfaces['annotations'] = point_l
self.foliations['annotations'] = foli_l
def reset_indices(self):
"""
Resets dataframe indices for foliations and interfaces.
Returns:
None
"""
self.interfaces.reset_index(inplace=True, drop=True)
self.foliations.reset_index(inplace=True, drop=True)
def interface_modify(self, index, **kwargs):
"""
Allows modification of the x,y and/or z-coordinates of an interface at specified dataframe index.
Args:
index: dataframe index of the foliation point
**kwargs: X, Y, Z (int or float)
Returns:
None
"""
for key in kwargs:
self.interfaces.ix[index, str(key)] = kwargs[key]
def interface_add(self, **kwargs):
"""
Adds interface to dataframe.
Args:
**kwargs: X, Y, Z, formation, labels, order_series, series
Returns:
None
"""
l = len(self.interfaces)
for key in kwargs:
self.interfaces.ix[l, str(key)] = kwargs[key]
self.set_series()
self.order_table()
def interface_drop(self, index):
"""
Drops interface from dataframe identified by index
Args:
index: dataframe index
Returns:
None
"""
self.interfaces.drop(index, inplace=True)
def foliation_modify(self, index, recalculate_gradient=False, recalculate_orientations=False, **kwargs):
"""
Allows modification of foliation data at specified dataframe index.
Args:
index: dataframe index of the foliation point
**kwargs: G_x, G_y, G_z, X, Y, Z, azimuth, dip, formation, labels, order_series, polarity
Returns:
None
"""
for key in kwargs:
self.foliations.ix[index, str(key)] = kwargs[key]
if recalculate_gradient:
self.calculate_gradient()
if recalculate_orientations:
self.calculate_orientations()
def foliation_add(self, **kwargs):
"""
Adds foliation to dataframe.
Args:
**kwargs: G_x, G_y, G_z, X, Y, Z, azimuth, dip, formation, labels, order_series, polarity, series
Returns: Nothing
"""
l = len(self.foliations)
for key in kwargs:
self.foliations.ix[l, str(key)] = kwargs[key]
self.calculate_gradient()
self.set_series()
self.order_table()
def foliations_drop(self, index):
"""
Drops foliation from dataframe identified by index
Args:
index: dataframe index
Returns:
None
"""
self.foliations.drop(index, inplace=True)
def get_formation_number(self):
"""
Get a dictionary with the key the name of the formation and the value their number
Returns:
dict: key the name of the formation and the value their number
"""
pn_series = self.interfaces.groupby('formation number').formation.unique()
ip_addresses = {}
for e, i in enumerate(pn_series):
ip_addresses[i[0]] = e + 1
ip_addresses['DefaultBasement'] = 0
return ip_addresses
# # TODO think where this function should go
# def read_vox(self, path):
# """
# read vox from geomodeller and transform it to gempy format
# Returns:
# numpy.array: block model
# """
#
# geo_res = pn.read_csv(path)
#
# geo_res = geo_res.iloc[9:]
#
# #ip_addresses = geo_res['nx 50'].unique() # geo_data.interfaces["formation"].unique()
# ip_dict = self.get_formation_number()
#
# geo_res_num = geo_res.iloc[:, 0].replace(ip_dict)
# block_geomodeller = np.ravel(geo_res_num.as_matrix().reshape(
# self.resolution[0], self.resolution[1], self.resolution[2], order='C').T)
# return block_geomodeller
def set_triangle_foliations(self, verbose=False):
# next we need to iterate over every unique triangle id to create a foliation from each triplet
# of points and assign the same triange_id to it
tri_ids = np.unique(self.interfaces["triangle_id"])
# check if column in foliations too, else create it
if "triangle_id" not in self.foliations.columns:
self.foliations["triangle_id"] = "NaN"
if verbose:
print("Setting triangle_id column in geo_data.foliations.")
# loop over all triangle_id's
for tri_id in tri_ids[tri_ids != "NaN"]:
# get the three points dataframe
_filter = self.interfaces["triangle_id"] == tri_id
# check if triangle foliation value already exists
if tri_id in np.unique(self.foliations["triangle_id"]):
if verbose:
print("triangle_id already in geo_data.foliations - skipping it.")
continue # if yes, continue with the next iteration not not double append
if verbose:
print("tri_id: "+tri_id)
if len(self.interfaces[_filter]) == 3:
# get points as [x,y,z]
_points = []
for i, interf in self.interfaces[_filter].iterrows():
_points.append([interf["X"], interf["Y"], interf["Z"]])
if verbose:
print("3 points xyz:",_points)
# get plane normal from three points
_normal = _get_plane_normal(_points[0], _points[1], _points[2], verbose=verbose)
# get dip and azimuth
_dip, _az = _get_dip(_normal)
# now get centroid of three points
_centroid = _get_centroid(_points[0], _points[1], _points[2])
# set polarity according to overturned or not
if -90 < _dip < 90:
_pol = 1
else:
_pol = -1
_fmt = np.unique(self.interfaces[_filter]["formation"])[0]
# _series = np.unique(self.interfaces[_filter]["series"])[0]
if verbose:
print("plane normal:", _normal)
print("dip", _dip)
print("az", _az)
print("centroid x,y,z:", _centroid)
_f = [_centroid[0], _centroid[1], _centroid[2], _dip, _az, _pol, _fmt, tri_id]
_fs = pn.Series(_f, ['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation', 'triangle_id'])
_df = _fs.to_frame().transpose()
self.set_foliations(_df, append=True)
elif len(self.interfaces[_filter]) > 3:
print("More than three points share the same triangle-id: " + str(
tri_id) + ". Only exactly 3 points are supported.")
elif len(self.interfaces[_filter]) < 3:
print("Less than three points share the same triangle-id: " + str(
tri_id) + ". Only exactly 3 points are supported.")
class DataPlane:
def __init__(self, geo_data, group_id, mode, verbose=False):
"""
:param geo_data: InputData object
:param group_id: (str) identifier for the data group
:param mode: (str), either 'interf_to_fol' or 'fol_to_interf'
:param verbose: (bool) adjusts verbosity, default False
"""
self.geo_data = geo_data
self.group_id = group_id
if mode is "interf_to_fol":
# df bool filter
self._f = self.geo_data.interfaces["group_id"] == self.group_id
# get formation string
self.formation = self.geo_data.interfaces[self._f]["formation"].values[0]
# df indices
self.interf_i = self.geo_data.interfaces[self._f].index
# get point coordinates from df
self.interf_p = self._get_points()
# get point cloud centroid and normal vector of plane
self.centroid, self.normal = self._fit_plane_svd()
# get dip and azimuth of plane from normal vector
self.dip, self.azimuth, self.polarity = self._get_dip(verbose=verbose)
elif mode == "fol_to_interf":
self._f = self.geo_data.foliations["group_id"] == self.group_id
self.formation = self.geo_data.foliations[self._f]["formation"].values[0]
# get interface indices
self.interf_i = self.geo_data.interfaces[self.geo_data.interfaces["group_id"]==self.group_id].index
# get interface point coordinates from df
self.interf_p = self._get_points()
self.normal = [self.geo_data.foliations[self._f]["G_x"],
self.geo_data.foliations[self._f]["G_y"],
self.geo_data.foliations[self._f]["G_z"]]
self.centroid = [self.geo_data.foliations[self._f]["X"],
self.geo_data.foliations[self._f]["Y"],
self.geo_data.foliations[self._f]["Z"]]
# modify all Z of interface points belonging to group_id to fit plane
self._fol_to_p()
else:
print("Mode must be either 'interf_to_fol' or 'fol_to_interf'.")
def _fol_to_p(self):
a, b, c = self.normal
d = -a * self.centroid[0] - b * self.centroid[1] - c * self.centroid[2]
for i, row in self.geo_data.interfaces[self.geo_data.interfaces["group_id"] == self.group_id].iterrows():
# iterate over each point and recalculate Z, set Z
# x, y, z = row["X"], row["Y"], row["Z"]
Z = (a*row["X"] + b*row["Y"] + d)/-c
self.geo_data.interfaces.set_value(i, "Z", Z)
def _get_points(self):
"""Returns n points from geo_data.interfaces matching group_id in np.array shape (n, 3)."""
# TODO: zip
x = []
y = []
z = []
for i, row in self.geo_data.interfaces[self.geo_data.interfaces["group_id"]==self.group_id].iterrows():
x.append(float(row["X"]))
y.append(float(row["Y"]))
z.append(float(row["Z"]))
return np.array([x, y, z])
def _fit_plane_svd(self):
"""Fit plane to points using singular value decomposition (svd). Returns point cloud centroid [x,y,z] and
normal vector of plane [x,y,z]."""
from numpy.linalg import svd
# https://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points
ctr = self.interf_p.mean(axis=1) # calculate point cloud centroid [x,y,z]
x = self.interf_p - ctr[:, np.newaxis]
m = np.dot(x, x.T) # np.cov(x)
return ctr, svd(m)[0][:, -1]
def _get_dip(self, verbose=False):
"""Returns dip angle and azimuth of normal vector [x,y,z]."""
dip = np.arccos(self.normal[2] / np.linalg.norm(self.normal)) / np.pi * 180.
azimuth = None
if self.normal[0] >= 0 and self.normal[1] > 0:
azimuth = np.arctan(self.normal[0] / self.normal[1]) / np.pi * 180.
# border cases where arctan not defined:
elif self.normal[0] > 0 and self.normal[1] == 0:
azimuth = 90
elif self.normal[0] < 0 and self.normal[1] == 0:
azimuth = 270
elif self.normal[1] < 0:
azimuth = 180 + np.arctan(self.normal[0] / self.normal[1]) / np.pi * 180.
elif self.normal[1] >= 0 < self.normal[0]:
azimuth = 360 + np.arctan(self.normal[0] / self.normal[1]) / np.pi * 180.
if -90 < dip < 90:
polarity = 1
else:
polarity = -1
return dip, azimuth, polarity
def set_fol(self):
"""Appends foliation data point for group_id to geo_data.foliations."""
if "group_id" not in self.geo_data.foliations.columns:
self.geo_data.foliations["group_id"] = "NaN"
fol = [self.centroid[0], self.centroid[1], self.centroid[2],
self.dip, self.azimuth, self.polarity,
self.formation, self.group_id]
fol_series = pn.Series(fol, ['X', 'Y', 'Z', 'dip', 'azimuth', 'polarity', 'formation', 'group_id'])
fol_df = fol_series.to_frame().transpose()
self.geo_data.set_foliations(fol_df, append=True)
def _get_plane_normal(A, B, C, verbose=False):
"""Returns normal vector of plane defined by points A,B,C as [x,y,z]."""
A = np.array(A)
B = np.array(B)
C = np.array(C)
v1 = C - A
v2 = B - A
if verbose:
print("vector C-A", v1)
print("vector B-A", v2)
return np.cross(v1, v2)
def _get_centroid(A, B, C):
"""Returns centroid (x,y,z) of three points 3x[x,y,z]."""
X = (A[0]+B[0]+C[0])/3
Y = (A[1]+B[1]+C[1])/3
Z = (A[2]+B[2]+C[2])/3
return X,Y,Z
class GridClass(object):
"""
-DOCS NOT UPDATED- Class with set of functions to generate grids
Args:
extent (list): [x_min, x_max, y_min, y_max, z_min, z_max]
resolution (list): [nx, ny, nz].
grid_type(str): Type of grid. So far only regular 3D is implemented
"""
def __init__(self, extent, resolution, grid_type="regular_3D"):
self._grid_ext = extent
self._grid_res = resolution
if grid_type == "regular_3D":
self.grid = self.create_regular_grid_3d()
else:
print("Wrong type")
def create_regular_grid_3d(self):
"""
Method to create a 3D regular grid where is interpolated
Returns:
numpy.ndarray: Unraveled 3D numpy array where every row correspond to the xyz coordinates of a regular grid
"""
g = np.meshgrid(
np.linspace(self._grid_ext[0], self._grid_ext[1], self._grid_res[0], dtype="float32"),
np.linspace(self._grid_ext[2], self._grid_ext[3], self._grid_res[1], dtype="float32"),
np.linspace(self._grid_ext[4], self._grid_ext[5], self._grid_res[2], dtype="float32"), indexing="ij"
)
return np.vstack(map(np.ravel, g)).T.astype("float32")
class InterpolatorInput:
"""
InterpolatorInput is a class that contains all the preprocessing operations to prepare the data to compute the model.
Also is the object that has to be manipulated to vary the data without recompile the modeling function.
Args:
geo_data(gempy.DataManagement.InputData): All values of a DataManagement object
compile_theano (bool): select if the theano function is compiled during the initialization. Default: True
compute_all (bool): If true the solution gives back the block model of lithologies, the potential field and
the block model of faults. If False only return the block model of lithologies. This may be important to speed
up the computation. Default True
u_grade (list): grade of the polynomial for the universal part of the Kriging interpolations. The value has to
be either 0, 3 or 9 (number of equations) and the length has to be the number of series. By default the value
depends on the number of points given as input to try to avoid singular matrix. NOTE: if during the computation
of the model a singular matrix is returned try to reduce the u_grade of the series.
rescaling_factor (float): rescaling factor of the input data to improve the stability when float32 is used. By
defaut the rescaling factor is calculated to obtein values between 0 and 1.
Keyword Args:
dtype ('str'): Choosing if using float32 or float64. This is important if is intended to use the GPU
See Also InterpolatorClass kwargs
Attributes:
geo_data: Original gempy.DataManagement.InputData object
geo_data_res: Rescaled data. It has the same structure has gempy.InputData
interpolator: Instance of the gempy.DataManagement.InterpolaorInput.InterpolatorClass. See Also
gempy.DataManagement.InterpolaorInput.InterpolatorClass docs
th_fn: Theano function which compute the interpolation
dtype: type of float
"""
def __init__(self, geo_data, output='geology', compile_theano=True, compute_all=True,
u_grade=None, rescaling_factor=None, **kwargs):
# TODO add all options before compilation in here. Basically this is n_faults, n_layers, verbose, dtype, and \
# only block or all
assert isinstance(geo_data, InputData), 'You need to pass a InputData object'
# Store the original InputData object
self._geo_data = geo_data
# Here we can change the dtype for stability and GPU vs CPU
self.dtype = kwargs.get('dtype', 'float32')
#self.in_data = self.rescale_data(geo_data, rescaling_factor=rescaling_factor)
# Set some parameters. TODO possibly this should go in kwargs
self.u_grade = u_grade
# This two properties get set calling rescale data
self.rescaling_factor = None
self.centers = None
self.extent_rescaled = None
# Rescaling
self.geo_data_res = self.rescale_data(geo_data, rescaling_factor=rescaling_factor)
# # This are necessary parameters for the visualization package
#self.resolution = self.geo_data.resolution
#self.extent = self.extent_rescaled.as_matrix()
# Creating interpolator class with all the precompilation options
# --DEP-- self.interpolator = self.set_interpolator(**kwargs)
self.interpolator = self.InterpolatorClass(self.geo_data_res, self.geo_data_res.grid, output=output, **kwargs)
if compile_theano:
self.th_fn = self.compile_th_fn(output, compute_all=compute_all)
self.geophy = None
def compile_th_fn(self, output, compute_all=True):
"""
Compile the theano function given the input data.
Args:
compute_all (bool): If true the solution gives back the block model of lithologies, the potential field and
the block model of faults. If False only return the block model of lithologies. This may be important to speed
up the computation. Default True
Returns:
theano.function: Compiled function if C or CUDA which computes the interpolation given the input data
(XYZ of dips, dip, azimuth, polarity, XYZ ref interfaces, XYZ rest interfaces)
"""
# This are the shared parameters and the compilation of the function. This will be hidden as well at some point
input_data_T = self.interpolator.tg.input_parameters_list()
if output is 'geology':
# then we compile we have to pass the number of formations that are faults!!