-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmasa_utils.py
1493 lines (1324 loc) · 56.5 KB
/
masa_utils.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
import numpy as np
from scipy import optimize
from scipy.constants import mu_0, epsilon_0
from scipy import fftpack
from scipy import sparse
from scipy.special import factorial
from scipy.signal import butter, filtfilt
from scipy.interpolate import interp1d, CubicSpline,splrep, BSpline
from scipy.sparse import csr_matrix, csc_matrix
import csv
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.linalg import lu_factor, lu_solve
from scipy import signal
import empymod
import discretize
import os
eps= np.finfo(float).eps
class TikonovInversion:
def __init__(self, G_f, Wd, alphax=1.,Wx=None,
alphas=1., Ws=None, m_ref=None,Proj_m=None,m_fix=None,
sparse_matrix=False
):
self.G_f = G_f
self.Wd = Wd
self.Wx = Wx
self.Ws = Ws
self.nD = G_f.shape[0]
self.nP = G_f.shape[1]
self.alphax = alphax
self.Proj_m = Proj_m
self.m_fix = m_fix
if Proj_m is not None:
assert Proj_m.shape[0] == self.nP
self.nM = Proj_m.shape[1]
else:
self.Proj_m = np.eye(self.nP)
self.nM = self.nP
self.m_fix = np.zeros(self.nP)
self.alphas = alphas
self.m_ref=m_ref
self.sparse_matrix = sparse_matrix
def get_Wx(self):
nP = self.nP
Wx = np.zeros((nP-1, nP))
element = np.ones(nP-1)
Wx[:,:-1] = np.diag(element)
Wx[:,1:] += np.diag(-element)
self.Wx = Wx
return Wx
def get_Ws(self):
nM = self.nM
Ws = np.eye(nM)
self.Ws= Ws
return Ws
def recover_model(self, dobs, beta, sparse_matrix=False):
# This is for the mapping
G_f = self.G_f
Wd = self.Wd
alphax = self.alphax
alphas = self.alphas
Wx = self.Wx
Ws = self.Ws
m_ref= self.m_ref
Proj_m = self.Proj_m
m_fix= self.m_fix
sparse_matrix = self.sparse_matrix
left = Proj_m.T @G_f.T @ Wd.T @ Wd @ G_f@Proj_m
left += beta * alphax * (Proj_m.T @Wx.T @ Wx@Proj_m)
if m_ref is not None:
left += beta * alphas * (Ws.T @ Ws)
if sparse_matrix:
left = csr_matrix(left)
right = G_f.T @ Wd.T @Wd@ dobs@Proj_m
right += -m_fix.T@[email protected]@Wd@G_f@Proj_m
right+= -beta*alphax* [email protected]@Wx@Proj_m
if m_ref is not None:
right+= beta*alphas*[email protected]@Ws
m_rec = np.linalg.solve(left, right)
#filt_curr = spsolve(left, right)
rd = Wd@(G_f@Proj_m@m_rec-dobs)
rmx = alphax*Wx@Proj_m@m_rec
if m_ref is not None:
rms = alphas*Ws@(m_rec-m_ref)
phid = 0.5 * np.dot(rd, rd)
phim = 0.5 * np.dot(rmx,rmx)
if m_ref is not None:
phim+=0.5 * np.dot(rms,rms)
p_rec = m_fix + Proj_m@m_rec
return p_rec, phid, phim
def tikonov_inversion(self,beta_values, dobs):
n_beta = len(beta_values)
nP= self.nP
mrec_tik = np.zeros(nP, n_beta) # np.nan * np.ones(shape)
phid_tik = np.zeros(n_beta)
phim_tik = np.zeros(n_beta)
for i, beta in enumerate(beta_values):
mrec_tik[:, i], phid_tik[i], phim_tik[i] = self.recover_model(
dobs=dobs, beta=beta)
return mrec_tik, phid_tik, phim_tik
def estimate_beta_range(self, num=20, eig_tol=1e-12):
G_f = self.G_f
alphax=self.alphax
alphas=self.alphas
Wd = self.Wd
Wx = self.Wx
Ws= self.Ws
Proj_m = self.Proj_m # Use `Proj_m` to map the model space
# Effective data misfit term with projection matrix
A_data = Proj_m.T @ G_f.T @ Wd.T @ Wd @ G_f @ Proj_m
eig_data = np.linalg.eigvalsh(A_data)
# Effective regularization term with projection matrix
A_reg = alphax* Proj_m.T @ Wx.T @ Wx @ Proj_m
if Ws is not None:
A_reg += alphas * (Ws.T @ Ws)
eig_reg = np.linalg.eigvalsh(A_reg)
# Ensure numerical stability (avoid dividing by zero)
eig_data = eig_data[eig_data > eig_tol]
eig_reg = eig_reg[eig_reg > eig_tol]
# Use the ratio of eigenvalues to set beta range
beta_min = np.min(eig_data) / np.max(eig_reg)
beta_max = np.max(eig_data) / np.min(eig_reg)
# Generate 20 logarithmically spaced beta values
beta_values = np.logspace(np.log10(beta_min), np.log10(beta_max), num=num)
return beta_values
class projection_convex_set:
def __init__(self,maxiter=100, tol=1e-2,
lower_bound=None, upper_bound=None, a=None, b=None):
self.maxiter = maxiter
self.tol = tol
self.lower_bound = lower_bound
self.upper_bound = upper_bound
self.a = a
self.b = b
def get_param(self, param, default):
return param if param is not None else default
def projection_halfspace(self, a, x, b):
a = self.get_param(a, self.a)
b = self.get_param(b, self.b)
projected_x = x + a * ((b - np.dot(a, x)) / np.dot(a, a)) if np.dot(a, x) > b else x
# Ensure scalar output if input x is scalar
if np.isscalar(x):
return float(projected_x)
return projected_x
def projection_plane(self, a, x, b):
a = self.get_param(a, self.a)
b = self.get_param(b, self.b)
projected_x = x + a * ((b - np.dot(a, x)) / np.dot(a, a))
# Ensure scalar output if input x is scalar
if np.isscalar(x):
return float(projected_x)
return projected_x
def clip_model(self, x, lower_bound=None, upper_bound=None):
lower_bound = self.get_param(lower_bound, self.lower_bound)
upper_bound = self.get_param(upper_bound, self.upper_bound)
clipped_x = np.clip(x, self.lower_bound, self.upper_bound)
return clipped_x
def proj_c(self,x, maxiter=100, tol=1e-2):
"Project model vector to convex set defined by bound information"
x_c_0 = x.copy()
x_c_1 = np.zerps_like(x)
maxiter = self.get_param(maxiter, self.maxiter)
tol = self.tol
lower_bound = self.lower_bound
upper_bound = self.upper_bound
a = self.a
b = self.b
for i in range(maxiter):
x_c_1 = self.clip_model(x=x_c_0,lower_bound=lower_bound, upper_bound=upper_bound)
x_c_1 = self.projection_plane(a=a, x=x_c_1, b=b)
if np.linalg.norm(x_c_1 - x_c_0) < tol:
break
x_c_0 = x_c_1
return x_c_1
class empymod_IPinv:
def __init__(self, model_base, nlayer,
m_ref=None, nD=0, nlayer_fix=0, Prj_m=None, m_fix=None,
resmin=1e-3 , resmax=1e6, chgmin=1e-3, chgmax=0.9,
taumin=1e-6, taumax=1e-1, cmin= 0.4, cmax=0.9,
Wd = None, Ws=None, Wx=None, alphax=None, alphas=None,
cut_off=None,filt_curr = None, window_mat = None
):
self.model_base = model_base
self.nlayer = int(nlayer)
self.nlayer_fix = int(nlayer_fix)
self.nP = 4*(nlayer + nlayer_fix)
self.m_ref = m_ref
self.Prj_m = Prj_m
self.m_fix = m_fix
if Prj_m is not None:
assert Prj_m.shape[0] == self.nP
self.nM = Prj_m.shape[1]
else:
self.Proj_m = np.eye(self.nP)
self.nM = self.nP
self.m_fix = np.zeros(self.nP)
self.nD = nD
self.resmin = resmin
self.resmax = resmax
self.chgmin = chgmin
self.chgmax = chgmax
self.taumin = taumin
self.taumax = taumax
self.cmin = cmin
self.cmax = cmax
self.Wd = Wd
self.Ws = Ws
self.Wx = Wx
self.alphax = alphax
self.alphas = alphas
self.cut_off = cut_off
self.filt_curr = filt_curr
self.window_mat = window_mat
def get_param(self, param, default):
return param if param is not None else default
def fix_sea_basement(self, res_sea, res_base,
chg_sea, chg_base, tau_sea, tau_base, c_sea, c_base):
## return and set mapping for fixigin sea and basement resistivity
## Assert there are no fix ing at this stage
nlayer = self.nlayer
nlayer_fix=2
nlayer_sum = nlayer+nlayer_fix
Prj_m_A = np.block([
[np.zeros(nlayer)], # sea water
[np.eye(nlayer)], # layers
[np.zeros(nlayer)], # basement
])
Prj_m=np.block([
[Prj_m_A, np.zeros((nlayer_sum, 3*nlayer))], # Resistivity
[np.zeros((nlayer_sum, nlayer)), Prj_m_A, np.zeros((nlayer_sum, 2*nlayer))], # Chargeability
[np.zeros((nlayer_sum,2*nlayer)), Prj_m_A, np.zeros((nlayer_sum, nlayer))], # Time constant
[np.zeros((nlayer_sum,3*nlayer)), Prj_m_A], # Exponent C
])
m_fix = np.r_[
np.log(res_sea), np.zeros(nlayer), np.log(res_base), # Resistivity
chg_sea, np.zeros(nlayer), chg_base, # Chargeability
np.log(tau_sea),np.zeros(nlayer), np.log(tau_base), # Time constant
c_sea,np.zeros(nlayer),c_base # Exponent C
]
assert len(m_fix) == 4*nlayer_sum
self.nlayer_fix = nlayer_fix
self.Prj_m = Prj_m
self.m_fix = m_fix
self.nP= Prj_m.shape[0]
self.nM= Prj_m.shape[1]
assert self.nP == 4*(nlayer+nlayer_fix)
assert self.nM == 4*nlayer
return Prj_m, m_fix
def fix_sea(self, res_sea, chg_sea, tau_sea, c_sea):
## return and set mapping for fixigin sea and basement resistivity
## Assert there are no fix ing at this stage
nlayer = self.nlayer
nlayer_fix=1
nlayer_sum = nlayer+nlayer_fix
Prj_m_A = np.block([
[np.zeros(nlayer)], # sea water
[np.eye(nlayer)], # layers
])
Prj_m=np.block([
[Prj_m_A, np.zeros((nlayer_sum, 3*nlayer))], # Resistivity
[np.zeros((nlayer_sum, nlayer)), Prj_m_A, np.zeros((nlayer_sum, 2*nlayer))], # Chargeability
[np.zeros((nlayer_sum,2*nlayer)), Prj_m_A, np.zeros((nlayer_sum, nlayer))], # Time constant
[np.zeros((nlayer_sum,3*nlayer)), Prj_m_A], # Exponent C
])
m_fix = np.r_[
np.log(res_sea), np.zeros(nlayer), # Resistivity
chg_sea, np.zeros(nlayer), # Chargeability
np.log(tau_sea),np.zeros(nlayer), # Time constant
c_sea,np.zeros(nlayer)# Exponent C
]
assert len(m_fix) == 4*nlayer_sum
self.nlayer_fix = nlayer_fix
self.Prj_m = Prj_m
self.m_fix = m_fix
self.nP= Prj_m.shape[0]
self.nM= Prj_m.shape[1]
assert self.nP == 4*(nlayer+nlayer_fix)
assert self.nM == 4*nlayer
return Prj_m, m_fix
def pelton_et_al(self, inp, p_dict):
""" Pelton et al. (1978)."""
# Compute complex resistivity from Pelton et al.
iotc = np.outer(2j * np.pi * p_dict['freq'], inp['tau']) ** inp['c']
rhoH = inp['rho_0'] * (1 - inp['m'] * (1 - 1 / (1 + iotc)))
rhoV = rhoH * p_dict['aniso'] ** 2
# Add electric permittivity contribution
etaH = 1 / rhoH + 1j * p_dict['etaH'].imag
etaV = 1 / rhoV + 1j * p_dict['etaV'].imag
return etaH, etaV
def get_ip_model(self, mvec):
Prj_m = self.Prj_m
m_fix = self.m_fix
nlayer= self.nlayer
nlayer_fix = self.nlayer_fix
nlayer_sum = nlayer + nlayer_fix
param = Prj_m @ mvec + m_fix
res = np.exp(param[ : nlayer_sum])
m = param[ nlayer_sum: 2*nlayer_sum]
tau = np.exp(param[2*nlayer_sum: 3*nlayer_sum])
c = param[3*nlayer_sum: 4*nlayer_sum]
pelton_model = {'res': res, 'rho_0': res, 'm': m,
'tau': tau, 'c': c, 'func_eta': self.pelton_et_al}
return pelton_model
def predicted_data(self, model_vector):
cut_off = self.cut_off
filt_curr = self.filt_curr
window_mat = self.window_mat
ip_model = self.get_ip_model(model_vector)
data = empymod.bipole(res=ip_model, **self.model_base)
if data.ndim == 3:
# Sum over transmitter and receiver dimensions (axis 1 and axis 2)
data=np.sum(data, axis=(1, 2))
elif data.ndim == 2:
# Sum over the transmitter dimension (axis 1)
data= np.sum(data, axis=1)
self.nD = len(data)
if cut_off is not None:
times = self.model_base['freqtime']
smp_freq = 1/(times[1]-times[0])
data_LPF = self.apply_lowpass_filter(
data=data,cut_off=cut_off,smp_freq=smp_freq
)
data = data_LPF
if filt_curr is not None:
data_curr = signal.convolve(data_LPF, filt_curr)[:len(data)]
data = data_curr
if window_mat is not None:
data_window = window_mat @ data_curr
self.nD = len(data_window)
data = data_window
return data
def apply_lowpass_filter(self, data, cut_off,smp_freq, order=1):
nyquist = 0.5 * smp_freq
normal_cutoff = cut_off / nyquist
b, a = butter(order, normal_cutoff, btype='low', analog=False)
y = filtfilt(b, a, data)
return y
def projection_halfspace(self, a, x, b):
projected_x = x + a * ((b - np.dot(a, x)) / np.dot(a, a)) if np.dot(a, x) > b else x
# Ensure scalar output if input x is scalar
if np.isscalar(x):
return float(projected_x)
return projected_x
def proj_c(self,mvec):
"Project model vector to convex set defined by bound information"
nlayer = self.nlayer
a = np.r_[1]
print(mvec)
for j in range(nlayer):
r_prj = mvec[j]
m_prj = mvec[j+ nlayer]
t_prj = mvec[j+ 2*nlayer]
c_prj = mvec[j+ 3*nlayer]
r_prj = float(self.projection_halfspace( a, r_prj, np.log(self.resmax)))
r_prj = float(self.projection_halfspace(-a, r_prj, -np.log(self.resmin)))
m_prj = float(self.projection_halfspace( a, m_prj, self.chgmax))
m_prj = float(self.projection_halfspace(-a, m_prj, -self.chgmin))
t_prj = float(self.projection_halfspace( a, t_prj, np.log(self.taumax)))
t_prj = float(self.projection_halfspace(-a, t_prj, -np.log(self.taumin)))
c_prj = float(self.projection_halfspace( a, c_prj, self.cmax))
c_prj = float(self.projection_halfspace(-a, c_prj, -self.cmin))
mvec[j ] = r_prj
mvec[j+ nlayer] = m_prj
mvec[j+2*nlayer] = t_prj
mvec[j+3*nlayer] = c_prj
return mvec
def clip_model(self, mvec):
mvec_tmp = mvec.copy()
nlayer = self.nlayer
mvec_tmp[ : nlayer]=np.clip(
mvec[ : nlayer], np.log(self.resmin), np.log(self.resmax)
)
mvec_tmp[ nlayer:2*nlayer]=np.clip(
mvec[ nlayer:2*nlayer], self.chgmin, self.chgmax
)
mvec_tmp[2*nlayer:3*nlayer]=np.clip(
mvec[2*nlayer:3*nlayer], np.log(self.taumin), np.log(self.taumax)
)
mvec_tmp[3*nlayer:4*nlayer]=np.clip(
mvec[3*nlayer:4*nlayer], self.cmin, self.cmax
)
return mvec_tmp
def Japprox(self, model_vector, perturbation=0.1, min_perturbation=1e-3):
delta_m = min_perturbation # np.max([perturbation*m.mean(), min_perturbation])
# delta_m = perturbation # np.max([perturbation*m.mean(), min_perturbation])
J = []
for i, entry in enumerate(model_vector):
mpos = model_vector.copy()
mpos[i] = entry + delta_m
mneg = model_vector.copy()
mneg[i] = entry - delta_m
pos = self.predicted_data(mpos)
neg = self.predicted_data(mneg)
J.append((pos - neg) / (2. * delta_m))
return np.vstack(J).T
def get_Wd(self, dobs, dp=1, ratio=0.10, plateau=0):
std = np.abs(dobs * ratio) ** dp + plateau
Wd = np.diag(1 / std)
self.Wd = Wd
return Wd
def get_Ws(self):
nlayer = self.nlayer
nx = 4*nlayer
Ws = np.diag(np.ones(nx))
self.Ws = Ws
return Ws
def get_Wx(self):
nlayer = self.nlayer
if nlayer == 1:
print("No smoothness for one layer model")
Wx = np.zeros((4,4))
self.Wx = Wx
return Wx
nx = nlayer - 1
ny = nlayer
Wx = np.zeros((4 * nx, 4 * ny))
for i in range(4):
Wx[i * nx:(i + 1) * nx, i * ny:(i + 1) * ny - 1] = -np.diag(np.ones(nx))
Wx[i * nx:(i + 1) * nx, i * ny + 1:(i + 1) * ny] += np.diag(np.ones(nx))
self.Wx = Wx
return Wx
def get_Wxx(self):
e = np.ones(self.nlayers*4)
p1 = np.ones(self.nlayers)
p1[0] = 2
p1[-1] = 0
eup = np.tile(p1, 4)
p2 = np.ones(self.nlayers)
p2[0] = 0
p2[-1] = 2
edwn = np.tile(p2, 4)
Wxx = np.diag(-2 * e) + np.diag(eup[:-1], 1) + np.diag(edwn[1:], -1)
return Wxx
def steepest_descent(self, dobs, model_init, niter):
'''
Eldad Haber, EOSC555, 2023, UBC-EOAS
'''
model_vector = model_init
r = dobs - self.predicted_data(model_vector)
f = 0.5 * np.dot(r, r)
error = np.zeros(niter + 1)
error[0] = f
model_itr = np.zeros((niter + 1, model_vector.shape[0]))
model_itr[0, :] = model_vector
print(f'Steepest Descent \n initial phid= {f:.3e} ')
for i in range(niter):
J = self.Japprox(model_vector)
r = dobs - self.predicted_data(model_vector)
dm = J.T @ r
g = np.dot(J.T, r)
Ag = J @ g
alpha = np.mean(Ag * r) / np.mean(Ag * Ag)
model_vector = self.constrain_model_vector(model_vector + alpha * dm)
r = self.predicted_data(model_vector) - dobs
f = 0.5 * np.dot(r, r)
if np.linalg.norm(dm) < 1e-12:
break
error[i + 1] = f
model_itr[i + 1, :] = model_vector
print(f' i= {i:3d}, phid= {f:.3e} ')
return model_vector, error, model_itr
def Gradient_Descent(self, dobs, mvec_init, niter, beta, alphas, alphax,
s0=1, sfac=0.5, stol=1e-6, gtol=1e-3, mu=1e-4, ELS=True, BLS=True ):
"""
Perform the Gradient Descent algorithm for optimization.
Parameters
----------
dobs : ndarray
The observed data.
mvec_init : ndarray
The initial model vector.
niter : int
The number of iterations to perform.
beta : float
The beta parameter for the algorithm.
alphas : float
The alpha_s parameter for the algorithm.
alphax : float
The alpha_x parameter for the algorithm.
s0 : float, optional
The initial step size (default is 1).
sfac : float, optional
The step size reduction factor (default is 0.5).
stol : float, optional
The step size tolerance (default is 1e-6).
gtol : float
The stopping criteria for the norm of the gradient.
mu : float, optional
The mu parameter for the algorithm (default is 1e-4).
ELS : bool, optional
Whether to use exact line search (default is True).
BLS : bool, optional
Whether to use backtracking line search (default is True).
Returns
-------
mvec_new : ndarray
The optimized model vector.
error_prg : ndarray
The progress of the error.
mvec_prg : ndarray
The progress of the model vector.
"""
Wd = self.Wd
Ws = self.Ws
Wx = self.Wx
mvec_old = mvec_init
mvec_new = None
mref = mvec_init
error_prg = np.zeros(niter + 1)
mvec_prg = np.zeros((niter + 1, mvec_init.shape[0]))
rd = Wd @ (self.predicted_data(mvec_old) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(Ws@(mvec_old - mref), Ws@(mvec_old - mref))
rmx = 0.5 * np.dot(Wx @ mvec_old, Wx @ mvec_old)
phim = alphas * rms + alphax * rmx
f_old = phid + beta * phim
k = 0
error_prg[0] = f_old
mvec_prg[0, :] = mvec_old
print(f'Gradient Descent \n Initial phid = {phid:.2e} ,phim = {phim:.2e}, error= {f_old:.2e} ')
for i in range(niter):
# Calculate J:Jacobian and g:gradient
J = self.Japprox(mvec_old)
g = J.T @ Wd.T @ rd + beta * (alphas * Ws.T @ Ws @ (mvec_old - mref)
+ alphax * Wx.T @ Wx @ mvec_old)
# Exact line search
if ELS:
t = np.dot(g,g)/np.dot(Wd@J@g,Wd@J@g)
# t = (g.T@g)/([email protected]@J@g)
else:
t = 1.
# End inversion if gradient is smaller than tolerance
g_norm = np.linalg.norm(g, ord=2)
if g_norm < gtol:
print(f"Inversion complete since norm of gradient is small as :{g_norm :.3e} ")
break
# Line search method Armijo using directional derivative
s = s0
dm = t*g
directional_derivative = np.dot(g, -dm)
mvec_new = self.proj_c(mvec_old - s * dm)
rd = Wd @ (self.predicted_data(mvec_new) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(Ws @ (mvec_new - mref), Ws @ (mvec_new - mref))
rmx = 0.5 * np.dot(Wx @ mvec_new, Wx @ mvec_new)
phim = alphas * rms + alphax * rmx
f_new = phid + beta * phim
if BLS:
while f_new >= f_old + s * mu * directional_derivative:
s *= sfac
mvec_new = self.proj_c(mvec_old - s * dm)
rd = Wd @ (self.predicted_data(mvec_new) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(Ws @ (mvec_new - mref), Ws @ (mvec_new - mref))
rmx = 0.5 * np.dot(Wx @ mvec_new, Wx @ mvec_new)
phim = alphas * rms + alphax * rmx
f_new = phid + beta * phim
if np.linalg.norm(s) < stol:
break
mvec_old = mvec_new
mvec_prg[i + 1, :] = mvec_new
f_old = f_new
error_prg[i + 1] = f_new
k = i + 1
print(f'{k:3}, s:{s:.2e}, gradient:{g_norm:.2e}, phid:{phid:.2e}, phim:{phim:.2e}, f:{f_new:.2e} ')
# filter model prog data
mvec_prg = mvec_prg[:k]
error_prg = error_prg[:k]
# Save Jacobian
self.Jacobian = J
return mvec_new, error_prg, mvec_prg
def GaussNewton_smooth(self, dobs, mvec_init, niter,beta,
s0=1, sfac=0.5, stol=1e-6, gtol=1e-3, mu=1e-4):
Wd = self.Wd
Ws = self.Ws
Wx = self.Wx
alphas = self.alphas
alphax = self.alphax
mvec_old = mvec_init
# applay initial mvec for reference mode
mref = mvec_init
# get noise part
# Initialize object function
rd = Wd @ (self.predicted_data(mvec_old) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(mvec_old - mref, mvec_old - mref)
rmx = 0.5 * np.dot(Wx @ mvec_old, Wx @ mvec_old)
phim = alphas * rms + alphax * rmx
f_old = phid + beta * phim
# Prepare array for storing error and model in progress
error_prg = np.zeros(niter + 1)
mvec_prg = np.zeros((niter + 1, mvec_init.shape[0]))
error_prg[0] = f_old
mvec_prg[0, :] = mvec_old
print(f'Gauss-Newton \n Initial phid = {phid:.2e} ,phim = {phim:.2e}, error= {f_old:.2e} ')
for i in range(niter):
# Jacobian
J = self.Japprox(mvec_old)
# gradient
g = J.T @ Wd.T @ rd + beta * (alphas * Ws.T @ Ws @ (mvec_old - mref)
+ alphax * Wx.T @ Wx @ mvec_old)
# Hessian approximation
H = J.T @ Wd.T @ Wd @ J + beta * (alphas * Ws.T @ Ws + alphax * Wx.T @ Wx)
# model step
dm = np.linalg.solve(H, g)
# End inversion if gradient is smaller than tolerance
g_norm = np.linalg.norm(g, ord=2)
if g_norm < gtol:
print(f"Inversion complete since norm of gradient is small as :{g_norm :.3e} ")
break
# update object function
s = s0
mvec_new = self.clip_model(mvec_old - s * dm)
rd = Wd @ (self.predicted_data(mvec_new) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(mvec_new - mref, mvec_new - mref)
rmx = 0.5 * np.dot(Wx @ mvec_new, Wx @ mvec_new)
phim = alphas * rms + alphax * rmx
f_new = phid + beta * phim
# Backtracking method using directional derivative Amijo
directional_derivative = np.dot(g, -dm)
while f_new >= f_old + s * mu * directional_derivative:
# backtracking
s *= sfac
# update object function
mvec_new = self.clip_model(mvec_old - s * dm)
rd = Wd @ (self.predicted_data(mvec_new) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(Ws @ (mvec_new - mref), Ws @ (mvec_new - mref))
rmx = 0.5 * np.dot(Wx @ mvec_new, Wx @ mvec_new)
phim = alphas * rms + alphax * rmx
f_new = phid + beta * phim
# Stopping criteria for backtrackinng
if s < stol:
break
# Update model
mvec_old = mvec_new
mvec_prg[i + 1, :] = mvec_new
f_old = f_new
error_prg[i + 1] = f_new
k = i + 1
print(f'{k:3}, step:{s:.2e}, gradient:{g_norm:.2e}, phid:{phid:.2e}, phim:{phim:.2e}, f:{f_new:.2e} ')
# clip progress of model and error in inversion
error_prg = error_prg[:k]
mvec_prg = mvec_prg[:k]
return mvec_new, mvec_prg
def objec_func(self,mvec,dobs,beta):
Wd = self.Wd
Ws = self.Ws
Wx = self.Wx
alphas = self.alphas
alphax = self.alphax
m_ref = self.m_ref
rd = Wd @ (self.predicted_data(mvec) - dobs)
phid = 0.5 * np.dot(rd, rd)
rms = 0.5 * np.dot(Ws @ (mvec - m_ref), Ws @ (mvec - m_ref))
rmx = 0.5 * np.dot(Wx @ mvec, Wx @ mvec)
phim = alphas * rms + alphax * rmx
f_obj = phid + beta * phim
return f_obj, phid, phim
# def plot_model(self, model, depth_min=-100,ax=None, **kwargs):
# if ax is None:
# fig, ax = plt.subplots(1, 1)
# default_kwargs = {
# "linestyle": "-",
# "color": "orange",
# "linewidth": 1.0,
# "marker": None,
# "label": "model",
# }
# default_kwargs.update(kwargs)
# depth = np.r_[depth_min+self.model_base["depth"][0], self.model_base["depth"]]
# depth_plot = np.vstack([depth, depth]).flatten(order="F")[1:]
# depth_plot = np.hstack([depth_plot, depth_plot[-1] * 1.5])
# model_plot = np.vstack([model, model]).flatten(order="F")
# ax.plot(model_plot, depth_plot,**kwargs)
# return ax
def plot_model(self, model, depth_min=-100, ax=None, **kwargs):
"""
Plot a single model (e.g., resistivity, chargeability) with depth.
"""
if ax is None:
fig, ax = plt.subplots(1, 1)
# Default plotting parameters
default_kwargs = {
"linestyle": "-",
"color": "orange",
"linewidth": 1.0,
"marker": None,
"label": "model",
}
default_kwargs.update(kwargs)
# Prepare depth and model data for plotting
depth = np.r_[depth_min + self.model_base["depth"][0], self.model_base["depth"]]
depth_plot = np.vstack([depth, depth]).flatten(order="F")[1:]
depth_plot = np.hstack([depth_plot, depth_plot[-1] * 1.5]) # Extend depth for plot
model_plot = np.vstack([model, model]).flatten(order="F")
# Plot model with depth
ax.plot(model_plot, depth_plot, **default_kwargs)
return ax
def plot_IP_par(self, mvec, ax=None, label=None, **kwargs):
"""
Plot all IP parameters (resistivity, chargeability, time constant, exponent c).
"""
if ax is None:
fig, ax = plt.subplots(2, 2, figsize=(12, 8)) # Create 2x2 grid of subplots
else:
ax = np.array(ax) # Convert ax to a NumPy array if it's not already
ax = ax.flatten() # Ensure ax is a flat array
# Convert model vector to parameters
model = self.get_ip_model(mvec)
# Plot each model parameter
self.plot_model(model["res"], ax=ax[0], label=label, **kwargs)
ax[0].set_title("Resistivity (ohm-m)")
self.plot_model(model["m"], ax=ax[1], label=label, **kwargs)
ax[1].set_title("Chargeability")
self.plot_model(model["tau"], ax=ax[2], label=label, **kwargs)
ax[2].set_title("Time Constant (s)")
self.plot_model(model["c"], ax=ax[3], label=label, **kwargs)
ax[3].set_title("Exponent c")
return ax
class InducedPolarization:
def __init__(self,
res0=None, con8=None, eta=None, tau=None, c=None,
freq=None, times=None, windows_strt=None, windows_end=None
):
if res0 is not None and con8 is not None and eta is not None:
assert np.allclose(con8 * res0 * (1 - eta), 1.)
self.con8 = con8
self.res0 = res0
self.eta = eta
if self.res0 is None and self.con8 is not None and self.eta is not None:
self.res0 = 1./ (self.con8 * (1. - self.eta))
if self.res0 is not None and self.con8 is None and self.eta is not None:
self.con8 = 1./ (self.res0 * (1. - self.eta))
self.tau = tau
self.c = c
self.freq = freq
self.times = times
self.windows_strt = windows_strt
self.windows_end = windows_end
def validate_times(self, times):
assert np.all(times >= -eps ), "All time values must be non-negative."
if len(times) > 1:
assert np.all(np.diff(times) >= 0), "Time values must be in ascending order."
def get_param(self, param, default):
return param if param is not None else default
def pelton_res_f(self, freq=None, res0=None, eta=None, tau=None, c=None):
freq = self.get_param(freq, self.freq)
res0 = self.get_param(res0, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
c = self.get_param(c, self.c)
iwtc = (1.j * 2. * np.pi * freq*tau) ** c
return res0*(1.-eta*(1.-1./(1. + iwtc)))
def pelton_con_f(self, freq=None, con8=None, eta=None, tau=None, c=None):
freq = self.get_param(freq, self.freq)
con8 = self.get_param(con8, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
c = self.get_param(c, self.c)
iwtc = (1.j * 2. * np.pi * freq*tau) ** c
return con8-con8*(eta/(1.+(1.-eta)*iwtc))
def debye_con_t(self, times=None, con8=None, eta=None, tau=None):
times = self.get_param(times, self.times)
con8 = self.get_param(con8, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
self.validate_times(times)
debye = np.zeros_like(times)
ind_0 = (times == 0)
debye[ind_0] = 1.0
debye[~ind_0] = -eta/((1.0-eta)*tau)*np.exp(-times[~ind_0]/((1.0-eta)*tau))
return con8*debye
def debye_con_t_intg(self, times=None, con8=None, eta=None, tau=None):
times = self.get_param(times, self.times)
con8 = self.get_param(con8, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
self.validate_times(times)
return con8 *(1.0 -eta*(1. -np.exp(-times/((1.0-eta)*tau))))
def debye_res_t(self, times=None, res0=None, eta=None, tau=None):
times = self.get_param(times, self.times)
res0 = self.get_param(res0, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
self.validate_times(times)
debye = np.zeros_like(times)
res8 = res0 * (1.0 - eta)
ind_0 = (times == 0)
debye[ind_0] = res8
debye[~ind_0] = (res0-res8)/tau * np.exp(-times[~ind_0] / tau)
return debye
def debye_res_t_intg(self, times=None, res0=None, eta=None, tau=None):
times = self.get_param(times, self.times)
res0 = self.get_param(res0, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
self.validate_times(times)
res8 = res0 * (1.0 - eta)
return res8 + (res8 - res0)*(np.exp(-times/tau) - 1.0)
def freq_symmetric(self,f):
symmetric = np.zeros_like(f, dtype=complex)
nstep = len(f)
half_step = nstep // 2
symmetric[:half_step] = f[:half_step]
symmetric[half_step:] = f[:half_step].conj()[::-1]
assert np.allclose(symmetric[:half_step].real, symmetric[half_step:].real[::-1])
assert np.allclose(symmetric[:half_step].imag, -symmetric[half_step:].imag[::-1])
return symmetric
def get_frequency_tau(self, tau=None, log2nfreq=16):
tau = self.get_param(tau, self.tau)
log2nfreq = int(log2nfreq)
nfreq = 2**log2nfreq
freqcen = 1 / tau
freqend = freqcen * nfreq**0.5
freqstep = freqend / nfreq
freq = np.arange(0, freqend, freqstep)
self.freq = freq
print(f'log2(len(freq)) {np.log2(len(freq))} considering tau')
return freq
def get_frequency_tau2(self, tau=None, log2min=-8, log2max=8):
tau = self.get_param(tau, self.tau)
freqcen = 1 / tau
freqend = freqcen * 2**log2max
freqstep = freqcen * 2**log2min
freq = np.arange(0, freqend, freqstep)
self.freq = freq
print(f'log2(len(freq)) {np.log2(len(freq))} considering tau')
return freq
def get_frequency_tau_times(self, tau=None, times=None,log2min=-8, log2max=8):
tau = self.get_param(tau, self.tau)
times = self.get_param(times, self.times)
self.validate_times(times)
_, windows_end = self.get_windows(times)
freqstep = 1/tau*(2**np.floor(np.min(
np.r_[log2min,np.log2(tau/windows_end[-1])]
)))
freqend = 1/tau*(2**np.ceil(np.max(
np.r_[log2max, np.log2(2*tau/min(np.diff(times)))]
)))
freq = np.arange(0,freqend,freqstep)
self.freq=freq
print(f'log2(freq) {np.log2(len(freq))} considering tau and times')
return freq
def compute_fft(self, fft_f, freqend, freqstep):
fft_f = self.freq_symmetric(fft_f)
fft_data = fftpack.ifft(fft_f).real * freqend
fft_times = np.fft.fftfreq(len(fft_data), d=freqstep)
return fft_times[fft_times > -eps], fft_data[fft_times > -eps]
def pelton_fft(self, con_form=True, con8=None, res0=None, eta=None, tau=None, c=None, freq=None):
res0 = self.get_param(res0, self.res0)
eta = self.get_param(eta, self.eta)
tau = self.get_param(tau, self.tau)
c = self.get_param(c, self.c)
freq = self.get_param(freq, self.freq)
freqstep = freq[1] - freq[0]
freqend = freq[-1] +freqstep
if con_form:
con8 = self.get_param(con8, self.con8)
fft_f = self.pelton_con_f(freq=freq,
con8=con8, eta=eta, tau=tau, c=c)
else:
res0 = self.get_param(res0, self.res0)
fft_f = self.pelton_res_f(freq=freq,
res0=res0, eta=eta, tau=tau, c=c)
fft_times, fft_data = self.compute_fft(fft_f, freqend, freqstep)
return fft_times, fft_data
def get_windows(self, times):
self.validate_times(times)
windows_strt = np.zeros_like(times)
windows_end = np.zeros_like(times)
dt = np.diff(times)
windows_strt[1:] = times[:-1] + dt / 2
windows_end[:-1] = times[1:] - dt / 2
windows_strt[0] = times[0] - dt[0] / 2
windows_end[-1] = times[-1] + dt[-1] / 2
self.windows_strt = windows_strt
self.windows_end = windows_end
return windows_strt,windows_end
def apply_windows(self, times, data, windows_strt=None, windows_end=None):
if windows_strt is None:
windows_strt = self.windows_strt
if windows_end is None:
windows_end = self.windows_end
self.validate_times(times)
# Find bin indices for start and end of each window
start_indices = np.searchsorted(times, windows_strt, side='left')
end_indices = np.searchsorted(times, windows_end, side='right')