Coverage for packages/dqm-ml-core/src/dqm_ml_core/utils/processor_runner.py: 99%

96 statements  

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

1"""Processor runner utility for executing metrics on DataFrames. 

2 

3This module contains the ProcessorRunner class that provides a high-level 

4API for running feature and metric processors directly on Pandas DataFrames. 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10from typing import Any 

11 

12import numpy as np 

13from pandas import DataFrame, Series 

14import pyarrow as pa 

15 

16from dqm_ml_core.api.gap_processor import GapProcessor 

17from dqm_ml_core.api.metrics_processor import MetricsProcessor 

18from dqm_ml_core.api.processor import Processor 

19 

20logger = logging.getLogger(__name__) 

21 

22 

23class ProcessorRunner: 

24 """ 

25 Orchestrator for executing metric processors on in-memory Pandas DataFrames. 

26 

27 This class provides a high-level API for users who want to compute metrics 

28 directly on DataFrames without using the full YAML-driven pipeline. 

29 """ 

30 

31 def __init__(self, config: dict[str, Any] | None = None) -> None: 

32 """ 

33 Initialize the runner. 

34 

35 Args: 

36 config: Optional configuration for metric default behaviors. 

37 """ 

38 self.config = config or {} 

39 

40 @staticmethod 

41 def _uniform_ndarray_dim(series: Series) -> int | None: 

42 """Return the vector length when every value is a same-shape 1-D ndarray. 

43 

44 Args: 

45 series: Pandas Series to inspect. 

46 

47 Returns: 

48 The shared vector length, or ``None`` when the column does not hold 

49 uniform-size numpy arrays. 

50 """ 

51 if series.dtype != object or series.empty: 

52 return None 

53 first = series.iloc[0] 

54 if not isinstance(first, np.ndarray): 

55 return None 

56 dim = int(first.shape[0]) 

57 if all(isinstance(value, np.ndarray) and value.shape == (dim,) for value in series): 

58 return dim 

59 return None 

60 

61 @staticmethod 

62 def _series_to_pyarrow_array(series: Series) -> pa.Array: 

63 """Convert one DataFrame column to a PyArrow array. 

64 

65 Uniform-size numpy arrays (e.g. embeddings) are converted to 

66 ``FixedSizeListArray``, which is required by processors like 

67 ``DomainGapProcessor``. 

68 

69 Args: 

70 series: Pandas Series to convert. 

71 

72 Returns: 

73 The converted PyArrow array. 

74 """ 

75 dim = ProcessorRunner._uniform_ndarray_dim(series) 

76 if dim is None: 

77 return pa.Array.from_pandas(series) 

78 flat = np.vstack(series.values).astype(np.float64) 

79 return pa.FixedSizeListArray.from_arrays(pa.array(flat.flatten().tolist()), dim) 

80 

81 @staticmethod 

82 def _df_to_record_batch(df: DataFrame) -> pa.RecordBatch: 

83 """Convert a pandas DataFrame to a pyarrow RecordBatch. 

84 

85 Handles conversion of object columns containing uniform-size numpy 

86 arrays (e.g. embeddings) to FixedSizeListArray, which is required 

87 by processors like DomainGapProcessor. 

88 

89 Args: 

90 df: DataFrame to convert. 

91 

92 Returns: 

93 A single RecordBatch containing all rows of the DataFrame. 

94 """ 

95 arrays = [ProcessorRunner._series_to_pyarrow_array(df[column]) for column in df.columns] 

96 table = pa.table(dict(zip(df.columns, arrays, strict=True))) 

97 return table.to_batches()[0] 

98 

99 def _compute_batch_level(self, df: DataFrame, processors: list[Processor]) -> tuple[dict[str, Any], dict[str, Any]]: 

100 """Compute features and batch-level metrics from non-Gap processors. 

101 

102 Returns: 

103 Tuple of (batch_features, batch_metrics) merged dicts. 

104 """ 

105 from dqm_ml_core.api.features_processor import FeaturesProcessor 

106 

107 batch = self._df_to_record_batch(df) 

108 batch_features: dict[str, Any] = {} 

109 batch_metrics: dict[str, Any] = {} 

110 

111 for metric in processors: 

112 logger.debug(f"Processing metric {metric.__class__.__name__}") 

113 if isinstance(metric, FeaturesProcessor): 

114 batch_features |= metric.compute_features(batch, prev_features=batch_features) 

115 elif isinstance(metric, MetricsProcessor): 115 ↛ 120line 115 didn't jump to line 120 because the condition on line 115 was always true

116 # select_columns returns intermediate columns for metric computation, 

117 # not final features - use only for compute_batch_metric 

118 intermediate = metric.select_columns(batch, prev_features=batch_features) 

119 

120 if isinstance(metric, MetricsProcessor): 

121 batch_metrics |= metric.compute_batch_metric(intermediate) 

122 

123 return batch_features, batch_metrics 

124 

125 def _compute_dataset_level(self, batch_metrics: dict[str, Any], processors: list[Processor]) -> dict[str, Any]: 

126 """Compute dataset-level metrics from MetricsProcessor instances.""" 

127 dataset_metrics: dict[str, Any] = {} 

128 for metric in processors: 

129 if not isinstance(metric, MetricsProcessor): 

130 continue 

131 logger.debug(f"Computing final score for {metric.__class__.__name__}") 

132 dataset_metrics |= metric.compute(batch_metrics=batch_metrics) 

133 return dataset_metrics 

134 

135 def run(self, df: DataFrame, processors: list[Processor]) -> dict[str, Any]: 

136 """ 

137 Execute the provided processors on a DataFrame. 

138 

139 Args: 

140 df: The input Pandas DataFrame. 

141 processors: List of initialized Processor instances. 

142 

143 Returns: 

144 A dictionary containing the aggregated dataset-level metrics 

145 and/or per-sample features. Features from FeaturesProcessor 

146 instances are included alongside metrics from MetricsProcessor instances. 

147 """ 

148 if df.empty or not processors: 

149 logger.warning("Empty DataFrame or no processors provided to ProcessorRunner") 

150 return {} 

151 

152 active = [p for p in processors if not isinstance(p, GapProcessor)] 

153 batch_features, batch_metrics = self._compute_batch_level(df, active) 

154 dataset_metrics = self._compute_dataset_level(batch_metrics, active) 

155 

156 # Merge features (from FeaturesProcessor) and metrics (from MetricsProcessor) 

157 result = {} 

158 result.update(batch_features) # Per-sample features 

159 result.update(dataset_metrics) # Aggregated metrics 

160 return result 

161 

162 def _compute_features(self, df: DataFrame, features: list[Processor]) -> DataFrame: 

163 """Run FeaturesProcessors on a DataFrame and return a new DataFrame with computed columns. 

164 

165 Args: 

166 df: The input DataFrame. 

167 features: List of FeaturesProcessor instances. 

168 

169 Returns: 

170 A new DataFrame with the original columns plus any new feature columns. 

171 """ 

172 result = self.run(df, features) 

173 if not result: 

174 return df 

175 out = df.copy() 

176 for col, values in result.items(): 

177 out[col] = values 

178 return out 

179 

180 def run_gap( 

181 self, 

182 source_df: DataFrame, 

183 target_df: DataFrame, 

184 processor: GapProcessor, 

185 features: list[Processor] | None = None, 

186 source_selection_name: str = "source", 

187 target_selection_name: str = "target", 

188 ) -> dict[str, Any]: 

189 """ 

190 Execute a GapProcessor on two DataFrames and compute the domain gap. 

191 

192 This method handles the two-dataset execution pattern required by GapProcessor: 

193 1. Optionally compute features (e.g. embeddings) on both DataFrames 

194 2. Process source DataFrame to compute source statistics 

195 3. Process target DataFrame to compute target statistics 

196 4. Compute the domain gap delta between source and target 

197 

198 Args: 

199 source_df: The source dataset DataFrame. 

200 target_df: The target dataset DataFrame. 

201 processor: An initialized GapProcessor instance. 

202 features: Optional list of FeaturesProcessor instances to run on both 

203 DataFrames before computing the gap. For example, pass an 

204 ImageEmbeddingProcessor to compute embeddings from raw images. 

205 source_selection_name: Name for the source selection (default: "source"). 

206 target_selection_name: Name for the target selection (default: "target"). 

207 

208 Returns: 

209 A dictionary containing: 

210 - {metric_name}: The domain gap metric value 

211 - "selection_source": Name of the source selection 

212 - "selection_target": Name of the target selection 

213 """ 

214 if source_df.empty or target_df.empty: 

215 logger.warning("Empty DataFrame provided to run_gap") 

216 return {} 

217 

218 # Compute features if provided (e.g. embeddings from raw images) 

219 if features: 

220 source_df = self._compute_features(source_df, features) 

221 target_df = self._compute_features(target_df, features) 

222 

223 # Process source dataset 

224 source_batch = self._df_to_record_batch(source_df) 

225 source_features = processor.select_features(source_batch, prev_features={}) 

226 source_batch_metrics = processor.compute_batch_metric(source_features) 

227 source_stats = processor.compute(source_batch_metrics) 

228 

229 # Process target dataset 

230 target_batch = self._df_to_record_batch(target_df) 

231 target_features = processor.select_features(target_batch, prev_features={}) 

232 target_batch_metrics = processor.compute_batch_metric(target_features) 

233 target_stats = processor.compute(target_batch_metrics) 

234 

235 # Compute domain gap delta 

236 result = processor.compute_delta(source_stats, target_stats) 

237 

238 # Add selection metadata 

239 result["selection_source"] = pa.array([source_selection_name]) 

240 result["selection_target"] = pa.array([target_selection_name]) 

241 

242 return result