Coverage for src/signalk_cli/history/_results.py: 91%

114 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-22 09:25 +0000

1"""Reshape History API /values responses into long rows, wide rows, and per-path statistics. 

2 

3Values keep their JSON types here (numbers, strings, objects, arrays); the CLI 

4writers and the Arrow conversion decide how to represent them. 

5""" 

6 

7from __future__ import annotations 

8 

9import json 

10import re 

11from typing import Any 

12 

13POSITION_RE = re.compile(r"navigation.*\.position") 

14 

15WIDE_SCALAR_COLUMNS = ["min_value", "avg_value", "max_value"] 

16_WIDE_METHOD_FOR_COLUMN = { 

17 "min_value": "min", 

18 "avg_value": "average", 

19 "max_value": "max", 

20} 

21 

22CARDINALITY_COLUMNS = [ 

23 "path", 

24 "distinct_values", 

25 "distinct_values_2_decimal_places", 

26 "nulls", 

27 "zeroes", 

28 "min", 

29 "max", 

30 "average", 

31] 

32 

33 

34def _is_number(v: object) -> bool: 

35 return isinstance(v, (int, float)) and not isinstance(v, bool) 

36 

37 

38def _cell(row: list[Any], col_idx: int) -> Any: 

39 """Value at 0-based value column col_idx (row[0] is the timestamp), or None.""" 

40 i = col_idx + 1 

41 return row[i] if i < len(row) else None 

42 

43 

44def _paths_by_column(payload: dict[str, Any]) -> list[str]: 

45 return [ 

46 col.get("path", f"col_{i}") for i, col in enumerate(payload.get("values", [])) 

47 ] 

48 

49 

50# --------------------------------------------------------------------------- 

51# Long: one row per (timestamp, path) 

52# --------------------------------------------------------------------------- 

53 

54 

55def long_rows(payload: dict[str, Any]) -> tuple[list[str], list[str], list[Any]]: 

56 """Flatten a /values response into (timestamps, paths, values), skipping nulls.""" 

57 col_paths = _paths_by_column(payload) 

58 timestamps: list[str] = [] 

59 paths: list[str] = [] 

60 values: list[Any] = [] 

61 for row in payload.get("data", []): 

62 if not row: 62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true

63 continue 

64 for i, path in enumerate(col_paths): 

65 value = _cell(row, i) 

66 if value is None: 

67 continue 

68 timestamps.append(row[0]) 

69 paths.append(path) 

70 values.append(value) 

71 return timestamps, paths, values 

72 

73 

74# --------------------------------------------------------------------------- 

75# Wide: one row per (timestamp, path) with min/avg/max or array element columns 

76# --------------------------------------------------------------------------- 

77 

78 

79def _first_value(data_rows: list[Any], col_idx: int) -> Any: 

80 for row in data_rows: 80 ↛ 85line 80 didn't jump to line 85 because the loop on line 80 didn't complete

81 if row: 81 ↛ 80line 81 didn't jump to line 80 because the condition on line 81 was always true

82 v = _cell(row, col_idx) 

83 if v is not None: 

84 return v 

85 return None 

86 

87 

88def _array_col_names(path: str, length: int) -> list[str]: 

89 if length == 2 and POSITION_RE.fullmatch(path): 

90 return ["longitude", "latitude"] 

91 return [f"value_{i}" for i in range(length)] 

92 

93 

94def wide_rows( 

95 payload: dict[str, Any], 

96) -> tuple[list[str], list[str], dict[str, list[Any]]]: 

97 """Reshape a /values response into (timestamps, paths, value_columns). 

98 

99 Scalar paths fill `min_value`/`avg_value`/`max_value`. Array paths 

100 fill one column per element: `longitude`/`latitude` for 

101 `navigation.*.position`, otherwise `value_0`, `value_1`, ... Cells 

102 that don't apply to a row's path are None, and rows where every cell is 

103 null are dropped. 

104 """ 

105 value_columns = payload.get("values", []) 

106 data_rows = payload.get("data", []) 

107 

108 path_method_idx: dict[str, dict[str, int]] = {} 

109 for i, col in enumerate(value_columns): 

110 path = col.get("path", f"col_{i}") 

111 path_method_idx.setdefault(path, {})[col.get("method", "")] = i 

112 

113 path_cols: dict[str, list[str]] = {} 

114 path_is_array: dict[str, bool] = {} 

115 for path, methods in path_method_idx.items(): 

116 sample = None 

117 for col_idx in methods.values(): 117 ↛ 121line 117 didn't jump to line 121 because the loop on line 117 didn't complete

118 sample = _first_value(data_rows, col_idx) 

119 if sample is not None: 119 ↛ 117line 119 didn't jump to line 117 because the condition on line 119 was always true

120 break 

121 path_is_array[path] = isinstance(sample, list) 

122 path_cols[path] = ( 

123 _array_col_names(path, len(sample)) 

124 if isinstance(sample, list) 

125 else WIDE_SCALAR_COLUMNS 

126 ) 

127 

128 all_cols: list[str] = [] 

129 for cols in path_cols.values(): 

130 all_cols.extend(c for c in cols if c not in all_cols) 

131 

132 timestamps: list[str] = [] 

133 paths_out: list[str] = [] 

134 out: dict[str, list[Any]] = {c: [] for c in all_cols} 

135 

136 for row in data_rows: 

137 if not row: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true

138 continue 

139 for path, methods in path_method_idx.items(): 

140 cells: dict[str, Any] = {} 

141 if path_is_array[path]: 

142 arr = next( 

143 ( 

144 v 

145 for v in (_cell(row, i) for i in methods.values()) 

146 if v is not None 

147 ), 

148 None, 

149 ) 

150 if arr is None: 150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true

151 continue 

152 cells = dict(zip(path_cols[path], arr)) 

153 else: 

154 cells = { 

155 col: _cell(row, methods[method]) if method in methods else None 

156 for col, method in _WIDE_METHOD_FOR_COLUMN.items() 

157 } 

158 if all(v is None for v in cells.values()): 

159 continue 

160 timestamps.append(row[0]) 

161 paths_out.append(path) 

162 for col in all_cols: 

163 out[col].append(cells.get(col)) 

164 

165 return timestamps, paths_out, out 

166 

167 

168# --------------------------------------------------------------------------- 

169# Cardinality 

170# --------------------------------------------------------------------------- 

171 

172 

173def _distinct_2dp(vals: list[Any]) -> int | None: 

174 if not vals: 

175 return 0 

176 if all(_is_number(v) for v in vals): 

177 return len({round(float(v), 2) for v in vals}) 

178 if isinstance(vals[0], list): 178 ↛ 182line 178 didn't jump to line 182 because the condition on line 178 was always true

179 return len( 

180 {tuple(round(x, 2) if _is_number(x) else x for x in v) for v in vals} 

181 ) 

182 return None 

183 

184 

185def cardinality(payload: dict[str, Any]) -> list[dict[str, Any]]: 

186 """Per-path statistics: distinct values, nulls, zeroes, and min/max/average. 

187 

188 Each row has the keys in `CARDINALITY_COLUMNS`. `min`, `max` and 

189 `average` are None unless every value of the path is a number; 

190 `distinct_values_2_decimal_places` is None for paths whose values are 

191 neither numbers nor arrays. 

192 """ 

193 col_paths = _paths_by_column(payload) 

194 ordered = list(dict.fromkeys(col_paths)) 

195 vals: dict[str, list[Any]] = {p: [] for p in ordered} 

196 nulls = dict.fromkeys(ordered, 0) 

197 zeroes = dict.fromkeys(ordered, 0) 

198 

199 for row in payload.get("data", []): 

200 if not row: 200 ↛ 201line 200 didn't jump to line 201 because the condition on line 200 was never true

201 continue 

202 for i, path in enumerate(col_paths): 

203 v = _cell(row, i) 

204 if v is None: 

205 nulls[path] += 1 

206 continue 

207 if _is_number(v) and v == 0: 

208 zeroes[path] += 1 

209 vals[path].append(v) 

210 

211 rows = [] 

212 for path in ordered: 

213 pv = vals[path] 

214 numeric = bool(pv) and all(_is_number(v) for v in pv) 

215 rows.append( 

216 { 

217 "path": path, 

218 "distinct_values": len( 

219 { 

220 json.dumps(v, sort_keys=True) 

221 if isinstance(v, (dict, list)) 

222 else str(v) 

223 for v in pv 

224 } 

225 ), 

226 "distinct_values_2_decimal_places": _distinct_2dp(pv), 

227 "nulls": nulls[path], 

228 "zeroes": zeroes[path], 

229 "min": min(pv) if numeric else None, 

230 "max": max(pv) if numeric else None, 

231 "average": sum(pv) / len(pv) if numeric else None, 

232 } 

233 ) 

234 return rows