forked from simpeg/simpeg
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Maps.py
3383 lines (2688 loc) · 105 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
from . import Mesh
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
from SimPEG.Utils import mkvc
import properties
from . import Utils
from .Tests import checkDerivative
class IdentityMap(object):
"""
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:`SimPEG.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:`SimPEG.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 np.any([isinstance(m, SumMap), isinstance(m, IdentityMap)]):
self.maps += [m]
elif isinstance(m, ComboMap):
self.maps += m.maps
else:
raise ValueError(
'Map[{0!s}] not supported',
m.__class__.__name__
)
@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 SumMap(ComboMap):
"""
A map to add model parameters contributing to the
forward operation e.g. F(m) = F m1 + F m2 + ...
"""
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 == '*' or m.shape == '*') and
not self.shape == m.shape
):
raise ValueError(
'Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) '
'and map[{3!s}] ({4!s}, {5!s}).'.format(
self.maps[0].__class__.__name__,
self.maps[0].shape[0],
self.maps[0].shape[1],
m.__class__.__name__,
m.shape[0],
m.shape[1]
)
)
self.maps += [m]
@property
def shape(self):
return (self.maps[0].shape[0], self.maps[0].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].shape[1]
def _transform(self, m):
for ii, map_i in enumerate(self.maps):
m0 = m.copy()
m0 = map_i * m0
if ii == 0:
mout = m0
else:
mout += m0
return mout
def deriv(self, m, v=None):
for ii, map_i in enumerate(self.maps):
m0 = m.copy()
if v is not None:
deriv = v
else:
deriv = sp.eye(self.nP)
deriv = map_i.deriv(m0, v=deriv)
if ii == 0:
sumDeriv = deriv
else:
sumDeriv += deriv
return sumDeriv
class SurjectUnits(IdentityMap):
"""
A map to group model cells into an homogeneous unit
:param list index: list of bool for each homogeneous unit
"""
nBlock = 1 # Variable allowing to stack same Map over multiple sets
def __init__(self, index, **kwargs):
assert isinstance(index, (list)), (
'index must be a list, not {}'.format(type(index)))
super(SurjectUnits, self).__init__(**kwargs)
self.index = index
nP = len(self.index[0])
self._shape = self.nBlock*nP, self.nBlock*len(self.index),
@property
def P(self):
if getattr(self, '_P', None) is None:
nP = len(self.index[0])
# sparse projection matrix
row = []
col = []
val = []
for ii, ind in enumerate(self.index):
row += [ii]*ind.sum()
col += np.where(ind)[0].tolist()
val += [1]*ind.sum()
P = sp.csr_matrix(
(val, (row, col)), shape=(len(self.index), nP)
).T
self._P = sp.block_diag([P for ii in range(self.nBlock)])
return self._P
def _transform(self, m):
return self.P * m
@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 Tile(IdentityMap):
"""
Mapping for tiled inversion
"""
nCell = 26 # Number of neighbors to use in averaging
tol = 1e-8 # Tolerance to avoid zero division
nBlock = 1
def __init__(self, *args, **kwargs):
assert len(args) == 2, ('Mapping requires a tuple' +
'(MeshGlobal, ActiveGlobal),' +
'(MeshLocal, ActiveLocal)')
super(Tile, self).__init__(**kwargs)
# check if tree in kwargs
if 'tree' in kwargs.keys(): # kwargs is a dict
tree = kwargs.pop('tree')
assert isinstance(tree, cKDTree), ('Tree input must be a cKDTRee')
self._tree = tree
self.meshGlobal = args[0][0]
self.actvGlobal = args[0][1]
if not isinstance(self.actvGlobal, bool):
temp = np.zeros(self.meshGlobal.nC, dtype='bool')
temp[self.actvGlobal] = True
self.actvGlobal = temp
self.meshLocal = args[1][0]
self.activeLocal = args[1][1]
# if not isinstance(self.activeLocal, bool):
# temp = np.zeros(self.meshLocal.nC, dtype='bool')
# temp[self.activeLocal] = True
# self.activeLocal = temp
if self.nCell > self.meshGlobal.nC:
self.nCell = self.meshGlobal.nC
self.index = np.ones(self.actvGlobal.sum(), dtype='bool')
self.P
@property
def tree(self):
"""
Create cKDTree structure for given global mesh
"""
if getattr(self, '_tree', None) is None:
# if self.meshGlobal.dim == 1:
# ccMat = np.c_[self.meshGlobal.gridCC[self.actvGlobal, 0]]
# elif self.meshGlobal.dim == 2:
# ccMat = np.c_[self.meshGlobal.gridCC[self.actvGlobal, 0],
# self.meshGlobal.gridCC[self.actvGlobal, 1]]
# elif self.meshGlobal.dim == 3:
# ccMat = np.c_[self.meshGlobal.gridCC[self.actvGlobal, 0],
# self.meshGlobal.gridCC[self.actvGlobal, 1],
# self.meshGlobal.gridCC[self.actvGlobal, 2]]
self._tree = cKDTree(self.meshGlobal.gridCC[self.actvGlobal, :])
return self._tree
@property
def activeLocal(self):
"""This is the activeLocal of the actvGlobal used in the global problem."""
return getattr(self, '_activeLocal', None)
@activeLocal.setter
def activeLocal(self, activeLocal):
if not isinstance(activeLocal, bool):
temp = np.zeros(self.meshLocal.nC, dtype='bool')
temp[activeLocal] = True
activeLocal = temp
self._activeLocal = activeLocal
@property
def index(self):
"""This is the index of the actvGlobal used in the global problem."""
return getattr(self, '_index', None)
@index.setter
def index(self, index):
if getattr(self, '_index', None) is not None:
self._S = None
if not isinstance(index, bool):
temp = np.zeros(self.actvGlobal.sum(), dtype='bool')
temp[index] = True
index = temp
self._nP = index.sum()
self._index = index
@property
def S(self):
"""
Create sub-selection matrix in case where the global
mesh is not touched by all sub meshes
"""
if getattr(self, '_S', None) is None:
nP = self.actvGlobal.sum()
nI = self.index.sum()
assert (nI <= nP), (
'maximum index must be less than {}'.format(nP))
# sparse projection matrix
S = sp.csr_matrix(
(np.ones(nI), (np.where(self.index)[0], range(nI))), shape=(nP, nI)
)
self._S = S
return self._S
@property
def P(self):
"""
Set the projection matrix with partial volumes
"""
if getattr(self, '_P', None) is None:
if self.meshLocal._meshType == "TREE":
actvIndGlobal = np.where(self.actvGlobal)[0].tolist()
indL = self.meshLocal._get_containing_cell_indexes(self.meshGlobal.gridCC)
full = np.c_[indL, np.arange(self.meshGlobal.nC)]
# Create new index based on unique active
# [ua, ind] = np.unique(indL, return_index=True)
check = np.where(self.meshLocal.vol[indL] < self.meshGlobal.vol)[0].tolist()
# Reverse inside global to local
indG = self.meshGlobal._get_containing_cell_indexes(self.meshLocal.gridCC)
model = np.zeros(self.meshLocal.nC)
rows = []
for ind in check:
if ind in actvIndGlobal:
indAdd = np.where(ind == indG)[0]
rows += [np.c_[indAdd, np.ones_like(indAdd)*ind]]
# model[indAdd] = 0.5
# indL = indL[actv]
if len(rows) > 0:
full = np.r_[full[actvIndGlobal, :], np.vstack(rows)]
else:
full = full[actvIndGlobal, :]
# model[full[:,0]]=0.5
actvIndLocal = np.unique(full[:, 0])
full = np.c_[np.searchsorted(actvIndLocal, full[:, 0]), np.searchsorted(actvIndGlobal, full[:, 1])]
activeLocal = np.zeros(self.meshLocal.nC, dtype='bool')
activeLocal[actvIndLocal] = True
self.activeLocal = activeLocal
else:
indx = self.getTreeIndex(self.tree, self.meshLocal, self.activeLocal)
local2Global = np.c_[np.kron(np.ones(self.nCell), np.asarray(range(self.activeLocal.sum()))).astype('int'), mkvc(indx)]
tree = cKDTree(self.meshLocal.gridCC[self.activeLocal, :])
r, ind = tree.query(self.meshGlobal.gridCC[self.actvGlobal], k=self.nCell)
global2Local = np.c_[np.kron(np.ones(self.nCell), np.asarray(range(self.actvGlobal.sum()))).astype('int'), mkvc(ind)]
full = np.unique(np.vstack([local2Global, global2Local[:, [1, 0]]]), axis=0)
# Free up memory
self._tree = None
tree = None
# Get the node coordinates (bottom-SW) and (top-NE) of cells
# in the global and local mesh
global_bsw, global_tne = self.getNodeExtent(self.meshGlobal,
self.actvGlobal)
local_bsw, local_tne = self.getNodeExtent(self.meshLocal,
self.activeLocal)
nactv = full.shape[0]
# Compute intersecting cell volumes
if self.meshLocal.dim == 1:
dV = np.max(
[(np.min(
[global_tne[full[:, 1]],
local_tne[full[:, 0]]], axis=0
) -
np.max(
[global_bsw[full[:, 1]],
local_bsw[full[:, 0]]], axis=0)
), np.zeros(nactv)
], axis=0
)
elif self.meshLocal.dim >= 2:
dV = np.max(
[(np.min(
[global_tne[full[:, 1], 0],
local_tne[full[:, 0], 0]], axis=0
) -
np.max(
[global_bsw[full[:, 1], 0],
local_bsw[full[:, 0], 0]], axis=0)
), np.zeros(nactv)], axis=0
)
dV *= np.max([(np.min([global_tne[full[:, 1], 1], local_tne[full[:, 0], 1]],
axis=0) -
np.max([global_bsw[full[:, 1], 1], local_bsw[full[:, 0], 1]],
axis=0)),
np.zeros(nactv)], axis=0)
if self.meshLocal.dim == 3:
dV *= np.max([(np.min([global_tne[full[:, 1], 2], local_tne[full[:, 0], 2]],
axis=0) -
np.max([global_bsw[full[:, 1], 2], local_bsw[full[:, 0], 2]],
axis=0)),
np.zeros(nactv)], axis=0)
# Select only cells with non-zero intersecting volumes
nzV = dV > 0
self.V = dV[nzV]
P = sp.csr_matrix((self.V, (full[nzV, 0], full[nzV, 1])),
shape=(self.activeLocal.sum(), self.actvGlobal.sum()))
sumRow = Utils.mkvc(np.sum(P, axis=1) + self.tol)
self.scaleJ = sp.block_diag([
Utils.sdiag(sumRow/self.meshLocal.vol[self.activeLocal])
for ii in range(self.nBlock)])
self._P = sp.block_diag([
Utils.sdiag(1./sumRow) * P * self.S
for ii in range(self.nBlock)])
self._shape = int(self.activeLocal.sum()*self.nBlock), int(self.actvGlobal.sum()*self.nBlock)
return self._P
def getTreeIndex(self, tree, mesh, actvCell):
"""
Querry the KDTree for nearest cells
"""
# if self.meshGlobal.dim == 1:
d, indx = tree.query(mesh.gridCC[actvCell, :],
k=self.nCell)
# elif self.meshGlobal.dim == 2:
# d, indx = tree.query(np.c_[mesh.gridCC[actvCell, 0],
# mesh.gridCC[actvCell, 1]],
# k=self.nCell)
# elif self.meshGlobal.dim == 3:
# d, indx = tree.query(np.c_[mesh.gridCC[actvCell, 0],
# mesh.gridCC[actvCell, 1],
# mesh.gridCC[actvCell, 2]],
# k=self.nCell)
return indx
def getNodeExtent(self, mesh, actvCell):
bsw = mesh.gridCC - mesh.h_gridded/2.
tne = mesh.gridCC + mesh.h_gridded/2.
# Return only active set
return bsw[actvCell], tne[actvCell]
def _transform(self, m):
return self.P * m
@property
def shape(self):
"""
Shape of the matrix operation (number of indices x nP)
"""
return self.P.shape
def deriv(self, m, v=None):
"""
:param numpy.array m: model
:rtype: scipy.sparse.csr_matrix
:return: derivative of transformed model
"""
self.P
if v is not None:
return self.scaleJ * self.P * v
return self.scaleJ * self.P
class SelfConsistentEffectiveMedium(IdentityMap, properties.HasProperties):
"""
Two phase self-consistent effective medium theory mapping for
ellipsoidal inclusions. The model is the concentration
(volume fraction) of the phase 2 material.
The 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}
.. todo::
Prolate spheroids (\alpha > 1, needle-like) have not been
implemented yet
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
)
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.
)
rel_tol = properties.Float(
"relative tolerance for convergence for the fixed-point iteration",
default = 1e-4
)
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 wennerBounds(self, phi1):
"""Define Wenner Conductivity Bounds"""
# TODO: Add HS bounds (not needed for spherical particles, but for ellipsoidal ones)
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 getQ(self, alpha):
if alpha < 1.:
Chi = np.sqrt((1./alpha**2.) - 1.)
return 1./2.*(1. + 1./(alpha**2. - 1.)*(1. - np.arctan(Chi)/Chi))
elif alpha > 1.:
raise NotImplementedError(
'Aspect ratios > 1 have not been implemeted'
)