示例#1
0
def prettify(value, roundValue=False):
    """Return prettified string for value .. if possible."""
    if isinstance(value, dict):
        import json
        # class CustomEncoder(json.JSONEncoder):
        #     def __init__(self, *args, **kwargs):
        #         super().__init__(*args, **kwargs)

        #     def _iterencode(self, o):
        #         try:
        #             return super()._iterencode(o)
        #         except:
        #             return "{0} is not JSON serializable".format(type(o))

        try:
            return json.dumps(value, indent=4)
        except Exception as e:
            pg.warning('prettify fails:', e)
            return str(value)
    elif pg.isScalar(value):
        return prettyFloat(value, roundValue)
    pg.warn("Don't know how to prettify the string representation for: ",
            value)
    return value
示例#2
0
 def wrapper(*args, **kwargs):
     import pygimli as pg
     pg.warning(func.__name__ + ' had been renamed to ' + \
                self.newFunc.__name__ + \
                ' and will be removed in: ' + self.removed)
     return self.newFunc(*args, **kwargs)
示例#3
0
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)

    try:
        ax, cbar = drawERTData(ax, data, vals=vals, **kwargs)
    except:
        pg.warning('Something gone wrong while drawing data. '
                   'Try fallback with equidistant electrodes.')
        d = pg.DataContainerERT(data)
        sc = data.sensorCount()
        d.setSensors(list(zip(range(sc), np.zeros(sc))))
        ax, cbar = drawERTData(ax, d, 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
示例#4
0
###############################################################################
# Perform the modeling with the mesh and the measuring scheme itself
# and return a data container with apparent resistivity values,
# geometric factors and estimated data errors specified by the noise setting.
# The noise is also added to the data. Here 1% plus 1µV.
# Note, we force a specific noise seed as we want reproducable results for
# testing purposes.
data = ert.simulate(mesh,
                    scheme=scheme,
                    res=rhomap,
                    noiseLevel=1,
                    noiseAbs=1e-6,
                    seed=1337)

pg.warning(np.linalg.norm(data['err']), np.linalg.norm(data['rhoa']))
pg.info('Simulated data', data)
pg.info('The data contains:', data.dataMap().keys())

pg.info('Simulated rhoa (min/max)', min(data['rhoa']), max(data['rhoa']))
pg.info('Selected data noise %(min/max)',
        min(data['err']) * 100,
        max(data['err']) * 100)

###############################################################################
# Optional: you can filter all values and tokens in the data container.
# Its possible that there are some negative data values due to noise and
# huge geometric factors. So we need to remove them.
data.remove(data['rhoa'] < 0)
pg.info('Filtered rhoa (min/max)', min(data['rhoa']), max(data['rhoa']))