-
Notifications
You must be signed in to change notification settings - Fork 31
/
multifaultsolve.py
2027 lines (1617 loc) · 68.2 KB
/
multifaultsolve.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
'''
A Class to assemble several faults into a single inverse problem. All the faults must have been intialized and constructed using the same data set.
This class allows then to:
1. Spit the G, m, Cm, and Cd elements for a third party solver (such as Altar, for instance)
2. Proposes a simple solution based on a least-square optimization.
Written by R. Jolivet, April 2013.
Updated by T. Shreve, May 2019, to include pressure sources in describeParams and distributem.
'''
import copy
import numpy as np
import pyproj as pp
import matplotlib.pyplot as plt
try:
import h5py
except:
print('HDF5 capabilities not available')
class multifaultsolve(object):
'''
A class that assembles the linear inverse problem for multiple faults and multiple datasets. This class can also solve the problem using simple linear least squares (bounded or unbounded).
Args:
* name : Name of the project.
* faults : List of faults from verticalfault or pressure .
'''
def __init__(self, name, faults, verbose=True):
self.verbose = verbose
if self.verbose:
print ("---------------------------------")
print ("---------------------------------")
print ("Initializing solver object")
# Ready to compute?
self.ready = False
self.figurePath = './'
# Store things into self
self.name = name
self.faults = faults
# check the utm zone
self.utmzone = faults[0].utmzone
for fault in faults:
if fault.utmzone is not self.utmzone:
print("UTM zones are not equivalent, this is a problem")
self.ready = False
return
self.xy2ll = faults[0].xy2ll
self.ll2xy = faults[0].ll2xy
# check that G and d have been assembled prior to initialization
for fault in faults:
if fault.Gassembled is None:
self.ready = False
print("G has not been assembled in fault structure {}".format(fault.name))
if fault.dassembled is None:
self.ready = False
print("d has not been assembled in fault structure {}".format(fault.name))
# Check that the sizes of the data vectors are consistent
self.d = faults[0].dassembled
for fault in faults:
if (fault.dassembled != self.d).all():
print("Data vectors are not consistent, please re-consider your data in fault structure {}".format(fault.name))
# Check that the data covariance matrix is the same
self.Cd = faults[0].Cd
for fault in faults:
if (fault.Cd != self.Cd).all():
print("Data Covariance Matrix are not consistent, please re-consider your data in fault structure {}".format(fault.name))
# Initialize things
self.fault_indexes = None
# Store an array of the patch areas
patchAreas = []
for fault in faults:
if fault.type=="Fault":
if fault.patchType == 'triangletent':
fault.computeTentArea()
for tentIndex in range(fault.slip.shape[0]):
patchAreas.append(fault.area_tent[tentIndex])
else:
fault.computeArea()
for patchIndex in range(fault.slip.shape[0]):
patchAreas.append(fault.area[patchIndex])
self.patchAreas = np.array(patchAreas)
self.type = "Fault"
elif fault.type=="Pressure":
self.type = "Pressure"
elif fault.type in ('notafault', 'transformation'):
print('Not a fault detected')
# All done
return
def assembleGFs(self):
'''
Assembles the Green's functions matrix G for the concerned faults or pressure sources.
Returns:
* None
'''
# Get the faults
faults = self.faults
# Get the size of the total G matrix
Nd = self.d.size
Np = 0
st = []
se = []
if self.fault_indexes is None:
self.fault_indexes = {}
for fault in faults:
st.append(Np)
Np += fault.Gassembled.shape[1]
se.append(Np)
self.fault_indexes[fault.name] = [st[-1], se[-1]]
# Allocate the big G matrix
self.G = np.zeros((Nd, Np))
# Store the guys
for fault in faults:
# get the good indexes
st = self.fault_indexes[fault.name][0]
se = self.fault_indexes[fault.name][1]
# Store the G matrix
self.G[:,st:se] = fault.Gassembled
# Keep track of indexing
if fault.type=="Fault":
self.affectIndexParameters(fault)
# self ready
self.ready = True
# Set the number of parameters
self.Nd = Nd
self.Np = Np
# CHeck
if self.verbose:
print('Number of data: {}'.format(self.Nd))
print('Number of parameters: {}'.format(self.Np))
# Describe which parameters are what
self.describeParams()
# All done
return
def equalizeParams(self, iparams, Cm=None):
'''
This is a step to force parameters to be equal. Effectively, since the
problem is linear, we sum columns of G to have a single parameter. The
parameter in question is set at the end of G.
Cm is modified so that it has 1 on the idagonal or what is provided in Cm
The original G is saved as Goriginal. The original Cm is in Cmoriginal.
The method distributem accounts for such modification by restoring G and Cm
and the mpost vector according to the original problem.
iparams is a list of list of groups of parameters:
iparams = [ [1,2,3,19,39], [23, 24]]
Args:
* iparams: List of lists
Kwargs:
* Cm : List of covariances
'''
# Problem must be assembled first, otherwise it is a mess
assert self.ready, 'Must assemble the problem first'
# Save original problem
self.Goriginal = copy.deepcopy(self.G)
self.Cmoriginal = copy.deepcopy(self.Cm)
# Check format of iparams
if type(iparams[0]) is not list:
iparams = [iparams]
for ipar in iparams:
assert type(ipar) is list, 'Elements of iparams must be lists'
for i in ipar: assert type(i) in (int, np.int64), 'Indexes in iparams must be int: {}'.format(type(i))
# Remove the columns in G
allpars = [i for ipar in iparams for i in ipar]
self.G = np.delete(self.G, allpars, axis=1)
self.paramTypes = np.delete(self.paramTypes, allpars)
self.Cm = np.delete(self.Cm, allpars, axis=1)
self.Cm = np.delete(self.Cm, allpars, axis=0)
# Iterate over the columns of G
self.equalized = {}
for i, ipar in enumerate(iparams):
p = np.array([None for i in range(len(self.paramTypes)+1)])
p[:-1] = self.paramTypes
p[-1] = ('Equalized', ipar)
self.paramTypes = p
self.equalized[self.G.shape[1]] = ipar
newG = np.zeros((self.G.shape[0], self.G.shape[1]+1))
newG[:self.G.shape[0], :self.G.shape[1]] = self.G
newG[:,-1] = self.Goriginal[:,ipar].sum(axis=1)
self.G = newG
Cmnew = np.zeros((self.Cm.shape[0]+1,self.Cm.shape[1]+1))
Cmnew[:self.Cm.shape[0],:self.Cm.shape[0]] = self.Cm
if Cm is not None:
Cmnew[-1,-1] = Cm[i]
else:
Cmnew[-1,-1] = 1.
self.Cm = Cmnew
# Build mapping between mnew and mpost
eye = np.eye(self.Goriginal.shape[1])
eye = np.delete(eye, allpars, axis=1)
eye[allpars,:] = 0.
mapping = np.zeros((self.Goriginal.shape[1], self.G.shape[1]))
mapping[:,:eye.shape[1]] = eye
for eq in self.equalized:
ipar = self.equalized[eq]
mapping[ipar,eq] = 1.
self.equalized['map'] = mapping
# Change things
self.Np = self.G.shape[1]
# Change the parameter description thing
self.paramDescription = {}
couples,inverse = np.unique(self.paramTypes, return_inverse=True)
for icouple,couple in enumerate(couples):
uu = np.flatnonzero(inverse==icouple)
if len(uu)>0:
if 'Equalized' not in couple:
fault = couple[0]
component = couple[1]
if fault not in self.paramDescription: self.paramDescription[fault] = {}
ss = '{:12s}'.format('{:4d} - {:4d}'.format(uu[0], uu[-1]+1))
self.paramDescription[fault][component] = ss
else:
if 'Equalized' not in self.paramDescription: self.paramDescription['Equalized'] = []
self.paramDescription['Equalized'].append([uu[0], couple[1]])
# All done
return
def unequalizeParams(self):
'''
Restores the shape of G and Cm and organizes mpost accordingly whem the
problem has been altered by equalizedParams.
'''
# Check
assert hasattr(self, 'equalized'), 'Cannot unequalize if equalizedParams was not used'
# Restore G
self.G = copy.deepcopy(self.Goriginal)
del self.Goriginal
self.Cm = copy.deepcopy(self.Cmoriginal)
del self.Cmoriginal
# Reorganize mpost
msave = copy.deepcopy(self.mpost)
self.mpost = self.equalized['map'].dot(msave)
self.Np = len(self.mpost)
# Parameter Description
self.makeParamDescription()
# All done
return
def strongConstraint(self, iparams, cov=1e-6):
'''
Adds a bunch of lines to force the parameters {iparams} to
be equal, within {cov}. Effectively, it adds a line of +1 and -1
to the parameters so that all {iparams} are equal to the first one.
The equality will fall within {cov} as this number is set as the diagonal
term of the data covariance for the corresponding lines.
Args:
* iparams : List of parameters
Kwargs:
* cov : Covariance
'''
# Number of constraints
nc = len(iparams) - 1
# Create the new lines
Glines = np.zeros((nc, self.G.shape[1]))
dlines = np.zeros((nc,))
# Iterate
for i,ip in enumerate(iparams[1:]):
Glines[i,iparams[0]] = 1.
Glines[i,ip] = -1.
# Concatenate
self.G = np.concatenate((self.G, Glines))
self.d = np.concatenate((self.d, dlines))
# Expand Cd
self.Cd = np.concatenate((self.Cd, np.zeros((self.Cd.shape[0], nc))), axis=1)
self.Cd = np.concatenate((self.Cd, np.zeros((nc, self.Cd.shape[1]))), axis=0)
cc = np.eye(nc)*cov
self.Cd[-nc:,-nc:] = cc
# Update
self.Nd = len(self.d)
# All done
return
def OrganizeGBySlipmode(self):
'''
Organize G by slip mode instead of fault segment Return the new G matrix.
Returns:
* array
'''
assert len(self.faults) !=1, 'You have only one fault, why would you want to do that?'
assert self.ready, 'You need to assemble the GFs before'
info = self.paramDescription
Gtemp = np.zeros((self.G.shape))
N = 0
slipmode = ['Strike Slip', 'Dip Slip', 'Tensile Slip', 'Coupling', 'Extra Parameters']
for mode in slipmode:
for fault in self.faults:
if info[fault.name][mode].replace(' ','') != 'None':
ib = int(info[fault.name][mode].replace(' ','').partition('-')[0])
ie = int(info[fault.name][mode].replace(' ','').partition('-')[2])
Gtemp[:,N:N+ie-ib] = self.G[:,ib:ie]
N += ie-ib
return Gtemp
def sensitivity(self):
'''
Calculates the sensitivity matrix of the problem, :math:`S = \\text{diag}( G^t C_d^{-1} G )`
Returns:
* array
'''
# Import things
import scipy.linalg as scilin
# Invert Cd
iCd = scilin.inv(self.Cd)
s = np.diag(np.dot(self.G.T,np.dot(iCd,self.G)))
# All done
return s
def describeParams(self, redo=True):
'''
Print the parameter description.
Returns:
* None
'''
# Create the parameter description
if redo:
self.makeParamDescription()
# Get the faults
faults = self.faults
if self.verbose:
print('Parameter Description ----------------------------------')
# Loop over the param description
for fault in self.paramDescription:
description = self.paramDescription[fault]
if ('Strike Slip' in description) or ('Dip Slip' in description) or ('Tensile' in description) or ('Coupling' in description) or ('Extra Parameters' in description):
#Prepare the table
if self.verbose:
print('-----------------')
print('{:30s}||{:12s}||{:12s}||{:12s}||{:12s}||{:12s}'.format('Fault Name', 'Strike Slip', 'Dip Slip', 'Tensile', 'Coupling', 'Extra Parms'))
# Get info
if 'Strike Slip' in description:
ss = description['Strike Slip']
else:
ss = 'None'
if 'Dip Slip' in description:
ds = description['Dip Slip']
else:
ds = 'None'
if 'Tensile Slip' in description:
ts = description['Tensile Slip']
else:
ts = 'None'
if 'Coupling' in description:
cp = description['Coupling']
else:
cp = 'None'
if 'Extra Parameters' in description:
op = description['Extra Parameters']
else:
op = 'None'
# print things
if self.verbose:
print('{:30s}||{:12s}||{:12s}||{:12s}||{:12s}||{:12s}'.format(fault, ss, ds, ts, cp, op))
elif 'Pressure' in description:
#Prepare the table
if self.verbose:
print('-----------------')
print('{:30s}||{:12s}||{:12s}'.format('Object Name', 'Pressure', 'Extra Parms'))
# Get info
if 'Pressure' in description:
dp = description['Pressure']
else:
dp = 'None'
if 'Extra Parameters' in description:
op = description['Extra Parameters']
else:
op = 'None'
# print things
if self.verbose:
print('{:30s}||{:12s}||{:12s}'.format(fault, dp, op))
elif 'Surface' in description:
#Prepare the table
if self.verbose:
print('-----------------')
print('{:30s}||{:12s}'.format('Surface Name', 'Surface'))
# Get the size
dp = description['Surface']
# print things
if self.verbose: print('{:30s}||{:12s}'.format(fault, dp))
if 'Equalized' in self.paramDescription:
for case in self.paramDescription['Equalized']:
new,old = case
if self.verbose:
print('-----------------')
print('Equalized parameter indexes: {} --> {}'.format(old,new))
# all done
return
def makeParamDescription(self):
'''
Store what parameters mean
Returns:
* None
'''
faults = self.faults
# initialize the counters
ns = 0
ne = 0
nSlip = 0
# Store that somewhere
self.paramDescription = {}
# Make a list of parameter types
self.paramTypes = np.array([None for i in range(self.Np)])
# Loop over the faults
for fault in faults:
# Where does this fault starts
nfs = copy.deepcopy(ns)
if fault.type=="Fault" or fault.type=='transformation':
# Initialize the values
ss = 'None'
ds = 'None'
ts = 'None'
cp = 'None'
# Conditions on slip
if 's' in fault.slipdir:
ne += fault.slip.shape[0]
ss = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Strike Slip')
ns += fault.slip.shape[0]
if 'd' in fault.slipdir:
ne += fault.slip.shape[0]
ds = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Dip Slip')
ns += fault.slip.shape[0]
if 't' in fault.slipdir:
ne += fault.slip.shape[0]
ts = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Tensile')
ns += fault.slip.shape[0]
if 'c' in fault.slipdir:
ne += fault.slip.shape[0]
cp = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Coupling')
ns += fault.slip.shape[0]
# How many slip parameters
if ne>nSlip:
nSlip = ne
# conditions on orbits (the rest is orbits)
npo = ne - nfs
no = fault.Gassembled.shape[1] - npo
if no>0:
ne += no
op = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Extra Parameters')
ns += no
else:
op = 'None'
# Store
self.paramDescription[fault.name] = {}
self.paramDescription[fault.name]['Strike Slip'] = ss
self.paramDescription[fault.name]['Dip Slip'] = ds
self.paramDescription[fault.name]['Tensile Slip'] = ts
self.paramDescription[fault.name]['Coupling'] = cp
self.paramDescription[fault.name]['Extra Parameters'] = op
elif fault.type=="Pressure":
# Initialize the values
dp = 'None'
if fault.source=="pCDM":
ne += 3
dp = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Pressure')
ns += 3 #fault.slip.shape[0]
else:
ne += 1
dp = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Pressure')
ns += 1 #fault.slip.shape[0]
# How many slip parameters
if ne>nSlip:
nSlip = ne
# conditions on orbits (the rest is orbits)
npo = ne - nfs
no = fault.Gassembled.shape[1] - npo
if no>0:
ne += no
op = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Extra Parameters')
ns += no
else:
op = 'None'
# Store
self.paramDescription[fault.name] = {}
self.paramDescription[fault.name]['Pressure'] = dp
self.paramDescription[fault.name]['Extra Parameters'] = op
elif fault.type == 'Surface':
# Get how long the GFs are
ne += fault.Gassembled.shape[1]
for i in range(ns,ne): self.paramTypes[i] = (fault.name, 'Surface')
dp = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
self.paramDescription[fault.name] = {}
self.paramDescription[fault.name]['Surface'] = dp
# Store the number of slip parameters
self.nSlip = nSlip
# all done
return
def assembleCm(self):
'''
Assembles the Model Covariance Matrix for the concerned faults.
Returns:
* None
'''
# Get the faults
faults = self.faults
# Get the size of Cm
Np = 0
st = []
se = []
if self.fault_indexes is None:
self.fault_indexes = {}
for fault in faults:
st.append(Np)
Np += fault.Gassembled.shape[1]
se.append(Np)
self.fault_indexes[fault.name] = [st[-1], se[-1]]
# Allocate Cm
self.Cm = np.zeros((Np, Np))
# Store the guys
for fault in faults:
st = self.fault_indexes[fault.name][0]
se = self.fault_indexes[fault.name][1]
self.Cm[st:se, st:se] = fault.Cm
# Store the number of parameters
self.Np = Np
# All done
return
def affectIndexParameters(self, fault):
'''
Build the index parameter for a fault.
Args:
* fault : instance of a fault
Returns:
* None
'''
# Get indexes
st = self.fault_indexes[fault.name][0]
se = self.fault_indexes[fault.name][1]
# Save the fault indexes
fault.index_parameter = np.zeros((fault.slip.shape))
fault.index_parameter[:,:] = 9999999
if 's' in fault.slipdir:
fault.index_parameter[:,0] = range(st, st+fault.slip.shape[0])
st += fault.slip.shape[0]
if 'd' in fault.slipdir:
fault.index_parameter[:,1] = range(st, st+fault.slip.shape[0])
st += fault.slip.shape[0]
if 't' in fault.slipdir:
fault.index_parameter[:,2] = range(st, st+fault.slip.shape[0])
# All done
return
def distributem(self, verbose=False):
'''
After computing the m_post model, this routine distributes the m parameters to the faults.
Kwargs:
* verbose : talk to me
Returns:
* None
'''
# Get the faults
faults = self.faults
# Loop over the faults
for fault in faults:
if verbose:
print ("---------------------------------")
print ("---------------------------------")
print("Distribute the slip values to fault {}".format(fault.name))
# Store the mpost
st = self.fault_indexes[fault.name][0]
se = self.fault_indexes[fault.name][1]
fault.mpost = self.mpost[st:se]
# Transformation object
if fault.type=='transformation':
# Distribute simply
fault.distributem()
# Fault object
if fault.type=="Fault":
# Affect the indexes
self.affectIndexParameters(fault)
# put the slip values in slip
st = 0
if 's' in fault.slipdir:
se = st + fault.slip.shape[0]
fault.slip[:,0] = fault.mpost[st:se]
st += fault.slip.shape[0]
if 'd' in fault.slipdir:
se = st + fault.slip.shape[0]
fault.slip[:,1] = fault.mpost[st:se]
st += fault.slip.shape[0]
if 't' in fault.slipdir:
se = st + fault.slip.shape[0]
fault.slip[:,2] = fault.mpost[st:se]
st += fault.slip.shape[0]
if 'c' in fault.slipdir:
se = st + fault.slip.shape[0]
fault.coupling = fault.mpost[st:se]
st += fault.slip.shape[0]
# check
if hasattr(fault, 'NumberCustom'):
fault.custom = {} # Initialize dictionnary
# Get custom params for each dataset
for dset in fault.datanames:
if 'custom' in fault.G[dset].keys():
nc = fault.G[dset]['custom'].shape[1] # Get number of param for this dset
se = st + nc
fault.custom[dset] = fault.mpost[st:se]
st += nc
# Pressure object
elif fault.type=="Pressure":
st = 0
if fault.source in {"Mogi", "Yang"}:
se = st + 1
fault.deltapressure = fault.mpost[st:se].item()
st += 1
elif fault.source=="pCDM":
se = st + 1
fault.DVx = fault.mpost[st:se].item()
st += 1
se = st + 1
fault.DVy = fault.mpost[st:se].item()
st += 1
se = st + 1
fault.DVz = fault.mpost[st:se].item()
st += 1
if fault.DVtot is None:
fault.computeTotalpotency()
elif fault.source=="CDM":
se = st + 1
fault.deltaopening = fault.mpost[st:se].item()
st += 1
elif fault.type == 'Surface':
directions = [fault.direction[data] for data in fault.direction][0]
st = 0
if 'e' in directions:
se = st + fault.motion.shape[0]
fault.motion[:,0] = fault.mpost[st:se]
st += fault.motion.shape[0]
if 'n' in directions:
se = st + fault.motion.shape[0]
fault.motion[:,1] = fault.mpost[st:se]
st += fault.motion.shape[0]
if 'u' in directions:
se = st + fault.motion.shape[0]
fault.motion[:,2] = fault.mpost[st:se]
# Get the polynomial/orbital/helmert values if they exist
if fault.type in ('Fault', 'Pressure'):
fault.polysol = {}
fault.polysolindex = {}
for dset in fault.datanames:
if dset in fault.poly.keys():
if (fault.poly[dset] is None):
fault.polysol[dset] = None
else:
if (fault.poly[dset].__class__ is not str) and (fault.poly[dset].__class__ is not list):
if (fault.poly[dset] > 0):
se = st + fault.poly[dset]
fault.polysol[dset] = fault.mpost[st:se]
fault.polysolindex[dset] = range(st,se)
st += fault.poly[dset]
elif (fault.poly[dset].__class__ is str):
if fault.poly[dset]=='full':
nh = fault.helmert[dset]
se = st + nh
fault.polysol[dset] = fault.mpost[st:se]
fault.polysolindex[dset] = range(st,se)
st += nh
if fault.poly[dset] in ('strain', 'strainnorotation', 'strainonly', 'strainnotranslation', 'translation', 'translationrotation'):
nh = fault.strain[dset]
se = st + nh
fault.polysol[dset] = fault.mpost[st:se]
fault.polysolindex[dset] = range(st,se)
st += nh
elif (fault.poly[dset].__class__ is list):
nh = fault.transformation[dset]
se = st + nh
fault.polysol[dset] = fault.mpost[st:se]
fault.polysolindex[dset] = range(st,se)
st += nh
# All done
return
def SetSolutionFromExternal(self, soln):
'''
Takes a vector where the solution of the problem is and affects it to mpost.
Args:
* soln : array
Returns:
* None
'''
# Check if array
if type(soln) is list:
soln = np.array(soln)
# put it in mpost
self.mpost = soln
# All done
return
def NonNegativeBruteSoln(self):
'''
Solves the least square problem argmin_x || Ax - b ||_2 for x>=0.
No Covariance can be used here, maybe in the future.
Returns:
* None
'''
# Import what is needed
import scipy.optimize as sciopt
# Get things
d = self.d
G = self.G
# Solution
mpost, rnorm = sciopt.nnls(G, -1*d)
# Store results
self.mpost = mpost
self.rnorm = rnorm
# All done
return
def SimpleLeastSquareSoln(self):
'''
Solves the simple least square problem.
:math:`\\textbf{m}_{post} = (\\textbf{G}^t \\textbf{G})^{-1} \\textbf{G}^t \\textbf{d}`
Returns:
* None
'''
# Import things
import scipy.linalg as scilin
# Print
print ("---------------------------------")
print ("---------------------------------")
print ("Computing the Simple Least Squares")
# Get the matrixes and vectors
G = self.G
d = self.d
# Copmute
mpost = np.dot( np.dot( scilin.inv(np.dot( G.T, G )), G.T ), d)
# Store mpost
self.mpost = mpost
# All done
return
def UnregularizedLeastSquareSoln(self, mprior=None):
'''
Solves the unregularized generalized least-square problem using the following formula (Tarantolla, 2005, "Inverse Problem Theory", SIAM):
:math:`\\textbf{m}_{post} = \\textbf{m}_{prior} + (\\textbf{G}^t \\textbf{C}_d^{-1} \\textbf{G})^{-1} \\textbf{G}^t \\textbf{C}_d^{-1} (\\textbf{d} - \\textbf{Gm}_{prior})`
Kwargs:
* mprior : A Priori model. If None, then mprior = np.zeros((Nm,)).
Returns:
* None
'''
# Assert
assert self.ready, 'You need to assemble the GFs'
# Import things
import scipy.linalg as scilin
if self.verbose:
# Print
print ("---------------------------------")
print ("---------------------------------")
print ("Computing the Unregularized Least Square Solution")
# Get the matrixes and vectors
G = self.G
d = self.d
Cd = self.Cd
# Get the number of model parameters
Nm = G.shape[1]
# Check If Cm is symmetric and positive definite
if (Cd.transpose() != Cd).all():
print("Cd is not symmetric, Return...")
return
# Get the inverse of Cd
if self.verbose: print ("Computing the inverse of the data covariance")
iCd = scilin.inv(Cd)
# Construct mprior
if mprior is None:
mprior = np.zeros((Nm,))
# Compute mpost
if self.verbose: print ("Computing m_post")
One = scilin.inv(np.dot( np.dot(G.T, iCd), G ) )
Res = d - np.dot( G, mprior )
Two = np.dot( np.dot( G.T, iCd ), Res )
mpost = mprior + np.dot( One, Two )
# Store m_post
self.mpost = mpost
# All done
return
def GeneralizedLeastSquareSoln(self, mprior=None, rcond=None, useCm=True, mw=False):
'''
Solves the generalized least-square problem using the following formula (Tarantolla, 2005, Inverse Problem Theory, SIAM):
:math:`\\textbf{m}_{post} = \\textbf{m}_{prior} + (\\textbf{G}^t \\textbf{C}_d^{-1} \\textbf{G} + \\textbf{C}_m^{-1})^{-1} \\textbf{G}^t \\textbf{C}_d^{-1} (\\textbf{d} - \\textbf{Gm}_{prior})`
Args:
* mprior : A Priori model. If None, then mprior = np.zeros((Nm,)).
Returns:
* None
'''
# Assert
assert self.ready, 'You need to assemble the GFs'
# Import things
import scipy.linalg as scilin
if self.verbose:
# Print
print ("---------------------------------")
print ("---------------------------------")
print ("Computing the Generalized Inverse")
def computeMwDiff(m, Mw_thresh, patchAreas, mu):
"""
Ahhhhh hard coded shear modulus.
Probably need to edit this to include tensile as well ???
"""
Npatch = len(self.patchAreas)
shearModulus = mu #22.5e9
if len(m) < 2*Npatch: #If only one component of slip (dip or strikeslip)
slip = np.sqrt(m[:Npatch]**2)
else: #If both components of slip (dip or strikeslip)
slip = np.sqrt(m[:Npatch]**2+m[Npatch:2*Npatch]**2)
moment = np.abs(np.dot(shearModulus * patchAreas, slip))
if moment>0.:
Mw = 2.0 / 3.0 * (np.log10(moment) - 9.1)
print("Magnitude is")
print(Mw)
else:
Mw = -6.0
return np.array([Mw_thresh - Mw])
# Get the matrixes and vectors