def saveani(mesh, plc, data, label, out, cMin=None, cMax=None, logScale=False, cmap=None): """ """ dpi = 92 scale = 1 fig = plt.figure(facecolor="white", figsize=(scale * 800 / dpi, scale * 490 / dpi), dpi=dpi) ax = fig.add_subplot(1, 1, 1) gci = pg.mplviewer.drawModel(ax, mesh, data=data[0], cMin=cMin, cMax=cMax, cmap=cmap, logScale=logScale) cbar = pg.mplviewer.createColorbar(gci, label=label, pad=0.55) ax.set_ylabel("Depth [m]") ax.set_xlabel("$x$ [m]") ticks = ax.yaxis.get_majorticklocs() tickLabels = [] for t in ticks: tickLabels.append(str(int(abs(t)))) ax.set_yticklabels(tickLabels) pg.show(plc, axes=ax) plt.tight_layout() plt.pause(0.001) def animate(i): print(out + ": Frame:", i, "/", len(data)) pg.mplviewer.setMappableData(gci, pg.abs(data[i]), cMin=cMin, cMax=cMax, logScale=logScale) # plt.pause(0.001) createAnimation(fig, animate, int(len(data)), dpi, out)
def showModel(ax, model, mesh, petro=1, cMin=None, cMax=None, label=None, savefig=None, showMesh=False): """Utility function to show and save models for the CG paper.""" if cMin is None: cMin = 0.3 if cMax is None: cMax = 1.0 if petro: ax, _ = pg.show(mesh, model, label=label, cMin=cMin, cMax=cMax, logScale=0, ax=ax, cMap='viridis', hold=1) else: ax, _ = pg.show(mesh, model, label=label, logScale=1, ax=ax, cMin=cMin, cMax=cMax, hold=1) ticks = [-.2, -.1, 0, .1, .2] ax.xaxis.set_ticks(ticks) ax.yaxis.set_ticks(ticks) pg.mplviewer.drawSensors(ax, ertData.sensorPositions(), diam=0.005) # despine(ax=ax, offset=5, trim=True) if showMesh: pg.mplviewer.drawSelectedMeshBoundaries(ax, mesh.boundaries(), linewidth=0.3, color="0.2") if savefig: pg.mplviewer.saveAxes(ax, savefig, adjust=False) return ax
def show(self, data, values=None, axes=None, cMin=None, cMax=None, colorBar=1, **kwargs): """ """ gci = None if isinstance(data, pg.DataContainer): scheme = kwargs.pop('scheme', 'unknown') pseudoscheme = getattr(pb.dataview.Pseudotype, scheme) if values is None: values = data('rhoa') gci = pb.dataview.dataview.drawDataAsMatrix( axes, data, values, pseudotype=pseudoscheme) gci.set_clim((cMin, cMax)) if colorBar: pg.mplviewer.colorbar.createColorbar( gci, nLevs=5, cMin=cMin, cMax=cMax, label='Apparent resistivity in $\Omega m$', **kwargs) elif isinstance(data, pg.RVector): # assuming this is a model from the last inversion run pg.show(self.fop.regionManager().paraDomain(), data, axes=axes, **kwargs) else: print(type(data)) raise return gci
def showCoverage(self, ax=None, name='coverage'): """shows the ray coverage in logscale""" if ax is None: fig, ax = plt.subplots() self.figs[name] = fig self.axs[name] = ax cov = self.rayCoverage() pg.show(self.mesh, pg.log10(cov+min(cov[cov > 0])*.5), axes=ax, coverage=self.standardizedCoverage())
def makeJacobianPDF(self, ind=None): """Make multipage Jacobian PDF.""" from matplotlib.backends.backend_pdf import PdfPages if ind is None: ind = range(self.dataContainer.size()) with PdfPages(self.basename+'-jacobian.pdf') as pdf: fig, ax = pg.plt.subplots() for ii in ind: jj = self.fop.jacobian().row(ii) pg.show(self.mesh, jj, ax=ax, coverage=(jj > 0)) fig.savefig(pdf, format='pdf') ax.cla()
def showResult(self, val=None, ax=None, cMin=None, cMax=None, logScale=False, name='result', **kwargs): """show resulting velocity vector""" mesh = self.paraDomain() if val is None: val = self.velocity if cMin is None or cMax is None: cMin, cMax = interperc(val, 3) if ax is None: fig, ax = plt.subplots() self.figs[name] = fig ax, cbar = pg.show(mesh, val, logScale=logScale, axes=ax, colorBar=True, cMin=cMin, cMax=cMax, coverage=self.standardizedCoverage(), **kwargs) self.figs[name] = plt.gcf() else: gci = drawModel(ax, mesh, val, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, coverage=self.standardizedCoverage(), **kwargs) labels = ['cMin', 'cMax', 'nLevs', 'orientation', 'label'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} cbar = createColorbar(gci, **subkwargs) browser = CellBrowser(self.mesh, val, ax) browser.connect() self.axs[name] = ax if 'lines' in kwargs: plotLines(ax, kwargs['lines']) return ax, cbar
def showQuality(mesh, qualities): fig, axes = plt.subplots(1, 2) axes[1].hist(qualities, color="grey") pg.show(mesh, qualities, ax=axes[0], cMin=0.5, cMax=1, hold=True, logScale=False, label="Mesh quality", cmap="RdYlGn", showMesh=True) s = "Min: %.2f, Mean: %.2f, Max: %.2f" % ( np.min(qualities), np.mean(qualities), np.max(qualities)) axes[1].set_title(s) axes[1].set_xlabel("Mesh quality") axes[1].set_ylabel("Frequency") axes[1].set_xlim(0, 1) # Figure resizing according to mesh dimesions x = mesh.xmax() - mesh.xmin() y = mesh.ymax() - mesh.ymin() width, height = fig.get_size_inches() fig.set_figheight(height * 1.3 * (y / x)) fig.tight_layout()
def _test_(mesh, show=False): vTest = 0.1 u = pg.solve(mesh, a=1, f=0, bc={'Node': [mesh.findNearestNode([0.0, 0.0]), 0.], 'Neumann': [[1, -vTest], [2, vTest]]}, verbose=0) if show: if mesh.dim() == 1: pg.plt.plot(pg.x(mesh), u) elif mesh.dim() == 2: pg.show(grid, pg.abs(v)) pg.show(grid, v, showMesh=1) pg.wait() v = pg.solver.grad(mesh, u) #print("|v|:", min(pg.abs(v)), max(pg.abs(v)), pg.mean(pg.abs(v))) np.testing.assert_allclose(pg.abs(v), np.ones(mesh.cellCount())*vTest) return v
def savefig(mesh, geom, data=None, label='', out=None, **kwargs): """Little shortcut to plot mesh with asociated geometry.""" pg.mplviewer.hold(1) ax = kwargs.pop('ax', None) print(ax) if data is not None: ax, _ = pg.show(mesh, data, hold=1, pad=0.55, label=label, ax=ax, **kwargs) if out: ax, _ = pg.show(geom, ax=ax, fillRegion=False, **kwargs) saveAxes(ax, out, adjust=True) else: ax, _ = pg.show(geom, fillRegion=False, ax=ax, **kwargs) if kwargs.pop('adjust', True): pg.mplviewer.adjustWorldAxes(ax) return ax
def _testP1_(mesh, show=False): """ Laplace u = 0 solves u = x for u(r=0)=0 and u(r=1)=1 Test for u == exact x for P1 base functions """ u = pg.solve(mesh, a=1, b=0, f=0, bc={'Dirichlet': [[1, 0], [2, 1]]}) if show: if mesh.dim()==1: pg.plt.plot(pg.x(mesh), u) pg.wait() elif mesh.dim()==2: pg.show(mesh, u, label='u') pg.wait() xMin = mesh.xmin() xSpan = (mesh.xmax() - xMin) np.testing.assert_allclose(u, (pg.x(mesh)-xMin)/ xSpan) return u
def invertGravimetry(gravPoints, dz): dzerr = np.random.randn(len(gravPoints)) * 0.0001 dz = dz + dzerr mesh = pg.createGrid(x=np.linspace(-20, 20, 41), y=np.linspace(-20, 0, 21)) grav = Gravimetry(verbose=True) model = grav.invert(gravPoints, dz, verbose=1, mesh=mesh) plt.plot(pg.x(gravPoints), dz) plt.plot(pg.x(gravPoints), grav.inv.response()) paraDomain=grav.fop.regionManager().paraDomain() pg.show(paraDomain, model, colorBar=1, hold=1) pg.showNow() plt.show() pass
def saveAnimation(mesh, data, out, vData=None, plc=None, label='', cMin=None, cMax=None, logScale=False, cmap=None, **kwargs): """Create and save an animation for a given mesh with a set of field data. Until I know a better place. """ dpi = 92 scale = 1 fig = plt.figure(facecolor='white', figsize=(scale * 800 / dpi, scale * 490 / dpi), dpi=dpi) ax = fig.add_subplot(1, 1, 1) gci = pg.mplviewer.drawModel(ax, mesh, data=data[0], cMin=cMin, cMax=cMax, cmap=cmap, logScale=logScale) pg.mplviewer.createColorbar(gci, label=label, pad=0.55) if plc: pg.show(plc, ax=ax) adjustWorldAxes(ax) def animate(i): """TODO WRITEME.""" print(out + ": Frame:", i, "/", len(data)) if vData is not None: ax.clear() pg.mplviewer.holdAxes_ = 1 pg.mplviewer.drawModel(ax, mesh, data=data[i], cMin=cMin, cMax=cMax, cmap=cmap, logScale=logScale) pg.mplviewer.drawStreams(ax, mesh, vData[i], **kwargs) else: print(min(data[i]), max(data[i])) pg.mplviewer.setMappableData(gci, data[i], cMin=cMin, cMax=cMax, logScale=logScale) plt.pause(0.001) createAnimation(fig, animate, int(len(data)), dpi, out)
def showModel(outPath): # geom = pg.load('synth/' + 'synthGeom.bms') # pd = pg.load(outPath + '/paraDomain.bms') paraMesh = pg.load(outPath + '/paraMesh.bms') model = pg.load(outPath + "/model.vector") fopMesh = pg.load(outPath + "fopMesh.bms") fopModel = pg.load(outPath + "fopModel.vector") allModel = np.zeros(len(model)+2) allModel[2:] = model # allModel[0] = fopModel[fopMesh.findCellByMarker( # pg.MARKER_FIXEDVALUE_REGION - 0)[0].id()] allModel[1] = fopModel[fopMesh.findCellByMarker( pg.MARKER_FIXEDVALUE_REGION - 1)[0].id()] ax = savefig(paraMesh, None, allModel[paraMesh.cellMarkers()], 'Hydraulic conductivity $K$ in m$/$s', cMin=1e-5, cMax=1e-2, nLevs=4, cMap='viridis') pg.wait() pg.show(fopMesh, ax=ax, linewidth=0.2) paraMesh.createNeighbourInfos() bs = [] for b in paraMesh.boundaries(): if b.leftCell() and b.rightCell(): if b.leftCell().marker() > 1 or b.rightCell().marker() > 1: bs.append(b) pg.mplviewer.drawSelectedMeshBoundaries( ax, bs, color=(0.0, 0.0, 0.0, 1.0), linewidth=1.0) pg.mplviewer.saveFigure(ax.figure, 'hydrInversionModel') print('Done!') pg.wait()
def savefig(mesh, plc, data=None, label="", out=None, showMesh=0): ax = None if data is not None: ax, _ = pg.show(mesh, data, hold=1, colorBar=1, pad=0.55, label=label) if showMesh: ax, _ = pg.show(mesh, axes=ax, hold=1) if out: ax, _ = pg.show(plc, axes=ax) adjustAxes(ax) plt.pause(0.01) ax.figure.savefig(out + ".pdf", bbox_inches="tight") try: print("trying pdf2pdfS ... ") os.system("pdf2pdfBB " + out + ".pdf") os.system("pdf2pdfS " + out + ".pdf") except: pass else: ax, _ = pg.show(plc, axes=ax) return ax
def showResult(self, ax=None, cMin=None, cMax=None, logScale=False, **kwargs): """show resulting velocity vector""" if cMin is None or cMax is None: cMin, cMax = interperc(self.velocity, 3) if ax is None: ax, cbar = pg.show(self.mesh, self.velocity, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, **kwargs) self.figs['result'] = plt.gcf() else: gci = drawModel(ax, self.mesh, self.velocity, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, **kwargs) createColorbar(gci, **kwargs) browser = CellBrowser(self.mesh, self.velocity, ax) browser.connect() self.axs['result'] = ax if 'lines' in kwargs: plotLines(ax, kwargs['lines'])
def showResult(self, ax=None, cMin=None, cMax=None, logScale=False, **kwargs): """show resulting velocity vector""" if cMin is None or cMax is None: cMin, cMax = interperc(self.velocity, 3) if ax is None: ax, cbar = pg.show( self.mesh, self.velocity, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, **kwargs ) fig, ax = plt.subplots() self.figs["result"] = fig else: gci = drawModel( ax, self.mesh, self.velocity, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, **kwargs ) cbar = createColorbar(gci, **kwargs) browser = CellBrowser(self.mesh, self.velocity, ax) browser.connect() plt.show() # block=False) self.axs["result"] = ax if "lines" in kwargs: plotLines(ax, kwargs["lines"])
# There are different ways of specifying BCs. They can be maps from markers to # values, explicit functions or implicit (lambda) functions. # # The boundary 1 (top) and 2 (left) are directly mapped to the values 1 and 2. # On side 3 (bottom) a lambda function 3+x is used (p is the boundary position # and p[0] its x coordinate. On side 4 (right) a function uDirichlet is used # that simply returns 4 in this example but can compute anything as a function # of the individual boundaries b. ############################################################################### # Short test: setting single node dirichlet BC u = solve(grid, f=1., bc={'Dirichlet': [grid.node(2), 0.]}) ax, _ = pg.show( grid, u, label='Solution $u$', ) show(grid, ax=ax) def uDirichlet(boundary): """Return a solution value for coordinate p.""" return 4.0 dirichletBC = [ [1, 1.0], # left [grid.findBoundaryByMarker(2), 2.0], # right [ grid.findBoundaryByMarker(3),
Now we can generate the unstructured mesh. """ #mesh2 = pg.Mesh(2) #tri.generate(mesh2) #for cell in mesh2.cells(): #cell.setMarker(1) """ .. lastcout:: Finally, the grid and the unstructured mesh can be merged to single mesh for further modelling. """ pg.show(mesh1) # looking for *** Error in `/usr/bin/python3.3': corrupted double-linked list: 0x00000000022a0ac0 *** #mesh3 = merge2Meshes(mesh1, mesh2) #pg.show(mesh3) #""" #.. lastcout:: #Of course, you can treat the hybrid mesh like any other mesh and append a triangle #boundary for example with :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`. #""" #mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, #smooth=True, marker=3, isSubSurface=True)
############################################################################### # For more information on the triangle switches and the corresponding settings, # the reader is referred to `the triangle website <http://www.cs.cmu.edu/~quake/triangle.switch.html>`_. # # Now we can generate the unstructured mesh. mesh2 = pg.Mesh(2) tri.generate(mesh2) for cell in mesh2.cells(): cell.setMarker(1) ############################################################################### # Finally, the grid and the unstructured mesh can be merged to single mesh for further # modelling. pg.show(mesh2) mesh3 = merge2Meshes(mesh1, mesh2) pg.show(mesh3) ############################################################################### # Of course, you can treat the hybrid mesh like any other mesh and append a triangle # boundary for example with :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`. mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, smooth=True, marker=3, isSubSurface=True) ax, cbar = showMesh(mesh, mesh.cellMarker(), cmap="summer", label="Region marker") drawMesh(ax, mesh)
modelMesh = fop.regionManager().paraDomain() pg.showLater(1) fig = pg.plt.figure() ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) #pg.show(modelMesh, jacRe[0:len(jacRe)/2], colorBar=1, axes=ax1) #ax1.set_title("jac real/real") #pg.show(modelMesh, jacRe[len(jacRe)/2:len(jacRe)], colorBar=1, axes=ax2) #ax2.set_title("jac real/imag") #pg.show(modelMesh, jacIm[0:len(jacIm)/2], colorBar=1, axes=ax3) #ax3.set_title("jac imag/real") #pg.show(modelMesh, jacIm[len(jacIm)/2:len(jacIm)], colorBar=1, axes=ax4) #ax4.set_title("jac imag/imag") ax, cbar = pg.show(modelMesh, model[0:len(model)/2], colorBar=1) ax.set_title("model real") ax, cbar = pg.show(modelMesh, model[len(model)/2:len(model)], colorBar=1) ax.set_title("model imag") # #pg.show(modelMesh, data.sensorPositions(), axes=ax, showLater=1) #pg.show(modelMesh, axes=ax) pg.showLater(0)
# outer ring is assigned the marker 0 in the figure, although we specified # marker=1 for the larger circle? A marker value of 0 is assigned to a region # if no region marker is found, indicating that the marker for the outer ring # was overwritten/ignored by the inner circle, which was added later. circle_outer = mt.createCircle(pos=[0.0, 0.0], radius=3.0, marker=1) circle_inner = mt.createCircle( pos=[0.0, 0.0], radius=1.0, # area=.3, boundaryMarker=0, marker=2) plc = mt.mergePLC([circle_outer, circle_inner]) ax, cb = pg.show(plc, markers=True) ############################################################################### # The solution to this problem is the region marker, which defines the marker # value of the region that it is placed in. By default all region markers are # assigned the position (0,0,0), thereby overwriting each other (see black dots # in figure below). If no region marker is present in a region, a marker value # of 0 is assigned. fig = ax.get_figure() for nr, marker in enumerate(plc.regionMarker()): print('Position marker number {}:'.format(nr + 1), marker.x(), marker.y(), marker.z()) ax.scatter(marker.x(), marker.y(), s=(2 - nr) * 30, color='k') ax.set_title('marker positions - non-working example') fig.show()
preBoundary=preBoundary, pre0=pre, vel0=vel, maxIter=maxIter, tol=1e-2, verbose=1) print(" Time: ", swatch.duration(True)) print("OverallTime:", swatchG.duration(True)) fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax, cbar = pg.show(mesh, data=pg.cellDataToPointData(mesh, pre), logScale=False, colorBar=True, axes=ax1) cbar.ax.set_xlabel('Pressure in ??') meshC, velBoundary, preBoundary, a, maxIter = modelBuilder(0.01) pg.show(mesh, data=vel, coarseMesh=meshC, axes=ax1) pg.show(mesh, axes=ax1) ax2 = fig.add_subplot(1, 2, 2) ax, cbar = pg.show(mesh, data=pg.cellDataToPointData(mesh, np.sqrt(vel[:,0]*vel[:,0] +vel[:,1]*vel[:,1])), logScale=False, colorBar=True, axes=ax2) cbar.ax.set_xlabel('Geschwindigkeit in m$/$s') pg.show(mesh, data=vel, coarseMesh=meshC, axes=ax2) pg.show(mesh, axes=ax2)
""" Minimal example of using pygimli to simulate the steady heat equation. """ import pygimli as pg import pygimli.meshtools as mt # Create geometry definition for the modelling domain world = mt.createWorld(start=[-20, 0], end=[20, -16], layers=[-2, -8], worldMarker=False) # Create a heterogeneous block block = mt.createRectangle(start=[-6, -3.5], end=[6, -6.0], marker=4, boundaryMarker=10, area=0.1) # Merge geometrical entities geom = mt.mergePLC([world, block]) pg.show(geom, boundaryMarker=True, savefig='geometry.pdf') # Create a mesh from the geometry definition mesh = mt.createMesh(geom, quality=33, area=0.2, smooth=[1, 10]) pg.show(mesh, savefig='mesh.pdf') # $\diverg(a\grad T)=0$ with $T(bottom)=1$, $T(top)=0$ T = pg.solver.solveFiniteElements(mesh, a=[[1, 1.0], [2, 2.0], [3, 3.0], [4, 0.1]], uB=[[8, 1.0], [4, 0.0]], verbose=True) ax, _ = pg.show(mesh, data=T, label='Temperature $T$', cmap="hot_r", showBoundary=True, savefig='T_field.pdf') #ax, _ = pg.show(mesh, data=T, label='Temperature $T$', cmap="hot_r") #pg.show(geom, ax=ax, fillRegion=False, savefig='T_field.pdf')
def showResult(self, val=None, ax=None, cMin=None, cMax=None, logScale=False, rays=False, name='result', **kwargs): """Show resulting velocity vector. Parameters ---------- val : result array [self.velocity] field to show, usually the velocity vector ax : matplotlib.axes axes to plot into, if not give a new one-axis figure is created cMin/cMax : float minimum and maximum values for ranging colorbar logScale : bool [False] use logarithmic scale rays : bool [False] Show ray paths as well. Other parameters ---------------- useCoverage : bool [True] use standardized (0 or 1) ray coverage as alpha-shading label : str label to write on colorbar orientaton : str color bar orientation nLevs : int [7] number of level values for color bar **kwargs : keyword arguments passed to the show function Returns ------- ax : maxplotlib axes cb : matplotlib color bar object """ mesh = self.paraDomain() if val is None: val = self.velocity if cMin is None or cMax is None: cMin, cMax = interperc(val, 3) coverage = 1 if kwargs.pop('useCoverage', True): coverage = self.standardizedCoverage() label = kwargs.pop("label", "Velocity (m/s)") if ax is None: fig, ax = plt.subplots() self.figs[name] = fig ax, cbar = pg.show(mesh, val, logScale=logScale, ax=ax, colorBar=True, cMin=cMin, cMax=cMax, coverage=coverage, label=label, hold=True, **kwargs) self.figs[name] = plt.gcf() else: gci = drawModel(ax, mesh, val, logScale=logScale, colorBar=True, cMin=cMin, cMax=cMax, coverage=coverage, **kwargs) labels = ['cMin', 'cMax', 'nLevs', 'orientation'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} cbar = createColorBar(gci, label=label, **subkwargs) if rays: self.showRayPaths(ax=ax, alpha=0.5, color="w", linewidths=.8) browser = CellBrowser(self.mesh, val, ax) browser.connect() self.axs[name] = ax if 'lines' in kwargs: plotLines(ax, kwargs['lines']) return ax, cbar
print('Solve Darcy equation ... ') # Map regions to hydraulic conductivity in $m/s$ kMap = [[1, 1e-8], [2, 5e-3], [3, 1e-4], [4, 8e-4]] # Map conductivity value per region to each cell in the given mesh K = pg.solver.parseMapToCellArray(kMap, mesh) # Dirichlet conditions for hydraulic potential pBound = [[[1, 2, 3], 0.75], [[5, 6, 7], 0.0]] # Solve for hydraulic potential p = pg.solver.solveFiniteElements(mesh, a=K, uB=pBound) # Solve velocity as gradient of hydraulic potential vel = -pg.solver.grad(mesh, p) * np.asarray([K, K, K]).T ax, _ = pg.show(mesh, data=K, label='Hydraulic conductivity $K$ in m$/$s', cMin=1e-5, cMax=1e-2, nLevs=4, cmap='viridis') ax, _ = pg.show(mesh, data=pg.abs(vel), logScale=0, label='Velocity $v$ in m$/$s') ax, _ = pg.show(mesh, data=vel, ax=ax, color='black', linewidth=0.5, dropTol=1e-6) print('Solve Advection-diffusion equation ...')
# <http://www.cs.cmu.edu/~quake/triangle.switch.html>`_. # # Now we can generate the unstructured mesh. mesh2 = pg.Mesh(2) tri.generate(mesh2) for cell in mesh2.cells(): cell.setMarker(1) ############################################################################### # Finally, the grid and the unstructured mesh can be merged to single mesh for # further modelling. mesh3 = merge2Meshes(mesh1, mesh2) ############################################################################### # Of course, you can treat the hybrid mesh like any other mesh and append a # triangle boundary for example with the function # :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`. mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, smooth=True, marker=3, isSubSurface=True) pg.show(mesh, markers=True, showMesh=True) pg.wait()
layer1 = mt.createPolygon([[0.0, 137], [117.5, 164], [117.5, 162], [0.0, 135]], isClosed=True, marker=1, area=1) layer2 = mt.createPolygon([[0.0, 126], [0.0, 135], [117.5, 162], [117.5, 153]], isClosed=True, marker=2) layer3 = mt.createPolygon([[0.0, 110], [0.0, 126], [117.5, 153], [117.5, 110]], isClosed=True, marker=3) slope = (164 - 137) / 117.5 geom = mt.mergePLC([layer1, layer2, layer3]) mesh = mt.createMesh(geom, quality=34.3, area=3, smooth=[1, 10]) pg.show(mesh) ############################################################################### # Next we define geophone positions and a measurement scheme, which consists of # shot and receiver indices. numberGeophones = 48 sensors = np.linspace(0., 117.5, numberGeophones) scheme = pg.physics.traveltime.createRAData(sensors) # Adapt sensor positions to slope pos = np.array(scheme.sensorPositions()) for x in pos[:, 0]: i = np.where(pos[:, 0] == x) new_y = x * slope + 137 pos[i, 1] = new_y
def resistivityArchie(rFluid, porosity, a=1.0, m=2.0, sat=1.0, n=2.0, mesh=None, meshI=None, fill=None, show=False): r"""Resistivity of rock for the petrophysical model from Archies law. Calculates resistivity of rock for the petrophysical model from Archie's law. :cite:`Archie1942` .. math:: \rho = a\rho_{\text{fl}}\phi^{-m} S^{-n} * :math:`\rho` - the electrical resistivity of the fluid saturated rock in :math:`\Omega\text{m}` * :math:`\rho_{\text{fl}}` - rFluid: electrical resistivity of the fluid in :math:`\Omega\text{m}` * :math:`\phi` - porosity 0.0 --1.0 * :math:`S` - fluid saturation 0.0 --1.0 [sat] * :math:`a` - Tortuosity factor. (common 1) * :math:`m` - Cementation exponent of the rock (usually in the range 1.3 -- 2.5 for sandstones) * :math:`n` - is the saturation exponent (usually close to 2) If mesh is not None the resulting values are calculated for each cell of the mesh. All parameter can be scalar, array of length mesh.cellCount() or callable(pg.cell). If rFluid is non-steady n-step distribution than rFluid can be a matrix of size(n, mesh.cellCount()) If meshI is not None the result is interpolated to meshI.cellCenters() and prolonged (if fill ==1). Notes ----- We experience some unstable nonlinear behavior. Until this is clarified all results are rounded to the precision 1e-6. Examples -------- >>> # WRITEME """ phi = porosity if isinstance(porosity, list): phi = np.array(porosity) if mesh is None: return rFluid * a * phi**(-m) * sat**(-n) rB = None if isinstance(rFluid, float): rB = pg.RMatrix(1, mesh.cellCount()) rB[0] = pg.solver.parseArgToArray(rFluid, mesh.cellCount(), mesh) elif isinstance(rFluid, pg.RVector): rB = pg.RMatrix(1, len(rFluid)) rB[0] = pg.solver.parseArgToArray(rFluid, mesh.cellCount(), mesh) elif hasattr(rFluid, 'ndim') and rFluid.ndim == 1: rB = pg.RMatrix(1, len(rFluid)) rB[0] = pg.solver.parseArgToArray(rFluid, mesh.cellCount(), mesh) elif hasattr(rFluid, 'ndim') and rFluid.ndim == 2: rB = pg.RMatrix(len(rFluid), len(rFluid[0])) for i, rFi in enumerate(rFluid): rB[i] = rFi phi = pg.solver.parseArgToArray(phi, mesh.cellCount(), mesh) a = pg.solver.parseArgToArray(a, mesh.cellCount(), mesh) m = pg.solver.parseArgToArray(m, mesh.cellCount(), mesh) S = pg.solver.parseArgToArray(sat, mesh.cellCount(), mesh) n = pg.solver.parseArgToArray(n, mesh.cellCount(), mesh) if show: pg.show(mesh, S, label='S') pg.show(mesh, phi, label='p') pg.wait() r = pg.RMatrix(len(rB), len(rB[0])) for i, _ in enumerate(r): r[i] = rB[i] * a * phi**(-m) * S**(-n) r.round(1e-6) if meshI is None: if len(r) == 1: return r[0].copy() return r rI = pg.RMatrix(len(r), meshI.cellCount()) if meshI: pg.interpolate(mesh, r, meshI.cellCenters(), rI) if fill: for i, ri_ in enumerate(rI): # slope == True produce unstable behavior .. check!!!!!! rI[i] = mt.fillEmptyToCellArray(meshI, ri_, slope=False) rI.round(1e-6) if len(rI) == 1: # copy here because of missing refcounter TODO return rI[0].array() return rI
# fig = plt.figure(figsize=(11,7), dpi=100) # ax1 = fig.add_subplot(1,3,1) # ax2 = fig.add_subplot(1,3,2) # ax3 = fig.add_subplot(1,3,3) grid = pg.createGrid(x, y) fig = plt.figure() ax1 = fig.add_subplot(1, 3, 1) ax2 = fig.add_subplot(1, 3, 2) ax3 = fig.add_subplot(1, 3, 3) pl = pg.logTransDropTol(np.array((p.T).flat), 1e-2) ul = pg.logTransDropTol(np.array((u.T).flat), 1e-2) vl = pg.logTransDropTol(np.array((v.T).flat), 1e-2) pg.show(grid, pl, logScale=False, showLater=True, colorBar=True, axes=ax1, cmap='b2r') pg.show(grid, ul, logScale=False, showLater=True, colorBar=True, axes=ax2) pg.show(grid, vl, logScale=False, showLater=True, colorBar=True, axes=ax3) vel = np.vstack([np.array((u.T).flat), np.array((v.T).flat)]).T pg.mplviewer.drawStreams(ax1, grid, vel) #im1 = ax1.contourf(X,Y,p,alpha=0.5) ###plnttong the pressure field as a contour #divider1 = make_axes_locatable(ax1) #cax1 = divider1.append_axes("right", size="20%", pad=0.05) #cbar1 = plt.colorbar(im1, cax=cax1) #im2 = ax2.contourf(X,Y,u,alpha=0.5) ###plnttong the pressure field as a contour #divider2 = make_axes_locatable(ax2) #cax2 = divider2.append_axes("right", size="20%", pad=0.05)
m_with_bg = createMesh(self.poly, qual, smooth=smooth, node_move=False, area=area) if only_pd_mesh: pd = pg.Mesh(2) marker_start = 2 marker_end = -1 pd.createMeshByMarker(m_with_bg, marker_start, marker_end) return pd return m_with_bg def show(self, ax=None, **kwargs): """ Diplays the polygon model. """ if ax is None: figkeys = ("nrows", "ncols", "sharex", "sharey", "figsize") figargs = dict((k, kwargs.pop(k)) for k in figkeys if k in kwargs) f, ax = plt.subplots(**figargs) drawMesh(ax, self.poly, **kwargs) if __name__ == "__main__": p = Poly2D("example.xml") # Poly2D handles loading/creating a 2D-PLCs p.show() mesh = p.create_mesh() pg.show(mesh, mesh.cellMarker())
tri.setSwitches('-pzeAfaq31') ############################################################################### # For more information on the triangle switches and the corresponding settings, # the reader is referred to `the triangle website # <http://www.cs.cmu.edu/~quake/triangle.switch.html>`_. # # Now we can generate the unstructured mesh. mesh2 = pg.Mesh(2) tri.generate(mesh2) for cell in mesh2.cells(): cell.setMarker(1) ############################################################################### # Finally, the grid and the unstructured mesh can be merged to single mesh for # further modelling. mesh3 = merge2Meshes(mesh1, mesh2) ############################################################################### # Of course, you can treat the hybrid mesh like any other mesh and append a # triangle boundary for example with the function # :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`. mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, smooth=True, marker=3, isSubSurface=True) pg.show(mesh, markers=True, showMesh=True) pg.wait()
poly = pg.Mesh(2) for n in patch.get_verts() * 50: poly.createNodeWithCheck(n) for i in range(poly.nodeCount() - 1): poly.createEdge(poly.node(i), poly.node(i + 1)) poly.createEdge(poly.node(poly.nodeCount() - 1), poly.node(0)) ############################################################################### # We create mesh from the polygone and set the x values as the # data for a color transition. mesh = pg.meshtools.createMesh(poly, area=5) ############################################################################### # Last, we create a BERT caption, visualize the mesh and fine-tune the figure. fig, ax = plt.subplots(figsize=(4, 3)) ax.axis('off') offset = -10 t = ax.text(mesh.xmin() + (mesh.xmax()-mesh.xmin())/2, offset, 'BERT', horizontalalignment='center', size=40, fontweight='bold') pg.show(mesh, pg.x(mesh.cellCenters()), ax=ax, cMap='RdBu', logScale=False, showLater=True, showMesh=True) ax.set_ylim(offset, mesh.ymax()) pg.wait()
print(c, p, g) dux[i] = g[0] * 4.0 * np.pi # wo kommen die 4 pi her? duz[i] = -g[1] * 4.0 * np.pi # wo kommen die 4 pi her? uI = pg.interpolate(mesh, u, pnts) plt.plot(pg.x(pnts), dux, label='dux') plt.plot(pg.x(pnts), duz, label='duz') plt.plot(pg.x(pnts), pg.sqrt(dux*dux + duz*duz), label='du') dgz, dggz = solveGravimetry(circ, dDensity=1000, pnts=pnts, complete=1) plt.plot(pg.x(pnts), dgz[:,0], label='dgx') plt.plot(pg.x(pnts), dgz[:,2], label='dgz') plt.plot(pg.x(pnts), np.sqrt(dgz[:,0]**2 + dgz[:,1]**2 + dgz[:,2]**2), label='dg') print(dux/dgz[:,0]) print(duz/dgz[:,2]) #plt.plot(pg.x(pnts), uI, label='ui') plt.legend() ax, cbar= pg.show(mesh, data=u, showLater=1) pg.mplviewer.drawMesh(ax, mesh) plt.show()
############################################################################### # We start by creating a three-layered slope (The model is taken from the BSc # thesis of Constanze Reinken (University of Bonn). layer1 = mt.createPolygon([[0.0, 137], [117.5, 164], [117.5, 162], [0.0, 135]], isClosed=True, marker=1, area=1) layer2 = mt.createPolygon([[0.0, 126], [0.0, 135], [117.5, 162], [117.5, 153]], isClosed=True, marker=2) layer3 = mt.createPolygon([[0.0, 110], [0.0, 126], [117.5, 153], [117.5, 110]], isClosed=True, marker=3) slope = (164 - 137) / 117.5 geom = mt.mergePLC([layer1, layer2, layer3]) mesh = mt.createMesh(geom, quality=34.3, area=3, smooth=[1, 10]) pg.show(mesh) ############################################################################### # Next we define geophone positions and a measurement scheme, which consists of # shot and receiver indices. numberGeophones = 48 sensors = np.linspace(0., 117.5, numberGeophones) scheme = pg.physics.traveltime.createRAData(sensors) # Adapt sensor positions to slope pos = np.array(scheme.sensorPositions()) for x in pos[:, 0]: i = np.where(pos[:, 0] == x) new_y = x * slope + 137 pos[i, 1] = new_y
print("Forward calculation time: {} seconds.".format(time.time()-tic)) delta_t = np.array(data("t")) - t_fmm # f, ax = plt.subplots() # x = pg.x(data.sensorPositions()) # ax.plot(abs(delta_t), 'r-.', label='abs. diff') # ax.plot(delta_t, 'b-', label='diff') # ax.legend(loc='best') # f.show() # raise SystemExit() l = fwd._trace_back(50, 0) fig, a = plt.subplots() drawMesh(a, mesh) pg.show(mesh, axes=a, data=l[0]) cells = fwd.mesh().cells() active_cells = [cells[i] for i in range(mesh.cellCount()) if l[0][i]] # active_cells.append(cells[2044]) for c in active_cells: pos = c.center() gradient = 2000*c.grad(pos, fwd.timefields[0]) dx, dy = gradient.x(), gradient.y() a.text(pos.x(), pos.y(), str(c.id())) a.arrow(pos.x(), pos.y(), dx, dy) ray = fwd.poslist a.plot(pg.x(ray), pg.y(ray), 'm-*', ) plt.show()
################################################################################ # We now import pygimli and create simple grid/mesh with 3x3 cells. import pygimli as pg m = pg.createGrid(4,4) ################################################################################ # The following code creates the main plot and shows how the different mesh # entities can be called. # Create matplotlib figure and set size fig, ax = plt.subplots(figsize=(8,8), dpi=90) ax.set_title("The anatomy of a pyGIMLi mesh", fontweight="bold") # Visualize mesh with the generic pg.show command pg.show(m, ax=ax) # Number all cells for cell in m.cells(): node = cell.allNodes()[2] ax.text(node.x() - 0.5, node.y() - .05, "m.cell(%d)" % cell.id(), fontsize=11, ha="center", va="top", color="grey") # Mark horizontal and vertical extent circle(m.xmin(), m.xmax(), "m.xmin(),\nm.ymax() ", c="grey") circle(m.xmin(), m.ymin(), "m.xmin(),\nm.ymin() ", c="grey") circle(m.xmax(), m.ymin(), "m.xmax(),\nm.ymin() ", c="grey") circle(m.xmax(), m.ymax(), "m.xmax(),\nm.ymax() ", c="grey") # Mark center of a cell cid = 2
# t_fmm = fwd.response(1.0/np.array(vel)) pg.toc() # delta_t = np.array(data("t")) - t_fmm # f, ax = plt.subplots() # x = pg.x(data.sensorPositions()) # ax.plot(abs(delta_t), 'r-.', label='abs. diff') # ax.plot(delta_t, 'b-', label='diff') # ax.legend(loc='best') # f.show() # raise SystemExit() l = fwd._trace_back(50, 0) fig, a = plt.subplots() drawMesh(a, mesh) pg.show(mesh, axes=a, data=l[0]) cells = fwd.mesh().cells() active_cells = [cells[i] for i in range(mesh.cellCount()) if l[0][i]] # active_cells.append(cells[2044]) for c in active_cells: pos = c.center() gradient = 2000*c.grad(pos, fwd.timefields[0]) dx, dy = gradient.x(), gradient.y() a.text(pos.x(), pos.y(), str(c.id())) a.arrow(pos.x(), pos.y(), dx, dy) ray = fwd.poslist a.plot(pg.x(ray), pg.y(ray), 'm-*', ) plt.show()