plotly / plotly/plotly.py

`PlotlyJSONEncoder` always casts values to float64 due to using `tolist()`

Abierto
#3,232 5 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

feature P3
Lenguaje dominante
Python
Estrellas
18.8k
Forks
2.8k
Merge medio
16 h 26 min
PR fusionados (30 d)
21

Descripción

Regarding the numpy floating point precision and that PlotlyJSONEncoder always casts those to float64 due to using tolist()...

This had always bugged me, as it resulted in much larger exports (i.e. html / ipynb file sizes) than necessary (when float16 or float32 is sufficient) and affected not only coordinate data, but also marker sizes, meta info, etc.

Just in case the plotly.py devs or others are interested: I had found a way to avoid this number inflation by modifying (& monkey patching) the encode_as_list method:

@staticmethod
def encode_as_list_patch(obj):
    """Attempt to use `tolist` method to convert to normal Python list."""
    if hasattr(obj, "tolist"):

        numpy = get_module("numpy")
        try:
            if isinstance(obj, numpy.ndarray) \
               and obj.dtype == numpy.float32 or obj.dtype == numpy.float16 \
               and obj.flags.contiguous:
                return [float('%s' % x) for x in obj]
        except AttributeError:
            raise NotEncodable

        return obj.tolist()
    else:
        raise NotEncodable

It's about 30-50x slower than .tolist(), but - being in the order of a few μs - still much faster than the json encoding, with the benefit of ~3x smaller exports.

I always wanted to report this, and this PR revived the topic. Could this be relevant for a new issue (especially since orjson will not become the default)?

FYI: for reference, a quick search revealed that a patch of encode_as_list was already suggested before: https://github.com/plotly/plotly.py/issues/1842#issuecomment-549401190, in the context of treating inf & NaN, which got brought up again in https://github.com/plotly/plotly.py/pull/2880#issuecomment-726860782.

Originally posted by @mherrmann3 in https://github.com/plotly/plotly.py/issues/2955#issuecomment-856651213

Guía de contribución

Abrir la guía de contribución

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.

Línea de trabajo

Comienza en packages/python/plotly/_plotly_utils/utils.py, en PlotlyJSONEncoder.encode_as_list, y luego revisa la discusión enlazada sobre el manejo de NumPy float16 y float32. Determina cómo afecta conservar su precisión a la serialización y al tamaño de exportación sin cambiar otros valores; se considera terminado cuando el comportamiento se haya validado para los tipos de NumPy relevantes y el comportamiento de codificación existente permanezca intacto.

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

Evaluación

Stack tecnológico
numpy, python
Área
data-visualization
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.