Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions ceos_alos2/sar_image/caching/encoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ def encode_datetime(obj):


def encode_array(obj):
# If obj is a list or lacks a dtype, convert to numpy array

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can be simplified by extending Variable.__post_init__ with:

if isinstance(self.data, list):
    super().__setattr__("data", np.array(self.data))

Even better would be to do this immediately after parsing because that would help us use the byte structure to determine a dtype, and thus avoid platform-specific behavior (e.g. windows will choose 32-bit dtypes instead of 64-bit dtypes by default). I haven't had time to look into what it would take to do that, but in the meantime we could do

if isinstance(self.data, list):
    super().__setattr__("data", np.array(self.data, dtype=infer_dtype(self.data)))

and then define infer_dtype as something like

def infer_dtype(x):
    match x:
        case np.ndarray() | np.generic():
            return x.dtype
        case list([int()]):
            return np.int64
        case list([float()]):
           return np.float64
        case list([str()]):
            return np.dtypes.StringDType
        case _:
            return None

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I implemented something very close to what you propose and it is working.
let me know if you prefer to for for the match / case syntax.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a strong attachment to the match / case syntax, but I do believe that the pattern matching is more readable than the chain of comparisons

if isinstance(obj, list):
obj = np.array(obj)
elif not hasattr(obj, "dtype"):
# Attempt conversion for other types (e.g., tuple, scalar)
try:
obj = np.array(obj)
except Exception:
# Fallback: store as a raw list (but this may break later)
return {
"__type__": "array",
"dtype": "object",
"data": obj,
"encoding": {},
}

if isinstance(obj, Array):
return {
"__type__": "backend_array",
Expand Down
Loading