Coverage for /opt/conda/envs/apienv/lib/python3.10/site-packages/daiquiri/core/utils/arrayutils.py: 70%

43 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-14 02:13 +0000

1import numpy 

2from typing import Tuple, Union 

3 

4 

5def parse_slice(slice_string) -> Tuple[Union[slice, int], ...]: 

6 """Parse a slicing sequence and return an associated tuple. 

7 

8 It supports a sequence of `...`, `:`, and integers separated by a coma. 

9 """ 

10 

11 def str_to_slice(string): 

12 if string == "...": 

13 return Ellipsis 

14 elif ":" in string: 

15 if string == ":": 

16 return slice(None) 

17 else: 

18 

19 def get_value(my_str): 

20 if my_str in ("", None): 

21 return None 

22 else: 

23 return int(my_str) 

24 

25 sss = string.split(":") 

26 start = get_value(sss[0]) 

27 stop = get_value(sss[1] if len(sss) > 1 else None) 

28 step = get_value(sss[2] if len(sss) > 2 else None) 

29 return slice(start, stop, step) 

30 else: 

31 return int(string) 

32 

33 if slice_string == "": 

34 raise ValueError("An empty slice is not valid") 

35 

36 tokens = slice_string.split(",") 

37 data_slice = [] 

38 for t in tokens: 

39 try: 

40 data_slice.append(str_to_slice(t)) 

41 except ValueError: 

42 raise ValueError("'%s' is not a valid slicing" % t) 

43 return tuple(data_slice) 

44 

45 

46def to_safe_js_dtype(dtype: numpy.dtype) -> numpy.dtype: 

47 """Convert dtype to a dtype supported by js-numpy-parser. 

48 See https://github.com/ludwigschubert/js-numpy-parser 

49 

50 raises: 

51 ValueError: For unsupported array dtype 

52 """ 

53 if dtype.kind not in ("f", "i", "u"): 

54 raise ValueError("Unsupported array type") 

55 

56 # Convert to little endian 

57 result = dtype.newbyteorder("<") 

58 

59 if result.kind == "i" and result.itemsize > 4: 

60 return numpy.dtype("<i4") # int64 -> int32 

61 

62 if result.kind == "u" and result.itemsize > 4: 

63 return numpy.dtype("<u4") # uint64 -> uint32 

64 

65 if result.kind == "f": 

66 if result.itemsize < 4: 

67 return numpy.dtype("<f4") 

68 if result.itemsize > 8: 

69 return numpy.dtype("<f8") 

70 

71 return result