Coverage for packages/dqm-ml-job/src/dqm_ml_job/dataloaders/pandas.py: 91%

115 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-02 17:15 +0000

1"""Pandas data loader for reading CSV files. 

2 

3This module contains the PandasDataLoader and PandasDataSelection classes 

4for loading and iterating over CSV file data using Pandas. 

5""" 

6 

7import fnmatch 

8import logging 

9from typing import Any 

10 

11from dqm_ml_core.utils.matching import has_pattern, resolve_include_exclude, resolve_patterns 

12import pandas as pd 

13import pyarrow as pa 

14 

15# COMPATIBILITY : from typing import Any, override # When support of 3.11 will be removed 

16from typing_extensions import override 

17 

18from dqm_ml_job.dataloaders.proto import DataSelection 

19 

20logger = logging.getLogger(__name__) 

21 

22 

23def _match_wildcard(series: pd.Series, patterns: list[str]) -> pd.Series: 

24 """Return boolean mask for rows matching any wildcard pattern. 

25 

26 Args: 

27 series: Pandas Series to filter. 

28 patterns: List of patterns with fnmatch wildcards (* and ?). 

29 

30 Returns: 

31 Boolean Series indicating matches. 

32 """ 

33 mask = pd.Series(False, index=series.index) 

34 for pattern in patterns: 

35 mask = mask | series.astype(str).apply(lambda x, p=pattern: fnmatch.fnmatch(x, p)) 

36 return mask 

37 

38 

39_PANDAS_TYPE_MAP: dict[str, Any] = { 

40 "int32": "int32", 

41 "int64": "int64", 

42 "float32": "float32", 

43 "float64": "float64", 

44 "bool": "bool", 

45 "str": "string", 

46 "categorical": "category", 

47} 

48 

49 

50def _to_pyarrow_array(series: pd.Series) -> pa.Array: 

51 """Convert a pandas Series to a single, flat PyArrow array. 

52 

53 ``pa.array`` returns a ``ChunkedArray`` for pandas 3 Arrow-backed string 

54 columns that span multiple chunks. ``RecordBatch.from_arrays`` only accepts 

55 flat arrays, so combine the chunks first. 

56 """ 

57 array = pa.array(series) 

58 if isinstance(array, pa.ChunkedArray): 

59 if not array.chunks: 59 ↛ 60line 59 didn't jump to line 60 because the condition on line 59 was never true

60 return pa.array([], type=array.type) 

61 return pa.concat_arrays(array.chunks) 

62 return array 

63 

64 

65def _apply_pandas_transforms(df: pd.DataFrame, transforms: list[dict[str, Any]]) -> None: 

66 """Apply column transforms to a pandas DataFrame in-place.""" 

67 for t in transforms: 

68 col = t["column"] 

69 if col not in df.columns: 

70 continue 

71 pandas_type = _PANDAS_TYPE_MAP[t["to_type"]] 

72 if t.get("in_place", False): 

73 df[col] = df[col].astype(pandas_type) 

74 else: 

75 new_name = f"{col}_{t['to_type']}" 

76 df[new_name] = df[col].astype(pandas_type) 

77 

78 

79class PandasDataSelection(DataSelection): 

80 """A selection of data from a CSV file loaded via Pandas. 

81 

82 This class represents data loaded from a CSV file and provides 

83 an iterator over PyArrow RecordBatches. 

84 

85 Attributes: 

86 name: Name identifier for this selection. 

87 path: Path to the CSV file. 

88 data: The loaded pandas DataFrame. 

89 sample_path: List of sample path configs describing column path prefixes. 

90 transforms: List of transform configs (column cast operations). 

91 """ 

92 

93 def __init__( 

94 self, 

95 name: str, 

96 path: str, 

97 sample_path: list[dict[str, Any]] | None = None, 

98 transforms: list[dict[str, Any]] | None = None, 

99 filters_dict: dict[str, Any] | None = None, 

100 ): 

101 """Initialize a Pandas data selection. 

102 

103 Args: 

104 name: Name identifier for this selection. 

105 path: Path to the CSV file. 

106 sample_path: List of sample path configs describing column path prefixes. 

107 transforms: List of transform configs (column cast operations). 

108 filters_dict: Column-value pairs to filter rows by. 

109 """ 

110 self.name = name 

111 self.path = path 

112 self.sample_path = sample_path or [] 

113 self.transforms = transforms or [] 

114 self.filters_dict = filters_dict or {} 

115 self.data: pd.DataFrame | None = None 

116 

117 @override 

118 def bootstrap(self, columns_list: list[str] | None = None) -> None: 

119 """Load the CSV file into memory as a pandas DataFrame. 

120 

121 Args: 

122 columns_list: Unused, kept for API compatibility. 

123 """ 

124 from dqm_ml_job.dataloaders.filters import build_filter_condition 

125 

126 data = pd.read_csv(self.path, sep=",") 

127 assert isinstance(data, pd.DataFrame) 

128 self.data = data 

129 for col, val in self.filters_dict.items(): 

130 condition = build_filter_condition( 

131 col, 

132 val, 

133 wildcard_fn=lambda c, vals: _match_wildcard(data[c], vals), 

134 isin_fn=lambda c, vals: data[c].isin(vals), 

135 equal_fn=lambda c, v: data[c] == v, 

136 ) 

137 self.data = self.data[condition.reindex(self.data.index, fill_value=False)] 

138 

139 def __len__(self) -> int: 

140 return len(self.data) if self.data is not None else 0 

141 

142 @override 

143 def get_nb_batches(self) -> int: 

144 """Return the estimated number of batches (always 1 for CSV). 

145 

146 Returns: 

147 1 if data is loaded, 0 otherwise. 

148 """ 

149 return 1 if self.data is not None else 0 

150 

151 @override 

152 def __iter__(self) -> Any: 

153 if self.data is not None: 153 ↛ exitline 153 didn't return from function '__iter__' because the condition on line 153 was always true

154 df = self.data.copy() if self.transforms else self.data 

155 _apply_pandas_transforms(df, self.transforms) 

156 yield pa.RecordBatch.from_arrays( 

157 [_to_pyarrow_array(df[column]) for column in df.columns], 

158 names=[str(column) for column in df.columns], 

159 ) 

160 

161 @override 

162 def __repr__(self) -> str: 

163 return f"PandasSelection(name='{self.name}', path='{self.path}')" 

164 

165 

166class PandasDataLoader: 

167 """Data loader for CSV files using Pandas. 

168 

169 This loader reads CSV files and provides DataSelections for 

170 processing by the DQM pipeline. 

171 

172 Attributes: 

173 type: The loader type identifier ("csv"). 

174 """ 

175 

176 type: str = "csv" 

177 

178 def __init__(self, name: str, config: dict[str, Any] | None = None): 

179 """Initialize the Pandas data loader. 

180 

181 Args: 

182 name: Unique name for this loader instance. 

183 config: Configuration dictionary containing: 

184 - path: Path to CSV file (required) 

185 

186 Raises: 

187 ValueError: If required config keys are missing. 

188 """ 

189 if config is None: 189 ↛ 190line 189 didn't jump to line 190 because the condition on line 189 was never true

190 config = {} 

191 self.name = name 

192 self.path = config["path"] 

193 # Use SplitConfig model fields instead of hardcoded keys 

194 from dqm_ml_core.models.dataloaders import SplitConfig 

195 

196 split = config.get("split") 

197 self.split = SplitConfig.model_validate(split) if split else None 

198 self.split_by = self.split.by if self.split else None 

199 self.split_values = self.split.values if self.split else None 

200 filters = config.get("filters") 

201 # transform the list of dict into a dict 

202 self.filters_dict = {} 

203 if filters is not None: 

204 for item in filters: 

205 column = item["column"] 

206 self.filters_dict[column] = item["values"] 

207 self.id_column = config.get("id_column") 

208 self.sample_path = config.get("sample_path", []) 

209 self.transforms = config.get("transform", []) 

210 

211 # Storage filesystem configuration - only for S3 paths, not local paths 

212 self.filesystem = None 

213 storage_cfg = config.get("storage") 

214 if storage_cfg: 214 ↛ 216line 214 didn't jump to line 216 because the condition on line 214 was never true

215 # Use StorageConfig model to validate and access fields 

216 from dqm_ml_core.models.global_ import StorageConfig 

217 

218 storage_config = StorageConfig.model_validate(storage_cfg) 

219 

220 if storage_config.type == "s3": 

221 from dqm_ml_job.utils.s3 import get_s3_filesystem 

222 

223 self.filesystem = get_s3_filesystem(storage_config) 

224 

225 def _read_split_values(self) -> list[str]: 

226 """Read the distinct values of the split column from the CSV file. 

227 

228 Returns: 

229 List of non-null split values as strings, in discovery order. 

230 """ 

231 df = pd.read_csv(self.path, sep=",", usecols=[self.split_by]) 

232 return [str(value) for value in df[self.split_by].unique() if value is not None] 

233 

234 def _resolve_split_values(self) -> list[str]: 

235 """Resolve split values, expanding wildcards and applying exclusions. 

236 

237 Returns: 

238 The resolved list of split values. 

239 """ 

240 values = self.split_values 

241 if values is None: 

242 values = self._read_split_values() 

243 elif any(has_pattern(value) for value in values): 

244 values = resolve_patterns(values, self._read_split_values()) 

245 

246 if self.split and self.split.exclude: 

247 values = resolve_include_exclude(None, self.split.exclude, values) 

248 return values 

249 

250 def _make_selection(self, name: str, filters_dict: dict[str, Any]) -> PandasDataSelection: 

251 """Build a PandasDataSelection for this loader. 

252 

253 Args: 

254 name: Selection name. 

255 filters_dict: Filters to apply to the selection. 

256 

257 Returns: 

258 The configured selection. 

259 """ 

260 return PandasDataSelection( 

261 name=name, 

262 path=self.path, 

263 sample_path=self.sample_path, 

264 transforms=self.transforms, 

265 filters_dict=filters_dict, 

266 ) 

267 

268 def _make_split_selection(self, value: str) -> PandasDataSelection: 

269 """Build a selection for one split value. 

270 

271 Args: 

272 value: Split column value. 

273 

274 Returns: 

275 The configured selection with the split filter merged in. 

276 """ 

277 merged_filters = dict(self.filters_dict or {}) 

278 merged_filters[self.split_by] = value 

279 return self._make_selection(f"{self.name}_{value}", merged_filters) 

280 

281 def get_selections(self) -> list[DataSelection]: 

282 """Create one or more PandasDataSelection instances based on split config. 

283 

284 If split is configured, returns one selection per split value. 

285 Otherwise returns a single selection for the entire CSV file. 

286 

287 Returns: 

288 A list of DataSelection instances. 

289 """ 

290 if not self.split_by: 

291 return [self._make_selection(self.name, self.filters_dict)] 

292 

293 values = self._resolve_split_values() 

294 return [self._make_split_selection(value) for value in values]