From bf38fc8b0fc475c51164368728396ff45b012b30 Mon Sep 17 00:00:00 2001 From: Simon Renblad Date: Mon, 3 Jul 2023 11:36:44 +0800 Subject: [PATCH] tools: refactor short_format with metadata --- artiq/tools.py | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/artiq/tools.py b/artiq/tools.py index 1c4949a23..c0c49620e 100644 --- a/artiq/tools.py +++ b/artiq/tools.py @@ -15,6 +15,7 @@ from sipyco import pyon from artiq import __version__ as artiq_version from artiq.appdirs import user_config_dir from artiq.language.environment import is_public_experiment +from artiq.language import units __all__ = ["parse_arguments", "elide", "short_format", "file_import", @@ -54,20 +55,40 @@ def elide(s, maxlen): return s -def short_format(v): +def short_format(v, metadata={}): + m = metadata + unit = m.get("unit", "") + default_scale = getattr(units, unit, 1) + scale = m.get("scale", default_scale) + precision = m.get("precision", None) if v is None: return "None" t = type(v) - if np.issubdtype(t, np.number) or np.issubdtype(t, np.bool_): - return str(v) + if np.issubdtype(t, np.number): + v_t = np.divide(v, scale) + v_str = np.format_float_positional(v_t, + precision=precision, + unique=True) + v_str += " " + unit if unit else "" + return v_str + elif np.issubdtype(t, np.bool_): + return str(v) elif np.issubdtype(t, np.unicode_): return "\"" + elide(v, 50) + "\"" - else: - r = t.__name__ - if t is list or t is dict or t is set: - r += " ({})".format(len(v)) - if t is np.ndarray: - r += " " + str(np.shape(v)) + elif t is np.ndarray: + v_t = np.divide(v, scale) + v_str = np.array2string(v_t, + max_line_width=1000, + precision=precision, + suppress_small=True, + separator=', ', + threshold=4, + edgeitems=2, + floatmode='maxprec') + v_str += " " + unit if unit else "" + return v_str + elif isinstance(v, (dict, list)): + r = t.__name__ + " ({})".format(len(v)) return r