Compare commits

..
Author SHA1 Message Date
Lindsey Heagy 3cbefac3ba try using list for Jv instead of datapair - has been seen to cause memory leaks 2016-06-29 15:55:34 -07:00
Lindsey Heagy e7e497a06d don't use Zero() in mapping derivs) 2016-06-29 08:45:45 -07:00
Lindsey Heagy 3157aa02cf naming update 2016-06-28 08:15:19 -07:00
Lindsey Heagy c40d11ef53 - better model for testing Parametric casing map
- allow vector containing values in the inactive set to be passed (not just nC in length)
2016-06-26 15:24:33 -07:00
Lindsey Heagy c75e3d0246 use a dictionary to keep track of parametric model parameters. Test mappings on cyl meshes, parametric casing and layer model 2016-06-25 16:51:18 -07:00
Lindsey Heagy 14f0d90f99 debugging derivs 2016-06-23 13:06:15 -07:00
Lindsey Heagy 425b1e292c only accept one source for the prim-sec source 2016-06-21 18:00:41 -07:00
Lindsey Heagy f6cd8696d1 call fields inside of SrcDeriv for primsec 2016-06-21 17:36:53 -07:00
Lindsey Heagy f788d5f05d bug hunting a silly memory issue (don't add vectors to column arrays!). return sparse matrices from mapping derivs for multiplying things 2016-06-21 17:20:02 -07:00
Lindsey Heagy 1521b08af6 remove @property from projPrimary 2016-05-31 23:48:04 -07:00
Lindsey Heagy 8c366463e7 call projection with problem 2016-05-31 23:19:02 -07:00
Lindsey Heagy 6d77ae9a12 pass problem to projection matrix in primsecsrc 2016-05-31 23:08:57 -07:00
Lindsey Heagy ce88c676d4 add a projection map (for re-arranging models)
use current sigmaModel in src
2016-05-31 22:44:39 -07:00
Lindsey Heagy 1e6ed86135 - parametrized layer
- parameterized block in layer inherits parametrized layer
2016-05-31 21:39:59 -07:00
Lindsey Heagy 9061ef5839 start of including primary fields derivs 2016-05-31 21:04:26 -07:00
Lindsey Heagy 0638fa308c start of prim sec src with more derivs 2016-05-30 20:30:00 -07:00
Lindsey Heagy 54478ad05e don't use adjoint when not asking for the adjoint! 2016-05-30 11:40:42 -07:00
Lindsey Heagy 2cf0edb736 bug fix in PrimSec src Deriv 2016-05-30 11:29:24 -07:00
Lindsey Heagy 3b5dfecb46 cleanup imports and class instantiation of prim-sec src in sigma 2016-05-30 10:05:15 -07:00
Lindsey Heagy 93d8ef5921 don't need m on the prim-sec src 2016-05-30 09:37:06 -07:00
Lindsey Heagy 5b0a58b751 typo in src input 2016-05-30 09:26:28 -07:00
Lindsey Heagy 9155a9c474 prim sec src in conductivity 2016-05-30 09:10:53 -07:00
Lindsey Heagy 64510bc606 Merge branch 'dev' into maps/feat-parametrizedBlock 2016-05-29 14:51:11 -07:00
Lindsey Heagy d9f0241da3 typo fix in nC (it is mesh.nC) 2016-05-29 14:21:08 -07:00
Lindsey Heagy 9a7225c9f6 - bug fix in parametrized block when active cells are used - need a shape
- add a pole receiver for DC
2016-05-29 13:40:21 -07:00
Lindsey Heagy e8e022fcc6 return a scipy sparse matrix for the deriv (a bit silly - it is dense, but nicer for multiplication). Init Regularization with a nP 2016-05-28 15:40:28 -07:00
Lindsey Heagy 341b98d23a use layer center and layer thickness to parametrize layer 2016-05-28 13:06:19 -07:00
Lindsey Heagy efbc8f9057 add docs for ParametrizedBlockInLayer, moved docs from rst to python files and automodule the docs for maps 2016-05-26 23:06:57 -07:00
Lindsey Heagy 39ece11d8a Merge branch 'dev' into maps/feat-parametrizedBlock 2016-05-26 21:32:57 -07:00
Lindsey Heagy c36b5a600d add parametrized block in a layer map 2016-05-26 10:30:10 -07:00
271 changed files with 2961 additions and 4574 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
[bumpversion] [bumpversion]
current_version = 0.1.12 current_version = 0.1.10
files = setup.py SimPEG/__init__.py docs/conf.py files = setup.py SimPEG/__init__.py docs/conf.py
-2
View File
@@ -39,5 +39,3 @@ nosetests.xml
*.sublime-workspace *.sublime-workspace
docs/_build/ docs/_build/
Makefile Makefile
docs/warnings.txt
.DS_Store
+5 -28
View File
@@ -1,7 +1,6 @@
language: python language: python
python: python:
- 2.7 - 2.7
- 3.4
sudo: false sudo: false
@@ -25,25 +24,18 @@ env:
- TEST_DIR=tests/examples - TEST_DIR=tests/examples
- TEST_DIR=tests/em/fdem/inverse/adjoint - TEST_DIR=tests/em/fdem/inverse/adjoint
- TEST_DIR=tests/em/fdem/forward - TEST_DIR=tests/em/fdem/forward
- TEST_DIR=tests/docs;
GAE_PYTHONPATH=${HOME}/.cache/google_appengine;
PATH=$PATH:${HOME}/google-cloud-sdk/bin;
PYTHONPATH=${PYTHONPATH}:${GAE_PYTHONPATH};
CLOUDSDK_CORE_DISABLE_PROMPTS=1
# Setup anaconda # Setup anaconda
before_install: before_install:
# Install packages - if [ ${TRAVIS_PYTHON_VERSION:0:1} == "2" ]; then wget http://repo.continuum.io/miniconda/Miniconda-3.8.3-Linux-x86_64.sh -O miniconda.sh; else wget http://repo.continuum.io/miniconda/Miniconda3-3.8.3-Linux-x86_64.sh -O miniconda.sh; fi
- if [ ${TRAVIS_PYTHON_VERSION:0:1} == "2" ]; then wget http://repo.continuum.io/miniconda/Miniconda-3.8.3-Linux-x86_64.sh
-O miniconda.sh; else wget http://repo.continuum.io/miniconda/Miniconda3-3.8.3-Linux-x86_64.sh
-O miniconda.sh; fi
- chmod +x miniconda.sh - chmod +x miniconda.sh
- ./miniconda.sh -b - ./miniconda.sh -b
- export PATH=/home/travis/anaconda/bin:/home/travis/anaconda3/bin:/home/travis/miniconda/bin:/home/travis/miniconda3/bin:$PATH - export PATH=/home/travis/anaconda/bin:/home/travis/miniconda/bin:$PATH
- conda update --yes conda - conda update --yes conda
# Install packages
install: install:
- conda install --yes pip python=$TRAVIS_PYTHON_VERSION numpy scipy matplotlib cython ipython nose vtk sphinx - conda install --yes pip python=$TRAVIS_PYTHON_VERSION numpy scipy matplotlib cython ipython nose vtk
- pip install nose-cov python-coveralls - pip install nose-cov python-coveralls
- git clone https://github.com/rowanc1/pymatsolver.git - git clone https://github.com/rowanc1/pymatsolver.git
@@ -54,26 +46,11 @@ install:
# Run test # Run test
script: script:
# test docs
- nosetests $TEST_DIR --with-cov --cov SimPEG --cov-config .coveragerc -v -s - nosetests $TEST_DIR --with-cov --cov SimPEG --cov-config .coveragerc -v -s
# Calculate coverage # Calculate coverage
after_success: after_success:
- bash <(curl -s https://codecov.io/bash) - coveralls --config_file .coveragerc
- if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then
if [ ${TEST_DIR} == "tests/docs" ]; then
python scripts/fetch_gae_sdk.py $(dirname "${GAE_PYTHONPATH}");
openssl aes-256-cbc -K $encrypted_93066031461c_key -iv $encrypted_93066031461c_iv
-in docs/credentials.tar.gz.enc -out credentials.tar.gz -d ;
if [ ! -d ${HOME}/google-cloud-sdk ]; then curl https://sdk.cloud.google.com | bash; fi ;
tar -xzf credentials.tar.gz ;
gcloud auth activate-service-account --key-file client-secret.json ;
gcloud config set project simpegdocs;
gcloud -q components update gae-python;
gcloud -q preview app deploy ./docs/app.yaml --version ${TRAVIS_COMMIT} --promote;
fi;
fi
notifications: notifications:
email: email:
+1 -5
View File
@@ -1,4 +1,4 @@
.. image:: https://raw.github.com/simpeg/simpeg/master/docs/images/simpeg-logo.png .. image:: https://raw.github.com/simpeg/simpeg/master/docs/simpeg-logo.png
:alt: SimPEG Logo :alt: SimPEG Logo
====== ======
@@ -29,10 +29,6 @@ SimPEG
:alt: gitter chat room at https://gitter.im/simpeg/simpeg :alt: gitter chat room at https://gitter.im/simpeg/simpeg
:target: https://gitter.im/simpeg/simpeg :target: https://gitter.im/simpeg/simpeg
.. image:: https://codecov.io/gh/simpeg/simpeg/branch/master/graph/badge.svg
  :target: https://codecov.io/gh/simpeg/simpeg
Simulation and Parameter Estimation in Geophysics - A python package for simulation and gradient based parameter estimation in the context of geophysical applications. Simulation and Parameter Estimation in Geophysics - A python package for simulation and gradient based parameter estimation in the context of geophysical applications.
The vision is to create a package for finite volume simulation with applications to geophysical imaging and subsurface flow. To enable the understanding of the many different components, this package has the following features: The vision is to create a package for finite volume simulation with applications to geophysical imaging and subsurface flow. To enable the understanding of the many different components, this package has the following features:
+3 -11
View File
@@ -1,11 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
class FieldsDC_CC(Problem.Fields): class FieldsDC_CC(Problem.Fields):
@@ -69,7 +61,7 @@ class SrcDipole(Survey.BaseSrc):
pts = [self.loc[0], self.loc[1]] pts = [self.loc[0], self.loc[1]]
inds = Utils.closestPoints(prob.mesh, pts) inds = Utils.closestPoints(prob.mesh, pts)
q = np.zeros(prob.mesh.nC) q = np.zeros(prob.mesh.nC)
q[inds] = - self.current * (np.r_[1., -1.] / prob.mesh.vol[inds]) q[inds] = - self.current * ( np.r_[1., -1.] / prob.mesh.vol[inds] )
# self._rhsDict[mesh] = q # self._rhsDict[mesh] = q
# return self._rhsDict[mesh] # return self._rhsDict[mesh]
return q return q
@@ -170,8 +162,8 @@ class ProblemDC_CC(Problem.BaseProblem):
""" """
Makes the matrix A(m) for the DC resistivity problem. Makes the matrix A(m) for the DC resistivity problem.
:param numpy.ndarray m: model :param numpy.array m: model
:rtype: scipy.sparse.csc_matrix :rtype: scipy.csc_matrix
:return: A(m) :return: A(m)
.. math:: .. math::
+3 -10
View File
@@ -1,12 +1,5 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
from .BaseDC import SurveyDC, FieldsDC_CC from BaseDC import SurveyDC, FieldsDC_CC
class SurveyIP(SurveyDC): class SurveyIP(SurveyDC):
""" """
@@ -59,7 +52,7 @@ class ProblemIP(Problem.BaseProblem):
# sigma = self.curModel.transform # sigma = self.curModel.transform
sigma = self.sigma sigma = self.sigma
Av = self.mesh.aveF2CC Av = self.mesh.aveF2CC
self._Msig = Utils.sdiag(1//(self.mesh.dim * Av.T * (1/sigma))) self._Msig = Utils.sdiag(1/(self.mesh.dim * Av.T * (1/sigma)))
return self._Msig return self._Msig
@property @property
@@ -78,7 +71,7 @@ class ProblemIP(Problem.BaseProblem):
Makes the matrix A(m) for the DC resistivity problem. Makes the matrix A(m) for the DC resistivity problem.
:param numpy.array m: model :param numpy.array m: model
:rtype: scipy.sparse.csc_matrix :rtype: scipy.csc_matrix
:return: A(m) :return: A(m)
.. math:: .. math::
+21 -31
View File
@@ -1,16 +1,6 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from builtins import open
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import map
from builtins import range
from SimPEG import np, Utils from SimPEG import np, Utils
from . import BaseDC as DC import BaseDC as DC
from . import BaseDC as IP import BaseDC as IP
import warnings import warnings
def getActiveindfromTopo(mesh, topo): def getActiveindfromTopo(mesh, topo):
@@ -77,7 +67,7 @@ def readUBC_DC3Dobstopo(filename,mesh,topo,probType="CC"):
if "!" in line.split(): continue if "!" in line.split(): continue
elif line == '\n': continue elif line == '\n': continue
elif line == ' \n': continue elif line == ' \n': continue
temp = list(map(float, line.split())) temp = map(float, line.split())
# Read a line for the current electrode # Read a line for the current electrode
if len(temp) == 5: # SRC: Only X and Y are provided (assume no topography) if len(temp) == 5: # SRC: Only X and Y are provided (assume no topography)
#TODO consider topography and assign the closest cell center in the earth #TODO consider topography and assign the closest cell center in the earth
@@ -238,10 +228,10 @@ def plot_pseudoSection(DCsurvey, axs, surveyType='dipole-dipole', unitType='volt
elif surveyType == 'dipole-dipole': elif surveyType == 'dipole-dipole':
leg = data * 2*np.pi / (1/MA - 1/MB - 1/NB + 1/NA) leg = data * 2*np.pi / ( 1/MA - 1/MB - 1/NB + 1/NA )
else: else:
print("""unitType must be 'pole-dipole' | 'dipole-dipole' """) print """unitType must be 'pole-dipole' | 'dipole-dipole' """
break break
@@ -256,11 +246,11 @@ def plot_pseudoSection(DCsurvey, axs, surveyType='dipole-dipole', unitType='volt
rho = np.hstack([rho,leg]) rho = np.hstack([rho,leg])
else: else:
print("""unitType must be 'appResistivity' | 'appConductivity' | 'volt' """) print """unitType must be 'appResistivity' | 'appConductivity' | 'volt' """
break break
midx = np.hstack([midx, (Cmid + Pmid)/2]) midx = np.hstack([midx, ( Cmid + Pmid )/2 ])
midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + (Tx[0][2] + Tx[1][2])/2]) midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + (Tx[0][2] + Tx[1][2])/2 ])
# Grid points # Grid points
grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)] grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)]
@@ -350,11 +340,11 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx):
dl_x = ( endl[1,0] - endl[0,0] ) / dl_len dl_x = ( endl[1,0] - endl[0,0] ) / dl_len
dl_y = ( endl[1,1] - endl[0,1] ) / dl_len dl_y = ( endl[1,1] - endl[0,1] ) / dl_len
nstn = np.floor(dl_len / AM_sep) nstn = np.floor( dl_len / AM_sep )
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = endl[0,0] + np.array(list(range(int(nstn))))*dl_x*AM_sep stn_x = endl[0,0] + np.array(range(int(nstn)))*dl_x*AM_sep
stn_y = endl[0,1] + np.array(list(range(int(nstn))))*dl_y*AM_sep stn_y = endl[0,1] + np.array(range(int(nstn)))*dl_y*AM_sep
# Create line of P1 locations # Create line of P1 locations
M = np.c_[stn_x, stn_y, np.ones(nstn).T*mesh.vectorNz[-1]] M = np.c_[stn_x, stn_y, np.ones(nstn).T*mesh.vectorNz[-1]]
@@ -386,15 +376,15 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx):
AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1]) AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1])
# Number of receivers to fit # Number of receivers to fit
nstn = np.min([(AB - MN_sep) // AM_sep, nrx]) nstn = np.min([np.floor( (AB - MN_sep) / AM_sep ) , nrx])
# Check if there is enough space, else break the loop # Check if there is enough space, else break the loop
if nstn <= 0: if nstn <= 0:
continue continue
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = N[ii,0] + dl_x*MN_sep + np.array(list(range(int(nstn))))*dl_x*AM_sep stn_x = N[ii,0] + dl_x*MN_sep + np.array(range(int(nstn)))*dl_x*AM_sep
stn_y = N[ii,1] + dl_y*MN_sep + np.array(list(range(int(nstn))))*dl_y*AM_sep stn_y = N[ii,1] + dl_y*MN_sep + np.array(range(int(nstn)))*dl_y*AM_sep
# Create receiver poles # Create receiver poles
# Create line of P1 locations # Create line of P1 locations
@@ -429,15 +419,15 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx):
box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 ) box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 )
box_w = box_l/2. box_w = box_l/2.
nstn = box_l // AM_sep nstn = np.floor( box_l / AM_sep )
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = min_x + np.array(list(range(int(nstn))))*dl_x*AM_sep stn_x = min_x + np.array(range(int(nstn)))*dl_x*AM_sep
stn_y = min_y + np.array(list(range(int(nstn))))*dl_y*AM_sep stn_y = min_y + np.array(range(int(nstn)))*dl_y*AM_sep
# Define number of cross lines # Define number of cross lines
nlin = int(box_w // AM_sep) nlin = int(np.floor( box_w / AM_sep ))
lind = list(range(-nlin,nlin+1)) lind = range(-nlin,nlin+1)
ngrad = nstn * len(lind) ngrad = nstn * len(lind)
@@ -459,7 +449,7 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx):
srcClass = DC.SrcDipole([rxClass], M[0,:], N[-1,:]) srcClass = DC.SrcDipole([rxClass], M[0,:], N[-1,:])
SrcList.append(srcClass) SrcList.append(srcClass)
else: else:
print("""surveyType must be either 'pole-dipole', 'dipole-dipole' or 'gradient'. """) print """surveyType must be either 'pole-dipole', 'dipole-dipole' or 'gradient'. """
survey = DC.SurveyDC(SrcList) survey = DC.SurveyDC(SrcList)
return survey, Tx, Rx return survey, Tx, Rx
@@ -678,7 +668,7 @@ def readUBC_DC3Dobs(fileName, rtype = 'DC'):
obsfile = np.genfromtxt(fileName,delimiter=' \n',dtype=np.str,comments='!') obsfile = np.genfromtxt(fileName,delimiter=' \n',dtype=np.str,comments='!')
else: else:
print("rtype must be 'DC'(default) | 'IP'") print "rtype must be 'DC'(default) | 'IP'"
# Pre-allocate # Pre-allocate
srcLists = [] srcLists = []
+1 -8
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
import numpy as np import numpy as np
def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False):
@@ -12,7 +5,7 @@ def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False):
import SimPEG.DCIP as DC import SimPEG.DCIP as DC
elocs = np.arange(0,aSpacing*nElecs,aSpacing) elocs = np.arange(0,aSpacing*nElecs,aSpacing)
elocs -= (nElecs*aSpacing - aSpacing) / 2 elocs -= (nElecs*aSpacing - aSpacing)/2
space = 1 space = 1
WENNER = np.zeros((0,),dtype=int) WENNER = np.zeros((0,),dtype=int)
for ii in range(nElecs): for ii in range(nElecs):
+4 -10
View File
@@ -1,10 +1,4 @@
from __future__ import absolute_import from BaseDC import *
from __future__ import unicode_literals from BaseIP import *
from __future__ import print_function from DCIPUtils import *
from __future__ import division import Utils
from future import standard_library
standard_library.install_aliases()
from .BaseDC import *
from .BaseIP import *
from .DCIPUtils import *
from . import Utils
+6 -13
View File
@@ -1,16 +1,7 @@
from __future__ import print_function import Utils, Survey, Problem, numpy as np, scipy.sparse as sp, gc
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
from . import Utils, Survey, Problem
import numpy as np, scipy.sparse as sp, gc
from future.utils import with_metaclass
class BaseDataMisfit(with_metaclass(Utils.SimPEGMetaClass, object)): class BaseDataMisfit(object):
"""BaseDataMisfit """BaseDataMisfit
.. note:: .. note::
@@ -18,6 +9,8 @@ class BaseDataMisfit(with_metaclass(Utils.SimPEGMetaClass, object)):
You should inherit from this class to create your own data misfit term. You should inherit from this class to create your own data misfit term.
""" """
__metaclass__ = Utils.SimPEGMetaClass
debug = False #: Print debugging information debug = False #: Print debugging information
counter = None #: Set this to a SimPEG.Utils.Counter() if you want to count things counter = None #: Set this to a SimPEG.Utils.Counter() if you want to count things
@@ -100,11 +93,11 @@ class l2_DataMisfit(BaseDataMisfit):
survey = self.survey survey = self.survey
if getattr(survey,'std', None) is None: if getattr(survey,'std', None) is None:
print('SimPEG.DataMisfit.l2_DataMisfit assigning default std of 5%') print 'SimPEG.DataMisfit.l2_DataMisfit assigning default std of 5%'
survey.std = 0.05 survey.std = 0.05
if getattr(survey, 'eps', None) is None: if getattr(survey, 'eps', None) is None:
print('SimPEG.DataMisfit.l2_DataMisfit assigning default eps of 1e-5 * ||dobs||') print 'SimPEG.DataMisfit.l2_DataMisfit assigning default eps of 1e-5 * ||dobs||'
survey.eps = np.linalg.norm(Utils.mkvc(survey.dobs),2)*1e-5 survey.eps = np.linalg.norm(Utils.mkvc(survey.dobs),2)*1e-5
self._Wd = Utils.sdiag(1/(abs(survey.dobs)*survey.std+survey.eps)) self._Wd = Utils.sdiag(1/(abs(survey.dobs)*survey.std+survey.eps))
+66 -151
View File
@@ -1,15 +1,4 @@
from __future__ import print_function import Utils, numpy as np
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import open
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
from . import Utils
import numpy as np
class InversionDirective(object): class InversionDirective(object):
"""InversionDirective""" """InversionDirective"""
@@ -26,7 +15,7 @@ class InversionDirective(object):
@inversion.setter @inversion.setter
def inversion(self, i): def inversion(self, i):
if getattr(self,'_inversion',None) is not None: if getattr(self,'_inversion',None) is not None:
print('Warning: InversionDirective %s has switched to a new inversion.' % self.__name__) print 'Warning: InversionDirective %s has switched to a new inversion.' % self.__name__
self._inversion = i self._inversion = i
@property @property
@@ -79,7 +68,7 @@ class DirectiveList(object):
def inversion(self, i): def inversion(self, i):
if self.inversion is i: return if self.inversion is i: return
if getattr(self,'_inversion',None) is not None: if getattr(self,'_inversion',None) is not None:
print('Warning: %s has switched to a new inversion.' % self.__name__) print 'Warning: %s has switched to a new inversion.' % self.__name__
for d in self.dList: for d in self.dList:
d.inversion = i d.inversion = i
self._inversion = i self._inversion = i
@@ -131,7 +120,7 @@ class BetaEstimate_ByEig(InversionDirective):
:return: beta0 :return: beta0
""" """
if self.debug: print('Calculating the beta0 parameter.') if self.debug: print 'Calculating the beta0 parameter.'
m = self.invProb.curModel m = self.invProb.curModel
f = self.invProb.getFields(m, store=True, deleteWarmstart=False) f = self.invProb.getFields(m, store=True, deleteWarmstart=False)
@@ -152,10 +141,9 @@ class BetaSchedule(InversionDirective):
def endIter(self): def endIter(self):
if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0: if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0:
if self.debug: print('BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter) if self.debug: print 'BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter
self.invProb.beta /= self.coolingFactor self.invProb.beta /= self.coolingFactor
class TargetMisfit(InversionDirective): class TargetMisfit(InversionDirective):
chifact = 1. chifact = 1.
@@ -178,7 +166,7 @@ class TargetMisfit(InversionDirective):
class SaveEveryIteration(InversionDirective): class _SaveEveryIteration(InversionDirective):
@property @property
def name(self): def name(self):
if getattr(self, '_name', None) is None: if getattr(self, '_name', None) is None:
@@ -199,21 +187,21 @@ class SaveEveryIteration(InversionDirective):
self._fileName = value self._fileName = value
class SaveModelEveryIteration(SaveEveryIteration): class SaveModelEveryIteration(_SaveEveryIteration):
"""SaveModelEveryIteration""" """SaveModelEveryIteration"""
def initialize(self): def initialize(self):
print("SimPEG.SaveModelEveryIteration will save your models as: '###-%s.npy'"%self.fileName) print "SimPEG.SaveModelEveryIteration will save your models as: '###-%s.npy'"%self.fileName
def endIter(self): def endIter(self):
np.save('%03d-%s' % (self.opt.iter, self.fileName), self.opt.xc) np.save('%03d-%s' % (self.opt.iter, self.fileName), self.opt.xc)
class SaveOutputEveryIteration(SaveEveryIteration): class SaveOutputEveryIteration(_SaveEveryIteration):
"""SaveModelEveryIteration""" """SaveModelEveryIteration"""
def initialize(self): def initialize(self):
print("SimPEG.SaveOutputEveryIteration will save your inversion progress as: '###-%s.txt'"%self.fileName) print "SimPEG.SaveOutputEveryIteration will save your inversion progress as: '###-%s.txt'"%self.fileName
f = open(self.fileName+'.txt', 'w') f = open(self.fileName+'.txt', 'w')
f.write(" # beta phi_d phi_m f\n") f.write(" # beta phi_d phi_m f\n")
f.close() f.close()
@@ -223,11 +211,11 @@ class SaveOutputEveryIteration(SaveEveryIteration):
f.write(' %3d %1.4e %1.4e %1.4e %1.4e\n'%(self.opt.iter, self.invProb.beta, self.invProb.phi_d, self.invProb.phi_m, self.opt.f)) f.write(' %3d %1.4e %1.4e %1.4e %1.4e\n'%(self.opt.iter, self.invProb.beta, self.invProb.phi_d, self.invProb.phi_m, self.opt.f))
f.close() f.close()
class SaveOutputDictEveryIteration(SaveEveryIteration): class SaveOutputDictEveryIteration(_SaveEveryIteration):
"""SaveOutputDictEveryIteration""" """SaveOutputDictEveryIteration"""
def initialize(self): def initialize(self):
print("SimPEG.SaveOutputDictEveryIteration will save your inversion progress as dictionary: '###-%s.npz'"%self.fileName) print "SimPEG.SaveOutputDictEveryIteration will save your inversion progress as dictionary: '###-%s.npz'"%self.fileName
def endIter(self): def endIter(self):
# Save the data. # Save the data.
@@ -254,6 +242,12 @@ class SaveOutputDictEveryIteration(SaveEveryIteration):
# Save the file as a npz # Save the file as a npz
np.savez('{:03d}-{:s}'.format(self.opt.iter,self.fileName), iter=self.opt.iter, beta=self.invProb.beta, phi_d=self.invProb.phi_d, phi_m=self.invProb.phi_m, phi_ms=phi_ms, phi_mx=phi_mx, phi_my=phi_my, phi_mz=phi_mz,f=self.opt.f, m=self.invProb.curModel,dpred=self.invProb.dpred) np.savez('{:03d}-{:s}'.format(self.opt.iter,self.fileName), iter=self.opt.iter, beta=self.invProb.beta, phi_d=self.invProb.phi_d, phi_m=self.invProb.phi_m, phi_ms=phi_ms, phi_mx=phi_mx, phi_my=phi_my, phi_mz=phi_mz,f=self.opt.f, m=self.invProb.curModel,dpred=self.invProb.dpred)
# class UpdateReferenceModel(Parameter):
# mref0 = None
# def nextIter(self):
# mref = getattr(self, 'm_prev', None) # mref = getattr(self, 'm_prev', None)
# if mref is None: # if mref is None:
# if self.debug: print 'UpdateReferenceModel is using mref0' # if self.debug: print 'UpdateReferenceModel is using mref0'
@@ -264,151 +258,56 @@ class SaveOutputDictEveryIteration(SaveEveryIteration):
class Update_IRLS(InversionDirective): class Update_IRLS(InversionDirective):
eps_min = None eps_min = None
eps = None
norms = [2.,2.,2.,2.]
factor = None factor = None
gamma = None gamma = None
phi_m_last = None phi_m_last = None
phi_d_last = None phi_d_last = None
f_old = None
f_min_change = 1e-2
beta_tol = 5e-2
prctile = 95
# Solving parameter for IRLS (mode:2)
IRLSiter = 0
minGNiter = 5
maxIRLSiter = 10
iterStart = 0
# Beta schedule
coolingFactor = 2.
coolingRate = 1
mode = 1
@property
def target(self):
if getattr(self, '_target', None) is None:
self._target = self.survey.nD*0.5
return self._target
@target.setter
def target(self, val):
self._target = val
def initialize(self): def initialize(self):
if self.mode == 1: # Scale the regularization for changes in norm
self.reg.norms = [2., 2., 2., 2.] if getattr(self, 'phi_m_last', None) is not None:
self.reg.curModel = self.invProb.curModel
self.reg.gamma = 1.
phim_new = self.reg.eval(self.invProb.curModel)
self.gamma = self.phi_m_last / phim_new
self.reg.curModel = self.invProb.curModel
self.reg.gamma = self.gamma
if getattr(self, 'phi_d_last', None) is None:
self.phi_d_last = self.invProb.phi_d
def endIter(self): def endIter(self):
# Cool the threshold parameter if required
if getattr(self, 'factor', None) is not None:
eps = self.reg.eps / self.factor
# After reaching target misfit with l2-norm, switch to IRLS (mode:2) if getattr(self, 'eps_min', None) is not None:
if self.invProb.phi_d < self.target and self.mode == 1: self.reg.eps = np.max([self.eps_min,eps])
print("Convergence with smooth l2-norm regularization: Start IRLS steps...")
self.mode = 2
# Either use the supplied epsilon, or fix base on distribution of
# model values
if getattr(self, 'reg.eps', None) is None:
self.reg.eps_p = np.percentile(np.abs(self.invProb.curModel),self.prctile)
else: else:
self.reg.eps_p = self.eps[0] self.reg.eps = eps
if getattr(self, 'reg.eps', None) is None: # Get phi_m at the end of current iteration
self.reg.eps_q = np.percentile(np.abs(self.reg.regmesh.cellDiffxStencil*(self.reg.mapping * self.invProb.curModel)),self.prctile) self.phi_m_last = self.invProb.phi_m_last
else:
self.reg.eps_q = self.eps[1]
print("L[p qx qy qz]-norm : " + str(self.reg.norms)) # Update the model used for the IRLS weights
print("eps_p: " + str(self.reg.eps_p) + " eps_q: " + str(self.reg.eps_q)) self.reg.curModel = self.invProb.curModel
self.reg.norms = self.norms # Temporarely set gamma to 1. to get raw phi_m
self.coolingFactor = 1. self.reg.gamma = 1.
self.coolingRate = 1
self.iterStart = self.opt.iter
self.phi_d_last = self.invProb.phi_d
self.phi_m_last = self.invProb.phi_m_last
self.reg.l2model = self.invProb.curModel # Compute new model objective function value
self.reg.curModel = self.invProb.curModel phim_new = self.reg.eval(self.invProb.curModel)
if getattr(self, 'f_old', None) is None: # Update gamma to scale the regularization between IRLS iterations
self.f_old = self.reg.eval(self.invProb.curModel)#self.invProb.evalFunction(self.invProb.curModel, return_g=False, return_H=False) self.reg.gamma = self.phi_m_last / phim_new
# Beta Schedule # Set the weighting matrix to None so that it is recomputed next time
if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0: # it is called in the inversion
if self.debug: print('BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter) self.reg._W = None
self.invProb.beta /= self.coolingFactor
# Only update after GN iterations
if (self.opt.iter-self.iterStart) % self.minGNiter == 0 and self.mode==2:
self.IRLSiter += 1
phim_new = self.reg.eval(self.invProb.curModel)
self.f_change = np.abs(self.f_old - phim_new) / self.f_old
print("Regularization decrease: %6.3e" % (self.f_change))
# Check for maximum number of IRLS cycles
if self.IRLSiter == self.maxIRLSiter:
print("Reach maximum number of IRLS cycles: %i" % self.maxIRLSiter)
self.opt.stopNextIteration = True
return
# Check if the function has changed enough
if self.f_change < self.f_min_change and self.IRLSiter > 1:
print("Minimum decrease in regularization. End of IRLS")
self.opt.stopNextIteration = True
return
else:
self.f_old = phim_new
# # Cool the threshold parameter if required
# if getattr(self, 'factor', None) is not None:
# eps = self.reg.eps / self.factor
#
# if getattr(self, 'eps_min', None) is not None:
# self.reg.eps = np.max([self.eps_min,eps])
# else:
# self.reg.eps = eps
# Get phi_m at the end of current iteration
self.phi_m_last = self.invProb.phi_m_last
# Reset the regularization matrices so that it is
# recalculated for current model
self.reg._Wsmall = None
self.reg._Wx = None
self.reg._Wy = None
self.reg._Wz = None
# Update the model used for the IRLS weights
self.reg.curModel = self.invProb.curModel
# Temporarely set gamma to 1. to get raw phi_m
self.reg.gamma = 1.
# Compute new model objective function value
phim_new = self.reg.eval(self.invProb.curModel)
# Update gamma to scale the regularization between IRLS iterations
self.reg.gamma = self.phi_m_last / phim_new
# Reset the regularization matrices again for new gamma
self.reg._Wsmall = None
self.reg._Wx = None
self.reg._Wy = None
self.reg._Wz = None
# Check if misfit is within the tolerance, otherwise scale beta
val = self.invProb.phi_d / (self.survey.nD*0.5)
if np.abs(1.-val) > self.beta_tol:
self.invProb.beta = self.invProb.beta * self.survey.nD*0.5 / self.invProb.phi_d
class Update_lin_PreCond(InversionDirective): class Update_lin_PreCond(InversionDirective):
""" """
@@ -461,3 +360,19 @@ class Update_Wj(InversionDirective):
JtJdiag = JtJdiag / max(JtJdiag) JtJdiag = JtJdiag / max(JtJdiag)
self.reg.wght = JtJdiag self.reg.wght = JtJdiag
class Scale_Beta(InversionDirective):
"""
Instead of a linear cooling schedule, beta is allowed to change based
on the ratio between the target misfit and the current data misfit. The
update is done only if the misfit is outside some threshold bounds.
"""
tol = 0.05
def endIter(self):
# Check if misfit is within the tolerance, otherwise adjust beta
val = self.invProb.phi_d / (self.survey.nD*0.5)
if np.abs(1.-val) > self.tol:
self.invProb.beta = self.invProb.beta * self.survey.nD*0.5 / self.invProb.phi_d
-7
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
import numpy as np import numpy as np
from scipy.constants import mu_0, pi from scipy.constants import mu_0, pi
from scipy import special from scipy import special
-5
View File
@@ -1,9 +1,4 @@
from __future__ import division from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np import numpy as np
from scipy.constants import mu_0, pi from scipy.constants import mu_0, pi
from scipy.special import erf from scipy.special import erf
-307
View File
@@ -1,307 +0,0 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
from scipy.special import erf
from SimPEG import Utils
omega = lambda f: 2.*np.pi*f
# TODO:
# r = lambda dx, dy, dz: np.sqrt( dx**2. + dy**2. + dz**2.)
# k = lambda f, mu, epsilon, sig: np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
def E_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=0., epsr=1.):
"""
Computing Analytic Electric fields from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
mu = mu_0*(1+kappa)
epsilon = epsilon_0*epsr
sig_hat = sig + 1j*omega(f)*epsilon
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & f.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
dx = XYZ[:,0]-srcLoc[0]
dy = XYZ[:,1]-srcLoc[1]
dz = XYZ[:,2]-srcLoc[2]
r = np.sqrt( dx**2. + dy**2. + dz**2.)
# k = np.sqrt( -1j*2.*np.pi*f*mu*sig )
k = np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
front = current * length / (4.*np.pi*sig_hat* r**3) * np.exp(-1j*k*r)
mid = -k**2 * r**2 + 3*1j*k*r + 3
if orientation.upper() == 'X':
Ex = front*((dx**2 / r**2)*mid + (k**2 * r**2 -1j*k*r-1.))
Ey = front*(dx*dy / r**2)*mid
Ez = front*(dx*dz / r**2)*mid
return Ex, Ey, Ez
elif orientation.upper() == 'Y':
# x--> y, y--> z, z-->x
Ey = front*((dy**2 / r**2)*mid + (k**2 * r**2 -1j*k*r-1.))
Ez = front*(dy*dz / r**2)*mid
Ex = front*(dy*dx / r**2)*mid
return Ex, Ey, Ez
elif orientation.upper() == 'Z':
# x --> z, y --> x, z --> y
Ez = front*((dz**2 / r**2)*mid + (k**2 * r**2 -1j*k*r-1.))
Ex = front*(dz*dx / r**2)*mid
Ey = front*(dz*dy / r**2)*mid
return Ex, Ey, Ez
def E_galvanic_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Galvanic portion of Electric fields from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
mu = mu_0*(1+kappa)
epsilon = epsilon_0*epsr
sig_hat = sig + 1j*omega(f)*epsilon
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & f.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
dx = XYZ[:,0]-srcLoc[0]
dy = XYZ[:,1]-srcLoc[1]
dz = XYZ[:,2]-srcLoc[2]
r = np.sqrt( dx**2. + dy**2. + dz**2.)
# k = np.sqrt( -1j*2.*np.pi*f*mu*sig )
k = np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
front = current * length / (4.*np.pi*sig_hat* r**3) * np.exp(-1j*k*r)
mid = -k**2 * r**2 + 3*1j*k*r + 3
if orientation.upper() == 'X':
Ex_galvanic = front*((dx**2 / r**2)*mid + (-1j*k*r-1.))
Ey_galvanic = front*(dx*dy / r**2)*mid
Ez_galvanic = front*(dx*dz / r**2)*mid
return Ex_galvanic, Ey_galvanic, Ez_galvanic
elif orientation.upper() == 'Y':
# x--> y, y--> z, z-->x
Ey_galvanic = front*((dy**2 / r**2)*mid + (-1j*k*r-1.))
Ez_galvanic = front*(dy*dz / r**2)*mid
Ex_galvanic = front*(dy*dx / r**2)*mid
return Ex_galvanic, Ey_galvanic, Ez_galvanic
elif orientation.upper() == 'Z':
# x --> z, y --> x, z --> y
Ez_galvanic = front*((dz**2 / r**2)*mid + (-1j*k*r-1.))
Ex_galvanic = front*(dz*dx / r**2)*mid
Ey_galvanic = front*(dz*dy / r**2)*mid
return Ex_galvanic, Ey_galvanic, Ez_galvanic
def E_inductive_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Inductive portion of Electric fields from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
mu = mu_0*(1+kappa)
epsilon = epsilon_0*epsr
sig_hat = sig + 1j*omega(f)*epsilon
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & f.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
dx = XYZ[:,0]-srcLoc[0]
dy = XYZ[:,1]-srcLoc[1]
dz = XYZ[:,2]-srcLoc[2]
r = np.sqrt( dx**2. + dy**2. + dz**2.)
# k = np.sqrt( -1j*2.*np.pi*f*mu*sig )
k = np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
front = current * length / (4.*np.pi*sig_hat* r**3) * np.exp(-1j*k*r)
if orientation.upper() == 'X':
Ex_inductive = front*(k**2 * r**2)
Ey_inductive = np.zeros_like(Ex_inductive)
Ez_inductive = np.zeros_like(Ex_inductive)
return Ex_inductive, Ey_inductive, Ez_inductive
elif orientation.upper() == 'Y':
# x--> y, y--> z, z-->x
Ey_inductive = front*(k**2 * r**2)
Ez_inductive = np.zeros_like(Ey_inductive)
Ex_inductive = np.zeros_like(Ey_inductive)
return Ex_inductive, Ey_inductive, Ez_inductive
elif orientation.upper() == 'Z':
# x --> z, y --> x, z --> y
Ez_inductive = front*(k**2 * r**2)
Ex_inductive = np.zeros_like(Ez_inductive)
Ey_inductive = np.zeros_like(Ez_inductive)
return Ex_inductive, Ey_inductive, Ez_inductive
def J_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Current densities from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
Ex, Ey, Ez = E_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=current, length=length, orientation=orientation, kappa=kappa, epsr=epsr)
Jx = sig*Ex
Jy = sig*Ey
Jz = sig*Ez
return Jx, Jy, Jz
def J_galvanic_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Galvanic portion of Current densities from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
Ex_galvanic, Ey_galvanic, Ez_galvanic = E_galvanic_from_ElectricDipoleWholeSpaced(XYZ, srcLoc, sig, f, current=current, length=length, orientation=orientation, kappa=kappa, epsr=epsr)
Jx_galvanic = sig*Ex_galvanic
Jy_galvanic = sig*Ey_galvanic
Jz_galvanic = sig*Ez_galvanic
return Jx_galvanic, Jy_galvanic, Jz_galvanic
def J_inductive_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Inductive portion of Current densities from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
Ex_inductive, Ey_inductive, Ez_inductive = E_inductive_from_ElectricDipoleWholeSpaced(XYZ, srcLoc, sig, f, current=current, length=length, orientation=orientation, kappa=kappa, epsr=epsr)
Jx_inductive = sig*Ex_inductive
Jy_inductive = sig*Ey_inductive
Jz_inductive = sig*Ez_inductive
return Jx_inductive, Jy_inductive, Jz_inductive
def H_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Magnetic fields from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
mu = mu_0*(1+kappa)
epsilon = epsilon_0*epsr
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & f.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
dx = XYZ[:,0]-srcLoc[0]
dy = XYZ[:,1]-srcLoc[1]
dz = XYZ[:,2]-srcLoc[2]
r = np.sqrt( dx**2. + dy**2. + dz**2.)
# k = np.sqrt( -1j*2.*np.pi*f*mu*sig )
k = np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
front = current * length / (4.*np.pi* r**2) * (-1j*k*r + 1) * np.exp(-1j*k*r)
if orientation.upper() == 'X':
Hy = front*(-dz / r)
Hz = front*(dy / r)
Hx = np.zeros_like(Hy)
return Hx, Hy, Hz
elif orientation.upper() == 'Y':
Hx = front*(dz / r)
Hz = front*(-dx / r)
Hy = np.zeros_like(Hx)
return Hx, Hy, Hz
elif orientation.upper() == 'Z':
Hx = front*(-dy / r)
Hy = front*(dx / r)
Hz = np.zeros_like(Hx)
return Hx, Hy, Hz
def B_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Magnetic flux densites from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
Hx, Hy, Hz = H_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=current, length=length, orientation=orientation, kappa=kappa, epsr=epsr)
Bx = mu*Hx
By = mu*Hy
Bz = mu*Hz
return Bx, By, Bz
def A_from_ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', kappa=1., epsr=1.):
"""
Computing Electric vector potentials from Electrical Dipole in a Wholespace
TODO:
Add description of parameters
"""
mu = mu_0*(1+kappa)
epsilon = epsilon_0*epsr
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
# Check
if XYZ.shape[0] > 1 & f.shape[0] > 1:
raise Exception("I/O type error: For multiple field locations only a single frequency can be specified.")
dx = XYZ[:,0]-srcLoc[0]
dy = XYZ[:,1]-srcLoc[1]
dz = XYZ[:,2]-srcLoc[2]
r = np.sqrt( dx**2. + dy**2. + dz**2.)
k = np.sqrt( omega(f)**2. *mu*epsilon -1j*omega(f)*mu*sig )
front = current * length / (4.*np.pi*r)
if orientation.upper() == 'X':
Ax = front*np.exp(-1j*k*r)
Ay = np.zeros_like(Ax)
Az = np.zeros_like(Ax)
return Ax, Ay, Az
elif orientation.upper() == 'Y':
Ay = front*np.exp(-1j*k*r)
Ax = np.zeros_like(Ay)
Az = np.zeros_like(Ay)
return Ax, Ay, Az
elif orientation.upper() == 'Z':
Az = front*np.exp(-1j*k*r)
Ax = np.zeros_like(Ay)
Ay = np.zeros_like(Ay)
return Ax, Ay, Az
+1 -7
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Utils, np from SimPEG import Utils, np
from scipy.constants import mu_0, epsilon_0 from scipy.constants import mu_0, epsilon_0
from SimPEG.EM.Utils.EMUtils import k from SimPEG.EM.Utils.EMUtils import k
@@ -40,7 +34,7 @@ def _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones
sqrtr2z2 = np.sqrt(r2 + dxyz[:,2]**2) sqrtr2z2 = np.sqrt(r2 + dxyz[:,2]**2)
k2 = k(freq,sigma[2],mu[2],eps) k2 = k(freq,sigma[2],mu[2],eps)
return -HertzZ * np.sqrt(r2) / sqrtr2z2 * (1j*k2 + 1. / sqrtr2z2) return -HertzZ * np.sqrt(r2) / sqrtr2z2 * (1j*k2 + 1./ sqrtr2z2)
def _getCasingHertzMagDipoleDeriv_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.): def _getCasingHertzMagDipoleDeriv_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
-6
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np import numpy as np
from scipy.constants import mu_0, pi from scipy.constants import mu_0, pi
from scipy.special import erf from scipy.special import erf
+4 -11
View File
@@ -1,11 +1,4 @@
from __future__ import absolute_import from TDEM import hzAnalyticDipoleT
from __future__ import unicode_literals from FDEM import hzAnalyticDipoleF
from __future__ import print_function from FDEMcasing import *
from __future__ import division from DC import DCAnalyticHalf, DCAnalyticSphere
from future import standard_library
standard_library.install_aliases()
from .TDEM import hzAnalyticDipoleT
from .FDEM import hzAnalyticDipoleF
from .FDEMcasing import *
from .DC import DCAnalyticHalf, DCAnalyticSphere
from .FDEMDipolarfields import *
+3 -10
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Survey, Problem, Utils, Models, Maps, PropMaps, np, sp, Solver as SimpegSolver from SimPEG import Survey, Problem, Utils, Models, Maps, PropMaps, np, sp, Solver as SimpegSolver
from scipy.constants import mu_0 from scipy.constants import mu_0
@@ -26,10 +20,10 @@ class BaseEMProblem(Problem.BaseProblem):
Problem.BaseProblem.__init__(self, mesh, **kwargs) Problem.BaseProblem.__init__(self, mesh, **kwargs)
surveyPair = Survey.BaseSurvey #: The survey to pair with. surveyPair = Survey.BaseSurvey
dataPair = Survey.Data #: The data to pair with. dataPair = Survey.Data
PropMap = EMPropMap #: The property mapping PropMap = EMPropMap
Solver = SimpegSolver Solver = SimpegSolver
solverOpts = {} solverOpts = {}
@@ -223,7 +217,6 @@ class BaseEMSurvey(Survey.BaseSurvey):
def eval(self, f): def eval(self, f):
""" """
Project fields to receiver locations Project fields to receiver locations
:param Fields u: fields object :param Fields u: fields object
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: data :return: data
+62 -57
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
import numpy as np import numpy as np
import scipy.sparse as sp import scipy.sparse as sp
import SimPEG import SimPEG
@@ -13,11 +6,11 @@ from SimPEG.EM.Utils import omega
from SimPEG.Utils import Zero, Identity, sdiag from SimPEG.Utils import Zero, Identity, sdiag
class FieldsFDEM(SimPEG.Problem.Fields): class Fields(SimPEG.Problem.Fields):
""" """
Fancy Field Storage for a FDEM survey. Only one field type is stored for Fancy Field Storage for a FDEM survey. Only one field type is stored for
each problem, the rest are computed. The fields object acts like an array and is indexed by each problem, the rest are computed. The fields obejct acts like an array and is indexed by
.. code-block:: python .. code-block:: python
@@ -49,7 +42,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: total electric field :return: total electric field
""" """
if getattr(self, '_ePrimary', None) is None or getattr(self, '_eSecondary', None) is None: if getattr(self, '_ePrimary', None) is None or getattr(self, '_eSecondary', None) is None:
raise NotImplementedError ('Getting e from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting e from %s is not implemented' %self.knownFields.keys()[0])
return self._ePrimary(solution,srcList) + self._eSecondary(solution,srcList) return self._ePrimary(solution,srcList) + self._eSecondary(solution,srcList)
@@ -63,7 +56,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: total magnetic flux density :return: total magnetic flux density
""" """
if getattr(self, '_bPrimary', None) is None or getattr(self, '_bSecondary', None) is None: if getattr(self, '_bPrimary', None) is None or getattr(self, '_bSecondary', None) is None:
raise NotImplementedError ('Getting b from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting b from %s is not implemented' %self.knownFields.keys()[0])
return self._bPrimary(solution, srcList) + self._bSecondary(solution, srcList) return self._bPrimary(solution, srcList) + self._bSecondary(solution, srcList)
@@ -77,7 +70,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: total magnetic field :return: total magnetic field
""" """
if getattr(self, '_hPrimary', None) is None or getattr(self, '_hSecondary', None) is None: if getattr(self, '_hPrimary', None) is None or getattr(self, '_hSecondary', None) is None:
raise NotImplementedError ('Getting h from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting h from %s is not implemented' %self.knownFields.keys()[0])
return self._hPrimary(solution, srcList) + self._hSecondary(solution, srcList) return self._hPrimary(solution, srcList) + self._hSecondary(solution, srcList)
@@ -91,7 +84,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: total current density :return: total current density
""" """
if getattr(self, '_jPrimary', None) is None or getattr(self, '_jSecondary', None) is None: if getattr(self, '_jPrimary', None) is None or getattr(self, '_jSecondary', None) is None:
raise NotImplementedError ('Getting j from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting j from %s is not implemented' %self.knownFields.keys()[0])
return self._jPrimary(solution, srcList) + self._jSecondary(solution, srcList) return self._jPrimary(solution, srcList) + self._jSecondary(solution, srcList)
@@ -99,7 +92,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
""" """
Total derivative of e with respect to the inversion model. Returns :math:`d\mathbf{e}/d\mathbf{m}` for forward and (:math:`d\mathbf{e}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint Total derivative of e with respect to the inversion model. Returns :math:`d\mathbf{e}/d\mathbf{m}` for forward and (:math:`d\mathbf{e}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: source :param Src src: sorce
:param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint) :param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint)
:param numpy.ndarray v: vector to take sensitivity product with :param numpy.ndarray v: vector to take sensitivity product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
@@ -107,7 +100,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: derivative times a vector (or tuple for adjoint) :return: derivative times a vector (or tuple for adjoint)
""" """
if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None:
raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint)
@@ -117,7 +110,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
""" """
Total derivative of b with respect to the inversion model. Returns :math:`d\mathbf{b}/d\mathbf{m}` for forward and (:math:`d\mathbf{b}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint Total derivative of b with respect to the inversion model. Returns :math:`d\mathbf{b}/d\mathbf{m}` for forward and (:math:`d\mathbf{b}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: source :param Src src: sorce
:param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint) :param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint)
:param numpy.ndarray v: vector to take sensitivity product with :param numpy.ndarray v: vector to take sensitivity product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
@@ -125,7 +118,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: derivative times a vector (or tuple for adjoint) :return: derivative times a vector (or tuple for adjoint)
""" """
if getattr(self, '_bDeriv_u', None) is None or getattr(self, '_bDeriv_m', None) is None: if getattr(self, '_bDeriv_u', None) is None or getattr(self, '_bDeriv_m', None) is None:
raise NotImplementedError ('Getting bDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting bDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._bDeriv_u(src, v, adjoint), self._bDeriv_m(src, v, adjoint) return self._bDeriv_u(src, v, adjoint), self._bDeriv_m(src, v, adjoint)
@@ -135,7 +128,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
""" """
Total derivative of h with respect to the inversion model. Returns :math:`d\mathbf{h}/d\mathbf{m}` for forward and (:math:`d\mathbf{h}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint Total derivative of h with respect to the inversion model. Returns :math:`d\mathbf{h}/d\mathbf{m}` for forward and (:math:`d\mathbf{h}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: source :param Src src: sorce
:param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint) :param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint)
:param numpy.ndarray v: vector to take sensitivity product with :param numpy.ndarray v: vector to take sensitivity product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
@@ -143,7 +136,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: derivative times a vector (or tuple for adjoint) :return: derivative times a vector (or tuple for adjoint)
""" """
if getattr(self, '_hDeriv_u', None) is None or getattr(self, '_hDeriv_m', None) is None: if getattr(self, '_hDeriv_u', None) is None or getattr(self, '_hDeriv_m', None) is None:
raise NotImplementedError ('Getting hDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting hDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._hDeriv_u(src, v, adjoint), self._hDeriv_m(src, v, adjoint) return self._hDeriv_u(src, v, adjoint), self._hDeriv_m(src, v, adjoint)
@@ -153,7 +146,7 @@ class FieldsFDEM(SimPEG.Problem.Fields):
""" """
Total derivative of j with respect to the inversion model. Returns :math:`d\mathbf{j}/d\mathbf{m}` for forward and (:math:`d\mathbf{j}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint Total derivative of j with respect to the inversion model. Returns :math:`d\mathbf{j}/d\mathbf{m}` for forward and (:math:`d\mathbf{j}/d\mathbf{u}`, :math:`d\mathb{u}/d\mathbf{m}`) for the adjoint
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: source :param Src src: sorce
:param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint) :param numpy.ndarray du_dm_v: derivative of the solution vector with respect to the model times a vector (is None for adjoint)
:param numpy.ndarray v: vector to take sensitivity product with :param numpy.ndarray v: vector to take sensitivity product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
@@ -161,18 +154,18 @@ class FieldsFDEM(SimPEG.Problem.Fields):
:return: derivative times a vector (or tuple for adjoint) :return: derivative times a vector (or tuple for adjoint)
""" """
if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None:
raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint) return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint)
return np.array(self._jDeriv_u(src, du_dm_v, adjoint) + self._jDeriv_m(src, v, adjoint), dtype = complex) return np.array(self._jDeriv_u(src, du_dm_v, adjoint) + self._jDeriv_m(src, v, adjoint), dtype = complex)
class Fields3D_e(FieldsFDEM): class Fields3D_e(Fields):
""" """
Fields object for Problem3D_e. Fields object for Problem3D_e.
:param BaseMesh mesh: mesh :param Mesh mesh: mesh
:param SimPEG.EM.FDEM.SurveyFDEM.Survey survey: survey :param Survey survey: survey
""" """
knownFields = {'eSolution':'E'} knownFields = {'eSolution':'E'}
@@ -187,6 +180,9 @@ class Fields3D_e(FieldsFDEM):
'h' : ['eSolution','CCV','_h'], 'h' : ['eSolution','CCV','_h'],
} }
def __init__(self, mesh, survey, **kwargs):
Fields.__init__(self, mesh, survey, **kwargs)
def startup(self): def startup(self):
self.prob = self.survey.prob self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl self._edgeCurl = self.survey.prob.mesh.edgeCurl
@@ -261,7 +257,7 @@ class Fields3D_e(FieldsFDEM):
""" """
# assuming primary does not depend on the model # assuming primary does not depend on the model
return Zero() return src.ePrimaryDeriv(self.prob, v, adjoint) #Zero()
def _bPrimary(self, eSolution, srcList): def _bPrimary(self, eSolution, srcList):
""" """
@@ -292,7 +288,7 @@ class Fields3D_e(FieldsFDEM):
C = self._edgeCurl C = self._edgeCurl
b = (C * eSolution) b = (C * eSolution)
for i, src in enumerate(srcList): for i, src in enumerate(srcList):
b[:,i] *= -1./(1j*omega(src.freq)) b[:,i] *= - 1./(1j*omega(src.freq))
s_m, _ = src.eval(self.prob) s_m, _ = src.eval(self.prob)
b[:,i] = b[:,i]+ 1./(1j*omega(src.freq)) * s_m b[:,i] = b[:,i]+ 1./(1j*omega(src.freq)) * s_m
return b return b
@@ -352,7 +348,7 @@ class Fields3D_e(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the current density with respect to the field we solved for with a vector :return: product of the derivative of the current density with respect to the field we solved for with a vector
""" """
n = int(self._aveE2CCV.shape[0] // self._nC) # number of components (instead of checking if cyl or not) n = int(self._aveE2CCV.shape[0] / self._nC) # number of components (instead of checking if cyl or not)
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
@@ -389,8 +385,8 @@ class Fields3D_e(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: magnetic field :return: magnetic field
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # Number of Components n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components
VI = sdiag(np.kron(np.ones(n), 1. // self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveF2CCV * (self._MfMui * self._b(eSolution, srcList))) return VI * (self._aveF2CCV * (self._MfMui * self._b(eSolution, srcList)))
@@ -404,7 +400,7 @@ class Fields3D_e(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the magnetic field with respect to the field we solved for with a vector :return: product of the derivative of the magnetic field with respect to the field we solved for with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # Number of Components n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * du_dm_v)) v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * du_dm_v))
@@ -421,7 +417,7 @@ class Fields3D_e(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the magnetic field derivative with respect to the inversion model with a vector :return: product of the magnetic field derivative with respect to the inversion model with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # Number of Components n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * v)) v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * v))
@@ -430,12 +426,12 @@ class Fields3D_e(FieldsFDEM):
class Fields3D_b(FieldsFDEM): class Fields3D_b(Fields):
""" """
Fields object for Problem3D_b. Fields object for Problem3D_b.
:param BaseMesh mesh: mesh :param Mesh mesh: mesh
:param SimPEG.EM.FDEM.SurveyFDEM.Survey survey: survey :param Survey survey: survey
""" """
knownFields = {'bSolution':'F'} knownFields = {'bSolution':'F'}
@@ -450,6 +446,9 @@ class Fields3D_b(FieldsFDEM):
'h' : ['bSolution','CCV','_h'], 'h' : ['bSolution','CCV','_h'],
} }
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self): def startup(self):
self.prob = self.survey.prob self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl self._edgeCurl = self.survey.prob.mesh.edgeCurl
@@ -601,8 +600,8 @@ class Fields3D_b(FieldsFDEM):
if adjoint: if adjoint:
return self._MeSigmaIDeriv(w).T * v - self._MeSigmaI.T * s_eDeriv return self._MeSigmaIDeriv(w).T * v - self._MeSigmaI.T * s_eDeriv + src.ePrimaryDeriv(self.prob, v, adjoint)
return self._MeSigmaIDeriv(w) * v - self._MeSigmaI * s_eDeriv return self._MeSigmaIDeriv(w) * v - self._MeSigmaI * s_eDeriv + src.ePrimaryDeriv(self.prob, v, adjoint)
def _j(self, bSolution, srcList): def _j(self, bSolution, srcList):
""" """
@@ -614,7 +613,7 @@ class Fields3D_b(FieldsFDEM):
:return: primary current density :return: primary current density
""" """
n = int(self._aveE2CCV.shape[0] // self._nC) # number of components n = int(self._aveE2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveE2CCV * ( self._MeSigma * self._e(bSolution,srcList ) ) ) return VI * (self._aveE2CCV * ( self._MeSigma * self._e(bSolution,srcList ) ) )
@@ -631,7 +630,7 @@ class Fields3D_b(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the current density with respect to the field we solved for with a vector :return: product of the derivative of the current density with respect to the field we solved for with a vector
""" """
n = int(self._aveE2CCV.shape[0] // self._nC) # number of components n = int(self._aveE2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return self._MfMui.T * ( self._edgeCurl * ( self._aveE2CCV.T * (VI.T * du_dm_v) ) ) return self._MfMui.T * ( self._edgeCurl * ( self._aveE2CCV.T * (VI.T * du_dm_v) ) )
@@ -659,7 +658,7 @@ class Fields3D_b(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: magnetic field :return: magnetic field
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) #number of components n = int(self._aveF2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveF2CCV * (self._MfMui * self._b(bSolution, srcList))) return VI * (self._aveF2CCV * (self._MfMui * self._b(bSolution, srcList)))
@@ -674,7 +673,7 @@ class Fields3D_b(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the magnetic field with respect to the field we solved for with a vector :return: product of the derivative of the magnetic field with respect to the field we solved for with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) #number of components n = int(self._aveF2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
@@ -694,12 +693,12 @@ class Fields3D_b(FieldsFDEM):
return Zero() return Zero()
class Fields3D_j(FieldsFDEM): class Fields3D_j(Fields):
""" """
Fields object for Problem3D_j. Fields object for Problem3D_j.
:param BaseMesh mesh: mesh :param Mesh mesh: mesh
:param SimPEG.EM.FDEM.SurveyFDEM.Survey survey: survey :param Survey survey: survey
""" """
knownFields = {'jSolution':'F'} knownFields = {'jSolution':'F'}
@@ -714,6 +713,9 @@ class Fields3D_j(FieldsFDEM):
'b' : ['jSolution','CCV','_b'], 'b' : ['jSolution','CCV','_b'],
} }
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self): def startup(self):
self.prob = self.survey.prob self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl self._edgeCurl = self.survey.prob.mesh.edgeCurl
@@ -897,7 +899,7 @@ class Fields3D_j(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: electric field :return: electric field
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # number of components n = int(self._aveF2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveF2CCV * (self._MfRho * self._j(jSolution, srcList))) return VI * (self._aveF2CCV * (self._MfRho * self._j(jSolution, srcList)))
@@ -911,7 +913,7 @@ class Fields3D_j(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the electric field with respect to the field we solved for with a vector :return: product of the derivative of the electric field with respect to the field we solved for with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # number of components n = int(self._aveF2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) ) return self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) )
@@ -928,7 +930,7 @@ class Fields3D_j(FieldsFDEM):
:return: product of the derivative of the electric field with respect to the model with a vector :return: product of the derivative of the electric field with respect to the model with a vector
""" """
jSolution = Utils.mkvc(self[src,'jSolution']) jSolution = Utils.mkvc(self[src,'jSolution'])
n = int(self._aveF2CCV.shape[0] // self._nC) # number of components n = int(self._aveF2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return self._MfRhoDeriv(jSolution).T * ( self._aveF2CCV.T * ( VI.T * v ) ) return self._MfRhoDeriv(jSolution).T * ( self._aveF2CCV.T * ( VI.T * v ) )
@@ -943,7 +945,7 @@ class Fields3D_j(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: secondary magnetic flux density :return: secondary magnetic flux density
""" """
n = int(self._aveE2CCV.shape[0] // self._nC) # number of components n = int(self._aveE2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveE2CCV * ( self._MeMu * self._h(jSolution,srcList)) ) return VI * (self._aveE2CCV * ( self._MeMu * self._h(jSolution,srcList)) )
@@ -958,7 +960,7 @@ class Fields3D_j(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector :return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) # number of components n = int(self._aveF2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
@@ -976,7 +978,7 @@ class Fields3D_j(FieldsFDEM):
:return: product of the derivative of the magnetic flux density with respect to the model with a vector :return: product of the derivative of the magnetic flux density with respect to the model with a vector
""" """
jSolution = self[src,'jSolution'] jSolution = self[src,'jSolution']
n = int(self._aveE2CCV.shape[0] // self._nC) # number of components n = int(self._aveE2CCV.shape[0] / self._nC) # number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
s_mDeriv,_ = src.evalDeriv(self.prob, adjoint = adjoint) s_mDeriv,_ = src.evalDeriv(self.prob, adjoint = adjoint)
@@ -986,12 +988,12 @@ class Fields3D_j(FieldsFDEM):
return 1./(1j * omega(src.freq)) * VI * (self._aveE2CCV * ( s_mDeriv(v) - self._edgeCurl.T * ( self._MfRhoDeriv(jSolution) * v ) ) ) return 1./(1j * omega(src.freq)) * VI * (self._aveE2CCV * ( s_mDeriv(v) - self._edgeCurl.T * ( self._MfRhoDeriv(jSolution) * v ) ) )
class Fields3D_h(FieldsFDEM): class Fields3D_h(Fields):
""" """
Fields object for Problem3D_h. Fields object for Problem3D_h.
:param BaseMesh mesh: mesh :param Mesh mesh: mesh
:param SimPEG.EM.FDEM.SurveyFDEM.Survey survey: survey :param Survey survey: survey
""" """
knownFields = {'hSolution':'E'} knownFields = {'hSolution':'E'}
@@ -1006,6 +1008,9 @@ class Fields3D_h(FieldsFDEM):
'b' : ['hSolution','CCV','_b'], 'b' : ['hSolution','CCV','_b'],
} }
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self): def startup(self):
self.prob = self.survey.prob self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl self._edgeCurl = self.survey.prob.mesh.edgeCurl
@@ -1158,7 +1163,7 @@ class Fields3D_h(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: electric field :return: electric field
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) #number of components n = int(self._aveF2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveF2CCV * (self._MfRho * self._j(hSolution, srcList))) return VI * (self._aveF2CCV * (self._MfRho * self._j(hSolution, srcList)))
@@ -1172,7 +1177,7 @@ class Fields3D_h(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the electric field with respect to the field we solved for with a vector :return: product of the derivative of the electric field with respect to the field we solved for with a vector
""" """
n = int(self._aveF2CCV.shape[0] // self._nC) #number of components n = int(self._aveF2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return self._edgeCurl.T * ( self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) ) ) return self._edgeCurl.T * ( self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) ) )
@@ -1189,7 +1194,7 @@ class Fields3D_h(FieldsFDEM):
:return: product of the electric field derivative with respect to the inversion model with a vector :return: product of the electric field derivative with respect to the inversion model with a vector
""" """
hSolution = Utils.mkvc(self[src,'hSolution']) hSolution = Utils.mkvc(self[src,'hSolution'])
n = int(self._aveF2CCV.shape[0] // self._nC) #number of components n = int(self._aveF2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return ( self._MfRhoDeriv(self._edgeCurl * hSolution).T * ( self._aveF2CCV.T * (VI.T * v) ) ) return ( self._MfRhoDeriv(self._edgeCurl * hSolution).T * ( self._aveF2CCV.T * (VI.T * v) ) )
@@ -1205,7 +1210,7 @@ class Fields3D_h(FieldsFDEM):
:return: magnetic flux density :return: magnetic flux density
""" """
h = self._h(hSolution, srcList) h = self._h(hSolution, srcList)
n = int(self._aveE2CCV.shape[0] // self._nC) #number of components n = int(self._aveE2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
return VI * (self._aveE2CCV * (self._MeMu * h)) return VI * (self._aveE2CCV * (self._MeMu * h))
@@ -1220,7 +1225,7 @@ class Fields3D_h(FieldsFDEM):
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector :return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector
""" """
n = int(self._aveE2CCV.shape[0] // self._nC) #number of components n = int(self._aveE2CCV.shape[0] / self._nC) #number of components
VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol))
if adjoint: if adjoint:
return self._MeMu.T * (self._aveE2CCV.T * ( VI.T * du_dm_v )) return self._MeMu.T * (self._aveE2CCV.T * ( VI.T * du_dm_v ))
+21 -32
View File
@@ -1,13 +1,7 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from SimPEG import Problem, Utils, np, sp, Solver as SimpegSolver from SimPEG import Problem, Utils, np, sp, Solver as SimpegSolver
from scipy.constants import mu_0 from scipy.constants import mu_0
from .SurveyFDEM import Survey as SurveyFDEM from SurveyFDEM import Survey as SurveyFDEM
from .FieldsFDEM import FieldsFDEM, Fields3D_e, Fields3D_b, Fields3D_h, Fields3D_j from FieldsFDEM import Fields, Fields3D_e, Fields3D_b, Fields3D_h, Fields3D_j
from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Base import BaseEMProblem
from SimPEG.EM.Utils import omega from SimPEG.EM.Utils import omega
@@ -37,11 +31,10 @@ class BaseFDEMProblem(BaseEMProblem):
if using the H-J formulation (:code:`Problem3D_j` or :code:`Problem3D_h`). Note that here, :math:`\mathbf{s_m}` is an integrated quantity. if using the H-J formulation (:code:`Problem3D_j` or :code:`Problem3D_h`). Note that here, :math:`\mathbf{s_m}` is an integrated quantity.
The problem performs the elimination so that we are solving the system for \\\(\\\mathbf{e},\\\mathbf{b},\\\mathbf{j} \\\) or \\\(\\\mathbf{h}\\\) The problem performs the elimination so that we are solving the system for \\\(\\\mathbf{e},\\\mathbf{b},\\\mathbf{j} \\\) or \\\(\\\mathbf{h}\\\)
""" """
surveyPair = SurveyFDEM surveyPair = SurveyFDEM
fieldsPair = FieldsFDEM fieldsPair = Fields
def fields(self, m): def fields(self, m):
""" """
@@ -71,7 +64,7 @@ class BaseFDEMProblem(BaseEMProblem):
:param numpy.array m: inversion model (nP,) :param numpy.array m: inversion model (nP,)
:param numpy.array v: vector which we take sensitivity product with (nP,) :param numpy.array v: vector which we take sensitivity product with (nP,)
:param SimPEG.EM.FDEM.FieldsFDEM.FieldsFDEM u: fields object :param SimPEG.EM.FDEM.Fields u: fields object
:rtype numpy.array: :rtype numpy.array:
:return: Jv (ndata,) :return: Jv (ndata,)
""" """
@@ -81,7 +74,8 @@ class BaseFDEMProblem(BaseEMProblem):
self.curModel = m self.curModel = m
Jv = self.dataPair(self.survey) # Jv = self.dataPair(self.survey)
Jv = []
for freq in self.survey.freqs: for freq in self.survey.freqs:
A = self.getA(freq) A = self.getA(freq)
@@ -96,9 +90,9 @@ class BaseFDEMProblem(BaseEMProblem):
for rx in src.rxList: for rx in src.rxList:
df_dmFun = getattr(f, '_{0}Deriv'.format(rx.projField), None) df_dmFun = getattr(f, '_{0}Deriv'.format(rx.projField), None)
df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False) df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False)
Jv[src, rx] = rx.evalDeriv(src, self.mesh, f, df_dm_v) Jv.append(rx.evalDeriv(src, self.mesh, f, df_dm_v))
Ainv.clean() Ainv.clean()
return Utils.mkvc(Jv) return np.hstack(Jv)
def Jtvec(self, m, v, f=None): def Jtvec(self, m, v, f=None):
""" """
@@ -106,7 +100,7 @@ class BaseFDEMProblem(BaseEMProblem):
:param numpy.array m: inversion model (nP,) :param numpy.array m: inversion model (nP,)
:param numpy.array v: vector which we take adjoint product with (nP,) :param numpy.array v: vector which we take adjoint product with (nP,)
:param SimPEG.EM.FDEM.FieldsFDEM.FieldsFDEM u: fields object :param SimPEG.EM.FDEM.Fields u: fields object
:rtype numpy.array: :rtype numpy.array:
:return: Jv (ndata,) :return: Jv (ndata,)
""" """
@@ -160,8 +154,8 @@ class BaseFDEMProblem(BaseEMProblem):
Evaluates the sources for a given frequency and puts them in matrix form Evaluates the sources for a given frequency and puts them in matrix form
:param float freq: Frequency :param float freq: Frequency
:rtype: tuple :rtype: (numpy.ndarray, numpy.ndarray)
:return: (s_m, s_e) (nE or nF, nSrc) :return: s_m, s_e (nE or nF, nSrc)
""" """
Srcs = self.survey.getSrcByFreq(freq) Srcs = self.survey.getSrcByFreq(freq)
if self._formulation is 'EB': if self._formulation is 'EB':
@@ -173,7 +167,6 @@ class BaseFDEMProblem(BaseEMProblem):
for i, src in enumerate(Srcs): for i, src in enumerate(Srcs):
smi, sei = src.eval(self) smi, sei = src.eval(self)
#Why are you adding?
s_m[:,i] = s_m[:,i] + smi s_m[:,i] = s_m[:,i] + smi
s_e[:,i] = s_e[:,i] + sei s_e[:,i] = s_e[:,i] + sei
@@ -201,7 +194,7 @@ class Problem3D_e(BaseFDEMProblem):
which we solve for :math:`\mathbf{e}`. which we solve for :math:`\mathbf{e}`.
:param SimPEG.Mesh.BaseMesh.BaseMesh mesh: mesh :param SimPEG.Mesh mesh: mesh
""" """
_solutionType = 'eSolution' _solutionType = 'eSolution'
@@ -276,7 +269,7 @@ class Problem3D_e(BaseFDEMProblem):
Derivative of the right hand side with respect to the model Derivative of the right hand side with respect to the model
:param float freq: frequency :param float freq: frequency
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param SimPEG.EM.FDEM.Src src: FDEM source
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
@@ -312,7 +305,7 @@ class Problem3D_b(BaseFDEMProblem):
.. note :: .. note ::
The inverse problem will not work with full anisotropy The inverse problem will not work with full anisotropy
:param SimPEG.Mesh.BaseMesh.BaseMesh mesh: mesh :param SimPEG.Mesh mesh: mesh
""" """
_solutionType = 'bSolution' _solutionType = 'bSolution'
@@ -407,7 +400,7 @@ class Problem3D_b(BaseFDEMProblem):
Derivative of the right hand side with respect to the model Derivative of the right hand side with respect to the model
:param float freq: frequency :param float freq: frequency
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param SimPEG.EM.FDEM.Src src: FDEM source
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
@@ -451,7 +444,6 @@ class Problem3D_j(BaseFDEMProblem):
\mathbf{h} = \\frac{1}{i \omega} \mathbf{M_{\mu}^e}^{-1} \\left(-\mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{j} + \mathbf{M^e} \mathbf{s_m} \\right) \mathbf{h} = \\frac{1}{i \omega} \mathbf{M_{\mu}^e}^{-1} \\left(-\mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{j} + \mathbf{M^e} \mathbf{s_m} \\right)
and solve for \\\(\\\mathbf{j}\\\) using and solve for \\\(\\\mathbf{j}\\\) using
.. math :: .. math ::
@@ -461,7 +453,7 @@ class Problem3D_j(BaseFDEMProblem):
.. note:: .. note::
This implementation does not yet work with full anisotropy!! This implementation does not yet work with full anisotropy!!
:param SimPEG.Mesh.BaseMesh.BaseMesh mesh: mesh :param SimPEG.Mesh mesh: mesh
""" """
_solutionType = 'jSolution' _solutionType = 'jSolution'
@@ -537,8 +529,8 @@ class Problem3D_j(BaseFDEMProblem):
\mathbf{RHS} = \mathbf{C} \mathbf{M_{\mu}^e}^{-1}\mathbf{s_m} -i\omega \mathbf{s_e} \mathbf{RHS} = \mathbf{C} \mathbf{M_{\mu}^e}^{-1}\mathbf{s_m} -i\omega \mathbf{s_e}
:param float freq: Frequency :param float freq: Frequency
:rtype: numpy.ndarray :rtype: numpy.ndarray (nE, nSrc)
:return: RHS (nE, nSrc) :return: RHS
""" """
s_m, s_e = self.getSourceTerm(freq) s_m, s_e = self.getSourceTerm(freq)
@@ -557,7 +549,7 @@ class Problem3D_j(BaseFDEMProblem):
Derivative of the right hand side with respect to the model Derivative of the right hand side with respect to the model
:param float freq: frequency :param float freq: frequency
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param SimPEG.EM.FDEM.Src src: FDEM source
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
@@ -599,7 +591,7 @@ class Problem3D_h(BaseFDEMProblem):
\\left(\mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e}\\right) \mathbf{h} = \mathbf{M^e} \mathbf{s_m} + \mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{s_e} \\left(\mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e}\\right) \mathbf{h} = \mathbf{M^e} \mathbf{s_m} + \mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{s_e}
:param SimPEG.Mesh.BaseMesh.BaseMesh mesh: mesh :param SimPEG.Mesh mesh: mesh
""" """
_solutionType = 'hSolution' _solutionType = 'hSolution'
@@ -616,11 +608,9 @@ class Problem3D_h(BaseFDEMProblem):
.. math:: .. math::
\mathbf{A} = \mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e} \mathbf{A} = \mathbf{C}^{\\top} \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e}
:param float freq: Frequency :param float freq: Frequency
:rtype: scipy.sparse.csr_matrix :rtype: scipy.sparse.csr_matrix
:return: A :return: A
""" """
MeMu = self.MeMu MeMu = self.MeMu
@@ -663,7 +653,6 @@ class Problem3D_h(BaseFDEMProblem):
:param float freq: Frequency :param float freq: Frequency
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: RHS (nE, nSrc) :return: RHS (nE, nSrc)
""" """
s_m, s_e = self.getSourceTerm(freq) s_m, s_e = self.getSourceTerm(freq)
@@ -677,7 +666,7 @@ class Problem3D_h(BaseFDEMProblem):
Derivative of the right hand side with respect to the model Derivative of the right hand side with respect to the model
:param float freq: frequency :param float freq: frequency
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param SimPEG.EM.FDEM.Src src: FDEM source
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
+5 -12
View File
@@ -1,10 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG import sp from SimPEG import sp
@@ -32,10 +25,10 @@ class BaseRx(SimPEG.Survey.BaseRx):
def eval(self, src, mesh, f): def eval(self, src, mesh, f):
""" """
Project fields to receivers to get data. Project fields to recievers to get data.
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param Source src: FDEM source
:param BaseMesh mesh: mesh used :param Mesh mesh: mesh used
:param Fields f: fields object :param Fields f: fields object
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: fields projected to recievers :return: fields projected to recievers
@@ -51,8 +44,8 @@ class BaseRx(SimPEG.Survey.BaseRx):
""" """
Derivative of projected fields with respect to the inversion model times a vector. Derivative of projected fields with respect to the inversion model times a vector.
:param SimPEG.EM.FDEM.SrcFDEM.BaseSrc src: FDEM source :param Source src: FDEM source
:param BaseMesh mesh: mesh used :param Mesh mesh: mesh used
:param Fields f: fields object :param Fields f: fields object
:param numpy.ndarray v: vector to multiply :param numpy.ndarray v: vector to multiply
:rtype: numpy.ndarray :rtype: numpy.ndarray
+227 -35
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Survey, Problem, Utils, np, sp from SimPEG import Survey, Problem, Utils, np, sp
from scipy.constants import mu_0 from scipy.constants import mu_0
from SimPEG.EM.Utils import * from SimPEG.EM.Utils import *
@@ -29,8 +23,8 @@ class BaseSrc(Survey.BaseSrc):
- :math:`s_m` : magnetic source term - :math:`s_m` : magnetic source term
- :math:`s_e` : electric source term - :math:`s_e` : electric source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: tuple :rtype: (numpy.ndarray, numpy.ndarray)
:return: tuple with magnetic source term and electric source term :return: tuple with magnetic source term and electric source term
""" """
s_m = self.s_m(prob) s_m = self.s_m(prob)
@@ -43,10 +37,10 @@ class BaseSrc(Survey.BaseSrc):
- :code:`s_mDeriv` : derivative of the magnetic source term - :code:`s_mDeriv` : derivative of the magnetic source term
- :code:`s_eDeriv` : derivative of the electric source term - :code:`s_eDeriv` : derivative of the electric source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: tuple :rtype: (numpy.ndarray, numpy.ndarray)
:return: tuple with magnetic source term and electric source term derivatives times a vector :return: tuple with magnetic source term and electric source term derivatives times a vector
""" """
if v is not None: if v is not None:
@@ -58,7 +52,7 @@ class BaseSrc(Survey.BaseSrc):
""" """
Primary magnetic flux density Primary magnetic flux density
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic flux density :return: primary magnetic flux density
""" """
@@ -66,11 +60,23 @@ class BaseSrc(Survey.BaseSrc):
return Zero() return Zero()
return self._bPrimary return self._bPrimary
def bPrimaryDeriv(self, prob, v, adjoint=False):
"""
Derivative of the primary magnetic flux density
:param Problem prob: FDEM Problem
:param numpy.ndarray v: vector
:param bool adjoint: adjoint?
:rtype: numpy.ndarray
:return: primary magnetic flux density
"""
return Zero()
def hPrimary(self, prob): def hPrimary(self, prob):
""" """
Primary magnetic field Primary magnetic field
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -78,11 +84,23 @@ class BaseSrc(Survey.BaseSrc):
return Zero() return Zero()
return self._hPrimary return self._hPrimary
def hPrimaryDeriv(self, prob, v, adjoint=False):
"""
Derivative of the primary magnetic field
:param Problem prob: FDEM Problem
:param numpy.ndarray v: vector
:param bool adjoint: adjoint?
:rtype: numpy.ndarray
:return: primary magnetic flux density
"""
return Zero()
def ePrimary(self, prob): def ePrimary(self, prob):
""" """
Primary electric field Primary electric field
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary electric field :return: primary electric field
""" """
@@ -90,11 +108,23 @@ class BaseSrc(Survey.BaseSrc):
return Zero() return Zero()
return self._ePrimary return self._ePrimary
def ePrimaryDeriv(self, prob, v, adjoint=False):
"""
Derivative of the primary electric field
:param Problem prob: FDEM Problem
:param numpy.ndarray v: vector
:param bool adjoint: adjoint?
:rtype: numpy.ndarray
:return: primary magnetic flux density
"""
return Zero()
def jPrimary(self, prob): def jPrimary(self, prob):
""" """
Primary current density Primary current density
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary current density :return: primary current density
""" """
@@ -102,11 +132,23 @@ class BaseSrc(Survey.BaseSrc):
return Zero() return Zero()
return self._jPrimary return self._jPrimary
def jPrimaryDeriv(self, prob, v, adjoint=False):
"""
Derivative of the primary current density
:param Problem prob: FDEM Problem
:param numpy.ndarray v: vector
:param bool adjoint: adjoint?
:rtype: numpy.ndarray
:return: primary magnetic flux density
"""
return Zero()
def s_m(self, prob): def s_m(self, prob):
""" """
Magnetic source term Magnetic source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: magnetic source term on mesh :return: magnetic source term on mesh
""" """
@@ -116,7 +158,7 @@ class BaseSrc(Survey.BaseSrc):
""" """
Electric source term Electric source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: electric source term on mesh :return: electric source term on mesh
""" """
@@ -126,7 +168,7 @@ class BaseSrc(Survey.BaseSrc):
""" """
Derivative of magnetic source term with respect to the inversion model Derivative of magnetic source term with respect to the inversion model
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
@@ -139,7 +181,7 @@ class BaseSrc(Survey.BaseSrc):
""" """
Derivative of electric source term with respect to the inversion model Derivative of electric source term with respect to the inversion model
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:param numpy.ndarray v: vector to take product with :param numpy.ndarray v: vector to take product with
:param bool adjoint: adjoint? :param bool adjoint: adjoint?
:rtype: numpy.ndarray :rtype: numpy.ndarray
@@ -168,7 +210,7 @@ class RawVec_e(BaseSrc):
""" """
Electric source term Electric source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: electric source term on mesh :return: electric source term on mesh
""" """
@@ -197,7 +239,7 @@ class RawVec_m(BaseSrc):
""" """
Magnetic source term Magnetic source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: magnetic source term on mesh :return: magnetic source term on mesh
""" """
@@ -226,7 +268,7 @@ class RawVec(BaseSrc):
""" """
Magnetic source term Magnetic source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: magnetic source term on mesh :return: magnetic source term on mesh
""" """
@@ -238,7 +280,7 @@ class RawVec(BaseSrc):
""" """
Electric source term Electric source term
:param BaseFDEMProblem prob: FDEM Problem :param Problem prob: FDEM Problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: electric source term on mesh :return: electric source term on mesh
""" """
@@ -307,7 +349,7 @@ class MagDipole(BaseSrc):
""" """
The primary magnetic flux density from a magnetic vector potential The primary magnetic flux density from a magnetic vector potential
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -345,7 +387,7 @@ class MagDipole(BaseSrc):
""" """
The primary magnetic field from a magnetic vector potential The primary magnetic field from a magnetic vector potential
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -356,7 +398,7 @@ class MagDipole(BaseSrc):
""" """
The magnetic source term The magnetic source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -370,7 +412,7 @@ class MagDipole(BaseSrc):
""" """
The electric source term The electric source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -422,7 +464,7 @@ class MagDipole_Bfield(BaseSrc):
""" """
The primary magnetic flux density from the analytic solution for magnetic fields from a dipole The primary magnetic flux density from the analytic solution for magnetic fields from a dipole
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -461,7 +503,7 @@ class MagDipole_Bfield(BaseSrc):
""" """
The primary magnetic field from a magnetic vector potential The primary magnetic field from a magnetic vector potential
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -472,7 +514,7 @@ class MagDipole_Bfield(BaseSrc):
""" """
The magnetic source term The magnetic source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -485,7 +527,7 @@ class MagDipole_Bfield(BaseSrc):
""" """
The electric source term The electric source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -536,7 +578,7 @@ class CircularLoop(BaseSrc):
""" """
The primary magnetic flux density from a magnetic vector potential The primary magnetic flux density from a magnetic vector potential
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -561,7 +603,7 @@ class CircularLoop(BaseSrc):
a = MagneticLoopVectorPotential(self.loc, gridY, 'y', moment=self.radius, mu=self.mu) a = MagneticLoopVectorPotential(self.loc, gridY, 'y', moment=self.radius, mu=self.mu)
else: else:
srcfct = MagneticDipoleVectorPotential srcfct = MagneticLoopVectorPotential
ax = srcfct(self.loc, gridX, 'x', self.radius, mu=self.mu) ax = srcfct(self.loc, gridX, 'x', self.radius, mu=self.mu)
ay = srcfct(self.loc, gridY, 'y', self.radius, mu=self.mu) ay = srcfct(self.loc, gridY, 'y', self.radius, mu=self.mu)
az = srcfct(self.loc, gridZ, 'z', self.radius, mu=self.mu) az = srcfct(self.loc, gridZ, 'z', self.radius, mu=self.mu)
@@ -573,7 +615,7 @@ class CircularLoop(BaseSrc):
""" """
The primary magnetic field from a magnetic vector potential The primary magnetic field from a magnetic vector potential
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -584,7 +626,7 @@ class CircularLoop(BaseSrc):
""" """
The magnetic source term The magnetic source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -597,7 +639,7 @@ class CircularLoop(BaseSrc):
""" """
The electric source term The electric source term
:param BaseFDEMProblem prob: FDEM problem :param Problem prob: FDEM problem
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: primary magnetic field :return: primary magnetic field
""" """
@@ -620,5 +662,155 @@ class CircularLoop(BaseSrc):
return -C.T * (MMui_s * self.bPrimary(prob)) return -C.T * (MMui_s * self.bPrimary(prob))
class PrimSecSigma(BaseSrc):
def __init__(self, rxList, freq, sigBack, ePrimary, **kwargs):
self.sigBack = sigBack
BaseSrc.__init__(self, rxList, freq=freq, _ePrimary=ePrimary, **kwargs)
def s_e(self, prob):
return (prob.MeSigma - prob.mesh.getEdgeInnerProduct(self.sigBack)) * self.ePrimary(prob)
def s_eDeriv(self, prob, v, adjoint=False):
if adjoint:
return prob.MeSigmaDeriv(self.ePrimary(prob)).T * v
return prob.MeSigmaDeriv(self.ePrimary(prob)) * v
class PrimSecMappedSigma(BaseSrc):
"""
Primary-Secondary Source in which a mapping is provided to put the current model
onto the primary mesh. This is solved on every model update.
There are a lot of layers to the derivatives here!
**Required**
:param list rxList: Receiver List
:param float freq: frequency
:param ProblemFDEM primaryProblem: FDEM primary problem
:param SurveyFDEM primarySurvey: FDEM primary survey
**Optional**
:param Mapping map2meshSecondary: mapping current model to act as primary model on the secondary mesh
"""
def __init__(self, rxList, freq, primaryProblem, primarySurvey, map2meshSecondary = None ,**kwargs):
self.primaryProblem = primaryProblem
self.primarySurvey = primarySurvey
if self.primaryProblem.ispaired is False:
self.primaryProblem.pair(self.primarySurvey)
self.map2meshSecondary = map2meshSecondary
BaseSrc.__init__(self, rxList, freq=freq, **kwargs)
def _ProjPrimary(self, prob):
# if getattr(self, '__ProjPrimary', None) is None:
return self.primaryProblem.mesh.getInterpolationMatCartMesh(prob.mesh, locType='F', locTypeTo='E')
# return self.__ProjPrimary
def _primaryFields(self, prob, fieldType=None):
# TODO: cache and check if prob.curModel has changed
fields = self.primaryProblem.fields(prob.curModel.sigmaModel)
if fieldType is not None:
return fields[:,fieldType]
return fields
def _primaryFieldsDeriv(self, prob, v, adjoint=False, f=None):
if adjoint:
raise NotImplementedError
# TODO: this should not be hard-coded for j
# jp = self._primaryFields(prob)[:,'j']
# TODO: pull apart Jvec so that don't have to copy paste this code in
# A = self.primaryProblem.getA(self.freq)
# Ainv = self.primaryProblem.Solver(A, **self.primaryProblem.solverOpts) # create the concept of Ainv (actually a solve)
if f is None:
f = self._primaryFields(prob.curModel.sigmaModel)
freq = self.freq
A = self.primaryProblem.getA(freq)
Ainv = self.primaryProblem.Solver(A, **self.primaryProblem.solverOpts) # create the concept of Ainv (actually a solve)
src = self.primarySurvey.srcList[0]
# for src in self.survey.getSrcByFreq(freq):
u_src = Utils.mkvc(f[src, self.primaryProblem._solutionType])
dA_dm_v = self.primaryProblem.getADeriv(freq, u_src, v)
dRHS_dm_v = self.primaryProblem.getRHSDeriv(freq, src, v)
du_dm_v = Ainv * ( - dA_dm_v + dRHS_dm_v )
df_dmFun = getattr(f, '_{0}Deriv'.format('j'), None)
df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False)
# Jv[src, rx] = rx.evalDeriv(src, self.mesh, f, df_dm_v)
Ainv.clean()
return df_dm_v
# return self.primaryProblem.Jvec(prob.curModel, v, f=f)
def ePrimary(self, prob, f=None):
if f is None:
f = self._primaryFields(prob)
ep = self._ProjPrimary(prob) * (
self.primaryProblem.MfI * (
self.primaryProblem.MfRho * f[:,'j'])
)
return Utils.mkvc(ep)
def ePrimaryDeriv(self, prob, v, adjoint=False, f=None):
if adjoint is True:
raise NotImplementedError
if f is None:
f = self._primaryFields(prob)
epDeriv = self._ProjPrimary(prob) * (
self.primaryProblem.MfI * (
(self.primaryProblem.MfRhoDeriv(f[:,'j']) * v)
+
(self.primaryProblem.MfRho * self._primaryFieldsDeriv(prob, v, f=f))
)
)
return Utils.mkvc(epDeriv)
def s_e(self, prob):
sigmaPrimary = self.map2meshSecondary * prob.curModel.sigmaModel
return Utils.mkvc((prob.MeSigma - prob.mesh.getEdgeInnerProduct(sigmaPrimary)) * self.ePrimary(prob))
def s_eDeriv(self, prob, v, adjoint=False):
if adjoint:
raise NotImplementedError
return prob.MeSigmaDeriv(self.ePrimary(prob)).T * v
sigmaPrimary = self.map2meshSecondary * prob.curModel.sigmaModel
sigmaPrimaryDeriv = self.map2meshSecondary.deriv(prob.curModel.sigmaModel)
f = self._primaryFields(prob)
ePrimary = self.ePrimary(prob,f=f)
return (prob.MeSigmaDeriv(ePrimary) * v
- prob.mesh.getEdgeInnerProductDeriv(sigmaPrimary)(ePrimary) * sigmaPrimaryDeriv * v
+ (prob.MeSigma - prob.mesh.getEdgeInnerProduct(sigmaPrimary)) * self.ePrimaryDeriv(prob, v, None, f=f)
)
+2 -8
View File
@@ -1,16 +1,10 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG.EM.Utils import * from SimPEG.EM.Utils import *
from SimPEG.EM.Base import BaseEMSurvey from SimPEG.EM.Base import BaseEMSurvey
from scipy.constants import mu_0 from scipy.constants import mu_0
from SimPEG.Utils import Zero, Identity from SimPEG.Utils import Zero, Identity
from . import SrcFDEM as Src import SrcFDEM as Src
from . import RxFDEM as Rx import RxFDEM as Rx
from SimPEG import sp from SimPEG import sp
class Survey(BaseEMSurvey): class Survey(BaseEMSurvey):
+5 -11
View File
@@ -1,11 +1,5 @@
from __future__ import absolute_import from SurveyFDEM import Survey
from __future__ import unicode_literals import SrcFDEM as Src
from __future__ import print_function import RxFDEM as Rx
from __future__ import division from ProblemFDEM import Problem3D_e, Problem3D_b, Problem3D_j, Problem3D_h
from future import standard_library from FieldsFDEM import Fields3D_e, Fields3D_b, Fields3D_j, Fields3D_h
standard_library.install_aliases()
from .SurveyFDEM import Survey
from . import SrcFDEM as Src
from . import RxFDEM as Rx
from .ProblemFDEM import Problem3D_e, Problem3D_b, Problem3D_j, Problem3D_h
from .FieldsFDEM import Fields3D_e, Fields3D_b, Fields3D_j, Fields3D_h
-6
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np import numpy as np
def getxBCyBC_CC(mesh, alpha, beta, gamma): def getxBCyBC_CC(mesh, alpha, beta, gamma):
+3 -9
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG.Utils import Identity, Zero from SimPEG.Utils import Identity, Zero
import numpy as np import numpy as np
@@ -15,7 +9,7 @@ class Fields(SimPEG.Problem.Fields):
def _phiDeriv(self, src, du_dm_v, v, adjoint=False): def _phiDeriv(self, src, du_dm_v, v, adjoint=False):
if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None: if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None:
raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._phiDeriv_u(src, v, adjoint=adjoint), self._phiDeriv_m(src, v, adjoint=adjoint) return self._phiDeriv_u(src, v, adjoint=adjoint), self._phiDeriv_m(src, v, adjoint=adjoint)
@@ -24,7 +18,7 @@ class Fields(SimPEG.Problem.Fields):
def _eDeriv(self, src, du_dm_v, v, adjoint=False): def _eDeriv(self, src, du_dm_v, v, adjoint=False):
if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None:
raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint)
@@ -32,7 +26,7 @@ class Fields(SimPEG.Problem.Fields):
def _jDeriv(self, src, du_dm_v, v, adjoint=False): def _jDeriv(self, src, du_dm_v, v, adjoint=False):
if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None:
raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint) return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint)
+3 -9
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG.Utils import Identity, Zero from SimPEG.Utils import Identity, Zero
import numpy as np import numpy as np
@@ -38,7 +32,7 @@ class Fields_ky(SimPEG.Problem.TimeFields):
def _phiDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): def _phiDeriv(self,kyInd, src, du_dm_v, v, adjoint=False):
if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None: if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None:
raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._phiDeriv_u(kyInd, src, v, adjoint=adjoint), self._phiDeriv_m(kyInd, src, v, adjoint=adjoint) return self._phiDeriv_u(kyInd, src, v, adjoint=adjoint), self._phiDeriv_m(kyInd, src, v, adjoint=adjoint)
@@ -47,7 +41,7 @@ class Fields_ky(SimPEG.Problem.TimeFields):
def _eDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): def _eDeriv(self,kyInd, src, du_dm_v, v, adjoint=False):
if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None:
raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._eDeriv_u(kyInd, src, v, adjoint), self._eDeriv_m(kyInd, src, v, adjoint) return self._eDeriv_u(kyInd, src, v, adjoint), self._eDeriv_m(kyInd, src, v, adjoint)
@@ -55,7 +49,7 @@ class Fields_ky(SimPEG.Problem.TimeFields):
def _jDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): def _jDeriv(self,kyInd, src, du_dm_v, v, adjoint=False):
if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None:
raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0])
if adjoint: if adjoint:
return self._jDeriv_u(kyInd, src, v, adjoint), self._jDeriv_m(kyInd, src, v, adjoint) return self._jDeriv_u(kyInd, src, v, adjoint), self._jDeriv_m(kyInd, src, v, adjoint)
+3 -9
View File
@@ -1,17 +1,11 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from SimPEG import Problem, Utils from SimPEG import Problem, Utils
from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Base import BaseEMProblem
from .SurveyDC import Survey from SurveyDC import Survey
from .FieldsDC import Fields, Fields_CC, Fields_N from FieldsDC import Fields, Fields_CC, Fields_N
from SimPEG.Utils import sdiag from SimPEG.Utils import sdiag
import numpy as np import numpy as np
from SimPEG.Utils import Zero from SimPEG.Utils import Zero
from .BoundaryUtils import getxBCyBC_CC from BoundaryUtils import getxBCyBC_CC
class BaseDCProblem(BaseEMProblem): class BaseDCProblem(BaseEMProblem):
+3 -10
View File
@@ -1,18 +1,11 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import Problem, Utils from SimPEG import Problem, Utils
from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Base import BaseEMProblem
from .SurveyDC import Survey, Survey_ky from SurveyDC import Survey, Survey_ky
from .FieldsDC_2D import Fields_ky, Fields_ky_CC, Fields_ky_N from FieldsDC_2D import Fields_ky, Fields_ky_CC, Fields_ky_N
from SimPEG.Utils import sdiag from SimPEG.Utils import sdiag
import numpy as np import numpy as np
from SimPEG.Utils import Zero from SimPEG.Utils import Zero
from .BoundaryUtils import getxBCyBC_CC from BoundaryUtils import getxBCyBC_CC
class BaseDCProblem_2D(BaseEMProblem): class BaseDCProblem_2D(BaseEMProblem):
+8 -8
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
import SimPEG import SimPEG
import numpy as np import numpy as np
from SimPEG.Utils import Zero, closestPoints from SimPEG.Utils import Zero, closestPoints
@@ -50,7 +43,14 @@ class BaseRx(SimPEG.Survey.BaseRx):
elif adjoint: elif adjoint:
return P.T*v return P.T*v
# DC.Rx.Dipole(locs) # DC.Rx.Pole(locs)
class Pole(BaseRx):
def __init__(self, locs, rxType = 'phi', **kwargs):
BaseRx.__init__(self, locs, rxType)
# DC.Rx.Dipole(locsM, locsN)
class Dipole(BaseRx): class Dipole(BaseRx):
def __init__(self, locsM, locsN, rxType = 'phi', **kwargs): def __init__(self, locsM, locsN, rxType = 'phi', **kwargs):
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
# from SimPEG.EM.Base import BaseEMSurvey # from SimPEG.EM.Base import BaseEMSurvey
from SimPEG.Utils import Zero, closestPoints, mkvc from SimPEG.Utils import Zero, closestPoints, mkvc
+2 -8
View File
@@ -1,15 +1,9 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG.EM.Base import BaseEMSurvey from SimPEG.EM.Base import BaseEMSurvey
from SimPEG import sp, Survey from SimPEG import sp, Survey
from SimPEG.Utils import Zero, Identity from SimPEG.Utils import Zero, Identity
from .RxDC import BaseRx from RxDC import BaseRx
from .SrcDC import BaseSrc from SrcDC import BaseSrc
class Survey(BaseEMSurvey): class Survey(BaseEMSurvey):
rxPair = BaseRx rxPair = BaseRx
-7
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
import numpy as np import numpy as np
def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False):
+8 -14
View File
@@ -1,14 +1,8 @@
from __future__ import absolute_import from ProblemDC import Problem3D_CC, Problem3D_N
from __future__ import unicode_literals from ProblemDC_2D import Problem2D_CC, Problem2D_N
from __future__ import print_function from SurveyDC import Survey, Survey_ky
from __future__ import division import SrcDC as Src #Pole
from future import standard_library import RxDC as Rx
standard_library.install_aliases() from FieldsDC import Fields_CC
from .ProblemDC import Problem3D_CC, Problem3D_N from BoundaryUtils import getxBCyBC_CC
from .ProblemDC_2D import Problem2D_CC, Problem2D_N import Utils
from .SurveyDC import Survey, Survey_ky
from . import SrcDC as Src #Pole
from . import RxDC as Rx
from .FieldsDC import Fields_CC
from .BoundaryUtils import getxBCyBC_CC
from . import Utils
+1 -7
View File
@@ -1,9 +1,3 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from SimPEG import Problem, Utils, Maps, Mesh from SimPEG import Problem, Utils, Maps, Mesh
from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Base import BaseEMProblem
from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N
@@ -11,7 +5,7 @@ from SimPEG.Utils import sdiag
import numpy as np import numpy as np
from SimPEG.Utils import Zero from SimPEG.Utils import Zero
from SimPEG.EM.Static.DC import getxBCyBC_CC from SimPEG.EM.Static.DC import getxBCyBC_CC
from .SurveyIP import Survey from SurveyIP import Survey
class IPPropMap(Maps.PropMap): class IPPropMap(Maps.PropMap):
""" """
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
from SimPEG.EM.Base import BaseEMSurvey from SimPEG.EM.Base import BaseEMSurvey
from SimPEG import sp, Survey from SimPEG import sp, Survey
+2 -8
View File
@@ -1,8 +1,2 @@
from __future__ import absolute_import from ProblemIP import Problem3D_CC, Problem3D_N
from __future__ import unicode_literals from SurveyIP import Survey
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .ProblemIP import Problem3D_CC, Problem3D_N
from .SurveyIP import Survey
+2 -10
View File
@@ -1,11 +1,3 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import Problem, Utils, Maps, Mesh from SimPEG import Problem, Utils, Maps, Mesh
from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Base import BaseEMProblem
from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N
@@ -13,7 +5,7 @@ from SimPEG.Utils import sdiag
import numpy as np import numpy as np
from SimPEG.Utils import Zero from SimPEG.Utils import Zero
from SimPEG.EM.Static.DC import getxBCyBC_CC from SimPEG.EM.Static.DC import getxBCyBC_CC
from .SurveySIP import Survey, Data from SurveySIP import Survey, Data
class ColeColePropMap(Maps.PropMap): class ColeColePropMap(Maps.PropMap):
""" """
@@ -113,7 +105,7 @@ class BaseSIPProblem(BaseEMProblem):
JvAll = [] JvAll = []
#Assume only eta and tau (eta first then tau) #Assume only eta and tau (eta first then tau)
# v = [2*Mx1] # v = [2*Mx1]
v = v.reshape((v.size//2), 2), order='F') v = v.reshape((int(v.size/2), 2), order='F')
for tind in range(len(self.survey.times)): for tind in range(len(self.survey.times)):
t = self.survey.times[tind] t = self.survey.times[tind]
-7
View File
@@ -1,10 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import Utils, Maps, Mesh, sp, np from SimPEG import Utils, Maps, Mesh, sp, np
from SimPEG.Regularization import BaseRegularization, Simple from SimPEG.Regularization import BaseRegularization, Simple
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
import numpy as np import numpy as np
from SimPEG.Utils import Zero, closestPoints from SimPEG.Utils import Zero, closestPoints
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG import SimPEG
# from SimPEG.EM.Base import BaseEMSurvey # from SimPEG.EM.Base import BaseEMSurvey
from SimPEG.Utils import Zero, closestPoints, mkvc from SimPEG.Utils import Zero, closestPoints, mkvc
-7
View File
@@ -1,10 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
import SimPEG import SimPEG
from SimPEG.EM.Base import BaseEMSurvey from SimPEG.EM.Base import BaseEMSurvey
from SimPEG import np, sp, Survey, Utils from SimPEG import np, sp, Survey, Utils
+5 -11
View File
@@ -1,11 +1,5 @@
from __future__ import absolute_import from ProblemSIP import Problem3D_CC, Problem3D_N
from __future__ import unicode_literals from SurveySIP import Survey, Data
from __future__ import print_function import SrcSIP as Src #Pole
from __future__ import division import RxSIP as Rx
from future import standard_library from Regularization import MultiRegularization
standard_library.install_aliases()
from .ProblemSIP import Problem3D_CC, Problem3D_N
from .SurveySIP import Survey, Data
from . import SrcSIP as Src #Pole
from . import RxSIP as Rx
from .Regularization import MultiRegularization
+19 -27
View File
@@ -1,11 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import np from SimPEG import np
from SimPEG.EM.Static import DC, IP from SimPEG.EM.Static import DC, IP
@@ -93,10 +85,10 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None):
elif stype == 'dpdp': elif stype == 'dpdp':
leg = data * 2*np.pi / (1/MA - 1/MB + 1/NB - 1/NA) leg = data * 2*np.pi / ( 1/MA - 1/MB + 1/NB - 1/NA )
LEG.append(1./(2*np.pi) * (1/MA - 1/MB + 1/NB - 1/NA)) LEG.append(1./(2*np.pi) *( 1/MA - 1/MB + 1/NB - 1/NA ))
else: else:
print("""dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """) print """dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """
break break
@@ -111,7 +103,7 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None):
rho = np.hstack([rho,leg]) rho = np.hstack([rho,leg])
else: else:
print("""dtype must be 'appr' | 'appc' | 'volt' """) print """dtype must be 'appr' | 'appc' | 'volt' """
break break
@@ -192,14 +184,14 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n):
# Mesure survey length and direction # Mesure survey length and direction
dl_len = xy_2_r(endl[0,0],endl[1,0],endl[0,1],endl[1,1]) dl_len = xy_2_r(endl[0,0],endl[1,0],endl[0,1],endl[1,1])
dl_x = (endl[1,0] - endl[0,0]) / dl_len dl_x = ( endl[1,0] - endl[0,0] ) / dl_len
dl_y = (endl[1,1] - endl[0,1]) / dl_len dl_y = ( endl[1,1] - endl[0,1] ) / dl_len
nstn = np.floor(dl_len / a) nstn = np.floor( dl_len / a )
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = endl[0,0] + np.array(list(range(int(nstn))))*dl_x*a stn_x = endl[0,0] + np.array(range(int(nstn)))*dl_x*a
stn_y = endl[0,1] + np.array(list(range(int(nstn))))*dl_y*a stn_y = endl[0,1] + np.array(range(int(nstn)))*dl_y*a
if mesh.dim==2: if mesh.dim==2:
ztop = mesh.vectorNy[-1] ztop = mesh.vectorNy[-1]
@@ -238,15 +230,15 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n):
AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1]) AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1])
# Number of receivers to fit # Number of receivers to fit
nstn = np.min([(AB - b) // a, n]) nstn = np.min([np.floor( (AB - b) / a ) , n])
# Check if there is enough space, else break the loop # Check if there is enough space, else break the loop
if nstn <= 0: if nstn <= 0:
continue continue
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = N[ii,0] + dl_x*b + np.array(list(range(int(nstn))))*dl_x*a stn_x = N[ii,0] + dl_x*b + np.array(range(int(nstn)))*dl_x*a
stn_y = N[ii,1] + dl_y*b + np.array(list(range(int(nstn))))*dl_y*a stn_y = N[ii,1] + dl_y*b + np.array(range(int(nstn)))*dl_y*a
# Create receiver poles # Create receiver poles
@@ -283,17 +275,17 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n):
max_y = endl[1,1] - dl_y * b max_y = endl[1,1] - dl_y * b
box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 ) box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 )
box_w = box_l / 2. box_w = box_l/2.
nstn = np.floor(box_l / a) nstn = np.floor( box_l / a )
# Compute discrete pole location along line # Compute discrete pole location along line
stn_x = min_x + np.array(list(range(int(nstn))))*dl_x*a stn_x = min_x + np.array(range(int(nstn)))*dl_x*a
stn_y = min_y + np.array(list(range(int(nstn))))*dl_y*a stn_y = min_y + np.array(range(int(nstn)))*dl_y*a
# Define number of cross lines # Define number of cross lines
nlin = int(box_w // a) nlin = int(np.floor( box_w / a ))
lind = list(range(-nlin,nlin+1)) lind = range(-nlin,nlin+1)
ngrad = nstn * len(lind) ngrad = nstn * len(lind)
@@ -318,7 +310,7 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n):
srcClass = DC.Src.Dipole([rxClass], M[0,:], N[-1,:]) srcClass = DC.Src.Dipole([rxClass], M[0,:], N[-1,:])
SrcList.append(srcClass) SrcList.append(srcClass)
else: else:
print("""stype must be either 'pdp', 'dpdp' or 'gradient'. """) print """stype must be either 'pdp', 'dpdp' or 'gradient'. """
return SrcList return SrcList
+1 -7
View File
@@ -1,7 +1 @@
from __future__ import absolute_import from StaticUtils import *
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .StaticUtils import *
+3 -9
View File
@@ -1,9 +1,3 @@
from __future__ import absolute_import import DC
from __future__ import unicode_literals import IP
from __future__ import print_function import SIP
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from . import DC
from . import IP
from . import SIP
+17 -24
View File
@@ -1,10 +1,3 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import Solver, Problem from SimPEG import Solver, Problem
from SimPEG.Problem import BaseTimeProblem from SimPEG.Problem import BaseTimeProblem
from SimPEG.EM.Utils import * from SimPEG.EM.Utils import *
@@ -54,7 +47,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
self.waveformType = "GENERAL" self.waveformType = "GENERAL"
def fields(self, m): def fields(self, m):
if self.verbose: print('%s\nCalculating fields(m)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nCalculating fields(m)\n%s'%('*'*50,'*'*50)
self.curModel = m self.curModel = m
# Create a fields storage object # Create a fields storage object
F = self._FieldsForward_pair(self.mesh, self.survey) F = self._FieldsForward_pair(self.mesh, self.survey)
@@ -62,7 +55,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
# Set the initial conditions # Set the initial conditions
F[src,:,0] = src.getInitialFields(self.mesh) F[src,:,0] = src.getInitialFields(self.mesh)
F = self.forward(m, self.getRHS, F=F) F = self.forward(m, self.getRHS, F=F)
if self.verbose: print('%s\nDone calculating fields(m)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nDone calculating fields(m)\n%s'%('*'*50,'*'*50)
return F return F
def forward(self, m, RHS, F=None): def forward(self, m, RHS, F=None):
@@ -77,13 +70,13 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
if Ainv is not None: if Ainv is not None:
Ainv.clean() Ainv.clean()
A = self.getA(tInd) A = self.getA(tInd)
if self.verbose: print('Factoring... (dt = %e)'%dt) if self.verbose: print 'Factoring... (dt = %e)'%dt
Ainv = self.Solver(A, **self.solverOpts) Ainv = self.Solver(A, **self.solverOpts)
if self.verbose: print('Done') if self.verbose: print 'Done'
rhs = RHS(tInd, F) rhs = RHS(tInd, F)
if self.verbose: print(' Solving... (tInd = %d)'%tInd) if self.verbose: print ' Solving... (tInd = %d)'%tInd
sol = Ainv * rhs sol = Ainv * rhs
if self.verbose: print(' Done...') if self.verbose: print ' Done...'
if sol.ndim == 1: if sol.ndim == 1:
sol.shape = (sol.size,1) sol.shape = (sol.size,1)
F[:,self.solType,tInd+1] = sol F[:,self.solType,tInd+1] = sol
@@ -102,13 +95,13 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
if Ainv is not None: if Ainv is not None:
Ainv.clean() Ainv.clean()
A = self.getA(tInd) A = self.getA(tInd)
if self.verbose: print('Factoring (Adjoint)... (dt = %e)'%dt) if self.verbose: print 'Factoring (Adjoint)... (dt = %e)'%dt
Ainv = self.Solver(A, **self.solverOpts) Ainv = self.Solver(A, **self.solverOpts)
if self.verbose: print('Done') if self.verbose: print 'Done'
rhs = RHS(tInd, F) rhs = RHS(tInd, F)
if self.verbose: print(' Solving (Adjoint)... (tInd = %d)'%tInd) if self.verbose: print ' Solving (Adjoint)... (tInd = %d)'%tInd
sol = Ainv * rhs sol = Ainv * rhs
if self.verbose: print(' Done...') if self.verbose: print ' Done...'
if sol.ndim == 1: if sol.ndim == 1:
sol.shape = (sol.size,1) sol.shape = (sol.size,1)
F[:,self.solType,tInd+1] = sol F[:,self.solType,tInd+1] = sol
@@ -119,7 +112,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param numpy.ndarray v: vector (model object) :param numpy.ndarray v: vector (model object)
:param FieldsTDEM f: Fields resulting from m :param simpegEM.TDEM.FieldsTDEM f: Fields resulting from m
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: w (data object) :return: w (data object)
@@ -130,21 +123,21 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
* Compute \\\(\\\\vec{w} = -\\\mathbf{Q} \\\\vec{y}\\\) * Compute \\\(\\\\vec{w} = -\\\mathbf{Q} \\\\vec{y}\\\)
""" """
if self.verbose: print('%s\nCalculating J(v)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nCalculating J(v)\n%s'%('*'*50,'*'*50)
self.curModel = m self.curModel = m
if f is None: if f is None:
f = self.fields(m) f = self.fields(m)
p = self.Gvec(m, v, f) p = self.Gvec(m, v, f)
y = self.solveAh(m, p) y = self.solveAh(m, p)
Jv = self.survey.evalDeriv(f, v=y) Jv = self.survey.evalDeriv(f, v=y)
if self.verbose: print('%s\nDone calculating J(v)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nDone calculating J(v)\n%s'%('*'*50,'*'*50)
return - mkvc(Jv) return - mkvc(Jv)
def Jtvec(self, m, v, f=None): def Jtvec(self, m, v, f=None):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param numpy.ndarray v: vector (or a :class:`SimPEG.Survey.Data` object) :param numpy.ndarray,SimPEG.Survey.Data v: vector (data object)
:param FieldsTDEM u: Fields resulting from m :param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: numpy.ndarray :rtype: numpy.ndarray
:return: w (model object) :return: w (model object)
@@ -155,7 +148,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
* Compute \\\(\\\\vec{w} = -\\\mathbf{G}^\\\\top y\\\) * Compute \\\(\\\\vec{w} = -\\\mathbf{G}^\\\\top y\\\)
""" """
if self.verbose: print('%s\nCalculating J^T(v)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nCalculating J^T(v)\n%s'%('*'*50,'*'*50)
self.curModel = m self.curModel = m
if f is None: if f is None:
f = self.fields(m) f = self.fields(m)
@@ -166,6 +159,6 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
p = self.survey.evalDeriv(f, v=v, adjoint=True) p = self.survey.evalDeriv(f, v=v, adjoint=True)
y = self.solveAht(m, p) y = self.solveAht(m, p)
w = self.Gtvec(m, y, f) w = self.Gtvec(m, y, f)
if self.verbose: print('%s\nDone calculating J^T(v)\n%s'%('*'*50,'*'*50)) if self.verbose: print '%s\nDone calculating J^T(v)\n%s'%('*'*50,'*'*50)
return - mkvc(w) return - mkvc(w)
+5 -11
View File
@@ -1,13 +1,7 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from SimPEG import Utils, Survey, np from SimPEG import Utils, Survey, np
from SimPEG.Survey import BaseSurvey from SimPEG.Survey import BaseSurvey
from SimPEG.EM.Utils import * from SimPEG.EM.Utils import *
from .BaseTDEM import FieldsTDEM from BaseTDEM import FieldsTDEM
class RxTDEM(Survey.BaseTimeRx): class RxTDEM(Survey.BaseTimeRx):
@@ -93,7 +87,7 @@ class SrcTDEM_VMD_MVP(SrcTDEM):
def getInitialFields(self, mesh): def getInitialFields(self, mesh):
"""Vertical magnetic dipole, magnetic vector potential""" """Vertical magnetic dipole, magnetic vector potential"""
if self.waveformType == "STEPOFF": if self.waveformType == "STEPOFF":
print(">> Step waveform: Non-zero initial condition") print ">> Step waveform: Non-zero initial condition"
if mesh._meshType is 'CYL': if mesh._meshType is 'CYL':
if mesh.isSymmetric: if mesh.isSymmetric:
MVP = MagneticDipoleVectorPotential(self.loc, mesh, 'Ey') MVP = MagneticDipoleVectorPotential(self.loc, mesh, 'Ey')
@@ -105,7 +99,7 @@ class SrcTDEM_VMD_MVP(SrcTDEM):
raise Exception('Unknown mesh for VMD') raise Exception('Unknown mesh for VMD')
return {"b": mesh.edgeCurl*MVP} return {"b": mesh.edgeCurl*MVP}
elif self.waveformType == "GENERAL": elif self.waveformType == "GENERAL":
print(">> General waveform: Zero initial condition") print ">> General waveform: Zero initial condition"
return {"b": np.zeros(mesh.nF)} return {"b": np.zeros(mesh.nF)}
else: else:
raise NotImplementedError("Only use STEPOFF or GENERAL") raise NotImplementedError("Only use STEPOFF or GENERAL")
@@ -133,7 +127,7 @@ class SrcTDEM_CircularLoop_MVP(SrcTDEM):
def getInitialFields(self, mesh): def getInitialFields(self, mesh):
"""Circular Loop, magnetic vector potential""" """Circular Loop, magnetic vector potential"""
if self.waveformType == "STEPOFF": if self.waveformType == "STEPOFF":
print(">> Step waveform: Non-zero initial condition") print ">> Step waveform: Non-zero initial condition"
if mesh._meshType is 'CYL': if mesh._meshType is 'CYL':
if mesh.isSymmetric: if mesh.isSymmetric:
MVP = MagneticLoopVectorPotential(self.loc, mesh, 'Ey', self.radius) MVP = MagneticLoopVectorPotential(self.loc, mesh, 'Ey', self.radius)
@@ -145,7 +139,7 @@ class SrcTDEM_CircularLoop_MVP(SrcTDEM):
raise Exception('Unknown mesh for CircularLoop') raise Exception('Unknown mesh for CircularLoop')
return {"b": mesh.edgeCurl*MVP} return {"b": mesh.edgeCurl*MVP}
elif self.waveformType == "GENERAL": elif self.waveformType == "GENERAL":
print(">> General waveform: Zero initial condition") print ">> General waveform: Zero initial condition"
return {"b": np.zeros(mesh.nF)} return {"b": np.zeros(mesh.nF)}
else: else:
raise NotImplementedError("Only use STEPOFF or GENERAL") raise NotImplementedError("Only use STEPOFF or GENERAL")
+15 -22
View File
@@ -1,14 +1,7 @@
from __future__ import absolute_import from BaseTDEM import BaseTDEMProblem, FieldsTDEM
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import range
from .BaseTDEM import BaseTDEMProblem, FieldsTDEM
from SimPEG.Utils import mkvc, sdiag from SimPEG.Utils import mkvc, sdiag
import numpy as np import numpy as np
from .SurveyTDEM import SurveyTDEM from SurveyTDEM import SurveyTDEM
class FieldsTDEM_e_from_b(FieldsTDEM): class FieldsTDEM_e_from_b(FieldsTDEM):
@@ -94,8 +87,8 @@ class ProblemTDEM_b(BaseTDEMProblem):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param numpy.array vec: vector (like a model) :param numpy.array vec: vector (like a model)
:param FieldsTDEM u: Fields resulting from m :param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: FieldsTDEM :rtype: simpegEM.TDEM.FieldsTDEM
:return: f :return: f
Multiply G by a vector Multiply G by a vector
@@ -132,9 +125,9 @@ class ProblemTDEM_b(BaseTDEMProblem):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param numpy.array vec: vector (like a fields) :param numpy.array vec: vector (like a fields)
:param FieldsTDEM u: Fields resulting from m :param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: numpy.ndarray :rtype: np.ndarray (like a model)
:return: p (like a model) :return: p
Multiply G.T by a vector Multiply G.T by a vector
""" """
@@ -160,8 +153,8 @@ class ProblemTDEM_b(BaseTDEMProblem):
def solveAh(self, m, p): def solveAh(self, m, p):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param FieldsTDEM p: Fields object :param simpegEM.TDEM.FieldsTDEM p: Fields object
:rtype: FieldsTDEM :rtype: simpegEM.TDEM.FieldsTDEM
:return: y :return: y
Solve the block-matrix system \\\(\\\hat{A} \\\hat{y} = \\\hat{p}\\\): Solve the block-matrix system \\\(\\\hat{A} \\\hat{y} = \\\hat{p}\\\):
@@ -207,8 +200,8 @@ class ProblemTDEM_b(BaseTDEMProblem):
def solveAht(self, m, p): def solveAht(self, m, p):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param FieldsTDEM p: Fields object :param simpegEM.TDEM.FieldsTDEM p: Fields object
:rtype: FieldsTDEM :rtype: simpegEM.TDEM.FieldsTDEM
:return: y :return: y
Solve the block-matrix system \\\(\\\hat{A}^\\\\top \\\hat{y} = \\\hat{p}\\\): Solve the block-matrix system \\\(\\\hat{A}^\\\\top \\\hat{y} = \\\hat{p}\\\):
@@ -277,8 +270,8 @@ class ProblemTDEM_b(BaseTDEMProblem):
def _AhVec(self, m, vec): def _AhVec(self, m, vec):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param FieldsTDEM vec: Fields object :param simpegEM.TDEM.FieldsTDEM vec: Fields object
:rtype: FieldsTDEM :rtype: simpegEM.TDEM.FieldsTDEM
:return: f :return: f
Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where
@@ -322,8 +315,8 @@ class ProblemTDEM_b(BaseTDEMProblem):
def _AhtVec(self, m, vec): def _AhtVec(self, m, vec):
""" """
:param numpy.array m: Conductivity model :param numpy.array m: Conductivity model
:param FieldsTDEM vec: Fields object :param simpegEM.TDEM.FieldsTDEM vec: Fields object
:rtype: FieldsTDEM :rtype: simpegEM.TDEM.FieldsTDEM
:return: f :return: f
Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where
+3 -9
View File
@@ -1,9 +1,3 @@
from __future__ import absolute_import from SurveyTDEM import * #SurveyTDEM, RxTDEM, SrcTDEM
from __future__ import unicode_literals from BaseTDEM import BaseTDEMProblem, FieldsTDEM
from __future__ import print_function from TDEM_b import ProblemTDEM_b
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .SurveyTDEM import * #SurveyTDEM, RxTDEM, SrcTDEM
from .BaseTDEM import BaseTDEMProblem, FieldsTDEM
from .TDEM_b import ProblemTDEM_b
+5 -12
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
from scipy.special import ellipk, ellipe from scipy.special import ellipk, ellipe
from scipy.constants import mu_0, pi from scipy.constants import mu_0, pi
@@ -24,7 +17,7 @@ def MagneticDipoleVectorPotential(srcLoc, obsLoc, component, moment=1., dipoleMo
#TODO: break this out! #TODO: break this out!
if type(component) in [list, tuple]: if type(component) in [list, tuple]:
out = list(range(len(component))) out = range(len(component))
for i, comp in enumerate(component): for i, comp in enumerate(component):
out[i] = MagneticDipoleVectorPotential(srcLoc, obsLoc, comp, dipoleMoment=dipoleMoment) out[i] = MagneticDipoleVectorPotential(srcLoc, obsLoc, comp, dipoleMoment=dipoleMoment)
return np.concatenate(out) return np.concatenate(out)
@@ -125,7 +118,7 @@ def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0):
""" """
if type(component) in [list, tuple]: if type(component) in [list, tuple]:
out = list(range(len(component))) out = range(len(component))
for i, comp in enumerate(component): for i, comp in enumerate(component):
out[i] = MagneticLoopVectorPotential(srcLoc, obsLoc, comp, radius, mu) out[i] = MagneticLoopVectorPotential(srcLoc, obsLoc, comp, radius, mu)
return np.concatenate(out) return np.concatenate(out)
@@ -165,11 +158,11 @@ def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0):
# % 1/r singular at r = 0 and K(m) singular at m = 1 # % 1/r singular at r = 0 and K(m) singular at m = 1
Aphi = np.zeros(n) Aphi = np.zeros(n)
# % Common factor is (mu * I) / pi with I = 1 and mu = 4e-7 * pi. # % Common factor is (mu * I) / pi with I = 1 and mu = 4e-7 * pi.
Aphi[ind] = 4e-7 / np.sqrt(m[ind]) * np.sqrt(radius/ r[ind]) *((1. - m[ind] / 2.) * K[ind] - E[ind]) Aphi[ind] = 4e-7 / np.sqrt(m[ind]) * np.sqrt(radius / r[ind]) *((1. - m[ind] / 2.) * K[ind] - E[ind])
if component == 'x': if component == 'x':
A[ind, i] = Aphi[ind] * (-y[ind] / r[ind]) A[ind, i] = Aphi[ind] * (-y[ind] / r[ind] )
elif component == 'y': elif component == 'y':
A[ind, i] = Aphi[ind] * (x[ind] / r[ind]) A[ind, i] = Aphi[ind] * ( x[ind] / r[ind] )
else: else:
raise ValueError('Invalid component') raise ValueError('Invalid component')
+2 -8
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import numpy as np import numpy as np
from scipy.constants import mu_0, epsilon_0 from scipy.constants import mu_0, epsilon_0
@@ -15,8 +9,8 @@ def omega(freq):
def k(freq, sigma, mu=mu_0, eps=epsilon_0): def k(freq, sigma, mu=mu_0, eps=epsilon_0):
""" Eq 1.47 - 1.49 in Ward and Hohmann """ """ Eq 1.47 - 1.49 in Ward and Hohmann """
w = omega(freq) w = omega(freq)
alp = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w)))**2 ) + 1) alp = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w))**2 ) + 1) )
beta = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w)))**2 ) - 1) beta = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w))**2 ) - 1) )
return alp - 1j*beta return alp - 1j*beta
+2 -8
View File
@@ -1,8 +1,2 @@
from __future__ import absolute_import from EMUtils import omega, k
from __future__ import unicode_literals from AnalyticUtils import MagneticDipoleFields, MagneticDipoleVectorPotential, MagneticLoopVectorPotential
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .EMUtils import omega, k
from .AnalyticUtils import MagneticDipoleFields, MagneticDipoleVectorPotential, MagneticLoopVectorPotential
+6 -13
View File
@@ -1,10 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
import unittest import unittest
from SimPEG import * from SimPEG import *
from SimPEG import EM from SimPEG import EM
@@ -65,7 +58,7 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False):
Src.append(EM.FDEM.Src.RawVec([rx0], freq, mesh.getEdgeInnerProduct()*S_m, S_e)) Src.append(EM.FDEM.Src.RawVec([rx0], freq, mesh.getEdgeInnerProduct()*S_m, S_e))
if verbose: if verbose:
print(' Fetching %s problem' % (fdemType)) print ' Fetching %s problem' % (fdemType)
if fdemType == 'e': if fdemType == 'e':
survey = EM.FDEM.Survey(Src) survey = EM.FDEM.Survey(Src)
@@ -90,7 +83,7 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False):
try: try:
from pymatsolver import MumpsSolver from pymatsolver import MumpsSolver
prb.Solver = MumpsSolver prb.Solver = MumpsSolver
except ImportError as e: except ImportError, e:
prb.Solver = SolverLU prb.Solver = SolverLU
return prb return prb
@@ -101,7 +94,7 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM
prb1 = getFDEMProblem(fdemType1, comp, SrcList, freq, useMu, verbose) prb1 = getFDEMProblem(fdemType1, comp, SrcList, freq, useMu, verbose)
mesh = prb1.mesh mesh = prb1.mesh
print('Cross Checking Forward: %s, %s formulations - %s' % (fdemType1, fdemType2, comp)) print 'Cross Checking Forward: %s, %s formulations - %s' % (fdemType1, fdemType2, comp)
logsig = np.log(np.ones(mesh.nC)*CONDUCTIVITY) logsig = np.log(np.ones(mesh.nC)*CONDUCTIVITY)
mu = np.ones(mesh.nC)*MU mu = np.ones(mesh.nC)*MU
@@ -119,7 +112,7 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM
d1 = survey1.dpred(m) d1 = survey1.dpred(m)
if verbose: if verbose:
print(' Problem 1 solved') print ' Problem 1 solved'
prb2 = getFDEMProblem(fdemType2, comp, SrcList, freq, useMu, verbose) prb2 = getFDEMProblem(fdemType2, comp, SrcList, freq, useMu, verbose)
@@ -128,11 +121,11 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM
d2 = survey2.dpred(m) d2 = survey2.dpred(m)
if verbose: if verbose:
print(' Problem 2 solved') print ' Problem 2 solved'
r = d2-d1 r = d2-d1
l2r = l2norm(r) l2r = l2norm(r)
tol = np.max([TOL*(10**int(np.log10(0.5* (l2norm(d1) + l2norm(d2)) ))),FLR]) tol = np.max([TOL*(10**int(np.log10(0.5* (l2norm(d1) + l2norm(d2)) ))),FLR])
print(l2norm(d1), l2norm(d2), l2r , tol, l2r < tol) print l2norm(d1), l2norm(d2), l2r , tol, l2r < tol
return l2r < tol return l2r < tol
+6 -12
View File
@@ -1,13 +1,7 @@
from __future__ import absolute_import import TDEM
from __future__ import unicode_literals import FDEM
from __future__ import print_function import Static
from __future__ import division import Base
from future import standard_library import Analytics
standard_library.install_aliases() import Utils
from . import TDEM
from . import FDEM
from . import Static
from . import Base
from . import Analytics
from . import Utils
from scipy.constants import mu_0, epsilon_0 from scipy.constants import mu_0, epsilon_0
+9 -15
View File
@@ -1,13 +1,7 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
import SimPEG.EM.Static.DC as DC import SimPEG.DCIP as DC
def run(plotIt=True): def run(plotIt=False):
cs = 25. cs = 25.
hx = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)] hx = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)]
hy = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)] hy = [(cs,7, -1.3),(cs,21),(cs,7, 1.3)]
@@ -27,15 +21,15 @@ def run(plotIt=True):
# ax.plot(xyz_rxP[:,0],xyz_rxP[:,1], 'w.') # ax.plot(xyz_rxP[:,0],xyz_rxP[:,1], 'w.')
# ax.plot(xyz_rxN[:,0],xyz_rxN[:,1], 'r.', ms = 3) # ax.plot(xyz_rxN[:,0],xyz_rxN[:,1], 'r.', ms = 3)
rx = DC.Rx.Dipole(xyz_rxP, xyz_rxN) rx = DC.RxDipole(xyz_rxP, xyz_rxN)
src = DC.Src.Dipole([rx], np.r_[-200, 0, -12.5], np.r_[+200, 0, -12.5]) src = DC.SrcDipole([rx], [-200, 0, -12.5], [+200, 0, -12.5])
survey = DC.Survey([src]) survey = DC.SurveyDC([src])
problem = DC.Problem3D_CC(mesh) problem = DC.ProblemDC_CC(mesh)
problem.pair(survey) problem.pair(survey)
try: try:
from pymatsolver import MumpsSolver from pymatsolver import MumpsSolver
problem.Solver = MumpsSolver problem.Solver = MumpsSolver
except Exception as e: except Exception, e:
pass pass
data = survey.dpred(sigma) data = survey.dpred(sigma)
@@ -67,8 +61,8 @@ def run(plotIt=True):
ax[0].set_title('Computed') ax[0].set_title('Computed')
plt.show() plt.show()
return np.linalg.norm(data-data_ana) / np.linalg.norm(data_ana) return np.linalg.norm(data-data_ana)/np.linalg.norm(data_ana)
if __name__ == '__main__': if __name__ == '__main__':
print(run()) print run(plotIt=True)
+6 -14
View File
@@ -1,11 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import Mesh, Utils, np, sp from SimPEG import Mesh, Utils, np, sp
import SimPEG.DCIP as DC import SimPEG.DCIP as DC
import time import time
@@ -65,7 +57,7 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u
model[ind] = sig[2] model[ind] = sig[2]
# Get index of the center # Get index of the center
indy = int(mesh.nCy // 2) indy = int(mesh.nCy/2)
# Plot the model for reference # Plot the model for reference
# Define core mesh extent # Define core mesh extent
@@ -132,10 +124,10 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u
tx = np.squeeze(Tx[ii][:,0:1]) tx = np.squeeze(Tx[ii][:,0:1])
tinf = tx + np.array([dl_x,dl_y,0])*dl_len*2 tinf = tx + np.array([dl_x,dl_y,0])*dl_len*2
inds = Utils.closestPoints(mesh, np.c_[tx,tinf].T) inds = Utils.closestPoints(mesh, np.c_[tx,tinf].T)
RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*([-1] / mesh.vol[inds]) RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( [-1] / mesh.vol[inds] )
else: else:
inds = Utils.closestPoints(mesh, np.asarray(Tx[ii]).T ) inds = Utils.closestPoints(mesh, np.asarray(Tx[ii]).T )
RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*([-1,1] / mesh.vol[inds]) RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( [-1,1] / mesh.vol[inds] )
# Iterative Solve # Iterative Solve
Ainvb = sp.linalg.bicgstab(P*A,P*RHS, tol=1e-5) Ainvb = sp.linalg.bicgstab(P*A,P*RHS, tol=1e-5)
@@ -151,10 +143,10 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u
dtemp = (P1*phi - P2*phi)*np.pi dtemp = (P1*phi - P2*phi)*np.pi
data.append( dtemp ) data.append( dtemp )
print('\rTransmitter {0} of {1} -> Time:{2} sec'.format(ii,len(Tx),time.time()- start_time), end=' ') print '\rTransmitter {0} of {1} -> Time:{2} sec'.format(ii,len(Tx),time.time()- start_time),
print('Transmitter {0} of {1}'.format(ii,len(Tx))) print 'Transmitter {0} of {1}'.format(ii,len(Tx))
print('Forward completed') print 'Forward completed'
# Let's just convert the 3D format into 2D (distance along line) and plot # Let's just convert the 3D format into 2D (distance along line) and plot
survey2D = DC.convertObs_DC3D_to_2D(survey, np.ones(survey.nSrc) , 'Xloc') survey2D = DC.convertObs_DC3D_to_2D(survey, np.ones(survey.nSrc) , 'Xloc')
+1 -7
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
import SimPEG.EM as EM import SimPEG.EM as EM
from SimPEG.EM import mu_0 from SimPEG.EM import mu_0
@@ -62,7 +56,7 @@ def run(plotIt=True):
try: try:
from pymatsolver import MumpsSolver from pymatsolver import MumpsSolver
prb.Solver = MumpsSolver prb.Solver = MumpsSolver
except ImportError as e: except ImportError, e:
prb.Solver = SolverLU prb.Solver = SolverLU
prb.pair(survey) prb.pair(survey)
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
import SimPEG.EM as EM import SimPEG.EM as EM
+16 -26
View File
@@ -1,10 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
from SimPEG.EM import FDEM, Analytics, mu_0 from SimPEG.EM import FDEM, Analytics, mu_0
import time import time
@@ -26,13 +19,10 @@ def run(plotIt=True):
Morrison Casing Model, and the results are used in a 2016 SEG abstract by Morrison Casing Model, and the results are used in a 2016 SEG abstract by
Yang et al. Yang et al.
.. code-block:: text - Schenkel, C.J., and H.F. Morrison, 1990, Effects of well casing on potential field measurements using downhole current sources: Geophysical prospecting, 38, 663-686.
Schenkel, C.J., and H.F. Morrison, 1990, Effects of well casing on potential field measurements using downhole current sources: Geophysical prospecting, 38, 663-686.
The model consists of: The model consists of:
- Air: Conductivity 1e-8 S/m, above z = 0 - Air: Conductivity 1e-8 S/m, above z = 0
- Background: conductivity 1e-2 S/m, below z = 0 - Background: conductivity 1e-2 S/m, below z = 0
- Casing: conductivity 1e6 S/m - Casing: conductivity 1e6 S/m
@@ -74,8 +64,8 @@ def run(plotIt=True):
casing_l = 300 # length of the casing casing_l = 300 # length of the casing
casing_r = 0.1 casing_r = 0.1
casing_a = casing_r - casing_t / 2. # inner radius casing_a = casing_r - casing_t/2. # inner radius
casing_b = casing_r + casing_t / 2. # outer radius casing_b = casing_r + casing_t/2. # outer radius
casing_z = np.r_[-casing_l,0.] casing_z = np.r_[-casing_l,0.]
@@ -85,25 +75,25 @@ def run(plotIt=True):
src_loc = np.r_[0.,0.,dsz] src_loc = np.r_[0.,0.,dsz]
inf_loc = np.r_[0.,0.,1e4] inf_loc = np.r_[0.,0.,1e4]
print('Skin Depth: ', [(500. / np.sqrt(sigmaback*_)) for _ in freqs]) print 'Skin Depth: ', [(500./np.sqrt(sigmaback*_)) for _ in freqs]
# ------------------ MESH ------------------ # ------------------ MESH ------------------
# fine cells near well bore # fine cells near well bore
csx1, csx2 = 2e-3, 60. csx1, csx2 = 2e-3, 60.
pfx1, pfx2 = 1.3, 1.3 pfx1, pfx2 = 1.3, 1.3
ncx1 = np.ceil(casing_b/csx1)+2 ncx1 = np.ceil(casing_b/csx1+2)
# pad nicely to second cell size # pad nicely to second cell size
npadx1 = np.log(csx2/csx1) // np.log(pfx1) npadx1 = np.floor(np.log(csx2/csx1) / np.log(pfx1))
hx1a,hx1b = Utils.meshTensor([(csx1,ncx1)]),Utils.meshTensor([(csx1,npadx1,pfx1)]) hx1a,hx1b = Utils.meshTensor([(csx1,ncx1)]),Utils.meshTensor([(csx1,npadx1,pfx1)])
dx1 = sum(hx1a)+sum(hx1b) dx1 = sum(hx1a)+sum(hx1b)
dx1 = dx1 // csx2 dx1 = np.floor(dx1/csx2)
hx1b *= (dx1*csx2 - sum(hx1a)) / sum(hx1b) hx1b *= (dx1*csx2 - sum(hx1a))/sum(hx1b)
# second chunk of mesh # second chunk of mesh
dx2 = 300. # uniform mesh out to here dx2 = 300. # uniform mesh out to here
ncx2 = np.ceil((dx2 - dx1) / csx2) ncx2 = np.ceil((dx2 - dx1)/csx2)
npadx2 = 45 npadx2 = 45
hx2a, hx2b = Utils.meshTensor([(csx2,ncx2)]), Utils.meshTensor([(csx2,npadx2,pfx2)]) hx2a, hx2b = Utils.meshTensor([(csx2,ncx2)]), Utils.meshTensor([(csx2,npadx2,pfx2)])
hx = np.hstack([hx1a,hx1b,hx2a,hx2b]) hx = np.hstack([hx1a,hx1b,hx2a,hx2b])
@@ -117,8 +107,8 @@ def run(plotIt=True):
# Mesh # Mesh
mesh = Mesh.CylMesh([hx,1.,hz], [0.,0.,-np.sum(hz[:npadzu+ncz-nza])]) mesh = Mesh.CylMesh([hx,1.,hz], [0.,0.,-np.sum(hz[:npadzu+ncz-nza])])
print('Mesh Extent xmax: %f,: zmin: %f, zmax: %f'%(mesh.vectorCCx.max(), mesh.vectorCCz.min(), mesh.vectorCCz.max())) print 'Mesh Extent xmax: %f,: zmin: %f, zmax: %f'%(mesh.vectorCCx.max(), mesh.vectorCCz.min(), mesh.vectorCCz.max())
print('Number of cells', mesh.nC) print 'Number of cells', mesh.nC
if plotIt is True: if plotIt is True:
fig, ax = plt.subplots(1, 1, figsize=(6, 4)) fig, ax = plt.subplots(1, 1, figsize=(6, 4))
@@ -225,13 +215,13 @@ def run(plotIt=True):
# ------------ Problem and Survey --------------- # ------------ Problem and Survey ---------------
survey = FDEM.Survey(sg_p + dg_p) survey = FDEM.Survey(sg_p + dg_p)
mapping = [('sigma', Maps.IdentityMap(mesh))] mapping = [('sigma', Maps.IdentityMap(mesh))]
problem = FDEM.Problem3D_h(mesh, mapping=mapping, Solver=solver) problem = FDEM.Problem3D_h(mesh, mapping=mapping)
problem.pair(survey) problem.pair(survey)
# ------------- Solve --------------------------- # ------------- Solve ---------------------------
t0 = time.time() t0 = time.time()
fieldsCasing = problem.fields(sigCasing) fieldsCasing = problem.fields(sigCasing)
print('Time to solve 2 sources', time.time() - t0) print 'Time to solve 2 sources', time.time() - t0
# Plot current # Plot current
@@ -258,9 +248,9 @@ def run(plotIt=True):
in1_in = in1[np.r_[inds]] in1_in = in1[np.r_[inds]]
z_in = mesh.gridFz[inds_fz,2] z_in = mesh.gridFz[inds_fz,2]
in0_in = in0_in.reshape([in0_in.shape[0]//3,3]) in0_in = in0_in.reshape([in0_in.shape[0]/3,3])
in1_in = in1_in.reshape([in1_in.shape[0]//3,3]) in1_in = in1_in.reshape([in1_in.shape[0]/3,3])
z_in = z_in.reshape([z_in.shape[0]//3,3]) z_in = z_in.reshape([z_in.shape[0]/3,3])
I0 = in0_in.sum(1).real I0 = in0_in.sum(1).real
I1 = in1_in.sum(1).real I1 = in1_in.sum(1).real
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
import SimPEG.EM as EM import SimPEG.EM as EM
from SimPEG.EM import mu_0 from SimPEG.EM import mu_0
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
from SimPEG.FLOW import Richards from SimPEG.FLOW import Richards
@@ -1,31 +1,22 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Mesh, Utils, np, SolverLU from SimPEG import Mesh, Utils, np, SolverLU
## 2D DC forward modeling example with Tensor and Curvilinear Meshes
def run(plotIt=True): def run(plotIt=True):
"""
Mesh: Basic Forward 2D DC Resistivity
=====================================
2D DC forward modeling example with Tensor and Curvilinear Meshes
"""
# Step1: Generate Tensor and Curvilinear Mesh # Step1: Generate Tensor and Curvilinear Mesh
sz = [40,40] sz = [40,40]
# Tensor Mesh
tM = Mesh.TensorMesh(sz) tM = Mesh.TensorMesh(sz)
# Curvilinear Mesh
rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate')) rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate'))
# Step2: Direct Current (DC) operator # Step2: Direct Current (DC) operator
def DCfun(mesh, pts): def DCfun(mesh, pts):
D = mesh.faceDiv D = mesh.faceDiv
G = D.T
sigma = 1e-2*np.ones(mesh.nC) sigma = 1e-2*np.ones(mesh.nC)
MsigI = mesh.getFaceInnerProduct(sigma, invProp=True, invMat=True) Msigi = mesh.getFaceInnerProduct(1./sigma)
A = -D*MsigI*D.T MsigI = Utils.sdInv(Msigi)
A = D*MsigI*G
A[-1,-1] /= mesh.vol[-1] # Remove null space A[-1,-1] /= mesh.vol[-1] # Remove null space
rhs = np.zeros(mesh.nC) rhs = np.zeros(mesh.nC)
txind = Utils.meshutils.closestPoints(mesh, pts) txind = Utils.meshutils.closestPoints(mesh, pts)
@@ -46,17 +37,39 @@ def run(plotIt=True):
if not plotIt: return if not plotIt: return
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib
from matplotlib.mlab import griddata
#Step4: Making Figure #Step4: Making Figure
fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2)) fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2))
label = ["(a)", "(b)"]
opts = {}
vmin, vmax = phitM.min(), phitM.max() vmin, vmax = phitM.min(), phitM.max()
dat = tM.plotImage(phitM, ax=axes[0], clim=(vmin, vmax), grid=True) dat = tM.plotImage(phitM, ax=axes[0], clim=(vmin, vmax), grid=True)
dat = rM.plotImage(phirM, ax=axes[1], clim=(vmin, vmax), grid=True)
#TODO: At the moment Curvilinear Mesh do not have plotimage
Xi = tM.gridCC[:,0].reshape(sz[0], sz[1], order='F')
Yi = tM.gridCC[:,1].reshape(sz[0], sz[1], order='F')
PHIrM = griddata(rM.gridCC[:,0], rM.gridCC[:,1], phirM, Xi, Yi, interp='linear')
axes[1].contourf(Xi, Yi, PHIrM, 100, vmin=vmin, vmax=vmax)
cb = plt.colorbar(dat[0], ax=axes[0]); cb.set_label("Voltage (V)") cb = plt.colorbar(dat[0], ax=axes[0]); cb.set_label("Voltage (V)")
cb = plt.colorbar(dat[0], ax=axes[1]); cb.set_label("Voltage (V)") cb = plt.colorbar(dat[0], ax=axes[1]); cb.set_label("Voltage (V)")
tM.plotGrid(ax=axes[0], **opts)
axes[0].set_title('TensorMesh') axes[0].set_title('TensorMesh')
rM.plotGrid(ax=axes[1], **opts)
axes[1].set_title('CurvilinearMesh') axes[1].set_title('CurvilinearMesh')
for i in range(2):
axes[i].set_xlim(0.025, 0.975)
axes[i].set_ylim(0.025, 0.975)
axes[i].text(0., 1.0, label[i], fontsize=20)
if i==0:
axes[i].set_ylabel("y")
else:
axes[i].set_ylabel(" ")
axes[i].set_xlabel("x")
plt.show() plt.show()
+47 -25
View File
@@ -1,15 +1,7 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from SimPEG import * from SimPEG import *
def run(N=100, plotIt=True): def run(N=200, plotIt=True):
""" """
Inversion: Linear Problem Inversion: Linear Problem
========================= =========================
@@ -26,8 +18,6 @@ def run(N=100, plotIt=True):
mesh = Mesh.TensorMesh([N]) mesh = Mesh.TensorMesh([N])
m0 = np.ones(mesh.nC) * 1e-4 m0 = np.ones(mesh.nC) * 1e-4
mref = np.zeros(mesh.nC)
nk = 10 nk = 10
jk = np.linspace(1.,nk,nk) jk = np.linspace(1.,nk,nk)
p = -2. p = -2.
@@ -50,40 +40,72 @@ def run(N=100, plotIt=True):
survey = Survey.LinearSurvey() survey = Survey.LinearSurvey()
survey.pair(prob) survey.pair(prob)
survey.dobs = prob.fields(mtrue) + std_noise * np.random.randn(nk) survey.dobs = prob.fields(mtrue) + std_noise * np.random.randn(nk)
#survey.makeSyntheticData(mtrue, std=std_noise)
wd = np.ones(nk) * std_noise wd = np.ones(nk) * std_noise
#print survey.std[0]
#M = prob.mesh
# Distance weighting # Distance weighting
wr = np.sum(prob.G**2.,axis=0)**0.5 wr = np.sum(prob.G**2.,axis=0)**0.5
wr = ( wr/np.max(wr)) wr = ( wr/np.max(wr) )
reg = Regularization.Simple(mesh)
reg.wght = wr
dmis = DataMisfit.l2_DataMisfit(survey) dmis = DataMisfit.l2_DataMisfit(survey)
dmis.Wd = 1./wd dmis.Wd = 1./wd
opt = Optimization.ProjectedGNCG(maxIter=30,lower=-2.,upper=2., maxIterCG= 20, tolCG = 1e-4)
invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
invProb.curModel = m0
beta = Directives.BetaSchedule(coolingFactor=2, coolingRate=1)
target = Directives.TargetMisfit()
betaest = Directives.BetaEstimate_ByEig() betaest = Directives.BetaEstimate_ByEig()
inv = Inversion.BaseInversion(invProb, directiveList=[beta, betaest, target])
mrec = inv.run(m0)
ml2 = mrec
print "Final misfit:" + str(invProb.dmisfit.eval(mrec))
# Switch regularization to sparse
phim = invProb.phi_m_last
phid = invProb.phi_d
reg = Regularization.Sparse(mesh) reg = Regularization.Sparse(mesh)
reg.mref = mref
reg.cell_weights = wr
#==============================================================================
# fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2))
# dmdx = reg.mesh.cellDiffxStencil * mrec
# plt.plot(np.sort(dmdx))
#==============================================================================
#reg.recModel = mrec
reg.wght = np.ones(mesh.nC)
reg.mref = np.zeros(mesh.nC) reg.mref = np.zeros(mesh.nC)
reg.eps_p = 5e-2
reg.eps_q = 1e-2
reg.norms = [0., 0., 2., 2.]
reg.wght = wr
opt = Optimization.ProjectedGNCG(maxIter=10 ,lower=-2.,upper=2., maxIterLS = 20, maxIterCG= 20, tolCG = 1e-3)
invProb = InvProblem.BaseInvProblem(dmis, reg, opt, beta = invProb.beta*2.)
beta = Directives.BetaSchedule(coolingFactor=1, coolingRate=1)
#betaest = Directives.BetaEstimate_ByEig()
target = Directives.TargetMisfit()
IRLS =Directives.Update_IRLS( phi_m_last = phim, phi_d_last = phid )
opt = Optimization.ProjectedGNCG(maxIter=100 ,lower=-2.,upper=2., maxIterLS = 20, maxIterCG= 10, tolCG = 1e-3) inv = Inversion.BaseInversion(invProb, directiveList=[beta,IRLS])
invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
update_Jacobi = Directives.Update_lin_PreCond()
# Set the IRLS directive, penalize the lowest 25 percentile of model values m0 = mrec
# Start with an l2-l2, then switch to lp-norms
norms = [0., 0., 2., 2.]
IRLS = Directives.Update_IRLS( norms=norms, prctile = 25, maxIRLSiter = 15, minGNiter=3)
inv = Inversion.BaseInversion(invProb, directiveList=[IRLS,betaest,update_Jacobi])
# Run inversion # Run inversion
mrec = inv.run(m0) mrec = inv.run(m0)
print("Final misfit:" + str(invProb.dmisfit.eval(mrec))) print "Final misfit:" + str(invProb.dmisfit.eval(mrec))
if plotIt: if plotIt:
@@ -95,7 +117,7 @@ def run(N=100, plotIt=True):
axes[0].set_title('Columns of matrix G') axes[0].set_title('Columns of matrix G')
axes[1].plot(mesh.vectorCCx, mtrue, 'b-') axes[1].plot(mesh.vectorCCx, mtrue, 'b-')
axes[1].plot(mesh.vectorCCx, reg.l2model, 'r-') axes[1].plot(mesh.vectorCCx, ml2, 'r-')
#axes[1].legend(('True Model', 'Recovered Model')) #axes[1].legend(('True Model', 'Recovered Model'))
axes[1].set_ylim(-1.0,1.25) axes[1].set_ylim(-1.0,1.25)
-7
View File
@@ -1,10 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
+3 -9
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import SimPEG as simpeg import SimPEG as simpeg
import numpy as np import numpy as np
import SimPEG.MT as MT import SimPEG.MT as MT
@@ -13,7 +7,7 @@ import matplotlib.pyplot as plt
def run(plotIt=True): def run(plotIt=True):
""" """
MT: 1D: Inversion MT: 1D: Inversion
================= =======================
Forward model 1D MT data. Forward model 1D MT data.
Setup and run a MT 1D inversion. Setup and run a MT 1D inversion.
@@ -56,7 +50,7 @@ def run(plotIt=True):
m_0 = np.log(sigma_0[active]) m_0 = np.log(sigma_0[active])
# Set the mapping # Set the mapping
actMap = simpeg.Maps.InjectActiveCells(m1d, active, np.log(1e-8), nC=m1d.nCx) actMap = simpeg.Maps.ActiveCells(m1d, active, np.log(1e-8), nC=m1d.nCx)
mappingExpAct = simpeg.Maps.ExpMap(m1d) * actMap mappingExpAct = simpeg.Maps.ExpMap(m1d) * actMap
## Setup the layout of the survey, set the sources and the connected receivers ## Setup the layout of the survey, set the sources and the connected receivers
@@ -82,7 +76,7 @@ def run(plotIt=True):
survey.dobs = survey.dtrue + 0.025*abs(survey.dtrue)*np.random.randn(*survey.dtrue.shape) survey.dobs = survey.dtrue + 0.025*abs(survey.dtrue)*np.random.randn(*survey.dtrue.shape)
if plotIt: if plotIt:
fig = MT.Utils.dataUtils.plotMT1DModelData(problem, [m_0]) fig = MT.Utils.dataUtils.plotMT1DModelData(problem)
fig.suptitle('Target - smooth true') fig.suptitle('Target - smooth true')
+4 -9
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
# Test script to use SimPEG.MT platform to forward model synthetic data. # Test script to use SimPEG.MT platform to forward model synthetic data.
# Import # Import
@@ -18,7 +12,7 @@ except:
def run(plotIt=True, nFreq=1): def run(plotIt=True, nFreq=1):
""" """
MT: 3D: Forward MT: 3D: Forward
=============== =======================
Forward model 3D MT data. Forward model 3D MT data.
@@ -52,15 +46,16 @@ def run(plotIt=True, nFreq=1):
survey = MT.Survey(srcList) survey = MT.Survey(srcList)
## Setup the problem object ## Setup the problem object
problem = MT.Problem3D.eForm_ps(M, sigmaPrimary=sigBG, Solver=Solver) problem = MT.Problem3D.eForm_ps(M, sigmaPrimary=sigBG)
problem.pair(survey) problem.pair(survey)
problem.Solver = Solver
# Calculate the data # Calculate the data
fields = problem.fields(sig) fields = problem.fields(sig)
dataVec = survey.eval(fields) dataVec = survey.eval(fields)
# Make the data # Make the data
mtData = MT.Data(survey, dataVec) mtData = MT.Data(survey,dataVec)
# Add plots # Add plots
if plotIt: if plotIt:
pass pass
-69
View File
@@ -1,69 +0,0 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import dict
from future import standard_library
standard_library.install_aliases()
from SimPEG import Mesh, Maps, np
def run(plotIt=True):
"""
Maps: ComboMaps
===============
We will use an example where we want a 1D layered earth as
our model, but we want to map this to a 2D discretization to do our forward
modeling. We will also assume that we are working in log conductivity still,
so after the transformation we want to map to conductivity space.
To do this we will introduce the vertical 1D map (:class:`SimPEG.Maps.SurjectVertical1D`),
which does the first part of what we just described. The second part will be
done by the :class:`SimPEG.Maps.ExpMap` described above.
.. code-block:: python
:linenos:
M = Mesh.TensorMesh([7,5])
v1dMap = Maps.SurjectVertical1D(M)
expMap = Maps.ExpMap(M)
myMap = expMap * v1dMap
m = np.r_[0.2,1,0.1,2,2.9] # only 5 model parameters!
sig = myMap * m
If you noticed, it was pretty easy to combine maps. What is even cooler is
that the derivatives also are made for you (if everything goes right).
Just to be sure that the derivative is correct, you should always run the test
on the mapping that you create.
"""
M = Mesh.TensorMesh([7,5])
v1dMap = Maps.SurjectVertical1D(M)
expMap = Maps.ExpMap(M)
myMap = expMap * v1dMap
m = np.r_[0.2,1,0.1,2,2.9] # only 5 model parameters!
sig = myMap * m
if not plotIt: return
import matplotlib.pyplot as plt
figs, axs = plt.subplots(1,2)
axs[0].plot(m, M.vectorCCy, 'b-o')
axs[0].set_title('Model')
axs[0].set_ylabel('Depth, y')
axs[0].set_xlabel('Value, $m_i$')
axs[0].set_xlim(0,3)
axs[0].set_ylim(0,1)
clbar = plt.colorbar(M.plotImage(sig,ax=axs[1],grid=True,gridOpts=dict(color='grey'))[0])
axs[1].set_title('Physical Property')
axs[1].set_ylabel('Depth, y')
clbar.set_label('$\sigma = \exp(\mathbf{P}m)$')
plt.tight_layout()
plt.show()
if __name__ == '__main__':
run()
-47
View File
@@ -1,47 +0,0 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Mesh, Maps, Utils
def run(plotIt=True):
"""
Maps: Mesh2Mesh
===============
This mapping allows you to go from one mesh to another.
"""
M = Mesh.TensorMesh([100,100])
h1 = Utils.meshTensor([(6,7,-1.5),(6,10),(6,7,1.5)])
h1 = h1/h1.sum()
M2 = Mesh.TensorMesh([h1,h1])
V = Utils.ModelBuilder.randomModel(M.vnC, seed=79, its=50)
v = Utils.mkvc(V)
modh = Maps.Mesh2Mesh([M,M2])
modH = Maps.Mesh2Mesh([M2,M])
H = modH * v
h = modh * H
if not plotIt: return
import matplotlib.pyplot as plt
ax = plt.subplot(131)
M.plotImage(v, ax=ax)
ax.set_title('Fine Mesh (Original)')
ax = plt.subplot(132)
M2.plotImage(H,clim=[0,1],ax=ax)
ax.set_title('Course Mesh')
ax = plt.subplot(133)
M.plotImage(h,clim=[0,1],ax=ax)
ax.set_title('Fine Mesh (Interpolated)')
plt.show()
if __name__ == '__main__':
run()
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
def run(plotIt=True): def run(plotIt=True):
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
def run(plotIt=True): def run(plotIt=True):
@@ -1,11 +1,3 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from SimPEG import * from SimPEG import *
def run(plotIt=True, n=60): def run(plotIt=True, n=60):
@@ -95,7 +87,7 @@ def run(plotIt=True, n=60):
if elapsed > capture[jj]: if elapsed > capture[jj]:
PHIS += [(elapsed, phi.copy())] PHIS += [(elapsed, phi.copy())]
jj += 1 jj += 1
if ii % 10 == 0: print(ii, elapsed) if ii % 10 == 0: print ii, elapsed
ii += 1 ii += 1
if plotIt: if plotIt:
@@ -1,10 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
def run(plotIt=True): def run(plotIt=True):
+3 -11
View File
@@ -1,11 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from builtins import range
from SimPEG import * from SimPEG import *
def run(plotIt=True, n=60): def run(plotIt=True, n=60):
@@ -36,15 +28,15 @@ def run(plotIt=True, n=60):
axes[0].set_xlim([-1,17]) axes[0].set_xlim([-1,17])
axes[0].set_ylim([-1,17]) axes[0].set_ylim([-1,17])
for ii, loc in zip(list(range(M.nC)),M.gridCC): for ii, loc in zip(range(M.nC),M.gridCC):
axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='r') axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='r')
axes[0].plot(M.gridFx[:,0],M.gridFx[:,1], 'g>') axes[0].plot(M.gridFx[:,0],M.gridFx[:,1], 'g>')
for ii, loc in zip(list(range(M.nFx)),M.gridFx): for ii, loc in zip(range(M.nFx),M.gridFx):
axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='g') axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='g')
axes[0].plot(M.gridFy[:,0],M.gridFy[:,1], 'm^') axes[0].plot(M.gridFy[:,0],M.gridFy[:,1], 'm^')
for ii, loc in zip(list(range(M.nFy)),M.gridFy): for ii, loc in zip(range(M.nFy),M.gridFy):
axes[0].text(loc[0]+0.2,loc[1]+0.2,'%d'%(ii+M.nFx), color='m') axes[0].text(loc[0]+0.2,loc[1]+0.2,'%d'%(ii+M.nFx), color='m')
axes[1].spy(M.faceDiv) axes[1].spy(M.faceDiv)
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
def run(plotIt=True): def run(plotIt=True):
-6
View File
@@ -1,9 +1,3 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
def run(plotIt=True): def run(plotIt=True):
+7 -15
View File
@@ -1,19 +1,9 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import * from SimPEG import *
from SimPEG.Utils import surface2ind_topo from SimPEG.Utils import surface2ind_topo
def run(plotIt=True, nx=5, ny=5): def run(plotIt=False, nx = 5, ny = 5):
""" """
Utils: surface2ind_topo
=======================
Here we show how to use :code:`Utils.surface2ind_topo` to identify cells below Here we show how to use :code:`Utils.surface2ind_topo` to identify cells below
a topographic surface. a topographic surface.
@@ -23,25 +13,27 @@ def run(plotIt=True, nx=5, ny=5):
xtopo = np.linspace(mesh.gridN[:,0].min(), mesh.gridN[:,0].max()) xtopo = np.linspace(mesh.gridN[:,0].min(), mesh.gridN[:,0].max())
topo = 0.4*np.sin(xtopo*5) # define a topographic surface topo = 0.4*np.sin(xtopo*5) # define a topographic surface
Topo = np.hstack([Utils.mkvc(xtopo,2), Utils.mkvc(topo,2)]) #make it an array Topo = np.hstack([Utils.mkvc(xtopo,2),Utils.mkvc(topo,2)]) #make it an array
indcc = surface2ind_topo(mesh, Topo, 'CC') indcc = surface2ind_topo(mesh, Topo,'CC')
if plotIt: if plotIt:
from matplotlib.pylab import plt from matplotlib.pylab import plt
from scipy.interpolate import interp1d from scipy.interpolate import interp1d
fig, ax = plt.subplots(1,1, figsize=(6,6)) fig, ax = plt.subplots(1,1,figsize=(6,6))
mesh.plotGrid(ax=ax, nodes=True, centers=True) mesh.plotGrid(ax=ax, nodes=True, centers=True)
ax.plot(xtopo,topo,'k',linewidth=1) ax.plot(xtopo,topo,'k',linewidth=1)
# ax.plot(mesh.vectorNx, interp1d(xtopo,topo)(mesh.vectorNx),'--k',linewidth=3)
ax.plot(mesh.vectorCCx, interp1d(xtopo,topo)(mesh.vectorCCx),'--k',linewidth=3) ax.plot(mesh.vectorCCx, interp1d(xtopo,topo)(mesh.vectorCCx),'--k',linewidth=3)
aveN2CC = Utils.sdiag(mesh.aveN2CC.T.sum(1))*mesh.aveN2CC.T aveN2CC = Utils.sdiag(mesh.aveN2CC.T.sum(1))*mesh.aveN2CC.T
a = aveN2CC * indcc a = aveN2CC * indcc
a[a > 0] = 1. a[a > 0] = 1.
a[a < 0.25] = np.nan a[a < 0.25] = np.nan
a = a.reshape(mesh.vnN, order='F') a = a.reshape(mesh.vnN, order='F')
masked_array = np.ma.array(a, mask=np.isnan(a)) masked_array = np.ma.array(a, mask=np.isnan(a))
ax.pcolor(mesh.vectorNx,mesh.vectorNy,masked_array.T, cmap=plt.cm.gray, alpha=0.2) ax.pcolor(mesh.vectorNx,mesh.vectorNy,masked_array.T, cmap = plt.cm.gray,alpha=0.2)
plt.show() plt.show()
+25 -34
View File
@@ -1,37 +1,28 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
from builtins import open
from future import standard_library
standard_library.install_aliases()
# Run this file to add imports. # Run this file to add imports.
##### AUTOIMPORTS ##### ##### AUTOIMPORTS #####
from . import DC_Analytic_Dipole import DC_Analytic_Dipole
from . import DC_Forward_PseudoSection import DC_Forward_PseudoSection
from . import EM_FDEM_1D_Inversion import EM_FDEM_1D_Inversion
from . import EM_FDEM_Analytic_MagDipoleWholespace import EM_FDEM_Analytic_MagDipoleWholespace
from . import EM_Schenkel_Morrison_Casing import EM_Schenkel_Morrison_Casing
from . import EM_TDEM_1D_Inversion import EM_TDEM_1D_Inversion
from . import FLOW_Richards_1D_Celia1990 import FLOW_Richards_1D_Celia1990
from . import Inversion_IRLS import Forward_BasicDirectCurrent
from . import Inversion_Linear import Inversion_IRLS
from . import Maps_ComboMaps import Inversion_Linear
from . import Maps_Mesh2Mesh import Mesh_Basic_PlotImage
from . import Mesh_Basic_ForwardDC import Mesh_Basic_Types
from . import Mesh_Basic_PlotImage import Mesh_Operators_CahnHilliard
from . import Mesh_Basic_Types import Mesh_QuadTree_Creation
from . import Mesh_Operators_CahnHilliard import Mesh_QuadTree_FaceDiv
from . import Mesh_QuadTree_Creation import Mesh_QuadTree_HangingNodes
from . import Mesh_QuadTree_FaceDiv import Mesh_Tensor_Creation
from . import Mesh_QuadTree_HangingNodes import MT_1D_ForwardAndInversion
from . import Mesh_Tensor_Creation import MT_3D_Foward
from . import MT_1D_ForwardAndInversion import Utils_surface2ind_topo
from . import MT_3D_Foward
from . import Utils_surface2ind_topo
__examples__ = ["DC_Analytic_Dipole", "DC_Forward_PseudoSection", "EM_FDEM_1D_Inversion", "EM_FDEM_Analytic_MagDipoleWholespace", "EM_Schenkel_Morrison_Casing", "EM_TDEM_1D_Inversion", "FLOW_Richards_1D_Celia1990", "Inversion_IRLS", "Inversion_Linear", "Maps_ComboMaps", "Maps_Mesh2Mesh", "Mesh_Basic_ForwardDC", "Mesh_Basic_PlotImage", "Mesh_Basic_Types", "Mesh_Operators_CahnHilliard", "Mesh_QuadTree_Creation", "Mesh_QuadTree_FaceDiv", "Mesh_QuadTree_HangingNodes", "Mesh_Tensor_Creation", "MT_1D_ForwardAndInversion", "MT_3D_Foward", "Utils_surface2ind_topo"] __examples__ = ["DC_Analytic_Dipole", "DC_Forward_PseudoSection", "EM_FDEM_1D_Inversion", "EM_FDEM_Analytic_MagDipoleWholespace", "EM_Schenkel_Morrison_Casing", "EM_TDEM_1D_Inversion", "FLOW_Richards_1D_Celia1990", "Forward_BasicDirectCurrent", "Inversion_IRLS", "Inversion_Linear", "Mesh_Basic_PlotImage", "Mesh_Basic_Types", "Mesh_Operators_CahnHilliard", "Mesh_QuadTree_Creation", "Mesh_QuadTree_FaceDiv", "Mesh_QuadTree_HangingNodes", "Mesh_Tensor_Creation", "MT_1D_ForwardAndInversion", "MT_3D_Foward", "Utils_surface2ind_topo"]
##### AUTOIMPORTS ##### ##### AUTOIMPORTS #####
@@ -47,7 +38,7 @@ if __name__ == '__main__':
# Create the examples dir in the docs folder. # Create the examples dir in the docs folder.
fName = os.path.realpath(__file__) fName = os.path.realpath(__file__)
docExamplesDir = os.path.sep.join(fName.split(os.path.sep)[:-3] + ['docs', 'content', 'examples']) docExamplesDir = os.path.sep.join(fName.split(os.path.sep)[:-3] + ['docs', 'examples'])
shutil.rmtree(docExamplesDir) shutil.rmtree(docExamplesDir)
os.makedirs(docExamplesDir) os.makedirs(docExamplesDir)
@@ -104,14 +95,14 @@ if __name__ == '__main__':
from SimPEG import Examples from SimPEG import Examples
Examples.%s.run() Examples.%s.run()
.. literalinclude:: ../../../SimPEG/Examples/%s.py .. literalinclude:: ../../SimPEG/Examples/%s.py
:language: python :language: python
:linenos: :linenos:
"""%(name,doc,name,name) """%(name,doc,name,name)
rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'content', 'examples', name + '.rst'])) rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'examples', name + '.rst']))
print('Creating: %s.rst'%name) print 'Creating: %s.rst'%name
f = open(rst, 'w') f = open(rst, 'w')
f.write(out) f.write(out)
f.close() f.close()
+8 -14
View File
@@ -1,20 +1,14 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
from SimPEG import Mesh, Maps, Utils, np from SimPEG import Mesh, Maps, Utils, np
from future.utils import with_metaclass
class NonLinearMap(with_metaclass(Utils.SimPEGMetaClass, object)): class NonLinearMap(object):
""" """
SimPEG NonLinearMap SimPEG NonLinearMap
""" """
__metaclass__ = Utils.SimPEGMetaClass
counter = None #: A SimPEG.Utils.Counter object counter = None #: A SimPEG.Utils.Counter object
mesh = None #: A SimPEG Mesh mesh = None #: A SimPEG Mesh
@@ -37,7 +31,7 @@ class NonLinearMap(with_metaclass(Utils.SimPEGMetaClass, object)):
""" """
:param numpy.array u: fields :param numpy.array u: fields
:param numpy.array m: model :param numpy.array m: model
:rtype: scipy.sparse.csr_matrix :rtype: scipy.csr_matrix
:return: derivative of transformed model :return: derivative of transformed model
The *transform* changes the model into the physical property. The *transform* changes the model into the physical property.
@@ -50,7 +44,7 @@ class NonLinearMap(with_metaclass(Utils.SimPEGMetaClass, object)):
""" """
:param numpy.array u: fields :param numpy.array u: fields
:param numpy.array m: model :param numpy.array m: model
:rtype: scipy.sparse.csr_matrix :rtype: scipy.csr_matrix
:return: derivative of transformed model :return: derivative of transformed model
The *transform* changes the model into the physical property. The *transform* changes the model into the physical property.
@@ -192,7 +186,7 @@ class _haverkamp_theta(NonLinearMap):
def transformDerivU(self, u, m): def transformDerivU(self, u, m):
self.setModel(m) self.setModel(m)
g = (self.alpha*((self.theta_s - self.theta_r) / g = (self.alpha*((self.theta_s - self.theta_r)/
(self.alpha + abs(u)**self.beta)**2) (self.alpha + abs(u)**self.beta)**2)
*(-self.beta*abs(u)**(self.beta-1)*np.sign(u))) *(-self.beta*abs(u)**(self.beta-1)*np.sign(u)))
g[u >= 0] = 0 g[u >= 0] = 0
@@ -279,7 +273,7 @@ class _vangenuchten_theta(NonLinearMap):
def transform(self, u, m): def transform(self, u, m):
self.setModel(m) self.setModel(m)
m = 1 - 1.0/self.n m = 1 - 1.0/self.n
f = (( self.theta_s - self.theta_r ) / f = (( self.theta_s - self.theta_r )/
((1+abs(self.alpha*u)**self.n)**m) + self.theta_r) ((1+abs(self.alpha*u)**self.n)**m) + self.theta_r)
if Utils.isScalar(self.theta_s): if Utils.isScalar(self.theta_s):
f[u >= 0] = self.theta_s f[u >= 0] = self.theta_s
@@ -349,7 +343,7 @@ class _vangenuchten_k(NonLinearMap):
Ks = self.Ks Ks = self.Ks
m = 1.0 - 1.0/n m = 1.0 - 1.0/n
g = I*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1.0)*np.sign(alpha*u)*(1.0/n - 1.0)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**(I - 1)*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)**2*(abs(alpha*u)**n + 1)**(1.0/n - 2) - (2*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1)*np.sign(alpha*u)*(1.0/n - 1)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**I*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)*(abs(alpha*u)**n + 1)**(1.0/n - 2))/(((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1))+ 1)*(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1.0/n) g = I*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1.0)*np.sign(alpha*u)*(1.0/n - 1.0)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**(I - 1)*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)**2*(abs(alpha*u)**n + 1)**(1.0/n - 2) - (2*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1)*np.sign(alpha*u)*(1.0/n - 1)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**I*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)*(abs(alpha*u)**n + 1)**(1.0/n - 2))/(((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1) + 1)*(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1.0/n))
g[u >= 0] = 0 g[u >= 0] = 0
g = Utils.sdiag(g) g = Utils.sdiag(g)
return g return g
+8 -15
View File
@@ -1,12 +1,5 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import range
from SimPEG import * from SimPEG import *
from .Empirical import RichardsMap from Empirical import RichardsMap
import time import time
@@ -68,7 +61,7 @@ class RichardsSurvey(Survey.BaseSurvey):
@Utils.requires('prob') @Utils.requires('prob')
def eval(self, U, m): def eval(self, U, m):
Ds = list(range(len(self.rxList))) Ds = range(len(self.rxList))
for ii, rx in enumerate(self.rxList): for ii, rx in enumerate(self.rxList):
Ds[ii] = rx.eval(U, m, Ds[ii] = rx.eval(U, m,
self.prob.mapping, self.prob.mapping,
@@ -80,7 +73,7 @@ class RichardsSurvey(Survey.BaseSurvey):
@Utils.requires('prob') @Utils.requires('prob')
def evalDeriv(self, U, m): def evalDeriv(self, U, m):
"""The Derivative with respect to the fields.""" """The Derivative with respect to the fields."""
Ds = list(range(len(self.rxList))) Ds = range(len(self.rxList))
for ii, rx in enumerate(self.rxList): for ii, rx in enumerate(self.rxList):
Ds[ii] = rx.evalDeriv(U, m, Ds[ii] = rx.evalDeriv(U, m,
self.prob.mapping, self.prob.mapping,
@@ -142,12 +135,12 @@ class RichardsProblem(Problem.BaseTimeProblem):
@Utils.timeIt @Utils.timeIt
def fields(self, m): def fields(self, m):
tic = time.time() tic = time.time()
u = list(range(self.nT+1)) u = range(self.nT+1)
u[0] = self.initialConditions u[0] = self.initialConditions
for ii, dt in enumerate(self.timeSteps): for ii, dt in enumerate(self.timeSteps):
bc = self.getBoundaryConditions(ii, u[ii]) bc = self.getBoundaryConditions(ii, u[ii])
u[ii+1] = self.rootFinder.root(lambda hn1m, return_g=True: self.getResidual(m, u[ii], hn1m, dt, bc, return_g=return_g), u[ii]) u[ii+1] = self.rootFinder.root(lambda hn1m, return_g=True: self.getResidual(m, u[ii], hn1m, dt, bc, return_g=return_g), u[ii])
if self.debug: print("Solving Fields (%4d/%d - %3.1f%% Done) %d Iterations, %4.2f seconds"%(ii+1, self.nT, 100.0*(ii+1)/self.nT, self.rootFinder.iter, time.time() - tic)) if self.debug: print "Solving Fields (%4d/%d - %3.1f%% Done) %d Iterations, %4.2f seconds"%(ii+1, self.nT, 100.0*(ii+1)/self.nT, self.rootFinder.iter, time.time() - tic)
return u return u
@Utils.timeIt @Utils.timeIt
@@ -245,7 +238,7 @@ class RichardsProblem(Problem.BaseTimeProblem):
f = self.fields(m) f = self.fields(m)
nn = len(f)-1 nn = len(f)-1
Asubs, Adiags, Bs = list(range(nn)), list(range(nn)), list(range(nn)) Asubs, Adiags, Bs = range(nn), range(nn), range(nn)
for ii in range(nn): for ii in range(nn):
dt = self.timeSteps[ii] dt = self.timeSteps[ii]
bc = self.getBoundaryConditions(ii, f[ii]) bc = self.getBoundaryConditions(ii, f[ii])
@@ -270,7 +263,7 @@ class RichardsProblem(Problem.BaseTimeProblem):
if f is None: if f is None:
f = self.fields(m) f = self.fields(m)
JvC = list(range(len(f)-1)) # Cell to hold each row of the long vector. JvC = range(len(f)-1) # Cell to hold each row of the long vector.
# This is done via forward substitution. # This is done via forward substitution.
bc = self.getBoundaryConditions(0, f[0]) bc = self.getBoundaryConditions(0, f[0])
@@ -302,7 +295,7 @@ class RichardsProblem(Problem.BaseTimeProblem):
bc = self.getBoundaryConditions(ii-1, f[ii-1]) bc = self.getBoundaryConditions(ii-1, f[ii-1])
Asub, Adiag, B = self.diagsJacobian(m, f[ii-1], f[ii], self.timeSteps[ii-1], bc) Asub, Adiag, B = self.diagsJacobian(m, f[ii-1], f[ii], self.timeSteps[ii-1], bc)
#select the correct part of v #select the correct part of v
vpart = list(range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0])) vpart = range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0])
AdiaginvT = self.Solver(Adiag.T, **self.solverOpts) AdiaginvT = self.Solver(Adiag.T, **self.solverOpts)
JTvC = AdiaginvT * (PTv[vpart] - minus) JTvC = AdiaginvT * (PTv[vpart] - minus)
minus = Asub.T*JTvC # this is now the super diagonal. minus = Asub.T*JTvC # this is now the super diagonal.
+2 -8
View File
@@ -1,8 +1,2 @@
from __future__ import absolute_import import Empirical
from __future__ import unicode_literals from RichardsProblem import *
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from . import Empirical
from .RichardsProblem import *
+1 -7
View File
@@ -1,7 +1 @@
from __future__ import absolute_import import Richards
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from . import Richards
+2 -11
View File
@@ -1,13 +1,4 @@
from __future__ import division import Utils, numpy as np, scipy.sparse as sp
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import range
from builtins import object
from . import Utils
import numpy as np, scipy.sparse as sp
class Fields(object): class Fields(object):
"""Fancy Field Storage """Fancy Field Storage
@@ -253,7 +244,7 @@ class TimeFields(Fields):
out = func(pointerFields, srcII, timeII) out = func(pointerFields, srcII, timeII)
else: #loop over the time steps else: #loop over the time steps
nT = pointerShape[2] nT = pointerShape[2]
out = list(range(nT)) out = range(nT)
for i, TIND_i in enumerate(timeII): for i, TIND_i in enumerate(timeII):
fieldI = pointerFields[:,:,i] fieldI = pointerFields[:,:,i]
if fieldI.shape[0] == fieldI.size: if fieldI.shape[0] == fieldI.size:
+12 -19
View File
@@ -1,21 +1,14 @@
from __future__ import print_function import Utils, Survey, Problem, numpy as np, scipy.sparse as sp, gc
from __future__ import absolute_import from Utils.SolverUtils import *
from __future__ import unicode_literals import DataMisfit
from __future__ import division import Regularization
from future import standard_library
standard_library.install_aliases()
from builtins import object
from . import Utils, Survey, Problem
import numpy as np, scipy.sparse as sp, gc
from .Utils.SolverUtils import *
from . import DataMisfit
from . import Regularization
from future.utils import with_metaclass
class BaseInvProblem(with_metaclass(Utils.SimPEGMetaClass, object)): class BaseInvProblem(object):
"""BaseInvProblem(dmisfit, reg, opt)""" """BaseInvProblem(dmisfit, reg, opt)"""
__metaclass__ = Utils.SimPEGMetaClass
beta = 1.0 #: Trade-off parameter beta = 1.0 #: Trade-off parameter
debug = False #: Print debugging information debug = False #: Print debugging information
@@ -61,10 +54,10 @@ class BaseInvProblem(with_metaclass(Utils.SimPEGMetaClass, object)):
Called when inversion is first starting. Called when inversion is first starting.
""" """
if self.debug: print('Calling InvProblem.startup') if self.debug: print 'Calling InvProblem.startup'
if self.reg.mref is None: if self.reg.mref is None:
print('SimPEG.InvProblem will set Regularization.mref to m0.') print 'SimPEG.InvProblem will set Regularization.mref to m0.'
self.reg.mref = m0 self.reg.mref = m0
self.phi_d = np.nan self.phi_d = np.nan
@@ -72,8 +65,8 @@ class BaseInvProblem(with_metaclass(Utils.SimPEGMetaClass, object)):
self.curModel = m0 self.curModel = m0
print("""SimPEG.InvProblem is setting bfgsH0 to the inverse of the eval2Deriv. print """SimPEG.InvProblem is setting bfgsH0 to the inverse of the eval2Deriv.
***Done using same Solver and solverOpts as the problem***""") ***Done using same Solver and solverOpts as the problem***"""
self.opt.bfgsH0 = self.prob.Solver(self.reg.eval2Deriv(self.curModel), **self.prob.solverOpts) self.opt.bfgsH0 = self.prob.Solver(self.reg.eval2Deriv(self.curModel), **self.prob.solverOpts)
@property @property
@@ -94,7 +87,7 @@ class BaseInvProblem(with_metaclass(Utils.SimPEGMetaClass, object)):
for mtest, u_ofmtest in self.warmstart: for mtest, u_ofmtest in self.warmstart:
if m is mtest: if m is mtest:
f = u_ofmtest f = u_ofmtest
if self.debug: print('InvProb is Warm Starting!') if self.debug: print 'InvProb is Warm Starting!'
break break
if f is None: if f is None:
+5 -11
View File
@@ -1,24 +1,18 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import object
import SimPEG import SimPEG
from SimPEG import Utils, sp, np from SimPEG import Utils, sp, np
from .Optimization import Remember, IterationPrinters, StoppingCriteria from Optimization import Remember, IterationPrinters, StoppingCriteria
from . import Directives import Directives
from future.utils import with_metaclass
class BaseInversion(with_metaclass(Utils.SimPEGMetaClass, object)): class BaseInversion(object):
""" """
Inversion Class. Inversion Class.
""" """
__metaclass__ = Utils.SimPEGMetaClass
name = 'BaseInversion' name = 'BaseInversion'
debug = False #: Print debugging information debug = False #: Print debugging information
+2 -8
View File
@@ -1,13 +1,7 @@
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from SimPEG import SolverLU as SimpegSolver, PropMaps, Utils, mkvc, sp, np from SimPEG import SolverLU as SimpegSolver, PropMaps, Utils, mkvc, sp, np
from SimPEG.EM.FDEM.ProblemFDEM import BaseFDEMProblem from SimPEG.EM.FDEM.ProblemFDEM import BaseFDEMProblem
from .SurveyMT import Survey, Data from SurveyMT import Survey, Data
from .FieldsMT import BaseMTFields from FieldsMT import BaseMTFields
class BaseMTProblem(BaseFDEMProblem): class BaseMTProblem(BaseFDEMProblem):
+5 -11
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Survey, Utils, Problem, np, sp, mkvc from SimPEG import Survey, Utils, Problem, np, sp, mkvc
from scipy.constants import mu_0 from scipy.constants import mu_0
import sys import sys
@@ -69,7 +63,7 @@ class Fields1D_e(BaseMTFields):
C = self.mesh.nodalGrad C = self.mesh.nodalGrad
b = (C * eSolution) b = (C * eSolution)
for i, src in enumerate(srcList): for i, src in enumerate(srcList):
b[:,i] *= -1./(1j*omega(src.freq)) b[:,i] *= - 1./(1j*omega(src.freq))
# There is no magnetic source in the MT problem # There is no magnetic source in the MT problem
# S_m, _ = src.eval(self.survey.prob) # S_m, _ = src.eval(self.survey.prob)
# if S_m is not None: # if S_m is not None:
@@ -194,7 +188,7 @@ class Fields3D_e(BaseMTFields):
# adjoint: returns a 2*nE long vector with zero's for py # adjoint: returns a 2*nE long vector with zero's for py
return np.vstack((v,np.zeros_like(v))) return np.vstack((v,np.zeros_like(v)))
# Not adjoint: return only the px part of the vector # Not adjoint: return only the px part of the vector
return v[:len(v)//2] return v[:len(v)/2]
def _e_pyDeriv_u(self, src, v, adjoint = False): def _e_pyDeriv_u(self, src, v, adjoint = False):
''' '''
@@ -204,7 +198,7 @@ class Fields3D_e(BaseMTFields):
# adjoint: returns a 2*nE long vector with zero's for px # adjoint: returns a 2*nE long vector with zero's for px
return np.vstack((np.zeros_like(v),v)) return np.vstack((np.zeros_like(v),v))
# Not adjoint: return only the px part of the vector # Not adjoint: return only the px part of the vector
return v[len(v)//2::] return v[len(v)/2::]
def _e_pxDeriv_m(self, src, v, adjoint = False): def _e_pxDeriv_m(self, src, v, adjoint = False):
# assuming primary does not depend on the model # assuming primary does not depend on the model
@@ -233,7 +227,7 @@ class Fields3D_e(BaseMTFields):
C = self.mesh.edgeCurl C = self.mesh.edgeCurl
b = (C * e_pxSolution) b = (C * e_pxSolution)
for i, src in enumerate(srcList): for i, src in enumerate(srcList):
b[:,i] *= -1./(1j*omega(src.freq)) b[:,i] *= - 1./(1j*omega(src.freq))
# There is no magnetic source in the MT problem # There is no magnetic source in the MT problem
# S_m, _ = src.eval(self.survey.prob) # S_m, _ = src.eval(self.survey.prob)
# if S_m is not None: # if S_m is not None:
@@ -244,7 +238,7 @@ class Fields3D_e(BaseMTFields):
C = self.mesh.edgeCurl C = self.mesh.edgeCurl
b = (C * e_pySolution) b = (C * e_pySolution)
for i, src in enumerate(srcList): for i, src in enumerate(srcList):
b[:,i] *= -1./(1j*omega(src.freq)) b[:,i] *= - 1./(1j*omega(src.freq))
# There is no magnetic source in the MT problem # There is no magnetic source in the MT problem
# S_m, _ = src.eval(self.survey.prob) # S_m, _ = src.eval(self.survey.prob)
# if S_m is not None: # if S_m is not None:
+7 -13
View File
@@ -1,9 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG.EM.Utils import omega from SimPEG.EM.Utils import omega
from SimPEG import mkvc from SimPEG import mkvc
from scipy.constants import mu_0 from scipy.constants import mu_0
@@ -52,7 +46,7 @@ class eForm_psField(BaseMTProblem):
Edge inner product matrix Edge inner product matrix
""" """
if getattr(self, '_MeMui', None) is None: if getattr(self, '_MeMui', None) is None:
self._MeMui = self.mesh.getEdgeInnerProduct(old_div(1.0,mu_0)) self._MeMui = self.mesh.getEdgeInnerProduct(1.0/mu_0)
return self._MeMui return self._MeMui
@property @property
@@ -148,7 +142,7 @@ class eForm_psField(BaseMTProblem):
for freq in self.survey.freqs: for freq in self.survey.freqs:
if self.verbose: if self.verbose:
startTime = time.time() startTime = time.time()
print('Starting work for {:.3e}'.format(freq)) print 'Starting work for {:.3e}'.format(freq)
sys.stdout.flush() sys.stdout.flush()
A = self.getA(freq) A = self.getA(freq)
rhs = self.getRHS(freq) rhs = self.getRHS(freq)
@@ -164,7 +158,7 @@ class eForm_psField(BaseMTProblem):
# b = -( self.mesh.nodalGrad * e )/( 1j*omega(freq) ) # b = -( self.mesh.nodalGrad * e )/( 1j*omega(freq) )
# F[Src, 'b_1d'] = b[:,1] # F[Src, 'b_1d'] = b[:,1]
if self.verbose: if self.verbose:
print('Ran for {:f} seconds'.format(time.time()-startTime)) print 'Ran for {:f} seconds'.format(time.time()-startTime)
sys.stdout.flush() sys.stdout.flush()
return F return F
@@ -197,7 +191,7 @@ class eForm_TotalField(BaseMTProblem):
Edge inner product matrix Edge inner product matrix
""" """
if getattr(self, '_MeMui', None) is None: if getattr(self, '_MeMui', None) is None:
self._MeMui = self.mesh.getEdgeInnerProduct(old_div(1.0,mu_0)) self._MeMui = self.mesh.getEdgeInnerProduct(1.0/mu_0)
return self._MeMui return self._MeMui
@property @property
@@ -255,7 +249,7 @@ class eForm_TotalField(BaseMTProblem):
Ed, Eu, Hd, Hu = getEHfields(self.mesh,self.curModel.sigma,freq,self.mesh.vectorNx) Ed, Eu, Hd, Hu = getEHfields(self.mesh,self.curModel.sigma,freq,self.mesh.vectorNx)
Etot = (Ed + Eu) Etot = (Ed + Eu)
sourceAmp = 1.0 sourceAmp = 1.0
Etot = ((old_div(Etot,Etot[-1]))*sourceAmp) # Scale the fields to be equal to sourceAmp at the top Etot = ((Etot/Etot[-1])*sourceAmp) # Scale the fields to be equal to sourceAmp at the top
## Note: The analytic solution is derived with e^iwt ## Note: The analytic solution is derived with e^iwt
eBC = np.r_[Etot[0],Etot[-1]] eBC = np.r_[Etot[0],Etot[-1]]
# The right hand side # The right hand side
@@ -280,7 +274,7 @@ class eForm_TotalField(BaseMTProblem):
for freq in self.survey.freqs: for freq in self.survey.freqs:
if self.verbose: if self.verbose:
startTime = time.time() startTime = time.time()
print('Starting work for {:.3e}'.format(freq)) print 'Starting work for {:.3e}'.format(freq)
sys.stdout.flush() sys.stdout.flush()
A = self.getA(freq) A = self.getA(freq)
rhs, e_o = self.getRHS(freq) rhs, e_o = self.getRHS(freq)
@@ -292,6 +286,6 @@ class eForm_TotalField(BaseMTProblem):
# NOTE: only store e fields # NOTE: only store e fields
F[Src, 'e_1dSolution'] = e[:,0] F[Src, 'e_1dSolution'] = e[:,0]
if self.verbose: if self.verbose:
print('Ran for {:f} seconds'.format(time.time()-startTime)) print 'Ran for {:f} seconds'.format(time.time()-startTime)
sys.stdout.flush() sys.stdout.flush()
return F return F
+1 -7
View File
@@ -1,7 +1 @@
from __future__ import absolute_import from Probs import eForm_TotalField, eForm_psField
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .Probs import eForm_TotalField, eForm_psField
-6
View File
@@ -1,7 +1 @@
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
pass pass
+2 -8
View File
@@ -1,9 +1,3 @@
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from SimPEG import Survey, Problem, Utils, Models, np, sp, mkvc, SolverLU as SimpegSolver from SimPEG import Survey, Problem, Utils, Models, np, sp, mkvc, SolverLU as SimpegSolver
from SimPEG.EM.Utils import omega from SimPEG.EM.Utils import omega
from scipy.constants import mu_0 from scipy.constants import mu_0
@@ -121,7 +115,7 @@ class eForm_ps(BaseMTProblem):
for freq in self.survey.freqs: for freq in self.survey.freqs:
if self.verbose: if self.verbose:
startTime = time.time() startTime = time.time()
print('Starting work for {:.3e}'.format(freq)) print 'Starting work for {:.3e}'.format(freq)
sys.stdout.flush() sys.stdout.flush()
A = self.getA(freq) A = self.getA(freq)
rhs = self.getRHS(freq) rhs = self.getRHS(freq)
@@ -137,7 +131,7 @@ class eForm_ps(BaseMTProblem):
# Note curl e = -iwb so b = -curl/iw # Note curl e = -iwb so b = -curl/iw
if self.verbose: if self.verbose:
print('Ran for {:f} seconds'.format(time.time()-startTime)) print 'Ran for {:f} seconds'.format(time.time()-startTime)
sys.stdout.flush() sys.stdout.flush()
Ainv.clean() Ainv.clean()
return F return F
+1 -7
View File
@@ -1,7 +1 @@
from __future__ import absolute_import from Probs import eForm_ps
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from .Probs import eForm_ps
+6 -12
View File
@@ -1,16 +1,10 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from SimPEG import Utils, Problem, Maps, np, sp, mkvc from SimPEG import Utils, Problem, Maps, np, sp, mkvc
from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc
from SimPEG.EM.Utils import omega from SimPEG.EM.Utils import omega
from scipy.constants import mu_0 from scipy.constants import mu_0
from numpy.lib import recfunctions as recFunc from numpy.lib import recfunctions as recFunc
from .Utils.sourceUtils import homo1DModelSource from Utils.sourceUtils import homo1DModelSource
from .Utils import rec2ndarr from Utils import rec2ndarr
import sys import sys
################# #################
@@ -84,7 +78,7 @@ class polxy_1Dprimary(BaseMTSrc):
C = problem.mesh.nodalGrad C = problem.mesh.nodalGrad
elif problem.mesh.dim == 3: elif problem.mesh.dim == 3:
C = problem.mesh.edgeCurl C = problem.mesh.edgeCurl
bBG_bp = (- C * self.ePrimary(problem) )*(1/(1j*omega(self.freq))) bBG_bp = (- C * self.ePrimary(problem) )*(1/( 1j*omega(self.freq) ))
return bBG_bp return bBG_bp
def S_e(self,problem): def S_e(self,problem):
@@ -92,7 +86,7 @@ class polxy_1Dprimary(BaseMTSrc):
Get the electrical field source Get the electrical field source
""" """
e_p = self.ePrimary(problem) e_p = self.ePrimary(problem)
Map_sigma_p = Maps.SurjectVertical1D(problem.mesh) Map_sigma_p = Maps.Vertical1DMap(problem.mesh)
sigma_p = Map_sigma_p._transform(self.sigma1d) sigma_p = Map_sigma_p._transform(self.sigma1d)
# Make mass matrix # Make mass matrix
# Note: M(sig) - M(sig_p) = M(sig - sig_p) # Note: M(sig) - M(sig_p) = M(sig - sig_p)
@@ -161,7 +155,7 @@ class polxy_3Dprimary(BaseMTSrc):
C = problem.mesh.nodalGrad C = problem.mesh.nodalGrad
elif problem.mesh.dim == 3: elif problem.mesh.dim == 3:
C = problem.mesh.edgeCurl C = problem.mesh.edgeCurl
bBG_bp = (- C * self.ePrimary(problem) )*(1/(1j*omega(self.freq))) bBG_bp = (- C * self.ePrimary(problem) )*(1/( 1j*omega(self.freq) ))
return bBG_bp return bBG_bp
def S_e(self,problem): def S_e(self,problem):
@@ -169,7 +163,7 @@ class polxy_3Dprimary(BaseMTSrc):
Get the electrical field source Get the electrical field source
""" """
e_p = self.ePrimary(problem) e_p = self.ePrimary(problem)
Map_sigma_p = Maps.SurjectVertical1D(problem.mesh) Map_sigma_p = Maps.Vertical1DMap(problem.mesh)
sigma_p = Map_sigma_p._transform(self.sigma1d) sigma_p = Map_sigma_p._transform(self.sigma1d)
# Make mass matrix # Make mass matrix
# Note: M(sig) - M(sig_p) = M(sig - sig_p) # Note: M(sig) - M(sig_p) = M(sig - sig_p)
+21 -27
View File
@@ -1,16 +1,10 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from SimPEG import Survey as SimPEGsurvey, Utils, Problem, Maps, np, sp, mkvc from SimPEG import Survey as SimPEGsurvey, Utils, Problem, Maps, np, sp, mkvc
from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc
from SimPEG.EM.Utils import omega from SimPEG.EM.Utils import omega
from scipy.constants import mu_0 from scipy.constants import mu_0
from numpy.lib import recfunctions as recFunc from numpy.lib import recfunctions as recFunc
from .Utils import rec2ndarr from Utils import rec2ndarr
from . import SrcMT import SrcMT
import sys import sys
################# #################
@@ -82,7 +76,7 @@ class Rx(SimPEGsurvey.BaseRx):
bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0
# Note: Has a minus sign in front, to comply with quadrant calculations. # Note: Has a minus sign in front, to comply with quadrant calculations.
# Can be derived from zyx case for the 3D case. # Can be derived from zyx case for the 3D case.
f_part_complex = old_div(-ex,bx) f_part_complex = -ex/bx
# elif self.projType is 'Z2D': # elif self.projType is 'Z2D':
elif self.projType is 'Z3D': elif self.projType is 'Z3D':
## NOTE: Assumes that e is on edges and b on the faces. Need to generalize that or use a prop of fields to determine that. ## NOTE: Assumes that e is on edges and b on the faces. Need to generalize that or use a prop of fields to determine that.
@@ -109,13 +103,13 @@ class Rx(SimPEGsurvey.BaseRx):
hy_py = Pby*f[src,'b_py']/mu_0 hy_py = Pby*f[src,'b_py']/mu_0
# Make the complex data # Make the complex data
if 'zxx' in self.rxType: if 'zxx' in self.rxType:
f_part_complex = old_div(( ex_px*hy_py - ex_py*hy_px),(hx_px*hy_py - hx_py*hy_px)) f_part_complex = ( ex_px*hy_py - ex_py*hy_px)/(hx_px*hy_py - hx_py*hy_px)
elif 'zxy' in self.rxType: elif 'zxy' in self.rxType:
f_part_complex = old_div((-ex_px*hx_py + ex_py*hx_px),(hx_px*hy_py - hx_py*hy_px)) f_part_complex = (-ex_px*hx_py + ex_py*hx_px)/(hx_px*hy_py - hx_py*hy_px)
elif 'zyx' in self.rxType: elif 'zyx' in self.rxType:
f_part_complex = old_div(( ey_px*hy_py - ey_py*hy_px),(hx_px*hy_py - hx_py*hy_px)) f_part_complex = ( ey_px*hy_py - ey_py*hy_px)/(hx_px*hy_py - hx_py*hy_px)
elif 'zyy' in self.rxType: elif 'zyy' in self.rxType:
f_part_complex = old_div((-ey_px*hx_py + ey_py*hx_px),(hx_px*hy_py - hx_py*hy_px)) f_part_complex = (-ey_px*hx_py + ey_py*hx_px)/(hx_px*hy_py - hx_py*hy_px)
elif self.projType is 'T3D': elif self.projType is 'T3D':
if self.locs.ndim == 3: if self.locs.ndim == 3:
horLoc = self.locs[:,:,0] horLoc = self.locs[:,:,0]
@@ -133,9 +127,9 @@ class Rx(SimPEGsurvey.BaseRx):
by_py = Pby*f[src,'b_py'] by_py = Pby*f[src,'b_py']
bz_py = Pbz*f[src,'b_py'] bz_py = Pbz*f[src,'b_py']
if 'tzx' in self.rxType: if 'tzx' in self.rxType:
f_part_complex = old_div((- by_px*bz_py + by_py*bz_px),(bx_px*by_py - bx_py*by_px)) f_part_complex = (- by_px*bz_py + by_py*bz_px)/(bx_px*by_py - bx_py*by_px)
if 'tzy' in self.rxType: if 'tzy' in self.rxType:
f_part_complex = old_div(( bx_px*bz_py - bx_py*bz_px),(bx_px*by_py - bx_py*by_px)) f_part_complex = ( bx_px*bz_py - bx_py*bz_px)/(bx_px*by_py - bx_py*by_px)
else: else:
NotImplementedError('Projection of {:s} receiver type is not implemented.'.format(self.rxType)) NotImplementedError('Projection of {:s} receiver type is not implemented.'.format(self.rxType))
@@ -163,8 +157,8 @@ class Rx(SimPEGsurvey.BaseRx):
Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex') Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex')
# ex = Pex*mkvc(f[src,'e_1d'],2) # ex = Pex*mkvc(f[src,'e_1d'],2)
# bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 # bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0
dP_de = -mkvc(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Pex*v),2) dP_de = -mkvc(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))*(Pex*v),2)
dP_db = mkvc( Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2))*(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))))*(Pbx*f._bDeriv_u(src,v)/mu_0),2) dP_db = mkvc( Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2))*(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)).T*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Pbx*f._bDeriv_u(src,v)/mu_0),2)
PDeriv_complex = np.sum(np.hstack((dP_de,dP_db)),1) PDeriv_complex = np.sum(np.hstack((dP_de,dP_db)),1)
elif self.projType is 'Z2D': elif self.projType is 'Z2D':
raise NotImplementedError('Has not been implement for 2D impedance tensor') raise NotImplementedError('Has not been implement for 2D impedance tensor')
@@ -204,7 +198,7 @@ class Rx(SimPEGsurvey.BaseRx):
# Update the input vector # Update the input vector
sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sDiag = lambda t: Utils.sdiag(mkvc(t,2))
# Define the components of the derivative # Define the components of the derivative
Hd = sDiag(old_div(1.,(sDiag(hx_px)*hy_py - sDiag(hx_py)*hy_px))) Hd = sDiag(1./(sDiag(hx_px)*hy_py - sDiag(hx_py)*hy_px))
Hd_uV = sDiag(hy_py)*hx_px_u(v) + sDiag(hx_px)*hy_py_u(v) - sDiag(hx_py)*hy_px_u(v) - sDiag(hy_px)*hx_py_u(v) Hd_uV = sDiag(hy_py)*hx_px_u(v) + sDiag(hx_px)*hy_py_u(v) - sDiag(hx_py)*hy_px_u(v) - sDiag(hy_px)*hx_py_u(v)
# Calculate components # Calculate components
if 'zxx' in self.rxType: if 'zxx' in self.rxType:
@@ -253,7 +247,7 @@ class Rx(SimPEGsurvey.BaseRx):
# Update the input vector # Update the input vector
sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sDiag = lambda t: Utils.sdiag(mkvc(t,2))
# Define the components of the derivative # Define the components of the derivative
Hd = sDiag(old_div(1.,(sDiag(bx_px)*by_py - sDiag(bx_py)*by_px))) Hd = sDiag(1./(sDiag(bx_px)*by_py - sDiag(bx_py)*by_px))
Hd_uV = sDiag(by_py)*bx_px_u(v) + sDiag(bx_px)*by_py_u(v) - sDiag(bx_py)*by_px_u(v) - sDiag(by_px)*bx_py_u(v) Hd_uV = sDiag(by_py)*bx_px_u(v) + sDiag(bx_px)*by_py_u(v) - sDiag(bx_py)*by_px_u(v) - sDiag(by_px)*bx_py_u(v)
if 'tzx' in self.rxType: if 'tzx' in self.rxType:
Tij = sDiag(Hd*( - sDiag(by_px)*bz_py + sDiag(by_py)*bz_px )) Tij = sDiag(Hd*( - sDiag(by_px)*bz_py + sDiag(by_py)*bz_px ))
@@ -273,8 +267,8 @@ class Rx(SimPEGsurvey.BaseRx):
Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex') Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex')
# ex = Pex*mkvc(f[src,'e_1d'],2) # ex = Pex*mkvc(f[src,'e_1d'],2)
# bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 # bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0
dP_deTv = -mkvc(Pex.T*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*v,2) dP_deTv = -mkvc(Pex.T*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)).T*v,2)
db_duv = Pbx.T/mu_0*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))).T*Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2)).T*v db_duv = Pbx.T/mu_0*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))*(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2)).T*v
dP_dbTv = mkvc(f._bDeriv_u(src,db_duv,adjoint=True),2) dP_dbTv = mkvc(f._bDeriv_u(src,db_duv,adjoint=True),2)
PDeriv_real = np.sum(np.hstack((dP_deTv,dP_dbTv)),1) PDeriv_real = np.sum(np.hstack((dP_deTv,dP_dbTv)),1)
elif self.projType is 'Z2D': elif self.projType is 'Z2D':
@@ -306,17 +300,17 @@ class Rx(SimPEGsurvey.BaseRx):
aey_px_u = lambda vec: f._e_pxDeriv_u(src,Pey.T*vec,adjoint=True) aey_px_u = lambda vec: f._e_pxDeriv_u(src,Pey.T*vec,adjoint=True)
aex_py_u = lambda vec: f._e_pyDeriv_u(src,Pex.T*vec,adjoint=True) aex_py_u = lambda vec: f._e_pyDeriv_u(src,Pex.T*vec,adjoint=True)
aey_py_u = lambda vec: f._e_pyDeriv_u(src,Pey.T*vec,adjoint=True) aey_py_u = lambda vec: f._e_pyDeriv_u(src,Pey.T*vec,adjoint=True)
ahx_px_u = lambda vec: old_div(f._b_pxDeriv_u(src,Pbx.T*vec,adjoint=True),mu_0) ahx_px_u = lambda vec: f._b_pxDeriv_u(src,Pbx.T*vec,adjoint=True)/mu_0
ahy_px_u = lambda vec: old_div(f._b_pxDeriv_u(src,Pby.T*vec,adjoint=True),mu_0) ahy_px_u = lambda vec: f._b_pxDeriv_u(src,Pby.T*vec,adjoint=True)/mu_0
ahx_py_u = lambda vec: old_div(f._b_pyDeriv_u(src,Pbx.T*vec,adjoint=True),mu_0) ahx_py_u = lambda vec: f._b_pyDeriv_u(src,Pbx.T*vec,adjoint=True)/mu_0
ahy_py_u = lambda vec: old_div(f._b_pyDeriv_u(src,Pby.T*vec,adjoint=True),mu_0) ahy_py_u = lambda vec: f._b_pyDeriv_u(src,Pby.T*vec,adjoint=True)/mu_0
# Update the input vector # Update the input vector
# Define shortcuts # Define shortcuts
sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sDiag = lambda t: Utils.sdiag(mkvc(t,2))
sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2)) sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2))
# Define the components of the derivative # Define the components of the derivative
aHd = sDiag(old_div(1.,(sDiag(ahx_px)*ahy_py - sDiag(ahx_py)*ahy_px))) aHd = sDiag(1./(sDiag(ahx_px)*ahy_py - sDiag(ahx_py)*ahy_px))
aHd_uV = lambda x: ahx_px_u(sDiag(ahy_py)*x) + ahx_px_u(sDiag(ahy_py)*x) - ahy_px_u(sDiag(ahx_py)*x) - ahx_py_u(sDiag(ahy_px)*x) aHd_uV = lambda x: ahx_px_u(sDiag(ahy_py)*x) + ahx_px_u(sDiag(ahy_py)*x) - ahy_px_u(sDiag(ahx_py)*x) - ahx_py_u(sDiag(ahy_px)*x)
# Need to fix this to reflect the adjoint # Need to fix this to reflect the adjoint
if 'zxx' in self.rxType: if 'zxx' in self.rxType:
@@ -368,7 +362,7 @@ class Rx(SimPEGsurvey.BaseRx):
sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sDiag = lambda t: Utils.sdiag(mkvc(t,2))
sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2)) sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2))
# Define the components of the derivative # Define the components of the derivative
aHd = sDiag(old_div(1.,(sDiag(abx_px)*aby_py - sDiag(abx_py)*aby_px))) aHd = sDiag(1./(sDiag(abx_px)*aby_py - sDiag(abx_py)*aby_px))
aHd_uV = lambda x: abx_px_u(sDiag(aby_py)*x) + abx_px_u(sDiag(aby_py)*x) - aby_px_u(sDiag(abx_py)*x) - abx_py_u(sDiag(aby_px)*x) aHd_uV = lambda x: abx_px_u(sDiag(aby_py)*x) + abx_px_u(sDiag(aby_py)*x) - aby_px_u(sDiag(abx_py)*x) - abx_py_u(sDiag(aby_px)*x)
# Need to fix this to reflect the adjoint # Need to fix this to reflect the adjoint
if 'tzx' in self.rxType: if 'tzx' in self.rxType:
+10 -17
View File
@@ -1,10 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import zip
# Analytic solution of EM fields due to a plane wave # Analytic solution of EM fields due to a plane wave
import numpy as np, SimPEG as simpeg import numpy as np, SimPEG as simpeg
@@ -40,8 +33,8 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True):
# Loop over all the layers, starting at the bottom layer # Loop over all the layers, starting at the bottom layer
for lnr, h in enumerate(m1d.hx): # lnr-number of layer, h-thickness of the layer for lnr, h in enumerate(m1d.hx): # lnr-number of layer, h-thickness of the layer
# Calculate # Calculate
yp1 = old_div(k[lnr],(w*mu[lnr])) # Admittance of the layer below the current layer yp1 = k[lnr]/(w*mu[lnr]) # Admittance of the layer below the current layer
zp = old_div((w*mu[lnr+1]),k[lnr+1]) # Impedance in the current layer zp = (w*mu[lnr+1])/k[lnr+1] # Impedance in the current layer
# Build the propagation matrix # Build the propagation matrix
# Convert fields to down/up going components in layer below current layer # Convert fields to down/up going components in layer below current layer
@@ -55,7 +48,7 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True):
UDp[:,lnr+1] = elamh.dot(Pjinv.dot(Pj1)).dot(UDp[:,lnr]) UDp[:,lnr+1] = elamh.dot(Pjinv.dot(Pj1)).dot(UDp[:,lnr])
if scaleUD: if scaleUD:
UDp[:,lnr+1::-1] = old_div(UDp[:,lnr+1::-1],UDp[1,lnr+1]) UDp[:,lnr+1::-1] = UDp[:,lnr+1::-1]/UDp[1,lnr+1]
# Calculate the fields # Calculate the fields
Ed = np.empty((zd.size,),dtype=complex) Ed = np.empty((zd.size,),dtype=complex)
@@ -69,14 +62,14 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True):
dind = dup >= zd dind = dup >= zd
Ed[dind] = UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind])) Ed[dind] = UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind]))
Eu[dind] = UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind])) Eu[dind] = UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind]))
Hd[dind] = (old_div(k[0],(w*mu[0])))*UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind])) Hd[dind] = (k[0]/(w*mu[0]))*UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind]))
Hu[dind] = -(old_div(k[0],(w*mu[0])))*UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind])) Hu[dind] = -(k[0]/(w*mu[0]))*UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind]))
for ki,mui,epsi,dlow,dup,Up,Dp in zip(k[1::],mu[1::],eps[1::],m1d.vectorNx[:-1],m1d.vectorNx[1::],UDp[0,1::],UDp[1,1::]): for ki,mui,epsi,dlow,dup,Up,Dp in zip(k[1::],mu[1::],eps[1::],m1d.vectorNx[:-1],m1d.vectorNx[1::],UDp[0,1::],UDp[1,1::]):
dind = np.logical_and(dup >= zd, zd > dlow) dind = np.logical_and(dup >= zd, zd > dlow)
Ed[dind] = Dp*np.exp(-1j*ki*(dup-zd[dind])) Ed[dind] = Dp*np.exp(-1j*ki*(dup-zd[dind]))
Eu[dind] = Up*np.exp(1j*ki*(dup-zd[dind])) Eu[dind] = Up*np.exp(1j*ki*(dup-zd[dind]))
Hd[dind] = (old_div(ki,(w*mui)))*Dp*np.exp(-1j*ki*(dup-zd[dind])) Hd[dind] = (ki/(w*mui))*Dp*np.exp(-1j*ki*(dup-zd[dind]))
Hu[dind] = -(old_div(ki,(w*mui)))*Up*np.exp(1j*ki*(dup-zd[dind])) Hu[dind] = -(ki/(w*mui))*Up*np.exp(1j*ki*(dup-zd[dind]))
# Return return the fields # Return return the fields
return Ed, Eu, Hd, Hu return Ed, Eu, Hd, Hu
@@ -99,15 +92,15 @@ def getImpedance(m1d,sigma,freq):
om = 2*np.pi*fr om = 2*np.pi*fr
Zall = np.empty(len(h)+1,dtype='complex') Zall = np.empty(len(h)+1,dtype='complex')
# Calculate the impedance for the bottom layer # Calculate the impedance for the bottom layer
Zall[0] = old_div((mu_0*om),np.sqrt(mu_0*eps_0*(om)**2 - 1j*mu_0*sigma[0]*om)) Zall[0] = (mu_0*om)/np.sqrt(mu_0*eps_0*(om)**2 - 1j*mu_0*sigma[0]*om)
for nr,hi in enumerate(h): for nr,hi in enumerate(h):
# Calculate the wave number # Calculate the wave number
# print nr,sigma[nr] # print nr,sigma[nr]
k = np.sqrt(mu_0*eps_0*om**2 - 1j*mu_0*sigma[nr]*om) k = np.sqrt(mu_0*eps_0*om**2 - 1j*mu_0*sigma[nr]*om)
Z = old_div((mu_0*om),k) Z = (mu_0*om)/k
Zall[nr+1] = Z *(old_div((Zall[nr] + Z*np.tanh(1j*k*hi)),(Z + Zall[nr]*np.tanh(1j*k*hi)))) Zall[nr+1] = Z *((Zall[nr] + Z*np.tanh(1j*k*hi))/(Z + Zall[nr]*np.tanh(1j*k*hi)))
#pdb.set_trace() #pdb.set_trace()
Z1d[nrFr] = Zall[-1] Z1d[nrFr] = Zall[-1]
+3 -9
View File
@@ -1,11 +1,5 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
import numpy as np, SimPEG as simpeg import numpy as np, SimPEG as simpeg
from .MT1Danalytic import getEHfields from MT1Danalytic import getEHfields
from scipy.constants import mu_0 from scipy.constants import mu_0
def get1DEfields(m1d,sigma,freq,sourceAmp=1.0): def get1DEfields(m1d,sigma,freq,sourceAmp=1.0):
@@ -15,7 +9,7 @@ def get1DEfields(m1d,sigma,freq,sourceAmp=1.0):
G = m1d.nodalGrad G = m1d.nodalGrad
# Mass matrices # Mass matrices
# Magnetic permeability # Magnetic permeability
Mmu = simpeg.Utils.sdiag(m1d.vol*(old_div(1.0,mu_0))) Mmu = simpeg.Utils.sdiag(m1d.vol*(1.0/mu_0))
# Conductivity # Conductivity
Msig = m1d.getFaceInnerProduct(sigma) Msig = m1d.getFaceInnerProduct(sigma)
# Set up the solution matrix # Set up the solution matrix
@@ -29,7 +23,7 @@ def get1DEfields(m1d,sigma,freq,sourceAmp=1.0):
Ed, Eu, Hd, Hu = getEHfields(m1d,sigma,freq,m1d.vectorNx) Ed, Eu, Hd, Hu = getEHfields(m1d,sigma,freq,m1d.vectorNx)
Etot = (Ed + Eu) Etot = (Ed + Eu)
if sourceAmp is not None: if sourceAmp is not None:
Etot = ((old_div(Etot,Etot[-1]))*sourceAmp) # Scale the fields to be equal to sourceAmp at the top Etot = ((Etot/Etot[-1])*sourceAmp) # Scale the fields to be equal to sourceAmp at the top
## Note: The analytic solution is derived with e^iwt ## Note: The analytic solution is derived with e^iwt
bc = np.r_[Etot[0],Etot[-1]] bc = np.r_[Etot[0],Etot[-1]]
# The right hand side # The right hand side
+4 -10
View File
@@ -1,10 +1,4 @@
from __future__ import absolute_import from MT1Dsolutions import * # Add the names of the functions
from __future__ import unicode_literals from MT1Danalytic import *
from __future__ import print_function from dataUtils import *
from __future__ import division from ediFilesUtils import *
from future import standard_library
standard_library.install_aliases()
from .MT1Dsolutions import * # Add the names of the functions
from .MT1Danalytic import *
from .dataUtils import *
from .ediFilesUtils import *
+15 -21
View File
@@ -1,9 +1,3 @@
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
# Utils used for the data, # Utils used for the data,
import numpy as np, matplotlib.pyplot as plt, sys import numpy as np, matplotlib.pyplot as plt, sys
import SimPEG as simpeg import SimPEG as simpeg
@@ -25,7 +19,7 @@ def getAppRes(MTdata):
zList.append(zc) zList.append(zc)
return [appResPhs(zList[i][0],np.sum(zList[i][1:3])) for i in np.arange(len(zList))] return [appResPhs(zList[i][0],np.sum(zList[i][1:3])) for i in np.arange(len(zList))]
def rotateData(MTdata, rotAngle): def rotateData(MTdata,rotAngle):
''' '''
Function that rotates clockwist by rotAngle (- negative for a counter-clockwise rotation) Function that rotates clockwist by rotAngle (- negative for a counter-clockwise rotation)
''' '''
@@ -50,19 +44,19 @@ def rotateData(MTdata, rotAngle):
return MT.Data.fromRecArray(outRec) return MT.Data.fromRecArray(outRec)
def appResPhs(freq, z): def appResPhs(freq,z):
app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2
app_phs = np.arctan2(z.imag,z.real)*(old_div(180,np.pi)) app_phs = np.arctan2(z.imag,z.real)*(180/np.pi)
return app_res, app_phs return app_res, app_phs
def skindepth(rho, freq): def skindepth(rho,freq):
''' Function to calculate the skindepth of EM waves''' ''' Function to calculate the skindepth of EM waves'''
return np.sqrt( (rho*((old_div(1,(freq * mu_0 * np.pi )))))) return np.sqrt( (rho*((1/(freq * mu_0 * np.pi )))))
def rec2ndarr(x, dt=float): def rec2ndarr(x,dt=float):
return x.view((dt, len(x.dtype.names))) return x.view((dt, len(x.dtype.names)))
def makeAnalyticSolution(mesh, model, elev, freqs): def makeAnalyticSolution(mesh,model,elev,freqs):
from SimPEG import MT from SimPEG import MT
data1D = [] data1D = []
for freq in freqs: for freq in freqs:
@@ -70,13 +64,13 @@ def makeAnalyticSolution(mesh, model, elev, freqs):
anaE = anaEd+anaEu anaE = anaEd+anaEu
anaH = anaHd+anaHu anaH = anaHd+anaHu
anaZ = old_div(anaE,anaH) anaZ = anaE/anaH
# Add to the list # Add to the list
data1D.append((freq,0,0,elev,anaZ[0])) data1D.append((freq,0,0,elev,anaZ[0]))
dataRec = np.array(data1D,dtype=[('freq',float),('x',float),('y',float),('z',float),('zyx',complex)]) dataRec = np.array(data1D,dtype=[('freq',float),('x',float),('y',float),('z',float),('zyx',complex)])
return dataRec return dataRec
def plotMT1DModelData(problem, models, symList=None): def plotMT1DModelData(problem,models,symList=None):
from SimPEG import MT from SimPEG import MT
# Setup the figure # Setup the figure
fontSize = 15 fontSize = 15
@@ -103,7 +97,7 @@ def plotMT1DModelData(problem, models, symList=None):
# if not symList: # if not symList:
# symList = ['x']*len(models) # symList = ['x']*len(models)
from . import plotDataTypes as pDt import plotDataTypes as pDt
# Loop through the models. # Loop through the models.
modelList = [problem.survey.mtrue] modelList = [problem.survey.mtrue]
modelList.extend(models) modelList.extend(models)
@@ -116,14 +110,14 @@ def plotMT1DModelData(problem, models, symList=None):
else: else:
data1D = problem.dataPair(problem.survey,problem.survey.dpred(model)).toRecArray('Complex') data1D = problem.dataPair(problem.survey,problem.survey.dpred(model)).toRecArray('Complex')
# Plot the data and the model # Plot the data and the model
colRat = old_div(nr,((len(modelList)-1.999)*1.)) colRat = nr/((len(modelList)-1.999)*1.)
if colRat > 1.: if colRat > 1.:
col = 'k' col = 'k'
else: else:
col = plt.cm.seismic(1-colRat) col = plt.cm.seismic(1-colRat)
# The model - make the pts to plot # The model - make the pts to plot
meshPts = np.concatenate((problem.mesh.gridN[0:1],np.kron(problem.mesh.gridN[1::],np.ones(2))[:-1])) meshPts = np.concatenate((problem.mesh.gridN[0:1],np.kron(problem.mesh.gridN[1::],np.ones(2))[:-1]))
modelPts = np.kron(old_div(1.,(problem.mapping.sigmaMap*model)),np.ones(2,)) modelPts = np.kron(1./(problem.mapping.sigmaMap*model),np.ones(2,))
axM.semilogx(modelPts,meshPts,color=col) axM.semilogx(modelPts,meshPts,color=col)
## Data ## Data
@@ -150,7 +144,7 @@ def plotMT1DModelData(problem, models, symList=None):
# Fix labels and ticks # Fix labels and ticks
yMtick = [old_div(l,1000) for l in axM.get_yticks().tolist()] yMtick = [l/1000 for l in axM.get_yticks().tolist()]
axM.set_yticklabels(yMtick) axM.set_yticklabels(yMtick)
[ l.set_rotation(90) for l in axM.get_yticklabels()] [ l.set_rotation(90) for l in axM.get_yticklabels()]
[ l.set_rotation(90) for l in axR.get_yticklabels()] [ l.set_rotation(90) for l in axR.get_yticklabels()]
@@ -163,7 +157,7 @@ def plotMT1DModelData(problem, models, symList=None):
def printTime(): def printTime():
import time import time
print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())) print time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
def convert3Dto1Dobject(MTdata,rxType3D='zyx'): def convert3Dto1Dobject(MTdata,rxType3D='zyx'):
from SimPEG import MT from SimPEG import MT
+4 -13
View File
@@ -1,12 +1,3 @@
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import open
from builtins import int
from future import standard_library
standard_library.install_aliases()
from builtins import object
# Functions to import and export MT EDI files. # Functions to import and export MT EDI files.
from SimPEG import mkvc from SimPEG import mkvc
from scipy.constants import mu_0 from scipy.constants import mu_0
@@ -18,7 +9,7 @@ import numpy as np
import os, sys, re import os, sys, re
class EDIimporter(object): class EDIimporter:
""" """
A class to import EDIfiles. A class to import EDIfiles.
@@ -27,7 +18,7 @@ class EDIimporter(object):
# Define data converters # Define data converters
_impUnitEDI2SI = 4*np.pi*1e-4 # Convert Z[mV/km/nT] (as in EDI)to Z[V/A] SI unit _impUnitEDI2SI = 4*np.pi*1e-4 # Convert Z[mV/km/nT] (as in EDI)to Z[V/A] SI unit
_impUnitSI2EDI = old_div(1.,_impUnitEDI2SI) # ConvertZ[V/A] SI unit to Z[mV/km/nT] (as in EDI) _impUnitSI2EDI = 1./_impUnitEDI2SI # ConvertZ[V/A] SI unit to Z[mV/km/nT] (as in EDI)
# Properties # Properties
filesList = None filesList = None
@@ -125,7 +116,7 @@ class EDIimporter(object):
try: try:
import osr import osr
except ImportError as e: except ImportError as e:
print('Could not import osr, missing the gdal package\nCan not project coordinates') print 'Could not import osr, missing the gdal package\nCan not project coordinates'
raise e raise e
# Coordinates convertor # Coordinates convertor
if self._2out is None: if self._2out is None:
@@ -135,7 +126,7 @@ class EDIimporter(object):
if self._outEPSG is None: if self._outEPSG is None:
# Find the UTM EPSG number # Find the UTM EPSG number
Nnr = 700 if latD < 0.0 else 600 Nnr = 700 if latD < 0.0 else 600
utmZ = int(1+old_div((longD+180.0),6.0)) utmZ = int(1+(longD+180.0)/6.0)
self._outEPSG = 32000 + Nnr + utmZ self._outEPSG = 32000 + Nnr + utmZ
out.ImportFromEPSG(self._outEPSG) out.ImportFromEPSG(self._outEPSG)
self._2out = osr.CoordinateTransformation(src,out) self._2out = osr.CoordinateTransformation(src,out)
+31 -37
View File
@@ -1,9 +1,3 @@
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from matplotlib import pyplot as plt, colors, numpy as np from matplotlib import pyplot as plt, colors, numpy as np
@@ -71,9 +65,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True
x, y = arrayList[0]['x'][indUniFreq0],arrayList[0]['y'][indUniFreq0] x, y = arrayList[0]['x'][indUniFreq0],arrayList[0]['y'][indUniFreq0]
if par == 'abs': if par == 'abs':
if useLog: if useLog:
zPlot = old_div((np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs(arrayList[1][flag][indUniFreq1]))) zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs(arrayList[1][flag][indUniFreq1]))
else: else:
zPlot = old_div((np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1])),np.abs(arrayList[1][flag][indUniFreq1])) zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1]))/np.abs(arrayList[1][flag][indUniFreq1])
if mask: if mask:
maskInd = np.logical_or(np.abs(arrayList[0][flag][indUniFreq0])< 1e-3,np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3) maskInd = np.logical_or(np.abs(arrayList[0][flag][indUniFreq0])< 1e-3,np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -86,9 +80,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True
clevel = np.linspace(zPlot.min(),zPlot.max(),10) clevel = np.linspace(zPlot.min(),zPlot.max(),10)
elif par == 'real': elif par == 'real':
if useLog: if useLog:
zPlot = old_div((np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1]))))) zPlot = (np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1]))))
else: else:
zPlot = old_div((np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1])),np.abs((np.real(arrayList[1][flag][indUniFreq1])))) zPlot = (np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1]))/np.abs((np.real(arrayList[1][flag][indUniFreq1])))
if mask: if mask:
maskInd = np.logical_or(np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3) maskInd = np.logical_or(np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -101,9 +95,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True
clevel = np.linspace(zPlot.min(),zPlot.max(),10) clevel = np.linspace(zPlot.min(),zPlot.max(),10)
elif par == 'imag': elif par == 'imag':
if useLog: if useLog:
zPlot = old_div((np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1]))))) zPlot = (np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1]))))
else: else:
zPlot = old_div((np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1])),np.abs((np.imag(arrayList[1][flag][indUniFreq1])))) zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1]))/np.abs((np.imag(arrayList[1][flag][indUniFreq1])))
if mask: if mask:
maskInd = np.logical_or(np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3) maskInd = np.logical_or(np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -182,7 +176,7 @@ def plotIsoFreqNStipper(ax,freq,array,flag,par='abs',colorbar=True,colorNorm='Sy
def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None): def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None):
appResFact = old_div(1,(8*np.pi**2*10**(-7))) appResFact = 1/(8*np.pi**2*10**(-7))
treshold = 1.0 # 1 meter treshold = 1.0 # 1 meter
indUniSta = np.sqrt(np.sum((rec2nd(array[['x','y']])-loc)**2,axis=1)) < treshold indUniSta = np.sqrt(np.sum((rec2nd(array[['x','y']])-loc)**2,axis=1)) < treshold
freq = array['freq'][indUniSta] freq = array['freq'][indUniSta]
@@ -194,9 +188,9 @@ def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None):
elif par == 'imag': elif par == 'imag':
zPlot = np.imag(array[flag][indUniSta]) zPlot = np.imag(array[flag][indUniSta])
elif par == 'res': elif par == 'res':
zPlot = (old_div(appResFact,freq))*np.abs(array[flag][indUniSta])**2 zPlot = (appResFact/freq)*np.abs(array[flag][indUniSta])**2
elif par == 'phs': elif par == 'phs':
zPlot = np.arctan2(array[flag][indUniSta].imag,array[flag][indUniSta].real)*(old_div(180,np.pi)) zPlot = np.arctan2(array[flag][indUniSta].imag,array[flag][indUniSta].real)*(180/np.pi)
if not pColor: if not pColor:
if 'xx' in flag: if 'xx' in flag:
@@ -217,10 +211,10 @@ def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None):
def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colorNorm='None',cLevel=None,contour=True): def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colorNorm='None',cLevel=None,contour=True):
indSect = np.where(list(sectDict.values())[0]==array[list(sectDict.keys())[0]]) indSect = np.where(sectDict.values()[0]==array[sectDict.keys()[0]])
# Define the plot axes # Define the plot axes
if 'x' in list(sectDict.keys())[0]: if 'x' in sectDict.keys()[0]:
x = array['y'][indSect] x = array['y'][indSect]
else: else:
x = array['x'][indSect] x = array['x'][indSect]
@@ -237,7 +231,7 @@ def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colo
clevel = np.linspace(zPlot.min(),zPlot.max(),10,endpoint=True) clevel = np.linspace(zPlot.min(),zPlot.max(),10,endpoint=True)
elif par == 'ares': elif par == 'ares':
zPlot = old_div(np.abs(array[flag][indSect])**2,(8*np.pi**2*10**(-7)*array['freq'][indSect])) zPlot = np.abs(array[flag][indSect])**2/(8*np.pi**2*10**(-7)*array['freq'][indSect])
cmap = plt.get_cmap('RdYlBu')#seismic) cmap = plt.get_cmap('RdYlBu')#seismic)
if cLevel: if cLevel:
zMax = np.log10(cLevel[1]) zMax = np.log10(cLevel[1])
@@ -250,7 +244,7 @@ def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colo
plotNorm = colors.LogNorm() plotNorm = colors.LogNorm()
elif par == 'aphs': elif par == 'aphs':
zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(old_div(180,np.pi)) zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(180/np.pi)
cmap = plt.get_cmap('RdYlBu')#seismic) cmap = plt.get_cmap('RdYlBu')#seismic)
if cLevel: if cLevel:
zMax = cLevel[1] zMax = cLevel[1]
@@ -313,14 +307,14 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
def sortInArr(arr): def sortInArr(arr):
return np.sort(arr,order=['freq','x','y','z']) return np.sort(arr,order=['freq','x','y','z'])
# Find the index for the slice # Find the index for the slice
indSect0 = np.where(list(sectDict.values())[0]==arrayList[0][list(sectDict.keys())[0]]) indSect0 = np.where(sectDict.values()[0]==arrayList[0][sectDict.keys()[0]])
indSect1 = np.where(list(sectDict.values())[0]==arrayList[1][list(sectDict.keys())[0]]) indSect1 = np.where(sectDict.values()[0]==arrayList[1][sectDict.keys()[0]])
# Extract and sort the mats # Extract and sort the mats
arr0 = sortInArr(arrayList[0][indSect0]) arr0 = sortInArr(arrayList[0][indSect0])
arr1 = sortInArr(arrayList[1][indSect1]) arr1 = sortInArr(arrayList[1][indSect1])
# Define the plot axes # Define the plot axes
if 'x' in list(sectDict.keys())[0]: if 'x' in sectDict.keys()[0]:
x0 = arr0['y'] x0 = arr0['y']
x1 = arr1['y'] x1 = arr1['y']
else: else:
@@ -332,20 +326,20 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
if par == 'abs': if par == 'abs':
if useLog: if useLog:
zPlot = old_div((np.log10(np.abs(arr0[flag])) - np.log10(np.abs(arr1[flag]))),np.log10(np.abs(arr1[flag]))) zPlot = (np.log10(np.abs(arr0[flag])) - np.log10(np.abs(arr1[flag])))/np.log10(np.abs(arr1[flag]))
else: else:
zPlot = old_div((np.abs(arr0[flag]) - np.abs(arr1[flag])),np.abs(arr1[flag])) zPlot = (np.abs(arr0[flag]) - np.abs(arr1[flag]))/np.abs(arr1[flag])
if mask: if mask:
maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
zPlot[maskInd] = mask zPlot[maskInd] = mask
cmap = plt.get_cmap('RdYlBu')#seismic) cmap = plt.get_cmap('RdYlBu')#seismic)
elif par == 'ares': elif par == 'ares':
arF = old_div(1,(8*np.pi**2*10**(-7))) arF = 1/(8*np.pi**2*10**(-7))
if useLog: if useLog:
zPlot = old_div((np.log10((old_div(arF,arr0['freq']))*np.abs(arr0[flag])**2) - np.log10((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)),np.log10((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)) zPlot = (np.log10((arF/arr0['freq'])*np.abs(arr0[flag])**2) - np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2))/np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2)
else: else:
zPlot = old_div(((old_div(arF,arr0['freq']))*np.abs(arr0[flag])**2 - (old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2),((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)) zPlot = ((arF/arr0['freq'])*np.abs(arr0[flag])**2 - (arF/arr1['freq'])*np.abs(arr1[flag])**2)/((arF/arr1['freq'])*np.abs(arr1[flag])**2)
if mask: if mask:
maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -354,9 +348,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
elif par == 'aphs': elif par == 'aphs':
if useLog: if useLog:
zPlot = old_div((np.log10(np.arctan2(arr0[flag].imag,arr0[flag].real)*(old_div(180,np.pi))) - np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi))) ),np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)))) zPlot = (np.log10(np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi)) - np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) )/np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi))
else: else:
zPlot = old_div(( np.arctan2(arr0[flag].imag,arr0[flag].real)*(old_div(180,np.pi)) - np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)) ),(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)))) zPlot = ( np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi) - np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi) )/(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi))
if mask: if mask:
maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -364,9 +358,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
cmap = plt.get_cmap('Spectral')#seismic) cmap = plt.get_cmap('Spectral')#seismic)
elif par == 'real': elif par == 'real':
if useLog: if useLog:
zPlot = old_div((np.log10(arr0[flag].real) - np.log10(arr1[flag].real)),np.log10(arr1[flag].real)) zPlot = (np.log10(arr0[flag].real) - np.log10(arr1[flag].real))/np.log10(arr1[flag].real)
else: else:
zPlot = old_div((arr0[flag].real - arr1[flag].real),arr1[flag].real) zPlot = (arr0[flag].real - arr1[flag].real)/arr1[flag].real
if mask: if mask:
maskInd = np.logical_or(arr0[flag].real< 1e-3,arr1[flag].real < 1e-3) maskInd = np.logical_or(arr0[flag].real< 1e-3,arr1[flag].real < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -375,9 +369,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
elif par == 'imag': elif par == 'imag':
if useLog: if useLog:
zPlot = old_div((np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag)),np.log10(arr1[flag].imag)) zPlot = (np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag))/np.log10(arr1[flag].imag)
else: else:
zPlot = old_div((arr0[flag].imag - arr1[flag].imag),arr1[flag].imag) zPlot = (arr0[flag].imag - arr1[flag].imag)/arr1[flag].imag
if mask: if mask:
maskInd = np.logical_or(arr0[flag].imag< 1e-3,arr1[flag].imag < 1e-3) maskInd = np.logical_or(arr0[flag].imag< 1e-3,arr1[flag].imag < 1e-3)
zPlot = np.ma.array(zPlot) zPlot = np.ma.array(zPlot)
@@ -398,11 +392,11 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color
plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1)
elif colorNorm=='Lin': elif colorNorm=='Lin':
if cLevel: if cLevel:
level = np.arange(cLevel[0],cLevel[1]+.1,old_div((cLevel[1] - cLevel[0]),50.)) level = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/50.)
clevel = np.arange(cLevel[0],cLevel[1]+.1,old_div((cLevel[1] - cLevel[0]),10.)) clevel = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/10.)
else: else:
level = np.arange(zPlot.min(),zPlot.max(),old_div((zPlot.max() - zPlot.min()),50.)) level = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/50.)
clevel = np.arange(zPlot.min(),zPlot.max(),old_div((zPlot.max() - zPlot.min()),10.)) clevel = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/10.)
plotNorm = colors.Normalize() plotNorm = colors.Normalize()
elif colorNorm=='Log': elif colorNorm=='Log':
level = np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True) level = np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True)

Some files were not shown because too many files have changed in this diff Show More