diff --git a/SimPEG/Examples/DCfwd.py b/SimPEG/Examples/Forward_BasicDirectCurrent.py similarity index 98% rename from SimPEG/Examples/DCfwd.py rename to SimPEG/Examples/Forward_BasicDirectCurrent.py index 33e7aad5..a3c9ff97 100644 --- a/SimPEG/Examples/DCfwd.py +++ b/SimPEG/Examples/Forward_BasicDirectCurrent.py @@ -12,7 +12,6 @@ def run(plotIt=True): 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 @@ -39,6 +38,7 @@ def run(plotIt=True): 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)"] @@ -69,7 +69,9 @@ def run(plotIt=True): else: axes[i].set_ylabel(" ") axes[i].set_xlabel("x") + plt.show() if __name__ == '__main__': + Utils._makeExample(__file__) run() diff --git a/SimPEG/Examples/Linear.py b/SimPEG/Examples/Inversion_Linear.py similarity index 78% rename from SimPEG/Examples/Linear.py rename to SimPEG/Examples/Inversion_Linear.py index b065682b..2446bd58 100644 --- a/SimPEG/Examples/Linear.py +++ b/SimPEG/Examples/Inversion_Linear.py @@ -23,7 +23,9 @@ class LinearProblem(Problem.BaseProblem): return self.G.T.dot(v) -def run(N, plotIt=True): +def run(N=100, plotIt=True): + np.random.seed(1) + mesh = Mesh.TensorMesh([N]) nk = 20 @@ -52,7 +54,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 +65,19 @@ 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) + Utils._makeExample(__file__) + run() diff --git a/SimPEG/Examples/Mesh_QuadTree_Create.py b/SimPEG/Examples/Mesh_QuadTree_Create.py new file mode 100644 index 00000000..f4417855 --- /dev/null +++ b/SimPEG/Examples/Mesh_QuadTree_Create.py @@ -0,0 +1,18 @@ +from SimPEG import * + +def run(plotIt=True): + from SimPEG import Mesh, np + 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__': + Utils._makeExample(__file__) + run() diff --git a/SimPEG/Examples/Mesh_ThreeMeshes.py b/SimPEG/Examples/Mesh_ThreeMeshes.py new file mode 100644 index 00000000..2fc7fa8d --- /dev/null +++ b/SimPEG/Examples/Mesh_ThreeMeshes.py @@ -0,0 +1,24 @@ +from SimPEG import * + +def run(plotIt=True): + 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__': + Utils._makeExample(__file__) + run() diff --git a/SimPEG/Examples/__init__.py b/SimPEG/Examples/__init__.py index 3fec0b99..53b1f9a8 100644 --- a/SimPEG/Examples/__init__.py +++ b/SimPEG/Examples/__init__.py @@ -1 +1,9 @@ -import Linear, DCfwd +# This will import everything in the directory into this file +from os import path as p +from glob import glob +__all__ = [] +for x in glob(p.join(p.dirname(__file__), '*.py')): + if not p.basename(x).startswith('__'): + __import__(p.basename(x)[:-3], globals(), locals()) + __all__ += [p.basename(x)] +del glob, p, x diff --git a/SimPEG/Mesh/TreeMesh.py b/SimPEG/Mesh/TreeMesh.py index 1e6c91c0..69a44fdc 100644 --- a/SimPEG/Mesh/TreeMesh.py +++ b/SimPEG/Mesh/TreeMesh.py @@ -1960,7 +1960,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts): def plotGrid(self, ax=None, showIt=False, grid=True, - cells=True, cellLine=False, + cells=False, cellLine=False, nodes=False, facesX=False, facesY=False, facesZ=False, edgesX=False, edgesY=False, edgesZ=False): @@ -2009,6 +2009,8 @@ class TreeMesh(BaseTensorMesh, InnerProducts): if facesY: ax.plot(self._gridFy[self._hangingFy.keys(),0], self._gridFy[self._hangingFy.keys(),1], 'gs', ms=10, mfc='none', mec='g') ax.plot(self._gridFy[:,0], self._gridFy[:,1], 'g^') + ax.set_xlabel('x1') + ax.set_ylabel('x2') elif self.dim == 3: if cells: ax.plot(self.gridCC[:,0], self.gridCC[:,1], 'r.', zs=self.gridCC[:,2]) @@ -2056,7 +2058,6 @@ class TreeMesh(BaseTensorMesh, InnerProducts): ind = [key, hf[0]] ax.plot(self._gridEx[ind,0], self._gridEx[ind,1], 'k:', zs=self._gridEx[ind,2]) - if edgesY: ax.plot(self._gridEy[:,0], self._gridEy[:,1], 'k<', zs=self._gridEy[:,2]) ax.plot(self._gridEy[self._hangingEy.keys(),0], self._gridEy[self._hangingEy.keys(),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEy[self._hangingEy.keys(),2]) @@ -2072,7 +2073,10 @@ class TreeMesh(BaseTensorMesh, InnerProducts): for hf in self._hangingEz[key]: ind = [key, hf[0]] ax.plot(self._gridEz[ind,0], self._gridEz[ind,1], 'k:', zs=self._gridEz[ind,2]) - + ax.set_xlabel('x1') + ax.set_ylabel('x2') + ax.set_zlabel('x3') + ax.grid(True) if showIt:plt.show() def plotImage(self, I, ax=None, showIt=True, grid=False): @@ -2191,7 +2195,7 @@ class Cell(object): @property def center(self): if getattr(self, '_center', None) is None: - self._center = self.mesh._cellC(self._pointer) + self._center = np.array(self.mesh._cellC(self._pointer)) return self._center @property def h(self): return self.mesh._cellH(self._pointer) diff --git a/SimPEG/Utils/__init__.py b/SimPEG/Utils/__init__.py index 5280ae79..67e1b117 100644 --- a/SimPEG/Utils/__init__.py +++ b/SimPEG/Utils/__init__.py @@ -1,5 +1,6 @@ from matutils import * from codeutils import * +from codeutils import _makeExample from meshutils import exampleLrmGrid, meshTensor, closestPoints, readUBCTensorMesh, writeUBCTensorMesh, writeUBCTensorModel, readVTRFile, writeVTRFile from curvutils import volTetra, faceInfo, indexCube from interputils import interpmat diff --git a/SimPEG/Utils/codeutils.py b/SimPEG/Utils/codeutils.py index 4a9a28a7..fef34282 100644 --- a/SimPEG/Utils/codeutils.py +++ b/SimPEG/Utils/codeutils.py @@ -227,3 +227,35 @@ def requires(var): return requiresVarWrapper return requiresVar + +def _makeExample(filePath): + + import os + name = filePath.split(os.path.sep)[-1][:-3] + out = """.. _examples_%s: + +.. ------------------------------ .. +.. THIS FILE IS AUTO GENEREATED .. +.. ------------------------------ .. + +%s +%s + +.. plot:: + + from SimPEG import Examples + Examples.%s.run() + +.. literalinclude:: ../../SimPEG/Examples/%s.py + :language: python + :linenos: +"""%(name,name.replace('_',' '),'='*len(name),name,name) + + rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'examples', name + '.rst'])) + + f = open(rst, 'w') + f.write(out) + f.close() + + + diff --git a/docs/api_Examples.rst b/docs/api_Examples.rst index 214dd8e1..68589fb3 100644 --- a/docs/api_Examples.rst +++ b/docs/api_Examples.rst @@ -3,8 +3,15 @@ Examples ******** -Forward problem -=============== +.. toctree:: + :maxdepth: 1 + :glob: + + examples/* + + +External Notebooks +================== * `Example 1: Direct Current `_ * `Example 2: Seismic-Acoustic `_ diff --git a/docs/api_Mesh.rst b/docs/api_Mesh.rst index 7bf398b1..a7f7abae 100644 --- a/docs/api_Mesh.rst +++ b/docs/api_Mesh.rst @@ -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 diff --git a/docs/examples/Forward_BasicDirectCurrent.rst b/docs/examples/Forward_BasicDirectCurrent.rst new file mode 100644 index 00000000..6fc816e7 --- /dev/null +++ b/docs/examples/Forward_BasicDirectCurrent.rst @@ -0,0 +1,17 @@ +.. _examples_Forward_BasicDirectCurrent: + +.. ------------------------------ .. +.. THIS FILE IS AUTO GENEREATED .. +.. ------------------------------ .. + +Forward BasicDirectCurrent +========================== + +.. plot:: + + from SimPEG import Examples + Examples.Forward_BasicDirectCurrent.run() + +.. literalinclude:: ../../SimPEG/Examples/Forward_BasicDirectCurrent.py + :language: python + :linenos: diff --git a/docs/examples/Inversion_Linear.rst b/docs/examples/Inversion_Linear.rst new file mode 100644 index 00000000..637315ae --- /dev/null +++ b/docs/examples/Inversion_Linear.rst @@ -0,0 +1,17 @@ +.. _examples_Inversion_Linear: + +.. ------------------------------ .. +.. THIS FILE IS AUTO GENEREATED .. +.. ------------------------------ .. + +Inversion Linear +================ + +.. plot:: + + from SimPEG import Examples + Examples.Inversion_Linear.run() + +.. literalinclude:: ../../SimPEG/Examples/Inversion_Linear.py + :language: python + :linenos: diff --git a/docs/examples/Mesh_QuadTree_Create.rst b/docs/examples/Mesh_QuadTree_Create.rst new file mode 100644 index 00000000..644593d5 --- /dev/null +++ b/docs/examples/Mesh_QuadTree_Create.rst @@ -0,0 +1,17 @@ +.. _examples_Mesh_QuadTree_Create: + +.. ------------------------------ .. +.. THIS FILE IS AUTO GENEREATED .. +.. ------------------------------ .. + +Mesh QuadTree Create +==================== + +.. plot:: + + from SimPEG import Examples + Examples.Mesh_QuadTree_Create.run() + +.. literalinclude:: ../../SimPEG/Examples/Mesh_QuadTree_Create.py + :language: python + :linenos: diff --git a/docs/examples/Mesh_ThreeMeshes.rst b/docs/examples/Mesh_ThreeMeshes.rst new file mode 100644 index 00000000..948398a7 --- /dev/null +++ b/docs/examples/Mesh_ThreeMeshes.rst @@ -0,0 +1,17 @@ +.. _examples_Mesh_ThreeMeshes: + +.. ------------------------------ .. +.. THIS FILE IS AUTO GENEREATED .. +.. ------------------------------ .. + +Mesh ThreeMeshes +================ + +.. plot:: + + from SimPEG import Examples + Examples.Mesh_ThreeMeshes.run() + +.. literalinclude:: ../../SimPEG/Examples/Mesh_ThreeMeshes.py + :language: python + :linenos: diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index 1fcf05f5..baddb6db 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -1,17 +1,22 @@ import unittest import sys -from SimPEG.Examples import Linear, DCfwd +from SimPEG import Examples import numpy as np -class TestLinear(unittest.TestCase): - def test_running(self): - Linear.run(100, plotIt=False) +def get_test(test): + def func(self): + print '\nTesting %s.run(plotIt=False)\n'%test + getattr(Examples, test).run(plotIt=False) self.assertTrue(True) + return func +attrs = dict() +tests = [_ for _ in dir(Examples) if not _.startswith('_')] +for test in tests: + attrs['test_'+test] = get_test(test) + + +TestExamples = type('TestExamples', (unittest.TestCase,), attrs) -class TestDCfwd(unittest.TestCase): - def test_running(self): - DCfwd.run(plotIt=False) - self.assertTrue(True) if __name__ == '__main__': unittest.main()