Coverage for install/scipp/utils/to_string.py: 88%

25 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-04-28 01:28 +0000

1# SPDX-License-Identifier: BSD-3-Clause 

2# Copyright (c) 2023 Scipp contributors (https://github.com/scipp) 

3# @file 

4# @author Neil Vaytet 

5 

6 

7def name_with_unit(var=None, name=None, log=False): 

8 """ 

9 Make a column title or axis label with "Name [unit]". 

10 """ 

11 text = "" 

12 if name is not None: 

13 text = name 

14 elif var is not None: 

15 text = str(var.dims[-1]) 

16 

17 if log: 

18 text = "log\u2081\u2080(" + text + ")" 

19 if var is not None: 

20 unit = var.unit if var.bins is None else var.bins.constituents["data"].unit 

21 if unit is not None: 

22 text += f" [{unit}]" 

23 return text 

24 

25 

26def value_to_string(val, precision=3, max_str_len=80): 

27 """ 

28 Convert a number to a human readable string. 

29 """ 

30 if (not isinstance(val, float)) or (val == 0): 

31 raw_text = str(val) 

32 if len(raw_text) > max_str_len: 

33 text = f"{raw_text[:max_str_len-3]}..." 

34 else: 

35 text = raw_text 

36 elif (abs(val) >= 10.0 ** (precision + 1)) or ( 

37 abs(val) <= 10.0 ** (-precision - 1) 

38 ): 

39 text = "{val:.{prec}e}".format(val=val, prec=precision) 

40 else: 

41 text = "{}".format(val) 

42 if len(text) > precision + 2 + (text[0] == '-'): 

43 text = "{val:.{prec}f}".format(val=val, prec=precision) 

44 return text