forked from simpeg/simpeg
/
Regularization.py
1910 lines (1535 loc) · 60.8 KB
/
Regularization.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
from __future__ import print_function
import numpy as np
import scipy.sparse as sp
import warnings
import properties
from . import Utils
from . import Maps
from . import Mesh
from . import ObjectiveFunction
from . import Props
__all__ = [
'SimpleSmall', 'SimpleSmoothDeriv', 'Simple',
'Small', 'SmoothDeriv', 'SmoothDeriv2', 'Tikhonov',
'SparseSmall', 'SparseDeriv', 'Sparse',
]
###############################################################################
# #
# Regularization Mesh #
# #
###############################################################################
class RegularizationMesh(Props.BaseSimPEG):
"""
**Regularization Mesh**
This contains the operators used in the regularization. Note that these
are not necessarily true differential operators, but are constructed from
a SimPEG Mesh.
:param discretize.base.BaseMesh mesh: problem mesh
:param numpy.ndarray indActive: bool array, size nC, that is True where we have active cells. Used to reduce the operators so we regularize only on active cells
"""
regularization_type = None # or 'Simple', 'Sparse' or 'Tikhonov'
def __init__(self, mesh, **kwargs):
self.mesh = mesh
Utils.setKwargs(self, **kwargs)
indActive = properties.Array("active indices in mesh", dtype=[bool, int])
@properties.validator('indActive')
def _cast_to_bool(self, change):
value = change['value']
if value is not None:
if value.dtype != 'bool': # cast it to a bool otherwise
tmp = value
value = np.zeros(self.mesh.nC, dtype=bool)
value[tmp] = True
change['value'] = value
@property
def vol(self):
"""
reduced volume vector
:rtype: numpy.ndarray
:return: reduced cell volume
"""
if getattr(self, '_vol', None) is None:
self._vol = self.Pac.T * self.mesh.vol
return self._vol
@property
def nC(self):
"""
reduced number of cells
:rtype: int
:return: number of cells being regularized
"""
if self.indActive is not None:
return int(self.indActive.sum())
return self.mesh.nC
@property
def dim(self):
"""
dimension of regularization mesh (1D, 2D, 3D)
:rtype: int
:return: dimension
"""
if getattr(self, '_dim', None) is None:
self._dim = self.mesh.dim
return self._dim
@property
def Pac(self):
"""
projection matrix that takes from the reduced space of active cells to
full modelling space (ie. nC x nindActive)
:rtype: scipy.sparse.csr_matrix
:return: active cell projection matrix
"""
if getattr(self, '_Pac', None) is None:
if self.indActive is None:
self._Pac = Utils.speye(self.mesh.nC)
else:
self._Pac = Utils.speye(self.mesh.nC)[:, self.indActive]
return self._Pac
@property
def Pafx(self):
"""
projection matrix that takes from the reduced space of active x-faces
to full modelling space (ie. nFx x nindActive_Fx )
:rtype: scipy.sparse.csr_matrix
:return: active face-x projection matrix
"""
if getattr(self, '_Pafx', None) is None:
if self.indActive is None:
self._Pafx = Utils.speye(self.mesh.nFx)
else:
# if getattr(self.mesh, 'aveCC2Fx', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
indActive_Fx = (
(self.mesh.aveFx2CC.T * self.indActive) >= 1
)
self._Pafx = (
Utils.speye(self.mesh.nFx)[:, indActive_Fx]
)
else:
indActive_Fx = (
(
self.mesh._aveCC2FxStencil() *
self.indActive
) >= 1
)
self._Pafx = (
Utils.speye(self.mesh.ntFx)[:, indActive_Fx]
)
else:
indActive_Fx = self.mesh.aveFx2CC.T * self.indActive >= 1
self._Pafx = Utils.speye(self.mesh.nFx)[:, indActive_Fx]
return self._Pafx
@property
def Pafy(self):
"""
projection matrix that takes from the reduced space of active y-faces
to full modelling space (ie. nFy x nindActive_Fy )
:rtype: scipy.sparse.csr_matrix
:return: active face-y projection matrix
"""
if getattr(self, '_Pafy', None) is None:
if self.indActive is None:
self._Pafy = Utils.speye(self.mesh.nFy)
else:
# if getattr(self.mesh, 'aveCC2Fy', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
indActive_Fy = (
(self.mesh.aveFy2CC.T * self.indActive) >= 1
)
self._Pafy = (
Utils.speye(self.mesh.nFy)[:, indActive_Fy]
)
else:
indActive_Fy = (
(
self.mesh._aveCC2FyStencil() *
self.indActive
) >= 1
)
self._Pafy = (
Utils.speye(self.mesh.ntFy)[:, indActive_Fy]
)
else:
indActive_Fy = (self.mesh.aveFy2CC.T * self.indActive) >= 1
self._Pafy = Utils.speye(self.mesh.nFy)[:, indActive_Fy]
return self._Pafy
@property
def Pafz(self):
"""
projection matrix that takes from the reduced space of active z-faces
to full modelling space (ie. nFz x nindActive_Fz )
:rtype: scipy.sparse.csr_matrix
:return: active face-z projection matrix
"""
if getattr(self, '_Pafz', None) is None:
if self.indActive is None:
self._Pafz = Utils.speye(self.mesh.nFz)
else:
# if getattr(self.mesh, 'aveCC2Fz', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
indActive_Fz = (
(self.mesh.aveFz2CC.T * self.indActive) >= 1
)
self._Pafz = (
Utils.speye(self.mesh.nFz)[:, indActive_Fz]
)
else:
indActive_Fz = (
(
self.mesh._aveCC2FzStencil() *
self.indActive
) >= 1
)
self._Pafz = (
Utils.speye(self.mesh.ntFz)[:, indActive_Fz]
)
else:
indActive_Fz = (self.mesh.aveFz2CC.T * self.indActive) >= 1
self._Pafz = Utils.speye(self.mesh.nFz)[:, indActive_Fz]
return self._Pafz
@property
def aveFx2CC(self):
"""
averaging from active cell centers to active x-faces
:rtype: scipy.sparse.csr_matrix
:return: averaging from active cell centers to active x-faces
"""
if getattr(self, '_aveFx2CC', None) is None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveFx2CC = (
self.Pac.T * self.mesh.aveFx2CC * self.Pafx
)
else:
nCinRow = mkvc((self.aveCC2Fx.T).sum(1))
nCinRow[nCinRow > 0] = 1./nCinRow[nCinRow > 0]
self._aveFx2CC = (
Utils.sdiag(nCinRow) *
self.aveCC2Fx.T
)
else:
self._aveFx2CC = self.Pac.T * self.mesh.aveFx2CC * self.Pafx
return self._aveFx2CC
@property
def aveCC2Fx(self):
"""
averaging from active x-faces to active cell centers
:rtype: scipy.sparse.csr_matrix
:return: averaging matrix from active x-faces to active cell centers
"""
if getattr(self, '_aveCC2Fx', None) is None:
# if getattr(self.mesh, 'aveCC2Fx', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveCC2Fx = (
Utils.sdiag(1./(self.aveFx2CC.T).sum(1)) *
self.aveFx2CC.T
)
else:
self._aveCC2Fx = (
self.Pafx.T * self.mesh._aveCC2FxStencil() * self.Pac
)
else:
self._aveCC2Fx = (
Utils.sdiag(1./(self.aveFx2CC.T).sum(1)) * self.aveFx2CC.T
)
return self._aveCC2Fx
@property
def aveFy2CC(self):
"""
averaging from active cell centers to active y-faces
:rtype: scipy.sparse.csr_matrix
:return: averaging from active cell centers to active y-faces
"""
if getattr(self, '_aveFy2CC', None) is None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveFy2CC = (
self.Pac.T * self.mesh.aveFy2CC * self.Pafy
)
else:
nCinRow = mkvc((self.aveCC2Fy.T).sum(1))
nCinRow[nCinRow > 0] = 1./nCinRow[nCinRow > 0]
self._aveFy2CC = (
Utils.sdiag(nCinRow) *
self.aveCC2Fy.T
)
else:
self._aveFy2CC = self.Pac.T * self.mesh.aveFy2CC * self.Pafy
return self._aveFy2CC
@property
def aveCC2Fy(self):
"""
averaging from active y-faces to active cell centers
:rtype: scipy.sparse.csr_matrix
:return: averaging matrix from active y-faces to active cell centers
"""
if getattr(self, '_aveCC2Fy', None) is None:
# if getattr(self.mesh, 'aveCC2Fy', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveCC2Fy = (
Utils.sdiag(1./(self.aveFy2CC.T).sum(1)) *
self.aveFy2CC.T
)
else:
self._aveCC2Fy = (
self.Pafy.T * self.mesh._aveCC2FyStencil() * self.Pac
)
else:
self._aveCC2Fy = (
Utils.sdiag(1./(self.aveFy2CC.T).sum(1)) * self.aveFy2CC.T
)
return self._aveCC2Fy
@property
def aveFz2CC(self):
"""
averaging from active cell centers to active z-faces
:rtype: scipy.sparse.csr_matrix
:return: averaging from active cell centers to active z-faces
"""
if getattr(self, '_aveFz2CC', None) is None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveFz2CC = (
self.Pac.T * self.mesh.aveFz2CC * self.Pafz
)
else:
nCinRow = mkvc((self.aveCC2Fz.T).sum(1))
nCinRow[nCinRow > 0] = 1./nCinRow[nCinRow > 0]
self._aveFz2CC = (
Utils.sdiag(nCinRow) *
self.aveCC2Fz.T
)
else:
self._aveFz2CC = self.Pac.T * self.mesh.aveFz2CC * self.Pafz
return self._aveFz2CC
@property
def aveCC2Fz(self):
"""
averaging from active z-faces to active cell centers
:rtype: scipy.sparse.csr_matrix
:return: averaging matrix from active z-faces to active cell centers
"""
if getattr(self, '_aveCC2Fz', None) is None:
# if getattr(self.mesh, 'aveCC2Fz', None) is not None:
if self.mesh._meshType == "TREE":
if self.regularization_type == "Tikhonov":
self._aveCC2Fz = (
Utils.sdiag(1./(self.aveFz2CC.T).sum(1)) *
self.aveFz2CC.T
)
else:
self._aveCC2Fz = (
self.Pafz.T * self.mesh._aveCC2FzStencil() * self.Pac
)
else:
self._aveCC2Fz = (
Utils.sdiag(1./(self.aveFz2CC.T).sum(1)) * self.aveFz2CC.T
)
return self._aveCC2Fz
@property
def cellDiffx(self):
"""
cell centered difference in the x-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the x-direction
"""
if getattr(self, '_cellDiffx', None) is None:
self._cellDiffx = self.Pafx.T * self.mesh.cellGradx * self.Pac
return self._cellDiffx
@property
def cellDiffy(self):
"""
cell centered difference in the y-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the y-direction
"""
if getattr(self, '_cellDiffy', None) is None:
self._cellDiffy = self.Pafy.T * self.mesh.cellGrady * self.Pac
return self._cellDiffy
@property
def cellDiffz(self):
"""
cell centered difference in the z-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the z-direction
"""
if getattr(self, '_cellDiffz', None) is None:
self._cellDiffz = self.Pafz.T * self.mesh.cellGradz * self.Pac
return self._cellDiffz
@property
def faceDiffx(self):
"""
x-face differences
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active faces in the x-direction
"""
if getattr(self, '_faceDiffx', None) is None:
self._faceDiffx = self.Pac.T * self.mesh.faceDivx * self.Pafx
return self._faceDiffx
@property
def faceDiffy(self):
"""
y-face differences
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active faces in the y-direction
"""
if getattr(self, '_faceDiffy', None) is None:
self._faceDiffy = self.Pac.T * self.mesh.faceDivy * self.Pafy
return self._faceDiffy
@property
def faceDiffz(self):
"""
z-face differences
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active faces in the z-direction
"""
if getattr(self, '_faceDiffz', None) is None:
self._faceDiffz = self.Pac.T * self.mesh.faceDivz * self.Pafz
return self._faceDiffz
@property
def cellDiffxStencil(self):
"""
cell centered difference stencil (no cell lengths include) in the
x-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the x-direction
"""
if getattr(self, '_cellDiffxStencil', None) is None:
self._cellDiffxStencil = (
self.Pafx.T * self.mesh._cellGradxStencil * self.Pac
)
return self._cellDiffxStencil
@property
def cellDiffyStencil(self):
"""
cell centered difference stencil (no cell lengths include) in the
y-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the y-direction
"""
if self.dim < 2:
return None
if getattr(self, '_cellDiffyStencil', None) is None:
self._cellDiffyStencil = (
self.Pafy.T * self.mesh._cellGradyStencil * self.Pac
)
return self._cellDiffyStencil
@property
def cellDiffzStencil(self):
"""
cell centered difference stencil (no cell lengths include) in the
y-direction
:rtype: scipy.sparse.csr_matrix
:return: differencing matrix for active cells in the y-direction
"""
if self.dim < 3:
return None
if getattr(self, '_cellDiffzStencil', None) is None:
self._cellDiffzStencil = (
self.Pafz.T * self.mesh._cellGradzStencil * self.Pac
)
return self._cellDiffzStencil
###############################################################################
# #
# Base Regularization #
# #
###############################################################################
class BaseRegularization(ObjectiveFunction.BaseObjectiveFunction):
"""
Base class for regularization. Inherit this for building your own
regularization. The base regularization assumes a weighted l2 style of
regularization. However, if you wish to employ a different norm, the
methods :meth:`__call__`, :meth:`deriv` and :meth:`deriv2` can be
over-written
:param discretize.base.BaseMesh mesh: SimPEG mesh
"""
def __init__(self, mesh=None, **kwargs):
super(BaseRegularization, self).__init__()
self.regmesh = RegularizationMesh(mesh)
if "indActive" in kwargs.keys():
indActive = kwargs.pop("indActive")
self.regmesh.indActive = indActive
Utils.setKwargs(self, **kwargs)
counter = None
# Properties
mref = Props.Array(
"reference model"
)
indActive = properties.Array(
"indices of active cells in the mesh", dtype=(bool, int)
)
cell_weights = properties.Array(
"regularization weights applied at cell centers", dtype=float
)
regmesh = properties.Instance(
"regularization mesh", RegularizationMesh, required=True
)
mapping = properties.Instance(
"mapping which is applied to model in the regularization",
Maps.IdentityMap, default=Maps.IdentityMap()
)
# Observers and Validators
@properties.validator('indActive')
def _cast_to_bool(self, change):
value = change['value']
if value is not None:
if value.dtype != 'bool': # cast it to a bool otherwise
tmp = value
value = np.zeros(self.regmesh.nC, dtype=bool)
value[tmp] = True
change['value'] = value
# update regmesh indActive
if getattr(self, 'regmesh', None) is not None:
self.regmesh.indActive = Utils.mkvc(value)
@properties.observer('indActive')
def _update_regmesh_indActive(self, change):
# update regmesh indActive
if getattr(self, 'regmesh', None) is not None:
self.regmesh.indActive = change['value']
@properties.validator('cell_weights')
def _validate_cell_weights(self, change):
if change['value'] is not None:
# todo: residual size? we need to know the expected end shape
if self._nC_residual != '*':
assert len(change['value']) == self._nC_residual, (
'cell_weights must be length {} not {}'.format(
self._nC_residual, len(change['value'])
)
)
# Other properties and methods
@property
def nP(self):
"""
number of model parameters
"""
if getattr(self.mapping, 'nP') != '*':
return self.mapping.nP
elif getattr(self.regmesh, 'nC') != '*':
return self.regmesh.nC
else:
return '*'
@property
def _nC_residual(self):
"""
Shape of the residual
"""
nC = getattr(self.regmesh, 'nC', None)
mapping = getattr(self, 'mapping', None)
if nC != '*' and nC is not None:
return self.regmesh.nC
elif mapping is not None and mapping.shape[0] != '*':
return self.mapping.shape[0]
else:
return self.nP
def _delta_m(self, m):
if self.mref is None:
return m
return (-self.mref + m) # in case self.mref is Zero, returns type m
@Utils.timeIt
def __call__(self, m):
"""
We use a weighted 2-norm objective function
.. math::
r(m) = \\frac{1}{2}
"""
r = self.W * (self.mapping * (self._delta_m(m)))
return 0.5 * r.dot(r)
@Utils.timeIt
def deriv(self, m):
"""
The regularization is:
.. math::
R(m) = \\frac{1}{2}\mathbf{(m-m_\\text{ref})^\\top W^\\top
W(m-m_\\text{ref})}
So the derivative is straight forward:
.. math::
R(m) = \mathbf{W^\\top W (m-m_\\text{ref})}
"""
mD = self.mapping.deriv(self._delta_m(m))
r = self.W * (self.mapping * (self._delta_m(m)))
return mD.T * (self.W.T * r)
@Utils.timeIt
def deriv2(self, m, v=None):
"""
Second derivative
:param numpy.ndarray m: geophysical model
:param numpy.ndarray v: vector to multiply
:rtype: scipy.sparse.csr_matrix
:return: WtW, or if v is supplied WtW*v (numpy.ndarray)
The regularization is:
.. math::
R(m) = \\frac{1}{2}\mathbf{(m-m_\\text{ref})^\\top W^\\top
W(m-m_\\text{ref})}
So the second derivative is straight forward:
.. math::
R(m) = \mathbf{W^\\top W}
"""
mD = self.mapping.deriv(self._delta_m(m))
if v is None:
return mD.T * self.W.T * self.W * mD
return mD.T * (self.W.T * (self.W * (mD * v)))
###############################################################################
# #
# Base Combo Regularization #
# #
###############################################################################
class BaseComboRegularization(ObjectiveFunction.ComboObjectiveFunction):
def __init__(
self, mesh, objfcts=[], **kwargs
):
super(BaseComboRegularization, self).__init__(
objfcts=objfcts, multipliers=None
)
self.regmesh = RegularizationMesh(mesh)
if "indActive" in kwargs.keys():
indActive = kwargs.pop("indActive")
self.regmesh.indActive = indActive
Utils.setKwargs(self, **kwargs)
# link these attributes
linkattrs = [
'regmesh', 'indActive', 'cell_weights', 'mapping'
]
for attr in linkattrs:
val = getattr(self, attr)
if val is not None:
[setattr(fct, attr, val) for fct in self.objfcts]
# Properties
alpha_s = Props.Float("smallness weight")
alpha_x = Props.Float("weight for the first x-derivative")
alpha_y = Props.Float("weight for the first y-derivative")
alpha_z = Props.Float("weight for the first z-derivative")
alpha_xx = Props.Float("weight for the second x-derivative")
alpha_yy = Props.Float("weight for the second y-derivative")
alpha_zz = Props.Float("weight for the second z-derivative")
counter = None
mref = Props.Array(
"reference model"
)
mrefInSmooth = properties.Bool(
"include mref in the smoothness calculation?", default=False
)
indActive = properties.Array(
"indices of active cells in the mesh", dtype=(bool, int)
)
cell_weights = properties.Array(
"regularization weights applied at cell centers", dtype=float
)
scale = properties.Float(
"function scaling applied inside the norm", default=1.
)
regmesh = properties.Instance(
"regularization mesh", RegularizationMesh, required=True
)
mapping = properties.Instance(
"mapping which is applied to model in the regularization",
Maps.IdentityMap, default=Maps.IdentityMap()
)
# Other properties and methods
@property
def nP(self):
"""
number of model parameters
"""
if getattr(self.mapping, 'nP') != '*':
return self.mapping.nP
elif getattr(self.regmesh, 'nC') != '*':
return self.regmesh.nC
else:
return '*'
@property
def _nC_residual(self):
"""
Shape of the residual
"""
nC = getattr(self.regmesh, 'nC', None)
mapping = getattr(self, 'mapping', None)
if nC != '*' and nC is not None:
return self.regmesh.nC
elif mapping is not None and mapping.shape[0] != '*':
return self.mapping.shape[0]
else:
return self.nP
def _delta_m(self, m):
if self.mref is None:
return m
return (-self.mref + m) # in case self.mref is Zero, returns type m
@property
def multipliers(self):
"""
Factors that multiply the objective functions that are summed together
to build to composite regularization
"""
return [
getattr(
self, '{alpha}'.format(alpha=objfct._multiplier_pair)
) for objfct in self.objfcts
]
# Observers and Validators
@properties.validator('indActive')
def _cast_to_bool(self, change):
value = change['value']
if value is not None:
if value.dtype != 'bool': # cast it to a bool otherwise
tmp = value
value = np.zeros(self.regmesh.nC, dtype=bool)
value[tmp] = True
change['value'] = value
# update regmesh indActive
if getattr(self, 'regmesh', None) is not None:
self.regmesh.indActive = Utils.mkvc(value)
@properties.observer('indActive')
def _update_regmesh_indActive(self, change):
# update regmesh indActive
if getattr(self, 'regmesh', None) is not None:
self.regmesh.indActive = change['value']
@properties.validator('cell_weights')
def _validate_cell_weights(self, change):
if change['value'] is not None:
# todo: residual size? we need to know the expected end shape
if self._nC_residual != '*':
assert len(change['value']) == self._nC_residual, (
'cell_weights must be length {} not {}'.format(
self._nC_residual, len(change['value'])
)
)
@properties.observer('mref')
def _mirror_mref_to_objfctlist(self, change):
for fct in self.objfcts:
if getattr(fct, 'mrefInSmooth', None) is not None:
if self.mrefInSmooth is False:
fct.mref = Utils.Zero()
else:
fct.mref = change['value']
else:
fct.mref = change['value']
@properties.observer('mrefInSmooth')
def _mirror_mrefInSmooth_to_objfctlist(self, change):
for fct in self.objfcts:
if getattr(fct, 'mrefInSmooth', None) is not None:
fct.mrefInSmooth = change['value']
@properties.observer('indActive')
def _mirror_indActive_to_objfctlist(self, change):
value = change['value']
if value is not None:
if value.dtype != 'bool':
tmp = value
value = np.zeros(self.mesh.nC, dtype=bool)
value[tmp] = True
change['value'] = value
if getattr(self, 'regmesh', None) is not None:
self.regmesh.indActive = value
for fct in self.objfcts:
fct.indActive = value
@properties.observer('cell_weights')
def _mirror_cell_weights_to_objfctlist(self, change):
for fct in self.objfcts:
fct.cell_weights = change['value']
@properties.observer('mapping')
def _mirror_mapping_to_objfctlist(self, change):
for fct in self.objfcts:
fct.mapping = change['value']
###############################################################################
# #
# Simple Regularization (no volume contribution) #
# #
###############################################################################
class SimpleSmall(BaseRegularization):
"""
Simple Small regularization - L2 regularization on the difference between a
model and a reference model. Cell weights may be included. This does not
include a volume contribution.
.. math::
r(m) = \\frac{1}{2}(\\mathbf{m} - \\mathbf{m_ref})^\top \\mathbf{W}^T
\\mathbf{W} (\\mathbf{m} - \\mathbf{m_{ref}})
where :math:`\\mathbf{m}` is the model, :math:`\\mathbf{m_{ref}}` is a
reference model and :math:`\\mathbf{W}` is a weighting
matrix (default Identity). If cell weights are provided, then it is
:code:`diag(np.sqrt(cell_weights))`)
**Optional Inputs**
:param discretize.base.BaseMesh mesh: SimPEG mesh
:param int nP: number of parameters
:param IdentityMap mapping: regularization mapping, takes the model from model space to the space you want to regularize in
:param numpy.ndarray mref: reference model
:param numpy.ndarray indActive: active cell indices for reducing the size of differential operators in the definition of a regularization mesh
:param numpy.ndarray cell_weights: cell weights
"""
_multiplier_pair = 'alpha_s'
def __init__(self, mesh=None, **kwargs):
super(SimpleSmall, self).__init__(
mesh=mesh, **kwargs
)
@property
def W(self):
"""
Weighting matrix
"""
if self.cell_weights is not None:
return Utils.sdiag(np.sqrt(self.cell_weights))
elif self._nC_residual != '*':
return sp.eye(self._nC_residual)
else:
return Utils.Identity()
class SimpleSmoothDeriv(BaseRegularization):
"""
Base Simple Smooth Regularization. This base class regularizes on the first
spatial derivative, not considering length scales, in the provided
orientation
**Optional Inputs**
:param discretize.base.BaseMesh mesh: SimPEG mesh
:param int nP: number of parameters
:param IdentityMap mapping: regularization mapping, takes the model from model space to the space you want to regularize in
:param numpy.ndarray mref: reference model
:param numpy.ndarray indActive: active cell indices for reducing the size of differential operators in the definition of a regularization mesh
:param numpy.ndarray cell_weights: cell weights
:param bool mrefInSmooth: include the reference model in the smoothness computation? (eg. look at Deriv of m (False) or Deriv of (m-mref) (True))
:param numpy.ndarray cell_weights: vector of cell weights (applied in all terms)
"""
def __init__(
self, mesh, orientation='x', **kwargs
):
self.orientation = orientation
assert self.orientation in ['x', 'y', 'z'], (
"Orientation must be 'x', 'y' or 'z'"
)
if self.orientation == 'y':
assert mesh.dim > 1, (
"Mesh must have at least 2 dimensions to regularize along the "
"y-direction"
)
elif self.orientation == 'z':
assert mesh.dim > 2, (
"Mesh must have at least 3 dimensions to regularize along the "
"z-direction"
)
super(SimpleSmoothDeriv, self).__init__(
mesh=mesh, **kwargs
)
mrefInSmooth = properties.Bool(
"include mref in the smoothness calculation?", default=False
)
@property
def _multiplier_pair(self):
return 'alpha_{orientation}'.format(orientation=self.orientation)
@property
def W(self):
"""
Weighting matrix that takes the first spatial difference (no
length scales considered) in the specified orientation
"""
W = getattr(
self.regmesh,
"cellDiff{orientation}Stencil".format(
orientation=self.orientation
)
)
if self.cell_weights is not None:
Ave = getattr(self.regmesh, 'aveCC2F{}'.format(self.orientation))
W = (
Utils.sdiag(
(Ave*self.cell_weights)**0.5
) * W
)
return W