-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathtest_features.py
More file actions
2670 lines (2227 loc) · 101 KB
/
test_features.py
File metadata and controls
2670 lines (2227 loc) · 101 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for new features: multi-band, integer nodata, packbits, zstd, dask, BigTIFF."""
from __future__ import annotations
import os
import numpy as np
import pytest
import xarray as xr
from xrspatial.geotiff import open_geotiff, to_geotiff
from xrspatial.geotiff._compression import (
COMPRESSION_PACKBITS,
packbits_compress,
packbits_decompress,
zstd_compress,
zstd_decompress,
)
from xrspatial.geotiff._header import parse_header, parse_all_ifds
from xrspatial.geotiff._reader import read_to_array
from xrspatial.geotiff._writer import write
# -----------------------------------------------------------------------
# Multi-band write and read
# -----------------------------------------------------------------------
class TestMultiBand:
def test_rgb_uint8_round_trip(self, tmp_path):
"""Write and read back RGB uint8 image."""
arr = np.zeros((8, 8, 3), dtype=np.uint8)
arr[:, :, 0] = 200 # red
arr[:, :, 1] = 100 # green
arr[:, :, 2] = 50 # blue
path = str(tmp_path / 'rgb.tif')
write(arr, path, compression='none', tiled=False)
result, geo = read_to_array(path)
assert result.shape == (8, 8, 3)
np.testing.assert_array_equal(result, arr)
def test_rgb_deflate_tiled(self, tmp_path):
rng = np.random.RandomState(42)
arr = rng.randint(0, 256, (16, 16, 3), dtype=np.uint8)
path = str(tmp_path / 'rgb_deflate.tif')
write(arr, path, compression='deflate', tiled=True, tile_size=8)
result, geo = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_rgba_uint8(self, tmp_path):
arr = np.ones((4, 4, 4), dtype=np.uint8) * 128
path = str(tmp_path / 'rgba.tif')
write(arr, path, compression='none', tiled=False)
result, geo = read_to_array(path)
assert result.shape == (4, 4, 4)
np.testing.assert_array_equal(result, arr)
def test_multiband_float32(self, tmp_path):
arr = np.random.RandomState(99).rand(8, 8, 5).astype(np.float32)
path = str(tmp_path / 'multi.tif')
write(arr, path, compression='deflate', tiled=False)
result, geo = read_to_array(path)
assert result.shape == (8, 8, 5)
np.testing.assert_array_equal(result, arr)
def test_single_band_selection(self, tmp_path):
"""band= parameter should extract one band."""
arr = np.zeros((4, 4, 3), dtype=np.uint8)
arr[:, :, 1] = 42
path = str(tmp_path / 'rgb_sel.tif')
write(arr, path, compression='none', tiled=False)
result, _ = read_to_array(path, band=1)
assert result.shape == (4, 4)
np.testing.assert_array_equal(result, 42)
def test_rgb_to_geotiff_api(self, tmp_path):
"""to_geotiff accepts 3D arrays."""
arr = np.arange(48, dtype=np.uint8).reshape(4, 4, 3)
path = str(tmp_path / 'rgb_api.tif')
to_geotiff(arr, path, compression='none')
result = open_geotiff(path)
assert 'band' in result.dims
assert result.shape == (4, 4, 3)
np.testing.assert_array_equal(result.values, arr)
def test_rgb_cog(self, tmp_path):
"""Multi-band COG with overviews."""
arr = np.random.RandomState(7).randint(
0, 256, (32, 32, 3), dtype=np.uint8)
path = str(tmp_path / 'rgb_cog.tif')
write(arr, path, compression='deflate', tiled=True, tile_size=16,
cog=True, overview_levels=[1])
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
# -----------------------------------------------------------------------
# Integer nodata masking
# -----------------------------------------------------------------------
class TestIntegerNodata:
def test_uint8_nodata_masked(self, tmp_path):
arr = np.array([[0, 1, 2], [3, 255, 5]], dtype=np.uint8)
path = str(tmp_path / 'uint8_nodata.tif')
write(arr, path, compression='none', tiled=False, nodata=255)
da = open_geotiff(path)
assert np.isnan(da.values[1, 1])
assert da.values[0, 1] == 1.0
assert da.dtype == np.float64 # promoted from uint8
def test_uint16_nodata_masked(self, tmp_path):
arr = np.array([[100, 0], [200, 0]], dtype=np.uint16)
path = str(tmp_path / 'uint16_nodata.tif')
write(arr, path, compression='none', tiled=False, nodata=0)
da = open_geotiff(path)
assert np.isnan(da.values[0, 1])
assert np.isnan(da.values[1, 1])
assert da.values[0, 0] == 100.0
def test_int16_nodata_negative(self, tmp_path):
arr = np.array([[-9999, 10], [20, -9999]], dtype=np.int16)
path = str(tmp_path / 'int16_nodata.tif')
write(arr, path, compression='none', tiled=False, nodata=-9999)
da = open_geotiff(path)
assert np.isnan(da.values[0, 0])
assert np.isnan(da.values[1, 1])
assert da.values[0, 1] == 10.0
def test_integer_no_nodata_stays_integer(self, tmp_path):
"""Without nodata, integer arrays should not be promoted."""
arr = np.arange(16, dtype=np.uint16).reshape(4, 4)
path = str(tmp_path / 'no_nodata.tif')
write(arr, path, compression='none', tiled=False)
da = open_geotiff(path)
assert da.dtype == np.uint16
# -----------------------------------------------------------------------
# PackBits compression
# -----------------------------------------------------------------------
class TestPackBits:
def test_packbits_round_trip(self):
data = b'\x00' * 100 + b'\xff' * 50 + bytes(range(200))
compressed = packbits_compress(data)
decompressed = packbits_decompress(compressed)
assert decompressed == data
def test_packbits_single_byte(self):
data = b'\x42'
assert packbits_decompress(packbits_compress(data)) == data
def test_packbits_empty(self):
assert packbits_decompress(packbits_compress(b'')) == b''
def test_packbits_all_same(self):
data = b'\xAA' * 500
compressed = packbits_compress(data)
assert len(compressed) < len(data)
assert packbits_decompress(compressed) == data
def test_write_read_packbits(self, tmp_path):
arr = np.arange(64, dtype=np.float32).reshape(8, 8)
path = str(tmp_path / 'packbits.tif')
write(arr, path, compression='packbits', tiled=False)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_packbits_tiled(self, tmp_path):
arr = np.random.RandomState(42).rand(16, 16).astype(np.float32)
path = str(tmp_path / 'packbits_tiled.tif')
write(arr, path, compression='packbits', tiled=True, tile_size=8)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
# -----------------------------------------------------------------------
# ZSTD compression
# -----------------------------------------------------------------------
class TestZstd:
def test_zstd_round_trip_bytes(self):
data = b'hello zstd! ' * 1000
compressed = zstd_compress(data)
assert len(compressed) < len(data)
assert zstd_decompress(compressed) == data
def test_zstd_empty(self):
compressed = zstd_compress(b'')
assert zstd_decompress(compressed) == b''
def test_zstd_random(self):
rng = np.random.RandomState(42)
data = bytes(rng.randint(0, 256, size=5000, dtype=np.uint8))
assert zstd_decompress(zstd_compress(data)) == data
def test_write_read_zstd_stripped(self, tmp_path):
arr = np.arange(64, dtype=np.float32).reshape(8, 8)
path = str(tmp_path / 'zstd_strip.tif')
write(arr, path, compression='zstd', tiled=False)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_write_read_zstd_tiled(self, tmp_path):
arr = np.random.RandomState(99).rand(16, 16).astype(np.float32)
path = str(tmp_path / 'zstd_tiled.tif')
write(arr, path, compression='zstd', tiled=True, tile_size=8)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_zstd_uint16(self, tmp_path):
arr = np.arange(100, dtype=np.uint16).reshape(10, 10)
path = str(tmp_path / 'zstd_u16.tif')
write(arr, path, compression='zstd', tiled=False)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_zstd_with_predictor(self, tmp_path):
arr = np.arange(64, dtype=np.float32).reshape(8, 8)
path = str(tmp_path / 'zstd_pred.tif')
write(arr, path, compression='zstd', tiled=False, predictor=True)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_zstd_multiband(self, tmp_path):
arr = np.random.RandomState(7).randint(0, 256, (8, 8, 3), dtype=np.uint8)
path = str(tmp_path / 'zstd_rgb.tif')
write(arr, path, compression='zstd', tiled=False)
result, _ = read_to_array(path)
np.testing.assert_array_equal(result, arr)
def test_zstd_public_api(self, tmp_path):
arr = np.ones((4, 4), dtype=np.float32)
path = str(tmp_path / 'zstd_api.tif')
to_geotiff(arr, path, compression='zstd')
result = open_geotiff(path)
np.testing.assert_array_equal(result.values, arr)
# -----------------------------------------------------------------------
# GeoKey metadata extraction
# -----------------------------------------------------------------------
class TestGeoKeys:
def test_geographic_crs_attrs(self, tmp_path):
"""Geographic CRS files expose citation and angular units."""
from xrspatial.geotiff._geotags import GeoTransform
arr = np.ones((4, 4), dtype=np.float32)
gt = GeoTransform(-120.0, 45.0, 0.001, -0.001)
path = str(tmp_path / 'geog.tif')
write(arr, path, compression='none', tiled=False,
geo_transform=gt, crs_epsg=4326)
da = open_geotiff(path)
assert da.attrs['crs'] == 4326
assert da.attrs.get('geog_citation') is not None or da.attrs['crs'] == 4326
def test_projected_crs_attrs(self, tmp_path):
"""Projected CRS files expose linear units."""
from xrspatial.geotiff._geotags import GeoTransform
arr = np.ones((4, 4), dtype=np.float32)
gt = GeoTransform(500000.0, 4500000.0, 30.0, -30.0)
path = str(tmp_path / 'proj.tif')
write(arr, path, compression='none', tiled=False,
geo_transform=gt, crs_epsg=32610)
da = open_geotiff(path)
assert da.attrs['crs'] == 32610
def test_geoinfo_fields_from_real_file(self):
"""Verify GeoInfo fields populated from a real geographic file."""
import os
path = '../rtxpy/examples/render_demo_terrain.tif'
if not os.path.exists(path):
pytest.skip("Real test files not available")
da = open_geotiff(path)
assert da.attrs['crs'] == 4269
assert da.attrs['geog_citation'] == 'NAD83'
assert da.attrs['angular_units'] == 'degree'
assert da.attrs['semi_major_axis'] == pytest.approx(6378137.0)
assert da.attrs['inv_flattening'] == pytest.approx(298.257, rel=1e-3)
def test_geoinfo_fields_from_projected_file(self):
"""Verify projected CRS fields from a real UTM file."""
import os
path = '../rtxpy/examples/USGS_one_meter_x65y454_NY_LongIsland_Z18_2014.tif'
if not os.path.exists(path):
pytest.skip("Real test files not available")
da = open_geotiff(path)
assert da.attrs['crs'] == 26918
assert da.attrs['crs_name'] == 'NAD83 / UTM zone 18N'
assert da.attrs['geog_citation'] == 'NAD83'
assert da.attrs['linear_units'] == 'metre'
def test_no_crs_no_geokey_attrs(self, tmp_path):
"""Files without CRS don't get geokey attrs."""
arr = np.ones((4, 4), dtype=np.float32)
path = str(tmp_path / 'bare.tif')
write(arr, path, compression='none', tiled=False)
da = open_geotiff(path)
assert 'crs_name' not in da.attrs
assert 'geog_citation' not in da.attrs
assert 'angular_units' not in da.attrs
assert 'linear_units' not in da.attrs
def test_angular_unit_lookup(self):
"""Unit code -> name lookup works for known codes."""
from xrspatial.geotiff._geotags import ANGULAR_UNITS, LINEAR_UNITS
assert ANGULAR_UNITS[9102] == 'degree'
assert ANGULAR_UNITS[9101] == 'radian'
assert LINEAR_UNITS[9001] == 'metre'
assert LINEAR_UNITS[9002] == 'foot'
assert LINEAR_UNITS[9003] == 'us_survey_foot'
def test_crs_wkt_from_epsg(self, tmp_path):
"""crs_wkt is resolved from EPSG via pyproj."""
from xrspatial.geotiff._geotags import GeoTransform
arr = np.ones((4, 4), dtype=np.float32)
gt = GeoTransform(-120.0, 45.0, 0.001, -0.001)
path = str(tmp_path / 'wkt.tif')
write(arr, path, compression='none', tiled=False,
geo_transform=gt, crs_epsg=4326)
da = open_geotiff(path)
assert 'crs_wkt' in da.attrs
wkt = da.attrs['crs_wkt']
assert 'WGS 84' in wkt or '4326' in wkt
def test_write_with_wkt_string(self, tmp_path):
"""crs= accepts a WKT string and resolves to EPSG."""
arr = np.ones((4, 4), dtype=np.float32)
wkt = ('GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",'
'ELLIPSOID["WGS 84",6378137,298.257223563]],'
'CS[ellipsoidal,2],'
'AXIS["geodetic latitude (Lat)",north],'
'AXIS["geodetic longitude (Lon)",east],'
'UNIT["degree",0.0174532925199433],'
'ID["EPSG",4326]]')
path = str(tmp_path / 'wkt_in.tif')
to_geotiff(arr, path, crs=wkt, compression='none')
da = open_geotiff(path)
assert da.attrs['crs'] == 4326
def test_write_with_proj_string(self, tmp_path):
"""crs= accepts a PROJ string."""
arr = np.ones((4, 4), dtype=np.float32)
path = str(tmp_path / 'proj_in.tif')
to_geotiff(arr, path, crs='+proj=utm +zone=18 +datum=NAD83',
compression='none')
da = open_geotiff(path)
# pyproj should resolve this to EPSG:26918
assert da.attrs.get('crs') is not None
def test_crs_wkt_attr_round_trip(self, tmp_path):
"""DataArray with crs_wkt attr (no int crs) round-trips."""
wkt = ('GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",'
'ELLIPSOID["WGS 84",6378137,298.257223563]],'
'CS[ellipsoidal,2],'
'AXIS["geodetic latitude (Lat)",north],'
'AXIS["geodetic longitude (Lon)",east],'
'UNIT["degree",0.0174532925199433],'
'ID["EPSG",4326]]')
y = np.linspace(45.0, 44.0, 4)
x = np.linspace(-120.0, -119.0, 4)
da = xr.DataArray(np.ones((4, 4), dtype=np.float32),
dims=['y', 'x'], coords={'y': y, 'x': x},
attrs={'crs_wkt': wkt})
path = str(tmp_path / 'wkt_rt.tif')
to_geotiff(da, path, compression='none')
result = open_geotiff(path)
assert result.attrs['crs'] == 4326
assert 'crs_wkt' in result.attrs
def test_no_crs_no_wkt(self, tmp_path):
"""File without CRS has no crs_wkt attr."""
arr = np.ones((4, 4), dtype=np.float32)
path = str(tmp_path / 'no_wkt.tif')
write(arr, path, compression='none', tiled=False)
da = open_geotiff(path)
assert 'crs_wkt' not in da.attrs
# -----------------------------------------------------------------------
# Resolution / DPI tags
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# GDAL metadata (tag 42112)
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# Arbitrary tag preservation
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# Big-endian pixel data
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# Cloud storage (fsspec) support
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# VRT (Virtual Raster Table) support
# -----------------------------------------------------------------------
# -----------------------------------------------------------------------
# Fixes: band-first, MinIsWhite, ExtraSamples, float16, VRT write, etc.
# -----------------------------------------------------------------------
class TestFixesBatch:
def test_band_first_dataarray(self, tmp_path):
"""DataArray with (band, y, x) dims is transposed before write."""
arr = np.zeros((3, 8, 8), dtype=np.uint8)
arr[0] = 200 # red
arr[1] = 100 # green
arr[2] = 50 # blue
da = xr.DataArray(arr, dims=['band', 'y', 'x'])
path = str(tmp_path / 'band_first.tif')
to_geotiff(da, path, compression='none')
result = open_geotiff(path)
assert result.shape == (8, 8, 3)
assert result.values[0, 0, 0] == 200 # red channel
assert result.values[0, 0, 1] == 100 # green channel
def test_band_last_dataarray_unchanged(self, tmp_path):
"""DataArray with (y, x, band) dims is not transposed."""
arr = np.zeros((8, 8, 3), dtype=np.uint8)
arr[:, :, 0] = 200
da = xr.DataArray(arr, dims=['y', 'x', 'band'])
path = str(tmp_path / 'band_last.tif')
to_geotiff(da, path, compression='none')
result = open_geotiff(path)
assert result.shape == (8, 8, 3)
assert result.values[0, 0, 0] == 200
def test_min_is_white_inversion(self, tmp_path):
"""MinIsWhite (photometric=0) inverts grayscale values on read."""
from .conftest import make_minimal_tiff
import struct
# Build a minimal TIFF with photometric=0
# The conftest doesn't support photometric param, so build manually
bo = '<'
width, height = 4, 4
pixels = np.array([[0, 50, 100, 200]], dtype=np.uint8).repeat(4, axis=0)
tag_list = []
def add_short(tag, val):
tag_list.append((tag, 3, 1, struct.pack(f'{bo}H', val)))
def add_long(tag, val):
tag_list.append((tag, 4, 1, struct.pack(f'{bo}I', val)))
add_short(256, width)
add_short(257, height)
add_short(258, 8)
add_short(259, 1)
add_short(262, 0) # MinIsWhite
add_short(277, 1)
add_short(278, height)
add_long(273, 0)
add_long(279, len(pixels.tobytes()))
add_short(339, 1)
tag_list.sort(key=lambda t: t[0])
num_entries = len(tag_list)
ifd_start = 8
ifd_size = 2 + 12 * num_entries + 4
overflow_start = ifd_start + ifd_size
pixel_start = overflow_start
# Patch strip offset
for i, (tag, typ, count, raw) in enumerate(tag_list):
if tag == 273:
tag_list[i] = (tag, typ, count, struct.pack(f'{bo}I', pixel_start))
out = bytearray()
out.extend(b'II')
out.extend(struct.pack(f'{bo}H', 42))
out.extend(struct.pack(f'{bo}I', ifd_start))
out.extend(struct.pack(f'{bo}H', num_entries))
for tag, typ, count, raw in tag_list:
out.extend(struct.pack(f'{bo}HHI', tag, typ, count))
out.extend(raw.ljust(4, b'\x00'))
out.extend(struct.pack(f'{bo}I', 0))
out.extend(pixels.tobytes())
path = str(tmp_path / 'miniswhite.tif')
with open(path, 'wb') as f:
f.write(bytes(out))
from xrspatial.geotiff._reader import read_to_array
result, _ = read_to_array(path)
# MinIsWhite: 0 -> 255, 50 -> 205, 100 -> 155, 200 -> 55
assert result[0, 0] == 255
assert result[0, 1] == 205
assert result[0, 2] == 155
assert result[0, 3] == 55
def test_extra_samples_rgba(self, tmp_path):
"""RGBA write includes ExtraSamples tag."""
from xrspatial.geotiff._header import parse_header, parse_all_ifds, TAG_EXTRA_SAMPLES
arr = np.ones((4, 4, 4), dtype=np.uint8) * 128
path = str(tmp_path / 'rgba.tif')
write(arr, path, compression='none', tiled=False)
with open(path, 'rb') as f:
data = f.read()
header = parse_header(data)
ifds = parse_all_ifds(data, header)
ifd = ifds[0]
extra = ifd.entries.get(TAG_EXTRA_SAMPLES)
assert extra is not None
# Value 2 = unassociated alpha
assert extra.value == 2 or (isinstance(extra.value, tuple) and extra.value[0] == 2)
def test_float16_auto_promotion(self, tmp_path):
"""Float16 arrays are auto-promoted to float32."""
arr = np.ones((4, 4), dtype=np.float16) * 3.14
path = str(tmp_path / 'f16.tif')
to_geotiff(arr, path, compression='none')
result = open_geotiff(path)
assert result.dtype == np.float32
np.testing.assert_array_almost_equal(result.values, 3.14, decimal=2)
def test_vrt_write_and_read_back(self, tmp_path):
"""write_vrt generates a valid VRT that reads back correctly."""
from xrspatial.geotiff import write_vrt
from xrspatial.geotiff._geotags import GeoTransform
# Write two tiles with known geo transforms
left = np.arange(16, dtype=np.float32).reshape(4, 4)
right = np.arange(16, 32, dtype=np.float32).reshape(4, 4)
gt_left = GeoTransform(origin_x=0.0, origin_y=4.0,
pixel_width=1.0, pixel_height=-1.0)
gt_right = GeoTransform(origin_x=4.0, origin_y=4.0,
pixel_width=1.0, pixel_height=-1.0)
lpath = str(tmp_path / 'left.tif')
rpath = str(tmp_path / 'right.tif')
write(left, lpath, geo_transform=gt_left, compression='none', tiled=False)
write(right, rpath, geo_transform=gt_right, compression='none', tiled=False)
vrt_path = str(tmp_path / 'mosaic.vrt')
write_vrt(vrt_path, [lpath, rpath])
da = open_geotiff(vrt_path)
assert da.shape == (4, 8)
np.testing.assert_array_equal(da.values[:, :4], left)
np.testing.assert_array_equal(da.values[:, 4:], right)
def test_dask_vrt(self, tmp_path):
"""read_geotiff_dask handles VRT files."""
from xrspatial.geotiff import read_geotiff_dask
arr = np.arange(16, dtype=np.float32).reshape(4, 4)
tile_path = str(tmp_path / 'tile.tif')
write(arr, tile_path, compression='none', tiled=False)
vrt_xml = (
'<VRTDataset rasterXSize="4" rasterYSize="4">\n'
' <VRTRasterBand dataType="Float32" band="1">\n'
' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
' <SourceBand>1</SourceBand>\n'
' <SrcRect xOff="0" yOff="0" xSize="4" ySize="4"/>\n'
' <DstRect xOff="0" yOff="0" xSize="4" ySize="4"/>\n'
' </SimpleSource>\n'
' </VRTRasterBand>\n'
'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'dask.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
import dask.array as da
result = read_geotiff_dask(vrt_path, chunks=2)
assert isinstance(result.data, da.Array)
computed = result.compute()
np.testing.assert_array_equal(computed.values, arr)
class TestVRT:
def _write_tile(self, tmp_path, name, data):
"""Write a GeoTIFF tile and return its path."""
from xrspatial.geotiff._writer import write
path = str(tmp_path / name)
write(data, path, compression='none', tiled=False)
return path
def _make_mosaic_vrt(self, tmp_path, tile_paths, tile_shapes,
tile_offsets, width, height, dtype='Float32'):
"""Build a VRT XML that mosaics multiple tiles."""
lines = [
f'<VRTDataset rasterXSize="{width}" rasterYSize="{height}">',
' <GeoTransform>0.0, 1.0, 0.0, 0.0, 0.0, -1.0</GeoTransform>',
f' <VRTRasterBand dataType="{dtype}" band="1">',
]
for path, (th, tw), (yo, xo) in zip(tile_paths, tile_shapes, tile_offsets):
lines.append(' <SimpleSource>')
lines.append(f' <SourceFilename relativeToVRT="1">{os.path.basename(path)}</SourceFilename>')
lines.append(' <SourceBand>1</SourceBand>')
lines.append(f' <SrcRect xOff="0" yOff="0" xSize="{tw}" ySize="{th}"/>')
lines.append(f' <DstRect xOff="{xo}" yOff="{yo}" xSize="{tw}" ySize="{th}"/>')
lines.append(' </SimpleSource>')
lines.append(' </VRTRasterBand>')
lines.append('</VRTDataset>')
vrt_path = str(tmp_path / 'mosaic.vrt')
with open(vrt_path, 'w') as f:
f.write('\n'.join(lines))
return vrt_path
def test_single_tile_vrt(self, tmp_path):
"""VRT with one source tile reads correctly."""
arr = np.arange(16, dtype=np.float32).reshape(4, 4)
tile_path = self._write_tile(tmp_path, 'tile.tif', arr)
vrt_path = self._make_mosaic_vrt(
tmp_path,
[tile_path], [(4, 4)], [(0, 0)],
width=4, height=4,
)
da = open_geotiff(vrt_path)
np.testing.assert_array_equal(da.values, arr)
def test_2x1_mosaic(self, tmp_path):
"""VRT that tiles two images side-by-side."""
left = np.arange(16, dtype=np.float32).reshape(4, 4)
right = np.arange(16, 32, dtype=np.float32).reshape(4, 4)
lpath = self._write_tile(tmp_path, 'left.tif', left)
rpath = self._write_tile(tmp_path, 'right.tif', right)
vrt_path = self._make_mosaic_vrt(
tmp_path,
[lpath, rpath], [(4, 4), (4, 4)], [(0, 0), (0, 4)],
width=8, height=4,
)
da = open_geotiff(vrt_path)
assert da.shape == (4, 8)
np.testing.assert_array_equal(da.values[:, :4], left)
np.testing.assert_array_equal(da.values[:, 4:], right)
def test_2x2_mosaic(self, tmp_path):
"""VRT that tiles four images in a 2x2 grid."""
tiles = []
paths = []
offsets = []
for r in range(2):
for c in range(2):
base = (r * 2 + c) * 16
arr = np.arange(base, base + 16, dtype=np.float32).reshape(4, 4)
name = f'tile_{r}_{c}.tif'
paths.append(self._write_tile(tmp_path, name, arr))
tiles.append(arr)
offsets.append((r * 4, c * 4))
vrt_path = self._make_mosaic_vrt(
tmp_path,
paths, [(4, 4)] * 4, offsets,
width=8, height=8,
)
da = open_geotiff(vrt_path)
assert da.shape == (8, 8)
# Check each quadrant
np.testing.assert_array_equal(da.values[0:4, 0:4], tiles[0])
np.testing.assert_array_equal(da.values[0:4, 4:8], tiles[1])
np.testing.assert_array_equal(da.values[4:8, 0:4], tiles[2])
np.testing.assert_array_equal(da.values[4:8, 4:8], tiles[3])
def test_windowed_vrt_read(self, tmp_path):
"""Windowed read of a VRT mosaic."""
left = np.arange(16, dtype=np.float32).reshape(4, 4)
right = np.arange(16, 32, dtype=np.float32).reshape(4, 4)
lpath = self._write_tile(tmp_path, 'left.tif', left)
rpath = self._write_tile(tmp_path, 'right.tif', right)
vrt_path = self._make_mosaic_vrt(
tmp_path,
[lpath, rpath], [(4, 4), (4, 4)], [(0, 0), (0, 4)],
width=8, height=4,
)
# Window spanning both tiles
da = open_geotiff(vrt_path, window=(1, 2, 3, 6))
assert da.shape == (2, 4)
expected = np.hstack([left, right])[1:3, 2:6]
np.testing.assert_array_equal(da.values, expected)
def test_vrt_with_crs(self, tmp_path):
"""VRT with SRS tag populates CRS in attrs."""
arr = np.ones((4, 4), dtype=np.float32)
tile_path = self._write_tile(tmp_path, 'tile.tif', arr)
vrt_xml = (
'<VRTDataset rasterXSize="4" rasterYSize="4">\n'
' <SRS>EPSG:4326</SRS>\n'
' <GeoTransform>-120.0, 0.001, 0.0, 45.0, 0.0, -0.001</GeoTransform>\n'
' <VRTRasterBand dataType="Float32" band="1">\n'
' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
' <SourceBand>1</SourceBand>\n'
' <SrcRect xOff="0" yOff="0" xSize="4" ySize="4"/>\n'
' <DstRect xOff="0" yOff="0" xSize="4" ySize="4"/>\n'
' </SimpleSource>\n'
' </VRTRasterBand>\n'
'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'crs.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
da = open_geotiff(vrt_path)
assert da.attrs.get('crs_wkt') == 'EPSG:4326'
assert len(da.coords['x']) == 4
assert len(da.coords['y']) == 4
def test_vrt_nodata(self, tmp_path):
"""VRT NoDataValue is stored in attrs."""
arr = np.array([[1, 2], [3, -9999]], dtype=np.float32)
tile_path = self._write_tile(tmp_path, 'tile.tif', arr)
vrt_xml = (
'<VRTDataset rasterXSize="2" rasterYSize="2">\n'
' <VRTRasterBand dataType="Float32" band="1">\n'
' <NoDataValue>-9999</NoDataValue>\n'
' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
' <SourceBand>1</SourceBand>\n'
' <SrcRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
' <DstRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
' </SimpleSource>\n'
' </VRTRasterBand>\n'
'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'nodata.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
da = open_geotiff(vrt_path)
assert da.attrs.get('nodata') == -9999.0
def test_read_vrt_function(self, tmp_path):
"""read_vrt() works directly."""
from xrspatial.geotiff import read_vrt
arr = np.arange(16, dtype=np.float32).reshape(4, 4)
tile_path = self._write_tile(tmp_path, 'tile.tif', arr)
vrt_path = self._make_mosaic_vrt(
tmp_path,
[tile_path], [(4, 4)], [(0, 0)],
width=4, height=4,
)
da = read_vrt(vrt_path)
assert da.name == 'mosaic'
np.testing.assert_array_equal(da.values, arr)
def test_vrt_parser(self):
"""VRT XML parser extracts all fields correctly."""
from xrspatial.geotiff._vrt import parse_vrt
xml = (
'<VRTDataset rasterXSize="100" rasterYSize="200">\n'
' <SRS>EPSG:32610</SRS>\n'
' <GeoTransform>500000, 30, 0, 4500000, 0, -30</GeoTransform>\n'
' <VRTRasterBand dataType="UInt16" band="1">\n'
' <NoDataValue>0</NoDataValue>\n'
' <SimpleSource>\n'
' <SourceFilename relativeToVRT="0">/data/tile.tif</SourceFilename>\n'
' <SourceBand>1</SourceBand>\n'
' <SrcRect xOff="10" yOff="20" xSize="80" ySize="160"/>\n'
' <DstRect xOff="0" yOff="0" xSize="80" ySize="160"/>\n'
' </SimpleSource>\n'
' </VRTRasterBand>\n'
'</VRTDataset>\n'
)
vrt = parse_vrt(xml)
assert vrt.width == 100
assert vrt.height == 200
assert vrt.crs_wkt == 'EPSG:32610'
assert vrt.geo_transform == (500000.0, 30.0, 0.0, 4500000.0, 0.0, -30.0)
assert len(vrt.bands) == 1
assert vrt.bands[0].dtype == np.uint16
assert vrt.bands[0].nodata == 0.0
assert len(vrt.bands[0].sources) == 1
src = vrt.bands[0].sources[0]
assert src.filename == os.path.realpath('/data/tile.tif')
assert src.src_rect.x_off == 10
def test_vrt_float64_fractional_nodata_masked(self, tmp_path):
"""VRT read masks float64 fractional nodata exactly.
Regression for the ``np.float32(src_nodata)`` hard-cast in
``_vrt.read_vrt``. A float64 source with a fractional
sentinel that is not exactly representable in float32
(e.g. -9999.1) used to miss the mask because
``np.float32(-9999.1) != np.float64(-9999.1)`` in the ``==``
comparison. The fix casts the sentinel to the source
array's own dtype.
-9999.1 is chosen over -9999.25 because the latter is
exactly representable in float32 and would not exercise
the bug.
"""
sentinel = np.float64(-9999.1)
# Sanity check the premise of the regression: the float32
# cast must not round-trip back to the float64 value.
assert np.float32(sentinel) != sentinel
arr = np.array(
[[1.0, 2.0],
[sentinel, 4.0]],
dtype=np.float64,
)
tile_path = self._write_tile(tmp_path, 'f64_nodata_1247.tif', arr)
vrt_xml = (
'<VRTDataset rasterXSize="2" rasterYSize="2">\n'
' <VRTRasterBand dataType="Float64" band="1">\n'
' <NoDataValue>-9999.1</NoDataValue>\n'
' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
' <SourceBand>1</SourceBand>\n'
' <SrcRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
' <DstRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
' </SimpleSource>\n'
' </VRTRasterBand>\n'
'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'f64_nodata_1247.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
da = open_geotiff(vrt_path)
vals = da.values
# The sentinel pixel must be NaN.
assert np.isnan(vals[1, 0]), (
f"float64 fractional nodata not masked: got {vals[1, 0]!r}")
# Other pixels untouched.
assert vals[0, 0] == 1.0
assert vals[0, 1] == 2.0
assert vals[1, 1] == 4.0
def test_vrt_pixel_is_point_no_half_pixel_shift(self, tmp_path):
"""VRT with AREA_OR_POINT=Point does not apply a half-pixel shift.
Before the fix, ``read_vrt`` always added ``(c + 0.5) * res``
to the GeoTransform origin, even when the VRT advertised
Point registration. That shifted coords by half a cell in
world space on any Point-tagged VRT.
The expected GDAL convention: when ``AREA_OR_POINT=Point``
the GeoTransform origin is already the *center* of pixel
(0, 0), so coords[0] must equal origin exactly.
"""
arr = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)
tile_path = self._write_tile(tmp_path, 'point_1247.tif', arr)
origin_x, origin_y = 100.0, 50.0
pixel_w, pixel_h = 10.0, -10.0
vrt_xml = (
f'<VRTDataset rasterXSize="2" rasterYSize="2">\n'
f' <Metadata>\n'
f' <MDI key="AREA_OR_POINT">Point</MDI>\n'
f' </Metadata>\n'
f' <GeoTransform>{origin_x}, {pixel_w}, 0.0, '
f'{origin_y}, 0.0, {pixel_h}</GeoTransform>\n'
f' <VRTRasterBand dataType="Float32" band="1">\n'
f' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
f' <SourceBand>1</SourceBand>\n'
f' <SrcRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
f' <DstRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
f' </SimpleSource>\n'
f' </VRTRasterBand>\n'
f'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'point_1247.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
da = open_geotiff(vrt_path)
# Point registration: coords[0] == origin, no 0.5*pixel shift.
assert float(da.coords['x'].values[0]) == pytest.approx(origin_x)
assert float(da.coords['y'].values[0]) == pytest.approx(origin_y)
# Adjacent cell is one full pixel away.
assert float(da.coords['x'].values[1]) == pytest.approx(
origin_x + pixel_w)
assert float(da.coords['y'].values[1]) == pytest.approx(
origin_y + pixel_h)
# Raster type is surfaced in attrs.
assert da.attrs.get('raster_type') == 'point'
def test_vrt_pixel_is_area_still_shifts(self, tmp_path):
"""Default VRT (no AREA_OR_POINT metadata) keeps the half-pixel shift.
This is the backwards-compat guard for the Point fix: Area
registration must continue to add ``0.5 * pixel`` to the
origin.
"""
arr = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)
tile_path = self._write_tile(tmp_path, 'area_1247.tif', arr)
origin_x, origin_y = 100.0, 50.0
pixel_w, pixel_h = 10.0, -10.0
vrt_xml = (
f'<VRTDataset rasterXSize="2" rasterYSize="2">\n'
f' <GeoTransform>{origin_x}, {pixel_w}, 0.0, '
f'{origin_y}, 0.0, {pixel_h}</GeoTransform>\n'
f' <VRTRasterBand dataType="Float32" band="1">\n'
f' <SimpleSource>\n'
f' <SourceFilename relativeToVRT="1">{os.path.basename(tile_path)}</SourceFilename>\n'
f' <SourceBand>1</SourceBand>\n'
f' <SrcRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
f' <DstRect xOff="0" yOff="0" xSize="2" ySize="2"/>\n'
f' </SimpleSource>\n'
f' </VRTRasterBand>\n'
f'</VRTDataset>\n'
)
vrt_path = str(tmp_path / 'area_1247.vrt')
with open(vrt_path, 'w') as f:
f.write(vrt_xml)
da = open_geotiff(vrt_path)
# Area registration: coords[0] == origin + 0.5 * pixel.
assert float(da.coords['x'].values[0]) == pytest.approx(
origin_x + 0.5 * pixel_w)
assert float(da.coords['y'].values[0]) == pytest.approx(
origin_y + 0.5 * pixel_h)
# No raster_type attr when Area (default).
assert da.attrs.get('raster_type') != 'point'
class TestCloudStorage:
def test_cloud_scheme_detection(self):
"""Cloud URI schemes are detected correctly."""
from xrspatial.geotiff._reader import _is_fsspec_uri
assert _is_fsspec_uri('s3://bucket/key.tif')
assert _is_fsspec_uri('gs://bucket/key.tif')
assert _is_fsspec_uri('az://container/blob.tif')
assert _is_fsspec_uri('abfs://container/blob.tif')
assert _is_fsspec_uri('memory:///test.tif')
assert not _is_fsspec_uri('/local/path.tif')
assert not _is_fsspec_uri('http://example.com/file.tif')
assert not _is_fsspec_uri('relative/path.tif')
def test_memory_filesystem_read_write(self, tmp_path):
"""Round-trip through fsspec's in-memory filesystem."""
import fsspec
arr = np.arange(16, dtype=np.float32).reshape(4, 4)
# Write to memory filesystem via fsspec
from xrspatial.geotiff._writer import write, _write_bytes
from xrspatial.geotiff._writer import _assemble_tiff, _write_stripped