|
3 | 3 | import sys
|
4 | 4 | import re
|
5 | 5 | from functools import reduce
|
| 6 | +import base64 |
6 | 7 |
|
7 | 8 | from _plotly_utils.optional_imports import get_module
|
8 | 9 | from _plotly_utils.basevalidators import ImageUriValidator
|
| 10 | +from _plotly_future_ import _future_flags |
9 | 11 |
|
10 | 12 |
|
11 | 13 | PY36_OR_LATER = sys.version_info >= (3, 6)
|
| 14 | +b64_encoding = "b64_encoding" in _future_flags |
12 | 15 |
|
13 | 16 |
|
14 | 17 | def cumsum(x):
|
@@ -182,7 +185,9 @@ def encode_as_numpy(obj):
|
182 | 185 | if not numpy:
|
183 | 186 | raise NotEncodable
|
184 | 187 |
|
185 |
| - if obj is numpy.ma.core.masked: |
| 188 | + if isinstance(obj, numpy.ndarray) and b64_encoding: |
| 189 | + return b64_encode_numpy(obj) |
| 190 | + elif obj is numpy.ma.core.masked: |
186 | 191 | return float("nan")
|
187 | 192 | else:
|
188 | 193 | raise NotEncodable
|
@@ -227,6 +232,25 @@ class NotEncodable(Exception):
|
227 | 232 | pass
|
228 | 233 |
|
229 | 234 |
|
| 235 | +def b64_encode_numpy(obj): |
| 236 | + # Convert 1D numpy arrays with numeric types to memoryviews with |
| 237 | + # datatype and shape metadata. |
| 238 | + if obj.dtype.kind in ["u", "i", "f"]: |
| 239 | + # We have a numpy array that is compatible with JavaScript typed |
| 240 | + # arrays |
| 241 | + buffer = base64.b64encode(memoryview( |
| 242 | + obj.ravel(order="C")) |
| 243 | + ).decode("utf-8") |
| 244 | + return { |
| 245 | + "bvals": buffer, |
| 246 | + "dtype": str(obj.dtype), |
| 247 | + "shape": obj.shape |
| 248 | + } |
| 249 | + else: |
| 250 | + # Convert all other numpy arrays to lists |
| 251 | + return obj.tolist() |
| 252 | + |
| 253 | + |
230 | 254 | def iso_to_plotly_time_string(iso_string):
|
231 | 255 | """Remove timezone info and replace 'T' delimeter with ' ' (ws)."""
|
232 | 256 | # make sure we don't send timezone info to plotly
|
|
0 commit comments