forked from jolivetr/csi
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTriangularTents.py
More file actions
1773 lines (1417 loc) · 60.5 KB
/
TriangularTents.py
File metadata and controls
1773 lines (1417 loc) · 60.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
A parent class that deals with piece-wise linear triangular fault discretization
Written by Junle Jiang Apr, 2014
'''
# Externals
import numpy as np
import pyproj as pp
import inspect
import matplotlib.pyplot as plt
import scipy.interpolate as sciint
from . import triangularDisp as tdisp
from scipy.linalg import block_diag
import copy
import sys
import os
# Personals
from .TriangularPatches import TriangularPatches
from .geodeticplot import geodeticplot as geoplot
from . import csiutils as utils
class TriangularTents(TriangularPatches):
'''
Classes implementing a fault made of triangular tents. Inherits from Fault
Args:
* name : Name of the fault.
Kwargs:
* utmzone : UTM zone (optional, default=None)
* lon0 : Longitude of the center of the UTM zone
* lat0 : Latitude of the center of the UTM zone
* ellps : ellipsoid (optional, default='WGS84')
* verbose : Speak to me (default=True)
'''
# ----------------------------------------------------------------------
def __init__(self, name, utmzone=None, ellps='WGS84', lon0=None,
lat0=None, verbose=True):
# Base class init
super(TriangularTents, self).__init__(name, utmzone=utmzone, ellps=ellps,
lon0=lon0, lat0=lat0,
verbose=verbose)
# Specify the type of patch
self.patchType = 'triangletent'
self.area = None
self.area_tent = None
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initializeFromFault(self, fault, adjMap=True):
'''
Initializes the tent fault object from a triangularPatches or a
triangularTents instance.
Args:
* fault : Instance of triangular fault.
Kwargs:
* adjMap : Build the adjacency map (True/False).
Returns:
* None
'''
# Assert
assert type(fault) in (TriangularPatches, type(self)), 'Input fault type must be {} or {}'.format(TriangularPatches, type(self))
# Create a list of the attributes we want to copy
Attributes = []
for attr in dir(fault):
if (attr[:2] not in ('__')) and (not inspect.ismethod(fault.__getattribute__(attr))) and attr!='name':
Attributes.append(attr)
# Loop
for attr in Attributes:
self.__setattr__(attr, copy.deepcopy(fault.__getattribute__(attr)))
# patchType
self.patchType = 'triangletent'
# Vertices2Tents
self.vertices2tents()
# Build the adjacency map
if adjMap:
self.buildAdjacencyMap()
# Slip
self.initializeslip()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getStrikes(self):
'''
Returns the strikes of each nodes.
'''
# All done in one line
return np.array([self.getTentInfo(t)[3] for t in self.tent])
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getDepths(self):
'''
Returns the depth of each nodes.
'''
# All done in one line
return np.array([self.getTentInfo(t)[2] for t in self.tent])
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getDips(self):
'''
Returns the dip of each nodes.
'''
# All done in one line
return np.array([self.getTentInfo(t)[4] for t in self.tent])
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getTentInfo(self, tent):
'''
Returns the geometry info related to vertex-based tent parameterization
Args:
* tent : index of the wanted tent or tent;
Returns:
* x, y, z, strike, dip : Tent Informations
'''
# Get the patch
u = None
if type(tent) in (int, np.int64, np.int32):
u = tent
else:
u = self.getTentindex(tent)
x, y, z = self.tent[u]
nbr_faces = self.adjacencyMap[self.tentid[u]]
strike = []
dip = []
for pid in nbr_faces:
xc, yc, zc, w, l, stk, dp = self.getpatchgeometry(pid, center=True)
strike.append(stk)
dip.append(dp)
# Compute the mean (beware of angle stuff), and we count from 0 to 2pi
j = complex(0., 1.)
strike = np.angle(np.sum([np.exp(j*s) for s in strike])/len(strike))
if strike<0.: strike += 2*np.pi
dip = np.mean(dip)
# All done
return x, y, z, strike, dip
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def deleteTent(self, tent):
'''
Deletes a tent.
Args:
* tent : index of the tent to remove.
Returns:
* None
'''
# Remove the patch
del self.tent[tent]
del self.tentll[tent]
del self.tentid[tent]
if self.N_slip!=None or self.N_slip==len(self.tent):
self.slip = np.delete(self.slip, tent, axis=0)
self.N_slip = len(self.slip)
self.numtent -= 1
else:
raise NotImplementedError('Only works for len(slip)==len(tent)', self.N_slip, len(self.slip), len(self.tent))
# Delete the vertex and the patch, if needed
self.deletevertex(tent, checkPatch=True, checkSlip=False)
# Rebuild architecture
self.buildAdjacencyMap(verbose=False)
self.vertices2tents()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def deleteTents(self, tents):
'''
Deletes a list of tent (indices)
Args:
* tents : list of indices
Returns:
* None
'''
while len(tents)>0:
# Get index to delete
i = tents.pop()
# delete it
self.deleteTent(i)
# Upgrade list
for u in range(len(tents)):
if tents[u]>i:
tents[u] -= 1
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def findNodes(self, lon, lat, round=2):
'''
Find the nodes with lon and lat (np.array or list)
Args:
* lon : array or float of longitude
* lat : array or float of latitude
Kwargs:
* round : Round to how many decimals
Returns:
* Indices of the nodes : list
'''
# Create list
indices = []
# Get lons and lats
lons = np.array([t[0] for t in self.tentll])
lats = np.array([t[1] for t in self.tentll])
# Loop
for lo, la in zip(lon, lat):
u = np.flatnonzero(np.logical_and(lons.round(round)==np.round(lo,round),
lats.round(round)==np.round(la,round)))
if len(u)==0:
indices.append(None)
else:
indices.append(u[0])
# All done
return indices
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def chooseTents(self, tents):
'''
Choose a subset of tents (indices)
Args:
* tents : List of indices
Returns:
* None
'''
tent_new = []
tentll_new = []
tentid_new = []
for it in tents:
tent_new.append(self.tent[it])
tentll_new.append(self.tentll[it])
tentid_new.append(self.tentid[it])
self.tent = tent_new
self.tentll = tentll_new
self.tentid = tentid_new
self.slip = self.slip[tents,:]
self.N_slip = len(self.slip)
self.numtent = len(tents)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getcenters(self):
'''
Returns a list of nodes.
'''
# All done
return self.tent
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def addTent(self, tent, slip=[0, 0, 0]):
'''
Append a tent to the current list.
Args:
* tent : tent to add
Kwargs:
* slip : List of the strike, dip and tensile slip.
Returns:
* None
'''
# append the patch
self.tent.append(tent)
z = tent[2]
lon, lat = self.xy2ll(tent[0], tent[1])
self.tentll.append([lon, lat, z])
# modify the slip
if self.N_slip!=None and self.N_slip==len(self.tent)-1:
sh = self.slip.shape
nl = sh[0] + 1
nc = 3
tmp = np.zeros((nl, nc))
if nl > 1: # Case where slip is empty
tmp[:nl-1,:] = self.slip
tmp[-1,:] = slip
self.slip = tmp
self.N_slip = len(self.slip)
else:
raise NotImplementedError('Only works for len(slip)==len(patch)')
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def addTents(self, tents, slip=None):
'''
Adds a list of tents
Args:
* tents : tent to add
Kwargs:
* slip : List of the strike, dip and tensile slip.
Returns:
* None
'''
if (slip is None) or (slip == [0, 0, 0]):
slip = np.zeros((len(tents),3))
for i in range(len(tents)):
self.addTent(tents[i], list(slip[i,:]))
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def readPatchesFromFile(self, filename, readpatchindex=True,
donotreadslip=False, inputCoordinates='lonlat'):
'''
Reads patches from a GMT formatted file.
Args:
* filename : Name of the file
Kwargs:
* inputCoordinates : Default is 'lonlat'. Can be 'utm'
* readpatchindex : Default True.
* donotreadslip : Default is False. If True, does not read the slip
* inputCoordinates : Default is 'lonlat', can be 'xyz'
Returns:
* None
'''
# Run the method from the parent class
super(TriangularTents, self).readPatchesFromFile(filename,
readpatchindex=readpatchindex, donotreadslip=donotreadslip,
inputCoordinates=inputCoordinates)
# Set up tent
self.vertices2tents()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writePatches2File(self, filename, add_slip=None, scale=1.0, stdh5=None, decim=1):
'''
Writes the patch corners in a file that can be used in psxyz.
Args:
* filename : Name of the file.
Kwargs:
* add_slip : Will be set to None
* scale : Multiply the slip value by a factor.
* patch : Can be 'normal' or 'equiv'
* stdh5 : Get std dev from an h5 file
* decim : decimate the h5 file
Returns:
* None
'''
# Set add_slip to none
if add_slip is not None:
print('Slip vector is not the same length as the number of patches for TriangularTent type.')
print('Setting add_slip to None')
add_slip = None
# Run the method from the parent class
super(TriangularTents, self).writePatches2File(filename, add_slip=add_slip, scale=scale, stdh5=stdh5, decim=decim)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeSources2Grd(self, filename, npoints=10, slip='strikeslip',
increments=None, nSamples=None, outDir='./',
mask=False, noValues=np.nan):
'''
Writes the values of slip in two grd files:
- z_{filename}
- {slip}_{filename}
Args:
* filename : Name of the grdfile (should end by grd or nc)
Kwargs:
* slip : Slip value to store.
* mask : If true,builds a mask based on the outer boundary of the fault.
* nSamples : How many samples on each axis
* increments : Size of increments along each axis
* outDir : Output directory
* noValues : What to write when there is no value
Returns:
* None
'''
# Assert
assert not ( (increments is None) and (nSamples is None) ), 'Specify increments or nSamples...'
# Lon lat limits
lonmin = np.min([t[0] for t in self.tentll])
lonmax = np.max([t[0] for t in self.tentll])
latmin = np.min([t[1] for t in self.tentll])
latmax = np.max([t[1] for t in self.tentll])
# Get the sources
gp = geoplot(figure=None, lonmin=lonmin, lonmax=lonmax, latmin=latmin, latmax=latmax)
lon, lat, z, s = gp.faultTents(self, slip=slip, method='scatter',
npoints=npoints)
gp.close()
del gp
# Mask?
if mask:
mask = self._getFaultContour()
else:
mask = None
# write 2 grd
utils.write2netCDF('{}/z_{}'.format(outDir, filename),
lon, lat, -1.0*z, increments=increments, nSamples=nSamples, mask=mask,
noValues=noValues)
utils.write2netCDF('{}/{}_{}'.format(outDir, slip, filename),
lon, lat, s, increments=increments, nSamples=nSamples, mask=mask,
noValues=noValues)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeNodes2File(self, filename, add_slip=None, scale=1.0, stdh5=None, decim=1):
'''
Writes the tent node in a file that can be used in psxyz.
Args:
* filename : Name of the file.
Kwargs:
* add_slip : Put the slip as a value for the color. Can be None, strikeslip, dipslip, total.
* scale : Multiply the slip value by a factor.
* stdh5 : Get standrad dev from a h5file
* decim : Decimate the h5 file
Returns:
* None
'''
# Check size
if self.N_slip!=None and self.N_slip!=len(self.tent):
raise NotImplementedError('Only works for len(slip)==len(tent)')
# Write something
print('Writing geometry to file {}'.format(filename))
# Open the file
fout = open(filename, 'w')
# If an h5 file is specified, open it
if stdh5 is not None:
import h5py
h5fid = h5py.File(stdh5, 'r')
samples = h5fid['samples'].value[::decim,:]
# Loop over the patches
nTents = len(self.tent)
for tIndex in range(nTents):
# Select the string for the color
if add_slip is not None:
if add_slip=='strikeslip':
if stdh5 is not None:
slp = np.std(samples[:,tIndex])
else:
slp = self.slip[tIndex,0]*scale
elif add_slip=='dipslip':
if stdh5 is not None:
slp = np.std(samples[:,tIndex+nPatches])
else:
slp = self.slip[tIndex,1]*scale
elif add_slip=='total':
if stdh5 is not None:
slp = np.std(samples[:,tIndex]**2 + samples[:,tIndex+nPatches]**2)
else:
slp = np.sqrt(self.slip[tIndex,0]**2 + self.slip[tIndex,1]**2)*scale
# Write the node
p = self.tentll[tIndex]
fout.write('{} {} {} {}\n'.format(p[0], p[1], p[2], slp))
# Close the file
fout.close()
# Close h5 file if it is open
if stdh5 is not None:
h5fid.close()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initializeslip(self, n=None, values=None):
'''
Re-initializes the fault slip array to zero values.
This function over-writes the function in the parent class Fault.
Kwargs:
* n : Number of slip values. If None, it'll take the number of patches.
* values: Can be depth, strike, dip, length, area or a numpy array
Returns:
* None
'''
# Shape
if n is None:
self.N_slip = len(self.Vertices)
else:
self.N_slip = n
self.slip = np.zeros((self.N_slip,3))
# Values
if values is not None:
# string type
if type(values) is str:
if values=='depth':
values = np.array([self.getTentInfo(t)[2] for t in self.tent])
elif values=='strike':
values = np.array([self.getTentInfo(t)[3] for t in self.tent])
elif values=='dip':
values = np.array([self.getTentInfo(t)[4] for t in self.tent])
elif values=='index':
values = np.array([float(self.getTentindex(t)) for t in self.tent])
self.slip[:,0] = values
# Numpy array
if type(values) is np.ndarray:
try:
self.slip[:,:] = values
except:
try:
self.slip[:,0] = values
except:
print('Wrong size for the slip array provided')
return
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def distanceMatrix(self, distance='center', lim=None):
'''
Returns a matrix of the distances between Nodes.
Kwargs:
* distance : distance estimation mode
- center : distance between the centers of the patches.
- no other method is implemented for now.
* lim : if not None, list of two float, the first one is the distance above which d=lim[1].
Returns:
* distance : 2d array
'''
# Assert
assert distance=='center', 'No other method implemented than center'
# Check
if self.N_slip==None:
self.N_slip = self.slip.shape[0]
# Loop
Distances = np.zeros((self.N_slip, self.N_slip))
for i in range(self.N_slip):
v1 = self.Vertices[i]
for j in range(self.N_slip):
if j == i:
continue
v2 = self.Vertices[j]
Distances[i,j] = self.distanceVertexToVertex(v1, v2, lim=lim)
# All done
return Distances
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def distancesMatrix(self, distance='center', lim=None):
'''
Returns two matrices of the distances between Nodes.
One along horizontal dimensions, the other along the vertical axis
Kwargs:
* distance : distance estimation mode
- center : distance between the centers of the patches.
- no other method is implemented for now.
* lim : if not None, list of two float, the first one is the distance above which d=lim[1].
Returns:
* distance : 2d array
'''
# Assert
assert distance=='center', 'No other method implemented than center'
# Check
if self.N_slip==None:
self.N_slip = self.slip.shape[0]
# Loop
HDistances = np.zeros((self.N_slip, self.N_slip))
VDistances = np.zeros((self.N_slip, self.N_slip))
for i in range(self.N_slip):
v1 = self.Vertices[i]
for j in range(self.N_slip):
if j == i:
continue
v2 = self.Vertices[j]
HDistances[i,j] = np.sqrt( (v1[0]-v2[0])**2 + (v1[1]-v2[1])**2 )
HDistances[j,i] = HDistances[i,j]
VDistances[i,j] = np.sqrt( (v1[2]-v2[2])**2 )
VDistances[j,i] = VDistances[i,j]
# All done
return HDistances,VDistances
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getTentindex(self, tent):
'''
Returns the index of a tent.
Args:
* tent : element of self.tents
Returns:
* iout : integer
'''
# Output index
iout = None
# Find it
for t in range(len(self.tent)):
if (self.tent[t] == tent):
iout = t
# All done
return iout
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def slipIntegrate(self, slip=None, factor=1.):
'''
Integrates slip on the patch. Stores integration in self.volume
Args:
* slip : slip vector. Can be strikeslip, dipslip, tensile, coupling or a list/array of floats.
* factor : multiply slip vector
Returns:
* None
'''
# Slip
if type(slip) is str:
if slip=='strikeslip':
slip = self.slip[:,0]
elif slip=='dipslip':
slip = self.slip[:,1]
elif slip=='tensile':
slip = self.slip[:,2]
elif slip=='coupling':
slip = self.coupling
elif type(slip) in (np.ndarray, list):
assert len(slip)==len(self.tent), 'Slip vector is the wrong size'
else:
slip = np.ones((len(self.tent),))
# Compute Volumes
self.computeTentArea()
# area_tent is in km**2
self.volume = self.area_tent*1e6*slip*factor/3.
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def computeTentArea(self):
'''
Computes the area for each node. Stores it in self.area_tent
Returns:
* None
'''
# Area
if self.area is None:
self.computeArea()
self.area_tent = []
areas = np.array(self.area)
# Loop over vertices
for i in range(self.numtent):
vid = self.tentid[i]
# find the triangle neighbors for each vertex
nbr_triangles = self.adjacencyMap[vid]
area = np.sum(areas[nbr_triangles])
self.area_tent.append(area)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def patches2triangles(self, fault, numberOfTriangles=4):
'''
Takes a fault with rectangular patches and splits them into triangles to
initialize self.
Args:
* fault : instance of rectangular patches.
Kwargs:
* numberOfTriangles : Split each patch in 2 or 4 (default) triangle
Returns:
* None
'''
# The method is in the parent class
super(TriangularTents, self).patches2triangles(fault,
numberOfTriangles=numberOfTriangles)
# We need the tents
self.vertices2tents()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def readGocadPatches(self, filename, neg_depth=False, utm=False, factor_xy=1.0,
factor_depth=1.0, verbose=False):
"""
Load a triangulated Gocad surface file. Vertices must be in geographical coordinates.
Args:
* filename: tsurf file to read
Kwargs:
* neg_depth: if true, use negative depth
* utm: if true, input file is given as utm coordinates (if false -> lon/lat)
* factor_xy: if utm==True, multiplication factor for x and y
* factor_depth: multiplication factor for z
"""
# Run the upper level routine
super(TriangularTents, self).readGocadPatches(filename, neg_depth=neg_depth, utm=utm,
factor_xy=factor_xy, factor_depth=factor_depth, verbose=verbose)
# Vertices to Tents
self.vertices2tents()
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def vertices2tents(self):
'''
Takes the list of vertices and builds the tents.
Returns:
* None
'''
# Initialize the lists of patches
self.tent = []
self.tentll = []
self.tentid = []
# Get vertices
vertices = self.Vertices
verticesll = self.Vertices_ll
vx, vy, vz = vertices[:,0], vertices[:,1], vertices[:,2]
# Loop over vetices and create a node-based tent consisting of coordinate tuples
self.numtent = vertices.shape[0]
for i in range(self.numtent):
# Get the coordinates
x, y, lon, lat, z = vx[i], vy[i], verticesll[i,0], verticesll[i,1], vz[i]
# Make the coordinate tuples
p = [x, y, z]; pll = [lon, lat, z]
# Store the patch
self.tent.append(p)
self.tentll.append(pll)
self.tentid.append(i)
# Create the adjacency map
self.buildAdjacencyMap(verbose=False)
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def Facet2Nodes(self, homogeneousStrike=False, homogeneousDip=False, keepFacetsSeparated=False):
'''
Transfers the edksSources list into the node based setup.
Kwargs:
* honogeneousStrike : In a tent, the strike varies among the faces. This variation can be a problem if the variation in strikes is too large, with slip that can partially cancel each other. If True, the strike of each of the point is equal to the strike of the main node of the tent.
* homogeneousDip : Same thing for the dip angle.
* keepFacetsSeparated : If True, each facet of each node will have a different identifier (int). This is needed when computing the Green's function for the Node based case.
Returns:
* None
'''
# Get the faces and Nodes
Faces = np.array(self.Faces)
Vertices = self.Vertices
# Get the surrounding triangles
Nodes = {}
# Loop for that
for nId in self.tentid:
Nodes[nId] = {'nTriangles': 0, 'idTriangles': []}
for idFace in range(self.Faces.shape[0]):
ns = self.Faces[idFace,:].tolist()
if nId in ns:
Nodes[nId]['nTriangles'] += 1
Nodes[nId]['idTriangles'].append(idFace)
# Save the nodes
self.Nodes = Nodes
# Create the new edksSources
Ids = []
xs = []; ys = []; zs = []
strike = []; dip = []
areas = []; slip = []
# Initialize counter
iSource = -1
# Iterate on the nodes to derive the weights
for mainNode in Nodes:
if homogeneousDip:
mainDip = self.getTentInfo(mainNode)[4]
if homogeneousStrike:
mainStrike = self.getTentInfo(mainNode)[3]
if keepFacetsSeparated:
Nodes[mainNode]['subSources'] = []
# Loop over each of these triangles
for tId in Nodes[mainNode]['idTriangles']:
# Find the sources in edksSources
iS = np.flatnonzero(self.edksSources[0]==(tId)).tolist()
# Get the three nodes
tNodes = Faces[tId]
# Affect the master node and the two outward nodes
nodeOne, nodeTwo = tNodes[np.where(tNodes!=mainNode)]
# Get weights (Attention: Vertices are in km, edksSources in m)
Wi = self._getWeights(Vertices[mainNode],
Vertices[nodeOne],
Vertices[nodeTwo],
self.edksSources[1][iS]/1000.,
self.edksSources[2][iS]/1000.,
self.edksSources[3][iS]/1000.)
# Source Ids
if keepFacetsSeparated:
iSource += 1
Nodes[mainNode]['subSources'].append(iSource)
else:
iSource = mainNode
# Save each source
Ids += (np.ones((len(iS),))*iSource).astype(int).tolist()
xs += self.edksSources[1][iS].tolist()
ys += self.edksSources[2][iS].tolist()
zs += self.edksSources[3][iS].tolist()
areas += self.edksSources[6][iS].tolist()
slip += Wi.tolist()
if homogeneousStrike:
strike += (np.ones((len(iS),))*mainStrike).tolist()
else:
strike += self.edksSources[4][iS].tolist()
if homogeneousDip:
dip += (np.ones((len(iS),))*mainDip).tolist()
else:
dip += self.edksSources[5][iS].tolist()
# Set the new edksSources
self.edksFacetSources = copy.deepcopy(self.edksSources)
self.edksSources = [np.array(Ids), np.array(xs), np.array(ys), np.array(zs),
np.array(strike), np.array(dip), np.array(areas), np.array(slip)]
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def buildAdjacencyMap(self, verbose=True):
'''
For each triangle vertex, find the indices of the adjacent triangles.
This function overwrites that from the parent class TriangularPatches.
Kwargs:
* verbose : Speak to me
Returns:
* None
'''
if verbose:
print("-----------------------------------------------")
print("-----------------------------------------------")
print("Finding the adjacent triangles for all vertices")
self.adjacencyMap = []