Compare commits

...
569 Commits
Author SHA1 Message Date
Rowan Cockett d93a23306c Bump version: 0.1.3 → 0.1.4 2016-01-10 12:47:43 -08:00
Rowan Cockett d38424a10f Merge pull request #193 from simpeg/feat/pymatsolver
Speed up the tests with pymatsolver.
2016-01-03 19:26:22 -08:00
Rowan Cockett 00a29d27aa Decrease the number of iterations on the EM derivatives.
This is to increase the speed at which travis runs tests.
2016-01-03 19:11:45 -08:00
Rowan Cockett 9ebd0fcedc Use pymatsolver in TravisCI 2016-01-03 19:02:06 -08:00
Rowan Cockett 6747882e52 Merge pull request #192 from simpeg/feat/examples
SimPEG examples
2016-01-03 14:02:38 -08:00
Rowan Cockett dd5f5df69e my_function.__name__ must be set to 'test_' for nosetests 2016-01-03 12:48:01 -08:00
Rowan Cockett d64fd4ae35 List examples in the init file. 2016-01-02 18:29:04 -08:00
Rowan Cockett a18d48348d Merge fast tests on travis. 2016-01-02 18:20:58 -08:00
Rowan Cockett f0f3f6c06a Update the examples init.py to explicitly reference things.
You can run the main function to update the docs and imports.
2016-01-02 18:06:49 -08:00
Rowan Cockett fe94bd3edf Merge pull request #187 from simpeg/bug/importTreeMesh
Addresses #183: Import errors for tree mesh
2015-11-26 19:41:21 -07:00
Rowan Cockett b2aab4163b New examples for Mesh 2015-11-26 13:56:04 -07:00
Rowan Cockett be3667b4ab New Examples
- Put all examples in same directory
   - Make a single test
   - use __init__.py to create the docs automatically
2015-11-25 16:03:08 -08:00
Rowan Cockett 06c66f6392 Addresses #183: Import errors for tree mesh 2015-11-25 13:27:35 -08:00
Rowan Cockett bcfe904015 remove test from the name in examples. 2015-11-25 08:26:27 -08:00
Rowan Cockett 7c0be4ec50 Merge pull request #181 from simpeg/em/dev
Em/dev
2015-11-25 08:23:05 -08:00
Rowan Cockett 56d5019b94 Updates to examples and documentation. 2015-11-24 22:09:50 -08:00
Rowan Cockett 109340c645 Merge pull request #178 from simpeg/bug/flowTests
Bug/flow tests
2015-11-24 21:54:48 -08:00
Rowan Cockett 83e29b74c7 Seed the random flowTests 2015-11-24 19:28:06 -08:00
Rowan Cockett c173ccd6b2 Merge pull request #175 from simpeg/em/ZeroIdentity
Em/zero identity
2015-11-24 19:09:08 -08:00
Rowan Cockett ca3b44bacc Merge pull request #176 from simpeg/dev
Layered Model
2015-11-24 18:48:32 -08:00
Rowan Cockett 9fd25b7104 Merge pull request #174 from simpeg/mesh/tree
Mesh/tree
2015-11-24 18:46:36 -08:00
Lindsey 37f56f25f3 cleaned out Zero, Identity import from FDEM.py 2015-11-24 16:15:57 -08:00
Lindsey 5bd9209d6a type cast b in solver so that it is not an object if we add zero 2015-11-24 14:38:58 -08:00
Lindsey Heagy 71a5c8b2c1 fix sizes in Fields object (make an array not a vector) 2015-11-24 11:01:51 -08:00
Lindsey Heagy 9b847c0e32 replaced all numpy (a += b) with (a = a + b) because it plays more nicely with the Zero class 2015-11-24 10:06:15 -08:00
Lindsey Heagy f3fb1e6481 added an __iadd__, __isub__ to zero class 2015-11-24 10:05:28 -08:00
Lindsey 815311bfec cleaned up sources 2015-11-23 18:03:49 -08:00
Lindsey 6a83af7334 merged master to get namespace changes, resolved merge conflicts, use zero, identity for derivs, defaults for primary fields and sources 2015-11-23 17:41:32 -08:00
Lindsey af540478c5 Merge branch 'master' into em/ZeroIdentity 2015-11-23 17:00:39 -08:00
Rowan Cockett 1a43600781 Updates to MeshSlice view. 2015-11-20 15:08:37 -08:00
Rowan Cockett c775917bb3 Refactoring 2015-11-18 17:21:34 -08:00
Rowan Cockett ccc3e4fe8f docstrs 2015-11-18 17:18:55 -08:00
Rowan Cockett f928ab8019 Refactoring. 2015-11-18 17:16:32 -08:00
Rowan Cockett dcb9b8787d Corsen Trees 2015-11-18 17:15:26 -08:00
Rowan Cockett ca05d0599e Grid x0 locations. 2015-11-18 16:12:59 -08:00
Rowan Cockett 5678d90ef1 Merge branch 'master' of https://github.com/simpeg/simpeg into mesh/tree 2015-11-18 15:41:57 -08:00
Rowan Cockett 81a36684ca NodalGrad 2015-11-18 15:34:55 -08:00
Rowan Cockett 134c163c01 Merge pull request #165 from simpeg/bsmithyman-patch-1
Be compatible with outside metaclasses, for now
2015-11-18 14:08:55 -08:00
Rowan Cockett 312acd217a Merge pull request #172 from simpeg/em/dev
Em/dev
2015-11-18 14:08:04 -08:00
Rowan Cockett 033a64d53f Updates to inheritance and faster innerproducts on treemesh. 2015-11-18 12:57:15 -08:00
Rowan Cockett c1b5f45ac7 PlotSlice in OcTree 2015-11-18 11:52:05 -08:00
Rowan Cockett 92cd1fa15a Merge pull request #171 from simpeg/em/namespace
Em/namespace
2015-11-18 11:47:15 -08:00
Lindsey Heagy 622152c0c8 import simpegEM utils 2015-11-17 22:33:59 -08:00
Lindsey Heagy 699f6452b2 cleaned up imports for source 2015-11-17 22:29:44 -08:00
Lindsey Heagy 7023e999bc SurveyFDEM --> Survey, FieldsFDEM --> Fields 2015-11-17 22:17:38 -08:00
Lindsey Heagy 2fbe0af108 BaseSrcFDEM --> BaseSrc 2015-11-17 21:47:38 -08:00
Lindsey Heagy fe2e29031c updated Rx naming in FDEM analytics test 2015-11-17 21:30:09 -08:00
Rowan Cockett 1718e3506d Interpolation 2015-11-17 19:47:10 -08:00
Rowan Cockett 5afaa54ad9 Remove compiling of C ext with numpy exts.
This should be done at run time.
2015-11-17 18:46:01 -08:00
Rowan Cockett 61460261f0 Updates to setup.py
Add a cleanall, and try to make the cython build things in the correct
place.
2015-11-17 18:44:13 -08:00
Lindsey Heagy c041ad3de6 EM.FDEM.RxFDEM --> EM.FDEM.Rx 2015-11-17 08:29:27 -08:00
Lindsey Heagy e0684a0820 aveN2CC 2015-11-15 21:33:54 -08:00
Rowan Cockett eafa2bfbe8 Minor performance updates. 2015-11-15 19:08:40 -08:00
Rowan Cockett 87eb02b76b Fancy mesh example 2015-11-15 18:16:07 -08:00
Rowan Cockett 2c00459846 Actually use Lindsey's changes... :) 2015-11-15 17:59:05 -08:00
Rowan Cockett 4ac85e81d6 Updates to merging 2015-11-15 17:51:51 -08:00
Rowan Cockett 5e20960335 50% speed up in refinement 2015-11-15 17:45:37 -08:00
Lindsey Heagy d7bcc0c074 broke up averaging so that we have averaging for components as well 2015-11-15 00:08:26 -08:00
Lindsey Heagy 9d92f62cfa analytic test update 2015-11-13 13:50:10 -08:00
Lindsey Heagy 52375ecd06 fixed fdem deriv test 2015-11-13 12:32:09 -08:00
Lindsey Heagy 2da82b7d19 fixed SrcUtils call in SurveyTDEM 2015-11-13 12:24:12 -08:00
Lindsey Heagy 356a5b103d and in SurveyTDEM 2015-11-13 12:20:07 -08:00
Lindsey Heagy aed5f5ad52 fixed SrcUtils import in BaseTDEM 2015-11-13 12:15:32 -08:00
Lindsey Heagy 19bcdbfbf5 EM.FDEM.SrcFDEM_XXX --> EM.FDEM.Src.XXX 2015-11-13 10:39:08 -08:00
Lindsey Heagy 3b62957d08 re-named SrcUtils to AnalyticUtils, cleaned up namespace for imports to close #159 2015-11-13 08:44:34 -08:00
Lindsey Heagy 25e21608df import all EM utils under Utils namespace 2015-11-13 08:34:46 -08:00
Lindsey Heagy 4fe9475ffc aveE2CCV for 3D 2015-11-13 08:32:01 -08:00
Lindsey Heagy d130b50f7f aveE2CC for 3D 2015-11-12 09:11:39 -08:00
Lindsey Heagy 6a30ea1d83 better mesh sizes for testing 2015-11-12 08:20:44 -08:00
Lindsey Heagy 821932ed82 aveF2CCV in 2 and 3D 2015-11-12 08:19:15 -08:00
Rowan Cockett 86eb244011 updates to innerProductDeriv tests for tree mesh 2015-11-11 14:04:36 -08:00
Rowan Cockett 8fc1a86742 Updates to order tests. added 'notatreeTree' mesh. 2015-11-11 13:19:48 -08:00
Rowan Cockett fd55aa6d67 Delete things when __dirty__ 2015-11-11 13:05:47 -08:00
Lindsey Heagy a53372a859 Averaging from faces to cell centres (2nd order on non-refined mesh, 1st order when we refine... which I think is ok) 2015-11-11 09:32:31 -08:00
Lindsey Heagy 7fd07f8213 import TreeMesh as Tree 2015-11-10 19:36:42 -08:00
Lindsey Heagy d1ef2fc330 import TreeMesh instead of PointerTree 2015-11-10 19:31:58 -08:00
Lindsey Heagy 29579c35e0 place holders for averaging 2015-11-10 18:42:09 -08:00
Rowan Cockett 601079dab3 Oh Travis. Just build the cython, please?! 2015-11-10 17:57:43 -08:00
Rowan Cockett 277318240c Delete old implementations 2015-11-10 17:54:35 -08:00
Rowan Cockett 13c8843fd1 Rearrange PointerTree 2015-11-10 17:48:37 -08:00
Rowan Cockett d860456105 move tests to new folder. 2015-11-10 17:30:40 -08:00
Rowan Cockett 314b50c435 Merge branch 'TreeMesh' of https://github.com/simpeg/simpeg into mesh/tree 2015-11-10 17:27:24 -08:00
Rowan Cockett 37a68dd5b7 Cython dep. the setup.py 2015-11-10 17:25:18 -08:00
Rowan Cockett f6c5b011e8 Tests octree order 2015-11-10 17:11:08 -08:00
Lindsey Heagy 4dafecaef7 cleaned up em deriv test to reduce testing time 2015-11-10 14:53:26 -08:00
Lindsey b870abbdce Merge pull request #166 from simpeg/seedCoorUtils
set seeds for the coord utils test
2015-11-10 13:41:40 -08:00
Lindsey Heagy b7be3861a0 set seeds for the coord utils test 2015-11-10 10:51:58 -08:00
Brendan Smithyman ff68400320 Be compatible with outside metaclasses, for now
Making this change would allow use of metaclasses in a more straightforward way for code that inherits from both SimPEG classes and external classes. In the future, this may need to be addressed in more detail.
2015-11-10 12:26:55 -05:00
Rowan Cockett da7fbbb461 edgeCurl is O(h) not O(h^2) ???? 2015-11-09 19:51:46 -08:00
Rowan Cockett 94a79298bd Inner products 2015-11-09 15:14:24 -08:00
Rowan Cockett 2ce694e9d5 test edgeCurl 2015-11-09 10:36:59 -08:00
Rowan Cockett 5b85bcaeaf ntFx: number of total faces in x direction 2015-11-09 10:13:45 -08:00
Lindsey Heagy 6b413c8b43 Merge branch 'master' into em/ZeroIdentity 2015-11-09 09:24:54 -08:00
Lindsey 4a5a0a3c8c Merge pull request #163 from simpeg/em/testSplitting
Em/test splitting
2015-11-09 09:17:43 -08:00
Lindsey f63847ddae Merge pull request #161 from simpeg/CoordRotations
coordinate rotations
2015-11-09 09:17:01 -08:00
Lindsey Heagy 554f507ba7 switch order of addition to satisfy Zero class 2015-11-09 09:15:02 -08:00
Lindsey Heagy 915a2f8446 cleaned out commented-out code 2015-11-08 15:18:19 -08:00
Lindsey Heagy 297ea916b4 light notation clean up 2015-11-08 14:58:28 -08:00
Lindsey Heagy 639a6e7a06 Adjoint for all 4 formulations with Zero Identity 2015-11-08 14:09:18 -08:00
Rowan Cockett 91284e2286 Edge Bug 2015-11-07 18:34:50 -08:00
Rowan Cockett fb18d8a5d8 Dirty edges 2015-11-07 18:19:40 -08:00
Rowan Cockett 855c92dc77 Number of hanging things. 2015-11-07 18:04:06 -08:00
Rowan Cockett 406addd332 Recursive force 2015-11-07 17:58:11 -08:00
Rowan Cockett b1058eb07d Remove structure change, replace with __dirty__ 2015-11-07 17:55:45 -08:00
Rowan Cockett b2381796f7 Fix numbering 2015-11-07 17:51:02 -08:00
Rowan Cockett ebb57f6218 edgeCurl 2015-11-07 17:32:59 -08:00
Rowan Cockett 0aafb8931b Rename _treeInds to _cells 2015-11-07 16:49:01 -08:00
Rowan Cockett e8ae516030 Speed improvements, cython, balancing. 2015-11-07 16:47:19 -08:00
Rowan Cockett 109a5f0f86 Simple Balancing 2015-11-06 19:43:21 -08:00
Rowan Cockett ac688254ac Deflation matrix and faceDiv start 2015-11-06 13:37:13 -08:00
Rowan Cockett e55dc2e78d rename hangingNodes --> hangingN etc. 2015-11-06 11:53:46 -08:00
Rowan Cockett 337383f8ab Hanging faces edges and node connectivity 2015-11-06 11:22:28 -08:00
Lindsey Heagy 0af1f59891 h,j jvec now with Zero and identity classes 2015-11-06 10:58:23 -08:00
Lindsey Heagy 4553d6db51 b formulation Zero Identity 2015-11-06 10:05:44 -08:00
Lindsey Heagy d102ec9c00 Zero, Identity for E formulation 2015-11-06 10:00:30 -08:00
Lindsey Heagy 7b0bea4e1d make sure subtraction of x0 is a matrix with length of number of points, add test for giving an array XYZ 2015-11-05 16:22:31 -08:00
Lindsey Heagy 96b855d71d use np.cross 2015-11-05 16:10:43 -08:00
Lindsey Heagy 41970a221a split up adjoint and deriv test, pulled out getProblem call and put it in utils 2015-11-05 15:44:35 -08:00
Lindsey Heagy 14f7cf4fff test 4 source types for cross check 2015-11-05 14:58:47 -08:00
Lindsey Heagy a4a2c400a7 fixed cross check test 2015-11-05 14:12:12 -08:00
Lindsey Heagy 6669c3d3aa fixed alignment 2015-11-05 14:09:27 -08:00
Lindsey Heagy 8ce9699b8a removed cross-check test from derive test 2015-11-05 13:34:01 -08:00
Lindsey Heagy ac9b50358f split fdem tests into forward and inverse 2015-11-05 13:30:37 -08:00
Lindsey Heagy 63a2ace3db em directory with tests, faded, them and travis update 2015-11-05 13:17:04 -08:00
Lindsey Heagy 10bd87ac02 move tdem, fdem tests up a directory 2015-11-05 13:14:44 -08:00
Lindsey Heagy 4b87b4b45f attempt to split up travis testing for em 2015-11-05 13:12:15 -08:00
Lindsey Heagy 025b2db70e coordinate rotations 2015-11-04 21:37:27 -08:00
Rowan Cockett e2e2fcec03 fix 2d plotting 2015-11-04 15:01:22 -08:00
Rowan Cockett ff5885cde0 OcTree faceZ 2015-11-04 14:55:46 -08:00
Rowan Cockett c688bfd5ae Start of 3D PointerTree 2015-11-04 14:23:36 -08:00
Rowan Cockett 0da5888e37 permutations 2015-11-04 13:51:18 -08:00
Rowan Cockett d2baf15b54 Test pointerTree 2015-11-04 12:13:54 -08:00
Rowan Cockett 21a3353aa7 Merge pull request #124 from simpeg/em/dev
Em/dev
2015-11-04 11:38:48 -08:00
Rowan Cockett 44d11542c7 PointerTree, FaceDiv, Visualization 2015-11-04 11:34:36 -08:00
Rowan Cockett 6fb93ee6e4 Lower iterations of Richards tests. 2015-11-04 10:28:19 -08:00
Rowan Cockett 7c897d0f21 Rearrange travis tests. 2015-11-04 10:15:41 -08:00
Rowan Cockett 4db756b060 simpegEM --> SimPEG.EM 2015-11-04 10:13:24 -08:00
Rowan Cockett e622dfb5cc Merge branch 'master' of https://github.com/simpeg/simpegem into em/dev
Conflicts:
	.coveragerc
	.gitignore
	.travis.yml
	docs/api_Utils.rst
	docs/conf.py
	docs/index.rst
	requirements.txt
	setup.py
2015-11-04 09:59:11 -08:00
Rowan Cockett 1aade8155d Merge pull request #122 from simpeg/flow
SimPEG.FLOW
2015-11-04 08:57:43 -08:00
Rowan Cockett cd01f07467 Early return on plotting code. 2015-10-30 14:43:11 -07:00
Rowan Cockett 465087beba SimPEG.FLOW 2015-10-30 14:36:51 -07:00
Rowan Cockett 536b9abb86 Merge pull request #121 from simpeg/travis
Rearrange Tests
2015-10-30 14:08:39 -07:00
Rowan Cockett f9b77a9128 Merge pull request #120 from simpeg/zero
Zero and Identity - Useful for writing derivatives.
2015-10-30 14:01:58 -07:00
Rowan Cockett fc3590ec9d Merge pull request #118 from simpeg/bsmithyman-cythondep
Add Cython dependency
2015-10-30 14:01:44 -07:00
Rowan Cockett 7106b2b57f Test examples 2015-10-30 13:59:25 -07:00
Rowan Cockett b8fe0cfdbf Separate tests into folders.
Build in a matrix?
2015-10-30 13:39:01 -07:00
Rowan Cockett 0885b72577 Zero and Identity - Useful for writing derivatives.
These should work with sparse matrices and numpy arrays.

```python
	z = Zero()
	z*A == 0
	o = Identity()
	o*A == A
```
2015-10-30 12:21:30 -07:00
Rowan Cockett b00488a6d0 Minor updates to TreeMesh 2015-10-30 11:56:26 -07:00
Brendan Smithyman de2891ccdf Add Cython dependency 2015-10-28 10:05:58 -04:00
Lindsey Heagy e85da0d15b jPrimary should be initiated as complex in the fields object 2015-10-18 21:25:31 -07:00
Lindsey Heagy 24f2bae3c2 ensure that primary fields can be complex s_m 2015-10-18 21:16:35 -07:00
Lindsey Heagy e4f67ef649 fixed bug in kwargs for raw vec s_m 2015-10-18 21:09:19 -07:00
Lindsey Heagy 059d318ab6 Primary fields kwargs for S_m 2015-10-18 14:45:37 -07:00
Lindsey Heagy 670511eb61 add e,b,h,j Primary to kwargs for raw e src 2015-10-18 11:15:23 -07:00
Lindsey ed463c736f Merge pull request #112 from simpeg/Citation
Citation
2015-10-11 19:38:41 -07:00
Lindsey d148a5342c Merge pull request #113 from simpeg/travis
try running travis on new framework
2015-10-10 13:23:17 -07:00
Lindsey Heagy 1cb06297ec Merge branch 'SrcIntegration' 2015-10-07 20:59:16 -07:00
Lindsey Heagy 5d844ac2c0 cleaned up commented out code 2015-10-07 20:58:52 -07:00
Lindsey 70453b6720 Merge pull request #34 from simpeg/SrcIntegration
Src integration: Inside of the source definitions, there is now the option of whether to integrate the source term by multiplying with an edge inner product matrix
2015-10-07 20:56:57 -07:00
Lindsey Heagy b927a1daf2 - moved integration of src term in to definition of src (makes it easier to trigger on / off)
- added mu to testing against analytics
2015-10-05 07:42:58 -07:00
Lindsey Heagy 8a358506f1 add test for mag dipole in wholespace 2015-10-03 14:06:06 -07:00
Lindsey Heagy d3d453ac48 try running travis on new framework 2015-10-02 08:10:22 -07:00
Lindsey Heagy 075cea488f test and see if we can run travis on updated infrastructure 2015-10-01 23:52:49 -07:00
Lindsey Heagy 97f27c76d1 added test for H-J formulation against analytic soon for an electric dipole in a whole-space on cyl mesh 2015-10-01 23:41:10 -07:00
Lindsey Heagy bac28ba133 updated tolerance for travis 2015-10-01 22:45:57 -07:00
Lindsey Heagy 0d88ec3652 explicit integration of sources (s_e for E-B formulation, s_m for H-J formulation) in the calculation of the RHS and associated updates to the documentation 2015-10-01 21:45:06 -07:00
Lindsey ed6d091705 Update README.rst
added citation (not sure why .. include doesn't work)
2015-10-01 10:04:44 -07:00
Lindsey c29f2792ff Update CITATION.rst 2015-10-01 09:46:11 -07:00
Lindsey ff2ce3f1c8 Update CITATION.rst 2015-10-01 09:43:06 -07:00
Lindsey 502e76c33a Update CITATION.rst 2015-10-01 09:42:38 -07:00
Lindsey Heagy 8566316a12 add citation 2015-10-01 09:41:42 -07:00
seogi_macbook 2b17ad45ac blah .. for spline map 2015-09-25 23:58:08 -07:00
seogi_macbook 23a3768b52 add spline fun 2015-09-25 23:36:37 -07:00
seogi_macbook 309e7f84cf fix poly map 2015-09-25 23:29:17 -07:00
seogi_macbook 2c6a2ae35c Fix bug for poly map
Working Spline map
2015-09-25 23:14:10 -07:00
seogi_macbook 575ac2ea7b fix active cell map 2015-09-17 22:15:59 -07:00
seogi_macbook c7c1126e9b fix couple bugs in TDEM 2015-09-17 21:38:16 -07:00
seogi_macbook 168ad8b0ff fix bug for active cell 2015-09-17 21:16:29 -07:00
seogi_macbook 7020201976 Extend polymap to 3D (now its kind of general), and test 2015-09-16 08:44:28 -07:00
seogi_macbook efbd0da0b3 Merge branch 'Mappings' 2015-09-15 08:51:18 -07:00
seogi_macbook f726a27269 Fix target misfit 2015-09-14 21:25:15 -07:00
Rowan Cockett 7f74f7ee82 Remove SimPEGLinearOperator as Scipy 16 has implemented this feature. 2015-09-14 15:14:33 -07:00
seogi_macbook c886817773 Fix bug in CircMap
Add PolyMap for 2D, and test
2015-09-14 13:06:51 -07:00
Lindsey d634575137 Update License
added 2015
2015-07-28 13:36:49 -07:00
Lindsey Heagy 7cd4ba7d61 updated inversion workflow image, discretization --> mesh and colors are same as in paper 2015-07-21 14:31:22 -07:00
Lindsey e4ed2265ba Update requirements to include SimPEG 2015-07-07 21:12:52 -05:00
Lindsey 5cb3babafe Merge pull request #28 from simpeg/dev
cleaned up math in docs
2015-07-07 07:25:23 -05:00
Lindsey Heagy cb73c38e8e cleaned up math in docs 2015-07-06 23:59:21 -05:00
Lindsey 59eb52dce8 Merge pull request #27 from simpeg/dev
Dev
2015-07-06 22:15:56 -05:00
Lindsey Heagy 037155e3f3 fixed indentation bug in FDEM 2015-07-06 19:16:00 -05:00
Lindsey Heagy a84bc5cbc1 documentation updates 2015-07-06 19:04:24 -05:00
Lindsey 2ef8beddb6 Merge pull request #26 from simpeg/dev
merge FDEM refactor from dev
2015-07-06 07:09:21 -05:00
Lindsey Heagy d518f1e685 fixed how mu was being included: assuming constant mu = mu_0 for now. need to write a new propmap to test inversion when mu is variable, but not part of the inversion model 2015-07-05 21:59:55 -05:00
Lindsey Heagy 039e3430ab clean up of tests 2015-07-05 21:59:06 -05:00
Lindsey Heagy b5b8b5fae6 - added check is S_e is zero in getRHSDeriv of FDEM.py
- deleted code that has been commented out
2015-07-05 21:58:14 -05:00
Lindsey Heagy 7c63bfb6ac Brackets to make sure we are doing matrix vector products 2015-07-05 21:57:19 -05:00
Lindsey Heagy 4fa5e9426d TDEM tests running and passing individually 2015-07-01 00:21:54 -07:00
Lindsey Heagy 265a1189e8 fixing sources in TDEM. test_TDEM_forward_Analytic.py now passes 2015-06-30 22:35:01 -07:00
Lindsey Heagy 2dcb356682 minor clean-up for reading and Ctrl+D in sublime 2015-06-30 22:33:38 -07:00
Lindsey f96cf0418a Merge pull request #24 from simpeg/feat/sourceRefactor
Feat/source refactor
2015-06-30 14:10:05 -07:00
Lindsey 5ec86300f6 have fields keep track of the problem so that calls to src.eval use the proper mass matrices if a model is switched out when running multiple forwards. This way fields also stores curModel 2015-06-29 18:05:32 -07:00
Lindsey Heagy 1fbf40568d shortened the test for travis 2015-06-24 16:57:15 -07:00
Lindsey Heagy d9e8996336 fixed loop source and mag dipole fields for variable mu, added both to testing 2015-06-23 23:02:33 -07:00
Lindsey ac3e7765fe Mag dipole sources, defined using prim-sec with a zero-frequency primary actually have a non-zer S_e component if there is variable mu. This has been corrected in the vector potential definition of the sources, and an issue created for the remaining sources. Testing has also been made more robust by using a rawVec source with both S_m and S_e defined which showed a couple bugs in some of the getRHSDeriv_m (which have been corrected), along with a couple minor sizing things in fields derivs 2015-06-23 18:32:00 -07:00
Lindsey 36f8eca25c Sources can take mu values other than mu_0 2015-06-23 18:25:29 -07:00
Lindsey 5732e85a2f fixed typo in MfRhoDeriv. note that it still won't work (but we don't call it anywhere... yet 2015-06-23 18:24:40 -07:00
Lindsey 7c01c84514 Analytics should take other values for mu 2015-06-23 18:22:44 -07:00
Lindsey Heagy 527133c709 update constant in casing analytic to match whole-space dipole soln 2015-06-16 11:37:57 -07:00
Lindsey Heagy 32f83322ca specified that A and RHS derivs are wrt m 2015-06-16 11:32:53 -07:00
Lindsey Heagy 7239d9cbe6 FDEM problems: e,b,h,j up and running with Jvec and Jtvec within the re-factored framework. Whenever a new element is created, we create its derive wrt u (the computed field) and wrt m (the model). Jvec and Jtvec then stitch these pieces together using chain rule 2015-06-16 11:28:29 -07:00
Lindsey 58e8ce4988 updated mult factor in casing soln analytic 2015-06-11 10:24:16 -07:00
Lindsey Heagy ab1f55cd9c Merge branch 'feat/sourceRefactor' of https://github.com/simpeg/simpegem into feat/sourceRefactor
# Conflicts:
#	simpegEM/FDEM/FDEM.py
2015-06-11 09:20:33 -07:00
Lindsey 05ca7bb78b Start of Jvec for problems j, h. failing at the moment 2015-06-10 18:49:35 -07:00
Lindsey Heagy 39b5b5eb3f cleaned up old commented-out code 2015-06-10 16:57:42 -07:00
Lindsey Heagy 69977ad0b2 raw vec should take complex values 2015-06-10 08:54:09 -07:00
Lindsey Heagy 9a732ae5b5 Problem_b derivs and adjoint. Notation updates in Jvec and Jtvec. 2015-06-09 20:32:15 -07:00
Lindsey 611e930925 made mu a vector in the casing soln, added E fields from an electric dipole 2015-06-05 18:07:35 -07:00
Rowan Cockett 4113a7438b updates to tolerances in the derivative check. 2015-06-05 16:29:15 -07:00
Rowan Cockett 26a84c7bfc updates to problem debugging abilities 2015-06-05 13:35:52 -07:00
Lindsey 678d8611d8 more reliable way of taking the sqrt of a complex number in defn of k 2015-06-04 16:12:58 -07:00
Lindsey 1240d65eaf B fields for casing mag dipole 2015-06-04 16:12:29 -07:00
Lindsey da9b541d81 Raw Vec Sources should be allowed to be complex 2015-06-04 11:38:16 -07:00
Lindsey Heagy d545d9e393 Working Problem_e Jvec and Jtvec 2015-06-02 22:45:48 -07:00
Lindsey Heagy cd94fea61d start of Jvec for Problem_e 2015-06-02 19:23:30 -07:00
Lindsey Heagy 54468c7751 removed test_FieldsObject.py as it is tested in SimPEG 2015-06-02 17:41:30 -07:00
Lindsey Heagy ca6c485889 _sol --> Solution 2015-06-02 16:14:09 -07:00
Lindsey Heagy 693ae256c1 broke apart primary-secondary 2015-06-02 15:31:46 -07:00
Lindsey c28e2c10de Merge pull request #20 from simpeg/PropMap
Prop map
2015-06-02 14:15:22 -07:00
Lindsey Heagy 66b26a1b5e _getS_m now S_m 2015-06-02 14:14:34 -07:00
Lindsey Heagy 1424d071d4 _p --> Primary 2015-06-02 14:07:41 -07:00
Lindsey Heagy e53b124724 Mass matrix derivs, and replaced call of forward with fields 2015-06-02 13:54:14 -07:00
Lindsey 80a7dfb51b start of moving mass matrix derivs onto base.py 2015-06-01 16:56:11 -07:00
Lindsey e0387978f2 Simgai --> Rho 2015-06-01 16:32:23 -07:00
Lindsey b7a3b4e5e6 Running EB, HJ with PropMap 2015-06-01 16:21:15 -07:00
Lindsey 27c8da341d start of using PropMaps for EB formulation 2015-06-01 14:52:39 -07:00
Lindsey 3df2140a88 Fields now take a srcList. A lot of this could be vectorized later 2015-06-01 14:32:42 -07:00
Lindsey Heagy 37fc9981f7 fixed bug in Base.py 2015-06-01 09:58:58 -07:00
Lindsey Heagy 3810b392dd removed sec fields which were defined based on source def 2015-05-31 21:16:00 -07:00
Lindsey Heagy 5e7194b078 Merge branch 'feat/sourceRefactor' of https://github.com/simpeg/simpegem into feat/sourceRefactor 2015-05-29 12:05:53 -07:00
Lindsey Heagy 8c4a01a665 Merge branch 'feat/sourceRefactor' of https://github.com/simpeg/simpegem into feat/sourceRefactor 2015-05-29 11:51:49 -07:00
Lindsey 44f5cf960f one more 2015-05-29 11:39:17 -07:00
Lindsey e634b00af0 removed calls of self.curModel.transform from each of the specific problems (now only looks for the relevant physprop) 2015-05-29 11:20:35 -07:00
Lindsey eea51c9923 start of seperating out model types in Base.py to later clean up deriv and allow for multiple model types to be used some house-keeping in FDEM.py 2015-05-28 15:52:07 -07:00
Lindsey b942d214d4 first stab at how to structure sources and fields for primary secondary formulations 2015-05-28 15:01:04 -07:00
Lindsey fbf022ff76 Merge branch 'feat/sourceRefactor' of https://github.com/simpeg/simpegem into feat/sourceRefactor 2015-05-28 11:17:51 -07:00
Lindsey Heagy 8d97f322c9 analytics return arrays 2015-05-28 11:15:58 -07:00
Lindsey Heagy f080c61f74 fixed test_FDEM_analytics.py 2015-05-28 08:35:41 -07:00
Lindsey dc3e641524 set loc and moment inside of MagDipoleB source 2015-05-27 13:21:14 -07:00
Lindsey 5b44b16bc4 order of arguments changed: rxList,freq, other stuff 2015-05-26 17:53:50 -07:00
Lindsey 59c141a5f1 survey.getSource --> survey.getSrcByFreq 2015-05-26 17:52:41 -07:00
Lindsey a87b37e6a7 missed a couple files 2015-05-14 13:31:23 -07:00
Lindsey 682528d555 removed RHS from call of fwd, primary-secondary should now be done through a Src class (which has not been written yet) 2015-05-14 13:30:42 -07:00
Lindsey 40aae0b610 FieldsFDEM functioning with branch bug/FieldsObject of SimPEG (run test_FDEM.py) 2015-05-08 15:26:56 -07:00
GudniRos 9eede4e840 Changed model to mesh in __init__ calls in all the FDEMProblems 2015-05-07 19:15:53 -07:00
Lindsey 35d56655f5 Fields Object functioning again. A bit of an ugly fix though... involves a Utils.mkvc on the knownFields for each 2015-05-07 16:00:50 -07:00
Lindsey 569d22bf6a made loc a kwarg 2015-05-06 16:58:46 -07:00
Lindsey 0869777284 hide startup variables 2015-05-06 11:55:06 -07:00
Lindsey Heagy df4819d02f tx --> src in a couple more 2015-05-06 09:39:20 -07:00
Lindsey Heagy 1e52c365bc start of Casing analytic and test 2015-05-06 06:47:53 -07:00
Lindsey 96b0d6a38c added def of k to utils and have getSourceDeriv take fields and vector 2015-05-04 16:48:57 -07:00
Lindsey deaa159f3f placeholder for getSourceDeriv 2015-05-04 11:33:28 -07:00
Lindsey 47fca47b33 getSources --> getSource 2015-05-04 11:29:17 -07:00
Lindsey c844f7b36a removed knownSrcType 2015-05-04 10:48:10 -07:00
Lindsey Heagy 77346af8ee fixed a couple bugs in source definitions and ensure that all types are properly set for RawVec sources 2015-05-04 08:49:06 -07:00
Lindsey Heagy d8c82da1d4 added a todo for breaking apart orientation and moment in source utils 2015-05-04 08:48:08 -07:00
Lindsey Heagy 4d75c9d6e5 changed source definitions for test_FieldsObject, still failing 2015-05-03 10:28:17 -07:00
Lindsey Heagy 5fc6ff39eb test_FDEM_analytics running 2015-05-03 10:15:07 -07:00
Lindsey Heagy 54a0580a8a Simple --> RawVec 2015-05-01 12:25:57 -07:00
Rowan Cockett 3d2128f333 Merge branch 'master' of https://github.com/simpeg/simpeg into TreeMesh 2015-05-01 11:16:04 -07:00
Rowan Cockett f86d3d7bdc updates to plotting 2015-05-01 11:13:44 -07:00
Lindsey Heagy a990849256 fixed name of MagDipole_Bfield so it is consistent with the current naming convention 2015-04-30 13:05:43 -07:00
Lindsey Heagy 51342e7cc8 Fairly major source refactor:
- removed the folder Sources and put those routines inside of SrcUtils.
	- Broke apart calls for MagDipole, MagDipole_B, CircularLoop
2015-04-29 16:32:50 -07:00
Lindsey dc7cc1c716 tx -> src 2015-04-17 16:41:54 -07:00
Lindsey Heagy 08d90bbb67 Fixed bug in setting self.curModel in FieldsFDEM_j 2015-04-17 12:29:49 -07:00
Lindsey 2864a976c6 derivatives for fields objects, UNTESTED. TODO: clean up how we get derivs of mass matrices wrt the physical properties 2015-04-17 11:21:07 -07:00
Lindsey 93778d13f1 ProblemFDEM_x.getSource now returns two matrices, S_m and S_e, which cleans up getRHS and the Fields 2015-04-17 10:53:25 -07:00
Lindsey e980477031 H-J Fields objects created and consistent. Derivatives not implemented yet 2015-04-16 16:52:29 -07:00
Lindsey Heagy 50a853a3b6 CalcFields is obselete 2015-04-16 14:49:29 -07:00
Lindsey 1964a002f1 Removed Known Fields from base Fields object, it is unique to each fields object type 2015-04-16 09:39:26 -07:00
Lindsey f5a0465f1e functioning fields object for e,b forward problems. Note that if it passes travis, that is because I am cheating and only testing things that should pass. The way getSources handles types is pretty ugly at the moment... see for example FieldsFDEM.py lines 63-69 2015-04-15 17:55:58 -07:00
Lindsey dbf3175c39 working on deBugging 2015-04-15 09:50:28 -07:00
Lindsey 903a418a11 each of the fields computations now just takes a transmitter 2015-04-15 09:33:21 -07:00
Lindsey 3dba2d9a04 cleaned up call of fields in Base.py, this will break the TDEM implementation 2015-04-14 20:01:58 -07:00
Lindsey fcc0650713 start of FDEM fields refactor, definately will not pass travis at the moment 2015-04-14 19:45:24 -07:00
Lindsey 228f3f7f38 Merge pull request #14 from simpeg/sourceRefactor
working on feat/sourceRefactor instead of creating a new branch
2015-04-14 16:55:22 -07:00
Lindsey e61679bdc6 now using j_m and j_g in FDEM problem for all formulations. Note that SimpleTxFDEM has been changed toSimpleTxFDEM_g and SimpleTxFDEM_m 2015-04-14 16:40:09 -07:00
Rowan Cockett e93295e91f additional unit tests for tree mesh 2015-04-06 10:19:00 -07:00
Rowan Cockett a9b1f89e7f updates to TreeMesh 2015-04-05 17:09:03 -07:00
Rowan Cockett 223380484b A bug that took six hours to track down. Two characters. 2015-04-05 17:07:10 -07:00
Rowan Cockett 6e4aac140b Merge branch 'master' of https://github.com/simpeg/simpeg into TreeMesh 2015-04-04 14:45:42 -07:00
Rowan Cockett b9818a600b updates to tx bug fix. 2015-03-23 07:50:28 -07:00
Rowan Cockett 78c98e5ad6 simple transmitter. 2015-03-21 21:59:27 -07:00
Rowan Cockett 224a5311d6 change where we get the source from (in the transmitter). 2015-03-21 21:50:47 -07:00
Rowan Cockett a6e82ecc2a remove trailing spaces. Fix reordering bug. 2015-03-21 21:20:03 -07:00
Rowan Cockett 127b90c88d Add more files to export on the init. 2015-03-21 21:19:06 -07:00
Lindsey 1a760cedc5 Merge pull request #12 from simpeg/HJformulation
H jformulation
2015-03-03 16:29:50 -08:00
Lindsey 65842379b5 Added self._makeASymmetric in b and j formulations (e and h are symmetric already) 2015-03-03 10:02:19 -08:00
Rowan Cockett 6ffeb5cc1a minor update to survey, to return dobs from makeSyntheticData 2015-03-03 10:00:36 -08:00
Lindsey c480279ae5 added _makeASymmetric option to j, b implementations 2015-03-02 15:43:17 -08:00
Lindsey ed61178b45 removed comment blocks of old code from get RHS in each formulation 2015-03-02 15:07:50 -08:00
Lindsey a697833b9f changed todo for constant mu to anisotropic mu 2015-03-02 14:49:06 -08:00
Lindsey Heagy fa0fd7f23f broke out calculation of source term from rhs so that you can do prb.getSource 2015-02-28 10:18:58 -08:00
Lindsey Heagy 35678c587d Removed extra mui in bformulation deriv terms 2015-02-28 08:20:58 -08:00
Lindsey 62b4edcf6d - changed H implementation to primary secondary for a dipole source (much faster)
- removed extra MeMui matrix floating around in the B implementation
- changed tests so that we do not cross-check the z-components, as this doesn't make sense for the primary secondary approach if we don't add back the primary
2015-02-27 18:43:47 -08:00
Lindsey 84fedcf2a7 seperated out calculation of j_s from calculation of rhs in j formulation 2015-02-27 15:25:13 -08:00
Lindsey 2780a4cea7 HJ formulation implemented. EB formlation will fail the cross-check test... maybe a problem in the source definition? 2015-02-27 13:55:18 -08:00
Lindsey 5c19da60cc fixed MeMuI, should be invmat=True, as opposed to 1/mu 2015-02-27 12:13:01 -08:00
Lindsey 564fa14826 Added CrossCheck test to make sure that both formulations give the same results. HJ is going to make travis fail... 2015-02-26 16:30:11 -08:00
Lindsey 94d12b257a Test everything 2015-02-26 15:40:51 -08:00
Lindsey 0e0033eb0a HJ formulation, Problem_h solving for j implemented. I don't yet trust the solution 2015-02-26 15:40:03 -08:00
Lindsey d5eef78b57 fixed typo on MeMuI property 2015-02-26 15:04:14 -08:00
Lindsey 5ac746f31f added MeMu and changed MeMui to MeMuI in mu setter 2015-02-26 15:03:04 -08:00
Lindsey 5284b91f33 changed _MeMui to _MeMuI 2015-02-26 14:57:08 -08:00
Lindsey 5d74fc2d1b Changed MeMui to MeMuI, it should be the full inverse 2015-02-26 14:27:49 -08:00
Lindsey 8d4e001301 HJ formulation solving for h, with h data 2015-02-26 13:51:42 -08:00
Lindsey 5e323591b9 expanded documentation for solving for J 2015-02-26 10:39:04 -08:00
Lindsey 5bb5e8f6b3 Start of JH implementation, solving for h. Derivatives for ProblemFDEM_h NOT working yet 2015-02-25 20:21:44 -08:00
Lindsey 3201d1fc59 Moved call of store these fields before the __init__ so that we don't mess with the base problem, updated names of mass matrices so it is clear they are mass matrices not phys props 2015-02-25 17:58:54 -08:00
Lindsey 31c697eafa added MeMu, and am using self.mu everywhere instead of mu_0 2015-02-25 17:06:38 -08:00
Lindsey 57380ea2d8 Tested and passing HJ formulation, solving for J. Only works with diagonal anisotropy 2015-02-25 16:28:54 -08:00
Lindsey 2a6f0ab440 Start of HJ formulation: FAILING TESTS right now 2015-02-24 18:00:34 -08:00
Lindsey 4e69ee1f1f Merge branch 'master' into HJformulation 2015-02-24 15:56:35 -08:00
Rowan Cockett ab0049180d Merge pull request #11 from simpeg/addingMu
Adding mu
2015-02-24 17:44:08 -05:00
Rowan Cockett e99d6dc208 update miniconda 2015-02-24 17:16:47 -05:00
Rowan Cockett 629bb56185 minor updates to travis. 2015-02-24 17:15:00 -05:00
Rowan Cockett 2a53b78ccd Update the miniconda version 3.3.0 --> 3.8.3
Reverse other changes.
2015-02-24 17:08:37 -05:00
Lindsey 0a98c5f1c3 Fixed Travis? 2015-02-24 12:54:45 -08:00
Lindsey 71881c7ce8 - added capability for adding a mu model
- added variable mu in the FDEM testing
- also added capability to add a small random vector to sigma and mu for testing
2015-02-24 11:43:59 -08:00
Lindsey ed1457df86 start of j implementation, UNTESTED 2015-02-23 17:42:25 -08:00
Rowan Cockett 0220ee57f2 start of inner products 2015-02-11 23:08:22 -08:00
Rowan Cockett 5cdab15aa1 nodal gradient 2015-02-11 21:57:05 -08:00
Rowan Cockett 3369096126 updates to edge Curlssssszzzz 2015-02-11 17:30:41 -08:00
Rowan Cockett 99ada822e8 faceDiv in 3D 2015-02-11 17:16:29 -08:00
Rowan Cockett 5afea4e2b6 update grids. Think refining is working properly 2015-02-11 16:36:57 -08:00
Rowan Cockett d65a3540a4 cell indexing 2015-02-11 13:38:08 -08:00
Rowan Cockett a4f3db398f fancy indexing classes 2015-02-11 12:53:15 -08:00
Rowan Cockett 5c85f13cb6 test counting, put dummies in for grid3D calcs 2015-02-10 12:42:35 -08:00
Rowan Cockett 72c8dfb3ef generalize sorting alg 2015-02-10 12:39:41 -08:00
Rowan Cockett 1c40cbb972 init3D 2015-02-10 12:34:48 -08:00
Rowan Cockett e0303b8dff multi face refinement 2015-02-09 22:52:08 -08:00
Rowan Cockett 156b85319c updates to multiple edge refinement 2015-02-09 22:51:52 -08:00
Rowan Cockett 006dcf393d updates to area calculation 2015-02-09 22:12:22 -08:00
Rowan Cockett 9a8f4d60f7 test area edge vol 2015-02-09 21:59:28 -08:00
Rowan Cockett 5e5a3221e8 test simple grid functions add Nodal Grid 2015-02-09 21:48:42 -08:00
Rowan Cockett 310f327b5a updates to edges and areas 2015-02-09 21:30:54 -08:00
Rowan Cockett a7a6671ad4 updates to tree mesh. faceDiv kinda working. 2015-02-09 20:52:26 -08:00
Rowan Cockett aa05cdc653 initial work on new tree mesh implementation 2015-02-09 20:19:00 -08:00
Rowan Cockett 5c675a7992 update the tests to test the 3D version of the equations. 2015-01-29 14:58:01 -08:00
Rowan Cockett b2d57e8892 updates to 2D testing 2015-01-29 14:02:26 -08:00
sgkang bc7fb2f1d7 Update __init__.py 2014-11-21 12:32:24 -08:00
seogi 1edca3b9e3 Fix bug 2014-11-21 11:01:58 -08:00
seogi e83b76a70c Modification for Cylinderical mesh 2014-11-21 09:45:24 -08:00
Rowan Cockett 9067590c65 VanG model bug. 2014-11-18 08:24:51 -08:00
SEOGI KANG bfb5e045fc FIx bug for loop source 2014-11-14 13:23:18 -08:00
rowanc1 7d14489c4e updates to analytics and a 'test' in the notebook
- need to change this into a real test!
2014-10-09 11:43:10 -07:00
Lindsey Heagy 3846a6303b FEM -> FDEM in tests for analytics 2014-10-08 15:41:38 -07:00
Lindsey Heagy 682a8e3877 call for analytics now: EM.Analytics.FDEM (or TDEM) 2014-10-08 14:10:27 -07:00
Lindsey Heagy c229e26f74 added plots 2014-10-08 14:06:48 -07:00
Lindsey Heagy ed54a230da - changed name of analytical dipole in a whole space fct (now: AnalyticMagDipoleWholeSpace)
- added todos in comments
- started notebook for checks
- added notebook checkpoints to git ignore
2014-10-07 17:45:56 -07:00
Lindsey Heagy cf2a9688c3 Start of analytical dipole in a whole-space. Not yet tested 2014-10-06 19:37:26 -07:00
rowanc1 6166c2b14b Make boundary conditions be passed the current head value. 2014-07-15 07:56:06 -07:00
rowanc1 dd766a3ce3 update the code to use sources differently. 2014-07-04 14:51:54 -07:00
rowanc1 2e0aadf113 Generalize sources a little bit to make them easier to use 2014-07-04 14:46:58 -07:00
rowanc1 c503173317 Move analytics and Sources into main directory. 2014-07-04 14:24:25 -07:00
Rowan Cockett 10cf6817a3 Merge pull request #7 from simpeg/innerProductUpdates
Inner product updates
2014-07-03 12:23:59 -07:00
rowanc1 896bb68bac Updates to innerproductsDervis 2014-07-03 11:13:53 -07:00
rowanc1 076005a7e9 fix tests for now. 2014-07-03 10:03:42 -07:00
rowanc1 f747d724c9 Make working in log conductivity a bit more explicit.
Should be fixed in the actual implementation, and use SimPEG maps
instead of forcing the user to work in weird units.
2014-07-03 09:56:05 -07:00
rowanc1 23141c682f update example to work with new problem formulation in simpeg 2014-07-03 07:50:25 -07:00
rowanc1 2e3f98800c tensorType in problem. 2014-06-18 11:09:23 -07:00
rowanc1 e5650dfc92 Merge branch 'master' of https://github.com/simpeg/simpegem into innerProductUpdates 2014-06-18 10:24:04 -07:00
rowanc1 57f16fc408 updates (a bit slower implementation that is more general) 2014-06-17 14:01:57 -06:00
rowanc1 932f1dbd05 minimal updates to get it working (with depreciation warnings) 2014-06-17 10:03:28 -06:00
seogi 1bcf58154f Fix import stuff 2014-06-05 13:36:37 -07:00
seogi 3e35c6068b Put CircularLoop as an option in TDEM 2014-06-05 13:11:24 -07:00
seogi 0838d21bce Working CircularLoop code
: Can be used to compute initial condition for TDEM or
  Secondary field approach for FDEM
2014-06-05 11:53:15 -07:00
rowanc1 b34b36bfb9 Test cyl example inversion 2014-05-19 11:53:58 -07:00
rowanc1 0718c2c50a coverage updates 2014-05-19 11:40:30 -07:00
rowanc1 75fb7a8719 Update travis! 2014-05-19 11:30:32 -07:00
rowanc1 49e07477b2 some cpu optimizations 2014-05-19 01:23:34 -07:00
rowanc1 26079333bb simpeg updates 2014-05-18 23:18:24 -07:00
rowanc1 bbf2a2a7f3 move fields to problem 2014-05-18 23:12:58 -07:00
rowanc1 f4a38e1165 update travis to email 2014-05-18 20:18:16 -07:00
rowanc1 6aaacc382a Memory optimizations. Fix y to be calculated on the fly. 2014-05-18 19:24:10 -07:00
rowanc1 06e8059e3c more mesh and model updates. 2014-05-18 16:39:39 -07:00
rowanc1 7a15797fbe Mesh and model updates. 2014-05-18 16:39:10 -07:00
rowanc1 6e7d88de77 Solver updates. 2014-05-16 22:06:59 -07:00
rowanc1 1530096d01 travis 2014-05-16 20:00:20 -07:00
rowanc1 9f7527d8bf travis 2014-05-16 19:54:32 -07:00
rowanc1 e11b8f3fe3 travis 2014-05-16 19:52:42 -07:00
rowanc1 3da5b6ebc0 travis updates 2014-05-16 19:51:55 -07:00
rowanc1 bb8dbd8c86 Solver updates. 2014-05-16 19:35:50 -07:00
rowanc1 6aada6d61d readme 2014-05-16 17:18:14 -07:00
rowanc1 9400bdd9e0 update coveralls 2014-05-16 17:16:01 -07:00
rowanc1 c4f795ea79 travis 2014-05-16 16:34:50 -07:00
rowanc1 897c0e4a13 travis 2014-05-16 16:32:30 -07:00
rowanc1 c28c358930 travis 2014-05-16 16:28:10 -07:00
rowanc1 711c66a2ab travis 2014-05-16 16:20:14 -07:00
rowanc1 5a1856c1cf Try adding coverage and a very different travis file.
see:
https://gist.github.com/dan-blanchard/7045057
2014-05-16 16:12:59 -07:00
rowanc1 48ad667c1f Clean up repo. 2014-05-16 15:51:57 -07:00
rowanc1 95a837b1fc speye 2014-05-16 15:13:06 -07:00
rowanc1 4398092023 Try changing travis file so it takes less time to run tests. 2014-05-16 14:33:08 -07:00
rowanc1 4e104ced08 Fix test. 2014-05-16 12:53:33 -07:00
rowanc1 220e244cdf Memory clean ups with fancier fields objects. 2014-05-16 12:42:14 -07:00
rowanc1 cfcf741a0b Clean up p indexing 2014-05-15 12:21:24 -07:00
rowanc1 4899346f6b Better fields object. 2014-05-15 12:20:56 -07:00
rowanc1 205d2e6b5e verbosity option. 2014-05-15 09:08:25 -07:00
rowanc1 d58cb21123 Minor Memory improvements and speedups.
Speedups are from brackets mat-vec prods vs mat-mat
Memory is from not setting all 'b' fields to zero in Gvec
2014-05-15 08:52:30 -07:00
rowanc1 06b34d8f7b indexing bug in E field derivs 2014-05-02 14:56:12 -07:00
rowanc1 464264b902 Merge branch 'master' of https://github.com/simpeg/simpegem
Remove mumps code, to put in SimPEG Solvers
2014-05-02 14:04:37 -07:00
rowanc1 cb4f699be5 currentModel changes to avoid recalculations of the modelTransform 2014-05-02 13:54:45 -07:00
seogi 5cf74864cc Working for Mumps 2014-05-02 11:46:57 -07:00
seogi 88e16ac1e0 Working for Mumps 2014-05-02 11:46:40 -07:00
rowanc1 1dd9109f22 dbdt projection in TDEM 2014-05-02 10:59:29 -07:00
SEOGI KANG 53c1fe220d Merge branch 'master' of https://github.com/simpeg/simpegem 2014-04-30 22:29:57 -07:00
SEOGI KANG 25267d1d32 working tdem inversion example 2014-04-30 22:29:12 -07:00
rowanc1 cb6781a138 turn off plotting in transect analytic test. 2014-04-30 21:53:59 -07:00
rowanc1 f0e0cade97 FDEM sign switch due to VMD, tdem renaming of 'test*' to dotest so travis doesn't run them.. 2014-04-30 19:17:32 -07:00
rowanc1 8b30a1fe6a MVP choose down. 2014-04-30 18:29:41 -07:00
rowanc1 a834b69744 Choose vertical down source for VMD_MVP 2014-04-30 09:11:17 -07:00
rowanc1 ce2ab57669 Rearrange methods. 2014-04-29 11:42:53 -07:00
rowanc1 c77a0279c8 Documentation updates. 2014-04-29 11:36:35 -07:00
rowanc1 6e21d32230 test Combinations of rxs and txs for J and Jt 2014-04-29 10:52:15 -07:00
rowanc1 b750faa3e0 Multiple recs on one tx for the same field had a bug. These should add in the projection adjoint. 2014-04-28 16:11:22 -07:00
Rowan Cockett 6f2d57857d Merge pull request #6 from simpeg/MultipleTransmitters
Multiple transmitters
2014-04-28 15:24:00 -07:00
rowanc1 8e5c93accb Updates to derivs for multiple Txs 2014-04-28 12:34:44 -07:00
rowanc1 4c15267c0c Adjoint test working. 2014-04-28 11:59:25 -07:00
rowanc1 3514ad56d3 Adjoint solve not yet working. 2014-04-27 23:24:49 -07:00
rowanc1 df7676f14c working jvec 2014-04-27 22:17:55 -07:00
rowanc1 d1f23081d6 comment G vec and Gt vec 2014-04-27 21:49:00 -07:00
rowanc1 45884ba865 Updates to TDEM (Jtvec still not working.) 2014-04-27 20:51:32 -07:00
rowanc1 9f82ffff7b column concat initial fields. 2014-04-26 23:22:02 -07:00
rowanc1 9ebbe7613d Forward problem working. Not yet tested with multi Tx. 2014-04-26 23:15:31 -07:00
rowanc1 78b3a281f4 typo. 2014-04-26 22:16:24 -07:00
rowanc1 05bb79f710 Make a base EM problem that is shared between TD and FD 2014-04-26 18:55:02 -07:00
rowanc1 9a801a87d5 Reference to FieldsTDEM 2014-04-26 17:12:26 -07:00
rowanc1 f3f571edbd Move Fields object to base simpeg. 2014-04-26 17:08:24 -07:00
rowanc1 06de6a346f Changes to MeshTensor. 2014-04-26 12:20:29 -07:00
rowanc1 7254933695 Minor bug fixes. 2014-04-25 17:27:32 -07:00
rowanc1 200a1680ca Switch to BaseTimeProblem 2014-04-24 16:50:58 -07:00
rowanc1 d9e91a5a1d Survey FDEMData object to SimPEG Survey.Data 2014-04-24 16:20:40 -07:00
rowanc1 96e129aae2 Time projections 2014-04-20 13:12:14 -07:00
rowanc1 f8f681df25 Updates to Rx and Tx in FDEM 2014-04-20 12:00:48 -07:00
rowanc1 2831b66ea9 Variable Time Stepping 2014-04-20 11:33:59 -07:00
rowanc1 44ec85cfaa More analytic tests. 2014-04-17 11:54:51 -07:00
rowanc1 7b8cbabbb3 Testing of analytics. 2014-04-17 11:25:26 -07:00
Dave Marchant 030e3bc521 Fix to TDEM_bTests 2014-04-15 21:30:30 -07:00
Rowan Cockett f4e210a61d Merge pull request #5 from simpeg/MapUpdates
Map updates (there are still serious(?) problems with TDEM), but not with these updates.
2014-04-15 16:43:58 -07:00
rowanc1 8f108d488d simper model-->mapping and docs updates. 2014-04-15 15:43:16 -07:00
rowanc1 2d90799415 travis updates. 2014-04-15 15:39:59 -07:00
rowanc1 eab87c892b Updates to for mapping changes in SimPEG 2014-04-15 12:07:58 -07:00
rowanc1 113c97ca87 cylMesh Conventions.. A start 2014-04-15 11:20:39 -07:00
rowanc1 3f7f95de8c magDipole Bug 2014-04-15 09:19:49 -07:00
rowanc1 4b569924f4 Empirical function updates. 2014-04-14 09:31:16 -07:00
rowanc1 9252ed7980 VanG empirical relations 2014-04-09 10:34:47 -06:00
Rowan Cockett 20d1ad27c8 Change showIt=False to pass test on Travis 2014-04-08 21:33:20 -06:00
seogi 8326c50d56 Inaccuracy problems with resistive background and closer to Tx.
Need to be tackled.
2014-04-08 18:48:16 -07:00
Lindsey Heagy beb2fa1a58 start of docs for e-formulation 2014-04-05 13:19:21 -07:00
Lindsey Heagy e26aa607a3 fix lists and improved intro a bit 2014-04-05 12:23:27 -07:00
Lindsey Heagy cd871dbaf4 I think the in-text math should be straightened out now! 2014-04-05 12:07:27 -07:00
Lindsey Heagy b7bff90c47 slight improvement on intro / background and second attempt at fixing the math 2014-04-05 11:59:16 -07:00
Lindsey Heagy 9779457448 fixed math and added a small intro (that could use a bit of work) 2014-04-05 11:47:46 -07:00
Lindsey Heagy fa657eb7d3 start of documentation for FDEM 2014-04-05 11:21:27 -07:00
rowanc1 b1613dba65 All derivatives/adjoints working for FDEM. 2014-03-30 14:06:54 -07:00
rowanc1 9acaae66db Projections and derivatives working. 2014-03-22 13:22:44 -07:00
rowanc1 b7d47bcf38 Organize data object by rx as well as tx 2014-03-22 12:52:30 -07:00
rowanc1 aacbc03cf6 Change rxList --> [rx,rx]
Projections are not shared at the moment, but this can be changed later.
2014-03-22 12:24:54 -07:00
rowanc1 a8f09ee869 forward problem changes in data projection. have broken the derivative test. 2014-03-21 17:09:39 -07:00
rowanc1 837a114ad7 capitalization changes. 2014-03-20 00:17:48 -07:00
rowanc1 879f13df70 Minor updates. 2014-03-20 00:04:56 -07:00
rowanc1 0a5a7aa5e3 Allows calculation of other fields, and derivatives. e.g. b from when solving e, and visa versa 2014-03-19 23:58:44 -07:00
rowanc1 3197689fb7 bug fix in test. 2014-03-19 17:46:14 -07:00
rowanc1 67aa72f494 Tested J and Jt for b and e formulations. Generalized code so it is easy to reuse. New receiver types. 2014-03-19 17:33:41 -07:00
rowanc1 0efdffa3d6 Rearrange the FDEM to be closer to the TDEM implementation. 2014-03-19 14:14:25 -07:00
rowanc1 4709545b0d Added FDEM_b example. 2014-03-19 13:42:11 -07:00
rowanc1 357633c39b Remove makeMassMatrices and change to a dependentProperty 2014-03-19 13:34:41 -07:00
rowanc1 0f7e4a88ff Documentation Updates 2014-03-19 11:46:24 -07:00
rowanc1 dd671e1277 Test with an analytic and some documentation. 2014-03-19 11:24:30 -07:00
rowanc1 49eddb4b83 Analytics, b and e formulations, and better solver access 2014-03-18 10:53:20 -07:00
rowanc1 d177960abb fake the sources for FDEM 2014-03-17 11:26:06 -07:00
rowanc1 3fd840201d model versus sigma bug 2014-03-17 10:49:06 -07:00
rowanc1 95e5a09523 Adjoint test and Jtvec for multiple transmitters 2014-03-17 10:28:43 -07:00
rowanc1 5c4ec4a1cd Updates to data objects. 2014-03-17 09:55:34 -07:00
rowanc1 31da380804 deleted example in fdem, use test for example for now. 2014-03-10 23:01:49 -07:00
rowanc1 e1010f9eca Initial fields and data implementation. 2014-03-10 22:47:43 -07:00
rowanc1 f10c029161 Updates to fields storage 2014-03-10 22:17:11 -07:00
rowanc1 98385e5f28 Changed Data --> Survey 2014-03-07 14:14:45 -08:00
rowanc1 a14d771515 Change Data to Survey 2014-03-07 14:01:46 -08:00
rowanc1 e074cca07c cleaning up FDEM 2014-03-05 17:25:42 -08:00
rowanc1 994bb2159e Tested Jvec for FDEM 2014-03-05 16:33:30 -08:00
Lindsey Heagy 880780fce0 Jv implemented for single TX 2014-03-04 11:09:12 -08:00
rowanc1 752696a5d5 added a few things! 2014-02-27 15:20:35 -08:00
rowanc1 8919861e91 try again! figure out where to put things... 2014-02-27 13:50:18 -08:00
rowanc1 4b7323b8f5 setup.py 2014-02-27 13:34:13 -08:00
rowanc1 ce9111efa1 move to inline plotting? 2014-02-27 12:40:46 -08:00
rowanc1 d8128c2976 setup.py work.. 2014-02-27 12:31:59 -08:00
rowanc1 0e9b1371e3 more setup.py stuff. 2014-02-27 12:23:36 -08:00
rowanc1 e5105065a5 testing setup.py 2014-02-27 12:18:22 -08:00
rowanc1 9fb83ad727 try updating rtfd 2014-02-27 09:51:02 -08:00
rowanc1 7a5fde8a3e Minor changes to problem 2014-02-27 09:44:23 -08:00
Dave Marchant 297b16bf43 Rewrote TDEM_b tests to work with a log/active cell/1D combo model. Reorganized. 2014-02-26 11:38:41 -08:00
Dave Marchant 8ed0ee29e2 Merge branch 'master' of https://github.com/simpeg/simpegem 2014-02-26 11:34:00 -08:00
Dave Marchant 3a3949d9bb Modifications to TDEM_b 2014-02-26 11:33:39 -08:00
rowanc1 1016def784 minor updates 2014-02-25 17:24:11 -08:00
rowanc1 0084a278b5 derivative tests 2014-02-25 16:54:29 -08:00
rowanc1 715bed21ce Initial commit of richards equation code. Forward working. Inverse untested. 2014-02-25 11:35:13 -08:00
rowanc1 beb87d1f36 initial commit 2014-02-25 11:20:27 -08:00
Lindsey Heagy 12b0755dfc start of the FDEM 2014-02-21 17:28:10 -08:00
rowanc1 d3789eebe2 travis again..sorry. 2014-02-21 10:49:27 -08:00
rowanc1 e897165edb update travis so it is easier to read. 2014-02-21 10:42:47 -08:00
Dave Marchant e696170ce8 Some documentation. 2014-02-20 15:28:38 -08:00
Dave Marchant 81e013857d Added Jtvec method & adjoint test. Relaxed adjoint test tolerances so TravisCI will stop bothering me. 2014-02-18 20:50:39 -08:00
Dave Marchant edc241eec2 Added Gtvec method to TDEM. Renamed G to Gvec. Added tests. 2014-02-18 20:34:34 -08:00
rowanc1 4cd25fde82 baseproblem 2014-02-18 18:02:11 -08:00
rowanc1 7195adc6c5 Merge branch 'master' of https://github.com/simpeg/simpegem 2014-02-18 17:57:04 -08:00
rowanc1 bf2021d8e8 initial commit of FDEM 2014-02-18 17:56:16 -08:00
Dave Marchant 915667ad4a solvent method and tests. 2014-02-18 16:27:09 -08:00
Dave Marchant 7bb70103aa Added AhtVec method & test. 2014-02-18 15:49:54 -08:00
Dave Marchant 1128fbe39b Added adjoint test for projection. 2014-02-15 14:16:48 -08:00
Dave Marchant d27e7d3aba Simplified fields method. Changed solveAh, AhVec & tests to be consistent with notes with regards to MfMui 2014-02-15 14:16:13 -08:00
rowanc1 2070bca0a6 Update to current version of develop in SimPEG 2014-02-14 13:51:17 -08:00
rowanc1 58b65e0acc working on adjoint 2014-02-13 18:33:12 -08:00
rowanc1 847070f1a2 updated and fixed em derivation 2014-02-13 18:16:57 -08:00
rowanc1 ea81e40ef7 fixed test 2014-02-13 18:15:27 -08:00
rowanc1 cc3f2d867c Data projections 2014-02-13 17:42:51 -08:00
rowanc1 cd62bfd17b added email notifications to the build testing 2014-02-13 16:10:47 -08:00
rowanc1 a2e9b3f780 docs reorganization 2014-02-13 16:05:34 -08:00
rowanc1 47c2927ffc changed to inline equation default for mathjax 2014-02-13 08:41:18 -08:00
rowanc1 b0a99d4116 moved notes to documentation. 2014-02-13 00:37:10 -08:00
rowanc1 9370e24643 Added code from KrisDavis for sources written for SimPEG. 2014-02-12 19:35:43 -08:00
rowanc1 5239e57c69 testing the sensitivities 2014-02-12 16:59:56 -08:00
Dave Marchant b42f523db0 Updates to the notes. 2014-02-12 15:56:19 -08:00
Dave Marchant 434a4232d5 Added test for AhVec and solveAh 2014-02-12 15:55:56 -08:00
rowanc1 4e08f12de4 bug fix for RHS variable 2014-02-12 15:53:11 -08:00
rowanc1 c01f1a4a5a make fields return vector if only one Tx 2014-02-12 15:24:55 -08:00
rowanc1 732ff882e0 minor changes to tdem writeup and code (still buggy!) 2014-02-12 15:02:55 -08:00
Dave Marchant 99157a89c8 Beginnings of some documentation. 2014-02-12 14:07:44 -08:00
Dave Marchant 80fff7722e Added some notes. 2014-02-12 14:07:07 -08:00
Dave Marchant ffb87aafa7 Added tests for G. 2014-02-12 11:36:49 -08:00
Dave Marchant d4a316b764 Playing with derivative tests.... I think its working..... 2014-02-12 00:00:03 -08:00
Dave Marchant cf620acf22 Reorganization. 2014-02-11 23:02:16 -08:00
Dave Marchant 6e6d90d362 Added AhVec method and test. 2014-02-11 22:51:10 -08:00
Dave Marchant 88fb57bd9f change field --> fields 2014-02-11 21:36:46 -08:00
rowanc1 4a92b6b5eb change field --> fields 2014-02-11 18:45:30 -08:00
Dave Marchant d7566f42e5 Work on the time domain inverse problem. 2014-02-11 16:41:17 -08:00
rowanc1 66ccdb4042 Updates to travis and documentation 2014-02-07 10:51:44 -08:00
rowanc1 68abb7a7cf Seogi's FDEM initial commit from SimPEG 2014-02-06 12:04:20 -08:00
Dave Marchant 08f2020ae9 Added analytics directory to Utils. Finished example of TDEM_b. Seems to be working.... 2014-02-05 23:47:21 -08:00
Dave Marchant d65705fd0b Added first pass of dared method and spacial interpolation to data class. 2014-02-05 23:45:04 -08:00
Dave Marchant 92788ad5f1 Added example of field generation. 2014-02-05 23:11:53 -08:00
Dave Marchant 710032e636 Working field and update methods. 2014-02-05 23:08:33 -08:00
Dave Marchant bb3e05fbfa Modify getInitialFields to return field object. Work on the fields object. Added methods to TDEM_b problem. (untested). 2014-02-05 22:28:04 -08:00
Dave Marchant 8efea97bb2 Setting up a B-formulation problem... 2014-02-05 21:33:32 -08:00
Dave Marchant 2c29d07fe7 Set up VMP_MVP initial fields. 2014-02-05 21:25:34 -08:00
Dave Marchant 2ec86ea09a Lots of work on time domain problem. 2014-02-05 16:28:16 -08:00
Dave Marchant f1f261243a Merge branch 'master' of https://github.com/simpeg/simpegem 2014-02-05 15:30:12 -08:00
Dave Marchant 50c2ec650e Create DataTDEM1D class 2014-02-05 15:29:37 -08:00
rowanc1 d9df40b5be Try setup.py for RTD 2014-02-05 13:48:54 -08:00
rowanc1 efc28e7251 __inti__.py --> __init__.py 2014-02-05 13:14:38 -08:00
rowanc1 7378d5f109 Merge branch 'master' of https://github.com/simpeg/simpegem 2014-02-05 13:13:16 -08:00
rowanc1 45c25365d9 Error in testing init file. 2014-02-05 13:13:06 -08:00
Dave Marchant 0532d99317 Create directories for time and frequency domain code. 2014-02-05 12:44:03 -08:00
rowanc1 81c77ad1ba Merge branch 'master' of https://github.com/simpeg/simpegem 2014-02-05 12:43:05 -08:00
rowanc1 566291955c Change travis. 2014-02-05 12:42:56 -08:00
Dave Marchant 76d971485e Created Utils/Sources dir. Added magnetic dipole code. 2014-02-05 12:28:39 -08:00
Rowan Cockett 5c509b3538 Create .gitignore 2014-02-05 12:24:17 -08:00
rowanc1 2404f3e08a Add Travis File 2014-02-05 12:22:44 -08:00
rowanc1 45567fd422 fix url 2014-02-05 12:00:55 -08:00
rowanc1 3ee18c8946 Initial Commit (boilerplate) 2014-02-05 11:55:45 -08:00
134 changed files with 23217 additions and 1931 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
[bumpversion]
current_version = 0.1.3
current_version = 0.1.4
files = setup.py SimPEG/__init__.py docs/conf.py
-1
View File
@@ -38,5 +38,4 @@ nosetests.xml
*.sublime-project
*.sublime-workspace
docs/_build/
*_cython.c
Makefile
+28 -6
View File
@@ -2,6 +2,27 @@ language: python
python:
- 2.7
sudo: false
addons:
apt:
packages:
- gcc
- gfortran
- libopenmpi-dev
- libmumps-seq-dev
- libblas-dev
- liblapack-dev
env:
- TEST_DIR="tests/mesh tests/base tests/utils"
- TEST_DIR=tests/examples
- TEST_DIR=tests/em/fdem/forward
- TEST_DIR=tests/em/fdem/inverse/derivs
- TEST_DIR=tests/em/fdem/inverse/adjoint
- TEST_DIR=tests/em/tdem
- TEST_DIR=tests/flow
# Setup anaconda
before_install:
- 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
@@ -9,20 +30,21 @@ before_install:
- ./miniconda.sh -b
- export PATH=/home/travis/anaconda/bin:/home/travis/miniconda/bin:$PATH
- conda update --yes conda
# The next couple lines fix a crash with multiprocessing on Travis and are not specific to using Miniconda
- sudo rm -rf /dev/shm
- sudo ln -s /run/shm /dev/shm
# Install packages
install:
- conda install --yes pip python=$TRAVIS_PYTHON_VERSION numpy scipy matplotlib cython
- conda install --yes pip python=$TRAVIS_PYTHON_VERSION numpy scipy matplotlib cython ipython nose
- pip install nose-cov python-coveralls
# - pip install -r requirements.txt
- git clone https://github.com/rowanc1/pymatsolver.git
- cd pymatsolver; python setup.py install; cd ..
- python setup.py install
- python setup.py build_ext --inplace
# Run test
script:
- nosetests --with-cov --cov SimPEG --cov-config .coveragerc -v -s
- nosetests $TEST_DIR --with-cov --cov SimPEG --cov-config .coveragerc -v -s
# Calculate coverage
after_success:
+22
View File
@@ -0,0 +1,22 @@
Citing SimPEG
=============
There is a paper about SimPEG!
Cockett, R., Kang, S., Heagy, L. J., Pidlisecky, A., & Oldenburg, D. W. (2015). SimPEG: An open source framework for simulation and gradient based parameter estimation in geophysical applications. Computers & Geosciences.
BibTex:
-------
.. code::
@article{cockett2015simpeg,
title={SimPEG: An open source framework for simulation and gradient based parameter estimation in geophysical applications},
author={Cockett, Rowan and Kang, Seogi and Heagy, Lindsey J and Pidlisecky, Adam and Oldenburg, Douglas W},
journal={Computers \& Geosciences},
year={2015},
publisher={Elsevier}
}
+23 -1
View File
@@ -36,6 +36,28 @@ The vision is to create a package for finite volume simulation with applications
* designed for large-scale inversions
Citing SimPEG:
--------------
There is a paper about SimPEG!
Cockett, R., Kang, S., Heagy, L. J., Pidlisecky, A., & Oldenburg, D. W. (2015). SimPEG: An open source framework for simulation and gradient based parameter estimation in geophysical applications. Computers & Geosciences.
**BibTex:**
.. code::
@article{cockett2015simpeg,
title={SimPEG: An open source framework for simulation and gradient based parameter estimation in geophysical applications},
author={Cockett, Rowan and Kang, Seogi and Heagy, Lindsey J and Pidlisecky, Adam and Oldenburg, Douglas W},
journal={Computers \& Geosciences},
year={2015},
publisher={Elsevier}
}
Website:
http://simpeg.xyz
@@ -57,4 +79,4 @@ https://github.com/simpeg/simpeg/issues
Code Snippets & Tutorials:
http://www.row1.ca/simpeg
http://simpeg.xyz/Journal
+1 -1
View File
@@ -149,7 +149,7 @@ class TargetMisfit(InversionDirective):
@property
def target(self):
if getattr(self, '_target', None) is None:
self._target = self.survey.nD
self._target = self.survey.nD*0.5
return self._target
@target.setter
def target(self, val):
+153
View File
@@ -0,0 +1,153 @@
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi
from scipy.special import erf
import matplotlib.pyplot as plt
from SimPEG import Utils
def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0):
"""
4.56 in Ward and Hohmann
.. plot::
import matplotlib.pyplot as plt
from SimPEG import EM
freq = np.logspace(-1, 6, 61)
test = EM.Analytics.FDEM.hzAnalyticDipoleF(100, freq, 0.001, secondary=False)
plt.loglog(freq, abs(test.real))
plt.loglog(freq, abs(test.imag))
plt.title('Response at $r$=100m')
plt.xlabel('Frequency')
plt.ylabel('Response')
plt.legend(('real','imag'))
plt.show()
"""
r = np.abs(r)
k = np.sqrt(-1j*2.*np.pi*freq*mu*sigma)
m = 1
front = m / (2. * np.pi * (k**2) * (r**5) )
back = 9 - ( 9 + 9j * k * r - 4 * (k**2) * (r**2) - 1j * (k**3) * (r**3)) * np.exp(-1j*k*r)
hz = front*back
if secondary:
hp =-1/(4*np.pi*r**3)
hz = hz-hp
if hz.ndim == 1:
hz = Utils.mkvc(hz,2)
return hz
def MagneticDipoleWholeSpace(XYZ, srcLoc, sig, f, moment=1., orientation='X', mu = mu_0):
"""
Analytical solution for a dipole in a whole-space.
Equation 2.57 of Ward and Hohmann
TODOs:
- set it up to instead take a mesh & survey
- add E-fields
- handle multiple frequencies
- add divide by zero safety
.. plot::
from SimPEG import EM
import matplotlib.pyplot as plt
freqs = np.logspace(-2,5,100)
Bx, By, Bz = EM.Analytics.FDEM.AnalyticMagDipoleWholeSpace([0,100,0], [0,0,0], 1e-2, freqs, m=1, orientation='Z')
plt.loglog(freqs, np.abs(Bz.real)/mu_0, 'b')
plt.loglog(freqs, np.abs(Bz.imag)/mu_0, 'r')
plt.legend(('real','imag'))
plt.show()
"""
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
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 )
kr = k*r
front = moment / (4.*pi * r**3.) * np.exp(-1j*kr)
mid = -kr**2. + 3.*1j*kr + 3.
if orientation.upper() == 'X':
Hx = front*( (dx/r)**2. * mid + (kr**2. - 1j*kr - 1.) )
Hy = front*( (dx*dy/r**2.) * mid )
Hz = front*( (dx*dz/r**2.) * mid )
elif orientation.upper() == 'Y':
Hx = front*( (dy*dx/r**2.) * mid )
Hy = front*( (dy/r)**2. * mid + (kr**2. - 1j*kr - 1.) )
Hz = front*( (dy*dz/r**2.) * mid )
elif orientation.upper() == 'Z':
Hx = front*( (dx*dz/r**2.) * mid )
Hy = front*( (dy*dz/r**2.) * mid )
Hz = front*( (dz/r)**2. * mid + (kr**2. - 1j*kr - 1.) )
Bx = mu*Hx
By = mu*Hy
Bz = mu*Hz
if Bx.ndim is 1:
Bx = Utils.mkvc(Bx,2)
if By.ndim is 1:
By = Utils.mkvc(By,2)
if Bz.ndim is 1:
Bz = Utils.mkvc(Bz,2)
return Bx, By, Bz
def ElectricDipoleWholeSpace(XYZ, srcLoc, sig, f, current=1., length=1., orientation='X', mu=mu_0):
XYZ = Utils.asArray_N_x_Dim(XYZ, 3)
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 )
kr = k*r
front = current * length / (4. * np.pi * sig * r**3) * np.exp(-1j*k*r)
mid = -k**2 * r**2 + 3*1j*k*r + 3
# Ex = front*((dx**2 / r**2)*mid + (k**2 * r**2 -1j*k*r))
# Ey = front*(dx*dy / r**2)*mid
# Ez = front*(dx*dz / r**2)*mid
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
# return Ey, Ez, Ex
+98
View File
@@ -0,0 +1,98 @@
from SimPEG import Utils, np
from scipy.constants import mu_0, epsilon_0
from SimPEG.EM.Utils.EMUtils import k
def getKc(freq,sigma,a,b,mu=mu_0,eps=epsilon_0):
a = float(a)
b = float(b)
# return 1./(2*np.pi) * np.sqrt(b / a) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a))
return np.sqrt(b / a) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a))
def _r2(xyz):
return np.sum(xyz**2,1)
def _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
Kc1 = getKc(freq,sigma[1],a,b,mu[1],eps)
nobs = obsloc.shape[0]
dxyz = obsloc - np.c_[np.ones(nobs)]*np.r_[srcloc]
r2 = _r2(dxyz[:,:2])
sqrtr2z2 = np.sqrt(r2 + dxyz[:,2]**2)
k2 = k(freq,sigma[2],mu[2],eps)
return Kc1 * moment / (4.*np.pi) *np.exp(-1j*k2*sqrtr2z2) / sqrtr2z2
def _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
nobs = obsloc.shape[0]
dxyz = obsloc - np.c_[np.ones(nobs)]*np.r_[srcloc]
r2 = _r2(dxyz[:,:2])
sqrtr2z2 = np.sqrt(r2 + dxyz[:,2]**2)
k2 = k(freq,sigma[2],mu[2],eps)
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.):
HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
nobs = obsloc.shape[0]
dxyz = obsloc - np.c_[np.ones(nobs)]*np.r_[srcloc]
r2z2 = _r2(dxyz)
sqrtr2z2 = np.sqrt(r2z2)
k2 = k(freq,sigma[2],mu[2],eps)
return -HertzZ*dxyz[:,2] /sqrtr2z2 * (1j*k2 + 1./sqrtr2z2)
def _getCasingHertzMagDipole2Deriv_z_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
dHertzZdr = _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
nobs = obsloc.shape[0]
dxyz = obsloc - np.c_[np.ones(nobs)]*np.r_[srcloc]
r2 = _r2(dxyz[:,:2])
r = np.sqrt(r2)
z = dxyz[:,2]
sqrtr2z2 = np.sqrt(r2 + z**2)
k2 = k(freq,sigma[2],mu[2],eps)
return dHertzZdr*(-z/sqrtr2z2)*(1j*k2+1./sqrtr2z2) + HertzZ*(z*r/sqrtr2z2**3)*(1j*k2 + 2./sqrtr2z2)
def _getCasingHertzMagDipole2Deriv_z_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
dHertzZdz = _getCasingHertzMagDipoleDeriv_z(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
nobs = obsloc.shape[0]
dxyz = obsloc - np.c_[np.ones(nobs)]*np.r_[srcloc]
r2 = _r2(dxyz[:,:2])
r = np.sqrt(r2)
z = dxyz[:,2]
sqrtr2z2 = np.sqrt(r2 + z**2)
k2 = k(freq,sigma[2],mu[2],eps)
return (dHertzZdz*z + HertzZ)/sqrtr2z2*(-1j*k2 - 1./sqrtr2z2) + HertzZ*z/sqrtr2z2**3*(1j*k2*z + 2.*z/sqrtr2z2)
def getCasingEphiMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
return 1j * omega(freq) * mu * _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
def getCasingHrMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
return _getCasingHertzMagDipole2Deriv_z_r(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
def getCasingHzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
d2HertzZdz2 = _getCasingHertzMagDipole2Deriv_z_z(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
k2 = k(freq,sigma[2],mu[2],eps)
HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
return d2HertzZdz2 + k2**2 * HertzZ
def getCasingBrMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
return mu_0 * getCasingHrMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
def getCasingBzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.):
return mu_0 * getCasingHzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment)
+12
View File
@@ -0,0 +1,12 @@
import numpy as np
from scipy.constants import mu_0, pi
from scipy.special import erf
def hzAnalyticDipoleT(r, t, sigma):
theta = np.sqrt((sigma*mu_0)/(4*t))
tr = theta*r
etr = erf(tr)
t1 = (9/(2*tr**2) - 1)*etr
t2 = (1/np.sqrt(pi))*(9/tr + 4*tr)*np.exp(-tr**2)
hz = (t1 - t2)/(4*pi*r**3)
return hz
+3
View File
@@ -0,0 +1,3 @@
from TDEM import hzAnalyticDipoleT
from FDEM import hzAnalyticDipoleF
from FDEMcasing import *
+186
View File
@@ -0,0 +1,186 @@
from SimPEG import Survey, Problem, Utils, Models, Maps, PropMaps, np, sp, Solver as SimpegSolver
from scipy.constants import mu_0
class EMPropMap(Maps.PropMap):
"""
Property Map for EM Problems. The electrical conductivity (\\(\\sigma\\)) is the default inversion property, and the default value of the magnetic permeability is that of free space (\\(\\mu = 4\\pi\\times 10^{-7} \\) H/m)
"""
sigma = Maps.Property("Electrical Conductivity", defaultInvProp = True, propertyLink=('rho',Maps.ReciprocalMap))
mu = Maps.Property("Inverse Magnetic Permeability", defaultVal = mu_0, propertyLink=('mui',Maps.ReciprocalMap))
rho = Maps.Property("Electrical Resistivity", propertyLink=('sigma', Maps.ReciprocalMap))
mui = Maps.Property("Inverse Magnetic Permeability", defaultVal = 1./mu_0, propertyLink=('mu', Maps.ReciprocalMap))
class BaseEMProblem(Problem.BaseProblem):
def __init__(self, mesh, **kwargs):
Problem.BaseProblem.__init__(self, mesh, **kwargs)
surveyPair = Survey.BaseSurvey
dataPair = Survey.Data
PropMap = EMPropMap
Solver = SimpegSolver
solverOpts = {}
verbose = False
####################################################
# Make A Symmetric
####################################################
@property
def _makeASymmetric(self):
if getattr(self, '__makeASymmetric', None) is None:
self.__makeASymmetric = True
return self.__makeASymmetric
####################################################
# Mass Matrices
####################################################
@property
def deleteTheseOnModelUpdate(self):
toDelete = []
if self.mapping.sigmaMap is not None or self.mapping.rhoMap is not None:
toDelete += ['_MeSigma', '_MeSigmaI','_MfRho','_MfRhoI']
if self.mapping.muMap is not None or self.mapping.muiMap is not None:
toDelete += ['_MeMu', '_MeMuI','_MfMui','_MfMuiI']
return toDelete
@property
def Me(self):
"""
Edge inner product matrix
"""
if getattr(self, '_Me', None) is None:
self._Me = self.mesh.getEdgeInnerProduct()
return self._Me
@property
def Mf(self):
"""
Face inner product matrix
"""
if getattr(self, '_Mf', None) is None:
self._Mf = self.mesh.getFaceInnerProduct()
return self._Mf
# ----- Magnetic Permeability ----- #
@property
def MfMui(self):
"""
Face inner product matrix for \\(\\mu^{-1}\\). Used in the E-B formulation
"""
if getattr(self, '_MfMui', None) is None:
self._MfMui = self.mesh.getFaceInnerProduct(self.curModel.mui)
return self._MfMui
@property
def MfMuiI(self):
"""
Inverse of :code:`MfMui`.
"""
if getattr(self, '_MfMuiI', None) is None:
self._MfMuiI = self.mesh.getFaceInnerProduct(self.curModel.mui, invMat=True)
return self._MfMuiI
@property
def MeMu(self):
"""
Edge inner product matrix for \\(\\mu\\). Used in the H-J formulation
"""
if getattr(self, '_MeMu', None) is None:
self._MeMu = self.mesh.getEdgeInnerProduct(self.curModel.mu)
return self._MeMu
@property
def MeMuI(self):
"""
Inverse of :code:`MeMu`
"""
if getattr(self, '_MeMuI', None) is None:
self._MeMuI = self.mesh.getEdgeInnerProduct(self.curModel.mu, invMat=True)
return self._MeMuI
# ----- Electrical Conductivity ----- #
#TODO: hardcoded to sigma as the model
@property
def MeSigma(self):
"""
Edge inner product matrix for \\(\\sigma\\). Used in the E-B formulation
"""
if getattr(self, '_MeSigma', None) is None:
self._MeSigma = self.mesh.getEdgeInnerProduct(self.curModel.sigma)
return self._MeSigma
# TODO: This should take a vector
def MeSigmaDeriv(self, u):
"""
Derivative of MeSigma with respect to the model
"""
return self.mesh.getEdgeInnerProductDeriv(self.curModel.sigma)(u) * self.curModel.sigmaDeriv
@property
def MeSigmaI(self):
"""
Inverse of the edge inner product matrix for \\(\\sigma\\).
"""
if getattr(self, '_MeSigmaI', None) is None:
self._MeSigmaI = self.mesh.getEdgeInnerProduct(self.curModel.sigma, invMat=True)
return self._MeSigmaI
# TODO: This should take a vector
def MeSigmaIDeriv(self, u):
"""
Derivative of :code:`MeSigma` with respect to the model
"""
# TODO: only works for diagonal tensors. getEdgeInnerProductDeriv, invMat=True should be implemented in SimPEG
dMeSigmaI_dI = -self.MeSigmaI**2
dMe_dsig = self.mesh.getEdgeInnerProductDeriv(self.curModel.sigma)(u)
dsig_dm = self.curModel.sigmaDeriv
return dMeSigmaI_dI * ( dMe_dsig * ( dsig_dm))
# return self.mesh.getEdgeInnerProductDeriv(self.curModel.sigma, invMat=True)(u)
@property
def MfRho(self):
"""
Face inner product matrix for \\(\\rho\\). Used in the H-J formulation
"""
if getattr(self, '_MfRho', None) is None:
self._MfRho = self.mesh.getFaceInnerProduct(self.curModel.rho)
return self._MfRho
# TODO: This should take a vector
def MfRhoDeriv(self,u):
"""
Derivative of :code:`MfRho` with respect to the model.
"""
return self.mesh.getFaceInnerProductDeriv(self.curModel.rho)(u) * (-Utils.sdiag(self.curModel.rho**2) * self.curModel.sigmaDeriv)
# self.curModel.rhoDeriv
@property
def MfRhoI(self):
"""
Inverse of :code:`MfRho`
"""
if getattr(self, '_MfRhoI', None) is None:
self._MfRhoI = self.mesh.getFaceInnerProduct(self.curModel.rho, invMat=True)
return self._MfRhoI
# TODO: This isn't going to work yet
# TODO: This should take a vector
def MfRhoIDeriv(self,u):
"""
Derivative of :code:`MfRhoI` with respect to the model.
"""
return self.mesh.getFaceInnerProductDeriv(self.curModel.rho, invMat=True)(u) * self.curModel.rhoDeriv
+570
View File
@@ -0,0 +1,570 @@
from SimPEG import Problem, Utils, np, sp, Solver as SimpegSolver
from scipy.constants import mu_0
from SurveyFDEM import Survey as SurveyFDEM
from FieldsFDEM import Fields, Fields_e, Fields_b, Fields_h, Fields_j
from SimPEG.EM.Base import BaseEMProblem
from SimPEG.EM.Utils import omega
class BaseFDEMProblem(BaseEMProblem):
"""
We start by looking at Maxwell's equations in the electric
field \\\(\\\mathbf{e}\\\) and the magnetic flux
density \\\(\\\mathbf{b}\\\)
.. math ::
\mathbf{C} \mathbf{e} + i \omega \mathbf{b} = \mathbf{s_m} \\\\
{\mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} \mathbf{b} - \mathbf{M_{\sigma}^e} \mathbf{e} = \mathbf{M^e} \mathbf{s_e}}
if using the E-B formulation (:code:`Problem_e`
or :code:`Problem_b`) or the magnetic field
\\\(\\\mathbf{h}\\\) and current density \\\(\\\mathbf{j}\\\)
.. math ::
\mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{j} + i \omega \mathbf{M_{\mu}^e} \mathbf{h} = \mathbf{M^e} \mathbf{s_m} \\\\
\mathbf{C} \mathbf{h} - \mathbf{j} = \mathbf{s_e}
if using the H-J formulation (:code:`Problem_j` or :code:`Problem_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
fieldsPair = Fields
def fields(self, m=None):
"""
Solve the forward problem for the fields.
"""
self.curModel = m
F = self.fieldsPair(self.mesh, self.survey)
for freq in self.survey.freqs:
A = self.getA(freq)
rhs = self.getRHS(freq)
Ainv = self.Solver(A, **self.solverOpts)
sol = Ainv * rhs
Srcs = self.survey.getSrcByFreq(freq)
ftype = self._fieldType + 'Solution'
F[Srcs, ftype] = sol
return F
def Jvec(self, m, v, f=None):
"""
Sensitivity times a vector
"""
if f is None:
f = self.fields(m)
self.curModel = m
Jv = self.dataPair(self.survey)
for freq in self.survey.freqs:
A = self.getA(freq) #
Ainv = self.Solver(A, **self.solverOpts)
for src in self.survey.getSrcByFreq(freq):
ftype = self._fieldType + 'Solution'
u_src = f[src, ftype]
dA_dm = self.getADeriv_m(freq, u_src, v)
dRHS_dm = self.getRHSDeriv_m(freq, src, v)
du_dm = Ainv * ( - dA_dm + dRHS_dm )
for rx in src.rxList:
df_duFun = getattr(f, '_%sDeriv_u'%rx.projField, None)
df_dudu_dm = df_duFun(src, du_dm, adjoint=False)
df_dmFun = getattr(f, '_%sDeriv_m'%rx.projField, None)
df_dm = df_dmFun(src, v, adjoint=False)
Df_Dm = np.array(df_dudu_dm + df_dm,dtype=complex)
P = lambda v: rx.projectFieldsDeriv(src, self.mesh, f, v) # wrt u, also have wrt m
Jv[src, rx] = P(Df_Dm)
return Utils.mkvc(Jv)
def Jtvec(self, m, v, f=None):
"""
Sensitivity transpose times a vector
"""
if f is None:
f = self.fields(m)
self.curModel = m
# Ensure v is a data object.
if not isinstance(v, self.dataPair):
v = self.dataPair(self.survey, v)
Jtv = np.zeros(m.size)
for freq in self.survey.freqs:
AT = self.getA(freq).T
ATinv = self.Solver(AT, **self.solverOpts)
for src in self.survey.getSrcByFreq(freq):
ftype = self._fieldType + 'Solution'
u_src = f[src, ftype]
for rx in src.rxList:
PTv = rx.projectFieldsDeriv(src, self.mesh, f, v[src, rx], adjoint=True) # wrt u, need possibility wrt m
df_duTFun = getattr(f, '_%sDeriv_u'%rx.projField, None)
df_duT = df_duTFun(src, PTv, adjoint=True)
ATinvdf_duT = ATinv * df_duT
dA_dmT = self.getADeriv_m(freq, u_src, ATinvdf_duT, adjoint=True)
dRHS_dmT = self.getRHSDeriv_m(freq,src, ATinvdf_duT, adjoint=True)
du_dmT = -dA_dmT + dRHS_dmT
df_dmFun = getattr(f, '_%sDeriv_m'%rx.projField, None)
dfT_dm = df_dmFun(src, PTv, adjoint=True)
du_dmT += dfT_dm
real_or_imag = rx.projComp
if real_or_imag is 'real':
Jtv += np.array(du_dmT,dtype=complex).real
elif real_or_imag is 'imag':
Jtv += - np.array(du_dmT,dtype=complex).real
else:
raise Exception('Must be real or imag')
return Jtv
def getSourceTerm(self, freq):
"""
Evaluates the sources for a given frequency and puts them in matrix form
:param float freq: Frequency
:rtype: numpy.ndarray (nE or nF, nSrc)
:return: S_m, S_e
"""
Srcs = self.survey.getSrcByFreq(freq)
if self._eqLocs is 'FE':
S_m = np.zeros((self.mesh.nF,len(Srcs)), dtype=complex)
S_e = np.zeros((self.mesh.nE,len(Srcs)), dtype=complex)
elif self._eqLocs is 'EF':
S_m = np.zeros((self.mesh.nE,len(Srcs)), dtype=complex)
S_e = np.zeros((self.mesh.nF,len(Srcs)), dtype=complex)
for i, src in enumerate(Srcs):
smi, sei = src.eval(self)
S_m[:,i] = S_m[:,i] + smi
S_e[:,i] = S_e[:,i] + sei
return S_m, S_e
##########################################################################################
################################ E-B Formulation #########################################
##########################################################################################
class Problem_e(BaseFDEMProblem):
"""
By eliminating the magnetic flux density using
.. math ::
\mathbf{b} = \\frac{1}{i \omega}\\left(-\mathbf{C} \mathbf{e} + \mathbf{s_m}\\right)
we can write Maxwell's equations as a second order system in \\\(\\\mathbf{e}\\\) only:
.. math ::
\\left(\mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} \mathbf{C}+ i \omega \mathbf{M^e_{\sigma}} \\right)\mathbf{e} = \mathbf{C}^T \mathbf{M_{\mu^{-1}}^f}\mathbf{s_m} -i\omega\mathbf{M^e}\mathbf{s_e}
which we solve for \\\(\\\mathbf{e}\\\).
"""
_fieldType = 'e'
_eqLocs = 'FE'
fieldsPair = Fields_e
def __init__(self, mesh, **kwargs):
BaseFDEMProblem.__init__(self, mesh, **kwargs)
def getA(self, freq):
"""
.. math ::
\mathbf{A} = \mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} \mathbf{C} + i \omega \mathbf{M^e_{\sigma}}
:param float freq: Frequency
:rtype: scipy.sparse.csr_matrix
:return: A
"""
MfMui = self.MfMui
MeSigma = self.MeSigma
C = self.mesh.edgeCurl
return C.T*MfMui*C + 1j*omega(freq)*MeSigma
def getADeriv_m(self, freq, u, v, adjoint=False):
dsig_dm = self.curModel.sigmaDeriv
dMe_dsig = self.MeSigmaDeriv(u)
if adjoint:
return 1j * omega(freq) * ( dMe_dsig.T * v )
return 1j * omega(freq) * ( dMe_dsig * v )
def getRHS(self, freq):
"""
.. math ::
\mathbf{RHS} = \mathbf{C}^T \mathbf{M_{\mu^{-1}}^f}\mathbf{s_m} -i\omega\mathbf{M_e}\mathbf{s_e}
:param float freq: Frequency
:rtype: numpy.ndarray (nE, nSrc)
:return: RHS
"""
S_m, S_e = self.getSourceTerm(freq)
C = self.mesh.edgeCurl
MfMui = self.MfMui
RHS = C.T * (MfMui * S_m) -1j * omega(freq) * S_e
return RHS
def getRHSDeriv_m(self, freq, src, v, adjoint=False):
C = self.mesh.edgeCurl
MfMui = self.MfMui
S_mDeriv, S_eDeriv = src.evalDeriv(self, adjoint)
if adjoint:
dRHS = MfMui * (C * v)
return S_mDeriv(dRHS) - 1j * omega(freq) * S_eDeriv(v)
else:
return C.T * (MfMui * S_mDeriv(v)) -1j * omega(freq) * S_eDeriv(v)
class Problem_b(BaseFDEMProblem):
"""
We eliminate \\\(\\\mathbf{e}\\\) using
.. math ::
\mathbf{e} = \mathbf{M^e_{\sigma}}^{-1} \\left(\mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} \mathbf{b} - \mathbf{s_e}\\right)
and solve for \\\(\\\mathbf{b}\\\) using:
.. math ::
\\left(\mathbf{C} \mathbf{M^e_{\sigma}}^{-1} \mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} + i \omega \\right)\mathbf{b} = \mathbf{s_m} + \mathbf{M^e_{\sigma}}^{-1}\mathbf{M^e}\mathbf{s_e}
.. note ::
The inverse problem will not work with full anisotropy
"""
_fieldType = 'b'
_eqLocs = 'FE'
fieldsPair = Fields_b
def __init__(self, mesh, **kwargs):
BaseFDEMProblem.__init__(self, mesh, **kwargs)
def getA(self, freq):
"""
.. math ::
\mathbf{A} = \mathbf{C} \mathbf{M^e_{\sigma}}^{-1} \mathbf{C}^T \mathbf{M_{\mu^{-1}}^f} + i \omega
:param float freq: Frequency
:rtype: scipy.sparse.csr_matrix
:return: A
"""
MfMui = self.MfMui
MeSigmaI = self.MeSigmaI
C = self.mesh.edgeCurl
iomega = 1j * omega(freq) * sp.eye(self.mesh.nF)
A = C * (MeSigmaI * (C.T * MfMui)) + iomega
if self._makeASymmetric is True:
return MfMui.T*A
return A
def getADeriv_m(self, freq, u, v, adjoint=False):
MfMui = self.MfMui
C = self.mesh.edgeCurl
MeSigmaIDeriv = self.MeSigmaIDeriv
vec = C.T * (MfMui * u)
MeSigmaIDeriv = MeSigmaIDeriv(vec)
if adjoint:
if self._makeASymmetric is True:
v = MfMui * v
return MeSigmaIDeriv.T * (C.T * v)
if self._makeASymmetric is True:
return MfMui.T * ( C * ( MeSigmaIDeriv * v ) )
return C * ( MeSigmaIDeriv * v )
def getRHS(self, freq):
"""
.. math ::
\mathbf{RHS} = \mathbf{s_m} + \mathbf{M^e_{\sigma}}^{-1}\mathbf{s_e}
:param float freq: Frequency
:rtype: numpy.ndarray (nE, nSrc)
:return: RHS
"""
S_m, S_e = self.getSourceTerm(freq)
C = self.mesh.edgeCurl
MeSigmaI = self.MeSigmaI
RHS = S_m + C * ( MeSigmaI * S_e )
if self._makeASymmetric is True:
MfMui = self.MfMui
return MfMui.T * RHS
return RHS
def getRHSDeriv_m(self, freq, src, v, adjoint=False):
C = self.mesh.edgeCurl
S_m, S_e = src.eval(self)
MfMui = self.MfMui
if self._makeASymmetric and adjoint:
v = self.MfMui * v
MeSigmaIDeriv = self.MeSigmaIDeriv(S_e)
S_mDeriv, S_eDeriv = src.evalDeriv(self, adjoint)
if not adjoint:
RHSderiv = C * (MeSigmaIDeriv * v)
SrcDeriv = S_mDeriv(v) + C * (self.MeSigmaI * S_eDeriv(v))
elif adjoint:
RHSderiv = MeSigmaIDeriv.T * (C.T * v)
SrcDeriv = S_mDeriv(v) + self.MeSigmaI.T * (C.T * S_eDeriv(v))
if self._makeASymmetric is True and not adjoint:
return MfMui.T * (SrcDeriv + RHSderiv)
return RHSderiv + SrcDeriv
##########################################################################################
################################ H-J Formulation #########################################
##########################################################################################
class Problem_j(BaseFDEMProblem):
"""
We eliminate \\\(\\\mathbf{h}\\\) using
.. math ::
\mathbf{h} = \\frac{1}{i \omega} \mathbf{M_{\mu}^e}^{-1} \\left(-\mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{j} + \mathbf{M^e} \mathbf{s_m} \\right)
and solve for \\\(\\\mathbf{j}\\\) using
.. math ::
\\left(\mathbf{C} \mathbf{M_{\mu}^e}^{-1} \mathbf{C}^T \mathbf{M_{\\rho}^f} + i \omega\\right)\mathbf{j} = \mathbf{C} \mathbf{M_{\mu}^e}^{-1} \mathbf{M^e} \mathbf{s_m} -i\omega\mathbf{s_e}
.. note::
This implementation does not yet work with full anisotropy!!
"""
_fieldType = 'j'
_eqLocs = 'EF'
fieldsPair = Fields_j
def __init__(self, mesh, **kwargs):
BaseFDEMProblem.__init__(self, mesh, **kwargs)
def getA(self, freq):
"""
.. math ::
\\mathbf{A} = \\mathbf{C} \\mathbf{M^e_{mu^{-1}}} \\mathbf{C}^T \\mathbf{M^f_{\\sigma^{-1}}} + i\\omega
:param float freq: Frequency
:rtype: scipy.sparse.csr_matrix
:return: A
"""
MeMuI = self.MeMuI
MfRho = self.MfRho
C = self.mesh.edgeCurl
iomega = 1j * omega(freq) * sp.eye(self.mesh.nF)
A = C * MeMuI * C.T * MfRho + iomega
if self._makeASymmetric is True:
return MfRho.T*A
return A
def getADeriv_m(self, freq, u, v, adjoint=False):
"""
In this case, we assume that electrical conductivity, \\\(\\\sigma\\\) is the physical property of interest (i.e. \\\(\\\sigma\\\) = model.transform). Then we want
.. math ::
\\frac{\mathbf{A(\sigma)} \mathbf{v}}{d \\mathbf{m}} &= \\mathbf{C} \\mathbf{M^e_{mu^{-1}}} \\mathbf{C^T} \\frac{d \\mathbf{M^f_{\\sigma^{-1}}}}{d \\mathbf{m}}
&= \\mathbf{C} \\mathbf{M^e_{mu}^{-1}} \\mathbf{C^T} \\frac{d \\mathbf{M^f_{\\sigma^{-1}}}}{d \\mathbf{\\sigma^{-1}}} \\frac{d \\mathbf{\\sigma^{-1}}}{d \\mathbf{\\sigma}} \\frac{d \\mathbf{\\sigma}}{d \\mathbf{m}}
"""
MeMuI = self.MeMuI
MfRho = self.MfRho
C = self.mesh.edgeCurl
MfRhoDeriv_m = self.MfRhoDeriv(u)
if adjoint:
if self._makeASymmetric is True:
v = MfRho * v
return MfRhoDeriv_m.T * (C * (MeMuI.T * (C.T * v)))
if self._makeASymmetric is True:
return MfRho.T * (C * ( MeMuI * (C.T * (MfRhoDeriv_m * v) )))
return C * (MeMuI * (C.T * (MfRhoDeriv_m * v)))
def getRHS(self, freq):
"""
.. math ::
\mathbf{RHS} = \mathbf{C} \mathbf{M_{\mu}^e}^{-1}\mathbf{s_m} -i\omega \mathbf{s_e}
:param float freq: Frequency
:rtype: numpy.ndarray (nE, nSrc)
:return: RHS
"""
S_m, S_e = self.getSourceTerm(freq)
C = self.mesh.edgeCurl
MeMuI = self.MeMuI
RHS = C * (MeMuI * S_m) - 1j * omega(freq) * S_e
if self._makeASymmetric is True:
MfRho = self.MfRho
return MfRho.T*RHS
return RHS
def getRHSDeriv_m(self, freq, src, v, adjoint=False):
C = self.mesh.edgeCurl
MeMuI = self.MeMuI
S_mDeriv, S_eDeriv = src.evalDeriv(self, adjoint)
if adjoint:
if self._makeASymmetric:
MfRho = self.MfRho
v = MfRho*v
return S_mDeriv(MeMuI.T * (C.T * v)) - 1j * omega(freq) * S_eDeriv(v)
else:
RHSDeriv = C * (MeMuI * S_mDeriv(v)) - 1j * omega(freq) * S_eDeriv(v)
if self._makeASymmetric:
MfRho = self.MfRho
return MfRho.T * RHSDeriv
return RHSDeriv
class Problem_h(BaseFDEMProblem):
"""
We eliminate \\\(\\\mathbf{j}\\\) using
.. math ::
\mathbf{j} = \mathbf{C} \mathbf{h} - \mathbf{s_e}
and solve for \\\(\\\mathbf{h}\\\) using
.. math ::
\\left(\mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e}\\right) \mathbf{h} = \mathbf{M^e} \mathbf{s_m} + \mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{s_e}
"""
_fieldType = 'h'
_eqLocs = 'EF'
fieldsPair = Fields_h
def __init__(self, mesh, **kwargs):
BaseFDEMProblem.__init__(self, mesh, **kwargs)
def getA(self, freq):
"""
.. math ::
\mathbf{A} = \mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{C} + i \omega \mathbf{M_{\mu}^e}
:param float freq: Frequency
:rtype: scipy.sparse.csr_matrix
:return: A
"""
MeMu = self.MeMu
MfRho = self.MfRho
C = self.mesh.edgeCurl
return C.T * (MfRho * C) + 1j*omega(freq)*MeMu
def getADeriv_m(self, freq, u, v, adjoint=False):
MeMu = self.MeMu
C = self.mesh.edgeCurl
MfRhoDeriv_m = self.MfRhoDeriv(C*u)
if adjoint:
return MfRhoDeriv_m.T * (C * v)
return C.T * (MfRhoDeriv_m * v)
def getRHS(self, freq):
"""
.. math ::
\mathbf{RHS} = \mathbf{M^e} \mathbf{s_m} + \mathbf{C}^T \mathbf{M_{\\rho}^f} \mathbf{s_e}
:param float freq: Frequency
:rtype: numpy.ndarray (nE, nSrc)
:return: RHS
"""
S_m, S_e = self.getSourceTerm(freq)
C = self.mesh.edgeCurl
MfRho = self.MfRho
RHS = S_m + C.T * ( MfRho * S_e )
return RHS
def getRHSDeriv_m(self, freq, src, v, adjoint=False):
_, S_e = src.eval(self)
C = self.mesh.edgeCurl
MfRho = self.MfRho
MfRhoDeriv = self.MfRhoDeriv(S_e)
if not adjoint:
RHSDeriv = C.T * (MfRhoDeriv * v)
elif adjoint:
RHSDeriv = MfRhoDeriv.T * (C * v)
S_mDeriv, S_eDeriv = src.evalDeriv(self, adjoint)
return RHSDeriv + S_mDeriv(v) + C.T * (MfRho * S_eDeriv(v))
+358
View File
@@ -0,0 +1,358 @@
import numpy as np
import scipy.sparse as sp
import SimPEG
from SimPEG import Utils
from SimPEG.EM.Utils import omega
from SimPEG.Utils import Zero, Identity
class Fields(SimPEG.Problem.Fields):
"""Fancy Field Storage for a FDEM survey."""
knownFields = {}
dtype = complex
class Fields_e(Fields):
knownFields = {'eSolution':'E'}
aliasFields = {
'e' : ['eSolution','E','_e'],
'ePrimary' : ['eSolution','E','_ePrimary'],
'eSecondary' : ['eSolution','E','_eSecondary'],
'b' : ['eSolution','F','_b'],
'bPrimary' : ['eSolution','F','_bPrimary'],
'bSecondary' : ['eSolution','F','_bSecondary']
}
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self):
self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl
def _ePrimary(self, eSolution, srcList):
ePrimary = np.zeros_like(eSolution)
for i, src in enumerate(srcList):
ep = src.ePrimary(self.prob)
ePrimary[:,i] = ePrimary[:,i] + ep
return ePrimary
def _eSecondary(self, eSolution, srcList):
return eSolution
def _e(self, eSolution, srcList):
return self._ePrimary(eSolution,srcList) + self._eSecondary(eSolution,srcList)
def _eDeriv_u(self, src, v, adjoint = False):
return Identity()*v
def _eDeriv_m(self, src, v, adjoint = False):
# assuming primary does not depend on the model
return Zero()
def _bPrimary(self, eSolution, srcList):
bPrimary = np.zeros([self._edgeCurl.shape[0],eSolution.shape[1]],dtype = complex)
for i, src in enumerate(srcList):
bp = src.bPrimary(self.prob)
bPrimary[:,i] = bPrimary[:,i] + bp
return bPrimary
def _bSecondary(self, eSolution, srcList):
C = self._edgeCurl
b = (C * eSolution)
for i, src in enumerate(srcList):
b[:,i] *= - 1./(1j*omega(src.freq))
S_m, _ = src.eval(self.prob)
b[:,i] = b[:,i]+ 1./(1j*omega(src.freq)) * S_m
return b
def _bSecondaryDeriv_u(self, src, v, adjoint = False):
C = self._edgeCurl
if adjoint:
return - 1./(1j*omega(src.freq)) * (C.T * v)
return - 1./(1j*omega(src.freq)) * (C * v)
def _bSecondaryDeriv_m(self, src, v, adjoint = False):
S_mDeriv, _ = src.evalDeriv(self.prob, adjoint)
S_mDeriv = S_mDeriv(v)
return 1./(1j * omega(src.freq)) * S_mDeriv
def _b(self, eSolution, srcList):
return self._bPrimary(eSolution, srcList) + self._bSecondary(eSolution, srcList)
def _bDeriv_u(self, src, v, adjoint=False):
# Primary does not depend on u
return self._bSecondaryDeriv_u(src, v, adjoint)
def _bDeriv_m(self, src, v, adjoint=False):
# Assuming the primary does not depend on the model
return self._bSecondaryDeriv_m(src, v, adjoint)
class Fields_b(Fields):
knownFields = {'bSolution':'F'}
aliasFields = {
'b' : ['bSolution','F','_b'],
'bPrimary' : ['bSolution','F','_bPrimary'],
'bSecondary' : ['bSolution','F','_bSecondary'],
'e' : ['bSolution','E','_e'],
'ePrimary' : ['bSolution','E','_ePrimary'],
'eSecondary' : ['bSolution','E','_eSecondary'],
}
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self):
self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl
self._MeSigmaI = self.survey.prob.MeSigmaI
self._MfMui = self.survey.prob.MfMui
self._MeSigmaIDeriv = self.survey.prob.MeSigmaIDeriv
self._Me = self.survey.prob.Me
def _bPrimary(self, bSolution, srcList):
bPrimary = np.zeros_like(bSolution)
for i, src in enumerate(srcList):
bp = src.bPrimary(self.prob)
bPrimary[:,i] = bPrimary[:,i] + bp
return bPrimary
def _bSecondary(self, bSolution, srcList):
return bSolution
def _b(self, bSolution, srcList):
return self._bPrimary(bSolution, srcList) + self._bSecondary(bSolution, srcList)
def _bDeriv_u(self, src, v, adjoint=False):
return Identity()*v
def _bDeriv_m(self, src, v, adjoint=False):
# assuming primary does not depend on the model
return Zero()
def _ePrimary(self, bSolution, srcList):
ePrimary = np.zeros([self._edgeCurl.shape[1],bSolution.shape[1]],dtype = complex)
for i,src in enumerate(srcList):
ep = src.ePrimary(self.prob)
ePrimary[:,i] = ePrimary[:,i] + ep
return ePrimary
def _eSecondary(self, bSolution, srcList):
e = self._MeSigmaI * ( self._edgeCurl.T * ( self._MfMui * bSolution))
for i,src in enumerate(srcList):
_,S_e = src.eval(self.prob)
e[:,i] = e[:,i]+ -self._MeSigmaI * S_e
return e
def _eSecondaryDeriv_u(self, src, v, adjoint=False):
if not adjoint:
return self._MeSigmaI * ( self._edgeCurl.T * ( self._MfMui * v) )
else:
return self._MfMui.T * (self._edgeCurl * (self._MeSigmaI.T * v))
def _eSecondaryDeriv_m(self, src, v, adjoint=False):
bSolution = self[[src],'bSolution']
_,S_e = src.eval(self.prob)
Me = self._Me
if adjoint:
Me = Me.T
w = self._edgeCurl.T * (self._MfMui * bSolution)
w = w - Utils.mkvc(Me * S_e,2)
if not adjoint:
de_dm = self._MeSigmaIDeriv(w) * v
elif adjoint:
de_dm = self._MeSigmaIDeriv(w).T * v
_, S_eDeriv = src.evalDeriv(self.prob, adjoint)
Se_Deriv = S_eDeriv(v)
de_dm = de_dm - self._MeSigmaI * Se_Deriv
return de_dm
def _e(self, bSolution, srcList):
return self._ePrimary(bSolution, srcList) + self._eSecondary(bSolution, srcList)
def _eDeriv_u(self, src, v, adjoint=False):
return self._eSecondaryDeriv_u(src, v, adjoint)
def _eDeriv_m(self, src, v, adjoint=False):
# assuming primary doesn't depend on model
return self._eSecondaryDeriv_m(src, v, adjoint)
class Fields_j(Fields):
knownFields = {'jSolution':'F'}
aliasFields = {
'j' : ['jSolution','F','_j'],
'jPrimary' : ['jSolution','F','_jPrimary'],
'jSecondary' : ['jSolution','F','_jSecondary'],
'h' : ['jSolution','E','_h'],
'hPrimary' : ['jSolution','E','_hPrimary'],
'hSecondary' : ['jSolution','E','_hSecondary'],
}
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self):
self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl
self._MeMuI = self.survey.prob.MeMuI
self._MfRho = self.survey.prob.MfRho
self._MfRhoDeriv = self.survey.prob.MfRhoDeriv
self._Me = self.survey.prob.Me
def _jPrimary(self, jSolution, srcList):
jPrimary = np.zeros_like(jSolution,dtype = complex)
for i, src in enumerate(srcList):
jp = src.jPrimary(self.prob)
jPrimary[:,i] = jPrimary[:,i] + jp
return jPrimary
def _jSecondary(self, jSolution, srcList):
return jSolution
def _j(self, jSolution, srcList):
return self._jPrimary(jSolution, srcList) + self._jSecondary(jSolution, srcList)
def _jDeriv_u(self, src, v, adjoint=False):
return Identity()*v
def _jDeriv_m(self, src, v, adjoint=False):
# assuming primary does not depend on the model
return Zero()
def _hPrimary(self, jSolution, srcList):
hPrimary = np.zeros([self._edgeCurl.shape[1],jSolution.shape[1]],dtype = complex)
for i, src in enumerate(srcList):
hp = src.hPrimary(self.prob)
hPrimary[:,i] = hPrimary[:,i] + hp
return hPrimary
def _hSecondary(self, jSolution, srcList):
h = self._MeMuI * (self._edgeCurl.T * (self._MfRho * jSolution) )
for i, src in enumerate(srcList):
h[:,i] *= -1./(1j*omega(src.freq))
S_m,_ = src.eval(self.prob)
h[:,i] = h[:,i]+ 1./(1j*omega(src.freq)) * self._MeMuI * (S_m)
return h
def _hSecondaryDeriv_u(self, src, v, adjoint=False):
if not adjoint:
return -1./(1j*omega(src.freq)) * self._MeMuI * (self._edgeCurl.T * (self._MfRho * v) )
elif adjoint:
return -1./(1j*omega(src.freq)) * self._MfRho.T * (self._edgeCurl * ( self._MeMuI.T * v))
def _hSecondaryDeriv_m(self, src, v, adjoint=False):
jSolution = self[[src],'jSolution']
MeMuI = self._MeMuI
C = self._edgeCurl
MfRho = self._MfRho
MfRhoDeriv = self._MfRhoDeriv
Me = self._Me
if not adjoint:
hDeriv_m = -1./(1j*omega(src.freq)) * MeMuI * (C.T * (MfRhoDeriv(jSolution)*v ) )
elif adjoint:
hDeriv_m = -1./(1j*omega(src.freq)) * MfRhoDeriv(jSolution).T * ( C * (MeMuI.T * v ) )
S_mDeriv,_ = src.evalDeriv(self.prob, adjoint)
if not adjoint:
S_mDeriv = S_mDeriv(v)
hDeriv_m = hDeriv_m + 1./(1j*omega(src.freq)) * MeMuI * (Me * S_mDeriv)
elif adjoint:
S_mDeriv = S_mDeriv(Me.T * (MeMuI.T * v))
hDeriv_m = hDeriv_m + 1./(1j*omega(src.freq)) * S_mDeriv
return hDeriv_m
def _h(self, jSolution, srcList):
return self._hPrimary(jSolution, srcList) + self._hSecondary(jSolution, srcList)
def _hDeriv_u(self, src, v, adjoint=False):
return self._hSecondaryDeriv_u(src, v, adjoint)
def _hDeriv_m(self, src, v, adjoint=False):
# assuming the primary doesn't depend on the model
return self._hSecondaryDeriv_m(src, v, adjoint)
class Fields_h(Fields):
knownFields = {'hSolution':'E'}
aliasFields = {
'h' : ['hSolution','E','_h'],
'hPrimary' : ['hSolution','E','_hPrimary'],
'hSecondary' : ['hSolution','E','_hSecondary'],
'j' : ['hSolution','F','_j'],
'jPrimary' : ['hSolution','F','_jPrimary'],
'jSecondary' : ['hSolution','F','_jSecondary']
}
def __init__(self,mesh,survey,**kwargs):
Fields.__init__(self,mesh,survey,**kwargs)
def startup(self):
self.prob = self.survey.prob
self._edgeCurl = self.survey.prob.mesh.edgeCurl
self._MeMuI = self.survey.prob.MeMuI
self._MfRho = self.survey.prob.MfRho
def _hPrimary(self, hSolution, srcList):
hPrimary = np.zeros_like(hSolution,dtype = complex)
for i, src in enumerate(srcList):
hp = src.hPrimary(self.prob)
hPrimary[:,i] = hPrimary[:,i] + hp
return hPrimary
def _hSecondary(self, hSolution, srcList):
return hSolution
def _h(self, hSolution, srcList):
return self._hPrimary(hSolution, srcList) + self._hSecondary(hSolution, srcList)
def _hDeriv_u(self, src, v, adjoint=False):
return Identity()*v
def _hDeriv_m(self, src, v, adjoint=False):
# assuming primary does not depend on the model
return Zero()
def _jPrimary(self, hSolution, srcList):
jPrimary = np.zeros([self._edgeCurl.shape[0], hSolution.shape[1]], dtype = complex)
for i, src in enumerate(srcList):
jp = src.jPrimary(self.prob)
jPrimary[:,i] = jPrimary[:,i] + jp
return jPrimary
def _jSecondary(self, hSolution, srcList):
j = self._edgeCurl*hSolution
for i, src in enumerate(srcList):
_,S_e = src.eval(self.prob)
j[:,i] = j[:,i]+ -S_e
return j
def _jSecondaryDeriv_u(self, src, v, adjoint=False):
if not adjoint:
return self._edgeCurl*v
elif adjoint:
return self._edgeCurl.T*v
def _jSecondaryDeriv_m(self, src, v, adjoint=False):
_,S_eDeriv = src.evalDeriv(self.prob, adjoint)
S_eDeriv = S_eDeriv(v)
return -S_eDeriv
def _j(self, hSolution, srcList):
return self._jPrimary(hSolution, srcList) + self._jSecondary(hSolution, srcList)
def _jDeriv_u(self, src, v, adjoint=False):
return self._jSecondaryDeriv_u(src,v,adjoint)
def _jDeriv_m(self, src, v, adjoint=False):
# assuming the primary does not depend on the model
return self._jSecondaryDeriv_m(src,v,adjoint)
+316
View File
@@ -0,0 +1,316 @@
from SimPEG import Survey, Problem, Utils, np, sp
from scipy.constants import mu_0
from SimPEG.EM.Utils import *
from SimPEG.Utils import Zero
# from SurveyFDEM import Rx
class BaseSrc(Survey.BaseSrc):
freq = None
# rxPair = Rx
integrate = True
def eval(self, prob):
S_m = self.S_m(prob)
S_e = self.S_e(prob)
return S_m, S_e
def evalDeriv(self, prob, v, adjoint=False):
return lambda v: self.S_mDeriv(prob,v,adjoint), lambda v: self.S_eDeriv(prob,v,adjoint)
def bPrimary(self, prob):
return Zero()
def hPrimary(self, prob):
return Zero()
def ePrimary(self, prob):
return Zero()
def jPrimary(self, prob):
return Zero()
def S_m(self, prob):
return Zero()
def S_e(self, prob):
return Zero()
def S_mDeriv(self, prob, v, adjoint = False):
return Zero()
def S_eDeriv(self, prob, v, adjoint = False):
return Zero()
class RawVec_e(BaseSrc):
"""
RawVec electric source. It is defined by the user provided vector S_e
:param numpy.array S_e: electric source term
:param float freq: frequency
:param rxList: receiver list
"""
def __init__(self, rxList, freq, S_e): #, ePrimary=None, bPrimary=None, hPrimary=None, jPrimary=None):
self._S_e = np.array(S_e,dtype=complex)
self.freq = float(freq)
BaseSrc.__init__(self, rxList)
def S_e(self, prob):
return self._S_e
class RawVec_m(BaseSrc):
"""
RawVec magnetic source. It is defined by the user provided vector S_m
:param numpy.array S_m: magnetic source term
:param float freq: frequency
:param rxList: receiver list
"""
def __init__(self, rxList, freq, S_m, integrate = True): #ePrimary=Zero(), bPrimary=Zero(), hPrimary=Zero(), jPrimary=Zero()):
self._S_m = np.array(S_m,dtype=complex)
self.freq = float(freq)
self.integrate = integrate
BaseSrc.__init__(self, rxList)
def S_m(self, prob):
return self._S_m
class RawVec(BaseSrc):
"""
RawVec source. It is defined by the user provided vectors S_m, S_e
:param numpy.array S_m: magnetic source term
:param numpy.array S_e: electric source term
:param float freq: frequency
:param rxList: receiver list
"""
def __init__(self, rxList, freq, S_m, S_e, integrate = True):
self._S_m = np.array(S_m,dtype=complex)
self._S_e = np.array(S_e,dtype=complex)
self.freq = float(freq)
self.integrate = integrate
BaseSrc.__init__(self, rxList)
def S_m(self, prob):
if prob._eqLocs is 'EF' and self.integrate is True:
return prob.Me * self._S_m
return self._S_m
def S_e(self, prob):
if prob._eqLocs is 'FE' and self.integrate is True:
return prob.Me * self._S_e
return self._S_e
class MagDipole(BaseSrc):
#TODO: right now, orientation doesn't actually do anything! The methods in SrcUtils should take care of that
def __init__(self, rxList, freq, loc, orientation='Z', moment=1., mu = mu_0):
self.freq = float(freq)
self.loc = loc
self.orientation = orientation
self.moment = moment
self.mu = mu
self.integrate = False
BaseSrc.__init__(self, rxList)
def bPrimary(self, prob):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
gridX = prob.mesh.gridEx
gridY = prob.mesh.gridEy
gridZ = prob.mesh.gridEz
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
gridX = prob.mesh.gridFx
gridY = prob.mesh.gridFy
gridZ = prob.mesh.gridFz
C = prob.mesh.edgeCurl.T
if prob.mesh._meshType is 'CYL':
if not prob.mesh.isSymmetric:
# TODO ?
raise NotImplementedError('Non-symmetric cyl mesh not implemented yet!')
a = MagneticDipoleVectorPotential(self.loc, gridY, 'y', mu=self.mu, moment=self.moment)
else:
srcfct = MagneticDipoleVectorPotential
ax = srcfct(self.loc, gridX, 'x', mu=self.mu, moment=self.moment)
ay = srcfct(self.loc, gridY, 'y', mu=self.mu, moment=self.moment)
az = srcfct(self.loc, gridZ, 'z', mu=self.mu, moment=self.moment)
a = np.concatenate((ax, ay, az))
return C*a
def hPrimary(self, prob):
b = self.bPrimary(prob)
return h_from_b(prob,b)
def S_m(self, prob):
b_p = self.bPrimary(prob)
return -1j*omega(self.freq)*b_p
def S_e(self, prob):
if all(np.r_[self.mu] == np.r_[prob.curModel.mu]):
return Zero()
else:
eqLocs = prob._eqLocs
if eqLocs is 'FE':
mui_s = prob.curModel.mui - 1./self.mu
MMui_s = prob.mesh.getFaceInnerProduct(mui_s)
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
mu_s = prob.curModel.mu - self.mu
MMui_s = prob.mesh.getEdgeInnerProduct(mu_s,invMat=True)
C = prob.mesh.edgeCurl.T
return -C.T * (MMui_s * self.bPrimary(prob))
class MagDipole_Bfield(BaseSrc):
#TODO: right now, orientation doesn't actually do anything! The methods in SrcUtils should take care of that
#TODO: neither does moment
def __init__(self, rxList, freq, loc, orientation='Z', moment=1., mu = mu_0):
self.freq = float(freq)
self.loc = loc
self.orientation = orientation
self.moment = moment
self.mu = mu
BaseSrc.__init__(self, rxList)
def bPrimary(self, prob):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
gridX = prob.mesh.gridFx
gridY = prob.mesh.gridFy
gridZ = prob.mesh.gridFz
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
gridX = prob.mesh.gridEx
gridY = prob.mesh.gridEy
gridZ = prob.mesh.gridEz
C = prob.mesh.edgeCurl.T
srcfct = MagneticDipoleFields
if prob.mesh._meshType is 'CYL':
if not prob.mesh.isSymmetric:
# TODO ?
raise NotImplementedError('Non-symmetric cyl mesh not implemented yet!')
bx = srcfct(self.loc, gridX, 'x', mu=self.mu, moment=self.moment)
bz = srcfct(self.loc, gridZ, 'z', mu=self.mu, moment=self.moment)
b = np.concatenate((bx,bz))
else:
bx = srcfct(self.loc, gridX, 'x', mu=self.mu, moment=self.moment)
by = srcfct(self.loc, gridY, 'y', mu=self.mu, moment=self.moment)
bz = srcfct(self.loc, gridZ, 'z', mu=self.mu, moment=self.moment)
b = np.concatenate((bx,by,bz))
return b
def hPrimary(self, prob):
b = self.bPrimary(prob)
return h_from_b(prob, b)
def S_m(self, prob):
b = self.bPrimary(prob)
return -1j*omega(self.freq)*b
def S_e(self, prob):
if all(np.r_[self.mu] == np.r_[prob.curModel.mu]):
return Zero()
else:
eqLocs = prob._eqLocs
if eqLocs is 'FE':
mui_s = prob.curModel.mui - 1./self.mu
MMui_s = prob.mesh.getFaceInnerProduct(mui_s)
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
mu_s = prob.curModel.mu - self.mu
MMui_s = prob.mesh.getEdgeInnerProduct(mu_s,invMat=True)
C = prob.mesh.edgeCurl.T
return -C.T * (MMui_s * self.bPrimary(prob))
class CircularLoop(BaseSrc):
#TODO: right now, orientation doesn't actually do anything! The methods in SrcUtils should take care of that
def __init__(self, rxList, freq, loc, orientation='Z', radius = 1., mu=mu_0):
self.freq = float(freq)
self.orientation = orientation
self.radius = radius
self.mu = mu
self.loc = loc
self.integrate = False
BaseSrc.__init__(self, rxList)
def bPrimary(self, prob):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
gridX = prob.mesh.gridEx
gridY = prob.mesh.gridEy
gridZ = prob.mesh.gridEz
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
gridX = prob.mesh.gridFx
gridY = prob.mesh.gridFy
gridZ = prob.mesh.gridFz
C = prob.mesh.edgeCurl.T
if prob.mesh._meshType is 'CYL':
if not prob.mesh.isSymmetric:
# TODO ?
raise NotImplementedError('Non-symmetric cyl mesh not implemented yet!')
a = MagneticDipoleVectorPotential(self.loc, gridY, 'y', moment=self.radius, mu=self.mu)
else:
srcfct = MagneticDipoleVectorPotential
ax = srcfct(self.loc, gridX, 'x', 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)
a = np.concatenate((ax, ay, az))
return C*a
def hPrimary(self, prob):
b = self.bPrimary(prob)
return 1./self.mu*b
def S_m(self, prob):
b = self.bPrimary(prob)
return -1j*omega(self.freq)*b
def S_e(self, prob):
if all(np.r_[self.mu] == np.r_[prob.curModel.mu]):
return Zero()
else:
eqLocs = prob._eqLocs
if eqLocs is 'FE':
mui_s = prob.curModel.mui - 1./self.mu
MMui_s = prob.mesh.getFaceInnerProduct(mui_s)
C = prob.mesh.edgeCurl
elif eqLocs is 'EF':
mu_s = prob.curModel.mu - self.mu
MMui_s = prob.mesh.getEdgeInnerProduct(mu_s,invMat=True)
C = prob.mesh.edgeCurl.T
return -C.T * (MMui_s * self.bPrimary(prob))
+148
View File
@@ -0,0 +1,148 @@
import SimPEG
from SimPEG.EM.Utils import *
from scipy.constants import mu_0
from SimPEG.Utils import Zero, Identity
import SrcFDEM as Src
####################################################
# Receivers
####################################################
class Rx(SimPEG.Survey.BaseRx):
knownRxTypes = {
'exr':['e', 'Ex', 'real'],
'eyr':['e', 'Ey', 'real'],
'ezr':['e', 'Ez', 'real'],
'exi':['e', 'Ex', 'imag'],
'eyi':['e', 'Ey', 'imag'],
'ezi':['e', 'Ez', 'imag'],
'bxr':['b', 'Fx', 'real'],
'byr':['b', 'Fy', 'real'],
'bzr':['b', 'Fz', 'real'],
'bxi':['b', 'Fx', 'imag'],
'byi':['b', 'Fy', 'imag'],
'bzi':['b', 'Fz', 'imag'],
'jxr':['j', 'Fx', 'real'],
'jyr':['j', 'Fy', 'real'],
'jzr':['j', 'Fz', 'real'],
'jxi':['j', 'Fx', 'imag'],
'jyi':['j', 'Fy', 'imag'],
'jzi':['j', 'Fz', 'imag'],
'hxr':['h', 'Ex', 'real'],
'hyr':['h', 'Ey', 'real'],
'hzr':['h', 'Ez', 'real'],
'hxi':['h', 'Ex', 'imag'],
'hyi':['h', 'Ey', 'imag'],
'hzi':['h', 'Ez', 'imag'],
}
radius = None
def __init__(self, locs, rxType):
SimPEG.Survey.BaseRx.__init__(self, locs, rxType)
@property
def projField(self):
"""Field Type projection (e.g. e b ...)"""
return self.knownRxTypes[self.rxType][0]
@property
def projGLoc(self):
"""Grid Location projection (e.g. Ex Fy ...)"""
return self.knownRxTypes[self.rxType][1]
@property
def projComp(self):
"""Component projection (real/imag)"""
return self.knownRxTypes[self.rxType][2]
def projectFields(self, src, mesh, u):
P = self.getP(mesh)
u_part_complex = u[src, self.projField]
# get the real or imag component
real_or_imag = self.projComp
u_part = getattr(u_part_complex, real_or_imag)
return P*u_part
def projectFieldsDeriv(self, src, mesh, u, v, adjoint=False):
P = self.getP(mesh)
if not adjoint:
Pv_complex = P * v
real_or_imag = self.projComp
Pv = getattr(Pv_complex, real_or_imag)
elif adjoint:
Pv_real = P.T * v
real_or_imag = self.projComp
if real_or_imag == 'imag':
Pv = 1j*Pv_real
elif real_or_imag == 'real':
Pv = Pv_real.astype(complex)
else:
raise NotImplementedError('must be real or imag')
return Pv
####################################################
# Survey
####################################################
class Survey(SimPEG.Survey.BaseSurvey):
"""
docstring for SurveyFDEM
"""
srcPair = Src.BaseSrc
def __init__(self, srcList, **kwargs):
# Sort these by frequency
self.srcList = srcList
SimPEG.Survey.BaseSurvey.__init__(self, **kwargs)
_freqDict = {}
for src in srcList:
if src.freq not in _freqDict:
_freqDict[src.freq] = []
_freqDict[src.freq] += [src]
self._freqDict = _freqDict
self._freqs = sorted([f for f in self._freqDict])
@property
def freqs(self):
"""Frequencies"""
return self._freqs
@property
def nFreq(self):
"""Number of frequencies"""
return len(self._freqDict)
@property
def nSrcByFreq(self):
if getattr(self, '_nSrcByFreq', None) is None:
self._nSrcByFreq = {}
for freq in self.freqs:
self._nSrcByFreq[freq] = len(self.getSrcByFreq(freq))
return self._nSrcByFreq
def getSrcByFreq(self, freq):
"""Returns the sources associated with a specific frequency."""
assert freq in self._freqDict, "The requested frequency is not in this survey."
return self._freqDict[freq]
def projectFields(self, u):
data = SimPEG.Survey.Data(self)
for src in self.srcList:
for rx in src.rxList:
data[src, rx] = rx.projectFields(src, self.mesh, u)
return data
def projectFieldsDeriv(self, u):
raise Exception('Use Sources to project fields deriv.')
+3
View File
@@ -0,0 +1,3 @@
from SurveyFDEM import Rx, Src, Survey
from FDEM import BaseFDEMProblem, Problem_e, Problem_b, Problem_j, Problem_h
from FieldsFDEM import *
+155
View File
@@ -0,0 +1,155 @@
from SimPEG import Solver, Problem
from SimPEG.Problem import BaseTimeProblem
from SimPEG.EM.Utils import *
from scipy.constants import mu_0
from SimPEG.Utils import sdiag, mkvc
from SimPEG import Utils, Mesh
from SimPEG.EM.Base import BaseEMProblem
import numpy as np
class FieldsTDEM(Problem.TimeFields):
"""Fancy Field Storage for a TDEM survey."""
knownFields = {'b': 'F', 'e': 'E'}
def tovec(self):
nSrc, nF, nE = self.survey.nSrc, self.mesh.nF, self.mesh.nE
u = np.empty((0,nSrc)) #((0,1) if nSrc == 1 else (0, nSrc))
for i in range(self.survey.prob.nT):
if 'b' in self:
b = self[:,'b',i+1]
else:
b = np.zeros((nF,nSrc)) # if nSrc == 1 else (nF, nSrc))
if 'e' in self:
e = self[:,'e',i+1]
else:
e = np.zeros((nE,nSrc)) # if nSrc == 1 else (nE, nSrc))
u = np.concatenate((u, b, e))
return Utils.mkvc(u,nSrc)
class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem):
"""docstring for ProblemTDEM1D"""
def __init__(self, mesh, mapping=None, **kwargs):
BaseTimeProblem.__init__(self, mesh, mapping=mapping, **kwargs)
_FieldsForward_pair = FieldsTDEM #: used for the forward calculation only
def fields(self, m):
if self.verbose: print '%s\nCalculating fields(m)\n%s'%('*'*50,'*'*50)
self.curModel = m
# Create a fields storage object
F = self._FieldsForward_pair(self.mesh, self.survey)
for src in self.survey.srcList:
# Set the initial conditions
F[src,:,0] = src.getInitialFields(self.mesh)
F = self.forward(m, self.getRHS, F=F)
if self.verbose: print '%s\nDone calculating fields(m)\n%s'%('*'*50,'*'*50)
return F
def forward(self, m, RHS, F=None):
self.curModel = m
F = F or FieldsTDEM(self.mesh, self.survey)
dtFact = None
Ainv = None
for tInd, dt in enumerate(self.timeSteps):
if dt != dtFact:
dtFact = dt
if Ainv is not None:
Ainv.clean()
A = self.getA(tInd)
if self.verbose: print 'Factoring... (dt = %e)'%dt
Ainv = self.Solver(A, **self.solverOpts)
if self.verbose: print 'Done'
rhs = RHS(tInd, F)
if self.verbose: print ' Solving... (tInd = %d)'%tInd
sol = Ainv * rhs
if self.verbose: print ' Done...'
if sol.ndim == 1:
sol.shape = (sol.size,1)
F[:,self.solType,tInd+1] = sol
Ainv.clean()
return F
def adjoint(self, m, RHS, F=None):
self.curModel = m
F = F or FieldsTDEM(self.mesh, self.survey)
dtFact = None
Ainv = None
for tInd, dt in reversed(list(enumerate(self.timeSteps))):
if dt != dtFact:
dtFact = dt
if Ainv is not None:
Ainv.clean()
A = self.getA(tInd)
if self.verbose: print 'Factoring (Adjoint)... (dt = %e)'%dt
Ainv = self.Solver(A, **self.solverOpts)
if self.verbose: print 'Done'
rhs = RHS(tInd, F)
if self.verbose: print ' Solving (Adjoint)... (tInd = %d)'%tInd
sol = Ainv * rhs
if self.verbose: print ' Done...'
if sol.ndim == 1:
sol.shape = (sol.size,1)
F[:,self.solType,tInd+1] = sol
Ainv.clean()
return F
def Jvec(self, m, v, u=None):
"""
:param numpy.array m: Conductivity model
:param numpy.ndarray v: vector (model object)
:param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: numpy.ndarray
:return: w (data object)
Multiplying \\\(\\\mathbf{J}\\\) onto a vector can be broken into three steps
* Compute \\\(\\\\vec{p} = \\\mathbf{G}v\\\)
* Solve \\\(\\\hat{\\\mathbf{A}} \\\\vec{y} = \\\\vec{p}\\\)
* Compute \\\(\\\\vec{w} = -\\\mathbf{Q} \\\\vec{y}\\\)
"""
if self.verbose: print '%s\nCalculating J(v)\n%s'%('*'*50,'*'*50)
self.curModel = m
if u is None:
u = self.fields(m)
p = self.Gvec(m, v, u)
y = self.solveAh(m, p)
Jv = self.survey.projectFieldsDeriv(u, v=y)
if self.verbose: print '%s\nDone calculating J(v)\n%s'%('*'*50,'*'*50)
return - mkvc(Jv)
def Jtvec(self, m, v, u=None):
"""
:param numpy.array m: Conductivity model
:param numpy.ndarray,SimPEG.Survey.Data v: vector (data object)
:param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: numpy.ndarray
:return: w (model object)
Multiplying \\\(\\\mathbf{J}^\\\\top\\\) onto a vector can be broken into three steps
* Compute \\\(\\\\vec{p} = \\\mathbf{Q}^\\\\top \\\\vec{v}\\\)
* Solve \\\(\\\hat{\\\mathbf{A}}^\\\\top \\\\vec{y} = \\\\vec{p}\\\)
* Compute \\\(\\\\vec{w} = -\\\mathbf{G}^\\\\top y\\\)
"""
if self.verbose: print '%s\nCalculating J^T(v)\n%s'%('*'*50,'*'*50)
self.curModel = m
if u is None:
u = self.fields(m)
if not isinstance(v, self.dataPair):
v = self.dataPair(self.survey, v)
p = self.survey.projectFieldsDeriv(u, v=v, adjoint=True)
y = self.solveAht(m, p)
w = self.Gtvec(m, y, u)
if self.verbose: print '%s\nDone calculating J^T(v)\n%s'%('*'*50,'*'*50)
return - mkvc(w)
+162
View File
@@ -0,0 +1,162 @@
from SimPEG import Utils, Survey, np
from SimPEG.Survey import BaseSurvey
from SimPEG.EM.Utils import *
from BaseTDEM import FieldsTDEM
class RxTDEM(Survey.BaseTimeRx):
knownRxTypes = {
'ex':['e', 'Ex', 'N'],
'ey':['e', 'Ey', 'N'],
'ez':['e', 'Ez', 'N'],
'bx':['b', 'Fx', 'N'],
'by':['b', 'Fy', 'N'],
'bz':['b', 'Fz', 'N'],
'dbxdt':['b', 'Fx', 'CC'],
'dbydt':['b', 'Fy', 'CC'],
'dbzdt':['b', 'Fz', 'CC'],
}
def __init__(self, locs, times, rxType):
Survey.BaseTimeRx.__init__(self, locs, times, rxType)
@property
def projField(self):
"""Field Type projection (e.g. e b ...)"""
return self.knownRxTypes[self.rxType][0]
@property
def projGLoc(self):
"""Grid Location projection (e.g. Ex Fy ...)"""
return self.knownRxTypes[self.rxType][1]
@property
def projTLoc(self):
"""Time Location projection (e.g. CC N)"""
return self.knownRxTypes[self.rxType][2]
def getTimeP(self, timeMesh):
"""
Returns the time projection matrix.
.. note::
This is not stored in memory, but is created on demand.
"""
if self.rxType in ['dbxdt','dbydt','dbzdt']:
return timeMesh.getInterpolationMat(self.times, self.projTLoc)*timeMesh.faceDiv
else:
return timeMesh.getInterpolationMat(self.times, self.projTLoc)
def projectFields(self, src, mesh, timeMesh, u):
P = self.getP(mesh, timeMesh)
u_part = Utils.mkvc(u[src, self.projField, :])
return P*u_part
def projectFieldsDeriv(self, src, mesh, timeMesh, u, v, adjoint=False):
P = self.getP(mesh, timeMesh)
if not adjoint:
return P * Utils.mkvc(v[src, self.projField, :])
elif adjoint:
return P.T * v[src, self]
class SrcTDEM(Survey.BaseSrc):
rxPair = RxTDEM
radius = None
def getInitialFields(self, mesh):
F0 = getattr(self, '_getInitialFields_' + self.srcType)(mesh)
return F0
def getJs(self, mesh, time):
return None
class SrcTDEM_VMD_MVP(SrcTDEM):
def __init__(self,rxList,loc):
self.loc = loc
SrcTDEM.__init__(self,rxList)
def getInitialFields(self, mesh):
"""Vertical magnetic dipole, magnetic vector potential"""
if mesh._meshType is 'CYL':
if mesh.isSymmetric:
MVP = MagneticDipoleVectorPotential(self.loc, mesh, 'Ey')
else:
raise NotImplementedError('Non-symmetric cyl mesh not implemented yet!')
elif mesh._meshType is 'TENSOR':
MVP = MagneticDipoleVectorPotential(self.loc, mesh, ['Ex','Ey','Ez'])
else:
raise Exception('Unknown mesh for VMD')
return {"b": mesh.edgeCurl*MVP}
class SrcTDEM_CircularLoop_MVP(SrcTDEM):
def __init__(self,rxList,loc,radius):
self.loc = loc
self.radius = radius
SrcTDEM.__init__(self,rxList)
def getInitialFields(self, mesh):
"""Circular Loop, magnetic vector potential"""
if mesh._meshType is 'CYL':
if mesh.isSymmetric:
MVP = MagneticLoopVectorPotential(self.loc, mesh, 'Ey', self.radius)
else:
raise NotImplementedError('Non-symmetric cyl mesh not implemented yet!')
elif mesh._meshType is 'TENSOR':
MVP = MagneticLoopVectorPotential(self.loc, mesh, ['Ex','Ey','Ez'], self.radius)
else:
raise Exception('Unknown mesh for CircularLoop')
return {"b": mesh.edgeCurl*MVP}
class SurveyTDEM(Survey.BaseSurvey):
"""
docstring for SurveyTDEM
"""
srcPair = SrcTDEM
def __init__(self, srcList, **kwargs):
# Sort these by frequency
self.srcList = srcList
Survey.BaseSurvey.__init__(self, **kwargs)
def projectFields(self, u):
data = Survey.Data(self)
for src in self.srcList:
for rx in src.rxList:
data[src, rx] = rx.projectFields(src, self.mesh, self.prob.timeMesh, u)
return data
def projectFieldsDeriv(self, u, v=None, adjoint=False):
assert v is not None, 'v to multiply must be provided.'
if not adjoint:
data = Survey.Data(self)
for src in self.srcList:
for rx in src.rxList:
data[src, rx] = rx.projectFieldsDeriv(src, self.mesh, self.prob.timeMesh, u, v)
return data
else:
f = FieldsTDEM(self.mesh, self)
for src in self.srcList:
for rx in src.rxList:
Ptv = rx.projectFieldsDeriv(src, self.mesh, self.prob.timeMesh, u, v, adjoint=True)
Ptv = Ptv.reshape((-1, self.prob.timeMesh.nN), order='F')
if rx.projField not in f: # first time we are projecting
f[src, rx.projField, :] = Ptv
else: # there are already fields, so let's add to them!
f[src, rx.projField, :] += Ptv
return f
+356
View File
@@ -0,0 +1,356 @@
from BaseTDEM import BaseTDEMProblem, FieldsTDEM
from SimPEG.Utils import mkvc, sdiag
import numpy as np
from SurveyTDEM import SurveyTDEM
class FieldsTDEM_e_from_b(FieldsTDEM):
"""Fancy Field Storage for a TDEM survey."""
knownFields = {'b': 'F'}
aliasFields = {'e': ['b','E','e_from_b']}
def startup(self):
self.MeSigmaI = self.survey.prob.MeSigmaI
self.edgeCurlT = self.survey.prob.mesh.edgeCurl.T
self.MfMui = self.survey.prob.MfMui
def e_from_b(self, b, srcInd, timeInd):
# TODO: implement non-zero js
return self.MeSigmaI*(self.edgeCurlT*(self.MfMui*b))
class FieldsTDEM_e_from_b_Ah(FieldsTDEM):
"""Fancy Field Storage for a TDEM survey.
This is used when solving Ahat and AhatT
"""
knownFields = {'b': 'F'}
aliasFields = {'e': ['b','E','e_from_b']}
p = None
def startup(self):
self.MeSigmaI = self.survey.prob.MeSigmaI
self.edgeCurlT = self.survey.prob.mesh.edgeCurl.T
self.MfMui = self.survey.prob.MfMui
def e_from_b(self, y_b, srcInd, tInd):
y_e = self.MeSigmaI*(self.edgeCurlT*(self.MfMui*y_b))
if 'e' in self.p:
y_e = y_e - self.MeSigmaI*self.p[srcInd,'e',tInd]
return y_e
class ProblemTDEM_b(BaseTDEMProblem):
"""
Time-Domain EM problem - B-formulation
TDEM_b treats the following discretization of Maxwell's equations
.. math::
\dcurl \e^{(t+1)} + \\frac{\\b^{(t+1)} - \\b^{(t)}}{\delta t} = 0 \\\\
\dcurl^\\top \MfMui \\b^{(t+1)} - \MeSig \e^{(t+1)} = \Me \j_s^{(t+1)}
with \\\(\\b\\\) defined on cell faces and \\\(\e\\\) defined on edges.
"""
def __init__(self, mesh, mapping=None, **kwargs):
BaseTDEMProblem.__init__(self, mesh, mapping=mapping, **kwargs)
solType = 'b' #: Type of the solution, in this case the 'b' field
surveyPair = SurveyTDEM
_FieldsForward_pair = FieldsTDEM_e_from_b #: used for the forward calculation only
####################################################
# Internal Methods
####################################################
def getA(self, tInd):
"""
:param int tInd: Time index
:rtype: scipy.sparse.csr_matrix
:return: A
"""
dt = self.timeSteps[tInd]
return self.MfMui*self.mesh.edgeCurl*self.MeSigmaI*self.mesh.edgeCurl.T*self.MfMui + (1.0/dt)*self.MfMui
def getRHS(self, tInd, F):
dt = self.timeSteps[tInd]
B_n = np.c_[[F[src,'b',tInd] for src in self.survey.srcList]].T
if B_n.shape[0] is not 1:
raise NotImplementedError('getRHS not implemented for this shape of B_n')
RHS = (1.0/dt)*self.MfMui*B_n[0,:,:] #TODO: This is a hack
return RHS
####################################################
# Derivatives
####################################################
def Gvec(self, m, vec, u=None):
"""
:param numpy.array m: Conductivity model
:param numpy.array vec: vector (like a model)
:param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: simpegEM.TDEM.FieldsTDEM
:return: f
Multiply G by a vector
"""
if u is None:
u = self.fields(m)
self.curModel = m
# Note: Fields has shape (nF/E, nSrc, nT+1)
# However, p will only really fill (:,:,1:nT+1)
# meaning the 'initial fields' are zero (:,:,0)
p = FieldsTDEM(self.mesh, self.survey)
# 'b' at all times is zero.
# However, to save memory we will **not** do:
#
# p[:, 'b', :] = 0.0
# fake initial 'e' fields
p[:, 'e', 0] = 0.0
dMdsig = self.MeSigmaDeriv
# self.mesh.getEdgeInnerProductDeriv(self.curModel.transform)
# dsigdm_x_v = self.curModel.sigmaDeriv*vec
# dsigdm_x_v = self.curModel.transformDeriv*vec
for i in range(1,self.nT+1):
# TODO: G[1] may be dependent on the model
# for a galvanic source (deriv of the dc problem)
#
# Do multiplication for all src in self.survey.srcList
for src in self.survey.srcList:
p[src, 'e', i] = - dMdsig(u[src,'e',i]) * vec
return p
def Gtvec(self, m, vec, u=None):
"""
:param numpy.array m: Conductivity model
:param numpy.array vec: vector (like a fields)
:param simpegEM.TDEM.FieldsTDEM u: Fields resulting from m
:rtype: np.ndarray (like a model)
:return: p
Multiply G.T by a vector
"""
if u is None:
u = self.fields(m)
self.curModel = m
# dMdsig = self.mesh.getEdgeInnerProductDeriv(self.curModel.transform)
# dsigdm = self.curModel.transformDeriv
MeSigmaDeriv = self.MeSigmaDeriv
nSrc = self.survey.nSrc
VUs = None
# Here we can do internal multiplications of Gt*v and then multiply by MsigDeriv.T in one go.
for i in range(1,self.nT+1):
vu = None
for src in self.survey.srcList:
vusrc = MeSigmaDeriv(u[src,'e',i]).T * vec[src,'e',i]
vu = vusrc if vu is None else vu + vusrc
VUs = vu if VUs is None else VUs + vu
# p = -dsigdm.T*VUs
return -VUs
def solveAh(self, m, p):
"""
:param numpy.array m: Conductivity model
:param simpegEM.TDEM.FieldsTDEM p: Fields object
:rtype: simpegEM.TDEM.FieldsTDEM
:return: y
Solve the block-matrix system \\\(\\\hat{A} \\\hat{y} = \\\hat{p}\\\):
.. math::
\mathbf{\hat{A}} = \left[
\\begin{array}{cccc}
A & 0 & & \\\\
B & A & & \\\\
& \ddots & \ddots & \\\\
& & B & A
\end{array}
\\right] \\\\
\mathbf{A} =
\left[
\\begin{array}{cc}
\\frac{1}{\delta t} \MfMui & \MfMui\dcurl \\\\
\dcurl^\\top \MfMui & -\MeSig
\end{array}
\\right] \\\\
\mathbf{B} =
\left[
\\begin{array}{cc}
-\\frac{1}{\delta t} \MfMui & 0 \\\\
0 & 0
\end{array}
\\right] \\\\
"""
def AhRHS(tInd, y):
rhs = self.MfMui*(self.mesh.edgeCurl*(self.MeSigmaI*p[:,'e',tInd+1]))
if 'b' in p:
rhs = rhs + p[:,'b',tInd+1]
if tInd == 0:
return rhs
dt = self.timeSteps[tInd]
return rhs + 1.0/dt*self.MfMui*y[:,'b',tInd]
F = FieldsTDEM_e_from_b_Ah(self.mesh, self.survey, p=p)
return self.forward(m, AhRHS, F)
def solveAht(self, m, p):
"""
:param numpy.array m: Conductivity model
:param simpegEM.TDEM.FieldsTDEM p: Fields object
:rtype: simpegEM.TDEM.FieldsTDEM
:return: y
Solve the block-matrix system \\\(\\\hat{A}^\\\\top \\\hat{y} = \\\hat{p}\\\):
.. math::
\mathbf{\hat{A}}^\\top = \left[
\\begin{array}{cccc}
A & B & & \\\\
& \ddots & \ddots & \\\\
& & A & B \\\\
& & 0 & A
\end{array}
\\right] \\\\
\mathbf{A} =
\left[
\\begin{array}{cc}
\\frac{1}{\delta t} \MfMui & \MfMui\dcurl \\\\
\dcurl^\\top \MfMui & -\MeSig
\end{array}
\\right] \\\\
\mathbf{B} =
\left[
\\begin{array}{cc}
-\\frac{1}{\delta t} \MfMui & 0 \\\\
0 & 0
\end{array}
\\right] \\\\
"""
# Mini Example:
#
# nT = 3, len(times) == 4, fields stored in F[:,:,1:4]
#
# 0 is held for initial conditions (this shifts the storage by +1)
# ^
# fLoc 0 1 2 3
# |-----|-----|-----|
# tInd 0 1 2
# / ___/
# 2 (tInd=2 uses fields 3 and would use 4 but it doesn't exist)
# / ___/
# 1 (tInd=1 uses fields 2 and 3)
def AhtRHS(tInd, y):
nSrc, nF = self.survey.nSrc, self.mesh.nF
rhs = np.zeros((nF,1) if nSrc == 1 else (nF, nSrc))
if 'e' in p:
rhs += self.MfMui*(self.mesh.edgeCurl*(self.MeSigmaI*p[:,'e',tInd+1]))
if 'b' in p:
rhs += p[:,'b',tInd+1]
if tInd == self.nT-1:
return rhs
dt = self.timeSteps[tInd+1]
return rhs + 1.0/dt*self.MfMui*y[:,'b',tInd+2]
F = FieldsTDEM_e_from_b_Ah(self.mesh, self.survey, p=p)
return self.adjoint(m, AhtRHS, F)
####################################################
# Functions for tests
####################################################
def _AhVec(self, m, vec):
"""
:param numpy.array m: Conductivity model
:param simpegEM.TDEM.FieldsTDEM vec: Fields object
:rtype: simpegEM.TDEM.FieldsTDEM
:return: f
Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where
.. math::
\mathbf{\hat{A}} = \left[
\\begin{array}{cccc}
A & 0 & & \\\\
B & A & & \\\\
& \ddots & \ddots & \\\\
& & B & A
\end{array}
\\right] \\\\
\mathbf{A} =
\left[
\\begin{array}{cc}
\\frac{1}{\delta t} \MfMui & \MfMui\dcurl \\\\
\dcurl^\\top \MfMui & -\MeSig
\end{array}
\\right] \\\\
\mathbf{B} =
\left[
\\begin{array}{cc}
-\\frac{1}{\delta t} \MfMui & 0 \\\\
0 & 0
\end{array}
\\right] \\\\
"""
self.curModel = m
f = FieldsTDEM(self.mesh, self.survey)
for i in range(1,self.nT+1):
dt = self.timeSteps[i-1]
b = 1.0/dt*self.MfMui*vec[:,'b',i] + self.MfMui*(self.mesh.edgeCurl*vec[:,'e',i])
if i > 1:
b = b - 1.0/dt*self.MfMui*vec[:,'b',i-1]
f[:,'b',i] = b
f[:,'e',i] = self.mesh.edgeCurl.T*(self.MfMui*vec[:,'b',i]) - self.MeSigma*vec[:,'e',i]
return f
def _AhtVec(self, m, vec):
"""
:param numpy.array m: Conductivity model
:param simpegEM.TDEM.FieldsTDEM vec: Fields object
:rtype: simpegEM.TDEM.FieldsTDEM
:return: f
Multiply the matrix \\\(\\\hat{A}\\\) by a fields vector where
.. math::
\mathbf{\hat{A}}^\\top = \left[
\\begin{array}{cccc}
A & B & & \\\\
& \ddots & \ddots & \\\\
& & A & B \\\\
& & 0 & A
\end{array}
\\right] \\\\
\mathbf{A} =
\left[
\\begin{array}{cc}
\\frac{1}{\delta t} \MfMui & \MfMui\dcurl \\\\
\dcurl^\\top \MfMui & -\MeSig
\end{array}
\\right] \\\\
\mathbf{B} =
\left[
\\begin{array}{cc}
-\\frac{1}{\delta t} \MfMui & 0 \\\\
0 & 0
\end{array}
\\right] \\\\
"""
self.curModel = m
f = FieldsTDEM(self.mesh, self.survey)
for i in range(self.nT):
b = 1.0/self.timeSteps[i]*self.MfMui*vec[:,'b',i+1] + self.MfMui*(self.mesh.edgeCurl*vec[:,'e',i+1])
if i < self.nT-1:
b = b - 1.0/self.timeSteps[i+1]*self.MfMui*vec[:,'b',i+2]
f[:,'b', i+1] = b
f[:,'e', i+1] = self.mesh.edgeCurl.T*(self.MfMui*vec[:,'b',i+1]) - self.MeSigma*vec[:,'e',i+1]
return f
+3
View File
@@ -0,0 +1,3 @@
from SurveyTDEM import * #SurveyTDEM, RxTDEM, SrcTDEM
from BaseTDEM import BaseTDEMProblem, FieldsTDEM
from TDEM_b import ProblemTDEM_b
+203
View File
@@ -0,0 +1,203 @@
from SimPEG import *
from scipy.special import ellipk, ellipe
from scipy.constants import mu_0, pi
def MagneticDipoleVectorPotential(srcLoc, obsLoc, component, moment=1., dipoleMoment=(0., 0., 1.), mu = mu_0):
"""
Calculate the vector potential of a set of magnetic dipoles
at given locations 'ref. <http://en.wikipedia.org/wiki/Dipole#Magnetic_vector_potential>'
:param numpy.ndarray srcLoc: Location of the source(s) (x, y, z)
:param numpy.ndarray,SimPEG.Mesh obsLoc: Where the potentials will be calculated (x, y, z) or a SimPEG Mesh
:param str,list component: The component to calculate - 'x', 'y', or 'z' if an array, or grid type if mesh, can be a list
:param numpy.ndarray dipoleMoment: The vector dipole moment
:rtype: numpy.ndarray
:return: The vector potential each dipole at each observation location
"""
#TODO: break this out!
if type(component) in [list, tuple]:
out = range(len(component))
for i, comp in enumerate(component):
out[i] = MagneticDipoleVectorPotential(srcLoc, obsLoc, comp, dipoleMoment=dipoleMoment)
return np.concatenate(out)
if isinstance(obsLoc, Mesh.BaseMesh):
mesh = obsLoc
assert component in ['Ex','Ey','Ez','Fx','Fy','Fz'], "Components must be in: ['Ex','Ey','Ez','Fx','Fy','Fz']"
return MagneticDipoleVectorPotential(srcLoc, getattr(mesh,'grid'+component), component[1], dipoleMoment=dipoleMoment)
if component == 'x':
dimInd = 0
elif component == 'y':
dimInd = 1
elif component == 'z':
dimInd = 2
else:
raise ValueError('Invalid component')
srcLoc = np.atleast_2d(srcLoc)
obsLoc = np.atleast_2d(obsLoc)
dipoleMoment = np.atleast_2d(dipoleMoment)
nEdges = obsLoc.shape[0]
nSrc = srcLoc.shape[0]
m = np.array(dipoleMoment).repeat(nEdges, axis=0)
A = np.empty((nEdges, nSrc))
for i in range(nSrc):
dR = obsLoc - srcLoc[i, np.newaxis].repeat(nEdges, axis=0)
mCr = np.cross(m, dR)
r = np.sqrt((dR**2).sum(axis=1))
A[:, i] = +(mu/(4*pi)) * mCr[:,dimInd]/(r**3)
if nSrc == 1:
return A.flatten()
return A
def MagneticDipoleFields(srcLoc, obsLoc, component, moment=1., mu = mu_0):
"""
Calculate the vector potential of a set of magnetic dipoles
at given locations 'ref. <http://en.wikipedia.org/wiki/Dipole#Magnetic_vector_potential>'
:param numpy.ndarray srcLoc: Location of the source(s) (x, y, z)
:param numpy.ndarray obsLoc: Where the potentials will be calculated (x, y, z)
:param str component: The component to calculate - 'x', 'y', or 'z'
:param numpy.ndarray moment: The vector dipole moment (vertical)
:rtype: numpy.ndarray
:return: The vector potential each dipole at each observation location
"""
if component=='x':
dimInd = 0
elif component=='y':
dimInd = 1
elif component=='z':
dimInd = 2
else:
raise ValueError('Invalid component')
srcLoc = np.atleast_2d(srcLoc)
obsLoc = np.atleast_2d(obsLoc)
moment = np.atleast_2d(moment)
nFaces = obsLoc.shape[0]
nSrc = srcLoc.shape[0]
m = np.array(moment).repeat(nFaces, axis=0)
B = np.empty((nFaces, nSrc))
for i in range(nSrc):
dR = obsLoc - srcLoc[i, np.newaxis].repeat(nFaces, axis=0)
r = np.sqrt((dR**2).sum(axis=1))
if dimInd == 0:
B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]*dR[:,0]/r**2)
elif dimInd == 1:
B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]*dR[:,1]/r**2)
elif dimInd == 2:
B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]**2/r**2-1)
else:
raise Exception("Not Implemented")
if nSrc == 1:
return B.flatten()
return B
def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0):
"""
Calculate the vector potential of horizontal circular loop
at given locations
:param numpy.ndarray srcLoc: Location of the source(s) (x, y, z)
:param numpy.ndarray,SimPEG.Mesh obsLoc: Where the potentials will be calculated (x, y, z) or a SimPEG Mesh
:param str,list component: The component to calculate - 'x', 'y', or 'z' if an array, or grid type if mesh, can be a list
:param numpy.ndarray I: Input current of the loop
:param numpy.ndarray radius: radius of the loop
:rtype: numpy.ndarray
:return: The vector potential each dipole at each observation location
"""
if type(component) in [list, tuple]:
out = range(len(component))
for i, comp in enumerate(component):
out[i] = MagneticLoopVectorPotential(srcLoc, obsLoc, comp, radius, mu)
return np.concatenate(out)
if isinstance(obsLoc, Mesh.BaseMesh):
mesh = obsLoc
assert component in ['Ex','Ey','Ez','Fx','Fy','Fz'], "Components must be in: ['Ex','Ey','Ez','Fx','Fy','Fz']"
return MagneticLoopVectorPotential(srcLoc, getattr(mesh,'grid'+component), component[1], radius, mu)
srcLoc = np.atleast_2d(srcLoc)
obsLoc = np.atleast_2d(obsLoc)
n = obsLoc.shape[0]
nSrc = srcLoc.shape[0]
if component=='z':
A = np.zeros((n, nSrc))
if nSrc ==1:
return A.flatten()
return A
else:
A = np.zeros((n, nSrc))
for i in range (nSrc):
x = obsLoc[:, 0] - srcLoc[i, 0]
y = obsLoc[:, 1] - srcLoc[i, 1]
z = obsLoc[:, 2] - srcLoc[i, 2]
r = np.sqrt(x**2 + y**2)
m = (4 * radius * r) / ((radius + r)**2 + z**2)
m[m > 1.] = 1.
# m might be slightly larger than 1 due to rounding errors
# but ellipke requires 0 <= m <= 1
K = ellipk(m)
E = ellipe(m)
ind = (r > 0) & (m < 1)
# % 1/r singular at r = 0 and K(m) singular at m = 1
Aphi = np.zeros(n)
# % 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])
if component == 'x':
A[ind, i] = Aphi[ind] * (-y[ind] / r[ind] )
elif component == 'y':
A[ind, i] = Aphi[ind] * ( x[ind] / r[ind] )
else:
raise ValueError('Invalid component')
if nSrc == 1:
return A.flatten()
return A
if __name__ == '__main__':
from SimPEG import Mesh
import matplotlib.pyplot as plt
cs = 20
ncx, ncy, ncz = 41, 41, 40
hx = np.ones(ncx)*cs
hy = np.ones(ncy)*cs
hz = np.ones(ncz)*cs
mesh = Mesh.TensorMesh([hx, hy, hz], 'CCC')
srcLoc = np.r_[0., 0., 0.]
Ax = MagneticLoopVectorPotential(srcLoc, mesh.gridEx, 'x', 200)
Ay = MagneticLoopVectorPotential(srcLoc, mesh.gridEy, 'y', 200)
Az = MagneticLoopVectorPotential(srcLoc, mesh.gridEz, 'z', 200)
A = np.r_[Ax, Ay, Az]
B0 = mesh.edgeCurl*A
J0 = mesh.edgeCurl.T*B0
# mesh.plotImage(A, vType = 'Ex')
# mesh.plotImage(A, vType = 'Ey')
mesh.plotImage(B0, vType = 'Fx')
mesh.plotImage(B0, vType = 'Fy')
mesh.plotImage(B0, vType = 'Fz')
# # mesh.plotImage(J0, vType = 'Ex')
# mesh.plotImage(J0, vType = 'Ey')
# mesh.plotImage(J0, vType = 'Ez')
plt.show()
+49
View File
@@ -0,0 +1,49 @@
import numpy as np
from scipy.constants import mu_0, epsilon_0
# useful params
def omega(freq):
"""Angular frequency, omega"""
return 2.*np.pi*freq
def k(freq, sigma, mu=mu_0, eps=epsilon_0):
""" Eq 1.47 - 1.49 in Ward and Hohmann """
w = omega(freq)
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) )
return alp - 1j*beta
# Constitutive relations
def e_from_j(prob,j):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
MSigmaI = prob.MeSigmaI
elif eqLocs is 'EF':
MSigmaI = prob.MfRho
return MSigmaI*j
def j_from_e(prob,e):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
MSigma = prob.MeSigma
elif eqLocs is 'EF':
MSigma = prob.MfRhoI
return MSigma*e
def b_from_h(prob,h):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
MMu = prob.MfMuiI
elif eqLocs is 'EF':
MMu = prob.MeMu
return MMu*h
def h_from_b(prob,b):
eqLocs = prob._eqLocs
if eqLocs is 'FE':
MMuI = prob.MfMui
elif eqLocs is 'EF':
MMuI = prob.MeMuI
return MMuI*b
+5
View File
@@ -0,0 +1,5 @@
# import Sources
# import Ana
# import Solver
from EMUtils import omega, e_from_j, j_from_e, b_from_h, h_from_b
from AnalyticUtils import MagneticDipoleFields, MagneticDipoleVectorPotential, MagneticLoopVectorPotential
+75
View File
@@ -0,0 +1,75 @@
import unittest
from SimPEG import *
from SimPEG import EM
import sys
from scipy.constants import mu_0
def getFDEMProblem(fdemType, comp, SrcList, freq, verbose=False):
cs = 5.
ncx, ncy, ncz = 6, 6, 6
npad = 3
hx = [(cs,npad,-1.3), (cs,ncx), (cs,npad,1.3)]
hy = [(cs,npad,-1.3), (cs,ncy), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.TensorMesh([hx,hy,hz],['C','C','C'])
mapping = Maps.ExpMap(mesh)
x = np.array([np.linspace(-30,-15,3),np.linspace(15,30,3)]) #don't sample right by the source
XYZ = Utils.ndgrid(x,x,np.r_[0.])
Rx0 = EM.FDEM.Rx(XYZ, comp)
Src = []
for SrcType in SrcList:
if SrcType is 'MagDipole':
Src.append(EM.FDEM.Src.MagDipole([Rx0], freq=freq, loc=np.r_[0.,0.,0.]))
elif SrcType is 'MagDipole_Bfield':
Src.append(EM.FDEM.Src.MagDipole_Bfield([Rx0], freq=freq, loc=np.r_[0.,0.,0.]))
elif SrcType is 'CircularLoop':
Src.append(EM.FDEM.Src.CircularLoop([Rx0], freq=freq, loc=np.r_[0.,0.,0.]))
elif SrcType is 'RawVec':
if fdemType is 'e' or fdemType is 'b':
S_m = np.zeros(mesh.nF)
S_e = np.zeros(mesh.nE)
S_m[Utils.closestPoints(mesh,[0.,0.,0.],'Fz') + np.sum(mesh.vnF[:1])] = 1.
S_e[Utils.closestPoints(mesh,[0.,0.,0.],'Ez') + np.sum(mesh.vnE[:1])] = 1.
Src.append(EM.FDEM.Src.RawVec([Rx0], freq, S_m, S_e))
elif fdemType is 'h' or fdemType is 'j':
S_m = np.zeros(mesh.nE)
S_e = np.zeros(mesh.nF)
S_m[Utils.closestPoints(mesh,[0.,0.,0.],'Ez') + np.sum(mesh.vnE[:1])] = 1.
S_e[Utils.closestPoints(mesh,[0.,0.,0.],'Fz') + np.sum(mesh.vnF[:1])] = 1.
Src.append(EM.FDEM.Src.RawVec([Rx0], freq, S_m, S_e))
if verbose:
print ' Fetching %s problem' % (fdemType)
if fdemType == 'e':
survey = EM.FDEM.Survey(Src)
prb = EM.FDEM.Problem_e(mesh, mapping=mapping)
elif fdemType == 'b':
survey = EM.FDEM.Survey(Src)
prb = EM.FDEM.Problem_b(mesh, mapping=mapping)
elif fdemType == 'j':
survey = EM.FDEM.Survey(Src)
prb = EM.FDEM.Problem_j(mesh, mapping=mapping)
elif fdemType == 'h':
survey = EM.FDEM.Survey(Src)
prb = EM.FDEM.Problem_h(mesh, mapping=mapping)
else:
raise NotImplementedError()
prb.pair(survey)
try:
from pymatsolver import MumpsSolver
prb.Solver = MumpsSolver
except ImportError, e:
pass
return prb
+6
View File
@@ -0,0 +1,6 @@
# from EM import *
import TDEM
import FDEM
import Base
import Analytics
import Utils
-71
View File
@@ -1,71 +0,0 @@
from SimPEG import Mesh, Utils, np, SolverLU
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.mlab import griddata
## 2D DC forward modeling example with Tensor and Curvilinear Meshes
# Step1: Generate Tensor and Curvilinear Mesh
sz = [40,40]
# Tensor Mesh
tM = Mesh.TensorMesh(sz)
# Curvilinear Mesh
rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate'))
# Step2: Direct Current (DC) operator
def DCfun(mesh, pts):
D = mesh.faceDiv
G = D.T
sigma = 1e-2*np.ones(mesh.nC)
Msigi = mesh.getFaceInnerProduct(1./sigma)
MsigI = Utils.sdInv(Msigi)
A = D*MsigI*G
A[-1,-1] /= mesh.vol[-1] # Remove null space
rhs = np.zeros(mesh.nC)
txind = Utils.meshutils.closestPoints(mesh, pts)
rhs[txind] = np.r_[1,-1]
return A, rhs
pts = np.vstack((np.r_[0.25, 0.5], np.r_[0.75, 0.5]))
#Step3: Solve DC problem (LU solver)
AtM, rhstM = DCfun(tM, pts)
AinvtM = SolverLU(AtM)
phitM = AinvtM*rhstM
ArM, rhsrM = DCfun(rM, pts)
AinvrM = SolverLU(ArM)
phirM = AinvrM*rhsrM
#Step4: Making Figure
fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2))
label = ["(a)", "(b)"]
opts = {}
vmin, vmax = phitM.min(), phitM.max()
dat = tM.plotImage(phitM, ax=axes[0], 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[1]); cb.set_label("Voltage (V)")
tM.plotGrid(ax=axes[0], **opts)
axes[0].set_title('TensorMesh')
rM.plotGrid(ax=axes[1], **opts)
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()
+104
View File
@@ -0,0 +1,104 @@
from SimPEG import *
import SimPEG.EM as EM
from scipy.constants import mu_0
import matplotlib.pyplot as plt
def run(plotIt=True):
"""
EM: FDEM: 1D: Inversion
=======================
Here we will create and run a FDEM 1D inversion.
"""
cs, ncx, ncz, npad = 5., 25, 15, 15
hx = [(cs,ncx), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.CylMesh([hx,1,hz], '00C')
active = mesh.vectorCCz<0.
layer = (mesh.vectorCCz<0.) & (mesh.vectorCCz>=-100.)
actMap = Maps.ActiveCells(mesh, active, np.log(1e-8), nC=mesh.nCz)
mapping = Maps.ExpMap(mesh) * Maps.Vertical1DMap(mesh) * actMap
sig_half = 2e-3
sig_air = 1e-8
sig_layer = 1e-3
sigma = np.ones(mesh.nCz)*sig_air
sigma[active] = sig_half
sigma[layer] = sig_layer
mtrue = np.log(sigma[active])
if plotIt:
fig, ax = plt.subplots(1,1, figsize = (3, 6))
plt.semilogx(sigma[active], mesh.vectorCCz[active])
ax.set_ylim(-600, 0)
ax.set_xlim(1e-4, 1e-2)
ax.set_xlabel('Conductivity (S/m)', fontsize = 14)
ax.set_ylabel('Depth (m)', fontsize = 14)
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
rxOffset=1e-3
rx = EM.TDEM.RxTDEM(np.array([[rxOffset, 0., 30]]), np.logspace(-5,-3, 31), 'bz')
src = EM.TDEM.SrcTDEM_VMD_MVP([rx], np.array([0., 0., 80]))
survey = EM.TDEM.SurveyTDEM([src])
prb = EM.TDEM.ProblemTDEM_b(mesh, mapping=mapping)
prb.Solver = SolverLU
prb.timeSteps = [(1e-06, 20),(1e-05, 20), (0.0001, 20)]
prb.pair(survey)
dtrue = survey.dpred(mtrue)
survey.dtrue = dtrue
std = 0.05
noise = std*abs(survey.dtrue)*np.random.randn(*survey.dtrue.shape)
survey.dobs = survey.dtrue+noise
survey.std = survey.dobs*0 + std
survey.Wd = 1/(abs(survey.dobs)*std)
if plotIt:
fig, ax = plt.subplots(1,1, figsize = (10, 6))
ax.loglog(rx.times, dtrue, 'b.-')
ax.loglog(rx.times, survey.dobs, 'r.-')
ax.legend(('Noisefree', '$d^{obs}$'), fontsize = 16)
ax.set_xlabel('Time (s)', fontsize = 14)
ax.set_ylabel('$B_z$ (T)', fontsize = 16)
ax.set_xlabel('Time (s)', fontsize = 14)
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
dmisfit = DataMisfit.l2_DataMisfit(survey)
regMesh = Mesh.TensorMesh([mesh.hz[mapping.maps[-1].indActive]])
reg = Regularization.Tikhonov(regMesh)
opt = Optimization.InexactGaussNewton(maxIter = 5)
invProb = InvProblem.BaseInvProblem(dmisfit, reg, opt)
# Create an inversion object
beta = Directives.BetaSchedule(coolingFactor=5, coolingRate=2)
betaest = Directives.BetaEstimate_ByEig(beta0_ratio=1e0)
inv = Inversion.BaseInversion(invProb, directiveList=[beta,betaest])
m0 = np.log(np.ones(mtrue.size)*sig_half)
reg.alpha_s = 1e-2
reg.alpha_x = 1.
prb.counter = opt.counter = Utils.Counter()
opt.LSshorten = 0.5
opt.remember('xc')
mopt = inv.run(m0)
if plotIt:
fig, ax = plt.subplots(1,1, figsize = (3, 6))
plt.semilogx(sigma[active], mesh.vectorCCz[active])
plt.semilogx(np.exp(mopt), mesh.vectorCCz[active])
ax.set_ylim(-600, 0)
ax.set_xlim(1e-4, 1e-2)
ax.set_xlabel('Conductivity (S/m)', fontsize = 14)
ax.set_ylabel('Depth (m)', fontsize = 14)
ax.grid(color='k', alpha=0.5, linestyle='dashed', linewidth=0.5)
plt.legend(['$\sigma_{true}$', '$\sigma_{pred}$'])
plt.show()
if __name__ == '__main__':
run()
@@ -0,0 +1,86 @@
from SimPEG import *
from SimPEG.FLOW import Richards
import matplotlib.pyplot as plt
def run(plotIt=True):
"""
FLOW: Richards: 1D: Celia1990
=============================
There are two different forms of Richards equation that differ
on how they deal with the non-linearity in the time-stepping term.
The most fundamental form, referred to as the
'mixed'-form of Richards Equation Celia1990_
.. math::
\\frac{\partial \\theta(\psi)}{\partial t} - \\nabla \cdot k(\psi) \\nabla \psi - \\frac{\partial k(\psi)}{\partial z} = 0
\quad \psi \in \Omega
where \\\\(\\\\theta\\\\) is water content, and \\\\(\\\\psi\\\\) is pressure head.
This formulation of Richards equation is called the
'mixed'-form because the equation is parameterized in \\\\(\\\\psi\\\\)
but the time-stepping is in terms of \\\\(\\\\theta\\\\).
As noted in Celia1990_ the 'head'-based form of Richards
equation can be written in the continuous form as:
.. math::
\\frac{\partial \\theta}{\partial \psi}\\frac{\partial \psi}{\partial t} - \\nabla \cdot k(\psi) \\nabla \psi - \\frac{\partial k(\psi)}{\partial z} = 0 \quad \psi \in \Omega
However, it can be shown that this does not conserve mass in the discrete formulation.
Here we reproduce the results from Celia1990_ demonstrating the head-based formulation and the mixed-formulation.
.. _Celia1990: http://www.webpages.uidaho.edu/ch/papers/Celia.pdf
"""
M = Mesh.TensorMesh([np.ones(40)])
M.setCellGradBC('dirichlet')
params = Richards.Empirical.HaverkampParams().celia1990
params['Ks'] = np.log(params['Ks'])
E = Richards.Empirical.Haverkamp(M, **params)
bc = np.array([-61.5,-20.7])
h = np.zeros(M.nC) + bc[0]
def getFields(timeStep,method):
timeSteps = np.ones(360/timeStep)*timeStep
prob = Richards.RichardsProblem(M, mapping=E, timeSteps=timeSteps,
boundaryConditions=bc, initialConditions=h,
doNewton=False, method=method)
return prob.fields(params['Ks'])
Hs_M10 = getFields(10., 'mixed')
Hs_M30 = getFields(30., 'mixed')
Hs_M120= getFields(120.,'mixed')
Hs_H10 = getFields(10., 'head')
Hs_H30 = getFields(30., 'head')
Hs_H120= getFields(120.,'head')
if not plotIt:return
plt.figure(figsize=(13,5))
plt.subplot(121)
plt.plot(40-M.gridCC, Hs_M10[-1],'b-')
plt.plot(40-M.gridCC, Hs_M30[-1],'r-')
plt.plot(40-M.gridCC, Hs_M120[-1],'k-')
plt.ylim([-70,-10])
plt.title('Mixed Method')
plt.xlabel('Depth, cm')
plt.ylabel('Pressure Head, cm')
plt.legend(('$\Delta t$ = 10 sec','$\Delta t$ = 30 sec','$\Delta t$ = 120 sec'))
plt.subplot(122)
plt.plot(40-M.gridCC, Hs_H10[-1],'b-')
plt.plot(40-M.gridCC, Hs_H30[-1],'r-')
plt.plot(40-M.gridCC, Hs_H120[-1],'k-')
plt.ylim([-70,-10])
plt.title('Head-Based Method')
plt.xlabel('Depth, cm')
plt.ylabel('Pressure Head, cm')
plt.legend(('$\Delta t$ = 10 sec','$\Delta t$ = 30 sec','$\Delta t$ = 120 sec'))
plt.show()
if __name__ == '__main__':
run()
@@ -0,0 +1,76 @@
from SimPEG import Mesh, Utils, np, SolverLU
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.mlab import griddata
## 2D DC forward modeling example with Tensor and Curvilinear Meshes
def run(plotIt=True):
# Step1: Generate Tensor and Curvilinear Mesh
sz = [40,40]
# Tensor Mesh
tM = Mesh.TensorMesh(sz)
# Curvilinear Mesh
rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate'))
# Step2: Direct Current (DC) operator
def DCfun(mesh, pts):
D = mesh.faceDiv
G = D.T
sigma = 1e-2*np.ones(mesh.nC)
Msigi = mesh.getFaceInnerProduct(1./sigma)
MsigI = Utils.sdInv(Msigi)
A = D*MsigI*G
A[-1,-1] /= mesh.vol[-1] # Remove null space
rhs = np.zeros(mesh.nC)
txind = Utils.meshutils.closestPoints(mesh, pts)
rhs[txind] = np.r_[1,-1]
return A, rhs
pts = np.vstack((np.r_[0.25, 0.5], np.r_[0.75, 0.5]))
#Step3: Solve DC problem (LU solver)
AtM, rhstM = DCfun(tM, pts)
AinvtM = SolverLU(AtM)
phitM = AinvtM*rhstM
ArM, rhsrM = DCfun(rM, pts)
AinvrM = SolverLU(ArM)
phirM = AinvrM*rhsrM
if not plotIt: return
#Step4: Making Figure
fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2))
label = ["(a)", "(b)"]
opts = {}
vmin, vmax = phitM.min(), phitM.max()
dat = tM.plotImage(phitM, ax=axes[0], 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[1]); cb.set_label("Voltage (V)")
tM.plotGrid(ax=axes[0], **opts)
axes[0].set_title('TensorMesh')
rM.plotGrid(ax=axes[1], **opts)
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()
if __name__ == '__main__':
run()
@@ -1,29 +1,39 @@
from SimPEG import *
class LinearSurvey(Survey.BaseSurvey):
def projectFields(self, u):
return u
class LinearProblem(Problem.BaseProblem):
"""docstring for LinearProblem"""
def run(N=100, plotIt=True):
"""
Inversion: Linear Problem
=========================
surveyPair = LinearSurvey
Here we go over the basics of creating a linear problem and inversion.
def __init__(self, mesh, G, **kwargs):
Problem.BaseProblem.__init__(self, mesh, **kwargs)
self.G = G
"""
def fields(self, m, u=None):
return self.G.dot(m)
class LinearSurvey(Survey.BaseSurvey):
def projectFields(self, u):
return u
def Jvec(self, m, v, u=None):
return self.G.dot(v)
class LinearProblem(Problem.BaseProblem):
def Jtvec(self, m, v, u=None):
return self.G.T.dot(v)
surveyPair = LinearSurvey
def __init__(self, mesh, G, **kwargs):
Problem.BaseProblem.__init__(self, mesh, **kwargs)
self.G = G
def fields(self, m, u=None):
return self.G.dot(m)
def Jvec(self, m, v, u=None):
return self.G.dot(v)
def Jtvec(self, m, v, u=None):
return self.G.T.dot(v)
def run(N, plotIt=True):
np.random.seed(1)
mesh = Mesh.TensorMesh([N])
nk = 20
@@ -52,7 +62,7 @@ def run(N, plotIt=True):
reg = Regularization.Tikhonov(mesh)
dmis = DataMisfit.l2_DataMisfit(survey)
opt = Optimization.InexactGaussNewton(maxIter=20)
opt = Optimization.InexactGaussNewton(maxIter=35)
invProb = InvProblem.BaseInvProblem(dmis, reg, opt)
beta = Directives.BetaSchedule()
betaest = Directives.BetaEstimate_ByEig()
@@ -63,16 +73,18 @@ def run(N, plotIt=True):
if plotIt:
import matplotlib.pyplot as plt
plt.figure(1)
for i in range(prob.G.shape[0]):
plt.plot(prob.G[i,:])
plt.figure(2)
plt.plot(M.vectorCCx, survey.mtrue, 'b-')
plt.plot(M.vectorCCx, mrec, 'r-')
fig, axes = plt.subplots(1,2,figsize=(12*1.2,4*1.2))
for i in range(prob.G.shape[0]):
axes[0].plot(prob.G[i,:])
axes[0].set_title('Columns of matrix G')
axes[1].plot(M.vectorCCx, survey.mtrue, 'b-')
axes[1].plot(M.vectorCCx, mrec, 'r-')
axes[1].legend(('True Model', 'Recovered Model'))
plt.show()
return prob, survey, mesh, mrec
if __name__ == '__main__':
run(100)
run()
+46
View File
@@ -0,0 +1,46 @@
from SimPEG import *
def run(plotIt=True):
"""
Mesh: Basic: PlotImage
======================
You can use M.PlotImage to plot images on all of the Meshes.
"""
M = Mesh.TensorMesh([32,32])
v = Utils.ModelBuilder.randomModel(M.vnC, seed=789)
v = Utils.mkvc(v)
O = Mesh.TreeMesh([32,32])
O.refine(1)
def function(cell):
if (cell.center[0] < 0.75 and cell.center[0] > 0.25 and
cell.center[1] < 0.75 and cell.center[1] > 0.25):return 5
if (cell.center[0] < 0.9 and cell.center[0] > 0.1 and
cell.center[1] < 0.9 and cell.center[1] > 0.1):return 4
return 3
O.refine(function)
P = M.getInterpolationMat(O.gridCC, 'CC')
ov = P * v
if plotIt:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1,2,figsize=(10,5))
out = M.plotImage(v, grid=True, ax=axes[0])
cb = plt.colorbar(out[0], ax=axes[0]); cb.set_label("Random Field")
axes[0].set_title('TensorMesh')
out = O.plotImage(ov, grid=True, ax=axes[1], clim=[0,1])
cb = plt.colorbar(out[0], ax=axes[1]); cb.set_label("Random Field")
axes[1].set_title('TreeMesh')
plt.show()
if __name__ == '__main__':
run()
+30
View File
@@ -0,0 +1,30 @@
from SimPEG import *
def run(plotIt=True):
"""
Mesh: Basic: Types
==================
Here we show SimPEG used to create three different types of meshes.
"""
sz = [16,16]
tM = Mesh.TensorMesh(sz)
qM = Mesh.TreeMesh(sz)
qM.refine(lambda cell: 4 if np.sqrt(((np.r_[cell.center]-0.5)**2).sum()) < 0.4 else 3)
rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate'))
if plotIt:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1,3,figsize=(14,5))
opts = {}
tM.plotGrid(ax=axes[0], **opts)
axes[0].set_title('TensorMesh')
qM.plotGrid(ax=axes[1], **opts)
axes[1].set_title('TreeMesh')
rM.plotGrid(ax=axes[2], **opts)
axes[2].set_title('CurvilinearMesh')
plt.show()
if __name__ == '__main__':
run()
@@ -0,0 +1,105 @@
from SimPEG import *
def run(plotIt=True, n=60):
"""
Mesh: Operators: Cahn Hilliard
==============================
This example is based on the example in the FiPy_ library.
Please see their documentation for more information about the Cahn-Hilliard equation.
The "Cahn-Hilliard" equation separates a field \\\\( \\\\phi \\\\) into 0 and 1 with smooth transitions.
.. math::
\\frac{\partial \phi}{\partial t} = \\nabla \cdot D \\nabla \left( \\frac{\partial f}{\partial \phi} - \epsilon^2 \\nabla^2 \phi \\right)
Where \\\\( f \\\\) is the energy function \\\\( f = ( a^2 / 2 )\\\\phi^2(1 - \\\\phi)^2 \\\\)
which drives \\\\( \\\\phi \\\\) towards either 0 or 1, this competes with the term
\\\\(\\\\epsilon^2 \\\\nabla^2 \\\\phi \\\\) which is a diffusion term that creates smooth changes in \\\\( \\\\phi \\\\).
The equation can be factored:
.. math::
\\frac{\partial \phi}{\partial t} = \\nabla \cdot D \\nabla \psi \\\\
\psi = \\frac{\partial^2 f}{\partial \phi^2} (\phi - \phi^{\\text{old}}) + \\frac{\partial f}{\partial \phi} - \epsilon^2 \\nabla^2 \phi
Here we will need the derivatives of \\\\( f \\\\):
.. math::
\\frac{\partial f}{\partial \phi} = (a^2/2)2\phi(1-\phi)(1-2\phi)
\\frac{\partial^2 f}{\partial \phi^2} = (a^2/2)2[1-6\phi(1-\phi)]
The implementation below uses backwards Euler in time with an exponentially increasing time step.
The initial \\\\( \\\\phi \\\\) is a normally distributed field with a standard deviation of 0.1 and mean of 0.5.
The grid is 60x60 and takes a few seconds to solve ~130 times. The results are seen below, and you can see the
field separating as the time increases.
.. _FiPy: http://www.ctcms.nist.gov/fipy/examples/cahnHilliard/generated/examples.cahnHilliard.mesh2DCoupled.html
"""
np.random.seed(5)
# Here we are going to rearrange the equations:
# (phi_ - phi)/dt = A*(d2fdphi2*(phi_ - phi) + dfdphi - L*phi_)
# (phi_ - phi)/dt = A*(d2fdphi2*phi_ - d2fdphi2*phi + dfdphi - L*phi_)
# (phi_ - phi)/dt = A*d2fdphi2*phi_ + A*( - d2fdphi2*phi + dfdphi - L*phi_)
# phi_ - phi = dt*A*d2fdphi2*phi_ + dt*A*(- d2fdphi2*phi + dfdphi - L*phi_)
# phi_ - dt*A*d2fdphi2 * phi_ = dt*A*(- d2fdphi2*phi + dfdphi - L*phi_) + phi
# (I - dt*A*d2fdphi2) * phi_ = dt*A*(- d2fdphi2*phi + dfdphi - L*phi_) + phi
# (I - dt*A*d2fdphi2) * phi_ = dt*A*dfdphi - dt*A*d2fdphi2*phi - dt*A*L*phi_ + phi
# (dt*A*d2fdphi2 - I) * phi_ = dt*A*d2fdphi2*phi + dt*A*L*phi_ - phi - dt*A*dfdphi
# (dt*A*d2fdphi2 - I - dt*A*L) * phi_ = (dt*A*d2fdphi2 - I)*phi - dt*A*dfdphi
h = [(0.25,n)]
M = Mesh.TensorMesh([h,h])
# Constants
D = a = epsilon = 1.
I = Utils.speye(M.nC)
# Operators
A = D * M.faceDiv * M.cellGrad
L = epsilon**2 * M.faceDiv * M.cellGrad
duration = 75
elapsed = 0.
dexp = -5
phi = np.random.normal(loc=0.5,scale=0.01,size=M.nC)
ii, jj = 0, 0
PHIS = []
capture = np.logspace(-1,np.log10(duration),8)
while elapsed < duration:
dt = min(100, np.exp(dexp))
elapsed += dt
dexp += 0.05
dfdphi = a**2 * 2 * phi * (1 - phi) * (1 - 2 * phi)
d2fdphi2 = Utils.sdiag(a**2 * 2 * (1 - 6 * phi * (1 - phi)))
MAT = (dt*A*d2fdphi2 - I - dt*A*L)
rhs = (dt*A*d2fdphi2 - I)*phi - dt*A*dfdphi
phi = Solver(MAT)*rhs
if elapsed > capture[jj]:
PHIS += [(elapsed, phi.copy())]
jj += 1
if ii % 10 == 0: print ii, elapsed
ii += 1
if plotIt:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,4,figsize=(14,6))
axes = np.array(axes).flatten().tolist()
for ii, ax in zip(np.linspace(0,len(PHIS)-1,len(axes)),axes):
ii = int(ii)
out = M.plotImage(PHIS[ii][1],ax=ax)
ax.axis('off')
ax.set_title('Elapsed Time: %4.1f'%PHIS[ii][0])
plt.show()
if __name__ == '__main__':
run()
+28
View File
@@ -0,0 +1,28 @@
from SimPEG import *
def run(plotIt=True):
"""
Mesh: QuadTree: Creation
========================
You can give the refine method a function, which is evaluated on every cell
of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
M = Mesh.TreeMesh([32,32])
M.refine(3)
def function(cell):
xyz = cell.center
for i in range(3):
if np.abs(np.sin(xyz[0]*np.pi*2)*0.5 + 0.5 - xyz[1]) < 0.2*i:
return 6-i
return 0
M.refine(function);
if plotIt: M.plotGrid(showIt=True)
if __name__ == '__main__':
run()
+49
View File
@@ -0,0 +1,49 @@
from SimPEG import *
def run(plotIt=True, n=60):
"""
Mesh: QuadTree: FaceDiv
=======================
"""
M = Mesh.TreeMesh([[(1,16)],[(1,16)]], levels=4)
M._refineCell([0,0,0])
M._refineCell([0,0,1])
M._refineCell([4,4,2])
M.__dirty__ = True
M.number()
if plotIt:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,1,figsize=(10,10))
M.plotGrid(cells=True, nodes=False, ax=axes[0])
axes[0].axis('off')
axes[0].set_title('Simple QuadTree Mesh')
axes[0].set_xlim([-1,17])
axes[0].set_ylim([-1,17])
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].plot(M.gridFx[:,0],M.gridFx[:,1], 'g>')
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].plot(M.gridFy[:,0],M.gridFy[:,1], 'm^')
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[1].spy(M.faceDiv)
axes[1].set_title('Face Divergence')
axes[1].set_ylabel('Cell Number')
axes[1].set_xlabel('Face Number')
plt.show()
if __name__ == '__main__':
run()
@@ -0,0 +1,32 @@
from SimPEG import *
def run(plotIt=True):
"""
Mesh: QuadTree: Hanging Nodes
=============================
You can give the refine method a function, which is evaluated on every cell
of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
"""
M = Mesh.TreeMesh([8,8])
def function(cell):
xyz = cell.center
dist = ((xyz - [0.25,0.25])**2).sum()**0.5
if dist < 0.25:
return 3
return 2
M.refine(function);
M.number()
if plotIt:
import matplotlib.pyplot as plt
M.plotGrid(nodes=True, cells=True, facesX=True)
plt.legend(('Grid', 'Cell Centers', 'Nodes', 'Hanging Nodes', 'X faces', 'Hanging X faces'))
plt.show()
if __name__ == '__main__':
run()
+35
View File
@@ -0,0 +1,35 @@
from SimPEG import *
def run(plotIt=True):
"""
Mesh: Tensor: Creation
======================
For tensor meshes, there are some functions that can come
in handy. For example, creating mesh tensors can be a bit time
consuming, these can be created speedily by just giving numbers
and sizes of padding. See the example below, that follows this
notation::
h1 = (
(cellSize, numPad, [, increaseFactor]),
(cellSize, numCore),
(cellSize, numPad, [, increaseFactor])
)
.. note::
You can center your mesh by passing a 'C' for the x0[i] position.
A 'N' will make the entire mesh negative, and a '0' (or a 0) will
make the mesh start at zero.
"""
h1 = [(10, 5, -1.3), (5, 20), (10, 3, 1.3)]
M = Mesh.TensorMesh([h1, h1], x0='CN')
if plotIt:
M.plotGrid(showIt=True)
if __name__ == '__main__':
run()
+103 -1
View File
@@ -1 +1,103 @@
import Linear
# Run this file to add imports.
##### AUTOIMPORTS #####
import EM_FDEM_1D_Inversion
import FLOW_Richards_1D_Celia1990
import Forward_BasicDirectCurrent
import Inversion_Linear
import Mesh_Basic_PlotImage
import Mesh_Basic_Types
import Mesh_Operators_CahnHilliard
import Mesh_QuadTree_Creation
import Mesh_QuadTree_FaceDiv
import Mesh_QuadTree_HangingNodes
import Mesh_Tensor_Creation
__examples__ = ["EM_FDEM_1D_Inversion", "FLOW_Richards_1D_Celia1990", "Forward_BasicDirectCurrent", "Inversion_Linear", "Mesh_Basic_PlotImage", "Mesh_Basic_Types", "Mesh_Operators_CahnHilliard", "Mesh_QuadTree_Creation", "Mesh_QuadTree_FaceDiv", "Mesh_QuadTree_HangingNodes", "Mesh_Tensor_Creation"]
##### AUTOIMPORTS #####
if __name__ == '__main__':
"""
Run the following to create the examples documentation and add to the imports at the top.
"""
import shutil, os
from SimPEG import Examples
# Create the examples dir in the docs folder.
docExamplesDir = os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-3] + ['docs', 'examples'])
shutil.rmtree(docExamplesDir)
os.makedirs(docExamplesDir)
# Get all the python examples in this folder
thispath = os.path.sep.join(__file__.split(os.path.sep)[:-1])
exfiles = [f[:-3] for f in os.listdir(thispath) if os.path.isfile(os.path.join(thispath, f)) and f.endswith('.py') and not f.startswith('_')]
# Add the imports to the top in the AUTOIMPORTS section
f = file(__file__, 'r')
inimports = False
out = ''
for line in f:
if not inimports:
out += line
if line == "##### AUTOIMPORTS #####\n":
inimports = not inimports
if inimports:
out += '\n'.join(["import %s"%_ for _ in exfiles])
out += '\n\n__examples__ = ["' + '", "'.join(exfiles)+ '"]\n'
out += '\n##### AUTOIMPORTS #####\n'
f.close()
f = file(__file__, 'w')
f.write(out)
f.close()
def _makeExample(filePath, runFunction):
"""Makes the example given a path of the file and the run function."""
filePath = os.path.realpath(filePath)
name = filePath.split(os.path.sep)[-1].rstrip('.pyc').rstrip('.py')
docstr = runFunction.__doc__
if docstr is None:
doc = '%s\n%s'%(name.replace('_',' '),'='*len(name))
else:
doc = '\n'.join([_[8:].rstrip() for _ in docstr.split('\n')])
out = """.. _examples_%s:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
%s
.. plot::
from SimPEG import Examples
Examples.%s.run()
.. literalinclude:: ../../SimPEG/Examples/%s.py
:language: python
:linenos:
"""%(name,doc,name,name)
rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'examples', name + '.rst']))
print 'Creating: %s.rst'%name
f = open(rst, 'w')
f.write(out)
f.close()
for ex in dir(Examples):
if ex.startswith('_'): continue
E = getattr(Examples,ex)
_makeExample(E.__file__, E.run)
+578
View File
@@ -0,0 +1,578 @@
from SimPEG import Mesh, Maps, Utils, np
class NonLinearMap(object):
"""
SimPEG NonLinearMap
"""
__metaclass__ = Utils.SimPEGMetaClass
counter = None #: A SimPEG.Utils.Counter object
mesh = None #: A SimPEG Mesh
def __init__(self, mesh):
self.mesh = mesh
def _transform(self, u, m):
"""
:param numpy.array u: fields
:param numpy.array m: model
:rtype: numpy.array
:return: transformed model
The *transform* changes the model into the physical property.
"""
return m
def derivU(self, u, m):
"""
:param numpy.array u: fields
:param numpy.array m: model
:rtype: scipy.csr_matrix
:return: derivative of transformed model
The *transform* changes the model into the physical property.
The *transformDerivU* provides the derivative of the *transform* with respect to the fields.
"""
raise NotImplementedError('The transformDerivU is not implemented.')
def derivM(self, u, m):
"""
:param numpy.array u: fields
:param numpy.array m: model
:rtype: scipy.csr_matrix
:return: derivative of transformed model
The *transform* changes the model into the physical property.
The *transformDerivU* provides the derivative of the *transform* with respect to the model.
"""
raise NotImplementedError('The transformDerivM is not implemented.')
@property
def nP(self):
"""Number of parameters in the model."""
return self.mesh.nC
def example(self):
raise NotImplementedError('The example is not implemented.')
def test(self, m=None):
raise NotImplementedError('The test is not implemented.')
class RichardsMap(object):
"""docstring for RichardsMap"""
mesh = None #: SimPEG mesh
@property
def thetaModel(self):
"""Model for moisture content"""
return self._thetaModel
@property
def kModel(self):
"""Model for hydraulic conductivity"""
return self._kModel
def __init__(self, mesh, thetaModel, kModel):
self.mesh = mesh
assert isinstance(thetaModel, NonLinearMap)
assert isinstance(kModel, NonLinearMap)
self._thetaModel = thetaModel
self._kModel = kModel
def theta(self, u, m):
return self.thetaModel.transform(u, m)
def thetaDerivM(self, u, m):
return self.thetaModel.transformDerivM(u, m)
def thetaDerivU(self, u, m):
return self.thetaModel.transformDerivU(u, m)
def k(self, u, m):
return self.kModel.transform(u, m)
def kDerivM(self, u, m):
return self.kModel.transformDerivM(u, m)
def kDerivU(self, u, m):
return self.kModel.transformDerivU(u, m)
def plot(self, m):
import matplotlib.pyplot as plt
m = m[0]
h = np.linspace(-100, 20, 1000)
ax = plt.subplot(121)
ax.plot(self.theta(h, m), h)
ax = plt.subplot(122)
ax.semilogx(self.k(h, m), h)
def _assertMatchesPair(self, pair):
assert isinstance(self, pair), "Mapping object must be an instance of a %s class."%(pair.__name__)
def _ModelProperty(name, models, doc=None, default=None):
def fget(self):
model = models[0]
if getattr(self, model, None) is not None:
MOD = getattr(self, model)
return getattr(MOD, name, default)
return default
def fset(self, value):
for model in models:
if getattr(self, model, None) is not None:
MOD = getattr(self, model)
setattr(MOD, name, value)
return property(fget, fset=fset, doc=doc)
class HaverkampParams(object):
"""Holds some default parameterizations for the Haverkamp model."""
def __init__(self): pass
@property
def celia1990(self):
"""
Parameters used in:
Celia, Michael A., Efthimios T. Bouloutas, and Rebecca L. Zarba.
"A general mass-conservative numerical solution for the unsaturated flow equation."
Water Resources Research 26.7 (1990): 1483-1496.
"""
return {'alpha':1.611e+06, 'beta':3.96,
'theta_r':0.075, 'theta_s':0.287,
'Ks':9.44e-03, 'A':1.175e+06,
'gamma':4.74}
class _haverkamp_theta(NonLinearMap):
theta_s = 0.430
theta_r = 0.078
alpha = 0.036
beta = 3.960
def __init__(self, mesh, **kwargs):
NonLinearMap.__init__(self, mesh)
Utils.setKwargs(self, **kwargs)
def setModel(self, m):
self._currentModel = m
def transform(self, u, m):
self.setModel(m)
f = (self.alpha*(self.theta_s - self.theta_r )/
(self.alpha + abs(u)**self.beta) + self.theta_r)
if Utils.isScalar(self.theta_s):
f[u >= 0] = self.theta_s
else:
f[u >= 0] = self.theta_s[u >= 0]
return f
def transformDerivM(self, u, m):
self.setModel(m)
def transformDerivU(self, u, m):
self.setModel(m)
g = (self.alpha*((self.theta_s - self.theta_r)/
(self.alpha + abs(u)**self.beta)**2)
*(-self.beta*abs(u)**(self.beta-1)*np.sign(u)))
g[u >= 0] = 0
g = Utils.sdiag(g)
return g
class _haverkamp_k(NonLinearMap):
A = 1.175e+06
gamma = 4.74
Ks = np.log(24.96)
def __init__(self, mesh, **kwargs):
NonLinearMap.__init__(self, mesh)
Utils.setKwargs(self, **kwargs)
def setModel(self, m):
self._currentModel = m
#TODO: Fix me!
self.Ks = m
def transform(self, u, m):
self.setModel(m)
f = np.exp(self.Ks)*self.A/(self.A+abs(u)**self.gamma)
if Utils.isScalar(self.Ks):
f[u >= 0] = np.exp(self.Ks)
else:
f[u >= 0] = np.exp(self.Ks[u >= 0])
return f
def transformDerivM(self, u, m):
self.setModel(m)
#A
# dA = np.exp(self.Ks)/(self.A+abs(u)**self.gamma) - np.exp(self.Ks)*self.A/(self.A+abs(u)**self.gamma)**2
#gamma
# dgamma = -(self.A*np.exp(self.Ks)*np.log(abs(u))*abs(u)**self.gamma)/(self.A + abs(u)**self.gamma)**2
# This assumes that the the model is Ks
return Utils.sdiag(self.transform(u, m))
def transformDerivU(self, u, m):
self.setModel(m)
g = -(np.exp(self.Ks)*self.A*self.gamma*abs(u)**(self.gamma-1)*np.sign(u))/((self.A+abs(u)**self.gamma)**2)
g[u >= 0] = 0
g = Utils.sdiag(g)
return g
class Haverkamp(RichardsMap):
"""Haverkamp Model"""
alpha = _ModelProperty('alpha', ['thetaModel'], default=1.6110e+06)
beta = _ModelProperty('beta', ['thetaModel'], default=3.96)
theta_r = _ModelProperty('theta_r', ['thetaModel'], default=0.075)
theta_s = _ModelProperty('theta_s', ['thetaModel'], default=0.287)
Ks = _ModelProperty('Ks', ['kModel'], default=np.log(24.96))
A = _ModelProperty('A', ['kModel'], default=1.1750e+06)
gamma = _ModelProperty('gamma', ['kModel'], default=4.74)
def __init__(self, mesh, **kwargs):
RichardsMap.__init__(self, mesh,
_haverkamp_theta(mesh),
_haverkamp_k(mesh))
Utils.setKwargs(self, **kwargs)
class _vangenuchten_theta(NonLinearMap):
theta_s = 0.430
theta_r = 0.078
alpha = 0.036
n = 1.560
def __init__(self, mesh, **kwargs):
NonLinearMap.__init__(self, mesh)
Utils.setKwargs(self, **kwargs)
def setModel(self, m):
self._currentModel = m
def transform(self, u, m):
self.setModel(m)
m = 1 - 1.0/self.n
f = (( self.theta_s - self.theta_r )/
((1+abs(self.alpha*u)**self.n)**m) + self.theta_r)
if Utils.isScalar(self.theta_s):
f[u >= 0] = self.theta_s
else:
f[u >= 0] = self.theta_s[u >= 0]
return f
def transformDerivM(self, u, m):
self.setModel(m)
def transformDerivU(self, u, m):
g = -self.alpha*self.n*abs(self.alpha*u)**(self.n - 1)*np.sign(self.alpha*u)*(1./self.n - 1)*(self.theta_r - self.theta_s)*(abs(self.alpha*u)**self.n + 1)**(1./self.n - 2)
g[u >= 0] = 0
g = Utils.sdiag(g)
return g
class _vangenuchten_k(NonLinearMap):
I = 0.500
alpha = 0.036
n = 1.560
Ks = np.log(24.96)
def __init__(self, mesh, **kwargs):
NonLinearMap.__init__(self, mesh)
Utils.setKwargs(self, **kwargs)
def setModel(self, m):
self._currentModel = m
#TODO: Fix me!
self.Ks = m
def transform(self, u, m):
self.setModel(m)
alpha = self.alpha
I = self.I
n = self.n
Ks = self.Ks
m = 1.0 - 1.0/n
theta_e = 1.0/((1.0+abs(alpha*u)**n)**m)
f = np.exp(Ks)*theta_e**I* ( ( 1.0 - ( 1.0 - theta_e**(1.0/m) )**m )**2 )
if Utils.isScalar(self.Ks):
f[u >= 0] = np.exp(self.Ks)
else:
f[u >= 0] = np.exp(self.Ks[u >= 0])
return f
def transformDerivM(self, u, m):
self.setModel(m)
# #alpha
# # dA = I*u*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 - 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*u*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));
# #n
# # dn = 2*np.exp(Ks)*((np.log(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))*(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n))/n**2 + ((1.0/n - 1)*(((np.log(abs(alpha*u)**n + 1)*(abs(alpha*u)**n + 1)**(1.0/n - 1))/n**2 - abs(alpha*u)**n*np.log(abs(alpha*u))*(1.0/n - 1)*(abs(alpha*u)**n + 1)**(1.0/n - 2))/((1.0/n - 1)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1) + 1)) - np.log((abs(alpha*u)**n + 1)**(1.0/n - 1))/(n**2*(1.0/n - 1)**2*((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))))/(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1.0/n))*((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) - I*np.exp(Ks)*((np.log(abs(alpha*u)**n + 1)*(abs(alpha*u)**n + 1)**(1.0/n - 1))/n**2 - abs(alpha*u)**n*np.log(abs(alpha*u))*(1.0/n - 1)*(abs(alpha*u)**n + 1)**(1.0/n - 2))*((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;
# #I
# # dI = np.exp(Ks)*np.log((abs(alpha*u)**n + 1)**(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)**2;
return Utils.sdiag(self.transform(u, m)) # This assumes that the the model is Ks
def transformDerivU(self, u, m):
self.setModel(m)
alpha = self.alpha
I = self.I
n = self.n
Ks = self.Ks
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[u >= 0] = 0
g = Utils.sdiag(g)
return g
class VanGenuchten(RichardsMap):
"""vanGenuchten Model"""
theta_r = _ModelProperty('theta_r', ['thetaModel'], default=0.075)
theta_s = _ModelProperty('theta_s', ['thetaModel'], default=0.287)
alpha = _ModelProperty('alpha', ['thetaModel', 'kModel'], default=0.036)
n = _ModelProperty('n', ['thetaModel', 'kModel'], default=1.560)
Ks = _ModelProperty('Ks', ['kModel'], default=np.log(24.96))
I = _ModelProperty('I', ['kModel'], default=0.500)
def __init__(self, mesh, **kwargs):
RichardsMap.__init__(self, mesh,
_vangenuchten_theta(mesh),
_vangenuchten_k(mesh))
Utils.setKwargs(self, **kwargs)
class VanGenuchtenParams(object):
"""
The RETC code for quantifying the hydraulic functions of unsaturated soils,
Van Genuchten, M Th, Leij, F J, Yates, S R
Table 3: Average values for selected soil water retention and hydraulic
conductivity parameters for 11 major soil textural groups
according to Rawls et al. [1982]
"""
def __init__(self): pass
@property
def sand(self):
return {"theta_r": 0.020, "theta_s": 0.417, "alpha": 0.138*100., "n": 1.592, "Ks": 504.0/100./24./60./60.}
@property
def loamySand(self):
return {"theta_r": 0.035, "theta_s": 0.401, "alpha": 0.115*100., "n": 1.474, "Ks": 146.6/100./24./60./60.}
@property
def sandyLoam(self):
return {"theta_r": 0.041, "theta_s": 0.412, "alpha": 0.068*100., "n": 1.322, "Ks": 62.16/100./24./60./60.}
@property
def loam(self):
return {"theta_r": 0.027, "theta_s": 0.434, "alpha": 0.090*100., "n": 1.220, "Ks": 16.32/100./24./60./60.}
@property
def siltLoam(self):
return {"theta_r": 0.015, "theta_s": 0.486, "alpha": 0.048*100., "n": 1.211, "Ks": 31.68/100./24./60./60.}
@property
def sandyClayLoam(self):
return {"theta_r": 0.068, "theta_s": 0.330, "alpha": 0.036*100., "n": 1.250, "Ks": 10.32/100./24./60./60.}
@property
def clayLoam(self):
return {"theta_r": 0.075, "theta_s": 0.390, "alpha": 0.039*100., "n": 1.194, "Ks": 5.52/100./24./60./60.}
@property
def siltyClayLoam(self):
return {"theta_r": 0.040, "theta_s": 0.432, "alpha": 0.031*100., "n": 1.151, "Ks": 3.60/100./24./60./60.}
@property
def sandyClay(self):
return {"theta_r": 0.109, "theta_s": 0.321, "alpha": 0.034*100., "n": 1.168, "Ks": 2.88/100./24./60./60.}
@property
def siltyClay(self):
return {"theta_r": 0.056, "theta_s": 0.423, "alpha": 0.029*100., "n": 1.127, "Ks": 2.16/100./24./60./60.}
@property
def clay(self):
return {"theta_r": 0.090, "theta_s": 0.385, "alpha": 0.027*100., "n": 1.131, "Ks": 1.44/100./24./60./60.}
# From: INDIRECT METHODS FOR ESTIMATING THE HYDRAULIC PROPERTIES OF UNSATURATED SOILS
# @property
# def siltLoamGE3(self):
# """Soil Index: 3310"""
# return {"theta_r": 0.139, "theta_s": 0.394, "alpha": 0.00414, "n": 2.15}
# @property
# def yoloLightClayK_WC(self):
# """Soil Index: None"""
# return {"theta_r": 0.205, "theta_s": 0.499, "alpha": 0.02793, "n": 1.71}
# @property
# def yoloLightClayK_H(self):
# """Soil Index: None"""
# return {"theta_r": 0.205, "theta_s": 0.499, "alpha": 0.02793, "n": 1.71}
# @property
# def hygieneSandstone(self):
# """Soil Index: 4130"""
# return {"theta_r": 0.000, "theta_s": 0.256, "alpha": 0.00562, "n": 3.27}
# @property
# def lambcrgClay(self):
# """Soil Index: 1003"""
# return {"theta_r": 0.000, "theta_s": 0.502, "alpha": 0.140, "n": 1.93}
# @property
# def beitNetofaClaySoil(self):
# """Soil Index: 1006"""
# return {"theta_r": 0.000, "theta_s": 0.447, "alpha": 0.00156, "n": 1.17}
# @property
# def shiohotSiltyClay(self):
# """Soil Index: 1101"""
# return {"theta_r": 0.000, "theta_s": 0.456, "alpha": 183, "n":1.17}
# @property
# def siltColumbia(self):
# """Soil Index: 2001"""
# return {"theta_r": 0.146, "theta_s": 0.397, "alpha": 0.0145, "n": 1.85}
# @property
# def siltMontCenis(self):
# """Soil Index: 2002"""
# return {"theta_r": 0.000, "theta_s": 0.425, "alpha": 0.0103, "n": 1.34}
# @property
# def slateDust(self):
# """Soil Index: 2004"""
# return {"theta_r": 0.000, "theta_s": 0.498, "alpha": 0.00981, "n": 6.75}
# @property
# def weldSiltyClayLoam(self):
# """Soil Index: 3001"""
# return {"theta_r": 0.159, "theta_s": 0.496, "alpha": 0.0136, "n": 5.45}
# @property
# def rideauClayLoam_Wetting(self):
# """Soil Index: 3101a"""
# return {"theta_r": 0.279, "theta_s": 0.419, "alpha": 0.0661, "n": 1.89}
# @property
# def rideauClayLoam_Drying(self):
# """Soil Index: 3101b"""
# return {"theta_r": 0.290, "theta_s": 0.419, "alpha": 0.0177, "n": 3.18}
# @property
# def caribouSiltLoam_Drying(self):
# """Soil Index: 3301a"""
# return {"theta_r": 0.000, "theta_s": 0.451, "alpha": 0.00845, "n": 1.29}
# @property
# def caribouSiltLoam_Wetting(self):
# """Soil Index: 3301b"""
# return {"theta_r": 0.000, "theta_s": 0.450, "alpha": 0.140, "n": 1.09}
# @property
# def grenvilleSiltLoam_Wetting(self):
# """Soil Index: 3302a"""
# return {"theta_r": 0.013, "theta_s": 0523, "alpha": 0.0630, "n": 1.24}
# @property
# def grenvilleSiltLoam_Drying(self):
# """Soil Index: 3302c"""
# return {"theta_r": 0.000, "theta_s": 0.488, "alpha": 0.0112, "n": 1.23}
# @property
# def touchetSiltLoam(self):
# """Soil Index: 3304"""
# return {"theta_r": 0.183, "theta_s": 0.498, "alpha": 0.0104, "n": 5.78}
# @property
# def gilatLoam(self):
# """Soil Index: 3402a"""
# return {"theta_r": 0.000, "theta_s": 0.454, "alpha": 0.0291, "n": 1.47}
# @property
# def pachapaLoam(self):
# """Soil Index: 3403"""
# return {"theta_r": 0.000, "theta_s": 0.472, "alpha": 0.00829, "n": 1.62}
# @property
# def adelantoLoam(self):
# """Soil Index: 3404"""
# return {"theta_r": 0.000, "theta_s": 0.444, "alpha": 0.00710, "n": 1.26}
# @property
# def indioLoam(self):
# """Soil Index: 3405a"""
# return {"theta_r": 0.000, "theta_s": 0.507, "alpha": 0.00847, "n": 1.60}
# @property
# def guclphLoam(self):
# """Soil Index: 3407a"""
# return {"theta_r": 0.000, "theta_s": 0.563, "alpha": 0.0275, "n": 1.27}
# @property
# def guclphLoam(self):
# """Soil Index: 3407b"""
# return {"theta_r": 0.236, "theta_s": 0.435, "alpha": 0.0271, "n": 262}
# @property
# def rubiconSandyLoam(self):
# """Soil Index: 3501a"""
# return {"theta_r": 0.000, "theta_s": 0.393, "alpha": 0.00972, "n": 2.18}
# @property
# def rubiconSandyLoam(self):
# """Soil Index: 350lb"""
# return {"theta_r": 0.000, "theta_s": 0.433, "alpha": 0.147, "n": 1.28}
# @property
# def pachapaFmeSandyClay(self):
# """Soil Index: 3503a"""
# return {"theta_r": 0.000, "theta_s": 0.340, "alpha": 0.0194, "n": 1.45}
# @property
# def gilatSandyLoam(self):
# """Soil Index: 3504"""
# return {"theta_r": 0.000, "theta_s": 0.432, "alpha": 0.0103, "n": 1.48}
# @property
# def plainfieldSand_210to250(self):
# """Soil Index: 4101a"""
# return {"theta_r": 0.000, "theta_s": 0.351, "alpha": 0.0236, "n": 12.30}
# @property
# def plainfieldSand_210to250(self):
# """Soil Index: 4101b"""
# return {"theta_r": 0.000, "theta_s": 0.312, "alpha": 0.0387, "n": 4.48}
# @property
# def plainfieldSand_177to210(self):
# """Soil Index: 4102a"""
# return {"theta_r": 0.000, "theta_s": 0.361, "alpha": 0.0207, "n": 10.0}
# @property
# def plainfieldSand_177to210(self):
# """Soil Index: 4102b"""
# return {"theta_r": 0.022, "theta_s": 0.309, "alpha": 0.0328, "n": 6.23}
# @property
# def plainfieldSand_149to177(self):
# """Soil Index: 4103a"""
# return {"theta_r": 0.000, "theta_s": 0.387, "alpha": 0.0173, "n": 7.80}
# @property
# def plainfieldSand_149to177(self):
# """Soil Index: 4103b"""
# return {"theta_r": 0.025, "theta_s": 0.321, "alpha": 0.0272, "n": 6.69}
# @property
# def plainfieldSand_l25to149(self):
# """Soil Index: 4104a"""
# return {"theta_r": 0.000, "theta_s": 03770, "alpha": 0.0145, "n": 10.60}
# @property
# def plainfieldSand_125to149(self):
# """Soil Index: 4104b"""
# return {"theta_r": 0.000, "theta_s": 0.342, "alpha": 0.0230, "n": 5.18}
if __name__ == '__main__':
import matplotlib.pyplot as plt
M = Mesh.TensorMesh([10])
VGparams = VanGenuchtenParams()
leg = []
for p in dir(VGparams):
if p[0] == '_': continue
leg += [p]
params = getattr(VGparams, p)
model = VanGenuchten(M, **params)
ks = np.log(np.r_[params['Ks']])
model.plot(ks)
plt.legend(leg)
plt.show()
+304
View File
@@ -0,0 +1,304 @@
from SimPEG import *
from Empirical import RichardsMap
import time
class RichardsRx(Survey.BaseTimeRx):
"""Richards Receiver Object"""
knownRxTypes = ['saturation','pressureHead']
def projectFields(self, U, m, mapping, mesh, timeMesh):
if self.rxType == 'pressureHead':
u = np.concatenate(U)
elif self.rxType == 'saturation':
u = np.concatenate([mapping.theta(ui, m) for ui in U])
return self.getP(mesh, timeMesh) * u
def projectFieldsDeriv(self, U, m, mapping, mesh, timeMesh):
P = self.getP(mesh, timeMesh)
if self.rxType == 'pressureHead':
return P
elif self.rxType == 'saturation':
#TODO: if m is a parameter in the theta
# distribution, we may need to do
# some more chain rule here.
dT = sp.block_diag([mapping.thetaDerivU(ui, m) for ui in U])
return P*dT
class RichardsSurvey(Survey.BaseSurvey):
"""docstring for RichardsSurvey"""
rxList = None
def __init__(self, rxList, **kwargs):
self.rxList = rxList
Survey.BaseSurvey.__init__(self, **kwargs)
@property
def nD(self):
return np.array([rx.nD for rx in self.rxList]).sum()
@Utils.count
@Utils.requires('prob')
def dpred(self, m, u=None):
"""
Create the projected data from a model.
The field, u, (if provided) will be used for the predicted data
instead of recalculating the fields (which may be expensive!).
.. math::
d_\\text{pred} = P(u(m), m)
Where P is a projection of the fields onto the data space.
"""
if u is None: u = self.prob.fields(m)
return Utils.mkvc(self.projectFields(u, m))
@Utils.requires('prob')
def projectFields(self, U, m):
Ds = range(len(self.rxList))
for ii, rx in enumerate(self.rxList):
Ds[ii] = rx.projectFields(U, m,
self.prob.mapping,
self.prob.mesh,
self.prob.timeMesh)
return np.concatenate(Ds)
@Utils.requires('prob')
def projectFieldsDeriv(self, U, m):
"""The Derivative with respect to the fields."""
Ds = range(len(self.rxList))
for ii, rx in enumerate(self.rxList):
Ds[ii] = rx.projectFieldsDeriv(U, m,
self.prob.mapping,
self.prob.mesh,
self.prob.timeMesh)
return sp.vstack(Ds)
class RichardsProblem(Problem.BaseTimeProblem):
"""docstring for RichardsProblem"""
boundaryConditions = None
initialConditions = None
surveyPair = RichardsSurvey
mapPair = RichardsMap
debug=True
Solver = Solver
solverOpts = {}
def __init__(self, mesh, mapping=None, **kwargs):
Problem.BaseTimeProblem.__init__(self, mesh, mapping=mapping, **kwargs)
def getBoundaryConditions(self, ii, u_ii):
if type(self.boundaryConditions) is np.ndarray:
return self.boundaryConditions
time = self.timeMesh.vectorCCx[ii]
return self.boundaryConditions(time, u_ii)
@property
def method(self):
"""Method must be either 'mixed' or 'head'. See notes in Celia et al., 1990."""
return getattr(self, '_method', 'mixed')
@method.setter
def method(self, value):
assert value in ['mixed','head'], "method must be 'mixed' or 'head'."
self._method = value
# Setting doNewton will clear the rootFinder, which will be reinitialized when called
doNewton = Utils.dependentProperty('_doNewton', False, ['_rootFinder'],
"Do a Newton iteration. If False, a Picard iteration will be completed.")
maxIterRootFinder = Utils.dependentProperty('_maxIterRootFinder', 30, ['_rootFinder'],
"Maximum iterations for rootFinder iteration.")
tolRootFinder = Utils.dependentProperty('_tolRootFinder', 1e-4, ['_rootFinder'],
"Maximum iterations for rootFinder iteration.")
@property
def rootFinder(self):
"""Root-finding Algorithm"""
if getattr(self, '_rootFinder', None) is None:
self._rootFinder = Optimization.NewtonRoot(doLS=self.doNewton, maxIter=self.maxIterRootFinder, tol=self.tolRootFinder, Solver=self.Solver)
return self._rootFinder
@Utils.timeIt
def fields(self, m):
tic = time.time()
u = range(self.nT+1)
u[0] = self.initialConditions
for ii, dt in enumerate(self.timeSteps):
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])
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
@Utils.timeIt
def diagsJacobian(self, m, hn, hn1, dt, bc):
DIV = self.mesh.faceDiv
GRAD = self.mesh.cellGrad
BC = self.mesh.cellGradBC
AV = self.mesh.aveF2CC.T
if self.mesh.dim == 1:
Dz = self.mesh.faceDivx
elif self.mesh.dim == 2:
Dz = sp.hstack((Utils.spzeros(self.mesh.nC,self.mesh.vnF[0]), self.mesh.faceDivy),format='csr')
elif self.mesh.dim == 3:
Dz = sp.hstack((Utils.spzeros(self.mesh.nC,self.mesh.vnF[0]+self.mesh.vnF[1]), self.mesh.faceDivz),format='csr')
dT = self.mapping.thetaDerivU(hn, m)
dT1 = self.mapping.thetaDerivU(hn1, m)
K1 = self.mapping.k(hn1, m)
dK1 = self.mapping.kDerivU(hn1, m)
dKm1 = self.mapping.kDerivM(hn1, m)
# Compute part of the derivative of:
#
# DIV*diag(GRAD*hn1+BC*bc)*(AV*(1.0/K))^-1
DdiagGh1 = DIV*Utils.sdiag(GRAD*hn1+BC*bc)
diagAVk2_AVdiagK2 = Utils.sdiag((AV*(1./K1))**(-2)) * AV*Utils.sdiag(K1**(-2))
# The matrix that we are computing has the form:
#
# - - - - - -
# | Adiag | | h1 | | b1 |
# | Asub Adiag | | h2 | | b2 |
# | Asub Adiag | | h3 | = | b3 |
# | ... ... | | .. | | .. |
# | Asub Adiag | | hn | | bn |
# - - - - - -
Asub = (-1.0/dt)*dT
Adiag = (
(1.0/dt)*dT1
-DdiagGh1*diagAVk2_AVdiagK2*dK1
-DIV*Utils.sdiag(1./(AV*(1./K1)))*GRAD
-Dz*diagAVk2_AVdiagK2*dK1
)
B = DdiagGh1*diagAVk2_AVdiagK2*dKm1 + Dz*diagAVk2_AVdiagK2*dKm1
return Asub, Adiag, B
@Utils.timeIt
def getResidual(self, m, hn, h, dt, bc, return_g=True):
"""
Where h is the proposed value for the next time iterate (h_{n+1})
"""
DIV = self.mesh.faceDiv
GRAD = self.mesh.cellGrad
BC = self.mesh.cellGradBC
AV = self.mesh.aveF2CC.T
if self.mesh.dim == 1:
Dz = self.mesh.faceDivx
elif self.mesh.dim == 2:
Dz = sp.hstack((Utils.spzeros(self.mesh.nC,self.mesh.vnF[0]), self.mesh.faceDivy),format='csr')
elif self.mesh.dim == 3:
Dz = sp.hstack((Utils.spzeros(self.mesh.nC,self.mesh.vnF[0]+self.mesh.vnF[1]), self.mesh.faceDivz),format='csr')
T = self.mapping.theta(h, m)
dT = self.mapping.thetaDerivU(h, m)
Tn = self.mapping.theta(hn, m)
K = self.mapping.k(h, m)
dK = self.mapping.kDerivU(h, m)
aveK = 1./(AV*(1./K))
RHS = DIV*Utils.sdiag(aveK)*(GRAD*h+BC*bc) + Dz*aveK
if self.method == 'mixed':
r = (T-Tn)/dt - RHS
elif self.method == 'head':
r = dT*(h - hn)/dt - RHS
if not return_g: return r
J = dT/dt - DIV*Utils.sdiag(aveK)*GRAD
if self.doNewton:
DDharmAve = Utils.sdiag(aveK**2)*AV*Utils.sdiag(K**(-2)) * dK
J = J - DIV*Utils.sdiag(GRAD*h + BC*bc)*DDharmAve - Dz*DDharmAve
return r, J
@Utils.timeIt
def Jfull(self, m, u=None):
if u is None:
u = self.fields(m)
nn = len(u)-1
Asubs, Adiags, Bs = range(nn), range(nn), range(nn)
for ii in range(nn):
dt = self.timeSteps[ii]
bc = self.getBoundaryConditions(ii, u[ii])
Asubs[ii], Adiags[ii], Bs[ii] = self.diagsJacobian(m, u[ii], u[ii+1], dt, bc)
Ad = sp.block_diag(Adiags)
zRight = Utils.spzeros((len(Asubs)-1)*Asubs[0].shape[0],Adiags[0].shape[1])
zTop = Utils.spzeros(Adiags[0].shape[0], len(Adiags)*Adiags[0].shape[1])
As = sp.vstack((zTop,sp.hstack((sp.block_diag(Asubs[1:]),zRight))))
A = As + Ad
B = np.array(sp.vstack(Bs).todense())
Ainv = self.Solver(A, **self.solverOpts)
P = self.survey.projectFieldsDeriv(u, m)
AinvB = Ainv * B
z = np.zeros((self.mesh.nC, B.shape[1]))
zAinvB = np.vstack((z, AinvB))
J = P * zAinvB
return J
@Utils.timeIt
def Jvec(self, m, v, u=None):
if u is None:
u = self.fields(m)
JvC = range(len(u)-1) # Cell to hold each row of the long vector.
# This is done via forward substitution.
bc = self.getBoundaryConditions(0, u[0])
temp, Adiag, B = self.diagsJacobian(m, u[0], u[1], self.timeSteps[0], bc)
Adiaginv = self.Solver(Adiag, **self.solverOpts)
JvC[0] = Adiaginv * (B*v)
for ii in range(1,len(u)-1):
bc = self.getBoundaryConditions(ii, u[ii])
Asub, Adiag, B = self.diagsJacobian(m, u[ii], u[ii+1], self.timeSteps[ii], bc)
Adiaginv = self.Solver(Adiag, **self.solverOpts)
JvC[ii] = Adiaginv * (B*v - Asub*JvC[ii-1])
P = self.survey.projectFieldsDeriv(u, m)
return P * np.concatenate([np.zeros(self.mesh.nC)] + JvC)
@Utils.timeIt
def Jtvec(self, m, v, u=None):
if u is None:
u = self.field(m)
P = self.survey.projectFieldsDeriv(u, m)
PTv = P.T*v
# This is done via backward substitution.
minus = 0
BJtv = 0
for ii in range(len(u)-1,0,-1):
bc = self.getBoundaryConditions(ii-1, u[ii-1])
Asub, Adiag, B = self.diagsJacobian(m, u[ii-1], u[ii], self.timeSteps[ii-1], bc)
#select the correct part of v
vpart = range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0])
AdiaginvT = self.Solver(Adiag.T, **self.solverOpts)
JTvC = AdiaginvT * (PTv[vpart] - minus)
minus = Asub.T*JTvC # this is now the super diagonal.
BJtv = BJtv + B.T*JTvC
return BJtv
+2
View File
@@ -0,0 +1,2 @@
import Empirical
from RichardsProblem import *
+1
View File
@@ -0,0 +1 @@
import Richards
+313 -11
View File
@@ -1,7 +1,9 @@
import Utils, numpy as np, scipy.sparse as sp
from scipy.sparse.linalg import LinearOperator
from Tests import checkDerivative
from PropMaps import PropMap, Property
from numpy.polynomial import polynomial
from scipy.interpolate import UnivariateSpline
class IdentityMap(object):
"""
@@ -289,7 +291,7 @@ class FullMap(IdentityMap):
"""
FullMap
Given a scalar, the FullMap maps the value to the
Given a scalar, the FullMap maps the value to the
full model space.
"""
@@ -314,8 +316,8 @@ class FullMap(IdentityMap):
:rtype: numpy.array
:return: derivative of transformed model
"""
return np.ones([self.mesh.nC,1])
return np.ones([self.mesh.nC,1])
class Vertical1DMap(IdentityMap):
"""Vertical1DMap
@@ -469,11 +471,11 @@ class ActiveCells(IdentityMap):
self.indActive = indActive
self.indInactive = np.logical_not(indActive)
if Utils.isScalar(valInactive):
valInactive = np.ones(self.nC)*float(valInactive)
valInactive[self.indActive] = 0
self.valInactive = valInactive
self.valInactive = np.ones(self.nC)*float(valInactive)
else:
self.valInactive = valInactive.copy()
self.valInactive[self.indActive] = 0
inds = np.nonzero(self.indActive)[0]
self.P = sp.csr_matrix((np.ones(inds.size),(inds, range(inds.size))), shape=(self.nC, self.nP))
@@ -639,7 +641,7 @@ class ComplexMap(IdentityMap):
return v[:nC] + v[nC:]*1j
def adj(v):
return np.r_[v.real,v.imag]
return Utils.SimPEGLinearOperator(shp,fwd,adj)
return LinearOperator(shp,matvec=fwd,rmatvec=adj)
inverse = deriv
@@ -696,4 +698,304 @@ class CircleMap(IdentityMap):
g3 = a*(-X + x)*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1)*np.sqrt((X - x)**2 + (Y - y)**2))
g4 = a*(-Y + y)*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1)*np.sqrt((X - x)**2 + (Y - y)**2))
g5 = -a*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1))
return np.c_[g1,g2,g3,g4,g5]
return sp.csr_matrix(np.c_[g1,g2,g3,g4,g5])
class PolyMap(IdentityMap):
"""PolyMap
Parameterize the model space using a polynomials in a wholespace.
..math::
y = \mathbf{V} c
Define the model as:
..math::
m = [\sigma_1, \sigma_2, c]
"""
def __init__(self, mesh, order, logSigma=True, normal='X'):
IdentityMap.__init__(self, mesh)
self.logSigma = logSigma
self.order = order
self.normal = normal
slope = 1e4
@property
def nP(self):
if np.isscalar(self.order):
nP = self.order+3
else:
nP =(self.order[0]+1)*(self.order[1]+1)+2
return nP
def _transform(self, m):
# Set model parameters
alpha = self.slope
sig1,sig2 = m[0],m[1]
c = m[2:]
if self.logSigma:
sig1, sig2 = np.exp(sig1), np.exp(sig2)
#2D
if self.mesh.dim == 2:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
if self.normal =='X':
f = polynomial.polyval(Y, c) - X
elif self.normal =='Y':
f = polynomial.polyval(X, c) - Y
else:
raise(Exception("Input for normal = X or Y or Z"))
#3D
elif self.mesh.dim == 3:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
Z = self.mesh.gridCC[:,2]
if self.normal =='X':
f = polynomial.polyval2d(Y, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - X
elif self.normal =='Y':
f = polynomial.polyval2d(X, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - Y
elif self.normal =='Z':
f = polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,self.order[1]+1))) - Z
else:
raise(Exception("Input for normal = X or Y or Z"))
else:
raise(Exception("Only supports 2D"))
return sig1+(sig2-sig1)*(np.arctan(alpha*f)/np.pi+0.5)
def deriv(self, m):
alpha = self.slope
sig1,sig2, c = m[0],m[1],m[2:]
if self.logSigma:
sig1, sig2 = np.exp(sig1), np.exp(sig2)
#2D
if self.mesh.dim == 2:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
if self.normal =='X':
f = polynomial.polyval(Y, c) - X
V = polynomial.polyvander(Y, len(c)-1)
elif self.normal =='Y':
f = polynomial.polyval(X, c) - Y
V = polynomial.polyvander(X, len(c)-1)
else:
raise(Exception("Input for normal = X or Y or Z"))
#3D
elif self.mesh.dim == 3:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
Z = self.mesh.gridCC[:,2]
if self.normal =='X':
f = polynomial.polyval2d(Y, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - X
V = polynomial.polyvander2d(Y, Z, self.order)
elif self.normal =='Y':
f = polynomial.polyval2d(X, Z, c.reshape((self.order[0]+1,self.order[1]+1))) - Y
V = polynomial.polyvander2d(X, Z, self.order)
elif self.normal =='Z':
f = polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,self.order[1]+1))) - Z
V = polynomial.polyvander2d(X, Y, self.order)
else:
raise(Exception("Input for normal = X or Y or Z"))
if self.logSigma:
g1 = -(np.arctan(alpha*f)/np.pi + 0.5)*sig1 + sig1
g2 = (np.arctan(alpha*f)/np.pi + 0.5)*sig2
else:
g1 = -(np.arctan(alpha*f)/np.pi + 0.5) + 1.0
g2 = (np.arctan(alpha*f)/np.pi + 0.5)
g3 = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*V
return sp.csr_matrix(np.c_[g1,g2,g3])
class SplineMap(IdentityMap):
"""SplineMap
Parameterize the boundary of two geological units using a spline interpolation
..math::
g = f(x)-y
Define the model as:
..math::
m = [\sigma_1, \sigma_2, y]
"""
def __init__(self, mesh, pts, ptsv=None,order=3, logSigma=True, normal='X'):
IdentityMap.__init__(self, mesh)
self.logSigma = logSigma
self.order = order
self.normal = normal
self.pts= pts
self.npts = np.size(pts)
self.ptsv = ptsv
self.spl = None
slope = 1e4
@property
def nP(self):
if self.mesh.dim == 2:
return np.size(self.pts)+2
elif self.mesh.dim == 3:
return np.size(self.pts)*2+2
else:
raise(Exception("Only supports 2D and 3D"))
def _transform(self, m):
# Set model parameters
alpha = self.slope
sig1,sig2 = m[0],m[1]
c = m[2:]
if self.logSigma:
sig1, sig2 = np.exp(sig1), np.exp(sig2)
#2D
if self.mesh.dim == 2:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
self.spl = UnivariateSpline(self.pts, c, k=self.order, s=0)
if self.normal =='X':
f = self.spl(Y) - X
elif self.normal =='Y':
f = self.spl(X) - Y
else:
raise(Exception("Input for normal = X or Y or Z"))
# 3D:
# Comments:
# Make two spline functions and link them using linear interpolation.
# This is not quite direct extension of 2D to 3D case
# Using 2D interpolation is possible
elif self.mesh.dim == 3:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
Z = self.mesh.gridCC[:,2]
npts = np.size(self.pts)
if np.mod(c.size, 2):
raise(Exception("Put even points!"))
self.spl = {"splb":UnivariateSpline(self.pts, c[:npts], k=self.order, s=0),
"splt":UnivariateSpline(self.pts, c[npts:], k=self.order, s=0)}
if self.normal =='X':
zb = self.ptsv[0]
zt = self.ptsv[1]
flines = (self.spl["splt"](Y)-self.spl["splb"](Y))*(Z-zb)/(zt-zb) + self.spl["splb"](Y)
f = flines - X
# elif self.normal =='Y':
# elif self.normal =='Z':
else:
raise(Exception("Input for normal = X or Y or Z"))
else:
raise(Exception("Only supports 2D and 3D"))
return sig1+(sig2-sig1)*(np.arctan(alpha*f)/np.pi+0.5)
def deriv(self, m):
alpha = self.slope
sig1,sig2, c = m[0],m[1],m[2:]
if self.logSigma:
sig1, sig2 = np.exp(sig1), np.exp(sig2)
#2D
if self.mesh.dim == 2:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
if self.normal =='X':
f = self.spl(Y) - X
elif self.normal =='Y':
f = self.spl(X) - Y
else:
raise(Exception("Input for normal = X or Y or Z"))
#3D
elif self.mesh.dim == 3:
X = self.mesh.gridCC[:,0]
Y = self.mesh.gridCC[:,1]
Z = self.mesh.gridCC[:,2]
if self.normal =='X':
zb = self.ptsv[0]
zt = self.ptsv[1]
flines = (self.spl["splt"](Y)-self.spl["splb"](Y))*(Z-zb)/(zt-zb) + self.spl["splb"](Y)
f = flines - X
# elif self.normal =='Y':
# elif self.normal =='Z':
else:
raise(Exception("Not Implemented for Y and Z, your turn :)"))
if self.logSigma:
g1 = -(np.arctan(alpha*f)/np.pi + 0.5)*sig1 + sig1
g2 = (np.arctan(alpha*f)/np.pi + 0.5)*sig2
else:
g1 = -(np.arctan(alpha*f)/np.pi + 0.5) + 1.0
g2 = (np.arctan(alpha*f)/np.pi + 0.5)
if self.mesh.dim ==2:
g3 = np.zeros((self.mesh.nC, self.npts))
if self.normal =='Y':
# Here we use perturbation to compute sensitivity
# TODO: bit more generalization of this ...
# Modfications for X and Z directions ...
for i in range(np.size(self.pts)):
ctemp = c[i]
ind = np.argmin(abs(self.mesh.vectorCCy-ctemp))
ca = c.copy()
cb = c.copy()
dy = self.mesh.hy[ind]*1.5
ca[i] = ctemp+dy
cb[i] = ctemp-dy
spla = UnivariateSpline(self.pts, ca, k=self.order, s=0)
splb = UnivariateSpline(self.pts, cb, k=self.order, s=0)
fderiv = (spla(X)-splb(X))/(2*dy)
g3[:,i] = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*fderiv
elif self.mesh.dim==3:
g3 = np.zeros((self.mesh.nC, self.npts*2))
if self.normal =='X':
# Here we use perturbation to compute sensitivity
for i in range(self.npts*2):
ctemp = c[i]
ind = np.argmin(abs(self.mesh.vectorCCy-ctemp))
ca = c.copy()
cb = c.copy()
dy = self.mesh.hy[ind]*1.5
ca[i] = ctemp+dy
cb[i] = ctemp-dy
#treat bottom boundary
if i< self.npts:
splba = UnivariateSpline(self.pts, ca[:self.npts], k=self.order, s=0)
splbb = UnivariateSpline(self.pts, cb[:self.npts], k=self.order, s=0)
flinesa = (self.spl["splt"](Y)-splba(Y))*(Z-zb)/(zt-zb) + splba(Y) - X
flinesb = (self.spl["splt"](Y)-splbb(Y))*(Z-zb)/(zt-zb) + splbb(Y) - X
#treat top boundary
else:
splta = UnivariateSpline(self.pts, ca[self.npts:], k=self.order, s=0)
spltb = UnivariateSpline(self.pts, ca[self.npts:], k=self.order, s=0)
flinesa = (self.spl["splt"](Y)-splta(Y))*(Z-zb)/(zt-zb) + splta(Y) - X
flinesb = (self.spl["splt"](Y)-spltb(Y))*(Z-zb)/(zt-zb) + spltb(Y) - X
fderiv = (flinesa-flinesb)/(2*dy)
g3[:,i] = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*fderiv
else :
raise(Exception("Not Implemented for Y and Z, your turn :)"))
return sp.csr_matrix(np.c_[g1,g2,g3])
+2 -1
View File
@@ -27,6 +27,7 @@ class BaseMesh(object):
# Ensure x0 & n are 1D vectors
self._n = np.array(n, dtype=int).ravel()
self._x0 = np.array(x0, dtype=float).ravel()
self._dim = len(self._x0)
@property
def x0(self):
@@ -46,7 +47,7 @@ class BaseMesh(object):
:rtype: int
:return: dim
"""
return len(self._n)
return self._dim
@property
def nC(self):
+2 -2
View File
@@ -2,12 +2,12 @@ import numpy as np
import scipy.sparse as sp
from scipy.constants import pi
from SimPEG.Utils import mkvc, ndgrid, sdiag, kron3, speye, spzeros, ddx, av, avExtrap
from TensorMesh import BaseTensorMesh
from TensorMesh import BaseTensorMesh, BaseRectangularMesh
from InnerProducts import InnerProducts
from View import CylView
class CylMesh(BaseTensorMesh, InnerProducts, CylView):
class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView):
"""
CylMesh is a mesh class for cylindrical problems
+27 -24
View File
@@ -1,10 +1,10 @@
from SimPEG import Utils, np, sp
from BaseMesh import BaseRectangularMesh
from BaseMesh import BaseMesh, BaseRectangularMesh
from View import TensorView
from DiffOperators import DiffOperators
from InnerProducts import InnerProducts
class BaseTensorMesh(BaseRectangularMesh):
class BaseTensorMesh(BaseMesh):
__metaclass__ = Utils.SimPEGMetaClass
@@ -42,7 +42,10 @@ class BaseTensorMesh(BaseRectangularMesh):
else:
raise Exception("x0[%i] must be a scalar or '0' to be zero, 'C' to center, or 'N' to be negative." % i)
BaseRectangularMesh.__init__(self, np.array([x.size for x in h]), x0)
if isinstance(self, BaseRectangularMesh):
BaseRectangularMesh.__init__(self, np.array([x.size for x in h]), x0)
else:
BaseMesh.__init__(self, np.array([x.size for x in h]), x0)
# Ensure h contains 1D vectors
self._h = [Utils.mkvc(x.astype(float)) for x in h]
@@ -356,7 +359,7 @@ class BaseTensorMesh(BaseRectangularMesh):
class TensorMesh(BaseTensorMesh, TensorView, DiffOperators, InnerProducts):
class TensorMesh(BaseTensorMesh, BaseRectangularMesh, TensorView, DiffOperators, InnerProducts):
"""
TensorMesh is a mesh class that deals with tensor product meshes.
@@ -413,34 +416,34 @@ class TensorMesh(BaseTensorMesh, TensorView, DiffOperators, InnerProducts):
break
if n == 1:
outStr = outStr + ' {0:.2f},'.format(h)
outStr += ' {0:.2f},'.format(h)
else:
outStr = outStr + ' {0:d}*{1:.2f},'.format(n,h)
outStr += ' {0:d}*{1:.2f},'.format(n,h)
return outStr[:-1]
if self.dim == 1:
outStr = outStr + '\n x0: {0:.2f}'.format(self.x0[0])
outStr = outStr + '\n nCx: {0:d}'.format(self.nCx)
outStr = outStr + printH(self.hx, outStr='\n hx:')
outStr += '\n x0: {0:.2f}'.format(self.x0[0])
outStr += '\n nCx: {0:d}'.format(self.nCx)
outStr += printH(self.hx, outStr='\n hx:')
pass
elif self.dim == 2:
outStr = outStr + '\n x0: {0:.2f}'.format(self.x0[0])
outStr = outStr + '\n y0: {0:.2f}'.format(self.x0[1])
outStr = outStr + '\n nCx: {0:d}'.format(self.nCx)
outStr = outStr + '\n nCy: {0:d}'.format(self.nCy)
outStr = outStr + printH(self.hx, outStr='\n hx:')
outStr = outStr + printH(self.hy, outStr='\n hy:')
outStr += '\n x0: {0:.2f}'.format(self.x0[0])
outStr += '\n y0: {0:.2f}'.format(self.x0[1])
outStr += '\n nCx: {0:d}'.format(self.nCx)
outStr += '\n nCy: {0:d}'.format(self.nCy)
outStr += printH(self.hx, outStr='\n hx:')
outStr += printH(self.hy, outStr='\n hy:')
elif self.dim == 3:
outStr = outStr + '\n x0: {0:.2f}'.format(self.x0[0])
outStr = outStr + '\n y0: {0:.2f}'.format(self.x0[1])
outStr = outStr + '\n z0: {0:.2f}'.format(self.x0[2])
outStr = outStr + '\n nCx: {0:d}'.format(self.nCx)
outStr = outStr + '\n nCy: {0:d}'.format(self.nCy)
outStr = outStr + '\n nCz: {0:d}'.format(self.nCz)
outStr = outStr + printH(self.hx, outStr='\n hx:')
outStr = outStr + printH(self.hy, outStr='\n hy:')
outStr = outStr + printH(self.hz, outStr='\n hz:')
outStr += '\n x0: {0:.2f}'.format(self.x0[0])
outStr += '\n y0: {0:.2f}'.format(self.x0[1])
outStr += '\n z0: {0:.2f}'.format(self.x0[2])
outStr += '\n nCx: {0:d}'.format(self.nCx)
outStr += '\n nCy: {0:d}'.format(self.nCy)
outStr += '\n nCz: {0:d}'.format(self.nCz)
outStr += printH(self.hx, outStr='\n hx:')
outStr += printH(self.hy, outStr='\n hy:')
outStr += printH(self.hz, outStr='\n hz:')
return outStr
+2341 -1105
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
# from __future__ import division
# import numpy as np
# cimport numpy as np
# from libcpp.vector cimport vector
"""
The Z-order curve is generated by interleaving the bits of an offset.
See also:
https://github.com/cortesi/scurve
Aldo Cortesi <aldo@corte.si>
"""
def bitrange(long x, int width, int start, int end):
"""
Extract a bit range as an integer.
(start, end) is inclusive lower bound, exclusive upper bound.
"""
return x >> (width-end) & ((2**(end-start))-1)
def index(int dimension, int bits, int levelBits, list p, int level):
cdef long idx = 0
cdef int iwidth
cdef int i
cdef long b
cdef int bitoff
p = [_ for _ in p]
p.reverse()
iwidth = bits * dimension
for i in range(iwidth):
bitoff = bits-(i/dimension)-1
poff = dimension-(i%dimension)-1
b = bitrange(p[poff], bits, bitoff, bitoff+1) << i
idx |= b
return (idx << levelBits) + level
def point(int dimension, int bits, int levelBits, long idx):
cdef list p
cdef int iwidth
cdef int i, n
cdef long b
n = idx & (2**levelBits-1)
idx = idx >> levelBits
p = [0]*dimension
iwidth = bits * dimension
for i in range(iwidth):
b = bitrange(idx, iwidth, i, i+1) << (iwidth-i-1)/dimension
p[i%dimension] |= b
p.reverse()
return p + [n]
# def _refineCell(int dimension, int bits, self, pointer):
# self._structureChange()
# pointer = self._asPointer(pointer)
# ind = self._asIndex(pointer)
# assert ind in self
# h = self._levelWidth(pointer[-1])/2 # halfWidth
# nL = pointer[-1] + 1 # new level
# add = lambda p:p[0]+p[1]
# added = []
# def addCell(p):
# i = self._index(p+[nL])
# self._treeInds.add(i)
# added.append(i)
# addCell(map(add, zip(pointer[:-1], [0,0,0])))
# addCell(map(add, zip(pointer[:-1], [h,0,0])))
# addCell(map(add, zip(pointer[:-1], [0,h,0])))
# addCell(map(add, zip(pointer[:-1], [h,h,0])))
# if self.dim == 3:
# addCell(map(add, zip(pointer[:-1], [0,0,h])))
# addCell(map(add, zip(pointer[:-1], [h,0,h])))
# addCell(map(add, zip(pointer[:-1], [0,h,h])))
# addCell(map(add, zip(pointer[:-1], [h,h,h])))
# self._treeInds.remove(ind)
# return added
+2 -1
View File
@@ -173,7 +173,7 @@ class TensorView(object):
ax=None, clim=None, showIt=False,
pcolorOpts={},
streamOpts={'color':'k'},
gridOpts={'color':'k'}
gridOpts={'color':'k', 'alpha':0.5}
):
"""
@@ -216,6 +216,7 @@ class TensorView(object):
if ind is None: ind = int(szSliceDim/2)
assert type(ind) in [int, long], 'ind must be an integer'
assert not (v.dtype == complex and view == 'vec'), 'Can not plot a complex vector.'
# The slicing and plotting code!!
def getIndSlice(v):
+1 -1
View File
@@ -367,7 +367,7 @@ class BaseSurvey(object):
"""
if getattr(self, 'dobs', None) is not None and not force:
raise Exception('Survey already has dobs.')
raise Exception('Survey already has dobs. You can use force=True to override this exception.')
self.mtrue = m
self.dtrue = self.dpred(m, u=u)
noise = std*abs(self.dtrue)*np.random.randn(*self.dtrue.shape)
@@ -4,6 +4,7 @@ from numpy.linalg import norm
from SimPEG.Utils import mkvc, sdiag, diagEst
from SimPEG import Utils
from SimPEG.Mesh import TensorMesh, CurvilinearMesh, CylMesh
from SimPEG.Mesh.TreeMesh import TreeMesh as Tree
import numpy as np
import scipy.sparse as sp
import unittest
@@ -132,6 +133,34 @@ class OrderTest(unittest.TestCase):
self.M = CurvilinearMesh([X, Y, Z])
return 1./nc
elif 'Tree' in self._meshType:
nc *= 2
if 'uniform' in self._meshType or 'notatree' in self._meshType:
h = [nc, nc, nc]
elif 'random' in self._meshType:
h1 = np.random.rand(nc)*nc*0.5 + nc*0.5
h2 = np.random.rand(nc)*nc*0.5 + nc*0.5
h3 = np.random.rand(nc)*nc*0.5 + nc*0.5
h = [hi/np.sum(hi) for hi in [h1, h2, h3]] # normalize
else:
raise Exception('Unexpected meshType')
levels = int(np.log(nc)/np.log(2))
self.M = Tree(h[:self.meshDimension], levels=levels)
def function(cell):
if 'notatree' in self._meshType:
return levels - 1
r = cell.center - np.array([0.5]*len(cell.center))
dist = np.sqrt(r.dot(r))
if dist < 0.2:
return levels
return levels - 1
self.M.refine(function,balance=False)
self.M.number(balance=False)
# self.M.plotGrid(showIt=True)
max_h = max([np.max(hi) for hi in self.M.h])
return max_h
def getError(self):
"""For given h, generate A[h], f and A(f) and return norm of error."""
return 1.
-505
View File
@@ -1,505 +0,0 @@
from SimPEG.Mesh import TensorMesh
from SimPEG.Mesh.TreeMesh import TreeMesh, TreeFace, TreeCell
import numpy as np
import unittest
import matplotlib.pyplot as plt
TOL = 1e-10
class TestOcTreeObjects(unittest.TestCase):
def setUp(self):
self.M = TreeMesh([2,1,1])
self.M.number()
self.Mr = TreeMesh([2,1,1])
self.Mr.children[0,0,0].refine()
self.Mr.number()
def q(s):
if s[0] == 'M':
m = self.M
s = s[1:]
else:
m = self.Mr
c = m.sortedCells[int(s[1])]
if len(s) == 2: return c
if s[2] == 'f' and len(s) == 5: return c.faceDict[s[2:]]
if s[2] == 'f': return getattr(c.faceDict[s[2:5]], 'edg' +s[5:])
if s[2] == 'e': return getattr(c,s[2:])
if s[2] == 'n': return getattr(c,'node'+s[3:])
self.q = q
def test_counts(self):
self.assertTrue(self.M.nC == 2)
self.assertTrue(self.M.nFx == 3)
self.assertTrue(self.M.nFy == 4)
self.assertTrue(self.M.nFz == 4)
self.assertTrue(self.M.nF == 11)
self.assertTrue(self.M.nEx == 8)
self.assertTrue(self.M.nEy == 6)
self.assertTrue(self.M.nEz == 6)
self.assertTrue(self.M.nE == 20)
self.assertTrue(self.M.nN == 12)
self.assertTrue(self.Mr.nC == 9)
self.assertTrue(self.Mr.nFx == 13)
self.assertTrue(self.Mr.nFy == 14)
self.assertTrue(self.Mr.nFz == 14)
self.assertTrue(self.Mr.nF == 41)
for cell in self.Mr.sortedCells:
for e in cell.edgeDict:
self.assertTrue(cell.edgeDict[e].edgeType==e[1].lower())
self.assertTrue(self.Mr.nN == 31)
self.assertTrue(self.Mr.nEx == 22)
self.assertTrue(self.Mr.nEy == 20)
self.assertTrue(self.Mr.nEz == 20)
def test_sizes(self):
q = self.q
for key in ['Mc0','Mc1']:
self.assertTrue(q(key).vol == 0.5)
self.assertTrue(q(key+'fXm').area == 1.)
self.assertTrue(q(key+'fXp').area == 1.)
self.assertTrue(q(key+'fYm').area == 0.5)
self.assertTrue(q(key+'fYp').area == 0.5)
self.assertTrue(q(key+'fZm').area == 0.5)
self.assertTrue(q(key+'fZp').area == 0.5)
def test_pointersM(self):
q = self.q
self.assertTrue(q('Mc0fXp') is q('Mc1fXm'))
self.assertTrue(q('Mc0fXpe0') is q('Mc1fXme0'))
self.assertTrue(q('Mc0fXpe1') is q('Mc1fXme1'))
self.assertTrue(q('Mc0fXpe2') is q('Mc1fXme2'))
self.assertTrue(q('Mc0fXpe3') is q('Mc1fXme3'))
self.assertTrue(q('Mc0fYp') is not q('c1fYm'))
self.assertTrue(q('Mc0fXm') is not q('c1fXm'))
# Test connectivity of shared edges
self.assertTrue(q('Mc0fZpe3') is not q('c1fZpe0'))
self.assertTrue(q('Mc0fZpe3') is not q('c1fZpe1'))
self.assertTrue(q('Mc0fZpe3') is q('Mc1fZpe2'))
self.assertTrue(q('Mc0fZpe3') is not q('c1fZpe3'))
self.assertTrue(q('Mc0fZme3') is not q('c1fZme0'))
self.assertTrue(q('Mc0fZme3') is not q('c1fZme1'))
self.assertTrue(q('Mc0fZme3') is q('Mc1fZme2'))
self.assertTrue(q('Mc0fZme3') is not q('c1fZme3'))
self.assertTrue(q('Mc0fYpe3') is not q('c1fYpe0'))
self.assertTrue(q('Mc0fYpe3') is not q('c1fYpe1'))
self.assertTrue(q('Mc0fYpe3') is q('Mc1fYpe2'))
self.assertTrue(q('Mc0fYpe3') is not q('c1fYpe3'))
self.assertTrue(q('Mc0fYme3') is not q('c1fYme0'))
self.assertTrue(q('Mc0fYme3') is not q('c1fYme1'))
self.assertTrue(q('Mc0fYme3') is q('Mc1fYme2'))
self.assertTrue(q('Mc0fYme3') is not q('c1fYme3'))
self.assertTrue(q('Mc0fZme3') is q('Mc1fXme0'))
self.assertTrue(q('Mc0fZpe3') is q('Mc1fXme1'))
self.assertTrue(q('Mc0fYme3') is q('Mc1fXme2'))
self.assertTrue(q('Mc0fYpe3') is q('Mc1fXme3'))
self.assertTrue(q('Mc0fZme3') is q('Mc0fXpe0'))
self.assertTrue(q('Mc0fZpe3') is q('Mc0fXpe1'))
self.assertTrue(q('Mc0fYme3') is q('Mc0fXpe2'))
self.assertTrue(q('Mc0fYpe3') is q('Mc0fXpe3'))
self.assertTrue(q('Mc1fZme2') is q('Mc1fXme0'))
self.assertTrue(q('Mc1fZpe2') is q('Mc1fXme1'))
self.assertTrue(q('Mc1fYme2') is q('Mc1fXme2'))
self.assertTrue(q('Mc1fYpe2') is q('Mc1fXme3'))
self.assertTrue(q('Mc1fZme2') is q('Mc0fXpe0'))
self.assertTrue(q('Mc1fZpe2') is q('Mc0fXpe1'))
self.assertTrue(q('Mc1fYme2') is q('Mc0fXpe2'))
self.assertTrue(q('Mc1fYpe2') is q('Mc0fXpe3'))
def test_nodePointers(self):
q = self.q
c0 = self.Mr.sortedCells[0]
c0n0 = c0.node0
self.assertTrue(c0n0 is q('c0n0'))
self.assertTrue(np.all(q('c0n0').center == np.r_[0,0,0.]))
self.assertTrue(q('c0n0').num == 0)
self.assertTrue(q('c0n1').num == 1)
self.assertTrue(q('c0n2').num == 4)
self.assertTrue(q('c0n3').num == 5)
self.assertTrue(q('c0n4').num == 11)
self.assertTrue(q('c0n5').num == 12)
self.assertTrue(q('c0n6').num == 14)
self.assertTrue(q('c0n7').num == 15)
def test_pointersMr(self):
q = self.q
c0 = self.Mr.sortedCells[0]
c0fXm = c0.fXm
c0eX0 = c0.eX0
c0fYme0 = c0.fYm.edge0
self.assertTrue(c0 is q('c0'))
self.assertTrue(c0fXm is q('c0fXm'))
self.assertTrue(c0eX0 is q('c0eX0'))
self.assertTrue(c0fYme0 is q('c0fYme0'))
self.assertTrue(q('c0').depth == 1)
self.assertTrue(q('c1').depth == 1)
self.assertTrue(q('c2').depth == 0)
# Make sure we know where the center of the cells are.
self.assertTrue(np.all(q('c0').center == np.r_[0.125,0.25,0.25]))
self.assertTrue(np.all(q('c1').center == np.r_[0.375,0.25,0.25]))
self.assertTrue(np.all(q('c2').center == np.r_[0.75,0.5,0.5]))
self.assertTrue(np.all(q('c3').center == np.r_[0.125,0.75,0.25]))
self.assertTrue(np.all(q('c4').center == np.r_[0.375,0.75,0.25]))
self.assertTrue(np.all(q('c5').center == np.r_[0.125,0.25,0.75]))
self.assertTrue(np.all(q('c6').center == np.r_[0.375,0.25,0.75]))
self.assertTrue(np.all(q('c7').center == np.r_[0.125,0.75,0.75]))
self.assertTrue(np.all(q('c8').center == np.r_[0.375,0.75,0.75]))
# Test X face connectivity and locations and stuff...
self.assertTrue(np.all(q('c0fXm').center == np.r_[0,0.25,0.25]))
self.assertTrue(np.all(q('c0fXp').center == np.r_[0.25,0.25,0.25]))
self.assertTrue(q('c0fXp') is q('c1fXm'))
self.assertTrue(np.all(q('c1fXp').center == np.r_[0.5,0.25,0.25]))
self.assertTrue(np.all(q('c2fXm').center == np.r_[0.5,0.5,0.5]))
self.assertTrue(q('c2fXm').branchdepth == 1)
self.assertTrue(q('c2fXm').children[0,0] is q('c1fXp'))
self.assertTrue(np.all(q('c3fXm').center == np.r_[0,0.75,0.25]))
self.assertTrue(np.all(q('c3fXp').center == np.r_[0.25,0.75,0.25]))
self.assertTrue(q('c4fXm') is q('c3fXp'))
self.assertTrue(q('c2fXm').children[1,0] is q('c4fXp'))
#Test some internal stuff (edges held by cell should be same as inside)
for key in ['Mc0', 'Mc1'] + ['c%d'%i for i in range(9)]:
self.assertTrue(q(key+'eX0') is q(key+'fZme0'))
self.assertTrue(q(key+'eX1') is q(key+'fZme1'))
self.assertTrue(q(key+'eX2') is q(key+'fZpe0'))
self.assertTrue(q(key+'eX3') is q(key+'fZpe1'))
self.assertTrue(q(key+'eX0') is q(key+'fYme0'))
self.assertTrue(q(key+'eX1') is q(key+'fYpe0'))
self.assertTrue(q(key+'eX2') is q(key+'fYme1'))
self.assertTrue(q(key+'eX3') is q(key+'fYpe1'))
self.assertTrue(q(key+'eY0') is q(key+'fXme0'))
self.assertTrue(q(key+'eY1') is q(key+'fXpe0'))
self.assertTrue(q(key+'eY2') is q(key+'fXme1'))
self.assertTrue(q(key+'eY3') is q(key+'fXpe1'))
self.assertTrue(q(key+'eY0') is q(key+'fZme2'))
self.assertTrue(q(key+'eY1') is q(key+'fZme3'))
self.assertTrue(q(key+'eY2') is q(key+'fZpe2'))
self.assertTrue(q(key+'eY3') is q(key+'fZpe3'))
self.assertTrue(q(key+'eZ0') is q(key+'fXme2'))
self.assertTrue(q(key+'eZ1') is q(key+'fXpe2'))
self.assertTrue(q(key+'eZ2') is q(key+'fXme3'))
self.assertTrue(q(key+'eZ3') is q(key+'fXpe3'))
self.assertTrue(q(key+'eZ0') is q(key+'fYme2'))
self.assertTrue(q(key+'eZ1') is q(key+'fYme3'))
self.assertTrue(q(key+'eZ2') is q(key+'fYpe2'))
self.assertTrue(q(key+'eZ3') is q(key+'fYpe3'))
#Test some edge stuff
self.assertTrue(np.all(q('c0eX0').center == np.r_[0.125,0,0]))
self.assertTrue(np.all(q('c0eX1').center == np.r_[0.125,0.5,0]))
self.assertTrue(np.all(q('c0eX2').center == np.r_[0.125,0,0.5]))
self.assertTrue(np.all(q('c0eX3').center == np.r_[0.125,0.5,0.5]))
self.assertTrue(np.all(q('c5eX0').center == np.r_[0.125,0,0.5]))
self.assertTrue(np.all(q('c5eX1').center == np.r_[0.125,0.5,0.5]))
self.assertTrue(q('c5eX0') is q('c0eX2'))
self.assertTrue(q('c5eX1') is q('c0eX3'))
self.assertTrue(np.all(q('c0eY0').center == np.r_[0,0.25,0]))
self.assertTrue(np.all(q('c0eY1').center == np.r_[0.25,0.25,0]))
self.assertTrue(np.all(q('c0eY2').center == np.r_[0,0.25,0.5]))
self.assertTrue(np.all(q('c0eY3').center == np.r_[0.25,0.25,0.5]))
self.assertTrue(np.all(q('c1eY0').center == np.r_[0.25,0.25,0]))
self.assertTrue(np.all(q('c1eY2').center == np.r_[0.25,0.25,0.5]))
self.assertTrue(q('c1eY0') is q('c0eY1'))
self.assertTrue(q('c1eY2') is q('c0eY3'))
self.assertTrue(np.all(q('c0eZ0').center == np.r_[0,0,0.25]))
self.assertTrue(np.all(q('c0eZ1').center == np.r_[0.25,0,0.25]))
self.assertTrue(np.all(q('c0eZ2').center == np.r_[0,0.5,0.25]))
self.assertTrue(np.all(q('c0eZ3').center == np.r_[0.25,0.5,0.25]))
self.assertTrue(np.all(q('c3eZ0').center == np.r_[0,0.5,0.25]))
self.assertTrue(np.all(q('c3eZ1').center == np.r_[0.25,0.5,0.25]))
self.assertTrue(q('c3eZ0') is q('c0eZ2'))
self.assertTrue(q('c3eZ1') is q('c0eZ3'))
self.assertTrue(q('c0fXp') is q('c1fXm'))
self.assertTrue(q('c0fYp') is not q('c1fYm'))
self.assertTrue(q('c0fXm') is not q('c1fXm'))
self.assertTrue(q('c1fXp') is q('c2fXm').children[0,0])
self.assertTrue(q('c1fYp') is q('c4fYm'))
self.assertTrue(q('c1fZp') is q('c6fZm'))
self.assertTrue(q('c6fXp') is q('c2fXm').children[0,1])
self.assertTrue(q('c4fXp') is q('c2fXm').children[1,0])
def test_gridCC(self):
x = np.r_[0.25,0.75]
y = np.r_[0.5,0.5]
z = np.r_[0.5,0.5]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridCC).flatten()) == 0)
x = np.r_[0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.125,0.375]
y = np.r_[0.25,0.25,0.5,0.75,0.75,0.25,0.25,0.75,0.75]
z = np.r_[0.25,0.25,0.5,0.25,0.25,0.75,0.75,0.75,0.75]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridCC).flatten()) == 0)
def test_gridN(self):
x = np.r_[0,0.5,1,0,0.5,1,0,0.5,1,0,0.5,1]
y = np.r_[0,0,0,1,1,1,0,0,0,1,1,1.]
z = np.r_[0,0,0,0,0,0,1,1,1,1,1,1.]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridN).flatten()) == 0)
x = np.r_[0,0.25,0.5,1,0,0.25,0.5,0,0.25,0.5,1,0,0.25,0.5,0,0.25,0.5,0,0.25,0.5,0,0.25,0.5,1,0,0.25,0.5,0,0.25,0.5,1]
y = np.r_[0,0,0,0,0.5,0.5,0.5,1,1,1,1,0,0,0,0.5,0.5,0.5,1,1,1,0,0,0,0,0.5,0.5,0.5,1,1,1,1]
z = np.r_[0,0,0,0,0,0,0,0,0,0,0,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,1,1,1,1,1,1,1,1,1,1,1]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridN).flatten()) == 0)
def test_gridFx(self):
x = np.r_[0.0,0.5,1.0]
y = np.r_[0.5,0.5,0.5]
z = np.r_[0.5,0.5,0.5]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridFx).flatten()) == 0)
x = np.r_[0.0,0.25,0.5,1.0,0.0,0.25,0.5,0.0,0.25,0.5,0.0,0.25,0.5]
y = np.r_[0.25,0.25,0.25,0.5,0.75,0.75,0.75,0.25,0.25,0.25,0.75,0.75,0.75]
z = np.r_[0.25,0.25,0.25,0.5,0.25,0.25,0.25,0.75,0.75,0.75,0.75,0.75,0.75]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridFx).flatten()) == 0)
def test_gridFy(self):
x = np.r_[0.25,0.75,0.25,0.75]
y = np.r_[0,0,1.,1.]
z = np.r_[0.5,0.5,0.5,0.5]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridFy).flatten()) == 0)
x = np.r_[0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.125,0.375]
y = np.r_[0,0,0,0.5,0.5,1,1,1,0,0,0.5,0.5,1,1]
z = np.r_[0.25,0.25,0.5,0.25,0.25,0.25,0.25,0.5,0.75,0.75,0.75,0.75,0.75,0.75]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridFy).flatten()) == 0)
def test_gridFz(self):
x = np.r_[0.25,0.75,0.25,0.75]
y = np.r_[0.5,0.5,0.5,0.5]
z = np.r_[0,0,1.,1.]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridFz).flatten()) == 0)
x = np.r_[0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.125,0.375,0.125,0.375,0.75,0.125,0.375]
y = np.r_[0.25,0.25,0.5,0.75,0.75,0.25,0.25,0.75,0.75,0.25,0.25,0.5,0.75,0.75]
z = np.r_[0,0,0,0,0,0.5,0.5,0.5,0.5,1,1,1,1,1]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridFz).flatten()) == 0)
def test_gridEx(self):
x = np.r_[0.25,0.75,0.25,0.75,0.25,0.75,0.25,0.75]
y = np.r_[0,0,1.,1.,0,0,1.,1.]
z = np.r_[0,0,0,0,1.,1.,1.,1.]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridEx).flatten()) == 0)
x = np.r_[0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.125,0.375,0.125,0.375,0.75,0.125,0.375,0.125,0.375,0.75]
y = np.r_[0,0,0,0.5,0.5,1,1,1,0,0,0.5,0.5,1,1,0,0,0,0.5,0.5,1,1,1]
z = np.r_[0,0,0,0,0,0,0,0,0.5,0.5,0.5,0.5,0.5,0.5,1,1,1,1,1,1,1,1]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridEx).flatten()) == 0)
def test_gridEy(self):
x = np.r_[0,0.5,1,0,0.5,1]
y = np.r_[0.5,0.5,0.5,0.5,0.5,0.5]
z = np.r_[0,0,0,1.,1.,1.]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridEy).flatten()) == 0)
x = np.r_[0,0.25,0.5,1,0,0.25,0.5,0,0.25,0.5,0,0.25,0.5,0,0.25,0.5,1,0,0.25,0.5]
y = np.r_[0.25,0.25,0.25,0.5,0.75,0.75,0.75,0.25,0.25,0.25,0.75,0.75,0.75,0.25,0.25,0.25,0.5,0.75,0.75,0.75]
z = np.r_[0,0,0,0,0,0,0,0.5,0.5,0.5,0.5,0.5,0.5,1,1,1,1,1,1,1]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridEy).flatten()) == 0)
def test_gridEz(self):
x = np.r_[0,0.5,1,0,0.5,1]
y = np.r_[0,0,0,1.,1.,1.]
z = np.r_[0.5,0.5,0.5,0.5,0.5,0.5]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.M.gridEz).flatten()) == 0)
x = np.r_[0,0.25,0.5,1,0 ,0.25,0.5,0,0.25,0.5,1,0,0.25,0.5,0 ,0.25,0.5,0 ,0.25,0.5]
y = np.r_[0,0 ,0 ,0,0.5,0.5 ,0.5,1,1 ,1 ,1,0,0 ,0 ,0.5,0.5 ,0.5,1 ,1 ,1 ]
z = np.r_[0.25,0.25,0.25,0.5,0.25,0.25,0.25,0.25,0.25,0.25,0.5,0.75,0.75,0.75,0.75,0.75,0.75,0.75,0.75,0.75]
self.assertTrue(np.linalg.norm((np.c_[x,y,z]-self.Mr.gridEz).flatten()) == 0)
class TestQuadTreeObjects(unittest.TestCase):
def setUp(self):
self.M = TreeMesh([2,1])
self.Mr = TreeMesh([2,1])
self.Mr.children[0,0].refine()
self.Mr.number()
# self.Mr.plotGrid(showIt=True)
def test_pointersM(self):
c0 = self.M.children[0,0]
c0fXm = c0.fXm
c0fXp = c0.fXp
c0fYm = c0.fYm
c0fYp = c0.fYp
c1 = self.M.children[1,0]
c1fXm = c1.fXm
c1fXp = c1.fXp
c1fYm = c1.fYm
c1fYp = c1.fYp
self.assertTrue(c0fXp is c1fXm)
self.assertTrue(c0fYp is not c1fYm)
self.assertTrue(c0fXm is not c1fXm)
self.assertTrue(c0fXm.area == 1)
self.assertTrue(c0fYm.area == 0.5)
self.assertTrue(c0.node1 is c1.node0)
self.assertTrue(c0.node3 is c1.node2)
self.assertTrue(self.M.nN == 6)
def test_pointersMr(self):
c0 = self.Mr.sortedCells[0]
c0fXm = c0.fXm
c0fXp = c0.fXp
c0fYm = c0.fYm
c0fYp = c0.fYp
c1 = self.Mr.sortedCells[1]
c1fXm = c1.fXm
c1fXp = c1.fXp
c1fYm = c1.fYm
c1fYp = c1.fYp
c2 = self.Mr.sortedCells[2]
c2fXm = c2.fXm
c2fXp = c2.fXp
c2fYm = c2.fYm
c2fYp = c2.fYp
c4 = self.Mr.sortedCells[4]
c4fXm = c4.fXm
c4fXp = c4.fXp
c4fYm = c4.fYm
c4fYp = c4.fYp
self.assertTrue(c0fXp is c1fXm)
self.assertTrue(c1fXp.node0 is c2fXm.node0)
self.assertTrue(c1fXp.node0 is c2fXm.node0)
self.assertTrue(c4fYm is c1fYp)
self.assertTrue(c4fXp.node1 is c2fXm.node1)
self.assertTrue(c4fXp.node0 is c1fYp.node1)
self.assertTrue(c0fXp.node1 is c4fYm.node0)
self.assertTrue(self.Mr.nN == 11)
self.assertTrue(np.all(c1fXp.node0.x0 == np.r_[0.5,0]))
self.assertTrue(np.all(c1fYp.node0.x0 == np.r_[0.25,0.5]))
class TestQuadTreeMesh(unittest.TestCase):
def setUp(self):
M = TreeMesh([np.ones(x) for x in [3,2]])
for ii in range(1):
M.children[ii,ii].refine()
self.M = M
M.number()
# M.plotGrid(showIt=True)
def test_MeshSizes(self):
self.assertTrue(self.M.nC==9)
self.assertTrue(self.M.nF==25)
self.assertTrue(self.M.nFx==12)
self.assertTrue(self.M.nFy==13)
self.assertTrue(self.M.nE==25)
self.assertTrue(self.M.nEx==13)
self.assertTrue(self.M.nEy==12)
def test_gridCC(self):
x = np.r_[0.25,0.75,1.5,2.5,0.25,0.75,0.5,1.5,2.5]
y = np.r_[0.25,0.25,0.5,0.5,0.75,0.75,1.5,1.5,1.5]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridCC).flatten()) == 0)
def test_gridN(self):
x = np.r_[0,0.5,1,2,3,0,0.5,1,0,0.5,1,2,3,0,1,2,3]
y = np.r_[0,0,0,0,0,.5,.5,.5,1,1,1,1,1,2,2,2,2]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridN).flatten()) == 0)
def test_gridFx(self):
x = np.r_[0.0,0.5,1.0,2.0,3.0,0.0,0.5,1.0,0.0,1.0,2.0,3.0]
y = np.r_[0.25,0.25,0.25,0.5,0.5,0.75,0.75,0.75,1.5,1.5,1.5,1.5]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridFx).flatten()) == 0)
def test_gridFy(self):
x = np.r_[0.25,0.75,1.5,2.5,0.25,0.75,0.25,0.75,1.5,2.5,0.5,1.5,2.5]
y = np.r_[0,0,0,0,0.5,0.5,1,1,1,1,2,2,2]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridFy).flatten()) == 0)
def test_gridEx(self):
x = np.r_[0.25,0.75,1.5,2.5,0.25,0.75,0.25,0.75,1.5,2.5,0.5,1.5,2.5]
y = np.r_[0,0,0,0,0.5,0.5,1,1,1,1,2,2,2]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridEx).flatten()) == 0)
def test_gridEy(self):
x = np.r_[0.0,0.5,1.0,2.0,3.0,0.0,0.5,1.0,0.0,1.0,2.0,3.0]
y = np.r_[0.25,0.25,0.25,0.5,0.5,0.75,0.75,0.75,1.5,1.5,1.5,1.5]
self.assertTrue(np.linalg.norm((np.c_[x,y]-self.M.gridEy).flatten()) == 0)
class SimpleOctreeOperatorTests(unittest.TestCase):
def setUp(self):
h1 = np.random.rand(5)
h2 = np.random.rand(7)
h3 = np.random.rand(3)
self.tM = TensorMesh([h1,h2,h3])
self.oM = TreeMesh([h1,h2,h3])
self.tM2 = TensorMesh([h1,h2])
self.oM2 = TreeMesh([h1,h2])
def test_faceDiv(self):
self.assertAlmostEqual((self.tM.faceDiv - self.oM.faceDiv).toarray().sum(), 0)
self.assertAlmostEqual((self.tM2.faceDiv - self.oM2.faceDiv).toarray().sum(), 0)
def test_nodalGrad(self):
self.assertAlmostEqual((self.tM.nodalGrad - self.oM.nodalGrad).toarray().sum(), 0)
self.assertAlmostEqual((self.tM2.nodalGrad - self.oM2.nodalGrad).toarray().sum(), 0)
def test_edgeCurl(self):
self.assertAlmostEqual((self.tM.edgeCurl - self.oM.edgeCurl).toarray().sum(), 0)
# self.assertAlmostEqual((self.tM2.edgeCurl - self.oM2.edgeCurl).toarray().sum(), 0)
def test_InnerProducts(self):
self.assertAlmostEqual((self.tM.getFaceInnerProduct() - self.oM.getFaceInnerProduct()).toarray().sum(), 0)
self.assertAlmostEqual((self.tM2.getFaceInnerProduct() - self.oM2.getFaceInnerProduct()).toarray().sum(), 0)
self.assertAlmostEqual((self.tM2.getEdgeInnerProduct() - self.oM2.getEdgeInnerProduct()).toarray().sum(), 0)
self.assertAlmostEqual((self.tM.getEdgeInnerProduct() - self.oM.getEdgeInnerProduct()).toarray().sum(), 0)
if __name__ == '__main__':
unittest.main()
-13
View File
@@ -1,13 +0,0 @@
import unittest
import sys
from SimPEG.Examples import Linear
import numpy as np
class TestLinear(unittest.TestCase):
def test_running(self):
Linear.run(100, plotIt=False)
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
+12 -3
View File
@@ -37,12 +37,20 @@ def SolverWrapD(fun, factorize=True, checkAccuracy=True, accuracyTol=1e-6):
if len(b.shape) == 1 or b.shape[1] == 1:
b = b.flatten()
# Just one RHS
if b.dtype is np.dtype('O'):
b = b.astype(type(b[0]))
if factorize:
X = self.solver.solve(b, **self.kwargs)
else:
X = fun(self.A, b, **self.kwargs)
else: # Multiple RHSs
if b.dtype is np.dtype('O'):
b = b.astype(type(b[0,0]))
X = np.empty_like(b)
for i in range(b.shape[1]):
if factorize:
X[:,i] = self.solver.solve(b[:,i])
@@ -110,9 +118,10 @@ def SolverWrapI(fun, checkAccuracy=True, accuracyTol=1e-5):
return type(fun.__name__+'_Wrapped', (object,), {"__init__": __init__, "clean": clean, "__mul__": __mul__})
Solver = SolverWrapD(sp.linalg.spsolve, factorize=False)
SolverLU = SolverWrapD(sp.linalg.splu, factorize=True)
SolverCG = SolverWrapI(sp.linalg.cg)
from scipy.sparse import linalg
Solver = SolverWrapD(linalg.spsolve, factorize=False)
SolverLU = SolverWrapD(linalg.splu, factorize=True)
SolverCG = SolverWrapI(linalg.cg)
class SolverDiag(object):
+1 -1
View File
@@ -7,4 +7,4 @@ from ipythonutils import easyAnimate as animate
from CounterUtils import *
import ModelBuilder
import SolverUtils
from coordutils import *
+1 -4
View File
@@ -3,10 +3,7 @@ import time
import numpy as np
from functools import wraps
class SimPEGMetaClass(type):
def __new__(cls, name, bases, attrs):
return super(SimPEGMetaClass, cls).__new__(cls, name, bases, attrs)
SimPEGMetaClass = type
def memProfileWrapper(towrap, *funNames):
"""
+62
View File
@@ -0,0 +1,62 @@
import numpy as np
from SimPEG.Utils import mkvc
def rotationMatrixFromNormals(v0,v1,tol=1e-20):
"""
Performs the minimum number of rotations to define a rotation from the direction indicated by the vector n0 to the direction indicated by n1.
The axis of rotation is n0 x n1
https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula
:param numpy.array v0: vector of length 3
:param numpy.array v1: vector of length 3
:param tol = 1e-20: tolerance. If the norm of the cross product between the two vectors is below this, no rotation is performed
:rtype: numpy.array, 3x3
:return: rotation matrix which rotates the frame so that n0 is aligned with n1
"""
# ensure both n0, n1 are vectors of length 1
assert len(v0) == 3, "Length of n0 should be 3"
assert len(v1) == 3, "Length of n1 should be 3"
# ensure both are true normals
n0 = v0*1./np.linalg.norm(v0)
n1 = v1*1./np.linalg.norm(v1)
n0dotn1 = n0.dot(n1)
# define the rotation axis, which is the cross product of the two vectors
rotAx = np.cross(n0,n1)
if np.linalg.norm(rotAx) < tol:
return np.eye(3,dtype=float)
rotAx *= 1./np.linalg.norm(rotAx)
cosT = n0dotn1/(np.linalg.norm(n0)*np.linalg.norm(n1))
sinT = np.sqrt(1.-n0dotn1**2)
ux = np.array([[0., -rotAx[2], rotAx[1]], [rotAx[2], 0., -rotAx[0]], [-rotAx[1], rotAx[0], 0.]],dtype=float)
return np.eye(3,dtype=float) + sinT*ux + (1.-cosT)*(ux.dot(ux))
def rotatePointsFromNormals(XYZ,n0,n1,x0=np.r_[0.,0.,0.]):
"""
rotates a grid so that the vector n0 is aligned with the vector n1
:param numpy.array n0: vector of length 3, should have norm 1
:param numpy.array n1: vector of length 3, should have norm 1
:param numpy.array x0: vector of length 3, point about which we perform the rotation
:rtype: numpy.array, 3x3
:return: rotation matrix which rotates the frame so that n0 is aligned with n1
"""
R = rotationMatrixFromNormals(n0, n1)
assert XYZ.shape[1] == 3, "Grid XYZ should be 3 wide"
assert len(x0) == 3, "x0 should have length 3"
X0 = np.ones([XYZ.shape[0],1])*mkvc(x0)
return (XYZ - X0).dot(R.T) + X0 # equivalent to (R*(XYZ - X0)).T + X0
+8 -8
View File
@@ -124,13 +124,13 @@ if not _interpCython:
ind_x1, ind_x2, wx1, wx2 = _interp_point_1D(x, locs[i, 0])
ind_y1, ind_y2, wy1, wy2 = _interp_point_1D(y, locs[i, 1])
inds += [( ind_x1, ind_y2),
( ind_x1, ind_y1),
inds += [( ind_x1, ind_y1),
( ind_x1, ind_y2),
( ind_x2, ind_y1),
( ind_x2, ind_y2)]
vals += [wx1*wy2,
wx1*wy1,
vals += [wx1*wy1,
wx1*wy2,
wx2*wy1,
wx2*wy2]
@@ -152,8 +152,8 @@ if not _interpCython:
ind_y1, ind_y2, wy1, wy2 = _interp_point_1D(y, locs[i, 1])
ind_z1, ind_z2, wz1, wz2 = _interp_point_1D(z, locs[i, 2])
inds += [( ind_x1, ind_y2, ind_z1),
( ind_x1, ind_y1, ind_z1),
inds += [( ind_x1, ind_y1, ind_z1),
( ind_x1, ind_y2, ind_z1),
( ind_x2, ind_y1, ind_z1),
( ind_x2, ind_y2, ind_z1),
( ind_x1, ind_y1, ind_z2),
@@ -161,8 +161,8 @@ if not _interpCython:
( ind_x2, ind_y1, ind_z2),
( ind_x2, ind_y2, ind_z2)]
vals += [wx1*wy2*wz1,
wx1*wy1*wz1,
vals += [wx1*wy1*wz1,
wx1*wy2*wz1,
wx2*wy1*wz1,
wx2*wy2*wz1,
wx1*wy1*wz2,
File diff suppressed because it is too large Load Diff
+7 -7
View File
@@ -71,12 +71,12 @@ def _interpmat2D(np.ndarray[np.float64_t, ndim=2] locs,
ind_x1, ind_x2, wx1, wx2 = _interp_point_1D(x, locs[i, 0])
ind_y1, ind_y2, wy1, wy2 = _interp_point_1D(y, locs[i, 1])
inds += [( ind_x1, ind_y2),
( ind_x1, ind_y1),
inds += [( ind_x1, ind_y1),
( ind_x1, ind_y2),
( ind_x2, ind_y1),
( ind_x2, ind_y2)]
vals += [wx1*wy2, wx1*wy1, wx2*wy1, wx2*wy2]
vals += [wx1*wy1, wx1*wy2, wx2*wy1, wx2*wy2]
return inds, vals
@@ -98,8 +98,8 @@ def _interpmat3D(np.ndarray[np.float64_t, ndim=2] locs,
ind_y1, ind_y2, wy1, wy2 = _interp_point_1D(y, locs[i, 1])
ind_z1, ind_z2, wz1, wz2 = _interp_point_1D(z, locs[i, 2])
inds += [( ind_x1, ind_y2, ind_z1),
( ind_x1, ind_y1, ind_z1),
inds += [( ind_x1, ind_y1, ind_z1),
( ind_x1, ind_y2, ind_z1),
( ind_x2, ind_y1, ind_z1),
( ind_x2, ind_y2, ind_z1),
( ind_x1, ind_y1, ind_z2),
@@ -107,8 +107,8 @@ def _interpmat3D(np.ndarray[np.float64_t, ndim=2] locs,
( ind_x2, ind_y1, ind_z2),
( ind_x2, ind_y2, ind_z2)]
vals += [wx1*wy2*wz1,
wx1*wy1*wz1,
vals += [wx1*wy1*wz1,
wx1*wy2*wz1,
wx2*wy1*wz1,
wx2*wy2*wz1,
wx1*wy1*wz2,
+60 -9
View File
@@ -342,10 +342,10 @@ def invPropertyTensor(M, tensor, returnMatrix=False):
def diagEst(matFun, n, k=None, approach='Probing'):
"""
"""
Estimate the diagonal of a matrix, A. Note that the matrix may be a function which returns A times a vector.
Three different approaches have been implemented,
Three different approaches have been implemented,
1. Probing : uses cyclic permutations of vectors with ones and zeros (default)
2. Ones : random +/- 1 entries
3. Random : random vectors
@@ -362,7 +362,7 @@ def diagEst(matFun, n, k=None, approach='Probing'):
if type(matFun).__name__=='ndarray':
A = matFun
matFun = lambda v: A.dot(v)
matFun = lambda v: A.dot(v)
if k is None:
k = np.floor(n/10.)
@@ -396,11 +396,62 @@ def diagEst(matFun, n, k=None, approach='Probing'):
return d
class Zero(object):
def __add__(self, v):return v
def __radd__(self, v):return v
def __iadd__(self, v):return v
def __sub__(self, v):return -v
def __rsub__(self, v):return v
def __isub__(self, v):return v
def __mul__(self, v):return self
def __rmul__(self, v):return self
def __div__(self, v): return self
def __truediv__(self, v): return self
def __rdiv__(self, v): raise ZeroDivisionError('Cannot divide by zero.')
def __pos__(self):return self
def __neg__(self):return self
def __lt__(self, v):return 0 < v
def __le__(self, v):return 0 <= v
def __eq__(self, v):return v == 0
def __ne__(self, v):return not (0 == v)
def __ge__(self, v):return 0 >= v
def __gt__(self, v):return 0 > v
class Identity(object):
_positive = True
def __init__(self, positive=True):
self._positive = positive is True
def __pos__(self):return self
def __neg__(self):return Identity(not self._positive)
def __add__(self, v):
if sp.issparse(v):
return v + speye(v.shape[0]) if self._positive else v - speye(v.shape[0])
return v + 1 if self._positive else v - 1
def __radd__(self, v):
return self.__add__(v)
def __sub__(self, v): return self+-v
def __rsub__(self, v):return -self+v
def __mul__(self, v): return v if self._positive else -v
def __rmul__(self, v):return v if self._positive else -v
def __div__(self, v):
if sp.issparse(v): raise NotImplementedError('Sparse arrays not divisibile.')
return 1/v if self._positive else -1/v
def __truediv__(self, v):
if sp.issparse(v): raise NotImplementedError('Sparse arrays not divisibile.')
return 1.0/v if self._positive else -1.0/v
def __rdiv__(self, v):
return v if self._positive else -v
def __lt__(self, v):return 1 < v if self._positive else -1 < v
def __le__(self, v):return 1 <= v if self._positive else -1 <= v
def __eq__(self, v):return v == 1 if self._positive else v == -1
def __ne__(self, v):return (not (1 == v))if self._positive else (not (-1 == v))
def __ge__(self, v):return 1 >= v if self._positive else -1 >= v
def __gt__(self, v):return 1 > v if self._positive else -1 > v
from scipy.sparse.linalg import LinearOperator
class SimPEGLinearOperator(LinearOperator):
"""Extends scipy.sparse.linalg.LinearOperator to have a .T function."""
@property
def T(self):
return self.__class__((self.shape[1],self.shape[0]),self.rmatvec,rmatvec=self.matvec,matmat=self.matmat)
+25 -25
View File
@@ -149,7 +149,7 @@ def readUBCTensorModel(fileName, mesh):
Input:
:param fileName, path to the UBC GIF mesh file to read
:param mesh, TensorMesh object, mesh that coresponds to the model
:param mesh, TensorMesh object, mesh that coresponds to the model
Output:
:return numpy array, model with TensorMesh ordered
@@ -170,7 +170,7 @@ def writeUBCTensorMesh(fileName, mesh):
:param str fileName: File to write to
:param simpeg.Mesh.TensorMesh mesh: The mesh
"""
assert mesh.dim == 3
s = ''
@@ -216,7 +216,7 @@ def readVTRFile(fileName):
Output:
:return SimPEG TensorMesh object
:return SimPEG model dictionary
"""
# Import
from vtk import vtkXMLRectilinearGridReader as vtrFileReader
@@ -324,56 +324,56 @@ def ExtractCoreMesh(xyzlim, mesh, meshType='tensor'):
Extracts Core Mesh from Global mesh
xyzlim: 2D array [ndim x 2]
mesh: SimPEG mesh
This function ouputs:
This function ouputs:
- actind: corresponding boolean index from global to core
- meshcore: core SimPEG mesh
- meshcore: core SimPEG mesh
Warning: 1D and 2D has not been tested
"""
from SimPEG import Mesh
if mesh.dim ==1:
xyzlim = xyzlim.flatten()
xmin, xmax = xyzlim[0], xyzlim[1]
xind = np.logical_and(mesh.vectorCCx>xmin, mesh.vectorCCx<xmax)
xind = np.logical_and(mesh.vectorCCx>xmin, mesh.vectorCCx<xmax)
xc = mesh.vectorCCx[xind]
hx = mesh.hx[xind]
x0 = [xc[0]-hx[0]*0.5, yc[0]-hy[0]*0.5]
meshCore = Mesh.TensorMesh([hx, hy] ,x0=x0)
actind = (mesh.gridCC[:,0]>xmin) & (mesh.gridCC[:,0]<xmax)
elif mesh.dim ==2:
xmin, xmax = xyzlim[0,0], xyzlim[0,1]
ymin, ymax = xyzlim[1,0], xyzlim[1,1]
yind = np.logical_and(mesh.vectorCCy>ymin, mesh.vectorCCy<ymax)
zind = np.logical_and(mesh.vectorCCz>zmin, mesh.vectorCCz<zmax)
zind = np.logical_and(mesh.vectorCCz>zmin, mesh.vectorCCz<zmax)
xc = mesh.vectorCCx[xind]
yc = mesh.vectorCCy[yind]
hx = mesh.hx[xind]
hy = mesh.hy[yind]
x0 = [xc[0]-hx[0]*0.5, yc[0]-hy[0]*0.5]
meshCore = Mesh.TensorMesh([hx, hy] ,x0=x0)
actind = (mesh.gridCC[:,0]>xmin) & (mesh.gridCC[:,0]<xmax) \
& (mesh.gridCC[:,1]>ymin) & (mesh.gridCC[:,1]<ymax) \
elif mesh.dim==3:
xmin, xmax = xyzlim[0,0], xyzlim[0,1]
ymin, ymax = xyzlim[1,0], xyzlim[1,1]
zmin, zmax = xyzlim[2,0], xyzlim[2,1]
xind = np.logical_and(mesh.vectorCCx>xmin, mesh.vectorCCx<xmax)
yind = np.logical_and(mesh.vectorCCy>ymin, mesh.vectorCCy<ymax)
zind = np.logical_and(mesh.vectorCCz>zmin, mesh.vectorCCz<zmax)
zind = np.logical_and(mesh.vectorCCz>zmin, mesh.vectorCCz<zmax)
xc = mesh.vectorCCx[xind]
yc = mesh.vectorCCy[yind]
@@ -382,19 +382,19 @@ def ExtractCoreMesh(xyzlim, mesh, meshType='tensor'):
hx = mesh.hx[xind]
hy = mesh.hy[yind]
hz = mesh.hz[zind]
x0 = [xc[0]-hx[0]*0.5, yc[0]-hy[0]*0.5, zc[0]-hz[0]*0.5]
meshCore = Mesh.TensorMesh([hx, hy, hz] ,x0=x0)
actind = (mesh.gridCC[:,0]>xmin) & (mesh.gridCC[:,0]<xmax) \
& (mesh.gridCC[:,1]>ymin) & (mesh.gridCC[:,1]<ymax) \
& (mesh.gridCC[:,2]>zmin) & (mesh.gridCC[:,2]<zmax)
else:
raise(Exception("Not implemented!"))
return actind, meshCore
+1 -1
View File
@@ -15,7 +15,7 @@ import Directives
import Inversion
import Tests
__version__ = '0.1.3'
__version__ = '0.1.4'
__author__ = 'Rowan Cockett'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Rowan Cockett'
Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+9 -2
View File
@@ -3,8 +3,15 @@
Examples
********
Forward problem
===============
.. toctree::
:maxdepth: 1
:glob:
examples/*
External Notebooks
==================
* `Example 1: Direct Current <http://www.seogi.me/s/notebooks/DCEx.html>`_
* `Example 2: Seismic-Acoustic <http://www.seogi.me/s/notebooks/SeismicEx.html>`_
+2 -16
View File
@@ -23,23 +23,9 @@ the implementations.
.. plot::
from SimPEG import Mesh, Utils, np
import matplotlib.pyplot as plt
sz = [10,10]
tM = Mesh.TensorMesh(sz)
qM = Mesh.TreeMesh(sz)
qM.refine(lambda X: 1 if np.sqrt(((X-0.5)**2).sum()) < 0.3 else 0)
rM = Mesh.CurvilinearMesh(Utils.meshutils.exampleLrmGrid(sz,'rotate'))
from SimPEG import Examples
Examples.Mesh_ThreeMeshes.run()
fig, axes = plt.subplots(1,3,figsize=(14,5))
opts = {}
tM.plotGrid(ax=axes[0], **opts)
axes[0].set_title('TensorMesh')
qM.plotGrid(ax=axes[1], **opts)
axes[1].set_title('TreeMesh')
rM.plotGrid(ax=axes[2], **opts)
axes[2].set_title('CurvilinearMesh')
plt.show()
Variable Locations and Terminology
+1 -1
View File
@@ -3,6 +3,6 @@
Testing SimPEG
==============
.. automodule:: SimPEG.Tests.TestUtils
.. automodule:: SimPEG.Tests
:members:
:undoc-members:
+2 -2
View File
@@ -51,9 +51,9 @@ copyright = u'2013, SimPEG Developers'
# built documents.
#
# The short X.Y version.
version = '0.1.3'
version = '0.1.4'
# The full version, including alpha/beta/rc tags.
release = '0.1.3'
release = '0.1.4'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+159
View File
@@ -0,0 +1,159 @@
.. _api_FDEM:
.. math::
\renewcommand{\div}{\nabla\cdot\,}
\newcommand{\grad}{\vec \nabla}
\newcommand{\curl}{{\vec \nabla}\times\,}
Frequency Domain Electromagnetics
*********************************
Electromagnetic (EM) geophysical methods are used in a variety of applications from resource exploration, including for hydrocarbons and minerals, to environmental applications, such as groundwater monitoring. The primary physical property of interest in EM is electrical conductivity, which describes the ease with which electric current flows through a material.
Background
==========
Electromagnetic phenomena are governed by Maxwell's equations. They describe the behavior of EM fields and fluxes. Electromagnetic theory for geophysical applications by Ward and Hohmann (1988) is a highly recommended resource on this topic.
Fourier Transform Convention
----------------------------
In order to examine Maxwell's equations in the frequency domain, we must first define our choice of harmonic time-dependence by choosing a Fourier transform convention. We use the \\(e^{i \\omega t} \\) convention, so we define our Fourier Transform pair as
.. math ::
F(\omega) = \int_{-\infty}^{\infty} f(t) e^{- i \omega t} dt \\
f(t) = \frac{1}{2\pi}\int_{-\infty}^{\infty} F(\omega) e^{i \omega t} d \omega
where \\(\\omega\\) is angular frequency, \\(t\\) is time, \\(F(\\omega)\\) is the function defined in the frequency domain and \\(f(t)\\) is the function defined in the time domain.
Maxwell's Equations
===================
In the frequency domain, Maxwell's equations are given by
.. math ::
\curl \vec{E} = - i \omega \vec{B} \\
\curl \vec{H} = \vec{J} + i \omega \vec{D} + \vec{S} \\
\div \vec{B} = 0 \\
\div \vec{D} = \rho_f
where:
- \\(\\vec{E}\\) : electric field (\\(V/m\\))
- \\(\\vec{H}\\) : magnetic field (\\(A/m\\))
- \\(\\vec{B}\\) : magnetic flux density (\\(Wb/m^2\\))
- \\(\\vec{D}\\) : electric displacement / electric flux density (\\(C/m^2\\))
- \\(\\vec{J}\\) : electric current density (\\(A/m^2\\))
- \\(\\rho_f\\) : free charge density
The source term is \\(\\vec{S}\\)
Constitutive Relations
----------------------
The fields and fluxes are related through the constitutive relations. At each frequency, they are given by
.. math ::
\vec{J} = \sigma \vec{E} \\
\vec{B} = \mu \vec{H} \\
\vec{D} = \varepsilon \vec{E}
where:
- \\(\\sigma\\) : electrical conductivity \\(S/m\\)
- \\(\\mu\\) : magnetic permeability \\(H/m\\)
- \\(\\varepsilon\\) : dielectric permittivity \\(F/m\\)
\\(\\sigma\\), \\(\\mu\\), \\(\\varepsilon\\) are physical properties which depend on the material. \\(\\sigma\\) describes how easily electric current passes through a material, \\(\\mu\\) describes how easily a material is magnetized, and \\(\\varepsilon\\) describes how easily a material is electrically polarized. In most geophysical applications of EM, \\(\\sigma\\) is the the primary physical property of interest, and \\(\\mu\\), \\(\\varepsilon\\) are assumed to have their free-space values \\(\\mu_0 = 4\\pi \\times 10^{-7} H/m \\), \\(\\varepsilon_0 = 8.85 \\times 10^{-12} F/m\\)
Quasi-static Approximation
--------------------------
For the frequency range typical of most geophysical surveys, the contribution of the electric displacement is negligible compared to the electric current density. In this case, we use the Quasi-static approximation and assume that this term can be neglected, giving
.. math ::
\nabla \times \vec{E} = -i \omega \vec{B} \\
\nabla \times \vec{H} = \vec{J} + \vec{S}
Implementation in SimPEG.EM
===========================
We consider two formulations in SimPEG.EM, both first-order and both in terms of one field and one flux. We allow for the definition of magnetic and electric sources (see for example: Ward and Hohmann, starting on page 144). The E-B formulation is in terms of the electric field and the magnetic flux:
.. math ::
\nabla \times \vec{E} + i \omega \vec{B} = \vec{S}_m \\
\nabla \times \mu^{-1} \vec{B} - \sigma \vec{E} = \vec{S}_e
The H-J formulation is in terms of the current density and the magnetic field:
.. math ::
\nabla \times \sigma^{-1} \vec{J} + i \omega \mu \vec{H} = \vec{S}_m \\
\nabla \times \vec{H} - \vec{J} = \vec{S}_e
Discretizing
------------
For both formulations, we use a finite volume discretization
and discretize fields on cell edges, fluxes on cell faces and
physical properties in cell centers. This is particularly
important when using symmetry to reduce the dimensionality of a problem
(for instance on a 2D CylMesh, there are \\(r\\), \\(z\\) faces and \\(\\theta\\) edges)
.. figure:: ../images/finitevolrealestate.png
:align: center
:scale: 60 %
For the two formulations, the discretization of the physical properties, fields and fluxes are summarized below.
.. figure:: ../images/ebjhdiscretizations.png
:align: center
:scale: 60 %
Note that resistivity is the inverse of conductivity, \\(\\rho = \\sigma^{-1}\\).
E-B Formulation:
****************
.. math ::
\mathbf{C} \mathbf{e} + i \omega \mathbf{b} = \mathbf{s_m} \\
\mathbf{C^T} \mathbf{M^f_{\mu^{-1}}} \mathbf{b} - \mathbf{M^e_\sigma} \mathbf{e} = \mathbf{M^e} \mathbf{s_e}
H-J Formulation:
****************
.. math ::
\mathbf{C^T} \mathbf{M^f_\rho} \mathbf{j} + i \omega \mathbf{M^e_\mu} \mathbf{h} = \mathbf{M^e} \mathbf{s_m} \\
\mathbf{C} \mathbf{h} - \mathbf{j} = \mathbf{s_e}
.. Forward Problem
.. ===============
.. Inverse Problem
.. ===============
API
===
.. automodule:: SimPEG.EM.FDEM.FDEM
:show-inheritance:
:members:
:undoc-members:
FDEM Survey
-----------
.. automodule:: SimPEG.EM.FDEM.SurveyFDEM
:show-inheritance:
:members:
:undoc-members:
+88
View File
@@ -0,0 +1,88 @@
.. _api_TDEM:
.. math::
\renewcommand{\div}{\nabla\cdot\,}
\newcommand{\grad}{\vec \nabla}
\newcommand{\curl}{{\vec \nabla}\times\,}
\newcommand {\J}{{\vec J}}
\renewcommand{\H}{{\vec H}}
\newcommand {\E}{{\vec E}}
\newcommand{\dcurl}{{\mathbf C}}
\newcommand{\dgrad}{{\mathbf G}}
\newcommand{\Acf}{{\mathbf A_c^f}}
\newcommand{\Ace}{{\mathbf A_c^e}}
\renewcommand{\S}{{\mathbf \Sigma}}
\newcommand{\St}{{\mathbf \Sigma_\tau}}
\newcommand{\T}{{\mathbf T}}
\newcommand{\Tt}{{\mathbf T_\tau}}
\newcommand{\diag}[1]{\,{\sf diag}\left( #1 \right)}
\newcommand{\M}{{\mathbf M}}
\newcommand{\MfMui}{{\M^f_{\mu^{-1}}}}
\newcommand{\MeSig}{{\M^e_\sigma}}
\newcommand{\MeSigInf}{{\M^e_{\sigma_\infty}}}
\newcommand{\MeSigO}{{\M^e_{\sigma_0}}}
\newcommand{\Me}{{\M^e}}
\newcommand{\Mes}[1]{{\M^e_{#1}}}
\newcommand{\Mee}{{\M^e_e}}
\newcommand{\Mej}{{\M^e_j}}
\newcommand{\BigO}[1]{\mathcal{O}\bigl(#1\bigr)}
\newcommand{\bE}{\mathbf{E}}
\newcommand{\bH}{\mathbf{H}}
\newcommand{\B}{\vec{B}}
\newcommand{\D}{\vec{D}}
\renewcommand{\H}{\vec{H}}
\newcommand{\s}{\vec{s}}
\newcommand{\bfJ}{\bf{J}}
\newcommand{\vecm}{\vec m}
\renewcommand{\Re}{\mathsf{Re}}
\renewcommand{\Im}{\mathsf{Im}}
\renewcommand {\j} { {\vec j} }
\newcommand {\h} { {\vec h} }
\renewcommand {\b} { {\vec b} }
\newcommand {\e} { {\vec e} }
\newcommand {\c} { {\vec c} }
\renewcommand {\d} { {\vec d} }
\renewcommand {\u} { {\vec u} }
\newcommand{\I}{\vec{I}}
TDEM - B formulation
====================
.. automodule:: SimPEG.EM.TDEM.TDEM_b
:show-inheritance:
:members:
:undoc-members:
Field Storage
=============
.. autoclass:: SimPEG.EM.TDEM.SurveyTDEM.FieldsTDEM
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
TDEM Survey Classes
===================
.. autoclass:: SimPEG.EM.TDEM.SurveyTDEM.SurveyTDEM
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
Base Classes
============
.. automodule:: SimPEG.EM.TDEM.BaseTDEM
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
+341
View File
@@ -0,0 +1,341 @@
.. _api_TDEM_derivation:
.. math::
\renewcommand{\div}{\nabla\cdot\,}
\newcommand{\grad}{\vec \nabla}
\newcommand{\curl}{{\vec \nabla}\times\,}
\newcommand {\J}{{\vec J}}
\renewcommand{\H}{{\vec H}}
\newcommand {\E}{{\vec E}}
\newcommand{\dcurl}{{\mathbf C}}
\newcommand{\dgrad}{{\mathbf G}}
\newcommand{\Acf}{{\mathbf A_c^f}}
\newcommand{\Ace}{{\mathbf A_c^e}}
\renewcommand{\S}{{\mathbf \Sigma}}
\newcommand{\St}{{\mathbf \Sigma_\tau}}
\newcommand{\T}{{\mathbf T}}
\newcommand{\Tt}{{\mathbf T_\tau}}
\newcommand{\diag}[1]{\,{\sf diag}\left( #1 \right)}
\newcommand{\M}{{\mathbf M}}
\newcommand{\MfMui}{{\M^f_{\mu^{-1}}}}
\newcommand{\MeSig}{{\M^e_\sigma}}
\newcommand{\MeSigInf}{{\M^e_{\sigma_\infty}}}
\newcommand{\MeSigO}{{\M^e_{\sigma_0}}}
\newcommand{\Me}{{\M^e}}
\newcommand{\Mes}[1]{{\M^e_{#1}}}
\newcommand{\Mee}{{\M^e_e}}
\newcommand{\Mej}{{\M^e_j}}
\newcommand{\BigO}[1]{\mathcal{O}\bigl(#1\bigr)}
\newcommand{\bE}{\mathbf{E}}
\newcommand{\bH}{\mathbf{H}}
\newcommand{\B}{\vec{B}}
\newcommand{\D}{\vec{D}}
\renewcommand{\H}{\vec{H}}
\newcommand{\s}{\vec{s}}
\newcommand{\bfJ}{\bf{J}}
\newcommand{\vecm}{\vec m}
\renewcommand{\Re}{\mathsf{Re}}
\renewcommand{\Im}{\mathsf{Im}}
\renewcommand {\j} { {\vec j} }
\newcommand {\h} { {\vec h} }
\renewcommand {\b} { {\vec b} }
\newcommand {\e} { {\vec e} }
\newcommand {\c} { {\vec c} }
\renewcommand {\d} { {\vec d} }
\renewcommand {\u} { {\vec u} }
\newcommand{\I}{\vec{I}}
Time-Domain EM Derivation
*************************
The following shows the derivation for the TDEM problem. We use the b-formulation below.
(More to come soon..!)
Sensitivity Calculation
=======================
.. math::
\begin{align}
\dcurl \e^{(t+1)} + \frac{\b^{(t+1)} - \b^{(t)}}{\delta t} = 0 \\
\dcurl^\top \MfMui \b^{(t+1)} - \MeSig \e^{(t+1)} = \Me \j_s^{(t+1)}
\end{align}
Using Gauss-Newton to solve the inverse problem requires the ability to calculate the product of the
Jacobian and a vector, as well as the transpose of the Jacobian times a vector.
The above system can be rewritten as:
.. math::
\begin{align}
\mathbf{A} \u^{(t+1)} + \mathbf{B} \u^{(t)}= \s^{(t+1)}
\end{align}
where
.. math::
\begin{align}
\mathbf{A} =
\left[
\begin{array}{cc}
\frac{1}{\delta t} \MfMui & \MfMui\dcurl \\
\dcurl^\top \MfMui & -\MeSig
\end{array}
\right] \\
\mathbf{B} =
\left[
\begin{array}{cc}
-\frac{1}{\delta t} \MfMui & 0 \\
0 & 0
\end{array}
\right] \\
\u^{(k)} = \left[
\begin{array}{c}
\b^{(k)}\\
\e^{(k)}
\end{array}
\right] \\
\s^{(k)} = \left[
\begin{array}{c}
0\\
\Me \j^{(k)}_s
\end{array}
\right]
\end{align}
.. note::
Here we have multiplied through by \\(\\MfMui\\) to make A and B symmetric!
The entire time dependent system can be written in a single matrix expression
.. math::
\begin{align}
\hat{\mathbf{A}} \hat{u} = \hat{s}
\end{align}
where
.. math::
\begin{align}
\mathbf{\hat{A}} = \left[
\begin{array}{cccc}
A & 0 & & \\
B & A & & \\
& \ddots & \ddots & \\
& & B & A
\end{array}
\right] \\
\hat{u} = \left[
\begin{array}{c}
\u^{(1)} \\
\u^{(2)} \\
\vdots \\
\u^{(N)}
\end{array} \right]\\
\hat{s} = \left[
\begin{array}{c}
\s^{(1)} - \mathbf{B} \u^{(0)} \\
\s^{(2)} \\
\vdots \\
\s^{(N)}
\end{array}
\right]
\end{align}
For the fields \\(\\u\\), the measured data is given by
.. math::
\begin{align}
\vec{d} = \mathbf{Q} \u
\end{align}
The sensitivity matrix **J** is then defined as
.. math::
\begin{align}
\mathbf{J} = \mathbf{Q} \frac{\partial \u}{\partial \sigma}
\end{align}
Defining the function \\(\\c(m,\\u)\\) to be
.. math::
\begin{align}
\vec{c}(m,\u) = \hat{\mathbf{A}} \vec{u} - \vec{q} = \vec{0}
\end{align}
then
.. math::
\begin{align}
\frac{\partial \vec{c}}{\partial m} \partial m
+ \frac{\partial \vec{c}}{\partial \u} \partial \vec{u} = 0
\end{align}
or
.. math::
\begin{align}
\frac{\partial \vec{u}}{\partial m} = -\left(\frac{\partial \vec{c}}{\partial \u} \right)^{-1} \frac{\partial \vec{c}}{\partial m}
\end{align}
Differentiating, we find that
.. math::
\begin{align}
\frac{\partial \vec{c}}{\partial \hat{u}} = \hat{\mathbf{A}}
\end{align}
and
.. math::
\begin{align}
\frac{\partial \vec{c}}{\partial \sigma} = \mathbf{G}_\sigma =
\left[
\begin{array}{c}
g_\sigma^{(1)}\\
g_\sigma^{(2)}\\
\vdots \\
g_\sigma^{(N)}
\end{array}
\right]
\end{align}
with
.. math::
\begin{align}
g_\sigma^{(n)} =
\left[
\begin{array}{c}
\mathbf{0} \\
- \diag{\e^{(n)}} \Ace \diag{\vec{V}}
\end{array}
\right]
\end{align}
Implementing **J** times a vector
=================================
Multiplying **J** onto a vector can be broken into three steps
* Compute \\(\\vec{p} = \\mathbf{G}m\\)
* Solve \\(\\hat{\\mathbf{A}} \\vec{y} = \\vec{p}\\)
* Compute \\(\\vec{w} = -\\mathbf{Q} \\vec{y}\\)
.. math::
\begin{align}
\vec{p}^{(n)} = \left[
\begin{array}{c}
\vec{p}_b^{(n)} \\
\vec{p}_e^{(n)}
\end{array}
\right] \\
\vec{p}_b^{(n)} = 0 \\
\vec{p}_e^{(n)} = - \diag{\e^{(n)}} \Ace \diag{V} m
\end{align}
For all time steps:
.. math::
\begin{align}
\frac{1}{\delta t} \MfMui\vec{y}_{b}^{(t+1)} + \MfMui\dcurl \vec{y}_{e}^{(t+1)}
- \frac{1}{\delta t} \MfMui \vec{y}_{b}^{(t)}
= \vec{p}_b^{(t+1)} \\
\dcurl^\top \MfMui \vec{y}_b^{(t+1)} - \MeSig \vec{y}_e^{(t+1)} = \vec{p}_e^{(t+1)}
\end{align}
and
.. math::
\begin{align}
\left( \MfMui \dcurl \MeSig^{-1} \dcurl^\top \MfMui + \frac{1}{\delta t} \MfMui \right) \vec{y}_{b}^{(t+1)} =
\frac{1}{\delta t} \MfMui \vec{y}_b^{(t)}
+ \MfMui \dcurl \MeSig^{-1} \vec{p}_e^{(t+1)} + \vec{p}_b^{(t+1)} \\
\vec{y}_e^{(t+1)} = \MeSig^{-1} \dcurl^\top \MfMui \vec{y}_b^{(t+1)} - \MeSig^{-1} \vec{p}_e^{(t+1)}
\end{align}
.. note::
For the first time step, \\\(t=0\\\), the term: \\\(\\frac{1}{\\delta t} \\MfMui \\vec{y}_b^{(0)}\\\) is zero.
Implementing **J** transpose times a vector
===========================================
Multiplying \\(\\mathbf{J}^\\top\\) onto a vector can be broken into three steps
* Compute \\(\\vec{p} = \\mathbf{Q}^\\top \\vec{v}\\)
* Solve \\(\\hat{\\mathbf{A}}^\\top \\vec{y} = \\vec{p}\\)
* Compute \\(\\vec{w} = -\\mathbf{G}^\\top y\\)
.. math::
\mathbf{\hat{A}}^\top = \left[
\begin{array}{cccc}
A & B & & \\
& \ddots & \ddots & \\
& & A & B \\
& & 0 & A
\end{array}
\right]
For the all time-steps (going backwards in time):
.. math::
A \vec{y}^{(t)} + B \vec{y}^{(t+1)} = \vec{p}^{(t)}
.. math::
\begin{align}
\frac{1}{\delta t} \MfMui\vec{y}_{b}^{(t)} + \MfMui\dcurl \vec{y}_{e}^{(t)}
- \frac{1}{\delta t} \MfMui \vec{y}_{b}^{(t+1)}
= \vec{p}_b^{(t)} \\
\dcurl^\top \MfMui \vec{y}_b^{(t)} - \MeSig \vec{y}_e^{(t)} = \vec{p}_e^{(t)}
\end{align}
and
.. math::
\begin{align}
\left( \MfMui \dcurl \MeSig^{-1} \dcurl^\top \MfMui + \frac{1}{\delta t} \MfMui \right) \vec{y}_{b}^{(t)} =
\frac{1}{\delta t} \MfMui \vec{y}_b^{(t+1)}
+ \MfMui \dcurl \MeSig^{-1} \vec{p}_e^{(t)} + \vec{p}_b^{(t)} \\
\vec{y}_e^{(t)} = \MeSig^{-1} \dcurl^\top \MfMui \vec{y}_b^{(t)} - \MeSig^{-1} \vec{p}_e^{(t)}
\end{align}
.. note::
For the last time step, \\\(t=N\\\), the term: \\\(\\frac{1}{\\delta t} \\MfMui \\vec{y}_b^{(N+1)}\\\) is zero.
+34
View File
@@ -0,0 +1,34 @@
simpegEM Utilities
******************
SimPEG for EM provides a few EM specific utility codes,
sources, and analytic functions.
Analytic Functions - Time
=========================
.. automodule:: SimPEG.EM.Utils.Ana.TEM
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
Analytic Functions - Frequency
==============================
.. automodule:: SimPEG.EM.Utils.Ana.FEM
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
Sources
=======
.. automodule:: SimPEG.EM.Utils.Sources.magneticDipole
:show-inheritance:
:members:
:undoc-members:
:inherited-members:
+45
View File
@@ -0,0 +1,45 @@
Electromagnetics
================
`SimPEG.EM` uses SimPEG as the framework for the forward and inverse
electromagnetics geophysical problems.
Time Domian Electromagnetics
----------------------------
.. toctree::
:maxdepth: 2
api_TDEM_derivation
Code for Time Domian Electromagnetics
-------------------------------------
.. toctree::
:maxdepth: 2
api_TDEM
Frequency Domian Electromagnetics
---------------------------------
.. toctree::
:maxdepth: 2
api_ForwardProblem
api_FDEM
Utility Codes
-------------
.. toctree::
:maxdepth: 2
api_Utils
+26
View File
@@ -0,0 +1,26 @@
.. _examples_EM_FDEM_1D_Inversion:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
EM: FDEM: 1D: Inversion
=======================
Here we will create and run a FDEM 1D inversion.
.. plot::
from SimPEG import Examples
Examples.EM_FDEM_1D_Inversion.run()
.. literalinclude:: ../../SimPEG/Examples/EM_FDEM_1D_Inversion.py
:language: python
:linenos:
@@ -0,0 +1,52 @@
.. _examples_FLOW_Richards_1D_Celia1990:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
FLOW: Richards: 1D: Celia1990
=============================
There are two different forms of Richards equation that differ
on how they deal with the non-linearity in the time-stepping term.
The most fundamental form, referred to as the
'mixed'-form of Richards Equation Celia1990_
.. math::
\frac{\partial \theta(\psi)}{\partial t} - \nabla \cdot k(\psi) \nabla \psi - \frac{\partial k(\psi)}{\partial z} = 0
\quad \psi \in \Omega
where \\(\\theta\\) is water content, and \\(\\psi\\) is pressure head.
This formulation of Richards equation is called the
'mixed'-form because the equation is parameterized in \\(\\psi\\)
but the time-stepping is in terms of \\(\\theta\\).
As noted in Celia1990_ the 'head'-based form of Richards
equation can be written in the continuous form as:
.. math::
\frac{\partial \theta}{\partial \psi}\frac{\partial \psi}{\partial t} - \nabla \cdot k(\psi) \nabla \psi - \frac{\partial k(\psi)}{\partial z} = 0 \quad \psi \in \Omega
However, it can be shown that this does not conserve mass in the discrete formulation.
Here we reproduce the results from Celia1990_ demonstrating the head-based formulation and the mixed-formulation.
.. _Celia1990: http://www.webpages.uidaho.edu/ch/papers/Celia.pdf
.. plot::
from SimPEG import Examples
Examples.FLOW_Richards_1D_Celia1990.run()
.. literalinclude:: ../../SimPEG/Examples/FLOW_Richards_1D_Celia1990.py
:language: python
:linenos:
@@ -0,0 +1,21 @@
.. _examples_Forward_BasicDirectCurrent:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Forward BasicDirectCurrent
==========================
.. plot::
from SimPEG import Examples
Examples.Forward_BasicDirectCurrent.run()
.. literalinclude:: ../../SimPEG/Examples/Forward_BasicDirectCurrent.py
:language: python
:linenos:
+26
View File
@@ -0,0 +1,26 @@
.. _examples_Inversion_Linear:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Inversion: Linear Problem
=========================
Here we go over the basics of creating a linear problem and inversion.
.. plot::
from SimPEG import Examples
Examples.Inversion_Linear.run()
.. literalinclude:: ../../SimPEG/Examples/Inversion_Linear.py
:language: python
:linenos:
+27
View File
@@ -0,0 +1,27 @@
.. _examples_Mesh_Basic_PlotImage:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: Basic: PlotImage
======================
You can use M.PlotImage to plot images on all of the Meshes.
.. plot::
from SimPEG import Examples
Examples.Mesh_Basic_PlotImage.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_Basic_PlotImage.py
:language: python
:linenos:
+26
View File
@@ -0,0 +1,26 @@
.. _examples_Mesh_Basic_Types:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: Basic: Types
==================
Here we show SimPEG used to create three different types of meshes.
.. plot::
from SimPEG import Examples
Examples.Mesh_Basic_Types.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_Basic_Types.py
:language: python
:linenos:
@@ -0,0 +1,57 @@
.. _examples_Mesh_Operators_CahnHilliard:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: Operators: Cahn Hilliard
==============================
This example is based on the example in the FiPy_ library.
Please see their documentation for more information about the Cahn-Hilliard equation.
The "Cahn-Hilliard" equation separates a field \\( \\phi \\) into 0 and 1 with smooth transitions.
.. math::
\frac{\partial \phi}{\partial t} = \nabla \cdot D \nabla \left( \frac{\partial f}{\partial \phi} - \epsilon^2 \nabla^2 \phi \right)
Where \\( f \\) is the energy function \\( f = ( a^2 / 2 )\\phi^2(1 - \\phi)^2 \\)
which drives \\( \\phi \\) towards either 0 or 1, this competes with the term
\\(\\epsilon^2 \\nabla^2 \\phi \\) which is a diffusion term that creates smooth changes in \\( \\phi \\).
The equation can be factored:
.. math::
\frac{\partial \phi}{\partial t} = \nabla \cdot D \nabla \psi \\
\psi = \frac{\partial^2 f}{\partial \phi^2} (\phi - \phi^{\text{old}}) + \frac{\partial f}{\partial \phi} - \epsilon^2 \nabla^2 \phi
Here we will need the derivatives of \\( f \\):
.. math::
\frac{\partial f}{\partial \phi} = (a^2/2)2\phi(1-\phi)(1-2\phi)
\frac{\partial^2 f}{\partial \phi^2} = (a^2/2)2[1-6\phi(1-\phi)]
The implementation below uses backwards Euler in time with an exponentially increasing time step.
The initial \\( \\phi \\) is a normally distributed field with a standard deviation of 0.1 and mean of 0.5.
The grid is 60x60 and takes a few seconds to solve ~130 times. The results are seen below, and you can see the
field separating as the time increases.
.. _FiPy: http://www.ctcms.nist.gov/fipy/examples/cahnHilliard/generated/examples.cahnHilliard.mesh2DCoupled.html
.. plot::
from SimPEG import Examples
Examples.Mesh_Operators_CahnHilliard.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_Operators_CahnHilliard.py
:language: python
:linenos:
+31
View File
@@ -0,0 +1,31 @@
.. _examples_Mesh_QuadTree_Creation:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: QuadTree: Creation
========================
You can give the refine method a function, which is evaluated on every cell
of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
.. plot::
from SimPEG import Examples
Examples.Mesh_QuadTree_Creation.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_QuadTree_Creation.py
:language: python
:linenos:
+26
View File
@@ -0,0 +1,26 @@
.. _examples_Mesh_QuadTree_FaceDiv:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: QuadTree: FaceDiv
=======================
.. plot::
from SimPEG import Examples
Examples.Mesh_QuadTree_FaceDiv.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_QuadTree_FaceDiv.py
:language: python
:linenos:
@@ -0,0 +1,31 @@
.. _examples_Mesh_QuadTree_HangingNodes:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: QuadTree: Hanging Nodes
=============================
You can give the refine method a function, which is evaluated on every cell
of the TreeMesh.
Occasionally it is useful to initially refine to a constant level
(e.g. 3 in this 32x32 mesh). This means the function is first evaluated
on an 8x8 mesh (2^3).
.. plot::
from SimPEG import Examples
Examples.Mesh_QuadTree_HangingNodes.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_QuadTree_HangingNodes.py
:language: python
:linenos:
+43
View File
@@ -0,0 +1,43 @@
.. _examples_Mesh_Tensor_Creation:
.. --------------------------------- ..
.. ..
.. THIS FILE IS AUTO GENEREATED ..
.. ..
.. SimPEG/Examples/__init__.py ..
.. ..
.. --------------------------------- ..
Mesh: Tensor: Creation
======================
For tensor meshes, there are some functions that can come
in handy. For example, creating mesh tensors can be a bit time
consuming, these can be created speedily by just giving numbers
and sizes of padding. See the example below, that follows this
notation::
h1 = (
(cellSize, numPad, [, increaseFactor]),
(cellSize, numCore),
(cellSize, numPad, [, increaseFactor])
)
.. note::
You can center your mesh by passing a 'C' for the x0[i] position.
A 'N' will make the entire mesh negative, and a '0' (or a 0) will
make the mesh start at zero.
.. plot::
from SimPEG import Examples
Examples.Mesh_Tensor_Creation.run()
.. literalinclude:: ../../SimPEG/Examples/Mesh_Tensor_Creation.py
:language: python
:linenos:
+47
View File
@@ -0,0 +1,47 @@
.. _api_Richards:
Richards Equation
*****************
There are two different forms of Richards equation that differ
on how they deal with the non-linearity in the time-stepping term.
The most fundamental form, referred to as the
'mixed'-form of Richards Equation [Celia et al., 1990]
.. math::
\frac{\partial \theta(\psi)}{\partial t} - \nabla \cdot k(\psi) \nabla \psi - \frac{\partial k(\psi)}{\partial z} = 0
\quad \psi \in \Omega
where theta is water content, and psi is pressure head.
This formulation of Richards equation is called the
'mixed'-form because the equation is parameterized in psi
but the time-stepping is in terms of theta.
As noted in [Celia et al., 1990] the 'head'-based form of Richards
equation can be written in the continuous form as:
.. math::
\frac{\partial \theta}{\partial \psi}\frac{\partial \psi}{\partial t} - \nabla \cdot k(\psi) \nabla \psi - \frac{\partial k(\psi)}{\partial z} = 0
\quad \psi \in \Omega
However, it can be shown that this does not conserve mass in the discrete formulation.
Here we reproduce the results from Celia et al. (1990):
.. plot::
from SimPEG.FLOW.Examples import Celia1990
Celia1990.run()
Richards
========
.. automodule:: simpegFLOW.Richards.Empirical
:show-inheritance:
:members:
:undoc-members:
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+9
View File
@@ -79,6 +79,15 @@ Utility Codes
api_Tests
Packages
********
.. toctree::
:maxdepth: 3
em/index
flow/index
Developer's Documentation
*************************
+50 -5
View File
@@ -5,10 +5,15 @@ SimPEG is a python package for simulation and gradient based
parameter estimation in the context of geophysical applications.
"""
import numpy as np
import os
import sys
import subprocess
from distutils.core import setup
from setuptools import find_packages
from Cython.Build import cythonize
import numpy as np
from distutils.extension import Extension
CLASSIFIERS = [
'Development Status :: 4 - Beta',
@@ -26,6 +31,44 @@ CLASSIFIERS = [
'Natural Language :: English',
]
args = sys.argv[1:]
# Make a `cleanall` rule to get rid of intermediate and library files
if "cleanall" in args:
print "Deleting cython files..."
# Just in case the build directory was created by accident,
# note that shell=True should be OK here because the command is constant.
subprocess.Popen("rm -rf build", shell=True, executable="/bin/bash")
subprocess.Popen("find . -name \*.c -type f -delete", shell=True, executable="/bin/bash")
subprocess.Popen("find . -name \*.so -type f -delete", shell=True, executable="/bin/bash")
# Now do a normal clean
sys.argv[sys.argv.index('cleanall')] = "clean"
# We want to always use build_ext --inplace
if args.count("build_ext") > 0 and args.count("--inplace") == 0:
sys.argv.insert(sys.argv.index("build_ext")+1, "--inplace")
try:
from Cython.Build import cythonize
from Cython.Distutils import build_ext
cythonKwargs = dict(cmdclass={'build_ext': build_ext})
USE_CYTHON = True
except Exception, e:
USE_CYTHON = False
cythonKwargs = dict()
ext = '.pyx' if USE_CYTHON else '.c'
cython_files = [
"SimPEG/Utils/interputils_cython",
"SimPEG/Mesh/TreeUtils"
]
extensions = [Extension(f, [f+ext]) for f in cython_files]
if USE_CYTHON and "cleanall" not in args:
from Cython.Build import cythonize
extensions = cythonize(extensions)
import os, os.path
with open("README.rst") as f:
@@ -33,10 +76,11 @@ with open("README.rst") as f:
setup(
name = "SimPEG",
version = "0.1.3",
version = "0.1.4",
packages = find_packages(),
install_requires = ['numpy>=1.7',
'scipy>=0.13'
'scipy>=0.13',
'Cython'
],
author = "Rowan Cockett",
author_email = "rowan@3ptscience.com",
@@ -50,5 +94,6 @@ setup(
platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"],
use_2to3 = False,
include_dirs=[np.get_include()],
ext_modules = cythonize('SimPEG/Utils/interputils_cython.pyx')
ext_modules = extensions,
**cythonKwargs
)
@@ -1,6 +1,3 @@
from TestUtils import checkDerivative, Rosenbrock, OrderTest, getQuadratic
if __name__ == '__main__':
import os
import glob
+11
View File
@@ -0,0 +1,11 @@
if __name__ == '__main__':
import os
import glob
import unittest
test_file_strings = glob.glob('test_*.py')
module_strings = [str[0:len(str)-3] for str in test_file_strings]
suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str
in module_strings]
testSuite = unittest.TestSuite(suites)
unittest.TextTestRunner(verbosity=2).run(testSuite)
@@ -8,9 +8,9 @@ class MyPropMap(Maps.PropMap):
mu = Maps.Property("Mu", defaultVal=mu_0)
class MyReciprocalPropMap(Maps.PropMap):
sigma = Maps.Property("Electrical Conductivity", defaultInvProp=True, propertyLink=('rho', Maps.ReciprocalMap))
rho = Maps.Property("Electrical Resistivity", propertyLink=('sigma', Maps.ReciprocalMap))
mu = Maps.Property("Mu", defaultVal=mu_0, propertyLink=('mui', Maps.ReciprocalMap))
sigma = Maps.Property("Electrical Conductivity", defaultInvProp=True, propertyLink=('rho', Maps.ReciprocalMap))
rho = Maps.Property("Electrical Resistivity", propertyLink=('sigma', Maps.ReciprocalMap))
mu = Maps.Property("Mu", defaultVal=mu_0, propertyLink=('mui', Maps.ReciprocalMap))
mui = Maps.Property("Mu", defaultVal=1./mu_0, propertyLink=('mu', Maps.ReciprocalMap))
@@ -1,7 +1,6 @@
import numpy as np
import unittest
from SimPEG import *
from TestUtils import checkDerivative
from scipy.sparse.linalg import dsolve
TOL = 1e-14
@@ -1,7 +1,6 @@
import numpy as np
import unittest
from SimPEG import *
from TestUtils import checkDerivative
from scipy.sparse.linalg import dsolve
import inspect
@@ -18,12 +17,16 @@ class RegularizationTests(unittest.TestCase):
if not issubclass(r, Regularization.BaseRegularization):
continue
# if 'Regularization' not in R: continue
print 'Check:', R
mapping = r.mapPair(self.mesh2)
reg = r(self.mesh2, mapping=mapping)
m = np.random.rand(mapping.nP)
reg.mref = m[:]*np.mean(m)
passed = checkDerivative(lambda m : [reg.eval(m), reg.evalDeriv(m)], m, plotIt=False)
print 'Check:', R
passed = Tests.checkDerivative(lambda m : [reg.eval(m), reg.evalDeriv(m)], m, plotIt=False)
self.assertTrue(passed)
print 'Check 2 Deriv:', R
passed = Tests.checkDerivative(lambda m : [reg.evalDeriv(m), reg.eval2Deriv(m)], m, plotIt=False)
self.assertTrue(passed)

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