Ejemplo n.º 1
0
def test(target=None, show=False, onlydoctests=False, coverage=False, htmlreport=False):
    """Run docstring examples and additional tests.

    Examples
    --------
    >>> from pygimli.utils import boxprint
    >>> test(target=boxprint)

    Parameters
    ----------
    target : function, optional
        Function or method to test. By default everything is tested.
    show : boolean, optional
        Show matplotlib windows during test run. They will be closed
        automatically.
    onlydoctests : boolean, optional
        Run test files in ../tests as well.
    coverage : boolean, optional
        Create a coverage report. Requires the pytest-cov plugin.
    htmlreport : str, optional
        Filename for HTML report such as www.pygimli.org/build_tests.html.
        Requires pytest-html plugin.
    """
    if target:
        import doctest
        doctest.run_docstring_examples(target, globals())
        return

    try:
        import pytest
    except ImportError:
        raise ImportError("pytest is required to run test suite. " + \
                          "Try 'sudo pip install pytest'.")

    from matplotlib import pyplot as plt
    from pygimli.utils import opt_import
    pc = opt_import("pytest_cov", "create a code coverage report")
    ph = opt_import("pytest_html", "create a html report")

    old_backend = plt.get_backend()
    if not show:
        plt.switch_backend("Agg")
    cwd = os.path.realpath(__path__[0])
    cfg = os.path.join(cwd, "../tests/setup.cfg")
    cmd = ""
    if os.path.exists(cfg):
        cmd += "-c %s " % cfg
    if pc and coverage:
        cmd += "--cov pygimli --cov-report term " + \
               "--cov-config %s " % cfg.replace("setup.cfg", ".coveragerc")
    if ph and htmlreport:
        cmd += "--html %s " % htmlreport
    cmd += "%s " % cwd
    if not onlydoctests and os.path.exists(cfg):
        cmd += os.path.join(cwd, "../tests")

    exitcode = pytest.main(cmd)
    plt.switch_backend(old_backend)
    plt.close('all')
    sys.exit(exitcode)
Ejemplo n.º 2
0
def GKtoUTM(R, H=None, zone=32, gk=None, gkzone=None):
    """Transforms any Gauss-Krueger to UTM autodetect GK zone from offset."""
    if gk is None and gkzone is None:
        if H is None:
            rr = R[0][0]
        else:
            if isinstance(R, list) or isinstance(R, tuple):
                rr = R[0]
            else:
                rr = R

        gkzone = int(floor(rr * 1e-6))
        print(gkzone)

        if gkzone <= 0 or gkzone >= 5:
            print("cannot detect valid GK zone")

    pyproj = opt_import('pyproj', 'coordinate transformations')
    if pyproj is None:
        return None

    gk = pyproj.Proj(init="epsg:"+str(31464+gkzone))
    wgs84 = pyproj.Proj(init="epsg:4326")  # pure ellipsoid to doubel transform
    utm = pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')  # UTM
    if H is None:  # two-column matrix
        lon, lat = pyproj.transform(gk, wgs84, R[0], R[1])
    else:
        lon, lat = pyproj.transform(gk, wgs84, R, H)

    return utm(lon, lat)
Ejemplo n.º 3
0
def test(show=False, coverage=False):
    """Test all code examples in docstrings using pytest."""
    try:
        import pytest
    except ImportError:
        raise ImportError("pytest is required to run test suite. " + "Try 'sudo pip install pytest'.")

    from matplotlib import pyplot as plt
    from pygimli.utils import opt_import

    pc = opt_import("pytest_cov", "create a coverage report")

    old_backend = plt.get_backend()
    if not show:
        plt.switch_backend("Agg")
    cwd = __path__[0]
    cfg = os.path.join(cwd, "../tests/setup.cfg")
    cmd = ""
    if os.path.exists(cfg):
        cmd += "-c %s " % cfg
    if pc and coverage:
        cmd += "--cov pygimli --cov-report coveralls --cov-report html " + "--cov-config %s " % cfg.replace(
            "setup.cfg", ".coveragerc"
        )
    cmd += "%s" % cwd
    try:
        pytest.main(cmd)
    finally:
        plt.switch_backend(old_backend)
Ejemplo n.º 4
0
    def _load(self, polyfile):
        """
        Read polygon info from XML file.
        Example of XML file:

        """
        ET = opt_import("xml.etree.cElementTree", "read in XML files")
        self.doc = ET.parse(polyfile)
        self._parse()
Ejemplo n.º 5
0
# -*- coding: utf-8 -*-

from pygimli.gui.mpl import AppResourceMPL
from pygimli.importexport import readGPX, readSimpleLatLon
from pygimli.mplviewer import underlayMap
from pygimli.utils import opt_import

pyproj = opt_import('pyproj', 'coordinate transformations of EM data')


def findUTMZone(lon, lat):
    """
    find utm zone for lon and lat values.

    Return str(zone)+hemisphere
    lon -180 -- -174 -> 1 ... 174 -- 180 -> 60
    lat < 0 hemisphere = S, > 0 hemisphere = N
    """
    zone = (int(lon) + 180) / 6 + 1

    if lat > 0:
        return str(zone) + 'N'
    else:
        return str(zone) + 'S'

# def findUTMZone(...)


class GPSViewerApp(AppResourceMPL):

    """
Ejemplo n.º 6
0
    def readHEMData(self, filename, takeevery=1, choosevcp=True):
        """ read RESOLVE type airborne EM data from .XYZ file """
        self.header = {}
        keyword = ''
        with open(filename) as f:
            for i, line in enumerate(f):
                if line[0] == '/':
                    line = line[1:].strip('\n').replace(',', '').replace('AND',
                                                                         '')
                    try:
                        result = [float(co) for co in line.split()]
                    except:
                        result = line.split()
                    if len(result) == 1:
                        result = result[0]
                    if keyword:
                        if isinstance(keyword, list):
                            for kw, res in zip(keyword, result):
                                self.header[kw] = res
                        else:
                            self.header[keyword] = result
                        keyword = ''
                    else:
                        keyword = result
                else:
                    break
            line = f.readline()
            print(line)
#            tmp = np.genfromtxt(fname=f, autostrip=True, comments='/',
#                skip_header=0, dtype=float, names=1, case_sensitive='lower',
#                missing_values='*', filling_values=-9999, skip_footer=1)
        tmp = np.genfromtxt(
            fname=filename, autostrip=True, comments='/',
            skip_header=i+1, dtype=float, names=True, case_sensitive='lower',
            missing_values='*', filling_values=-9999, skip_footer=1)
        # read properties from header
        if choosevcp:
            ivcp = np.nonzero(np.array(self.header['COILGEOMETRY']) == 1)[0]
        else:
            ivcp = range(len(self.header['FREQUENCY']))
        self.frequencies = np.array(self.header['FREQUENCY'])[ivcp]
        self.coilSpacing = np.array(self.header['COILSEPERATION'])[ivcp]
        # read properties from data block
        names = tmp.dtype.names
        pyproj = opt_import('pyproj', 'coordinate transformations EM lon,lat values')
        if 'lon' in names and 'lat' in names and pyproj is not None:
            utm = pyproj.Proj(proj='utm', zone=32, ellps='WGS84')  # projection
            x, y = utm(tmp['lon'], tmp['lat'])
        else:
            x, y = tmp['x'], tmp['y']
        self.pos = np.column_stack((x, y))[::takeevery]
        dx = np.sqrt(np.diff(self.pos[:, 0])**2 + np.diff(self.pos[:, 1])**2)
        self.x = np.hstack((0., np.cumsum(dx)))
        self.z = tmp['h_laser'][::takeevery]
        self.topo = tmp['topo'][::takeevery]
        IP = np.column_stack([tmp['real_'+str(i+1)] for i in ivcp])
        OP = np.column_stack([tmp['quad_'+str(i+1)] for i in ivcp])
        # better do a decimation or running average here
        self.IP = IP[::takeevery, :]
        self.OP = OP[::takeevery, :]
        self.isActiveFreq = self.frequencies > 0.0
        self.activeFreq = np.nonzero(self.isActiveFreq)[0]
Ejemplo n.º 7
0
# -*- coding: utf-8 -*-

from pygimli.gui.mpl import AppResourceMPL
from pygimli.importexport import readGPX, readSimpleLatLon
from pygimli.mplviewer import underlayMap
from pygimli.utils import opt_import

pyproj = opt_import('pyproj', 'coordinate transformations of EM data')


def findUTMZone(lon, lat):
    """
    find utm zone for lon and lat values.

    Return str(zone)+hemisphere
    lon -180 -- -174 -> 1 ... 174 -- 180 -> 60
    lat < 0 hemisphere = S, > 0 hemisphere = N
    """
    zone = (int(lon) + 180) / 6 + 1

    if lat > 0:
        return str(zone) + 'N'
    else:
        return str(zone) + 'S'


# def findUTMZone(...)


class GPSViewerApp(AppResourceMPL):
    """
Ejemplo n.º 8
0
from pygimli.utils import opt_import

json = opt_import("json", "read and write inversion settings")


class InversionSettings(dict):
    """
    Extends the built-in dict with methods for saving and loading a file.
    """
    def __init__(self, *args, **kwargs):
        """
        Initialize the settings object by either using a file or sepcifying the
        settings directly. Works exatly like a dict(), only with extended
        capabilities like saving and loading to disk.
        """

        try:
            self.filename = kwargs.pop('filename')
        except KeyError:
            print('Creating new settings object.')
        else:
            print('Loading settings from: "{}".'.format(self.filename))
        finally:
            super(InversionSettings, self).__init__(*args, **kwargs)

        if hasattr(self, 'filename'):
            self.update(InversionSettings.loadtxt(self.filename))

    def save(self, f):
        """
        Saves the settings object to disk.