File: test_merge.py

package info (click to toggle)
rasterio 1.4.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,760 kB
  • sloc: python: 22,520; makefile: 275; sh: 164; xml: 29
file content (298 lines) | stat: -rw-r--r-- 10,435 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""Tests of rasterio.merge"""

import boto3
from hypothesis import given, settings
from hypothesis.strategies import floats
import numpy
import pytest
import warnings

import affine
import rasterio
from rasterio.merge import merge
from rasterio.crs import CRS
from rasterio.errors import MergeError, RasterioError
from rasterio.vrt import WarpedVRT
from rasterio.warp import aligned_target
from rasterio import windows

from .conftest import gdal_version


@pytest.fixture(scope="function")
def test_data_complex(tmp_path):
    transform = affine.Affine(30.0, 0.0, 215200.0, 0.0, -30.0, 4397500.0)
    t2 = transform * transform.translation(0, 3)

    with rasterio.open(
        tmp_path.joinpath("r2.tif"),
        "w",
        nodata=0,
        dtype=numpy.complex64,
        height=2,
        width=2,
        count=1,
        crs="EPSG:32611",
        transform=transform,
    ) as src:
        src.write(numpy.ones((1, 2, 2)))

    with rasterio.open(
        tmp_path.joinpath("r1.tif"),
        "w",
        nodata=0,
        dtype=numpy.complex64,
        height=2,
        width=2,
        count=1,
        crs="EPSG:32611",
        transform=t2,
    ) as src:
        src.write(numpy.ones((1, 2, 2)) * 2 - 1j)

    return tmp_path


# Non-coincident datasets test fixture.
# Three overlapping GeoTIFFs, two to the NW and one to the SE.
@pytest.fixture(scope="function")
def test_data_dir_overlapping(tmp_path):
    kwargs = {
        "crs": "EPSG:4326",
        "transform": affine.Affine(0.2, 0, -114, 0, -0.2, 46),
        "count": 1,
        "dtype": rasterio.uint8,
        "driver": "GTiff",
        "width": 10,
        "height": 10,
        "nodata": 0,
    }

    with rasterio.open(tmp_path.joinpath("nw1.tif"), "w", **kwargs) as dst:
        data = numpy.ones((10, 10), dtype=rasterio.uint8)
        dst.write(data, indexes=1)

    with rasterio.open(tmp_path.joinpath("nw3.tif"), "w", **kwargs) as dst:
        data = numpy.ones((10, 10), dtype=rasterio.uint8) * 3
        dst.write(data, indexes=1)

    kwargs["transform"] = affine.Affine(0.2, 0, -113, 0, -0.2, 45)

    with rasterio.open(tmp_path.joinpath("se.tif"), "w", **kwargs) as dst:
        data = numpy.ones((10, 10), dtype=rasterio.uint8) * 2
        dst.write(data, indexes=1)

    return tmp_path


def test_different_crs(test_data_dir_overlapping):
    inputs = [x.name for x in test_data_dir_overlapping.iterdir()]

    # Create new raster with different crs
    with rasterio.open(test_data_dir_overlapping.joinpath(inputs[-1])) as ds_src:
        kwds = ds_src.profile
        kwds['crs'] = CRS.from_epsg(3499)
        with rasterio.open(test_data_dir_overlapping.joinpath("new.tif"), 'w', **kwds) as ds_out:
            ds_out.write(ds_src.read())

    with pytest.raises(RasterioError):
        result = merge(list(test_data_dir_overlapping.iterdir()))


@pytest.mark.parametrize(
    "method,value",
    [("first", 1), ("last", 2), ("min", 1), ("max", 3), ("sum", 6), ("count", 3)],
)
def test_merge_method(test_data_dir_overlapping, method, value):
    """Merge method produces expected values in intersection"""
    inputs = sorted(list(test_data_dir_overlapping.iterdir()))  # nw is first.
    datasets = [rasterio.open(x) for x in inputs]
    output_count = 1
    arr, _ = merge(
        datasets, output_count=output_count, method=method, dtype=numpy.uint64
    )
    numpy.testing.assert_array_equal(arr[:, 5:10, 5:10], value)


def test_issue2163():
    """Demonstrate fix for issue 2163"""
    with rasterio.open("tests/data/float_raster_with_nodata.tif") as src:
        data = src.read()
        result, transform = merge([src])
        assert numpy.allclose(data, result[:, : data.shape[1], : data.shape[2]])


def test_masked_output():
    """Get a masked array."""
    with rasterio.open("tests/data/float_raster_with_nodata.tif") as src:
        data = src.read()
        result, transform = merge([src], masked=True)
        assert numpy.allclose(data, result[:, : data.shape[1], : data.shape[2]])
        assert result.mask.any()
        assert result.fill_value == src.nodatavals[0]


def test_unsafe_casting():
    """Demonstrate fix for issue 2179"""
    with rasterio.open("tests/data/float_raster_with_nodata.tif") as src:
        result, transform = merge([src], dtype="uint8", nodata=0.0)
        assert not result.any()  # this is why it's called "unsafe".


@pytest.mark.skipif(
    not (boto3.Session().get_credentials()),
    reason="S3 raster access requires credentials",
)
@pytest.mark.network
@pytest.mark.slow
@settings(deadline=None, max_examples=5)
@given(
    dx=floats(min_value=-0.05, max_value=0.05),
    dy=floats(min_value=-0.05, max_value=0.05),
)
def test_issue2202(dx, dy):
    shapely = pytest.importorskip("shapely", reason="Test requires shapely.")
    import rasterio.merge
    from shapely import wkt
    from shapely.affinity import translate

    aoi = wkt.loads(
        r"POLYGON((11.09 47.94, 11.06 48.01, 11.12 48.11, 11.18 48.11, 11.18 47.94, 11.09 47.94))"
    )
    aoi = translate(aoi, dx, dy)

    with rasterio.Env(AWS_NO_SIGN_REQUEST=True,):
        ds = [
            rasterio.open(i)
            for i in [
                "/vsis3/copernicus-dem-30m/Copernicus_DSM_COG_10_N47_00_E011_00_DEM/Copernicus_DSM_COG_10_N47_00_E011_00_DEM.tif",
                "/vsis3/copernicus-dem-30m/Copernicus_DSM_COG_10_N48_00_E011_00_DEM/Copernicus_DSM_COG_10_N48_00_E011_00_DEM.tif",
            ]
        ]
        aux_array, aux_transform = rasterio.merge.merge(ds, bounds=aoi.bounds)
        from rasterio.plot import show

        show(aux_array)


def test_merge_destination_1(tmp_path):
    """Merge into an opened dataset."""
    with rasterio.open("tests/data/float_raster_with_nodata.tif") as src:
        profile = src.profile
        data = src.read()

        with rasterio.open(tmp_path.joinpath("test.tif"), "w", **profile) as dst:
            for chunk in windows.subdivide(
                windows.Window(0, 0, dst.width, dst.height), 256, 256
            ):
                chunk_bounds = windows.bounds(chunk, dst.transform)
                chunk_arr, chunk_transform = merge([src], bounds=chunk_bounds)
                dst_window = windows.from_bounds(*chunk_bounds, dst.transform)
                dw = windows.from_bounds(*chunk_bounds, dst.transform)
                dw = dw.round_offsets().round_lengths()
                dst.write(chunk_arr, window=dw)

        with rasterio.open(tmp_path.joinpath("test.tif")) as dst:
            result = dst.read()
            assert numpy.allclose(data, result[:, : data.shape[1], : data.shape[2]])


def test_merge_destination_2(tmp_path):
    """Merge into an opened, target-aligned dataset."""
    with rasterio.open("tests/data/RGB.byte.tif") as src:
        profile = src.profile
        dst_transform, dst_width, dst_height = aligned_target(
            src.transform,
            src.width,
            src.height,
            src.res,
        )
        profile.update(transform=dst_transform, width=dst_width, height=dst_height)
        data = src.read()

        with rasterio.open(tmp_path.joinpath("test.tif"), "w", **profile) as dst:
            for chunk in windows.subdivide(
                windows.Window(0, 0, dst.width, dst.height), 256, 256
            ):
                chunk_bounds = windows.bounds(chunk, dst.transform)
                chunk_arr, chunk_transform = merge([src], bounds=chunk_bounds)
                dw = windows.from_bounds(*chunk_bounds, dst.transform)
                dw = dw.round_offsets().round_lengths()
                dst.write(chunk_arr, window=dw)

        with rasterio.open(tmp_path.joinpath("test.tif")) as dst:
            result = dst.read()
            assert result.shape == (3, 719, 792)
            assert numpy.allclose(
                data[data != 0].mean(),
                result[result != 0].mean(),
            )


@pytest.mark.xfail(gdal_version.at_least("3.8"), reason="Unsolved mask read bug #3070.")
def test_complex_merge(test_data_complex):

    with warnings.catch_warnings():
        warnings.simplefilter('error')
        result, _ = merge([test_data_complex/"r2.tif"])
        assert result.dtype == numpy.complex64
        assert numpy.all(result == 1)


def test_complex_nodata(test_data_complex):
    inputs = list(test_data_complex.iterdir())

    with warnings.catch_warnings():
        warnings.simplefilter('error')

        result, _ = merge(inputs, nodata=numpy.nan)
        assert numpy.all(numpy.isnan(result[:, 2]))

        result, _ = merge(inputs, nodata=0-1j)
        assert numpy.all(result[:, 2] == 0-1j)


def test_complex_outrange_nodata_():
    with rasterio.open("tests/data/float_raster_with_nodata.tif") as src:
        with pytest.warns(UserWarning, match="Ignoring nodata value"):
            res, _ = merge([src], nodata=1+1j, dtype='float64')


@pytest.mark.parametrize(
    "matrix",
    [
        affine.Affine.scale(-1, 1),
        affine.Affine.scale(1, -1),
        affine.Affine.rotation(45.0),
    ],
)
def test_failure_source_transforms(data, matrix):
    """Rotated, flipped, and upside down rasters cannot be merged."""
    with rasterio.open(str(data.join("RGB.byte.tif")), "r+") as src:
        src.transform = matrix * src.transform
        with pytest.raises(MergeError):
            merge([src])


def test_merge_warpedvrt(tmp_path):
    """Merge a WarpedVRT into an opened dataset."""
    with rasterio.open("tests/data/RGB.byte.tif") as src:
        with WarpedVRT(src, crs="EPSG:3857") as vrt:
            profile = vrt.profile
            data = vrt.read()
            profile["driver"] = "GTiff"

            with rasterio.open(tmp_path.joinpath("test.tif"), "w", **profile) as dst:
                for chunk in windows.subdivide(
                    windows.Window(0, 0, dst.width, dst.height), 256, 256
                ):
                    chunk_bounds = windows.bounds(chunk, dst.transform)
                    chunk_arr, chunk_transform = merge([vrt], bounds=chunk_bounds)
                    dst_window = windows.from_bounds(*chunk_bounds, dst.transform)
                    dw = windows.from_bounds(*chunk_bounds, dst.transform)
                    dw = dw.round_offsets().round_lengths()
                    dst.write(chunk_arr, window=dw)

    with rasterio.open(tmp_path.joinpath("test.tif")) as dst:
        result = dst.read()
        assert numpy.allclose(data.mean(), result.mean(), rtol=1e-4)