def showMesh(self, ax=None): """show mesh in given axes or in a new figure""" if ax is None: fig, ax = plt.subplots() self.figs['mesh'] = fig self.axs['mesh'] = ax drawMesh(ax, self.mesh) plt.show(block=False)
def showMesh(self, ax=None, name='mesh'): """show mesh in given axes or in a new figure""" if ax is None: fig, ax = plt.subplots() self.figs[name] = fig self.axs[name] = ax drawMesh(ax, self.mesh) # plt.show(block=False) ax.set_aspect(1) return ax
def showMesh(self, ax=None, name='mesh'): """show mesh in given ax or in a new figure""" if ax is None: fig, ax = plt.subplots() self.figs[name] = fig self.axs[name] = ax drawMesh(ax, self.mesh) # plt.show(block=False) ax.set_aspect(1) return ax
def showMesh(mesh, data=None, showLater=False, colorBar=False, axes=None, *args, **kwargs): """ Syntactic sugar, short-cut to create axes and plot node or cell values return axes, cbar Parameters ---------- """ ret = [] ax = axes if ax == None: fig = plt.figure() ax = fig.add_subplot(1,1,1) gci = None cbar = None validData = False if data is None: drawMesh(ax, mesh) else: #print(data[0], type(data[0])) if hasattr(data[0], '__len__') and type(data) != np.ma.core.MaskedArray: if sum(data[:,0]) != sum(data[:,1]): drawStreamLines2(ax, mesh, data, *args, **kwargs) else: print("No valid stream data:", data) drawMesh(ax, mesh) elif min(data) == max(data): print(("No valid data", min(data), max(data))) drawMesh(ax, mesh) else: validData = True if len(data) == mesh.cellCount(): gci = drawModel(ax, mesh, data, *args, **kwargs) elif len(data) == mesh.nodeCount(): gci = drawField(ax, mesh, data, *args, **kwargs) ax.set_aspect('equal') if colorBar and validData: cbar = createColorbar(gci, *args, **kwargs) if not showLater: plt.show() #fig.show() #fig.canvas.draw() return ax, cbar
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 :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`. mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, smooth=True, marker=3, isSubSurface=True) ax, cbar = showMesh(mesh, mesh.cellMarkers(), cmap="summer", label="Region marker") drawMesh(ax, mesh) ax, _ = showMesh(mesh, mesh.cellMarkers(), logScale=False, label="Region marker") drawMesh(ax, mesh) pg.wait()
a = pg.RVector(mesh.cellCount(), 0.1) #Start FEM solution swatch = pg.Stopwatch(True) uDirichlet = [1, lambda p_: np.sin(np.arctan2(p_.center()[1], p_.center()[0]))/p_.center().abs()] uFEM = solver.solvePoisson(mesh, a=a, f=f, uBoundary=uDirichlet) print('FEM:', swatch.duration(True)) ax1, cbar = showMesh(mesh, data=uFEM, nLevs=12, cMin=0, cMax=10, colorBar=True, showLater=True) drawMesh(ax1, mesh) #print(min(u), max(u)) uAna = np.array(list(map(lambda p_: np.sin(np.arctan2(p_[1], p_[0]))/p_.abs(), mesh.positions()))) #drawStreamLines2(ax1, mesh, data=u) #ax2,cbar = showMesh(mesh, data=(u+1e-6)/(ua+1e-6), filled=True, colorBar=True, showLater=True) #showMesh(amesh) print('---:', swatch.duration(True)) uFV = solveFiniteVolume(mesh, a=a, f=f, uBoundary=uDirichlet) print('FVM:', swatch.duration(True))
def showMesh(mesh, data=None, hold=False, block=False, colorBar=False, coverage=None, axes=None, savefig=None, **kwargs): """ 2D Mesh visualization. Create an axes and plot node or cell values for the given 2d mesh. Returns the axes and the color bar. Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` 2D or 3D GIMLi mesh data : iterable [None] Optionally data to visualize. . None (draw mesh only) forward to :py:mod:`pygimli.mplviewer.meshview.drawMesh` . float per cell -- model, patch forward to :py:mod:`pygimli.mplviewer.meshview.drawModel` . float per node -- scalar field forward to :py:mod:`pygimli.mplviewer.meshview.drawField` . iterable of type [float, float] -- vector field forward to :py:mod:`pygimli.mplviewer.meshview.drawStreams` . pg.stdVectorRVector3 -- sensor positions forward to :py:mod:`pygimli.mplviewer.meshview.drawSensors` hold : bool [false] Set interactive plot mode for matplotlib. If this is set to false [default] your script will open a window with the figure and draw your content. If set to true nothing happens until you either force another show with hold=False, you call plt.show() or pg.wait(). If you want show with stopping your script set block = True. block : bool [false] Force show drawing your content and block the script until you close the current figure. colorBar : bool [false] Create and show a colorbar. coverage : iterable [None] Weight data by the given coverage array and fadeout the color. axes : matplotlib.Axes [None] Instead of create a new and empty axes, just draw into the a given. Useful to combine draws. savefig: string Filename for a direct save to disc. The matplotlib pdf-output is a little bit big so we try an epstopdf if the .eps suffix is found in savefig **kwargs : Will be forwarded to the draw functions and matplotlib methods, respectively. Returns ------- axes : matplotlib.axes colobar : matplotlib.colobar """ ax = axes if block: hold = 1 if hold: lastHoldStatus = pg.mplviewer.holdAxes_ pg.mplviewer.holdAxes_ = 1 if ax is None: fig, ax = plt.subplots() gci = None cbar = None validData = False if data is None: drawMesh(ax, mesh) elif isinstance(data, pg.stdVectorRVector3): drawSensors(ax, data) else: if hasattr(data[0], '__len__') and not isinstance(data, np.ma.core.MaskedArray): if len(data) == 2: # [u,v] data = np.array(data).T if sum(data[:, 0]) != sum(data[:, 1]): drawStreams(ax, mesh, data, **kwargs) else: print("No valid stream data:", data) drawMesh(ax, mesh) elif (min(data) == max(data)): # or pg.haveInfNaN(data): print("No valid data: ", min(data), max(data), pg.haveInfNaN(data)) drawMesh(ax, mesh) else: validData = True try: if len(data) == mesh.cellCount(): gci = drawModel(ax, mesh, data, **kwargs) elif len(data) == mesh.nodeCount(): gci = drawField(ax, mesh, data, **kwargs) except Exception as e: print("Exception occured: " + e) print("Data: ", min(data), max(data), pg.haveInfNaN(data)) print("Mesh: ", mesh) drawMesh(ax, mesh) ax.set_aspect('equal') label = kwargs.pop('label', None) if colorBar and validData: # , *args, **kwargs) # causes problems! cbar = createColorbar(gci, label=label, **kwargs) plt.tight_layout() if coverage is not None: if len(data) == mesh.cellCount(): addCoverageAlpha(gci, coverage) else: raise('toImplement') addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage)) if showLater in kwargs: hold = showLater print("showLater will be removed in the future. use hold instead") if not hold or block is not False: plt.show(block=block) try: plt.pause(0.01) except: pass if hold: pg.mplviewer.holdAxes_ = lastHoldStatus if savefig: print('saving: ' + savefig + ' ...') ax.figure.savefig(savefig, bbox_inches='tight') if '.eps' in savefig: try: print("trying eps2pdf ... ") os.system('epstopdf ' + savefig) except: pass print('..done') return ax, cbar
for i, n in enumerate(sec_nodes): ax[1, j].plot( px[1:], t_all[i] * 1000, label="Dijkstra (%d sec nodes, %.2f s)" % (n, durations[i])) ax[2, j].plot(px, np.zeros_like(px), label="Zero line") # to keep color cycle for i, n in enumerate(sec_nodes): ax[2, j].plot(px[1:], np.abs(t_all[i] - t_ana) * 1000) ax[1, j].legend() pg.show(mesh, vel, ax=ax[0, j], label="Velocity (m/s)", hold=True, logScale=False, cMap="summer_r", coverage=0.7) drawMesh(ax[0, j], mesh, color="white", lw=0.21) recs = [1, 3, 8, 13] cols = ["orangered", "blue", "black"] to_plot = [0, 1, 3] for i, k in enumerate(to_plot): n = sec_nodes[k] for r, p in enumerate(recs): if r == 0: lab = "Raypath with %d sec nodes" % n else: lab = None ax[0, j].plot(paths[i][p][0], paths[i][p][1], cols[i], label=lab) ax[0, j].plot(sensors[p], 0.0, "kv", ms=10)
while len(downwind) > 0: fastMarch(mesh, downwind, times, upTags, downTags) print(time.time() - tic, "s") # compare with analytical solution along the x axis x = np.arange(0., 100., 0.5) t = pg.interpolate(mesh, times, pg.asvector(x), x * 0., x * 0.) tdirect = x / v[0] # direct wave alfa = asin(v[0] / v[1]) # critically refracted wave angle xreflec = tan(alfa) * zlay * 2. # first critically refracted trefrac = (x - xreflec) / v[1] + xreflec * v[1] / v[0]**2 tana = np.where(trefrac < tdirect, trefrac, tdirect) # minimum of both print("min(dt)=", min(t - tana) * 1000, "ms max(dt)=", max(t - tana) * 1000, "ms") # plot traveltime field, a few lines fig = plt.figure() a = fig.add_subplot(211) drawMesh(a, mesh) drawField(a, mesh, times, True, 'Spectral') drawStreamLines(a, mesh, times, nx=50, ny=50) # plot calculated and measured travel times a2 = fig.add_subplot(212) plt.plot(x, t, 'b.-', x, tdirect, 'r-', x, trefrac, 'g-') plt.show()
t_fmm = fwd.response(cslo) # 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),
1, lambda p_: np.sin(np.arctan2(p_.center()[1], p_.center()[0])) / p_.center().abs() ] uFEM = solver.solvePoisson(mesh, a=a, f=f, uBoundary=uDirichlet) print('FEM:', swatch.duration(True)) ax1, cbar = showMesh(mesh, data=uFEM, nLevs=12, cMin=0, cMax=10, colorBar=True, showLater=True) drawMesh(ax1, mesh) #print(min(u), max(u)) uAna = np.array( list( map(lambda p_: np.sin(np.arctan2(p_[1], p_[0])) / p_.abs(), mesh.positions()))) #drawStreamLines2(ax1, mesh, data=u) #ax2,cbar = showMesh(mesh, data=(u+1e-6)/(ua+1e-6), filled=True, colorBar=True, showLater=True) #showMesh(amesh) print('---:', swatch.duration(True)) uFV = solveFiniteVolume(mesh, a=a, f=f, uBoundary=uDirichlet) print('FVM:', swatch.duration(True))
def showMesh(mesh, data=None, hold=False, block=False, colorBar=None, label=None, coverage=None, ax=None, savefig=None, **kwargs): """2D Mesh visualization. Create an axis object and plot a 2D mesh with given node or cell data. Returns the axis and the color bar. The type of data determine the appropriate draw method. Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` 2D or 3D GIMLi mesh data : iterable [None] Optionally data to visualize. . None (draw mesh only) forward to :py:mod:`pygimli.mplviewer.drawMesh` or if no cells are given: forward to :py:mod:`pygimli.mplviewer.drawPLC` . float per cell -- model, patch forward to :py:mod:`pygimli.mplviewer.drawModel` . float per node -- scalar field forward to :py:mod:`pygimli.mplviewer.drawField` . iterable of type [float, float] -- vector field forward to :py:mod:`pygimli.mplviewer.drawStreams` . pg.stdVectorRVector3 -- sensor positions forward to :py:mod:`pygimli.mplviewer.drawSensors` hold : bool [false] Set interactive plot mode for matplotlib. If this is set to false [default] your script will open a window with the figure and draw your content. If set to true nothing happens until you either force another show with hold=False, you call plt.show() or pg.wait(). If you want show with stopping your script set block = True. block : bool [false] Force show drawing your content and block the script until you close the current figure. colorBar : bool [None], Colorbar Create and show a colorbar. If colorBar is a valid colorbar then only his values will be updated. label : str Set colorbar label. If set colorbar is toggled to True. [None] coverage : iterable [None] Weight data by the given coverage array and fadeout the color. ax : matplotlib.Axes [None] Instead of create a new and empty ax, just draw into the a given. Useful to combine draws. savefig: string Filename for a direct save to disc. The matplotlib pdf-output is a little bit big so we try an epstopdf if the .eps suffix is found in savefig **kwargs : * xlabel : str [None] Add label to the x axis * ylabel : str [None] Add label to the y axis * all remaining Will be forwarded to the draw functions and matplotlib methods, respectively. Returns ------- ax : matplotlib.ax colobar : matplotlib.colobar """ ax = ax if block: hold = 1 if hold: lastHoldStatus = pg.mplviewer.utils.holdAxes__ pg.mplviewer.hold(val=1) # print('1*'*50) # print(locale.localeconv()) if ax is None: ax = plt.subplots()[1] # plt.subplots() resets locale setting to system default .. this went # horrible wrong for german 'decimal_point': ',' pg.checkAndFixLocaleDecimal_point(verbose=False) # print('2*'*50) # print(locale.localeconv()) gci = None validData = False if data is None: drawMesh(ax, mesh, **kwargs) elif isinstance(data, pg.stdVectorRVector3): drawSensors(ax, data, **kwargs) else: # print(data, type(data)) if (hasattr(data[0], '__len__') and not isinstance(data, np.ma.core.MaskedArray)): if len(data) == 2: # [u,v] data = np.array(data).T if sum(data[:, 0]) != sum(data[:, 1]): drawStreams(ax, mesh, data, **kwargs) else: print("No valid stream data:", data) drawMesh(ax, mesh, **kwargs) elif min(data) == max(data): # or pg.haveInfNaN(data): print("No valid data: ", min(data), max(data), pg.haveInfNaN(data)) drawMesh(ax, mesh, **kwargs) else: validData = True try: if len(data) == mesh.cellCount(): gci = drawModel(ax, mesh, data, **kwargs) elif len(data) == mesh.nodeCount(): gci = drawField(ax, mesh, data, **kwargs) cmap = kwargs.pop('cmap', None) cMap = kwargs.pop('cMap', None) if cMap is not None: cmap = cMap if cmap is not None: gci.set_cmap(cmapFromName(cmap)) except BaseException as e: print("Exception occured: " + e) print("Data: ", min(data), max(data), pg.haveInfNaN(data)) print("Mesh: ", mesh) drawMesh(ax, mesh, **kwargs) ax.set_aspect('equal') cbar = None if label is not None and colorBar is None: colorBar = True if colorBar and validData: # , **kwargs) # causes problems! labels = ['cMin', 'cMax', 'nLevs', 'orientation', 'pad'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} if colorBar is True or colorBar is 1: cbar = createColorBar(gci, label=label, **subkwargs) elif colorBar is not False: cbar = updateColorBar(colorBar, gci, label=label, **subkwargs) if coverage is not None: if len(data) == mesh.cellCount(): addCoverageAlpha(gci, coverage) else: raise BaseException('toImplement') # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage)) if not hold or block is not False: if data is not None: if len(data) == mesh.cellCount(): cb = CellBrowser(mesh, data, ax=ax) cb.connect() plt.show(block=block) try: plt.pause(0.01) except BaseException as _: pass if hold: pg.mplviewer.hold(val=lastHoldStatus) if savefig: print('saving: ' + savefig + ' ...') if '.' not in savefig: savefig += '.pdf' ax.figure.savefig(savefig, bbox_inches='tight') # rc params savefig.format=pdf if '.eps' in savefig: try: print("trying eps2pdf ... ") os.system('epstopdf ' + savefig) except BaseException as _: pass print('..done') return ax, cbar
def showMesh(mesh, data=None, hold=False, block=False, colorBar=None, label=None, coverage=None, ax=None, savefig=None, showMesh=False, showBoundary=None, markers=False, **kwargs): """2D Mesh visualization. Create an axis object and plot a 2D mesh with given node or cell data. Returns the axis and the color bar. The type of data determines the appropriate draw method. Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` 2D or 3D GIMLi mesh data : iterable [None] Optionally data to visualize. . None (draw mesh only) forward to :py:mod:`pygimli.mplviewer.drawMesh` or if no cells are given: forward to :py:mod:`pygimli.mplviewer.drawPLC` . [[marker, value], ...] List of Cellvalues per cell marker forward to :py:mod:`pygimli.mplviewer.drawModel` . float per cell -- model, patch forward to :py:mod:`pygimli.mplviewer.drawModel` . float per node -- scalar field forward to :py:mod:`pygimli.mplviewer.drawField` . iterable of type [float, float] -- vector field forward to :py:mod:`pygimli.mplviewer.drawStreams` . pg.R3Vector -- vector field forward to :py:mod:`pygimli.mplviewer.drawStreams` . pg.stdVectorRVector3 -- sensor positions forward to :py:mod:`pygimli.mplviewer.drawSensors` hold : bool [false] Set interactive plot mode for matplotlib. If this is set to false [default] your script will open a window with the figure and draw your content. If set to true nothing happens until you either force another show with hold=False, you call plt.show() or pg.wait(). If you want show with stopping your script set block = True. block : bool [false] Force show drawing your content and block the script until you close the current figure. colorBar : bool [None], Colorbar Create and show a colorbar. If colorBar is a valid colorbar then only its values will be updated. label : str Set colorbar label. If set colorbar is toggled to True. [None] coverage : iterable [None] Weight data by the given coverage array and fadeout the color. ax : matplotlib.Axes [None] Instead of creating a new and empty ax, just draw into the given one. Useful to combine multiple plots into one figure. savefig: string Filename for a direct save to disc. The matplotlib pdf-output is a little bit big so we try an epstopdf if the .eps suffix is found in savefig showMesh : bool [False] Shows the mesh itself aditional. showBoundary : bool [None] Shows all boundary with marker != 0. A value None means automatic True for cell data and False for node data. marker : bool [False] Show mesh and boundary marker. **kwargs : * xlabel : str [None] Add label to the x axis * ylabel : str [None] Add label to the y axis * all remaining Will be forwarded to the draw functions and matplotlib methods, respectively. Examples -------- >>> import pygimli as pg >>> import pygimli.meshtools as mt >>> world = mt.createWorld(start=[-10, 0], end=[10, -10], ... layers=[-3, -7], worldMarker=False) >>> mesh = mt.createMesh(world, quality=32, area=0.2, smooth=[1, 10]) >>> _ = pg.viewer.showMesh(mesh, markers=True) Returns ------- ax : matplotlib.axes colobar : matplotlib.colorbar """ pg.renameKwarg('cmap', 'cMap', kwargs) if ax is None: ax = plt.subplots()[1] # print('1*'*50) # print(locale.localeconv()) # plt.subplots() resets locale setting to system default .. this went # horrible wrong for german 'decimal_point': ',' pg.checkAndFixLocaleDecimal_point(verbose=False) # print('2*'*50) # print(locale.localeconv()) if block: hold = True lastHoldStatus = pg.mplviewer.utils.holdAxes__ if not lastHoldStatus or hold: pg.mplviewer.hold(val=1) hold = True gci = None validData = False if markers: kwargs["boundaryMarker"] = True if mesh.cellCount() > 0: uniquemarkers, uniqueidx = np.unique( np.array(mesh.cellMarkers()), return_inverse=True) label = "Cell markers" kwargs["cMap"] = plt.cm.get_cmap("Set3", len(uniquemarkers)) kwargs["logScale"] = False kwargs["cMin"] = -0.5 kwargs["cMax"] = len(uniquemarkers) - 0.5 data = np.arange(len(uniquemarkers))[uniqueidx] if data is None: showMesh = True if showBoundary is None: showBoundary = True elif isinstance(data, pg.stdVectorRVector3): drawSensors(ax, data, **kwargs) elif isinstance(data, pg.R3Vector): drawStreams(ax, mesh, data, **kwargs) else: ### data=[[marker, val], ....] if isinstance(data, list) and \ isinstance(data[0], list) and isinstance(data[0][0], int): data = pg.solver.parseMapToCellArray(data, mesh) if hasattr(data[0], '__len__') and not \ isinstance(data, np.ma.core.MaskedArray): if len(data) == 2: # [u,v] x N data = np.array(data).T if data.shape[1] == 2: drawStreams(ax, mesh, data, **kwargs) elif data.shape[1] == 3: # probably N x [u,v,w] # if sum(data[:, 0]) != sum(data[:, 1]): # drawStreams(ax, mesh, data, **kwargs) drawStreams(ax, mesh, data[:, 0:2], **kwargs) else: pg.warn("No valid stream data:", data.shape, data.ndim) showMesh = True elif min(data) == max(data): # or pg.haveInfNaN(data): pg.warn("No valid data: ", min(data), max(data), pg.haveInfNaN(data)) showMesh = True else: validData = True try: cMap = kwargs.pop('cMap', None) if len(data) == mesh.cellCount(): gci = drawModel(ax, mesh, data, **kwargs) if showBoundary is None: showBoundary = True elif len(data) == mesh.nodeCount(): gci = drawField(ax, mesh, data, **kwargs) if cMap is not None: gci.set_cmap(cmapFromName(cMap)) #gci.cmap.set_under('k') except BaseException as e: print("Exception occured: ", e) print("Data: ", min(data), max(data), pg.haveInfNaN(data)) print("Mesh: ", mesh) drawMesh(ax, mesh, **kwargs) if mesh.cellCount() == 0: showMesh = False if mesh.boundaryCount() == 0: pg.mplviewer.drawPLC(ax, mesh, showNodes=True, fillRegion=False, showBoundary=False, **kwargs) showBoundary = False #ax.plot(pg.x(mesh), pg.y(mesh), '.', color='black') else: pg.mplviewer.drawPLC(ax, mesh, **kwargs) if showMesh: if gci is not None and hasattr(gci, 'set_antialiased'): gci.set_antialiased(True) gci.set_linewidth(0.3) gci.set_edgecolor("0.1") else: pg.mplviewer.drawSelectedMeshBoundaries(ax, mesh.boundaries(), color="0.1", linewidth=0.3) #drawMesh(ax, mesh, **kwargs) if showBoundary is True or showBoundary is 1: b = mesh.boundaries(mesh.boundaryMarkers() != 0) pg.mplviewer.drawSelectedMeshBoundaries(ax, b, color=(0.0, 0.0, 0.0, 1.0), linewidth=1.4) fitView = kwargs.pop('fitView', True) if fitView: ax.set_xlim(mesh.xmin(), mesh.xmax()) ax.set_ylim(mesh.ymin(), mesh.ymax()) ax.set_aspect('equal') cbar = None if label is not None and colorBar is None: colorBar = True if colorBar and validData: # , **kwargs) # causes problems! labels = ['cMin', 'cMax', 'nLevs', 'cMap', 'logScale'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} subkwargs['label'] = label if colorBar is True or colorBar is 1: cbar = createColorBar(gci, orientation=kwargs.pop('orientation', 'horizontal'), size=kwargs.pop('size', 0.2), pad=kwargs.pop('pad', None) ) updateColorBar(cbar, **subkwargs) elif colorBar is not False: cbar = updateColorBar(colorBar, **subkwargs) if markers: ticks = np.arange(len(uniquemarkers)) cbar.set_ticks(ticks) labels = [] for marker in uniquemarkers: labels.append(str((marker))) cbar.set_ticklabels(labels) if coverage is not None: if len(data) == mesh.cellCount(): addCoverageAlpha(gci, coverage) else: raise BaseException('toImplement') # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage)) if not hold or block is not False and plt.get_backend() is not "Agg": if data is not None: if len(data) == mesh.cellCount(): cb = CellBrowser(mesh, data, ax=ax) plt.show(block=block) try: plt.pause(0.01) except BaseException as _: pass if hold: pg.mplviewer.hold(val=lastHoldStatus) if savefig: print('saving: ' + savefig + ' ...') if '.' not in savefig: savefig += '.pdf' ax.figure.savefig(savefig, bbox_inches='tight') # rc params savefig.format=pdf if '.eps' in savefig: try: print("trying eps2pdf ... ") os.system('epstopdf ' + savefig) except BaseException: pass print('..done') return ax, cbar
for nn in tmpNodes: if not upTags[nn.id()] and not downTags[nn.id()]: downwind.add(nn) downTags[nn.id()] = 1 # start fast marching tic = time.time() while len(downwind) > 0: fastMarch(mesh, downwind, times, upTags, downTags) print(time.time() - tic, "s") # compare with analytical solution along the x axis x = np.arange(-20., 150., 0.5) t = pg.interpolate(mesh, times, pg.asvector(x), x * 0., x * 0.) tdirect = np.abs(x) / v[0] # direct wave alfa = asin(v[0] / v[1]) # critically refracted wave angle xreflec = tan(alfa) * zlay * 2. # first critically refracted trefrac = (np.abs(x) - xreflec) / v[1] + xreflec * v[1] / v[0]**2 tana = np.where(trefrac < tdirect, trefrac, tdirect) # minimum of both print("min(dt)=", min(t-tana)*1e3, "ms max(dt)=", max(t-tana)*1e3, "ms") # %% plot traveltime field, a few lines fig, ax = plt.subplots(nrows=2, sharex=True) drawMesh(ax[0], mesh) drawField(ax[0], mesh, times, True) drawStreamLines(ax[0], mesh, times, color='white') # plot calculated and measured travel times ax[1].plot(x, t, 'b.-', x, tdirect, 'r-', x, trefrac, 'g-') plt.show()
if not upTags[nn.id()] and not downTags[nn.id()]: downwind.add(nn) downTags[nn.id()] = 1 ############################################################################### # Then we start marching until all fields are filled. tic = time.time() while len(downwind) > 0: fastMarch(mesh, downwind, times, upTags, downTags) print(time.time() - tic, "s") ############################################################################### # First, we plot the traveltime field and streamlines fig, ax = plt.subplots(figsize=(10, 5)) drawMesh(ax, mesh) ax.set_xlabel('x [m]') ax.set_ylabel('y [m]') drawField(ax, mesh, times, cmap='Spectral', fillContour=True) drawStreamLines(ax, mesh, -times, nx=50, ny=50) ############################################################################### # We compare the result with the analytical solution along the x axis x = np.arange(0., 140., 0.5) tFMM = pg.interpolate(mesh, times, x, x * 0., x * 0.) tAna = analyticalSolution2Layer(x) print("min(dt)={} ms max(dt)={} ms".format( min(tFMM - tAna) * 1000, max(tFMM - tAna) * 1000)) ###############################################################################
return outdata ############################################################################### # Visualization # ------------- meshes = [coarse, fine] datasets = [coarse_data, fine_data] ints = [nearest_neighbor_interpolation, linear_interpolation] fig, axes = plt.subplots(2, 2, figsize=(5, 5)) # Coarse data to fine mesh drawModel(axes[0, 0], fine, ints[0](coarse, coarse_data, fine), showCbar=False) drawMesh(axes[0, 0], fine) drawModel(axes[0, 1], fine, ints[1](coarse, coarse_data, fine), showCbar=False) drawMesh(axes[0, 1], fine) # Fine data to coarse mesh drawModel(axes[1, 0], coarse, ints[0](fine, fine_data, coarse), showCbar=False) drawMesh(axes[1, 0], coarse) drawModel(axes[1, 1], coarse, ints[1](fine, fine_data, coarse), showCbar=False) drawMesh(axes[1, 1], coarse) titles = ["Coarse to fine\nwith nearest neighbors", "Coarse to fine\nwith linear interpolation", "Fine to coarse\nwith nearest neighbors", "Fine to coarse\nwith linear interpolation"] for a, title in zip(axes.flat, titles):
def test(): """WRITEME.""" mesh = pg.Mesh('mesh/test2d') mesh.createNeighbourInfos() print(mesh) source = pg.RVector3(-80, 0.) times = pg.RVector(mesh.nodeCount(), 0.) for c in mesh.cells(): if c.marker() == 1: c.setAttribute(1.) elif c.marker() == 2: c.setAttribute(0.5) # c.setAttribute(abs(1./c.center()[1])) fig = plt.figure() ax = fig.subplot(1, 1, 1) anaTimes = pg.RVector(mesh.nodeCount(), 0.0) for n in mesh.nodes(): anaTimes[n.id()] = source.distance(n.pos()) # d = pg.DataContainer() # dijk = pg.TravelTimeDijkstraModelling(mesh, d) # upwind = set() downwind = set() upTags = np.zeros(mesh.nodeCount()) downTags = np.zeros(mesh.nodeCount()) # define initial condition cell = mesh.findCell(source) for n in cell.nodes(): times[n.id()] = cell.attribute() * n.pos().distance(source) upTags[n.id()] = 1 for n in cell.nodes(): tmpNodes = pg.commonNodes(n.cellSet()) for nn in tmpNodes: if not upTags[nn.id()] and not downTags[nn.id()]: downwind.add(nn) downTags[nn.id()] = 1 # start fast marching tic = time.time() while len(downwind) > 0: # model = pg.RVector(mesh.cellCount(), 0.0) # for c in upwind: model.setVal(2, c.id()) # for c in downwind: model.setVal(1, c.id()) # drawMesh(a, mesh) # a.plot(source[0], source[1], 'x') # for c in mesh.cells(): # a.text(c.center()[0],c.center()[1], str(c.id())) # for n in mesh.nodes(): # if upTags[n.id()]: # a.plot(n.pos()[0], n.pos()[1], 'o', color='black') # mindist = 9e99 # for n in downwind: # a.plot(n.pos()[0], n.pos()[1], 'o', color='white') # if n.pos().distance(source) < mindist: # mindist = n.pos().distance(source) # nextPredict = n # print "next predicted ", n.id(), mindist # a.plot(nextPredict.pos()[0], nextPredict.pos()[1], # 'o', color='green') # drawField(a, mesh, times) # drawField(a, mesh, anaTimes, colors = 'white') # a.figure.canvas.draw() # a.figure.show() # raw_input('Press Enter...') # a.clear() fastMarch(mesh, downwind, times, upTags, downTags) print(time.time() - tic, "s") drawMesh(ax, mesh) drawField(ax, mesh, times, filled=True)
def showMesh(mesh, data=None, hold=False, block=False, colorBar=None, label=None, coverage=None, ax=None, savefig=None, showMesh=False, showBoundary=None, markers=False, **kwargs): """2D Mesh visualization. Create an axis object and plot a 2D mesh with given node or cell data. Returns the axis and the color bar. The type of data determine the appropriate draw method. Parameters ---------- mesh : :gimliapi:`GIMLI::Mesh` 2D or 3D GIMLi mesh data : iterable [None] Optionally data to visualize. . None (draw mesh only) forward to :py:mod:`pygimli.mplviewer.drawMesh` or if no cells are given: forward to :py:mod:`pygimli.mplviewer.drawPLC` . [[marker, value], ...] List of Cellvalues per cell marker forward to :py:mod:`pygimli.mplviewer.drawModel` . float per cell -- model, patch forward to :py:mod:`pygimli.mplviewer.drawModel` . float per node -- scalar field forward to :py:mod:`pygimli.mplviewer.drawField` . iterable of type [float, float] -- vector field forward to :py:mod:`pygimli.mplviewer.drawStreams` . pg.R3Vector -- vector field forward to :py:mod:`pygimli.mplviewer.drawStreams` . pg.stdVectorRVector3 -- sensor positions forward to :py:mod:`pygimli.mplviewer.drawSensors` hold : bool [false] Set interactive plot mode for matplotlib. If this is set to false [default] your script will open a window with the figure and draw your content. If set to true nothing happens until you either force another show with hold=False, you call plt.show() or pg.wait(). If you want show with stopping your script set block = True. block : bool [false] Force show drawing your content and block the script until you close the current figure. colorBar : bool [None], Colorbar Create and show a colorbar. If colorBar is a valid colorbar then only its values will be updated. label : str Set colorbar label. If set colorbar is toggled to True. [None] coverage : iterable [None] Weight data by the given coverage array and fadeout the color. ax : matplotlib.Axes [None] Instead of create a new and empty ax, just draw into the a given. Useful to combine draws. savefig: string Filename for a direct save to disc. The matplotlib pdf-output is a little bit big so we try an epstopdf if the .eps suffix is found in savefig showMesh : bool [False] Shows the mesh itself aditional. showBoundary : bool [None] Shows all boundary with marker != 0. A value None means automatic True for cell data and False for node data. marker : bool [False] Show mesh and boundary marker. **kwargs : * xlabel : str [None] Add label to the x axis * ylabel : str [None] Add label to the y axis * all remaining Will be forwarded to the draw functions and matplotlib methods, respectively. Examples -------- >>> import pygimli as pg >>> import pygimli.meshtools as mt >>> world = mt.createWorld(start=[-10, 0], end=[10, -10], ... layers=[-3, -7], worldMarker=False) >>> mesh = mt.createMesh(world, quality=32, area=0.2, smooth=[1, 10]) >>> _ = pg.viewer.showMesh(mesh, markers=True) Returns ------- ax : matplotlib.axes colobar : matplotlib.colorbar """ pg.renameKwarg('cmap', 'cMap', kwargs) if ax is None: ax = plt.subplots()[1] # print('1*'*50) # print(locale.localeconv()) # plt.subplots() resets locale setting to system default .. this went # horrible wrong for german 'decimal_point': ',' pg.checkAndFixLocaleDecimal_point(verbose=False) # print('2*'*50) # print(locale.localeconv()) if block: hold = True if hold: lastHoldStatus = pg.mplviewer.utils.holdAxes__ pg.mplviewer.hold(val=1) gci = None validData = False if markers: kwargs["boundaryMarker"] = True if mesh.cellCount() > 0: uniquemarkers, uniqueidx = np.unique(np.array(mesh.cellMarkers()), return_inverse=True) label = "Cell markers" kwargs["cMap"] = plt.cm.get_cmap("Set3", len(uniquemarkers)) kwargs["logScale"] = False kwargs["cMin"] = -0.5 kwargs["cMax"] = len(uniquemarkers) - 0.5 data = np.arange(len(uniquemarkers))[uniqueidx] if data is None: showMesh = True if showBoundary is None: showBoundary = True elif isinstance(data, pg.stdVectorRVector3): drawSensors(ax, data, **kwargs) elif isinstance(data, pg.R3Vector): drawStreams(ax, mesh, data, **kwargs) else: #print('-----------------------------') #print(data, type(data)) #print('-----------------------------') ### data=[[marker, val], ....] if isinstance(data, list) and \ isinstance(data[0], list) and isinstance(data[0][0], int): data = pg.solver.parseMapToCellArray(data, mesh) if hasattr(data[0], '__len__') and not \ isinstance(data, np.ma.core.MaskedArray): if len(data) == 2: # [u,v] x N data = np.array(data).T if data.shape[1] == 2: drawStreams(ax, mesh, data, **kwargs) elif data.shape[1] == 3: # probably N x [u,v,w] # if sum(data[:, 0]) != sum(data[:, 1]): # drawStreams(ax, mesh, data, **kwargs) drawStreams(ax, mesh, data[:, 0:2], **kwargs) else: pg.warn("No valid stream data:", data.shape, data.ndim) showMesh = True elif min(data) == max(data): # or pg.haveInfNaN(data): pg.warn("No valid data: ", min(data), max(data), pg.haveInfNaN(data)) showMesh = True else: validData = True try: if len(data) == mesh.cellCount(): gci = drawModel(ax, mesh, data, **kwargs) if showBoundary is None: showBoundary = True elif len(data) == mesh.nodeCount(): gci = drawField(ax, mesh, data, **kwargs) cMap = kwargs.pop('cMap', None) if cMap is not None: gci.set_cmap(cmapFromName(cMap)) except BaseException as e: print("Exception occured: ", e) print("Data: ", min(data), max(data), pg.haveInfNaN(data)) print("Mesh: ", mesh) drawMesh(ax, mesh, **kwargs) if mesh.cellCount() == 0: showMesh = False if mesh.boundaryCount() == 0: pg.mplviewer.drawPLC(ax, mesh, showNodes=True, fillRegion=False, showBoundary=False, **kwargs) showBoundary = False #ax.plot(pg.x(mesh), pg.y(mesh), '.', color='black') else: pg.mplviewer.drawPLC(ax, mesh, **kwargs) if showMesh: if gci is not None and hasattr(gci, 'set_antialiased'): gci.set_antialiased(True) gci.set_linewidth(0.3) gci.set_edgecolor("0.1") else: pg.mplviewer.drawSelectedMeshBoundaries(ax, mesh.boundaries(), color="0.1", linewidth=0.3) #drawMesh(ax, mesh, **kwargs) if showBoundary is True or showBoundary is 1: b = mesh.boundaries(mesh.boundaryMarkers() != 0) pg.mplviewer.drawSelectedMeshBoundaries(ax, b, color=(0.0, 0.0, 0.0, 1.0), linewidth=1.4) fitView = kwargs.pop('fitView', True) if fitView: ax.set_xlim(mesh.xmin(), mesh.xmax()) ax.set_ylim(mesh.ymin(), mesh.ymax()) ax.set_aspect('equal') cbar = None if label is not None and colorBar is None: colorBar = True if colorBar and validData: # , **kwargs) # causes problems! labels = ['cMin', 'cMax', 'nLevs', 'cMap', 'logScale'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} subkwargs['label'] = label if colorBar is True or colorBar is 1: cbar = createColorBar(gci, orientation=kwargs.pop( 'orientation', 'horizontal'), size=kwargs.pop('size', 0.2), pad=kwargs.pop('pad', None)) updateColorBar(cbar, **subkwargs) elif colorBar is not False: cbar = updateColorBar(colorBar, **subkwargs) if markers: ticks = np.arange(len(uniquemarkers)) cbar.set_ticks(ticks) labels = [] for marker in uniquemarkers: labels.append(str((marker))) cbar.set_ticklabels(labels) if coverage is not None: if len(data) == mesh.cellCount(): addCoverageAlpha(gci, coverage) else: raise BaseException('toImplement') # addCoverageAlpha(gci, pg.cellDataToPointData(mesh, coverage)) if not hold or block is not False and plt.get_backend() is not "Agg": if data is not None: if len(data) == mesh.cellCount(): cb = CellBrowser(mesh, data, ax=ax) plt.show(block=block) try: plt.pause(0.01) except BaseException as _: pass if hold: pg.mplviewer.hold(val=lastHoldStatus) if savefig: print('saving: ' + savefig + ' ...') if '.' not in savefig: savefig += '.pdf' ax.figure.savefig(savefig, bbox_inches='tight') # rc params savefig.format=pdf if '.eps' in savefig: try: print("trying eps2pdf ... ") os.system('epstopdf ' + savefig) except BaseException: pass print('..done') return ax, cbar
return outdata ############################################################################### # Visualization # ------------- meshes = [coarse, fine] datasets = [coarse_data, fine_data] ints = [nearest_neighbor_interpolation, linear_interpolation] fig, ax = plt.subplots(2, 2, figsize=(5, 5)) # Coarse data to fine mesh drawModel(ax[0, 0], fine, ints[0](coarse, coarse_data, fine), showCbar=False) drawMesh(ax[0, 0], fine) drawModel(ax[0, 1], fine, ints[1](coarse, coarse_data, fine), showCbar=False) drawMesh(ax[0, 1], fine) # Fine data to coarse mesh drawModel(ax[1, 0], coarse, ints[0](fine, fine_data, coarse), showCbar=False) drawMesh(ax[1, 0], coarse) drawModel(ax[1, 1], coarse, ints[1](fine, fine_data, coarse), showCbar=False) drawMesh(ax[1, 1], coarse) titles = [ "Coarse to fine\nwith nearest neighbors", "Coarse to fine\nwith linear interpolation", "Fine to coarse\nwith nearest neighbors", "Fine to coarse\nwith linear interpolation" ]
[grid.findBoundaryByMarker(2), 2.0], # right [grid.findBoundaryByMarker(3), lambda p: 3.0 + p[0]], # top [grid.findBoundaryByMarker(4), uDirichlet]] # bottom """ The BC are passed using the uBoundary keyword. Note that showMesh returns the created figure axes ax while drawMesh plots on it and it can also be used as a class with plotting or decoration methods. """ u = solvePoisson(grid, f=1., uBoundary=dirichletBC) ax = showMesh(grid, data=u, filled=True, colorBar=True, orientation='vertical', label='Solution $u$', levels=np.linspace(1.0, 4.0, 17), showLater=True)[0] drawMesh(ax, grid) ax.text( 0.0, 1.02, '$u=1$') ax.text(-1.08, 0.0, '$u=2$', rotation='vertical') ax.text( 0.0, -1.08, '$u=3+x$') ax.text( 1.02, 0.0, '$u=4$', rotation='vertical') ax.set_title('$\\nabla\cdot(1\\nabla u)=1$') ax.set_xlim([-1.1, 1.1]) # some boundary for the text ax.set_ylim([-1.1, 1.1]) """ .. image:: PLOT2RST.current_figure :scale: 75
[2, mixedBC], #right boundary ] dirichletBC = [[4, 0]] #bottom boundary k = 0.1 uFE = solver.solveFiniteElements(grid, a=a, b=k*k, f=pointSource, duBoundary=neumannBC, uBoundary=dirichletBC, userData={'sourcePos': sourcePosA, 'k': k}, verbose=True) pg.showLater(1) ax1, cb = show(grid, uFE, cMin=0, cMax=1, nLevs=10, colorBar=True) drawMesh(ax1, grid) f = pg.RVector(grid.cellCount(), 0) f[grid.findCell(sourcePosA).id()]=1.0/grid.findCell(sourcePosA).size() uFV = solveFiniteVolume(grid, a=a, b=k*k, f=f, duBoundary=neumannBC, uBoundary=dirichletBC, userData={'sourcePos': sourcePosA, 'k': k}, verbose=True) #print('FVM:', swatch.duration(True)) ax2, cb = show(grid, uFV, interpolate=1, tri=1, cMin=0, cMax=1, nLevs=10, colorBar=True)