Ejemplo n.º 1
0
def tapeMeasureToCoordinates(tape, pos):
    """Interpolate 2D tape measured topography to 2D Cartesian coordinates.

    Tape and pos value are expected to be sorted along distance to the origin.

    DEPRECATED will be removed use
    :py:mod:`pygimli.meshtools.interpolateAlongCurve` instead

    TODO optional smooth curve with harmfit
    TODO parametric
    TODO parametric + Topo: 3d

    Parameters
    ----------
    tape : [[x,z]] | [RVector3] | R3Vector
        List of tape measured topography points with measured distance (x)
        from origin and height (z)

    pos : iterable
        Array of query positions along the tape measured profile t[0 ..

    Returns
    -------
    res : ndarray(N, 2)
        Same as pos but with interpolated height values.
        The Distance between pos points and res (along curve) points remains.

    """
    pg.deprecated("tapeMeasureToCoordinates", "interpolateAlongCurve")
    return interpolateAlongCurve(tape, pos)
Ejemplo n.º 2
0
def tapeMeasureToCoordinates(tape, pos):
    """Interpolate 2D tape measured topography to 2D Cartesian coordinates.

    Tape and pos value are expected to be sorted along distance to the origin.

    DEPRECATED will be removed use
    :py:mod:`pygimli.meshtools.interpolateAlongCurve` instead

    TODO optional smooth curve with harmfit
    TODO parametric
    TODO parametric + Topo: 3d

    Parameters
    ----------
    tape : [[x,z]] | [RVector3] | R3Vector
        List of tape measured topography points with measured distance (x)
        from origin and height (z)

    pos : iterable
        Array of query positions along the tape measured profile t[0 ..

    Returns
    -------
    res : ndarray(N, 2)
        Same as pos but with interpolated height values.
        The Distance between pos points and res (along curve) points remains.

    """
    pg.deprecated("tapeMeasureToCoordinates", "interpolateAlongCurve")
    return interpolateAlongCurve(tape, pos)
Ejemplo n.º 3
0
def randN(n, minVal=0.0, maxVal=1.0):
    """Create RVector of length n with normally distributed random numbers."""
    pg.deprecated('not needed')  # 20200515
    r = pg.Vector(n)
    pg.math.randn(r)
    r *= (maxVal - minVal)
    r += minVal
    return r
Ejemplo n.º 4
0
def plotFirstPicks(ax, data, tt=None, plotva=False, marker='x-'):
    """Naming convention. drawFOO(ax, ... )."""
    pg.deprecated("use drawFirstPicks")
    return drawFirstPicks(ax=ax,
                          data=data,
                          tt=tt,
                          plotva=plotva,
                          marker=marker)
Ejemplo n.º 5
0
def plotSpectrum(ax, freq, vals, ylabel=r'$-\phi$ (mrad)',
                 grid=True, marker='+', ylog=True, **kwargs):
    """Plot some spectrum (redundant).
    DEPRECATED
    """
    pg.deprecated('drawSpectrum')
    if 'label' not in kwargs:
        kwargs['label'] = 'obs'
    ax.loglog(freq, vals, marker=marker, **kwargs)
    if ylog:
        ax.set_yscale('log')
    ax.set_xlabel('f (Hz)')
    ax.set_ylabel(ylabel)
    ax.grid(grid)
Ejemplo n.º 6
0
def plotSpectrum(ax, freq, vals, ylabel=r'$-\phi$ (mrad)',
                 grid=True, marker='+', ylog=True, **kwargs):
    """Plot some spectrum (redundant).
    DEPRECATED
    """
    pg.deprecated('drawSpectrum')
    if 'label' not in kwargs:
        kwargs['label'] = 'obs'
    ax.loglog(freq, vals, marker=marker, **kwargs)
    if ylog:
        ax.set_yscale('log')
    ax.set_xlabel('f (Hz)')
    ax.set_ylabel(ylabel)
    ax.grid(grid)
Ejemplo n.º 7
0
def opt_import(*args, **kwargs):
    pg.deprecated()
    return optImport(*args, **kwargs)
Ejemplo n.º 8
0
def solveFiniteVolume(mesh,
                      a=1.0,
                      b=0.0,
                      f=0.0,
                      fn=0.0,
                      vel=None,
                      u0=0.0,
                      times=None,
                      uL=None,
                      relax=1.0,
                      ws=None,
                      scheme='CDS',
                      **kwargs):
    r"""Solve partial differential equation with Finite Volumes.

    This function is a syntactic sugar proxy for using the Finite Volume
    functionality of the library core to solve elliptic and parabolic partial
    differential of the following type:

    .. math::

        \frac{\partial u}{\partial t} + \mathbf{v}\cdot\nabla u & = \nabla\cdot(a \nabla u) + b u + f(\mathbf{r},t)\\
        u(\mathbf{r}, t) & = u_B  \quad\mathbf{r}\in\Gamma_{\text{Dirichlet}}\\
        \frac{\partial u(\mathbf{r}, t)}{\partial \mathbf{n}} & = u_{\partial \text{B}}  \quad\mathbf{r}\in\Gamma_{\text{Neumann}}\\
        u(\mathbf{r}, t=0) & = u_0 \quad\text{with} \quad\mathbf{r}\in\Omega

    The Domain :math:`\Omega` and the Boundary :math:`\Gamma` are defined
    through the given mesh with appropriate boundary marker.

    The solution :math:`u(\mathbf{r}, t)` is given for each cell in the mesh.

    TODO:

     * Refactor with solver class and Runga-Kutte solver
     * non steady boundary conditions

    Parameters
    ----------
    mesh: :gimliapi:`GIMLI::Mesh`
        Mesh represents spatial discretization of the calculation domain
    a: value | array | callable(cell, userData)
        Stiffness weighting per cell values.
    b: value | array | callable(cell, userData)
        Scale for mass values b
    f: iterable(cell)
        Load vector
    fn: iterable(cell)
        TODO What is fn
    vel: ndarray (N,dim) | RMatrix(N,dim)
        Velocity field :math:`\mathbf{v}(\mathbf{r}, t=\text{const}) = \{[v_i]_j,\}`
        with :math:`i=[1\ldots 3]` for the mesh dimension
        and :math:`j = [0\ldots N-1]` with N either the amount of cells,
        nodes, or boundaries.
        Velocities per boundary are preferred and will be interpolated
        on demand.
    u0: value | array | callable(cell, userData)
        Starting field
    times: iterable
        Time steps to calculate for.
    ws Workspace
        This can be an empty class that will used as an Workspace to store and
        cache data.

        If ws is given: The system matrix is taken from ws or
        calculated once and stored in ws for further usage.

        The system matrix is cached in this Workspace as ws.S
        The LinearSolver with the factorized matrix is cached in
        this Workspace as ws.solver
        The rhs vector is only stored in this Workspace as ws.rhs
    scheme: str [CDS]
        Finite volume scheme:
        :py:mod:`pygimli.solver.diffusionConvectionKernel`
    **kwargs:
        * bc : Boundary Conditions dictionary, see pg.solver
        * uB : Dirichlet boundary conditions DEPRECATED
        * duB : Neumann boundary conditions DEPRECATED

    Returns
    -------
    u: ndarray(nTimes, nCells)
        Solution field for all time steps.
    """
    verbose = kwargs.pop('verbose', False)
    # The Workspace is to hold temporary data or preserve matrix rebuild
    # swatch = pg.core.Stopwatch(True)
    sparse = True

    workspace = pg.solver.WorkSpace()
    if ws:
        workspace = ws

    a = pg.solver.parseArgToArray(a, [mesh.cellCount(), mesh.boundaryCount()])
    b = pg.solver.parseArgToArray(b, mesh.cellCount())
    f = pg.solver.parseArgToArray(f, mesh.cellCount())
    fn = pg.solver.parseArgToArray(fn, mesh.cellCount())

    boundsDirichlet = None
    boundsNeumann = None

    # BEGIN check for Courant-Friedrichs-Lewy
    if vel is not None:

        if isinstance(vel, float):
            print("Warning! .. velocity is float and no vector field")

        # we need velocities for boundaries
        if len(vel) is not mesh.boundaryCount():
            if len(vel) == mesh.cellCount():
                vel = pg.meshtools.cellDataToNodeData(mesh, vel)

            if len(vel) == mesh.nodeCount():
                vel = pg.meshtools.nodeDataToBoundaryData(mesh, vel)
            else:
                print("mesh:", mesh)
                print("vel:", vel.shape)

                raise Exception("Cannot determine data format for velocities")

        if times is not None:
            pg.solver.checkCFL(times, mesh, np.max(pg.abs(vel)))

    if not hasattr(workspace, 'S'):

        boundsDirichlet = []
        if 'bc' in kwargs:
            bct = dict(kwargs['bc'])
            if 'Dirichlet' in bct:
                boundsDirichlet += pg.solver.parseArgToBoundaries(
                    bct.pop('Dirichlet'), mesh)

            if 'Node' in bct:
                n = bct.pop('Node')
                boundsDirichlet.append([mesh.node(n[0]), n[1]])

            if 'Neumann' in bct:
                boundsNeumann = pg.solver.parseArgToBoundaries(
                    bct.pop('Neumann'), mesh)

        if 'uB' in kwargs:
            pg.deprecated('use new bc dictionary')
            boundsDirichlet = pg.solver.parseArgToBoundaries(
                kwargs['uB'], mesh)

        if 'duB' in kwargs:
            pg.deprecated('use new bc dictionary')
            boundsNeumann = pg.solver.parseArgToBoundaries(kwargs['duB'], mesh)

        workspace.S, workspace.rhsBCScales = diffusionConvectionKernel(
            mesh=mesh,
            a=a,
            b=b,
            uB=boundsDirichlet,
            duB=boundsNeumann,
            # u0=u0,
            fn=fn,
            vel=vel,
            scheme=scheme,
            sparse=sparse,
            userData=kwargs.pop('userData', None))

        dof = len(workspace.rhsBCScales)
        workspace.ap = np.zeros(dof)

        # for nonlinears
        if uL is not None:
            for i in range(dof):
                val = 0.0
                if sparse:
                    val = workspace.S.getVal(i, i) / relax
                    workspace.S.setVal(i, i, val)
                else:
                    val = workspace.S[i, i] / relax
                    workspace.S[i, i] = val

                workspace.ap[i] = val

        # print('FVM kernel 2:', swatch.duration(True))
    # endif: not hasattr(workspace, 'S'):

    workspace.rhs = np.zeros(len(workspace.rhsBCScales))
    workspace.rhs[0:mesh.cellCount()] = f  # * mesh.cellSizes()

    workspace.rhs += workspace.rhsBCScales

    # for nonlinear: relax progress with scaled last result
    if uL is not None:
        workspace.rhs += (1. - relax) * workspace.ap * uL
    # print('FVM: Prep:', swatch.duration(True))

    if not hasattr(times, '__len__'):

        if sparse and not hasattr(workspace, 'solver'):
            Sm = pg.matrix.SparseMatrix(workspace.S)
            # hold Sm until we have reference counting,
            # loosing Sm here will kill LinSolver later
            workspace.Sm = Sm
            workspace.solver = pg.core.LinSolver(Sm, verbose=verbose)

        u = None
        if sparse:
            u = workspace.solver.solve(workspace.rhs)
        else:
            u = np.linalg.solve(workspace.S, workspace.rhs)
        # print('FVM solve:', swatch.duration(True))
        return u[0:mesh.cellCount():1]
    else:
        theta = kwargs.pop('theta', 0.5 + 1e-6)

        if sparse:
            I = pg.solver.identity(len(workspace.rhs))
        else:
            I = np.diag(np.ones(len(workspace.rhs)))

        progress = None
        if verbose:
            from pygimli.utils import ProgressBar
            progress = ProgressBar(its=len(times))

            print("Solve timesteps with Crank-Nicolson.")

        return pg.solver.crankNicolson(times,
                                       theta,
                                       workspace.S,
                                       I,
                                       f=workspace.rhs,
                                       u0=pg.solver.cellValues(mesh, u0),
                                       progress=progress)
Ejemplo n.º 9
0
def plotMatrix(mat, *args, **kwargs):
    """Naming conventions. Use drawDataMatrix or showDataMatrix"""
    pg.deprecated("use drawDataMatrix or showMatrix")
    return showDataMatrix(*args, **kwargs)
Ejemplo n.º 10
0
def opt_import(*args, **kwargs):
    pg.deprecated()
    return optImport(*args, **kwargs)
Ejemplo n.º 11
0
def _getOffset(data, full=False):
    """Return vector of offsets (in m) between shot and receiver."""
    pg.deprecated('use shotReceiverDistances')  # 190429 ??
    return shotReceiverDistances(data, full)
Ejemplo n.º 12
0
def showAmplitudeSpectrum(*args, **kwargs):
    pg.deprecated('drawAmplitudeSpectrum')
    return drawAmplitudeSpectrum(*args, **kwargs)
Ejemplo n.º 13
0
def showPhaseSpectrum(*args, **kwargs):
    pg.deprecated('drawPhaseSpectrum')
    return drawPhaseSpectrum(*args, **kwargs)
Ejemplo n.º 14
0
def createfolders(foldername_list):
    pg.deprecated("use createFolders")  #190520
    return createFolders(foldername_list)
Ejemplo n.º 15
0
import pygimli as pg
from ..viewer.mpl import *
pg.deprecated("Please use pygimli.viewer.mpl instead of pygimli.mplviewer.",
              "The latter will be removed in pyGIMLi 1.2.")
Ejemplo n.º 16
0
def ColeColeRho(f, rho, m, tau, c, a=1):
    pg.deprecated("Please use modelColeColeRho instead of ColeColeRho.")
    return modelColeColeRho(f, rho, m, tau, c, a)
Ejemplo n.º 17
0
def plotVecMatrix(xvec, yvec, vals, full=False, **kwargs):
    """DEPRECATED for nameing
    """
    pg.deprecated('plotVecMatrix', 'showVecMatrix')
    return showVecMatrix(xvec, yvec, vals, full, **kwargs)
Ejemplo n.º 18
0
def opt_import(*args, **kwargs):
    pg.deprecated()  # last vis: 20190903
    return optImport(*args, **kwargs)
Ejemplo n.º 19
0
def ColeColeSigma(f, sigma, m, tau, c, a=1):
    pg.deprecated("Please use modelColeColeSigma instead of ColeColeSigma.")
    return modelColeColeSigma(f, sigma, m, tau, c, a)
Ejemplo n.º 20
0
def DebyeRelaxation(f, tau, m):
    pg.deprecated("Please use relaxationDebye instead of DebyeRelaxation.")
    return relaxationDebye(f, tau, m)
Ejemplo n.º 21
0
def showPhaseSpectrum(*args, **kwargs):
    pg.deprecated('drawPhaseSpectrum')
    return drawPhaseSpectrum(*args, **kwargs)
Ejemplo n.º 22
0
def WarbugRelaxation(f, tau, m):
    pg.deprecated("Please use relaxationWarbug instead of WarbugRelaxation.")
    return relaxationWarbug(f, tau, m)
Ejemplo n.º 23
0
def showAmplitudeSpectrum(*args, **kwargs):
    pg.deprecated('drawAmplitudeSpectrum')
    return drawAmplitudeSpectrum(*args, **kwargs)
Ejemplo n.º 24
0
def ColeColeEpsilon(f, e0, eInf, tau, alpha):
    pg.deprecated("Use modelColeColeEpsilon instead of ColeColeEpsilon.")
    return modelColeColeEpsilon(f, e0, eInf, tau, alpha)
Ejemplo n.º 25
0
def drawDataMatrix(ax,
                   mat,
                   xmap=None,
                   ymap=None,
                   cMin=None,
                   cMax=None,
                   logScale=None,
                   label=None,
                   **kwargs):
    """Draw previously generated (generateVecMatrix) matrix.

    Parameters
    ----------
    ax : mpl.axis
        axis to plot, if not given a new figure is created
    mat : numpy.array2d
        matrix to show
    xmap : dict {i:num}
        dict (must match A.shape[0])
    ymap : iterable
        vector for x axis (must match A.shape[0])
    cMin/cMax : float
        minimum/maximum color values
    logScale : bool
        logarithmic colour scale [min(A)>0]
    label : string
        colorbar label
    """
    if xmap is None:
        xmap = {i: i for i in range(mat.shape[0])}
    if ymap is None:
        ymap = {i: i for i in range(mat.shape[1])}
    if isinstance(mat, np.ma.MaskedArray):
        mat_ = mat
    else:
        mat_ = np.ma.masked_where(mat == 0.0, mat, False)

    if cMin is None:
        cMin = np.min(mat_)
    if cMax is None:
        cMax = np.max(mat_)
    if logScale is None:
        logScale = (cMin > 0.0)
    if logScale:
        norm = LogNorm(vmin=cMin, vmax=cMax)
    else:
        norm = Normalize(vmin=cMin, vmax=cMax)

    gci = ax.imshow(mat_, norm=norm, interpolation='nearest')
    if 'cmap' in kwargs:
        pg.deprecated('use cMap')  # 190422
        gci.set_cmap(kwargs.pop('cmap'))
    if 'cMap' in kwargs:
        gci.set_cmap(kwargs.pop('cMap'))

    ax.set_aspect(kwargs.pop('aspect', 1))
    ax.grid(True)
    xt = np.unique(ax.get_xticks().clip(0, len(xmap) - 1))
    yt = np.unique(ax.get_xticks().clip(0, len(ymap) - 1))

    if kwargs.pop('showally', False):
        yt = np.arange(len(ymap))
    else:
        yt = np.round(np.linspace(0, len(ymap) - 1, 5))

    xx = np.sort([k for k in xmap])
    ax.set_xticks(xt)
    ax.set_xticklabels(['{:g}'.format(round(xx[int(ti)], 2)) for ti in xt])

    yy = np.unique([k for k in ymap])
    ax.set_yticks(yt)
    ax.set_yticklabels(['{:g}'.format(round(yy[int(ti)], 2)) for ti in yt])
    return gci
Ejemplo n.º 26
0
def ColeDavidson(f, R, m, tau, a=1):
    pg.deprecated("Please use modelColeDavidson instead of ColeDavidson.")
    return modelColeDavidson(f, R, m, tau, a)
Ejemplo n.º 27
0
def plotDataContainerAsMatrix(*args, **kwargs):
    "DEPRECATED naming scheme" ""
    pg.deprecated('plotDataContainerAsMatrix', 'showDataContainerAsMatrix')
    return showDataContainerAsMatrix(*args, **kwargs)
Ejemplo n.º 28
0
def ColeColeRhoDouble(f, rho, m1, t1, c1, m2, t2, c2):
    pg.deprecated("Use modelColeColeRhoDouble instead of ColeColeRhoDouble.")
    return modelColeColeRhoDouble(f, rho, m1, t1, c1, m2, t2, c2)
Ejemplo n.º 29
0
def plotVecMatrix(xvec, yvec, vals, full=False, **kwargs):
    """DEPRECATED for nameing
    """
    pg.deprecated('plotVecMatrix', 'showVecMatrix')
    return showVecMatrix(xvec, yvec, vals, full, **kwargs)
Ejemplo n.º 30
0
def linsolve(A, b, verbose=False):
    """
    DEPRECATED wrong name style
    """
    pg.deprecated('linsolve', 'linSolve')
    return linSolve(A, b, verbose)