-
Notifications
You must be signed in to change notification settings - Fork 31
/
geodeticplot.py
1928 lines (1601 loc) · 69.1 KB
/
geodeticplot.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
'''
Class that plots the class verticalfault, gps and insar in 3D.
Written by R. Jolivet and Z. Duputel, April 2013.
Edited by T. Shreve, May 2019. Commented out lines 386, 391, 460, 485, 1121, 1131 because plotting fault patches was incorrect...
Added plotting option for pressure sources
July 2019: R Jolivet replaced basemap by cartopy.
'''
# Numerics
import numpy as np
import scipy.interpolate as sciint
import scipy.ndimage as sciim
# Geography
import pyproj as pp
# Os
import os, copy, sys
# Matplotlib
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import matplotlib.collections as colls
from matplotlib.patches import PathPatch
import matplotlib.patches as patches
import matplotlib.transforms as transforms
# Cartopy
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.io import PostprocessedRasterSource, LocatedImage
from cartopy.io.srtm import SRTM1Source, SRTM3Source
from cartopy.io import srtm
# mpl_toolkits
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
# CSI
from .SourceInv import SourceInv
from .gebco import GebcoSource
class geodeticplot(object):
'''
A class to create plots of geodetic data with faults. Geographic representation is based on cartopy.
Two figures are created. One with a map and the other with a 3D view of the fault.
Args:
* lonmin : left-boundary of the map
* lonmax : Right-boundary of the map
* latmin : Bottom-boundary of the map
* latmax : Top of the map
Kwargs:
* figure : Figure number
* pbaspect : ??
* resolution : Resolution of the mapped coastlines, lakes, rivers, etc. See cartopy for details
* figsize : tuple of the size of the 2 figures
Returns:
* None
'''
def __init__(self,lonmin, latmin, lonmax, latmax,
figure=None, pbaspect=None,resolution='auto',
figsize=[None,None], Map=True, Fault=True):
# Save
self.lonmin = lonmin
self.lonmax = lonmax
self.latmin = latmin
self.latmax = latmax
# Lon0 lat0
self.lon0 = lonmin + (lonmax-lonmin)/2.
self.lat0 = latmin + (latmax-latmin)/2.
# Projection
self.projection = ccrs.PlateCarree()
# Open a figure
if Fault:
figFaille = plt.figure(figure, figsize=figsize[0])
faille = figFaille.add_subplot(111, projection='3d')
# Chec figure number
if figure == None:
fignums = plt.get_fignums()
if len(fignums)>0:
nextFig = np.max(plt.get_fignums())+1
else:
nextFig = 1
else:
nextFig=figure+1
# Open another one
if Map:
figCarte = plt.figure(nextFig, figsize=figsize[1])
carte = figCarte.add_subplot(111, projection=self.projection)
carte.set_extent([self.lonmin, self.lonmax, self.latmin, self.latmax], crs=self.projection)
# Gridlines (there is something wrong with the gridlines class...)
gl = carte.gridlines(crs=self.projection, draw_labels=True, alpha=0.5, zorder=0)
gl.xlabel_style = {'size': 'large', 'color': 'k', 'weight': 'bold'}
gl.ylabel_style = {'size': 'large', 'color': 'k', 'weight': 'bold'}
self.cartegl = gl
#carte.set_xticks(carte.get_xticks())
#carte.set_yticks(carte.get_yticks())
#carte.tick_params(axis='both', which='major', labelsize='large')
# Set the axes
if Fault:
faille.set_xlabel('Longitude')
faille.set_ylabel('Latitude')
faille.set_zlabel('Depth (km)')
# store plots
if Fault:
self.faille = faille
self.figFaille = figFaille
else:
self.faille = None
self.figFaille = None
if Map:
self.carte = carte
self.figCarte = figCarte
else:
self.carte = None
self.figCarte = None
# All done
return
def drawScaleBar(self, scalebar, csiobj, lonlat=None, zorder=0, textoffset=10., linewidth=1, color='k', fontdict=None):
'''
Draw a {scalebar} km bar for scale at {lonlat}.
'''
# Check
assert type(scalebar) == float, 'scalebar should be float: {}'.format(type(scalebar))
# Chose where to put the bar
if lonlat is not None:
lonc, latc = lonlat
else:
lonc = self.lonmin + (self.lonmax-self.lonmin)/10.
latc = self.latmin + (self.latmax-self.latmin)/10.
# Convert to xy and build the end points
xc,yc = csiobj.ll2xy(lonc,latc)
# End points
x1 = xc-scalebar/2.
x2 = xc+scalebar/2.
# Convert
lon1,lat1 = csiobj.xy2ll(x1,yc)
lon2,lat2 = csiobj.xy2ll(x2,yc)
lonc,latc = csiobj.xy2ll(xc,yc+textoffset)
# Show me
self.carte.plot([lon1, lon2], [lat1,lat2], '-', color=color,
linewidth=linewidth, zorder=zorder)
self.carte.text(lonc,latc,'{} km'.format(scalebar), fontdict=fontdict,
horizontalalignment='center',zorder=zorder)
# All done
return
def close(self, fig2close=['map', 'fault']):
'''
Closes all the figures
Kwargs:
* fig2close : a list of 'map' and 'fault'. By default, closes both figures
Returns:
* None
'''
# Check
if type(fig2close) is not list:
fig2close = [fig2close]
# Figure 1
if 'fault' in fig2close:
plt.close(self.figFaille)
if 'map' in fig2close:
plt.close(self.figCarte)
# All done
return
def show(self, mapaxis=None, triDaxis=None, showFig=['fault', 'map'], fitOnBox=False):
'''
Show to screen
Kwargs:
* mapaxis : Specify the axis type for the map (see matplotlib)
* triDaxis : Specify the axis type for the 3D projection (see mpl_toolkits)
* showFig : List of plots to show on screen ('fault' and/or 'map')
* fitOnBox : If True, fits the horizontal axis to the one asked at initialization
Returns:
* None
'''
# Change axis of the map
if mapaxis != None and self.carte is not None:
self.carte.axis(mapaxis)
# Change the axis of the 3d projection
if triDaxis != None and self.faille is not None:
self.faille.axis(triDaxis)
# Fits the horizontal axis to the asked values
if fitOnBox:
if self.lonmin>180.:
self.lonmin -= 360.
if self.lonmax>180.:
self.lonmax -= 360.
if self.carte is not None: self.carte.set_extent([self.lonmin, self.lonmax, self.latmin, self.latmax])
if self.faille is not None:
self.faille.set_xlim(self.carte.get_xlim())
self.faille.set_ylim(self.carte.get_ylim())
# Delete figures
if 'map' not in showFig:
plt.close(self.figCarte)
if 'fault' not in showFig:
plt.close(self.figFaille)
# Show
plt.show()
# All done
return
def savefig(self, prefix, mapaxis='equal', ftype='pdf', dpi=None, bbox_inches=None,
triDaxis='auto', saveFig=['fault', 'map']):
'''
Save to file.
Args:
* prefix : Prefix used for filenames
Kwargs:
* mapaxis : 'equal' or 'auto'
* ftype : 'eps', 'pdf', 'png'
* dpi : whatever dot-per-inche you'd like
* bbox_inches : pdf details
* triDaxis : 3D axis scaling
* saveFig : Which figures to save
Returns:
* None
'''
# Change axis of the map
if mapaxis is not None and self.carte is not None:
self.carte.axis(mapaxis)
# Change the axis of the 3d proj
if triDaxis is not None and self.faille is not None:
self.faille.axis(triDaxis)
# Save
if (ftype == 'png') and (dpi is not None) and (bbox_inches is not None):
if 'fault' in saveFig and self.faille is not None:
self.figFaille.savefig('%s_fault.png' % (prefix),
dpi=dpi, bbox_inches=bbox_inches)
if 'map' in saveFig and self.carte is not None:
self.figCarte.savefig('%s_map.png' % (prefix),
dpi=dpi, bbox_inches=bbox_inches)
else:
if 'fault' in saveFig and self.faille is not None:
self.figFaille.savefig('{}_fault.{}'.format(prefix, ftype))
if 'map' in saveFig and self.carte is not None:
self.figCarte.savefig('{}_map.{}'.format(prefix, ftype))
# All done
return
def addColorbar(self, values, scalarMap, cbaxis, cborientation, figure, cblabel=''):
'''
Adds a colorbar for a given {scalarMap} to the chosen {figure}
Args:
* values : Values used fr the plot
* scalaMap : Scalar Mappable from matplotlib
* cbaxis : [Left, Bottom, Width, Height] shape of the axis in which the colorbar is plot
* cborientation : 'horizontal' or 'vertical'
* figure : Figure object
Kwargs:
* cblabel : Label the colorbar
'''
scalarMap.set_array(values)
cax = figure.add_axes(cbaxis)
cb = plt.colorbar(scalarMap, cax=cax, orientation=cborientation)
cb.set_label(label=cblabel, weight='bold')
# Save this axis
self.cbax = cb
# All done
return
def clf(self):
'''
Clears the figures
Returns:
* None
'''
self.figFaille.clf()
self.figCarte.clf()
return
def titlemap(self, titre, y=1.1):
'''
Sets the title of the map.
Args:
* titre : title of the map
Returns:
* None
'''
self.carte.set_title(titre, y=y)
# All done
return
def titlefault(self, titre):
'''
Sets the title of the fault model.
Args:
* titre : title of the fault
Returns:
* None
'''
self.faille.set_title(titre, title=1.08)
# All done
return
def setzaxis(self, depth, zticklabels=None):
'''
Set the z-axis.
Args:
* depth : Maximum depth.
Kwargs:
* ztickslabel : which labels to use
Returns:
* None
'''
if self.faille is None:
print('No fault figure work on')
return
self.faille.set_zlim3d([-1.0*(depth+5), 0])
if zticklabels is None:
zticks = []
zticklabels = []
for z in np.linspace(0,depth,5):
zticks.append(-1.0*z)
zticklabels.append(z)
else:
zticks = []
for z in zticklabels:
zticks.append(-1.0*z)
self.faille.set_zticks(zticks)
self.faille.set_zticklabels(zticklabels)
# All done
return
def set_view(self, elevation, azimuth, shape=(1., 1., 1.)):
'''
Sets azimuth and elevation angle for the 3D plot.
Args:
* elevation : Point of view elevation angle
* azimuth : Point of view azimuth angle
Kwargs:
* shape : [scale_x, scale_y, scale_z] (0-1 each)
Returns:
* None
'''
# Check
if self.faille is None:
print('No Fault figure to work on')
return
# Set angles
self.faille.view_init(elevation,azimuth)
# Thank you stackoverflow
self.faille.get_proj = lambda: np.dot(Axes3D.get_proj(self.faille),
np.diag([shape[0], shape[1], shape[2], 1]))
#all done
return
def equalize3dAspect(self):
"""
Make the 3D axes have equal aspect. Not working yet (maybe never).
Returns:
* None
"""
# Check
if self.faille is None:
print('No Fault figure to work on')
return
xlim = self.faille.get_xlim3d()
ylim = self.faille.get_ylim3d()
zlim = self.faille.get_zlim3d()
x_range = xlim[1] - xlim[0]
y_range = ylim[1] - ylim[0]
z_range = zlim[1] - zlim[0]
x0 = 0.5 * (xlim[1] + xlim[0])
y0 = 0.5 * (ylim[1] + ylim[0])
z0 = 0.5 * (zlim[1] + zlim[0])
max_range = 0.5 * np.array([x_range, y_range, z_range]).max()
self.faille.set_xlim3d([x0-max_range, x0+max_range])
self.faille.set_ylim3d([y0-max_range, y0+max_range])
self.faille.set_zlim3d(zlim)
self.figFaille.set_size_inches((14,6))
return
def set_xymap(self, xlim, ylim):
'''
Sets the xlim and ylim on the map.
Args:
* xlim : tuple of the ongitude limits
* ylim : tuple of the latitude limits
Returns:
* None
'''
# check
if self.carte is None: return
self.carte.set_extent([xlim[0], xlim[1], ylim[0], ylim[1]])
# All done
return
def shadedTopography(self, source='gebco', smooth=3, azimuth=140, altitude=45,
alpha=1., zorder=1, cmap='Greys', norm=None,
gebcotype='sub_ice_topo', gebcoyear=2022,
srtmversion=1):
'''
if source == 'gebco':
Plots the shaded topography Gebco.
Needs user to download Gebco data and store that in ~/.local/share/cartopy/GEBCO
if source == 'srtm':
Plots the shaded topography from SRTM. Thanks to Thomas Lecocq.
Needs user to download the SRTM tiles and unzip them beforehand (until the day cartopy guru's
manage to input a login and password to access directly SRTM data).
Tiles must be stored at ~/.local/share/cartopy/SRTM/SRTMGL1 or in the directory given
by the environment variable CARTOPY_DATA_DIR (which must be set before importing cartopy)
Args:
* smooth : Smoothing factor in pixels of SRTM data (3 is nice)
* azimuth : Azimuth of the sun
* elevation : Sun elevation
* alpha : Alpha
* srtmversion : 1 or 3
* gebcotype : 'sub_ice_topo'
* gebcoyear : 2022
Returns:
* None
'''
# check
if self.carte is None: return
# Define toposhading (thanks Thomas Lecocq and the Cartopy website)
def shade(located_elevations):
"""
Given an array of elevations in a LocatedImage, add a relief (shadows) to
give a realistic 3d appearance.
"""
new_img = srtm.add_shading(sciim.gaussian_filter(located_elevations.image, smooth),
azimuth=azimuth, altitude=altitude)
return LocatedImage(new_img, located_elevations.extent)
if source == 'srtm':
# Version
if srtmversion == 1:
source = SRTM1Source(max_nx=8, max_ny=8)
elif srtmversion == 3:
source = SRTM3Source(max_nx=8, max_ny=8)
elif source == 'gebco':
# Get it
source = GebcoSource(dtype=gebcotype, year=gebcoyear)
# Build the raster
if smooth>0.:
shaded_topo = PostprocessedRasterSource(source, shade)
else:
shaded_topo = source
# Add the raster
self.carte.add_raster(shaded_topo, cmap=cmap, alpha=alpha, zorder=zorder, clim=norm)
# All done
return
def drawCoastlines(self, color='k', linewidth=1.0, linestyle='solid',
resolution='10m', landcolor='lightgrey', seacolor=None, drawMapScale=None,
parallels=None, meridians=None, drawOnFault=False,
alpha=0.5, zorder=1):
'''
Draws the coast lines in the desired area.
Kwargs:
* color : Color of lines
* linewidth : Width of lines
* linestyle : Style of lines
* resolution : Resolution of the coastline. Can be 10m, 50m or 110m
* drawLand : Fill the continents (True/False)
* drawMapScale : Draw a map scale (None or length in km)
* parallels : If int, number of parallels. If float, spacing in degrees between parallels. If np.array, array of parallels
* meridians : Number of meridians to draw or array of meridians
* drawOnFault : Draw on 3D fault as well
* zorder : matplotlib order of plotting
Returns:
* None
'''
# check
if self.carte is None: return
# Scale bar
if drawMapScale is not None:
self.drawScaleBar(drawMapScale, lonlat=None)
# Ocean color (not really nice since this colors everything in the background)
if seacolor=='image':
self.carte.stock_img()
else:
if seacolor is not None:
self.carte.add_feature(cfeature.NaturalEarthFeature('physical',
'ocean',
scale=resolution,
edgecolor=color,
facecolor=seacolor,
zorder=np.max([zorder-1,0])))
# coastlines in cartopy are multipolygon objects. Polygon has exterior, which has xy
self.coastlines = cfeature.NaturalEarthFeature('physical', 'land', scale=resolution,
edgecolor=color,
facecolor=landcolor,
linewidth=linewidth,
linestyle=linestyle,
zorder=zorder, alpha=alpha)
# Draw and get the line object
self.carte.add_feature(self.coastlines)
## MapScale
if drawMapScale is not None:
assert False, 'Cannot draw a map scale yet. To be implemented...'
# Parallels
if parallels is not None:
lmin,lmax = self.latmin, self.latmax
if type(parallels) is int:
parallels = np.linspace(lmin, lmax, parallels+1)
elif type(parallels) is float:
parallels = np.arange(lmin, lmax+parallels, parallels)
parallels = np.round(parallels, decimals=2)
# Meridians
if meridians is not None:
lmin,lmax = self.lonmin, self.lonmax
if type(meridians) is int:
meridians = np.linspace(lmin, lmax, meridians+1)
elif type(meridians) is float:
meridians = np.arange(lmin, lmax+meridians, meridians)
meridians = np.round(meridians, decimals=2)
# Draw them
if meridians is not None and parallels is not None:
gl = self.carte.gridlines(color='gray', xlocs=meridians, ylocs=parallels, linestyle=(0, (1, 1)))
# All done
return
def drawCountries(self, resolution='10m', linewidth=1., edgecolor='gray', facecolor='lightgray', alpha=1., zorder=0):
'''
See the cartopy manual for options
'''
# Check
if self.carte is not None:
self.countries = cfeature.NaturalEarthFeature(scale=resolution, category='cultural', name='admin_0_countries',
linewidth=linewidth, edgecolor=edgecolor, facecolor=facecolor,
alpha=alpha, zorder=zorder)
self.carte.add_feature(self.countries)
# All done
return
def faulttrace(self, fault, color='r', add=False, discretized=False, linewidth=1, zorder=1):
'''
Plots a fault trace.
Args:
* fault : Fault instance
Kwargs:
* color : Color of the fault.
* add : plot the faults in fault.addfaults
* discretized : Plot the discretized fault
* zorder : matplotlib order of plotting
Returns:
* None
'''
# discretized?
if discretized:
lon = fault.loni
lat = fault.lati
else:
lon = fault.lon
lat = fault.lat
# Plot the added faults before
if add:
for f in fault.addfaults:
#f[0][f[0]<0.] += 360.
self.carte.plot(f[0], f[1], '-k', zorder=zorder, linewidth=linewidth)
for f in fault.addfaults:
if self.faille_flag:
self.faille.plot(f[0], f[1], '-k', linewidth=linewidth)
# Plot the surface trace
#lon[lon<0] += 360.
#lon[np.logical_or(lon<self.lonmin, lon>self.lonmax)] += 360.
if hasattr(fault, 'color'): color = fault.color
if hasattr(fault, 'linewidth'): linewidth = fault.linewidth
if self.faille is not None: self.faille.plot(lon, lat, '-{}'.format(color), linewidth=linewidth)
if self.carte is not None: self.carte.plot(lon, lat, '-{}'.format(color), zorder=zorder,
linewidth=linewidth)
# All done
return
def faultpatches(self, fault, slip='strikeslip', norm=None, colorbar=True,
cbaxis=[0.1, 0.2, 0.1, 0.02], cborientation='horizontal', cblabel='',
plot_on_2d=False, revmap=False, linewidth=1.0, cmap='jet', offset=None,
alpha=1.0, factor=1.0, zorder=3, edgecolor='slip', colorscale='normal'):
'''
Plot the fualt patches
Args:
* fault : Fault instance
Kwargs:
* slip : Can be 'strikeslip', 'dipslip', 'tensile', 'total' or 'coupling'
* norm : Limits for the colorbar.
* colorbar : if True, plots a colorbar.
* cbaxis : [Left, Bottom, Width, Height] of the colorbar axis
* cborientation : 'horizontal' (default)
* cblabel : Write something next to the colorbar.
* plot_on_2d : if True, adds the patches on the map.
* revmap : Revert the colormap
* linewidth : Width of the edges of the patches
* cmap : Colormap (any of the matplotlib ones)
* factor : scale factor for fault slip values
* zorder : matplotlib order of plotting
* edgecolor : either a color or 'slip'
* colorscale : 'normal' or 'log'
Returns:
* None
'''
# Get slip
if slip in ('strikeslip'):
slip = fault.slip[:,0].copy()
elif slip in ('dipslip'):
slip = fault.slip[:,1].copy()
elif slip in ('tensile'):
slip = fault.slip[:,2].copy()
elif slip in ('total'):
slip = np.sqrt(fault.slip[:,0]**2 + fault.slip[:,1]**2 + fault.slip[:,2]**2)
elif slip in ('coupling'):
slip = fault.coupling.copy()
else:
print ("Unknown slip direction")
return
slip *= factor
# norm
if norm == None:
vmin=slip.min()
vmax=slip.max()
else:
vmin=norm[0]
vmax=norm[1]
# Potential offset of the fault wrt. its true position
if offset is None:
offset = [0., 0., 0.]
# set z axis
try:
self.setzaxis(fault.depth+5., zticklabels=fault.z_patches)
except:
print('Warning: Depth cannot be determined automatically. Please set z-axis limit manually')
# set color business
if revmap:
cmap = plt.get_cmap(cmap)
else:
cmap = plt.get_cmap(cmap)
if colorscale in ('normal', 'n'):
cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
elif colorscale in ('log', 'l', 'lognormal'):
cNorm = colors.LogNorm(vmin=vmin, vmax=vmax)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
# fault figure
if self.faille is not None:
Xs = np.array([])
Ys = np.array([])
for p in range(len(fault.patch)):
ncorners = len(fault.patchll[0])
x = []
y = []
z = []
for i in range(ncorners):
x.append(fault.patchll[p][i][0]+offset[0])
y.append(fault.patchll[p][i][1]+offset[1])
z.append(-1.0*fault.patchll[p][i][2]+offset[2])
verts = []
for xi,yi,zi in zip(x,y,z):
#if xi<0.: xi += 360.
verts.append((xi,yi,zi))
rect = art3d.Poly3DCollection([verts])
rect.set_facecolor(scalarMap.to_rgba(slip[p]))
if edgecolor=='slip':
rect.set_edgecolors(scalarMap.to_rgba(slip[p]))
else:
rect.set_edgecolors(edgecolor)
if alpha<1.0:
rect.set_alpha(alpha)
rect.set_linewidth(linewidth)
self.faille.add_collection3d(rect)
# Reset x- and y-lims
self.faille.set_xlim([self.lonmin,self.lonmax])
self.faille.set_ylim([self.latmin,self.latmax])
# If 2d.
if plot_on_2d and self.carte is not None:
for p, patch in zip(range(len(fault.patchll)), fault.patchll):
x = []
y = []
ncorners = len(fault.patchll[0])
for i in range(ncorners):
x.append(patch[i][0]+offset[0])
y.append(patch[i][1]+offset[1])
verts = []
for xi,yi in zip(x,y):
#if xi<0.: xi += 360.
verts.append((xi,yi))
rect = colls.PolyCollection([verts])
rect.set_facecolor(scalarMap.to_rgba(slip[p]))
if edgecolor=='slip':
rect.set_edgecolors(scalarMap.to_rgba(slip[p]))
else:
rect.set_edgecolors(edgecolor)
rect.set_linewidth(linewidth)
if alpha<1.0: rect.set_alpha(alpha)
rect.set_zorder(zorder)
self.carte.add_collection(rect)
# put up a colorbar
if colorbar:
if self.faille is not None: self.addColorbar(slip, scalarMap, cbaxis, cborientation, self.figFaille, cblabel=cblabel)
if plot_on_2d and self.carte is not None:
self.addColorbar(slip, scalarMap, cbaxis, cborientation,self.figCarte, cblabel=cblabel)
# All done
return
def pressuresource(self, fault, delta='pressure', norm=None, colorbar=True,
cbaxis=[0.1, 0.2, 0.1, 0.02], cborientation='horizontal', cblabel='',
revmap=False, linewidth=1.0, cmap='jet',
alpha=1.0, factor=1.0, zorder=3, plot_on_2d=False):
'''
Plots a pressure source.
Args:
* fault : Pressure source instance
Kwargs:
* delta : Can be 'pressure' or 'volume'
* norm : Limits for the colorbar.
* colorbar : if True, plots a colorbar.
* revmap : Reverts the colormap
* linewidth : width of the edhe of the source
* cmap : matplotlib colormap
* plot_on_2d : if True, adds the patches on the map.
* factor : scale factor for pressure values
* zorder : matplotlib plotting order
Returns:
* None
'''
# Get slip
if delta == 'pressure':
delta = fault.deltapressure
elif delta == 'volume':
delta = fault.deltavolume
else:
print ("Unknown slip direction")
return
delta *= factor
# norm
if norm == None:
vmin=0
vmax=delta
else:
vmin=norm[0]
vmax=norm[1]
# set z axis
self.setzaxis(fault.ellipshape['z0']+5., zticklabels=None)
# set color business
if revmap:
cmap = plt.get_cmap(cmap)
else:
cmap = plt.get_cmap(cmap)
cNorm = colors.Normalize(vmin=vmin, vmax=vmax)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)
Xs = np.array([])
Ys = np.array([])
#plot 3-d spheroid here
#Radii -- assuming prolate spheroid (z-axis is the semi-major axis when dip = 90, y-axis is semi-major axis when strike = 0), in km
rx, ry, rz = fault.ellipshape['a']*fault.ellipshape['A']/1000.,fault.ellipshape['a']/1000.,fault.ellipshape['a']*fault.ellipshape['A']/1000.
#All spherical angles
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100 )
#xyz coordinates for spherical angles
ex = rx * np.outer(np.cos(u), np.sin(v))
ey = ry * np.outer(np.sin(u), np.sin(v))
ez = rz * np.outer(np.ones_like(u), np.cos(v))
#strike and dip in radians, multiplied by -1 because we want clockwise rotations
strike = -1*fault.ellipshape['strike']* np.pi / 180.
dip = -1*fault.ellipshape['dip']* np.pi / 180.
#??? NEEDS TO BE CONFIRMED ---(could use scipy.spatial.transformations, but would require an additional package installation)
#This conforms to the dMODELS formulation of Yang
#All of this should probably be double, triple-checked to make sure we are plotting the source correctly
rotex = np.asarray([[1,0,0],[0,np.cos(dip),-np.sin(dip)],[0,np.sin(dip),np.cos(dip)]])
#rotey = np.asarray([[np.cos(dip), 0., np.sin(dip)],[0., 1.,0.],[-np.sin(dip), 0, np.cos(dip)]])
rotez = np.asarray([[np.cos(strike), -np.sin(strike), 0.],[np.sin(strike), np.cos(strike),0.],[0.,0.,1.]])
#Rotate around y-axis (or x-axis???) first, then z-axis
xyz = np.dot(np.array([ex,ey,ez]).T,np.dot(rotex,rotez))
ex_ll,ey_ll = np.array(fault.xy2ll(xyz[:,:,0]+fault.xf,xyz[:,:,1]+fault.yf))
ez_ll = xyz[:,:,2]-(fault.ellipshape['z0']/1000.)
if self.faille is not None:
#x0 and y0 are in lat/lon, depth is negative and in km
self.faille.plot_surface(ex_ll,ey_ll,ez_ll,color=scalarMap.to_rgba(delta))
# Reset x- and y-lims
self.faille.set_xlim([self.lonmin,self.lonmax])
self.faille.set_ylim([self.latmin,self.latmax])
# # If 2d. Just plots center for now, should plot ellipse projection onto surface
if plot_on_2d and self.carte is not None:
self.carte.scatter(fault.ellipshape['x0'],fault.ellipshape['y0'])
# put up a colorbar
if colorbar:
if self.faille is not None: self.addColorbar(delta, scalaMap, cbaxis, cborientation, self.figFaille, cblabel=cblabel)
if plot_on_2d and self.carte is not None:
self.addColorbar(delta, scalaMap, cbaxis, cborientation, self.figCarte, cblabel=cblabel)
# All done
return
def faultTents(self, fault,
slip='strikeslip', norm=None, colorbar=True, alpha=1.0,
cbaxis=[0.1, 0.2, 0.1, 0.02], cborientation='horizontal', cblabel='',
method='scatter', cmap='jet', plot_on_2d=False,
revmap=False, factor=1.0, npoints=10,
xystrides=[100, 100], zorder=0,
vertIndex=False):
'''
Plot a fault with tents.
Args:
* fault : TriangularTent fault instance
Kwargs:
* slip : Can be 'strikeslip', 'dipslip', 'tensile', 'total' or 'coupling'
* norm : Limits for the colorbar.
* colorbar : if True, plots a colorbar.
* method : Can be 'scatter' (plots all the sub points as a colored dot) or 'surface' (interpolates a 3D surface which can be ugly...)
* cmap : matplotlib colormap
* plot_on_2d : if True, adds the patches on the map.
* revmap : Reverse the default colormap
* factor : Scale factor for fault slip values
* npoints : Number of subpoints per patch. This number is only indicative of the actual number of points that is picked out by the dropSourcesInPatch function of EDKS.py. It only matters to make the interpolation finer. Default value is generally alright.
* xystrides : If method is 'surface', then xystrides is going to be the number of points along x and along y used to interpolate the surface in 3D and its color.
* vertIndex : Writes the index of the vertices
Returns:
* None
'''
# Get slip
if slip in ('strikeslip'):
slip = fault.slip[:,0].copy()
elif slip in ('dipslip'):
slip = fault.slip[:,1].copy()
elif slip in ('tensile'):
slip = fault.slip[:,2].copy()
elif slip in ('total'):
slip = np.sqrt(fault.slip[:,0]**2 + fault.slip[:,1]**2 + fault.slip[:,2]**2)
elif slip in ('coupling'):
slip = fault.coupling.copy()
elif slip in ('sensitivity'):
slip = fault.sensitivity.copy()
else:
print ("Unknown slip direction")
return
slip *= factor
# norm
if norm == None:
vmin=slip.min()
vmax=slip.max()
else:
vmin=norm[0]
vmax=norm[1]
# set z axis
self.setzaxis(fault.depth+5., zticklabels=fault.z_patches)
# set color business
if revmap:
cmap = plt.get_cmap('{}_r'.format(cmap))
else: