def restore(self): """Read data from json infos""" if os.path.exists(self._name + '.json'): # Fricking mpl kills locale setting to system default .. this went # horrible wrong for german 'decimal_point': ',' pg.checkAndFixLocaleDecimal_point(verbose=False) try: with open(self._name + '.json') as file: self.info = json.load(file) # if len(self.info['type']) != 1: # pg.error('only single return caches supported for now.') #pg._y(pg.pf(self.info)) if self.info['type'] == 'DataContainerERT': self._value = pg.DataContainerERT(self.info['file'], removeInvalid=False) # print(self._value) elif self.info['type'] == 'RVector': self._value = pg.Vector() self._value.load(self.info['file'], format=pg.core.Binary) elif self.info['type'] == 'Mesh': pg.tic() self._value = pg.Mesh() self._value.loadBinaryV2(self.info['file'] + '.bms') pg.debug("Restoring cache took:", pg.dur(), "s") elif self.info['type'] == 'ndarray': self._value = np.load(self.info['file'] + '.npy', allow_pickle=True) elif self.info['type'] == 'Cm05Matrix': self._value = pg.matrix.Cm05Matrix(self.info['file']) elif self.info['type'] == 'GeostatisticConstraintsMatrix': self._value = pg.matrix.GeostatisticConstraintsMatrix( self.info['file']) else: self._value = np.load(self.info['file'] + '.npy', allow_pickle=True) if self.value is not None: self.info['restored'] = self.info['restored'] + 1 self.updateCacheInfo() pg.info('Cache {3} restored ({1}s x {0}): {2}'.\ format(self.info['restored'], round(self.info['dur'], 1), self._name, self.info['codeinfo'])) else: # default try numpy pg.warn('Could not restore cache of type {0}.'.format(self.info['type'])) pg.debug("Restoring cache took:", pg.dur(), "s") except Exception as e: import traceback traceback.print_exc(file=sys.stdout) print(self.info) pg.error('Cache restoring failed.')
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
def showERTData(data, vals=None, **kwargs): """Plot ERT data as pseudosection matrix (position over separation). Creates figure, axis and draw a pseudosection. Parameters ---------- data : :gimliapi:`BERT::DataContainerERT` **kwargs : * axes : matplotlib.axes Axes to plot into. Default is None and a new figure and axes are created. * vals : Array[nData] Values to be plotted. Default is data('rhoa'). """ var = kwargs.pop('var', 0) if var > 0: import pybert as pb pg._g(kwargs) return pb.showData(data, vals, var=var, **kwargs) # remove ax keyword global ax = kwargs.pop('ax', None) if ax is None: fig = pg.plt.figure() ax = None axTopo = None if 'showTopo' in kwargs: ax = fig.add_subplot(1, 1, 1) # axs = fig.subplots(2, 1, sharex=True) # # Remove horizontal space between axes # fig.subplots_adjust(hspace=0) # ax = axs[1] # axTopo = axs[0] else: ax = fig.add_subplot(1, 1, 1) pg.checkAndFixLocaleDecimal_point(verbose=False) if vals is None: vals = 'rhoa' if isinstance(vals, str): if data.haveData(vals): vals = data(vals) else: pg.critical('field not in data container: ', vals) kwargs['cMap'] = kwargs.pop('cMap', pg.utils.cMap('rhoa')) kwargs['label'] = kwargs.pop('label', pg.utils.unit('rhoa')) kwargs['logScale'] = kwargs.pop('logScale', min(vals) > 0.0) ax, cbar = drawERTData(ax, data, vals=vals, **kwargs) # TODO here cbar handling like pg.show if 'xlabel' in kwargs: ax.set_xlabel(kwargs['xlabel']) if 'ylabel' in kwargs: ax.set_ylabel(kwargs['ylabel']) if 'showTopo' in kwargs: # if axTopo is not None: print(ax.get_position()) axTopo = pg.plt.axes([ ax.get_position().x0, ax.get_position().y0, ax.get_position().x0 + 0.2, ax.get_position().y0 + 0.2 ]) x = pg.x(data) x *= (ax.get_xlim()[1] - ax.get_xlim()[0]) / (max(x) - min(x)) x += ax.get_xlim()[0] axTopo.plot(x, pg.z(data), '-o', markersize=4) axTopo.set_ylim(min(pg.z(data)), max(pg.z(data))) axTopo.set_aspect(1) # ax.set_aspect('equal') # plt.pause(0.1) pg.viewer.mpl.updateAxes(ax) 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.viewer.mpl.drawMesh` or if no cells are given: forward to :py:mod:`pygimli.viewer.mpl.drawPLC` . [[marker, value], ...] List of Cellvalues per cell marker forward to :py:mod:`pygimli.viewer.mpl.drawModel` . float per cell -- model, patch forward to :py:mod:`pygimli.viewer.mpl.drawModel` . float per node -- scalar field forward to :py:mod:`pygimli.viewer.mpl.drawField` . iterable of type [float, float] -- vector field forward to :py:mod:`pygimli.viewer.mpl.drawStreams` . pg.core.R3Vector -- vector field forward to :py:mod:`pygimli.viewer.mpl.drawStreams` . pg.core.stdVectorRVector3 -- sensor positions forward to :py:mod:`pygimli.viewer.mpl.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 additional. showBoundary: bool [None] Highlight all boundaries with marker != 0. A value None means automatic. Is set True for cell data and False for node data. marker: bool [False] Show cell markers and boundary marker. boundaryMarkers: bool [False] Highlight boundaries with marker !=0 and add Marker annotation. Applies :py:mod:`pygimli.viewer.mpl.drawBoundaryMarkers`. Dictionary "boundaryProps" can be added and will be forwarded to :py:mod:`pygimli.viewer.mpl.drawBoundaryMarkers`. Keyword Arguments ----------------- **kwargs: * xlabel: str [None] Add label to the x axis * ylabel: str [None] Add label to the y axis fitView: bool Fit the axes limits to the all content of the axes. Default is True. boundaryProps: dict Arguments for plotboundar 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 cBar : matplotlib.colorbar """ renameKwarg('cmap', 'cMap', kwargs) cMap = kwargs.pop('cMap', 'viridis') cBarOrientation = kwargs.pop('orientation', 'horizontal') replaceData = kwargs.pop('replaceData', False) if ax is None: ax, _ = pg.show(figsize=kwargs.pop('figsize', None), **kwargs) # adjust limits only when axis is empty fitViewDefault = True # if (ax.lines or ax.collections or ax.patches): # fitViewDefault = False # else: # plt.subplots() resets locale setting to system default .. this went # horrible wrong for german 'decimal_point': ',' pg.checkAndFixLocaleDecimal_point(verbose=False) if block: hold = True lastHoldStatus = pg.viewer.mpl.utils.holdAxes__ if not lastHoldStatus or hold: pg.viewer.mpl.hold(val=1) hold = True gci = None validData = False if markers: kwargs["boundaryMarkers"] = kwargs.get("boundaryMarkers", True) if mesh.cellCount() > 0: uniquemarkers, uniqueidx = np.unique(np.array(mesh.cellMarkers()), return_inverse=True) label = "Cell markers" 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 mesh.createNeighborInfos() if showBoundary is None: showBoundary = True elif isinstance(data, pg.core.stdVectorRVector3): drawSensors(ax, data, **kwargs) elif isinstance(data, pg.core.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.core.haveInfNaN(data): # pg.warn("No valid data: ", min(data), max(data), pg.core.haveInfNaN(data)) # showMesh = True else: if bool(colorBar) is not False: colorBar = True if len(data) == mesh.cellCount(): if showBoundary is None: showBoundary = True def _drawField(ax, mesh, data, kwargs): ### kwargs as reference here to set defaults valid outside too validData = True if len(data) == mesh.cellCount(): kwargs['nCols'] = kwargs.pop('nCols', 256) gci = drawModel(ax, mesh, data, **kwargs) elif len(data) == mesh.nodeCount(): kwargs['nLevs'] = kwargs.pop('nLevs', 5) kwargs['nCols'] = kwargs.pop('nCols', kwargs['nLevs'] - 1) gci = drawField(ax, mesh, data, **kwargs) else: pg.error("Data size invalid") print("Data: ", len(data), min(data), max(data), pg.core.haveInfNaN(data)) print("Mesh: ", mesh) validData = False drawMesh(ax, mesh) return gci, validData try: if label is None: label = "" if replaceData and hasattr(mesh, 'gci') and ax in mesh.gci: gci = mesh.gci[ax] if 'TriContourSet' in str(type(gci)): ax.clear() gci, validData = _drawField(ax, mesh, data, kwargs) updateAxes(ax, force=True) else: setMappableData( gci, data, cMin=kwargs.get('cMin', None), cMax=kwargs.get('cMax', None), ) updateAxes(ax, force=True) return ax, gci.colorbar else: gci, validData = _drawField(ax, mesh, data, kwargs) ### Cache mesh and scalarmappable to make replaceData work if not hasattr(mesh, 'gci'): mesh.gci = {} mesh.gci[ax] = gci if cMap is not None and gci is not None: gci.set_cmap(cmapFromName(cMap)) #gci.cmap.set_under('k') except BaseException as e: print(e) traceback.print_exc(file=sys.stdout) if mesh.cellCount() == 0: showMesh = False if mesh.boundaryCount() == 0: pg.viewer.mpl.drawPLC(ax, mesh, showNodes=True, fillRegion=False, showBoundary=False, **kwargs) showBoundary = False #ax.plot(pg.x(mesh), pg.y(mesh), '.', color='black') else: pg.viewer.mpl.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.viewer.mpl.drawSelectedMeshBoundaries(ax, mesh.boundaries(), color=kwargs.pop( 'color', "0.1"), linewidth=0.3) #drawMesh(ax, mesh, **kwargs) if bool(showBoundary) == True: b = mesh.boundaries(mesh.boundaryMarkers() != 0) pg.viewer.mpl.drawSelectedMeshBoundaries(ax, b, color=(0.0, 0.0, 0.0, 1.0), linewidth=1.4) if kwargs.pop("boundaryMarkers", False): pg.viewer.mpl.drawBoundaryMarkers(ax, mesh, clipBoundaryMarkers=kwargs.pop( 'clipBoundaryMarkers', False), **kwargs.pop('boundaryProps', {})) fitView = kwargs.pop('fitView', fitViewDefault) if fitView is not False: ax.autoscale(enable=True, axis='both', tight=True) ax.set_aspect('equal') cBar = None if label is not None and colorBar is None: colorBar = True if colorBar and validData: labels = ['cMin', 'cMax', 'nCols', 'nLevs', 'logScale', 'levels'] subkwargs = {key: kwargs[key] for key in labels if key in kwargs} subkwargs['label'] = label subkwargs['cMap'] = cMap subkwargs['orientation'] = cBarOrientation if bool(colorBar) is not False: cBar = createColorBar(gci, size=kwargs.pop('size', 0.2), pad=kwargs.pop('pad', None), **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, dropThreshold=kwargs.pop('dropThreshold', 0.4)) else: pg.error('show, coverage wrong length, toImplement') # addCoverageAlpha(gci, pg.core.cellDataToPointData(mesh, coverage)) if not hold or block is not False and plt.get_backend().lower() != "agg": if data is not None: if len(data) == mesh.cellCount(): CellBrowser(mesh, data, ax=ax) plt.show(block=block) try: plt.pause(0.01) except BaseException as _: pass if hold: pg.viewer.mpl.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
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