import re import datetime import pytest import numpy as np import pandas as pd import rasterio from pathlib import Path from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS from numbers import Rational from math import isclose from geopy import distance from sklearn.neighbors import NearestNeighbors FIELD_ALTITUDE = 587 NUMBER_REGEX = re.compile(r'DJI_(\d*)') @pytest.fixture def expected_low_alt_dirs(): return { "15.04.2024": {"2m"}, "26.04.2024": {"2m"}, "07.05.2024": {"2m"}, "14.05.2024": {"2m"}, "27.05.2024": {"5m", "10m"}, "06.06.2024": {"5m", "10m", "20m"}, "12.06.2024": {"5m", "10m", "20m"}, "24.06.2024": {"5m", "10m", "20m", "40m"}, "05.07.2024": {"5m", "10m", "20m", "40m"}, "10.07.2024": {"5m","10m", "40m"}, # "20m" was corrupted "16.07.2024": {"5m", "10m", "20m"}, # "40m" was corrupted "24.07.2024": {"5m", "10m", "20m", "40m"} } @pytest.fixture def expected_reconstructed_files(): return [ "dsm.tif", "result.tif", "result_Blue.tif", "result_Green.tif", "result_NIR.tif", "result_Red.tif", "result_RedEdge.tif", "index_map/GNDVI.tif", "index_map/LCI.tif", "index_map/NDRE.tif", "index_map/NDVI.tif", "index_map/OSAVI.tif", "index_map_color/GNDVI_local.tif", "index_map_color/LCI_local.tif", "index_map_color/NDRE_local.tif", "index_map_color/NDVI_local.tif", "index_map_color/OSAVI_local.tif", ] @pytest.fixture def dates(): current_dir = Path('.') return [date for date in current_dir.glob("*.2024") if date.is_dir()] @pytest.fixture def expected_coordinates(): points_from_clustering = np.array([ [42.652493119731815,23.5335933908046], [42.65268404501916,23.53364708716476], [42.65289795689655,23.53375856321839], [42.65308413122605,23.533792892720307], [42.65329313601532,23.53381995498084], [42.653500840996166,23.533874733716477], [42.653682366858234,23.53394230268199], [42.6536356321839,23.534255020114948], [42.65358158429118,23.53456061494253], [42.65336092049809,23.534458518199237], [42.65311266283525,23.53438435153257], [42.65285994058642,23.534302500771606], [42.65277988131313,23.534278771464646], [42.65269517624521,23.534265536398472], [42.65256960249042,23.53419812931035], [42.652472256704975,23.534161837164753], [42.65235443582375,23.534092082375487], [42.65221295019157,23.534681908045975], [42.652479424329506,23.534787376436785], [42.652771164750945,23.53494312452108], [42.65309712260537,23.535079702107286], [42.653323341954014,23.535162461685825], [42.65347431034482,23.535213143678156], [42.65338250383142,23.53566046743295], [42.65322460919539,23.535642157088123], [42.653034226053634,23.53558124042146], [42.65280317911878,23.535486852490422], [42.65260797605364,23.53538108333333], [42.6523800124521,23.53529239559387], [42.65213938122605,23.53520383429119], [42.65214804310344,23.534911490421457], [42.65237861302682,23.534422040229884], ]) assert points_from_clustering.shape == (32, 2) return points_from_clustering def degrees_to_decimal(degrees: Rational, minutes: Rational, seconds: Rational, direction: str): assert(isinstance(degrees, Rational)) # PIL.TiffImagePlugin.IFDRational is a subtype of Rational assert(isinstance(minutes, Rational)) assert(isinstance(seconds, Rational)) degrees = float(degrees) minutes = float(minutes) seconds = float(seconds) return (degrees + minutes / 60 + seconds / 3600) * (-1 if direction in ['W', 'S'] else 1) def get_exif_data(path): image = Image.open(path) exif_data = {} exif = image.getexif() assert exif is not None, path for tag, value in exif.items(): tag_name = TAGS.get(tag, tag) exif_data[tag_name] = value assert 'DateTime' in exif_data, path exif_data['DateTime'] = datetime.datetime.strptime(exif_data['DateTime'], '%Y:%m:%d %H:%M:%S') assert 'GPSInfo' in exif_data gps_info = {} for key,value in exif.get_ifd(0x8825).items(): decode = GPSTAGS.get(key, key) gps_info[decode] = value assert 'GPSLatitude' in gps_info, path assert 'GPSLongitude' in gps_info, path assert 'GPSAltitude' in gps_info, path for key in gps_info.keys(): if key == 'GPSLatitude': decim = degrees_to_decimal(*gps_info[key], gps_info['GPSLatitudeRef']) gps_info[key] = decim if key == 'GPSLongitude': decim = degrees_to_decimal(*gps_info[key], gps_info['GPSLongitudeRef']) gps_info[key] = decim exif_data['decoded_gps_info'] = gps_info return exif_data def test_all_dates_are_present(dates): assert len(dates) == 12 def test_lowalt_folder_integrity(dates, expected_low_alt_dirs, expected_coordinates): NUM_NEIGHBORS = 2 neighbors = NearestNeighbors(n_neighbors=NUM_NEIGHBORS).fit(expected_coordinates) points = [] for d in dates: low_alt_dirs = { lad for lad in d.glob("*m") if lad.is_dir() } assert len(low_alt_dirs) > 0 assert {n.name for n in low_alt_dirs} == expected_low_alt_dirs[d.name], d.name for low_alt_dir in low_alt_dirs: altitude = int(low_alt_dir.name[:-1]) + FIELD_ALTITUDE jpegs = list(low_alt_dir.glob("*.JPG")) jpegs.sort() # needed for consistency between windows and linux (latter may fail without it) assert len(jpegs) == 32 tifs = list(low_alt_dir.glob("*.TIF")) assert len(tifs) == 160 found_coordinates = {} for f in jpegs: ed = get_exif_data(f) assert ed['DateTime'].strftime("%d.%m.%Y") == d.name gps = ed['decoded_gps_info'] assert isclose(gps['GPSAltitude'], altitude, rel_tol=0.02), f'{low_alt_dir}, {f}' point = (gps['GPSLatitude'], gps['GPSLongitude']) indices = neighbors.kneighbors(np.expand_dims(point, 0), return_distance=False).flatten() for i in range(NUM_NEIGHBORS): nearest_point = tuple(expected_coordinates[indices[i]]) if nearest_point not in found_coordinates: found_coordinates[nearest_point] = point break else: print(( f"WARN: {f} nearest point {nearest_point} for {point} is already claimed by {found_coordinates[nearest_point]}. " f"Distance: {distance.distance(point, nearest_point).m}" ) ) assert nearest_point is not None, (f, point) assert distance.distance(point, nearest_point).m < 5.95, (f, point, nearest_point) points.append( { 'date': d.name, 'altitude': gps['GPSAltitude'], 'height': altitude - FIELD_ALTITUDE, 'file': str(f), 'geometry': point, 'x': point[0], 'y': point[1], 'ref_x': nearest_point[0], 'ref_y': nearest_point[1], } ) jpeg_number = int(NUMBER_REGEX.match(f.name).group(1)) assert jpeg_number > 0 and jpeg_number < 9999 tif_files = [f.parent / f"DJI_{jpeg_number + i:04d}.TIF" for i in range(1, 6)] for tif in tif_files: assert tif.exists(), tif tif_ed = get_exif_data(tif) assert tif_ed['DateTime'].strftime("%d.%m.%Y") == d.name, tif tif_gps = tif_ed['decoded_gps_info'] # expected that coords and altitude will be an exact match, but turned out there are slight differences assert isclose(tif_gps['GPSAltitude'], gps['GPSAltitude'], rel_tol=1e-3), tif assert isclose(tif_gps['GPSLatitude'], gps['GPSLatitude'], rel_tol=1e-7), tif assert isclose(tif_gps['GPSLongitude'], gps['GPSLongitude'], rel_tol=1e-7), tif assert len(found_coordinates) == 32, (d.name, low_alt_dir.name) pd.DataFrame(points).to_csv('points.csv', index=False) def test_aerial_folder_integrity(dates): for d in dates: aerial = d / "aerial" assert aerial.exists() jpegs = list(aerial.glob("*.JPG")) assert len(jpegs) == 36 tifs = list(aerial.glob("*.TIF")) assert len(tifs) == 180 for f in jpegs + tifs: ed = get_exif_data(f) assert ed['DateTime'].strftime("%d.%m.%Y") == d.name def test_terra_folder_integrity(dates, expected_reconstructed_files): for d in dates: for subdir in [d / "terra/default", d / "terra/lu"]: assert subdir.exists() assert subdir.is_dir() assert {f.name for f in subdir.iterdir()} == {"map", "mission.json"}, subdir assert {f.name for f in (subdir / "map").iterdir() if f.is_dir()} == {"index_map", "index_map_color" }, subdir / "map" assert {f.name for f in (subdir / "map/index_map").iterdir() if f.is_dir()} == set(), subdir / "map/index_map" assert {f.name for f in (subdir / "map/index_map_color").iterdir() if f.is_dir()} == set(), subdir / "map/index_map_color" assert (subdir / "map/SDK_Log.txt").exists() == False, subdir for f in [subdir / "map" / f for f in expected_reconstructed_files]: assert f.exists() assert f.is_file() dataset = rasterio.open(f) if not str(f).endswith("dsm.tif"): assert dataset.width >= 3532 and dataset.width <= 3682, f assert dataset.height >=3656 and dataset.height <= 3833, f if not str(f).endswith("_local.tif"): assert dataset.crs.to_epsg() == 4326, f b = dataset.bounds assert isclose(b.left, 23.533500842872694, rel_tol=1e-5), f assert isclose(b.right, 23.536542466168836, rel_tol=1e-5), f assert isclose(b.top, 42.65398844980852, rel_tol=1e-5), f assert isclose(b.bottom, 42.65168278534697, rel_tol=1e-5), f assert f.with_suffix(".prj").exists() assert f.with_suffix(".tfw").exists() if "index_map" in str(f) and "index_map_color" not in str(f): # vegetation indices should be in [-1, 1] data = dataset.read() assert np.nanmin(data) >= -1 assert np.nanmax(data) <= 1 def test_extra_folder_exists(dates): for d in dates: extra_dir = (d / "extra") assert extra_dir.exists() == False, extra_dir.absolute() # Not part of the published dataset