forked from jolivetr/csi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultifaultsolve.py
1603 lines (1288 loc) · 54.1 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
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.putm = faults[0].putm
# 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 is "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 is "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 is "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(faults)
# 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, faults):
'''
Prints to screen which parameters are what...
Args:
* faults: list of faults
Returns:
* None
'''
# initialize the counters
ns = 0
ne = 0
nSlip = 0
# Store that somewhere
self.paramDescription = {}
# Loop over the faults
for fault in faults:
# Where does this fault starts
nfs = copy.deepcopy(ns)
if fault.type is "Fault" or fault.type is 'transformation':
#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'))
# 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))
ns += fault.slip.shape[0]
if 'd' in fault.slipdir:
ne += fault.slip.shape[0]
ds = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
ns += fault.slip.shape[0]
if 't' in fault.slipdir:
ne += fault.slip.shape[0]
ts = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
ns += fault.slip.shape[0]
if 'c' in fault.slipdir:
ne += fault.slip.shape[0]
cp = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
ns += fault.slip.shape[0]
# How many slip parameters
if ne>nSlip:
nSlip = ne
# conditions on orbits (the rest is orbits)
np = ne - nfs
no = fault.Gassembled.shape[1] - np
if no>0:
ne += no
op = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
ns += no
else:
op = 'None'
# print things
if self.verbose:
print('{:30s}||{:12s}||{:12s}||{:12s}||{:12s}||{:12s}'.format(fault.name, ss, ds, ts, cp, op))
# Store details
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 is "Pressure":
#Prepare the table
if self.verbose:
print('{:30s}||{:12s}||{:12s}'.format('Fault Name', 'Pressure', 'Extra Parms'))
# Initialize the values
dp = 'None'
if fault.source is "pCDM":
ne += 3
dp = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
ns += 3 #fault.slip.shape[0]
else:
ne += 1
dp = '{:12s}'.format('{:4d} - {:4d}'.format(ns,ne))
ns += 1 #fault.slip.shape[0]
# How many slip parameters
if ne>nSlip:
nSlip = ne
# conditions on orbits (the rest is orbits)
np = ne - nfs
no = fault.Gassembled.shape[1] - np
if no>0:
ne += no
op = '{:12s}'.format('{:4d} - {:4d}'.format(ns, ne))
ns += no
else:
op = 'None'
# print things
if self.verbose:
print('{:30s}||{:12s}||{:12s}'.format(fault.name, dp, op))
# Store details
self.paramDescription[fault.name] = {}
self.paramDescription[fault.name]['pressure'] = dp
self.paramDescription[fault.name]['Extra Parameters'] = op
# 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 is "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 is "Pressure":
st = 0
if fault.source in {"Mogi", "Yang"}:
se = st + 1
print(np.asscalar(fault.mpost[st:se]*fault.mu))
fault.deltapressure = np.asscalar(fault.mpost[st:se]*fault.mu)
st += 1
elif fault.source is "pCDM":
se = st + 1
fault.DVx = np.asscalar(fault.mpost[st:se]*fault.scale)
st += 1
se = st + 1
fault.DVy = np.asscalar(fault.mpost[st:se]*fault.scale)
st += 1
se = st + 1
fault.DVz = np.asscalar(fault.mpost[st:se]*fault.scale)
st += 1
print("Total potency scaled by", fault.scale)
if fault.DVtot is None:
fault.computeTotalpotency()
elif fault.source is "CDM":
se = st + 1
print(np.asscalar(fault.mpost[st:se]*fault.mu))
fault.deltaopening = np.asscalar(fault.mpost[st:se])
st += 1
# 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] is '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
print ("Computing the inverse of the data covariance")
iCd = scilin.inv(Cd)
# Construct mprior
if mprior is None:
mprior = np.zeros((Nm,))
# Compute mpost
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):
'''
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
G = self.G
d = self.d
Cd = self.Cd
Cm = self.Cm
# Get the number of model parameters
Nm = Cm.shape[0]
# Check If Cm is symmetric and positive definite
if useCm and (Cm.transpose() != Cm).all():
print("Cm is not symmetric, Return...")
return
# Get the inverse of Cm
if useCm:
print ("Computing the inverse of the model covariance")
iCm = scilin.inv(Cm)
else:
iCm = np.zeros(Cm.shape)
# 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
print ("Computing the inverse of the data covariance")
if rcond is None:
iCd = scilin.inv(Cd)
else:
iCd = np.linalg.pinv(Cd, rcond=rcond)
# Construct mprior
if mprior is None:
mprior = np.zeros((Nm,))
# Compute mpost
print ("Computing m_post")
One = scilin.inv(np.dot( np.dot(G.T, iCd), G ) + iCm )
Res = d - np.dot( G, mprior )
Two = np.dot( np.dot( G.T, iCd ), Res )
mpost = mprior + np.dot( One, Two )
Err = d - np.dot( G, mpost )
# Store m_post
self.mpost = mpost
print ("Compute cost function")
print(np.sum(Err**2))
mu = 22.5e9
Mw_thresh = 10
if self.type is "Fault":
computeMwDiff(self.mpost, Mw_thresh, self.patchAreas*1.e6, mu)
# Compute Cmpost
self.Cmpost = np.linalg.inv(G.T.dot(iCd).dot(G) + iCm)
# All done
return
def ConstrainedLeastSquareSoln(self, mprior=None, Mw_thresh=None, bounds=None,
method='SLSQP', rcond=None,
iterations=100, tolerance=None, maxfun=100000,
checkIter=False, checkNorm=False):
"""
Solves the least squares problem:
:math:`\\text{min} [ (\\textbf{d} - \\textbf{Gm})^t \\textbf{C}_d^{-1} (\\textbf{d} - \\textbf{Gm}) + \\textbf{m}^t \\textbf{C}_m^{-1} \\textbf{m}]`
Args:
* mprior : a priori model; if None, mprior = np.zeros((Nm,))
* Mw_thresh : upper bound on moment magnitude
* bounds : list of tuple bounds for every parameter
* method : solver for constrained minimization: SLSQP, COBYLA, or nnls
* rcond : Add some conditionning for all inverse matrix to compute
* iterations : Modifies the maximum number of iterations for the solver (default=100).
* tolerance : Solver's tolerance
* maxfun : maximum number of funcrtion evaluation
* checkIter : Show Stuff
* checkNorm : prints the norm
Returns:
* None
"""
assert self.ready, 'You need to assemble the GFs'
# Import things
import scipy.linalg as scilin
from scipy.optimize import minimize, nnls
# Check the provided method is valid
assert method in ['SLSQP', 'COBYLA', 'nnls', 'TNC', 'L-BFGS-B'], 'unsupported minimizing method'
if self.verbose:
# Print
print ("---------------------------------")
print ("---------------------------------")
print ("Computing the Constrained least squares solution")
# Get the matrixes and vectors
G = self.G
d = self.d
Cd = self.Cd
Cm = self.Cm
# Get the number of model parameters
Nm = Cm.shape[0]
# Check If Cm is symmetric and positive definite
if (Cm.transpose() != Cm).all():
print("Cm is not symmetric, Return...")
return
# Get the inverse of Cm
if self.verbose:
print ("Computing the inverse of the model covariance")
if rcond is None:
iCm = scilin.inv(Cm)
else:
iCm = scilin.pinv(Cm, rcond=rcond)
# 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")
if rcond is None:
iCd = scilin.inv(Cd)
else:
iCd = np.linalg.pinv(Cd, rcond=rcond)
# Construct mprior
if mprior is None:
mprior = np.zeros((Nm,))
# Define the cost function
def costFunction(m, G, d, iCd, iCm, mprior, verbose=False):
"""
Compute data + prior misfits.
"""
dataMisfit = d - np.dot(G,m)
dataLikely = np.dot(dataMisfit, np.dot(iCd, dataMisfit))
priorMisfit = m - mprior
priorLikely = np.dot(priorMisfit, np.dot(iCm, priorMisfit))
if verbose:
print(0.5 * dataLikely + 0.5 * priorLikely)
return 0.5 * dataLikely + 0.5 * priorLikely
# Define the moment magnitude inequality constraint function
def computeMwDiff(m, Mw_thresh, patchAreas, mu):
"""
Ahhhhh hard coded shear modulus.
"""
Npatch = len(self.patchAreas)
shearModulus = mu #22.5e9
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"+ Mw)
else:
Mw = -6.0
return np.array([Mw_thresh - Mw])
# Define the constraints dictionary
if Mw_thresh is not None:
# Get shear modulus values
mu = np.array(())
for fault in self.faults:
mu = np.append(mu,fault.mu)
if None in mu.tolist(): # If mu not set in one fault, fix it for all of them
mu = 22.5e9
constraints = {'type': 'ineq',
'fun': computeMwDiff,
'args': (Mw_thresh, self.patchAreas*1.e6, mu)}
else:
constraints = ()
# Call solver
if method == 'nnls':
if self.verbose:
print("Performing non-negative least squares")
# Compute cholesky decomposition of iCd and iCm
L = np.linalg.cholesky(iCd)
M = np.linalg.cholesky(iCm)
# Form augmented matrices and vectors
d_zero = d - np.dot(G, mprior)
F = np.vstack((np.dot(L.T, G), M.T))
b = np.hstack((np.dot(L.T, d_zero), np.zeros_like(mprior)))
m = nnls(F, b)[0] + mprior
else:
if self.verbose:
print("Performing constrained minimzation")
options = {'disp': checkIter, 'maxiter': iterations}
if method=='L-BFGS-B':
options['maxfun']= maxfun
res = minimize(costFunction, mprior, args=(G,d,iCd,iCm,mprior,checkNorm),
constraints=constraints, method=method, bounds=bounds,
options=options, tol=tolerance)
m = res.x
#final data + prior misfits is
self.cost = res.fun
# Store result
self.mpost = m
# All done
return
def simpleSampler(self, priors, initialSample, nSample, nBurn, plotSampler=False,
writeSamples=False, dryRun=False, adaptiveDelay=300):
'''
Uses a Metropolis algorithme to sample the posterior distribution of the model
following Bayes's rule. This is exactly what is done in AlTar, but using an
open-source library called pymc. This routine is made for simple problems with
few parameters (i.e. More than 30 params needs a very fast computer).
Args:
* priors : List of priors. Each prior is specified by a list.
- Example: priors = [ ['Name of parameter', 'Uniform', min, max], ['Name of parameter', 'Gaussian', center, sigma] ]
* initialSample : List of initialSample.
* nSample : Length of the Metropolis chain.
* nBurn : Number of samples burned.
Kwargs:
* plotSampler : Plot some usefull stuffs from the sampler (default: False).
* writeSamples : Write the samples to a binary file.
* dryRun : If True, builds the sampler, saves it, but does not run. This can be used for debugging.
* adaptiveDelay : Recompute the covariance of the proposal every adaptiveDelay steps
The result is stored in self.samples. The variable mpost is the mean of the final sample set.
Returns:
* None
'''
if self.verbose:
# Print
print ("---------------------------------")
print ("---------------------------------")
print ("Running a Metropolis algorythm to")
print ("sample the posterior PDFs of the ")
print (" model: P(m|d) = C P(m) P(d|m) ")
# Import
try:
import pymc
except:
print('This method uses pymc. Please install it')
# Get the matrixes and vectors
assert hasattr(self, 'G'), 'Need an assembled G matrix...'
G = self.G
assert hasattr(self, 'd'), 'Need an assembled data vector...'
dobs = self.d
assert hasattr(self, 'Cd'), 'Need an assembled data covariance matrix...'
Cd = self.Cd
# Assert
assert len(priors)==G.shape[1], 'Not enough informations to estimate prior information...'
assert len(priors)==len(initialSample), 'There must be as many \
initialSamples ({}) as priors ({})...'.format(len(initialSample),len(priors))
if type(initialSample) is not list:
try:
initialSample = initialSample.tolist()
except:
print('Please provide a list of initialSample')
sys.exit(1)
# Build the prior PDFs
priorFunctions = []
for prior, init in zip(priors, initialSample):
name = prior[0]
function = prior[1]
params = prior[2:]
if function is 'Gaussian':
center = params[0]
tau = params[1]
p = pymc.Gaussian(name, center, tau, value=init)
elif function is 'Uniform':
boundMin = params[0]
boundMax = params[1]
p = pymc.Uniform(name, boundMin, boundMax, value=init)
else:
print('This prior type has not been implemented yet...')