forked from simpeg/simpeg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Maps.py
3159 lines (2546 loc) · 97.2 KB
/
Maps.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 absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from six import integer_types
from six import string_types
from collections import namedtuple
import warnings
import numpy as np
from numpy.polynomial import polynomial
import scipy.sparse as sp
from scipy.sparse.linalg import LinearOperator
from scipy.interpolate import UnivariateSpline
from scipy.constants import mu_0
from scipy.spatial import cKDTree
import properties
from discretize.Tests import checkDerivative
from . import Utils
class IdentityMap(properties.HasProperties):
"""
SimPEG Map
"""
def __init__(self, mesh=None, nP=None, **kwargs):
Utils.setKwargs(self, **kwargs)
if nP is not None:
if isinstance(nP, string_types):
assert nP == '*', (
"nP must be an integer or '*', not {}".format(nP)
)
assert isinstance(nP, integer_types + (np.int64,)), (
'Number of parameters must be an integer. Not `{}`.'
.format(type(nP))
)
nP = int(nP)
elif mesh is not None:
nP = mesh.nC
else:
nP = '*'
self.mesh = mesh
self._nP = nP
@property
def nP(self):
"""
:rtype: int
:return: number of parameters that the mapping accepts
"""
if self._nP != '*':
return int(self._nP)
if self.mesh is None:
return '*'
return int(self.mesh.nC)
@property
def shape(self):
"""
The default shape is (mesh.nC, nP) if the mesh is defined.
If this is a meshless mapping (i.e. nP is defined independently)
the shape will be the the shape (nP,nP).
:rtype: tuple
:return: shape of the operator as a tuple (int,int)
"""
if self.mesh is None:
return (self.nP, self.nP)
return (self.mesh.nC, self.nP)
def _transform(self, m):
"""
Changes the model into the physical property.
.. note::
This can be called by the __mul__ property against a
:meth:numpy.ndarray.
:param numpy.array m: model
:rtype: numpy.array
:return: transformed model
"""
return m
def inverse(self, D):
"""
Changes the physical property into the model.
.. note::
The *transformInverse* may not be easy to create in general.
:param numpy.array D: physical property
:rtype: numpy.array
:return: model
"""
raise NotImplementedError('The transformInverse is not implemented.')
def deriv(self, m, v=None):
"""
The derivative of the transformation.
:param numpy.array m: model
:rtype: scipy.sparse.csr_matrix
:return: derivative of transformed model
"""
if v is not None:
return v
if isinstance(self.nP, integer_types):
return sp.identity(self.nP)
return Utils.Identity()
def test(self, m=None, num=4, **kwargs):
"""Test the derivative of the mapping.
:param numpy.array m: model
:param kwargs: key word arguments of
:meth:`discretize.Tests.checkDerivative`
:rtype: bool
:return: passed the test?
"""
print('Testing {0!s}'.format(str(self)))
if m is None:
m = abs(np.random.rand(self.nP))
if 'plotIt' not in kwargs:
kwargs['plotIt'] = False
assert isinstance(self.nP, integer_types), (
"nP must be an integer for {}"
.format(self.__class__.__name__)
)
return checkDerivative(
lambda m: [self * m, self.deriv(m)], m, num=num, **kwargs
)
def testVec(self, m=None, **kwargs):
"""Test the derivative of the mapping times a vector.
:param numpy.array m: model
:param kwargs: key word arguments of
:meth:`discretize.Tests.checkDerivative`
:rtype: bool
:return: passed the test?
"""
print('Testing {0!s}'.format(self))
if m is None:
m = abs(np.random.rand(self.nP))
if 'plotIt' not in kwargs:
kwargs['plotIt'] = False
return checkDerivative(
lambda m: [self*m, lambda x: self.deriv(m, x)], m, num=4, **kwargs
)
def _assertMatchesPair(self, pair):
assert (
isinstance(self, pair) or
isinstance(self, ComboMap) and isinstance(self.maps[0], pair)
), "Mapping object must be an instance of a {0!s} class.".format(
pair.__name__
)
def __mul__(self, val):
if isinstance(val, IdentityMap):
if (
not (self.shape[1] == '*' or val.shape[0] == '*') and
not self.shape[1] == val.shape[0]
):
raise ValueError(
'Dimension mismatch in {0!s} and {1!s}.'.format(
str(self), str(val)
)
)
return ComboMap([self, val])
elif isinstance(val, np.ndarray):
if (
not self.shape[1] == '*' and not self.shape[1] == val.shape[0]
):
raise ValueError(
'Dimension mismatch in {0!s} and np.ndarray{1!s}.'.format(
str(self), str(val.shape)
)
)
return self._transform(val)
elif isinstance(val, Utils.Zero):
return Utils.Zero()
raise Exception(
'Unrecognized data type to multiply. Try a map or a numpy.ndarray!'
'You used a {} of type {}'.format(
val, type(val)
)
)
def __str__(self):
return "{0!s}({1!s},{2!s})".format(
self.__class__.__name__,
self.shape[0],
self.shape[1]
)
def __len__(self):
return 1
class ComboMap(IdentityMap):
"""
Combination of various maps.
The ComboMap holds the information for multiplying and combining
maps. It also uses the chain rule to create the derivative.
Remember, any time that you make your own combination of mappings
be sure to test that the derivative is correct.
"""
def __init__(self, maps, **kwargs):
IdentityMap.__init__(self, None, **kwargs)
self.maps = []
for ii, m in enumerate(maps):
assert isinstance(m, IdentityMap), "Unrecognized data type, "
"inherit from an IdentityMap or ComboMap!"
if (
ii > 0 and not (self.shape[1] == '*' or m.shape[0] == '*') and
not self.shape[1] == m.shape[0]
):
prev = self.maps[-1]
raise ValueError(
'Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) '
'and map[{3!s}] ({4!s}, {5!s}).'.format(
prev.__class__.__name__,
prev.shape[0],
prev.shape[1],
m.__class__.__name__,
m.shape[0],
m.shape[1]
)
)
if isinstance(m, ComboMap):
self.maps += m.maps
elif isinstance(m, IdentityMap):
self.maps += [m]
@property
def shape(self):
return (self.maps[0].shape[0], self.maps[-1].shape[1])
@property
def nP(self):
"""Number of model properties.
The number of cells in the
last dimension of the mesh."""
return self.maps[-1].nP
def _transform(self, m):
for map_i in reversed(self.maps):
m = map_i * m
return m
def deriv(self, m, v=None):
if v is not None:
deriv = v
else:
deriv = 1
mi = m
for map_i in reversed(self.maps):
deriv = map_i.deriv(mi) * deriv
mi = map_i * mi
return deriv
def __str__(self):
return 'ComboMap[{0!s}]({1!s},{2!s})'.format(
' * '.join([m.__str__() for m in self.maps]),
self.shape[0],
self.shape[1]
)
def __len__(self):
return len(self.maps)
class Projection(IdentityMap):
"""
A map to rearrange / select parameters
:param int nP: number of model parameters
:param numpy.array index: indices to select
"""
def __init__(self, nP, index, **kwargs):
assert isinstance(index, (np.ndarray, slice, list)), (
'index must be a np.ndarray or slice, not {}'.format(type(index)))
super(Projection, self).__init__(nP=nP, **kwargs)
if isinstance(index, slice):
index = list(range(*index.indices(self.nP)))
self.index = index
self._shape = nI, nP = len(self.index), self.nP
assert (max(index) < nP), (
'maximum index must be less than {}'.format(nP))
# sparse projection matrix
self.P = sp.csr_matrix(
(np.ones(nI), (range(nI), self.index)), shape=(nI, nP)
)
def _transform(self, m):
return m[self.index]
@property
def shape(self):
"""
Shape of the matrix operation (number of indices x nP)
"""
return self._shape
def deriv(self, m, v=None):
"""
:param numpy.array m: model
:rtype: scipy.sparse.csr_matrix
:return: derivative of transformed model
"""
if v is not None:
return self.P * v
return self.P
class Wires(object):
def __init__(self, *args):
for arg in args:
assert (
isinstance(arg, tuple) and
len(arg) == 2 and
isinstance(arg[0], string_types) and
# TODO: this should be extended to a slice.
isinstance(arg[1], integer_types)
), (
"Each wire needs to be a tuple: (name, length). "
"You provided: {}".format(arg)
)
self._nP = int(np.sum([w[1] for w in args]))
start = 0
maps = []
for arg in args:
wire = Projection(self.nP, slice(start, start + arg[1]))
setattr(self, arg[0], wire)
maps += [(arg[0], wire)]
start += arg[1]
self.maps = maps
self._tuple = namedtuple('Model', [w[0] for w in args])
def __mul__(self, val):
assert isinstance(val, np.ndarray)
split = []
for n, w in self.maps:
split += [w * val]
return self._tuple(*split)
@property
def nP(self):
return self._nP
class SelfConsistentEffectiveMedium(IdentityMap, properties.HasProperties):
"""
Two phase self-consistent effective medium theory mapping for
ellipsoidal inclusions. The inversion model is the concentration
(volume fraction) of the phase 2 material.
The inversion model is :math:`\\varphi`. We solve for :math:`\sigma`
given :math:`\sigma_0`, :math:`\sigma_1` and :math:`\\varphi` . Each of
the following are implicit expressions of the effective conductivity.
They are solved using a fixed point iteration.
**Spherical Inclusions**
If the shape of the inclusions are spheres, we use
.. math::
\sum_{j=1}^N (\sigma^* - \sigma_j)R^{j} = 0
where :math:`j=[1,N]` is the each material phase, and N is the number
of phases. Currently, the implementation is only set up for 2 phase
materials, so we solve
.. math::
(1-\\varphi)(\sigma - \sigma_0)R^{(0)} + \\varphi(\sigma - \sigma_1)R^{(1)} = 0.
Where :math:`R^{(j)}` is given by
.. math::
R^{(j)} = \\left[1 + \\frac{1}{3}\\frac{\sigma_j - \sigma}{\sigma} \\right]^{-1}.
**Ellipsoids**
.. todo::
Aligned Ellipsoids have not yet been implemented, only randomly
oriented ellipsoids
If the inclusions are aligned ellipsoids, we solve
.. math::
\sum_{j=1}^N \\varphi_j (\Sigma^* - \sigma_j\mathbf{I}) \mathbf{R}^{j, *} = 0
where
.. math::
\mathbf{R}^{(j, *)} = \left[ \mathbf{I} + \mathbf{A}_j {\Sigma^{*}}^{-1}(\sigma_j \mathbf{I} - \Sigma^*) \\right]^{-1}
and the depolarization tensor :math:`\mathbf{A}_j` is given by
.. math::
\mathbf{A}^* = \\left[\\begin{array}{ccc}
Q & 0 & 0 \\\\
0 & Q & 0 \\\\
0 & 0 & 1-2Q
\end{array}\\right]
for a spheroid aligned along the z-axis. For an oblate spheroid
(:math:`\\alpha < 1`, pancake-like)
.. math::
Q = \\frac{1}{2}\\left(
1 + \\frac{1}{\\alpha^2 - 1} \\left[
1 - \\frac{1}{\chi}\\tan^{-1}(\chi)
\\right]
\\right)
where
.. math::
\chi = \sqrt{\\frac{1}{\\alpha^2} - 1}
For reference, see
`Torquato (2002), Random Heterogeneous Materials <https://link.springer.com/book/10.1007/978-1-4757-6355-3>`_
"""
sigma0 = properties.Float(
"physical property value for phase-0 material",
min=0., required=True
) # this should also be allowed to be an array
sigma1 = properties.Float(
"physical property value for phase-1 material",
min=0., required=True
)
alpha0 = properties.Float(
"aspect ratio of the phase-0 ellipsoids", default=1.
)
alpha1 = properties.Float(
"aspect ratio of the phase-1 ellipsoids", default=1.
)
orientation0 = properties.Vector3(
"orientation of the phase-0 inclusions", default='Z'
)
orientation1 = properties.Vector3(
"orientation of the phase-1 inclusions", default='Z'
)
random = properties.Bool(
"are the inclusions randomly oriented (True) or preferentially "
"aligned (False)?",
default=True
)
rel_tol = properties.Float(
"relative tolerance for convergence for the fixed-point iteration",
default = 1e-3
)
maxIter = properties.Integer(
"maximum number of iterations for the fixed point iteration "
"calculation",
default = 50
)
def __init__(self, mesh=None, nP=None, sigstart=None, **kwargs):
self._sigstart = sigstart
super(SelfConsistentEffectiveMedium, self).__init__(mesh, nP, **kwargs)
@property
def tol(self):
"""
absolute tolerance for the convergence of the fixed point iteration
calc
"""
if getattr(self, '_tol', None) is None:
self._tol = self.rel_tol*min(self.sigma0, self.sigma1)
return self._tol
@property
def sigstart(self):
"""
first guess for sigma
"""
return self._sigstart
def wiener_bounds(self, phi1):
"""Define Wenner Conductivity Bounds
See Torquato, 2002
"""
phi0 = 1.0-phi1
sigWup = phi0*self.sigma0 + phi1*self.sigma1
sigWlo = 1.0/(phi0/self.sigma0 + phi1/self.sigma1)
W = np.array([sigWlo, sigWup])
return W
def hashin_shtrikman_bounds(self, phi1):
"""Hashin Shtrikman bounds
See Torquato, 2002
"""
# TODO: this should probably exsist on its own as a util
phi0 = 1.0 - phi1
sigWu = self.wiener_bounds(phi1)[1]
sig_tilde = phi0*self.sigma1 + phi1*self.sigma0
sigma_min = np.min([self.sigma0, self.sigma1])
sigma_max = np.max([self.sigma0, self.sigma1])
sigHSlo = (
sigWu -
(
(phi0*phi1*(self.sigma0 - self.sigma1)**2) /
(sig_tilde + 2*sigma_max)
)
)
sigHSup = (
sigWu - (
(phi0*phi1*(self.sigma0 - self.sigma1)**2) /
(sig_tilde + 2*sigma_min)
)
)
return np.array([sigHSlo, sigHSup])
def hashin_shtrikman_bounds_anisotropic(self, phi1):
"""Hashin Shtrikman bounds for anisotropic media
See Torquato, 2002
"""
phi0 = 1.0 - phi1
sigWu = self.wiener_bounds(phi1)[1]
sigma_min = np.min([self.sigma0, self.sigma1])
sigma_max = np.max([self.sigma0, self.sigma1])
phi_min = phi0 if self.sigma1 > self.sigma0 else phi1
phi_max = phi1 if self.sigma1 > self.sigma0 else phi0
amax = -phi0*phi1*self.getA(
self.alpha1 if self.sigma1 > self.sigma0 else self.alpha0,
self.orientation1 if self.sigma1 > self.sigma0 else
self.orientation0
)
I = np.eye(3)
sigHSlo = (
sigWu*I +
(
(sigma_min - sigma_max)**2* amax *
np.linalg.inv(sigma_min*I + (sigma_min-sigma_max)/phi_max*amax)
)
)
sigHSup = (
sigWu*I +
(
(sigma_max - sigma_min)**2* amax *
np.linalg.inv(sigma_max*I + (sigma_max-sigma_min)/phi_min*amax)
)
)
return [sigHSlo, sigHSup]
def getQ(self, alpha):
"""Geometric factor in the depolarization tensor
"""
if alpha < 1.: # oblate spheroid
chi = np.sqrt((1./alpha**2.) - 1)
return 1./2. * (
1 + 1./(alpha**2. - 1) * (1. - np.arctan(chi)/chi)
)
elif alpha > 1.: # prolate spheroid
chi = np.sqrt(1 - (1./alpha**2.))
return 1./2. * (
1 + 1./(alpha**2. - 1) * (1. - 1./(2.*chi) * np.log((1 + chi)/(1-chi)))
)
elif alpha == 1: # sphere
return 1./3.
def getA(self, alpha, orientation):
"""Depolarization tensor
"""
Q = self.getQ(alpha)
A = np.diag([Q, Q, 1-2*Q])
R = Utils.rotationMatrixFromNormals(np.r_[0., 0., 1.], orientation)
return (R.T).dot(A).dot(R)
def getR(self, sj, se, alpha, orientation=None):
"""Electric field concentration tensor
"""
if self.random is True: # isotropic
if alpha == 1.:
return 3.*se/(2.*se+sj)
Q = self.getQ(alpha)
return se/3.* (
2./(se + Q*(sj-se)) + 1./(sj - 2.*Q*(sj-se))
)
else: # anisotropic
if orientation is None:
raise Exception("orientation must be provided if random=False")
I = np.eye(3)
seinv = np.linalg.inv(se)
Rinv = I + self.getA(alpha, orientation)*seinv*(sj*I-se)
return np.linalg.inv(Rinv)
def getdR(self, sj, se, alpha, orientation=None):
"""
Derivative of the electric field concentration tensor with respect
to the concentration of the second phase material.
"""
if self.random is True:
if alpha == 1.:
return 3./(2.*se+sj) - 6.*se/(2.*se+sj)**2
Q = self.getQ(alpha)
return 1/3 * (
2./(se + Q*(sj-se)) + 1./(sj - 2.*Q*(sj-se)) +
se * (
-2*(1-Q)/(se + Q*(sj-se))**2 - 2*Q/(sj - 2.*Q*(sj-se))**2
)
)
else:
if orientation is None:
raise Exception("orientation must be provided if random=False")
raise NotImplementedError
def _sc2phaseEMTSpheroidstransform(self, phi1):
"""
Self Consistent Effective Medium Theory Model Transform,
alpha = aspect ratio (c/a <= 1)
"""
if not (np.all(0 <= phi1) and np.all(phi1 <= 1)):
warnings.warn('there are phis outside bounds of 0 and 1')
phi1 = np.median(np.c_[phi1*0, phi1, phi1*0+1.])
phi0 = 1.0-phi1
# starting guess
if self.sigstart is None:
sige1 = np.mean(self.wiener_bounds(phi1))
else:
sige1 = self.sigstart
if self.random is False:
sige1 = sige1 * np.eye(3)
for i in range(self.maxIter):
R0 = self.getR(self.sigma0, sige1, self.alpha0, self.orientation0)
R1 = self.getR(self.sigma1, sige1, self.alpha1, self.orientation1)
den = phi0*R0 + phi1*R1
num = phi0*self.sigma0*R0 + phi1*self.sigma1*R1
if self.random is True:
sige2 = num/den
relerr = np.abs(sige2-sige1)
else:
sige2 = num * np.linalg.inv(den)
relerr = np.linalg.norm(np.abs(sige2-sige1).flatten(), np.inf)
if np.all(relerr <= self.tol):
if self.sigstart is None:
self._sigstart = sige2 # store as a starting point for the next time around
return sige2
sige1 = sige2
# TODO: make this a proper warning, and output relevant info (sigma0, sigma1, phi, sigstart, and relerr)
warnings.warn('Maximum number of iterations reached')
return sige2
def _sc2phaseEMTSpheroidsinversetransform(self, sige):
R0 = self.getR(self.sigma0, sige, self.alpha0, self.orientation0)
R1 = self.getR(self.sigma1, sige, self.alpha1, self.orientation1)
num = -(self.sigma0 - sige)*R0
den = (self.sigma1-sige)*R1 - (self.sigma0-sige)*R0
return num/den
def _sc2phaseEMTSpheroidstransformDeriv(self, sige, phi1):
phi0 = 1.0-phi1
R0 = self.getR(self.sigma0, sige, self.alpha0, self.orientation0)
R1 = self.getR(self.sigma1, sige, self.alpha1, self.orientation1)
dR0 = self.getdR(self.sigma0, sige, self.alpha0, self.orientation0)
dR1 = self.getdR(self.sigma1, sige, self.alpha1, self.orientation1)
num = (sige-self.sigma0)*R0 - (sige-self.sigma1)*R1
den = phi0*(R0 + (sige-self.sigma0)*dR0) + phi1*(R1 + (sige-self.sigma1)*dR1)
return Utils.sdiag(num/den)
def _transform(self, m):
return self._sc2phaseEMTSpheroidstransform(m)
def deriv(self, m):
"""
Derivative of the effective conductivity with respect to the
volume fraction of phase 2 material
"""
sige = self._transform(m)
return self._sc2phaseEMTSpheroidstransformDeriv(sige, m)
def inverse(self, sige):
"""
Compute the concentration given the effective conductivity
"""
return self._sc2phaseEMTSpheroidsinversetransform(sige)
###############################################################################
# #
# Mesh Independent Maps #
# #
###############################################################################
class ExpMap(IdentityMap):
"""
Electrical conductivity varies over many orders of magnitude, so it is
a common technique when solving the inverse problem to parameterize and
optimize in terms of log conductivity. This makes sense not only
because it ensures all conductivities will be positive, but because
this is fundamentally the space where conductivity
lives (i.e. it varies logarithmically).
Changes the model into the physical property.
A common example of this is to invert for electrical conductivity
in log space. In this case, your model will be log(sigma) and to
get back to sigma, you can take the exponential:
.. math::
m = \log{\sigma}
\exp{m} = \exp{\log{\sigma}} = \sigma
"""
def __init__(self, mesh=None, nP=None, **kwargs):
super(ExpMap, self).__init__(mesh=mesh, nP=nP, **kwargs)
def _transform(self, m):
return np.exp(Utils.mkvc(m))
def inverse(self, D):
"""
:param numpy.array D: physical property
:rtype: numpy.array
:return: model
The *transformInverse* changes the physical property into the
model.
.. math::
m = \log{\sigma}
"""
return np.log(Utils.mkvc(D))
def deriv(self, m, v=None):
"""
:param numpy.array m: model
:rtype: scipy.sparse.csr_matrix
:return: derivative of transformed model
The *transform* changes the model into the physical property.
The *transformDeriv* provides the derivative of the *transform*.
If the model *transform* is:
.. math::
m = \log{\sigma}
\exp{m} = \exp{\log{\sigma}} = \sigma
Then the derivative is:
.. math::
\\frac{\partial \exp{m}}{\partial m} = \\text{sdiag}(\exp{m})
"""
deriv = Utils.sdiag(np.exp(Utils.mkvc(m)))
if v is not None:
return deriv * v
return deriv
class ReciprocalMap(IdentityMap):
"""
Reciprocal mapping. For example, electrical resistivity and
conductivity.
.. math::
\\rho = \\frac{1}{\sigma}
"""
def __init__(self, mesh=None, nP=None, **kwargs):
super(ReciprocalMap, self).__init__(mesh=mesh, nP=nP, **kwargs)
def _transform(self, m):
return 1.0 / Utils.mkvc(m)
def inverse(self, D):
return 1.0 / Utils.mkvc(D)
def deriv(self, m, v=None):
# TODO: if this is a tensor, you might have a problem.
deriv = Utils.sdiag(- Utils.mkvc(m)**(-2))
if v is not None:
return deriv * v
return deriv
class LogMap(IdentityMap):
"""
Changes the model into the physical property.
If \\(p\\) is the physical property and \\(m\\) is the model, then
.. math::
p = \\log(m)
and
.. math::
m = \\exp(p)
NOTE: If you have a model which is log conductivity
(ie. \\(m = \\log(\\sigma)\\)),
you should be using an ExpMap
"""
def __init__(self, mesh=None, nP=None, **kwargs):
super(LogMap, self).__init__(mesh=mesh, nP=nP, **kwargs)
def _transform(self, m):
return np.log(Utils.mkvc(m))
def deriv(self, m, v=None):
mod = Utils.mkvc(m)
deriv = np.zeros(mod.shape)
tol = 1e-16 # zero
ind = np.greater_equal(np.abs(mod), tol)
deriv[ind] = 1.0/mod[ind]
if v is not None:
return Utils.sdiag(deriv)*v
return Utils.sdiag(deriv)
def inverse(self, m):
return np.exp(Utils.mkvc(m))
class ChiMap(IdentityMap):
"""Chi Map
Convert Magnetic Susceptibility to Magnetic Permeability.
.. math::
\mu(m) = \mu_0 (1 + \chi(m))
"""
def __init__(self, mesh=None, nP=None, **kwargs):
super(ChiMap, self).__init__(mesh=mesh, nP=nP, **kwargs)
def _transform(self, m):
return mu_0 * (1 + m)
def deriv(self, m, v=None):
if v is not None:
return mu_0 * v
return mu_0 * sp.eye(self.nP)
def inverse(self, m):
return m / mu_0 - 1
class MuRelative(IdentityMap):
"""
Invert for relative permeability
.. math::
\mu(m) = \mu_0 * \mathbf{m}
"""
def __init__(self, mesh=None, nP=None, **kwargs):
super(MuRelative, self).__init__(mesh=mesh, nP=nP, **kwargs)
def _transform(self, m):
return mu_0 * m
def deriv(self, m, v=None):
if v is not None:
return mu_0 * v
return mu_0 * sp.eye(self.nP)
def inverse(self, m):
return 1./mu_0 * m
class Weighting(IdentityMap):
"""
Model weight parameters.
"""
def __init__(self, mesh=None, nP=None, weights=None, **kwargs):
if 'nC' in kwargs:
raise AttributeError(
'`nC` is depreciated. Use `nP` to set the number of model '
'parameters'
)
super(Weighting, self).__init__(mesh=mesh, nP=nP, **kwargs)
if weights is None:
weights = np.ones(self.nP)
self.weights = np.array(weights, dtype=float)
@property
def shape(self):
return (self.nP, self.nP)
@property
def P(self):
return Utils.sdiag(self.weights)
def _transform(self, m):
return self.weights*m