[rasterio] 01/03: Imported Upstream version 0.16

Johan Van de Wauw johanvdw-guest at moszumanska.debian.org
Tue Dec 23 20:16:24 UTC 2014


This is an automated email from the git hooks/post-receive script.

johanvdw-guest pushed a commit to branch master
in repository rasterio.

commit bbdbaef4fe0479d93dba96c035f3bb61cbcb2fd0
Author: Johan Van de Wauw <johan.vandewauw at gmail.com>
Date:   Mon Dec 22 23:53:39 2014 +0100

    Imported Upstream version 0.16
---
 .travis.yml             |   1 +
 AUTHORS.txt             |   1 +
 CHANGES.txt             |  12 ++-
 rasterio/__init__.py    |   3 +-
 rasterio/_base.pyx      |  22 +++--
 rasterio/_drivers.pyx   |  15 ++++
 rasterio/_features.pyx  |  10 ++-
 rasterio/_io.pyx        |  11 +++
 rasterio/_warp.pyx      |  26 ++++--
 rasterio/features.py    |  31 ++++---
 rasterio/transform.py   |  14 ++-
 rasterio/warp.py        | 140 ++++++++++++++++++++++++-----
 setup.py                |   5 +-
 tests/data/README.rst   |   6 ++
 tests/test_no_georef.py |  30 +++++++
 tests/test_read.py      |  26 ++++++
 tests/test_warp.py      | 235 ++++++++++++++++++++++++++++++++----------------
 17 files changed, 437 insertions(+), 151 deletions(-)

diff --git a/.travis.yml b/.travis.yml
index 7180aed..0fc4c5c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -8,6 +8,7 @@ before_install:
   - sudo apt-get update -qq
   - sudo apt-get install -y libgdal1h gdal-bin libgdal-dev
 install:
+  - pip install --install-option="--no-cython-compile" cython
   - "pip install -r requirements-dev.txt"
   - "pip install pytest"
   - "pip install coveralls"
diff --git a/AUTHORS.txt b/AUTHORS.txt
index 54f3fca..3cd8e34 100644
--- a/AUTHORS.txt
+++ b/AUTHORS.txt
@@ -9,5 +9,6 @@ Chrisophe Gohlke https://github.com/cgohlke
 Robin Wilson https://github.com/robintw
 Mike Toews https://github.com/mwtoews
 Amit Kapadia https://github.com/kapadia
+Alessandro Amici https://github.com/alexamici
 
 See also https://github.com/mapbox/rasterio/graphs/contributors.
diff --git a/CHANGES.txt b/CHANGES.txt
index afd760b..6830152 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,8 +1,16 @@
 Changes
 =======
 
-0.1.5.1 (2014-11-03)
---------------------
+0.16.0 (2014-12-16)
+-------------------
+- More graceful, slice-like handling of windows (#191).
+- Addition of optional z coordinate to warp.transform() (#199).
+- Relax excessively strict transform guard, allowing translation of rasters
+  with no georeferencing (#210).
+- Removal of setuptools from the package's install_requires (#222).
+
+0.15.1 (2014-11-03)
+-------------------
 - Fix incorrect use of output.dtype (#196).
 
 0.15 (2014-10-11)
diff --git a/rasterio/__init__.py b/rasterio/__init__.py
index 04c7691..4bbc8d0 100644
--- a/rasterio/__init__.py
+++ b/rasterio/__init__.py
@@ -18,7 +18,7 @@ from rasterio.transform import Affine, guard_transform
 
 __all__ = [
     'band', 'open', 'drivers', 'copy', 'pad']
-__version__ = "0.15.1"
+__version__ = "0.16"
 
 log = logging.getLogger('rasterio')
 class NullHandler(logging.Handler):
@@ -161,4 +161,3 @@ def pad(array, transform, pad_width, mode=None, **kwargs):
     padded_trans[2] -= pad_width*padded_trans[0]
     padded_trans[5] -= pad_width*padded_trans[4]
     return padded_array, Affine(*padded_trans[:6])
-
diff --git a/rasterio/_base.pyx b/rasterio/_base.pyx
index 87f696e..e529efd 100644
--- a/rasterio/_base.pyx
+++ b/rasterio/_base.pyx
@@ -511,12 +511,11 @@ cdef class DatasetReader(object):
         
         if self._hds == NULL:
           raise ValueError("can't read closed raster file")
-        if bidx > 0:
-            if bidx not in self.indexes:
-                raise ValueError("Invalid band index")
-            hBand = _gdal.GDALGetRasterBand(self._hds, bidx)
-            if hBand == NULL:
-                raise ValueError("NULL band")
+        if bidx not in self.indexes:
+            raise ValueError("Invalid band index")
+        hBand = _gdal.GDALGetRasterBand(self._hds, bidx)
+        if hBand == NULL:
+            raise ValueError("NULL band")
         value = _gdal.GDALGetRasterColorInterpretation(hBand)
         return ColorInterp(value)
     
@@ -528,12 +527,11 @@ cdef class DatasetReader(object):
         cdef _gdal.GDALColorEntry *color
         if self._hds == NULL:
             raise ValueError("can't read closed raster file")
-        if bidx > 0:
-            if bidx not in self.indexes:
-                raise ValueError("Invalid band index")
-            hBand = _gdal.GDALGetRasterBand(self._hds, bidx)
-            if hBand == NULL:
-                raise ValueError("NULL band")
+        if bidx not in self.indexes:
+            raise ValueError("Invalid band index")
+        hBand = _gdal.GDALGetRasterBand(self._hds, bidx)
+        if hBand == NULL:
+            raise ValueError("NULL band")
         hTable = _gdal.GDALGetRasterColorTable(hBand)
         if hTable == NULL:
             raise ValueError("NULL color table")
diff --git a/rasterio/_drivers.pyx b/rasterio/_drivers.pyx
index 26f6689..7d470e2 100644
--- a/rasterio/_drivers.pyx
+++ b/rasterio/_drivers.pyx
@@ -1,18 +1,24 @@
 # The GDAL and OGR driver registry.
 # GDAL driver management.
 
+import os
+import os.path
 import logging
+import sys
 
 from rasterio.five import string_types
 
+
 cdef extern from "cpl_conv.h":
     void    CPLFree (void *ptr)
     void    CPLSetThreadLocalConfigOption (char *key, char *val)
     const char * CPLGetConfigOption ( const char *key, const char *default)
 
+
 cdef extern from "cpl_error.h":
     void CPLSetErrorHandler (void *handler)
 
+
 cdef extern from "gdal.h":
     void GDALAllRegister()
     void GDALDestroyDriverManager()
@@ -21,17 +27,20 @@ cdef extern from "gdal.h":
     const char * GDALGetDriverShortName(void *driver)
     const char * GDALGetDriverLongName(void *driver)
 
+
 cdef extern from "ogr_api.h":
     void OGRRegisterAll()
     void OGRCleanupAll()
     int OGRGetDriverCount()
 
+
 log = logging.getLogger('GDAL')
 class NullHandler(logging.Handler):
     def emit(self, record):
         pass
 log.addHandler(NullHandler())
 
+
 level_map = {
     0: 0,
     1: logging.DEBUG,
@@ -84,6 +93,12 @@ cdef class GDALEnv(object):
         CPLSetErrorHandler(<void *>errorHandler)
         if driver_count() == 0:
             raise ValueError("Drivers not registered")
+
+        if 'GDAL_DATA' not in os.environ:
+            datadir = os.path.join(sys.prefix, 'share/gdal')
+            if os.path.exists(os.path.join(datadir, 'pcs.csv')):
+                os.environ['GDAL_DATA'] = datadir
+
         for key, val in self.options.items():
             key_b = key.upper().encode('utf-8')
             key_c = key_b
diff --git a/rasterio/_features.pyx b/rasterio/_features.pyx
index 2fc5ec6..3858af4 100644
--- a/rasterio/_features.pyx
+++ b/rasterio/_features.pyx
@@ -232,12 +232,14 @@ def _rasterize(shapes, image, transform, all_touched):
     image : numpy ndarray
         Array in which to store results.
     transform : Affine transformation object, optional
-        Transformation applied to shape geometries into pixel coordinates.
+        Transformation from pixel coordinates of `image` to the
+        coordinate system of the input `shapes`. See the `transform`
+        property of dataset objects.
     all_touched : boolean, optional
         If True, all pixels touched by geometries will be burned in.
-        If false, only pixels whose center is within the polygon or that are
-        selected by brezenhams line algorithm will be burned in.
-
+        If false, only pixels whose center is within the polygon or
+        that are selected by brezenhams line algorithm will be burned
+        in.
     """
 
     cdef int retval
diff --git a/rasterio/_io.pyx b/rasterio/_io.pyx
index 9ae404d..38edae0 100644
--- a/rasterio/_io.pyx
+++ b/rasterio/_io.pyx
@@ -22,6 +22,7 @@ from rasterio.five import text_type, string_types
 from rasterio.transform import Affine
 from rasterio.enums import ColorInterp
 
+
 log = logging.getLogger('rasterio')
 if 'all' in sys.warnoptions:
     # show messages in console with: python -W all
@@ -594,6 +595,16 @@ cdef class RasterReader(_base.DatasetReader):
             dtype = self.dtypes[0]
         else:  # unique dtype; normal case
             dtype = check_dtypes.pop()
+
+        # Windows are always limited to the dataset's extent.
+        if window:
+            window = eval_window(window, self.height, self.width)
+            window = ((
+                    min(window[0][0] or 0, self.height),
+                    min(window[0][1] or self.height, self.height)), (
+                    min(window[1][0] or 0, self.width),
+                    min(window[1][1] or self.width, self.width)))
+
         out_shape = (len(indexes),) + (
             window
             and window_shape(window, self.height, self.width)
diff --git a/rasterio/_warp.pyx b/rasterio/_warp.pyx
index 3137bf2..d9faaed 100644
--- a/rasterio/_warp.pyx
+++ b/rasterio/_warp.pyx
@@ -111,15 +111,16 @@ cdef void *_osr_from_crs(object crs):
     return osr
 
 
-def _transform(src_crs, dst_crs, xs, ys):
-    cdef double *x, *y
+def _transform(src_crs, dst_crs, xs, ys, zs):
+    cdef double *x, *y, *z = NULL
     cdef char *proj_c = NULL
     cdef void *src, *dst
     cdef void *transform
     cdef int i
 
     assert len(xs) == len(ys)
-    
+    assert zs is None or len(xs) == len(zs)
+
     src = _osr_from_crs(src_crs)
     dst = _osr_from_crs(dst_crs)
 
@@ -130,8 +131,13 @@ def _transform(src_crs, dst_crs, xs, ys):
         x[i] = xs[i]
         y[i] = ys[i]
 
+    if zs is not None:
+        z = <double *>_gdal.CPLMalloc(n*sizeof(double))
+        for i in range(n):
+            z[i] = zs[i]
+
     transform = _gdal.OCTNewCoordinateTransformation(src, dst)
-    res = _gdal.OCTTransform(transform, n, x, y, NULL)
+    res = _gdal.OCTTransform(transform, n, x, y, z)
     #if res:
     #    raise ValueError("Failed coordinate transformation")
 
@@ -142,12 +148,22 @@ def _transform(src_crs, dst_crs, xs, ys):
         res_xs[i] = x[i]
         res_ys[i] = y[i]
 
+    if zs is not None:
+        res_zs = [0]*n
+        for i in range(n):
+            res_zs[i] = z[i]
+        _gdal.CPLFree(z)
+
+        retval = (res_xs, res_ys, res_zs)
+    else:
+        retval = (res_xs, res_ys)
+
     _gdal.CPLFree(x)
     _gdal.CPLFree(y)
     _gdal.OCTDestroyCoordinateTransformation(transform)
     _gdal.OSRDestroySpatialReference(src)
     _gdal.OSRDestroySpatialReference(dst)
-    return res_xs, res_ys
+    return retval
 
 
 def _transform_geom(
diff --git a/rasterio/features.py b/rasterio/features.py
index 8e55cb8..ea5884a 100644
--- a/rasterio/features.py
+++ b/rasterio/features.py
@@ -182,26 +182,30 @@ def rasterize(
 
     Parameters
     ----------
-    shapes : iterable of (geometry, value) pairs or iterable over geometries
-        `geometry` can either be an object that implements the geo interface or
-        GeoJSON-like object.
+    shapes : iterable of (geometry, value) pairs or iterable over
+        geometries `geometry` can either be an object that implements
+        the geo interface or GeoJSON-like object.
     out_shape : tuple or list
-        Shape of output numpy ndarray
+        Shape of output numpy ndarray.
     fill : int or float, optional
-        Used as fill value for all areas not covered by input geometries
+        Used as fill value for all areas not covered by input
+        geometries.
     out : numpy ndarray, optional
-        Array of same shape and data type as `image` in which to store results.
+        Array of same shape and data type as `image` in which to store
+        results.
     output : older alias for `out`, will be removed before 1.0.
     transform : Affine transformation object, optional
-        transformation applied to shape geometries into pixel coordinates
+        Transformation from pixel coordinates of `image` to the
+        coordinate system of the input `shapes`. See the `transform`
+        property of dataset objects.
     all_touched : boolean, optional
-        If True, all pixels touched by geometries will be burned in.
-        If false, only pixels whose center is within the polygon or that are
-        selected by brezenhams line algorithm will be burned in.
+        If True, all pixels touched by geometries will be burned in.  If
+        false, only pixels whose center is within the polygon or that
+        are selected by brezenhams line algorithm will be burned in.
     default_value : int or float, optional
-        Used as value for all geometries, if not provided in `shapes`
+        Used as value for all geometries, if not provided in `shapes`.
     dtype : rasterio or numpy data type, optional
-        Used as data type for results, if `output` is not provided
+        Used as data type for results, if `output` is not provided.
 
     Returns
     -------
@@ -212,7 +216,8 @@ def rasterize(
     -----
     Valid data types for `fill`, `default_value`, `out`, `dtype` and
     shape values are rasterio.int16, rasterio.int32, rasterio.uint8,
-    rasterio.uint16, rasterio.uint32, rasterio.float32, rasterio.float64
+    rasterio.uint16, rasterio.uint32, rasterio.float32,
+    rasterio.float64.
 
     """
 
diff --git a/rasterio/transform.py b/rasterio/transform.py
index 4b3ed93..9b29945 100644
--- a/rasterio/transform.py
+++ b/rasterio/transform.py
@@ -1,12 +1,14 @@
-
 import warnings
 
 from affine import Affine
 
 IDENTITY = Affine.identity()
 
-def tastes_like_gdal(t):
-    return t[2] == t[4] == 0.0 and t[1] > 0 and t[5] < 0
+
+def tastes_like_gdal(seq):
+    """Return True if `seq` matches the GDAL geotransform pattern."""
+    return seq[2] == seq[4] == 0.0 and seq[1] > 0 and seq[5] < 0
+
 
 def guard_transform(transform):
     """Return an Affine transformation instance"""
@@ -20,10 +22,4 @@ def guard_transform(transform):
             transform = Affine.from_gdal(*transform)
         else:
             transform = Affine(*transform)
-    a, e = transform.a, transform.e
-    if a == 0.0 or e == 0.0:
-        raise ValueError(
-            "Transform has invalid coefficients a, e: (%f, %f)" % (
-                transform.a, transform.e))
     return transform
-
diff --git a/rasterio/warp.py b/rasterio/warp.py
index b01f841..25fd5a7 100644
--- a/rasterio/warp.py
+++ b/rasterio/warp.py
@@ -4,43 +4,139 @@ from rasterio._warp import _reproject, _transform, _transform_geom, RESAMPLING
 from rasterio.transform import guard_transform
 
 
-def transform(src_crs, dst_crs, xs, ys):
-    """Return transformed vectors of x and y."""
-    return _transform(src_crs, dst_crs, xs, ys)
+def transform(src_crs, dst_crs, xs, ys, zs=None):
+    """
+    Transform vectors of x, y and optionally z from source
+    coordinate reference system into target.
+
+    Parameters
+    ------------
+    src_crs: dict
+        Source coordinate reference system, in rasterio dict format.
+        Example: {'init': 'EPSG:4326'}
+    dst_crs: dict
+        Target coordinate reference system.
+    xs: array_like
+        Contains x values.  Will be cast to double floating point values.
+    ys:  array_like
+        Contains y values.
+    zs: array_like, optional
+        Contains z values.  Assumed to be all 0 if absent.
+
+    Returns
+    ---------
+    out: tuple of array_like, (xs, ys, [zs])
+    Tuple of x, y, and optionally z vectors, transformed into the target
+    coordinate reference system.
+    """
+    return _transform(src_crs, dst_crs, xs, ys, zs)
 
 
 def transform_geom(
-        src_crs, dst_crs, geom,
-        antimeridian_cutting=False, antimeridian_offset=10.0, precision=-1):
-    """Return transformed geometry."""
+        src_crs,
+        dst_crs,
+        geom,
+        antimeridian_cutting=False,
+        antimeridian_offset=10.0,
+        precision=-1):
+    """
+    Transform geometry from source coordinate reference system into target.
+
+    Parameters
+    ------------
+    src_crs: dict
+        Source coordinate reference system, in rasterio dict format.
+        Example: {'init': 'EPSG:4326'}
+    dst_crs: dict
+        Target coordinate reference system.
+    geom: GeoJSON like dict object
+    antimeridian_cutting: bool, optional
+        If True, cut geometries at the antimeridian, otherwise geometries will
+        not be cut (default).
+    antimeridian_offset: float
+        Offset from the antimeridian in degrees (default: 10) within which
+        any geometries will be split.
+    precision: float
+        If >= 0, geometry coordinates will be rounded to this number of decimal
+        places after the transform operation, otherwise original coordinate
+        values will be preserved (default).
+
+    Returns
+    ---------
+    out: GeoJSON like dict object
+        Transformed geometry in GeoJSON dict format
+    """
+
     return _transform_geom(
-        src_crs, dst_crs, geom,
-        antimeridian_cutting, antimeridian_offset, precision)
+        src_crs,
+        dst_crs,
+        geom,
+        antimeridian_cutting,
+        antimeridian_offset,
+        precision)
 
 
 def reproject(
-        source, destination,
-        src_transform=None, src_crs=None,
-        dst_transform=None, dst_crs=None,
+        source,
+        destination,
+        src_transform=None,
+        src_crs=None,
+        dst_transform=None,
+        dst_crs=None,
         resampling=RESAMPLING.nearest,
         **kwargs):
-    """Reproject a source raster to a destination.
+    """
+    Reproject a source raster to a destination raster.
 
-    If the source and destination are ndarrays, coordinate reference
-    system definitions and affine transformation parameters are required
-    for reprojection.
+    Parameters
+    ------------
+    source: ndarray or rasterio Band
+        Source raster.
+    destination: ndarray or rasterio Band
+        Target raster.
+    src_transform: affine transform object, optional
+        Source affine transformation.  Required if source and destination
+        are ndarrays.  Will be derived from source if it is a rasterio Band.
+    src_crs: dict, optional
+        Source coordinate reference system, in rasterio dict format.
+        Required if source and destination are ndarrays.
+        Will be derived from source if it is a rasterio Band.
+        Example: {'init': 'EPSG:4326'}
+    dst_transform: affine transform object, optional
+        Target affine transformation.  Required if source and destination
+        are ndarrays.  Will be derived from target if it is a rasterio Band.
+    dst_crs: dict, optional
+        Target coordinate reference system.  Required if source and destination
+        are ndarrays.  Will be derived from target if it is a rasterio Band.
+    resampling: int
+        Resampling method to use.  One of the following:
+            RESAMPLING.nearest,
+            RESAMPLING.bilinear,
+            RESAMPLING.cubic,
+            RESAMPLING.cubic_spline,
+            RESAMPLING.lanczos,
+            RESAMPLING.average,
+            RESAMPLING.mode
+    kwargs:  dict, optional
+        Additional arguments passed to transformation function.
 
-    If the source and destination are rasterio Bands, shorthand for
-    bands of datasets on disk, the coordinate reference systems and
-    transforms will be read from the appropriate datasets.
+    Returns
+    ---------
+    out: None
+        Output is written to destination.
     """
+
     if src_transform:
         src_transform = guard_transform(src_transform).to_gdal()
     if dst_transform:
         dst_transform = guard_transform(dst_transform).to_gdal()
 
     _reproject(
-        source, destination,
-        src_transform, src_crs,
-        dst_transform, dst_crs,
-        resampling, **kwargs)
+        source,
+        destination,
+        src_transform,
+        src_crs,
+        dst_transform,
+        dst_crs,
+        resampling,
+        **kwargs)
diff --git a/setup.py b/setup.py
index 98fbc4c..7e39bfa 100755
--- a/setup.py
+++ b/setup.py
@@ -124,9 +124,8 @@ with open('README.rst') as f:
 # Runtime requirements.
 inst_reqs = [
     'affine>=1.0',
-    'click',
-    'Numpy>=1.7',
-    'setuptools' ] 
+    'click>=3.0',
+    'Numpy>=1.7' ]
 
 if sys.version_info < (3, 4):
     inst_reqs.append('enum34')
diff --git a/tests/data/README.rst b/tests/data/README.rst
index 9c85140..0e63a6b 100644
--- a/tests/data/README.rst
+++ b/tests/data/README.rst
@@ -6,3 +6,9 @@ Rasterio's tests require several raster data files. Grab them from
 https://github.com/mapbox/rasterio/tree/master/tests/data
 
 and copy them to this directory.
+
+The RGB.byte.tif file is derived from USGS Landsat 7 ETM imagery. The shade.tif
+file is derived from USGS SRTM 90 data. The float.tif and float_nan.tif files
+are original works of the Rasterio authors. All test images are licensed under
+the CC0 1.0 Universal (CC0 1.0) Public Domain Dedication:
+http://creativecommons.org/publicdomain/zero/1.0/.
diff --git a/tests/test_no_georef.py b/tests/test_no_georef.py
new file mode 100644
index 0000000..05807b6
--- /dev/null
+++ b/tests/test_no_georef.py
@@ -0,0 +1,30 @@
+# You should be able to write rasters with no georeferencing, e.g., plain old
+# PNGs and JPEGs.
+
+import rasterio
+
+
+def test_write(tmpdir):
+    name = str(tmpdir.join("test.png"))
+    with rasterio.open('tests/data/RGB.byte.tif') as src:
+        kwargs = src.meta.copy()
+        del kwargs['affine']
+        del kwargs['transform']
+        del kwargs['crs']
+        kwargs['driver'] = 'PNG'
+        with rasterio.open(name, 'w', **kwargs) as dst:
+            dst.write(src.read())
+
+
+def test_read_write(tmpdir):
+    tif1 = str(tmpdir.join("test.tif"))
+    tif2 = str(tmpdir.join("test2.tif"))
+    with rasterio.open('tests/data/RGB.byte.tif') as src:
+        kwargs = src.meta.copy()
+        del kwargs['affine']
+        del kwargs['transform']
+        del kwargs['crs']
+        with rasterio.open(tif1, 'w', **kwargs) as dst:
+            dst.write(src.read())
+    with rasterio.open(tif1) as src, rasterio.open(tif2, 'w', **src.meta) as dst:
+        dst.write(src.read())
diff --git a/tests/test_read.py b/tests/test_read.py
index f962138..61bd736 100644
--- a/tests/test_read.py
+++ b/tests/test_read.py
@@ -1,3 +1,5 @@
+import logging
+import sys
 import unittest
 
 import numpy
@@ -6,6 +8,9 @@ from hashlib import md5
 import rasterio
 
 
+logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
+
+
 class ReaderContextTest(unittest.TestCase):
 
     def test_context(self):
@@ -188,6 +193,27 @@ class ReaderContextTest(unittest.TestCase):
                                '6a675416a32fcb70fbcf601d01aeb6ee',
                                '94fd2733b534376c273a894f36ad4e0b'])
 
+    def test_read_window_overflow(self):
+        """Test graceful Numpy-like handling of windows that overflow
+        the dataset's bounds."""
+        with rasterio.open('tests/data/RGB.byte.tif') as s:
+            a = s.read(window=((None, 20000), (None, 20000)))
+            self.assertEqual(a.shape, (3,) + s.shape)
+
+    def test_read_window_beyond(self):
+        """Test graceful Numpy-like handling of windows beyond
+        the dataset's bounds."""
+        with rasterio.open('tests/data/RGB.byte.tif') as s:
+            a = s.read(window=((10000, 20000), (10000, 20000)))
+            self.assertEqual(a.shape, (3,0,0))
+
+    def test_read_window_overlap(self):
+        """Test graceful Numpy-like handling of windows beyond
+        the dataset's bounds."""
+        with rasterio.open('tests/data/RGB.byte.tif') as s:
+            a = s.read(window=((-100, 20000), (-100, 20000)))
+            self.assertEqual(a.shape, (3,100,100))
+
     def test_read_out(self):
         with rasterio.open('tests/data/RGB.byte.tif') as s:
             # regular array, without mask
diff --git a/tests/test_warp.py b/tests/test_warp.py
index d9fef2b..fcf33be 100644
--- a/tests/test_warp.py
+++ b/tests/test_warp.py
@@ -7,39 +7,56 @@ import affine
 import numpy
 
 import rasterio
-from rasterio.warp import reproject, RESAMPLING, transform_geom
+from rasterio.warp import reproject, RESAMPLING, transform_geom, transform
 
 
 logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
 
+
+def test_transform():
+    """2D and 3D"""
+    WGS84_crs = {'init': 'EPSG:4326'}
+    WGS84_points = ([12.492269], [41.890169], [48.])
+    ECEF_crs = {'init': 'EPSG:4978'}
+    ECEF_points = ([4642610.], [1028584.], [4236562.])
+    ECEF_result = transform(WGS84_crs, ECEF_crs, *WGS84_points)
+    assert numpy.allclose(numpy.array(ECEF_result), numpy.array(ECEF_points))
+
+    UTM33_crs = {'init': 'EPSG:32633'}
+    UTM33_points = ([291952], [4640623])
+    UTM33_result = transform(WGS84_crs, UTM33_crs, *WGS84_points[:2])
+    assert numpy.allclose(numpy.array(UTM33_result), numpy.array(UTM33_points))
+
+
 def test_reproject():
     """Ndarry to ndarray"""
     with rasterio.drivers():
         with rasterio.open('tests/data/RGB.byte.tif') as src:
             source = src.read_band(1)
-        dst_transform = affine.Affine.from_gdal(-8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
+        dst_transform = affine.Affine.from_gdal(
+            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
         dst_crs = dict(
-                    proj='merc',
-                    a=6378137,
-                    b=6378137,
-                    lat_ts=0.0,
-                    lon_0=0.0,
-                    x_0=0.0,
-                    y_0=0,
-                    k=1.0,
-                    units='m',
-                    nadgrids='@null',
-                    wktext=True,
-                    no_defs=True)
+            proj='merc',
+            a=6378137,
+            b=6378137,
+            lat_ts=0.0,
+            lon_0=0.0,
+            x_0=0.0,
+            y_0=0,
+            k=1.0,
+            units='m',
+            nadgrids='@null',
+            wktext=True,
+            no_defs=True)
         destin = numpy.empty(src.shape, dtype=numpy.uint8)
         reproject(
-            source, 
+            source,
             destin,
             src_transform=src.transform,
             src_crs=src.crs,
-            dst_transform=dst_transform, 
+            dst_transform=dst_transform,
             dst_crs=dst_crs,
-            resampling=RESAMPLING.nearest )
+            resampling=RESAMPLING.nearest)
     assert destin.any()
     try:
         import matplotlib.pyplot as plt
@@ -49,35 +66,36 @@ def test_reproject():
     except:
         pass
 
+
 def test_reproject_multi():
     """Ndarry to ndarray"""
     with rasterio.drivers():
         with rasterio.open('tests/data/RGB.byte.tif') as src:
             source = src.read()
         dst_transform = affine.Affine.from_gdal(
-                            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
+            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
         dst_crs = dict(
-                    proj='merc',
-                    a=6378137,
-                    b=6378137,
-                    lat_ts=0.0,
-                    lon_0=0.0,
-                    x_0=0.0,
-                    y_0=0,
-                    k=1.0,
-                    units='m',
-                    nadgrids='@null',
-                    wktext=True,
-                    no_defs=True)
+            proj='merc',
+            a=6378137,
+            b=6378137,
+            lat_ts=0.0,
+            lon_0=0.0,
+            x_0=0.0,
+            y_0=0,
+            k=1.0,
+            units='m',
+            nadgrids='@null',
+            wktext=True,
+            no_defs=True)
         destin = numpy.empty(source.shape, dtype=numpy.uint8)
         reproject(
-            source, 
+            source,
             destin,
             src_transform=src.transform,
             src_crs=src.crs,
-            dst_transform=dst_transform, 
+            dst_transform=dst_transform,
             dst_crs=dst_crs,
-            resampling=RESAMPLING.nearest )
+            resampling=RESAMPLING.nearest)
     assert destin.any()
     try:
         import matplotlib.pyplot as plt
@@ -87,28 +105,30 @@ def test_reproject_multi():
     except:
         pass
 
+
 def test_warp_from_file():
     """File to ndarray"""
     with rasterio.open('tests/data/RGB.byte.tif') as src:
-        dst_transform = affine.Affine.from_gdal(-8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
+        dst_transform = affine.Affine.from_gdal(
+            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
         dst_crs = dict(
-                    proj='merc',
-                    a=6378137,
-                    b=6378137,
-                    lat_ts=0.0,
-                    lon_0=0.0,
-                    x_0=0.0,
-                    y_0=0,
-                    k=1.0,
-                    units='m',
-                    nadgrids='@null',
-                    wktext=True,
-                    no_defs=True)
+            proj='merc',
+            a=6378137,
+            b=6378137,
+            lat_ts=0.0,
+            lon_0=0.0,
+            x_0=0.0,
+            y_0=0,
+            k=1.0,
+            units='m',
+            nadgrids='@null',
+            wktext=True,
+            no_defs=True)
         destin = numpy.empty(src.shape, dtype=numpy.uint8)
         reproject(
-            rasterio.band(src, 1), 
-            destin, 
-            dst_transform=dst_transform, 
+            rasterio.band(src, 1),
+            destin,
+            dst_transform=dst_transform,
             dst_crs=dst_crs)
     assert destin.any()
     try:
@@ -119,24 +139,26 @@ def test_warp_from_file():
     except:
         pass
 
+
 def test_warp_from_to_file(tmpdir):
     """File to file"""
     tiffname = str(tmpdir.join('foo.tif'))
     with rasterio.open('tests/data/RGB.byte.tif') as src:
-        dst_transform = affine.Affine.from_gdal(-8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
+        dst_transform = affine.Affine.from_gdal(
+            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
         dst_crs = dict(
-                    proj='merc',
-                    a=6378137,
-                    b=6378137,
-                    lat_ts=0.0,
-                    lon_0=0.0,
-                    x_0=0.0,
-                    y_0=0,
-                    k=1.0,
-                    units='m',
-                    nadgrids='@null',
-                    wktext=True,
-                    no_defs=True)
+            proj='merc',
+            a=6378137,
+            b=6378137,
+            lat_ts=0.0,
+            lon_0=0.0,
+            x_0=0.0,
+            y_0=0,
+            k=1.0,
+            units='m',
+            nadgrids='@null',
+            wktext=True,
+            no_defs=True)
         kwargs = src.meta.copy()
         kwargs.update(
             transform=dst_transform,
@@ -146,24 +168,26 @@ def test_warp_from_to_file(tmpdir):
                 reproject(rasterio.band(src, i), rasterio.band(dst, i))
     # subprocess.call(['open', tiffname])
 
+
 def test_warp_from_to_file_multi(tmpdir):
     """File to file"""
     tiffname = str(tmpdir.join('foo.tif'))
     with rasterio.open('tests/data/RGB.byte.tif') as src:
-        dst_transform = affine.Affine.from_gdal(-8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
+        dst_transform = affine.Affine.from_gdal(
+            -8789636.708, 300.0, 0.0, 2943560.235, 0.0, -300.0)
         dst_crs = dict(
-                    proj='merc',
-                    a=6378137,
-                    b=6378137,
-                    lat_ts=0.0,
-                    lon_0=0.0,
-                    x_0=0.0,
-                    y_0=0,
-                    k=1.0,
-                    units='m',
-                    nadgrids='@null',
-                    wktext=True,
-                    no_defs=True)
+            proj='merc',
+            a=6378137,
+            b=6378137,
+            lat_ts=0.0,
+            lon_0=0.0,
+            x_0=0.0,
+            y_0=0,
+            k=1.0,
+            units='m',
+            nadgrids='@null',
+            wktext=True,
+            no_defs=True)
         kwargs = src.meta.copy()
         kwargs.update(
             transform=dst_transform,
@@ -171,14 +195,67 @@ def test_warp_from_to_file_multi(tmpdir):
         with rasterio.open(tiffname, 'w', **kwargs) as dst:
             for i in (1, 2, 3):
                 reproject(
-                    rasterio.band(src, i), 
+                    rasterio.band(src, i),
                     rasterio.band(dst, i),
                     num_threads=2)
     # subprocess.call(['open', tiffname])
 
-def test_transform_geom_wrap():
-    geom = {'type': 'Polygon', 'coordinates': (((798842.3090855901, 6569056.500655151), (756688.2826828464, 6412397.888771972), (755571.0617232556, 6408461.009397383), (677605.2284582685, 6425600.39266733), (677605.2284582683, 6425600.392667332), (670873.3791649605, 6427248.603432341), (664882.1106069803, 6407585.48425362), (663675.8662823177, 6403676.990080649), (485120.71963574126, 6449787.167760638), (485065.55660851026, 6449802.826920689), (485957.03982722526, 6452708.625101285), (48 [...]
+
+def test_transform_geom():
+    geom = {
+        'type': 'Polygon',
+        'coordinates': (
+            ((798842.3090855901, 6569056.500655151),
+                (756688.2826828464, 6412397.888771972),
+                (755571.0617232556, 6408461.009397383),
+                (677605.2284582685, 6425600.39266733),
+                (677605.2284582683, 6425600.392667332),
+                (670873.3791649605, 6427248.603432341),
+                (664882.1106069803, 6407585.48425362),
+                (663675.8662823177, 6403676.990080649),
+                (485120.71963574126, 6449787.167760638),
+                (485065.55660851026, 6449802.826920689),
+                (485957.03982722526, 6452708.625101285),
+                (487541.24541826674, 6457883.292107048),
+                (531008.5797472061, 6605816.560367976),
+                (530943.7197027118, 6605834.9333479265),
+                (531888.5010308184, 6608940.750411527),
+                (533299.5981959199, 6613962.642851984),
+                (533403.6388841148, 6613933.172096095),
+                (576345.6064638699, 6761983.708069147),
+                (577649.6721159086, 6766698.137844516),
+                (578600.3589008929, 6770143.99782289),
+                (578679.4732294685, 6770121.638265098),
+                (655836.640492081, 6749376.357102599),
+                (659913.0791150068, 6764770.1314677475),
+                (661105.8478791204, 6769515.168134831),
+                (661929.4670843681, 6772800.8565198565),
+                (661929.4670843673, 6772800.856519875),
+                (661975.1582566603, 6772983.354777632),
+                (662054.7979028501, 6772962.86384242),
+                (841909.6014891531, 6731793.200435557),
+                (840726.455490463, 6727039.8672589315),
+                (798842.3090855901, 6569056.500655151)),
+            )
+    }
+
+    result = transform_geom('EPSG:3373', 'EPSG:4326', geom)
+    assert result['type'] == 'Polygon'
+    assert len(result['coordinates']) == 1
+
     result = transform_geom(
-                'EPSG:3373', 'EPSG:4326', geom, antimeridian_cutting=True)
+        'EPSG:3373', 'EPSG:4326', geom, antimeridian_cutting=True)
     assert result['type'] == 'MultiPolygon'
     assert len(result['coordinates']) == 2
+
+    result = transform_geom(
+        'EPSG:3373', 
+        'EPSG:4326', 
+        geom, 
+        antimeridian_cutting=True, 
+        antimeridian_offset=0)
+    assert result['type'] == 'MultiPolygon'
+    assert len(result['coordinates']) == 2
+
+    result = transform_geom('EPSG:3373', 'EPSG:4326',  geom,  precision=1)
+    assert int(result['coordinates'][0][0][0] * 10) == -1778

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/rasterio.git



More information about the Pkg-grass-devel mailing list