plotly / plotly/plotly.py

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

オープン
#3,232 コメント 5 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

feature P3
主要言語
Python
スター
18.8k
フォーク
2.8k
平均マージ
16時間 26分
マージ済み PR(30日)
21

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

packages/python/plotly/_plotly_utils/utils.py の PlotlyJSONEncoder.encode_as_list から始め、NumPy float16 と float32 の扱いに関するリンク先の議論を確認します。他の値を変更せずにそれらの精度を保持することが、シリアライズとエクスポートサイズにどのような影響を与えるかを判断します。完了の条件は、関連する NumPy 型について動作が検証され、既存のエンコード動作が維持されることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
numpy, python
領域
data-visualization
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。