Skip to content

Commit 4df7c47

Browse files
committed
Fix earlier attempt to fix dateconf DerivedLayers, this time with a test to prove it
1 parent f6d6d6d commit 4df7c47

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

app/routes/datasets/queries.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -726,8 +726,12 @@ def _get_date_conf_derived_layers(
726726
# TODO should these somehow be in the metadata or creation options instead of hardcoded?
727727
# 16435 is number of days from 1970-01-01 to 2015-01-01, and can be used to convert
728728
# our encoding of days since 2015 to a number that can be used generally for datetimes
729-
decode_expression = "(A + 16435).astype('datetime64[D]').astype(str)"
730-
encode_expression = "(A.astype('datetime64[D]') - 16435).astype(uint16)"
729+
decode_expression = (
730+
"(A.astype('timedelta64[D]') + np.datetime64('2015-01-01', 'D')).astype(str)"
731+
)
732+
encode_expression = (
733+
"(np.datetime64(A, 'D') - np.datetime64('2015-01-01', 'D')).astype(uint16)"
734+
)
731735
conf_encoding = RasterTable(
732736
default_meaning="not_detected",
733737
rows=[

tests_v2/unit/app/routes/datasets/test_query.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import re
2-
from typing import Tuple
2+
from typing import List, Tuple
33
from unittest.mock import Mock, patch
44
from urllib.parse import parse_qsl, urlparse
55
from uuid import UUID
@@ -22,6 +22,7 @@
2222
from app.routes.datasets.queries import (
2323
_get_data_environment,
2424
_get_data_environment_sql,
25+
_get_date_conf_derived_layers,
2526
_query_dataset_json,
2627
_query_raster,
2728
_query_raster_lambda,
@@ -856,3 +857,23 @@ async def test_get_data_environment_sql():
856857
},
857858
],
858859
}
860+
861+
862+
def test__get_date_conf_derived_layers_encode_decode_roundtrip():
863+
"""The old encode_expression failed because datetime64(A) without unit
864+
specifier breaks with modern NumPy when A is a string."""
865+
import numpy as np
866+
from numpy import uint16
867+
868+
original_date = A = "2023-01-15"
869+
870+
layers: List[DerivedLayer] = _get_date_conf_derived_layers("foo", 0)
871+
872+
for layer in layers:
873+
if layer.encode_expression:
874+
encoded = eval(
875+
layer.encode_expression, {"np": np, "uint16": uint16, "A": A}
876+
)
877+
878+
decoded = eval(layer.decode_expression, {"np": np, "A": encoded})
879+
assert decoded == original_date

0 commit comments

Comments
 (0)