Feat: Add a mechanism for Serializing any index - `to_zarr` on a big RangeIndex causes a crash

Abierto
#11,034 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
35/100
Tipo de issue
Nueva funcionalidad
Claridad
Necesita aclaración
Estado de actividad
Estancado
Stack tecnológico
python
Área
data

Línea de trabajo

Comienza reproduciendo el comportamiento con RangeIndex.arange, Coordinates.from_xindex, to_zarr y open_zarr usando los ejemplos del issue. Sigue la ruta de serialización del índice y determina cómo deberían funcionar la restauración de índices personalizados y un fallback controlado; se considera terminado cuando se conservan los índices disponibles sin materializar un array de coordenadas prohibitivamente grande.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

enhancement
Is your feature request related to a problem?

As I understand it the current way that indexes are serialized is by writing the full contents of their coords to disk. This has some admirable properties in terms of interoperability with other tools and backcompatibility, but also some pitfalls.

1. Places burden on user's of xarray to remember re-install the index after loading + no mechanism for remembering what coords had set_xindex called on them.

A simple example:

import xarray as xr

ds = xr.Dataset(
    {"data": ("time", [0, 1, 2, 3])},
    coords={"time": [0.1, 0.2, 0.3, 0.4], "time_metadata": ("time", [10, 15, 20, 25])},
).set_xindex("time_metadata")
ds


ds.to_zarr("extra_index.zarr", mode="w")
roundtripped = xr.open_zarr("extra_index.zarr")

assert len(ds.xindexes) == len(roundtripped.xindexes)

fails with an assertion error.

2. For lazy indexes it's possible to crash your computer or run out of disk space with a simple to_zarr

For example, this snippet will create a 120 MiB zarr store when

import xarray as xr
step="1e-5"
idx1 = xr.indexes.RangeIndex.arange(0.0, 1000.0, float(step), dim="x")
ds1 = xr.Dataset(coords=xr.Coordinates.from_xindex(idx1))

ds1.to_zarr(f"float_range_step_{step}.zarr")

and I had to restart my laptop to get it unfrozen after running the below (offending line commented out) with the step value from the example (https://xarray-indexes.readthedocs.io/builtin/range.html)

import xarray as xr
step="1e-9"
idx1 = xr.indexes.RangeIndex.arange(0.0, 1000.0, float(step), dim="x")
ds1 = xr.Dataset(coords=xr.Coordinates.from_xindex(idx1))

# ds1.to_zarr(f"float_range_step_{step}.zarr")
Describe the solution you'd like

Allow indexes more control over how they are serialized and support a mechanism for automatically re-creating them if they are available in the current environment, with a graceful fallback.

Describe alternatives you've considered

If writing a custom index you could write your own loading function, but that would not solve the coord-bomb behavior and places more friction on the user.

Additional context

No response

Lenguaje dominante
Python
Estrellas
4.2k
Forks
1.5k
Merge medio
2 d 21 h
PR fusionados (30 d)
74

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de pydata/xarray

Todos los issues de pydata/xarray

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.