|
| 1 | +"""Source-data filtering helpers for multi-variable regression.""" |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import pandas as pd |
| 5 | + |
| 6 | +from .models import OutlierFilteringDiagnostics |
| 7 | + |
| 8 | +MINIMUM_RETAINED_FRACTION = 0.50 |
| 9 | +MINIMUM_RETAINED_ROWS = 30 |
| 10 | +SOLAR_REFERENCE_NAMES = ("solarPowerGeneration", "solarRadiation") |
| 11 | + |
| 12 | + |
| 13 | +def _solar_reference_column(frame: pd.DataFrame) -> str | None: |
| 14 | + for name in SOLAR_REFERENCE_NAMES: |
| 15 | + if name in frame.columns: |
| 16 | + return name |
| 17 | + |
| 18 | + for column in frame.columns: |
| 19 | + lower = column.lower() |
| 20 | + if "solar" in lower and ("generation" in lower or "radiation" in lower): |
| 21 | + return column |
| 22 | + |
| 23 | + return None |
| 24 | + |
| 25 | + |
| 26 | +def _is_solar_production_model(dependent_variable: str, frame: pd.DataFrame) -> bool: |
| 27 | + dependent = dependent_variable.lower() |
| 28 | + if "solarphotovoltaic" in dependent: |
| 29 | + return True |
| 30 | + if "solar" in dependent and "production" in dependent: |
| 31 | + return True |
| 32 | + return "production" in dependent and _solar_reference_column(frame) is not None |
| 33 | + |
| 34 | + |
| 35 | +def _positive_reference_threshold(series: pd.Series) -> float: |
| 36 | + positive = series[series > 0] |
| 37 | + if positive.empty: |
| 38 | + return 0.0 |
| 39 | + return max(float(positive.median()) * 0.10, 0.05) |
| 40 | + |
| 41 | + |
| 42 | +def _robust_ratio_outlier_mask(ratio: pd.Series) -> pd.Series: |
| 43 | + if len(ratio) < MINIMUM_RETAINED_ROWS: |
| 44 | + return pd.Series(False, index=ratio.index) |
| 45 | + |
| 46 | + median = float(ratio.median()) |
| 47 | + mad = float((ratio - median).abs().median()) |
| 48 | + if not np.isfinite(mad) or mad <= 0: |
| 49 | + q1 = float(ratio.quantile(0.25)) |
| 50 | + q3 = float(ratio.quantile(0.75)) |
| 51 | + iqr = q3 - q1 |
| 52 | + if not np.isfinite(iqr) or iqr <= 0: |
| 53 | + return pd.Series(False, index=ratio.index) |
| 54 | + return (ratio < q1 - 3.0 * iqr) | (ratio > q3 + 3.0 * iqr) |
| 55 | + |
| 56 | + robust_z = 0.6745 * (ratio - median).abs() / mad |
| 57 | + return robust_z > 4.5 |
| 58 | + |
| 59 | + |
| 60 | +def clean_regression_frame( |
| 61 | + frame: pd.DataFrame, |
| 62 | + dependent_variable: str, |
| 63 | +) -> tuple[pd.DataFrame, OutlierFilteringDiagnostics]: |
| 64 | + """Remove obvious bad source observations before fitting a regression model.""" |
| 65 | + |
| 66 | + original_count = len(frame) |
| 67 | + diagnostics = OutlierFilteringDiagnostics( |
| 68 | + originalObservationCount=original_count, |
| 69 | + retainedObservationCount=original_count, |
| 70 | + removedObservationCount=0, |
| 71 | + applied=False, |
| 72 | + ) |
| 73 | + |
| 74 | + if original_count == 0 or dependent_variable not in frame.columns: |
| 75 | + diagnostics.reason = "empty frame or missing dependent variable" |
| 76 | + return frame, diagnostics |
| 77 | + |
| 78 | + numeric_frame = frame.apply(pd.to_numeric, errors="coerce") |
| 79 | + keep = pd.Series(True, index=numeric_frame.index) |
| 80 | + |
| 81 | + finite_mask = np.isfinite(numeric_frame).all(axis=1) |
| 82 | + diagnostics.removed_non_finite_count = int((keep & ~finite_mask).sum()) |
| 83 | + keep &= finite_mask |
| 84 | + |
| 85 | + if not _is_solar_production_model(dependent_variable, numeric_frame): |
| 86 | + cleaned = numeric_frame.loc[keep].copy() |
| 87 | + diagnostics.retained_observation_count = len(cleaned) |
| 88 | + diagnostics.removed_observation_count = original_count - len(cleaned) |
| 89 | + diagnostics.applied = diagnostics.removed_observation_count > 0 |
| 90 | + diagnostics.reason = "generic non-finite filtering only" |
| 91 | + return cleaned, diagnostics |
| 92 | + |
| 93 | + y = numeric_frame[dependent_variable] |
| 94 | + negative_mask = y < 0 |
| 95 | + diagnostics.removed_negative_count = int((keep & negative_mask).sum()) |
| 96 | + keep &= ~negative_mask |
| 97 | + |
| 98 | + solar_column = _solar_reference_column(numeric_frame) |
| 99 | + if solar_column is not None: |
| 100 | + solar_reference = numeric_frame[solar_column] |
| 101 | + solar_threshold = _positive_reference_threshold(solar_reference[keep]) |
| 102 | + |
| 103 | + zero_with_solar_mask = (y <= 0) & (solar_reference > solar_threshold) |
| 104 | + diagnostics.removed_zero_with_solar_count = int((keep & zero_with_solar_mask).sum()) |
| 105 | + keep &= ~zero_with_solar_mask |
| 106 | + |
| 107 | + ratio_candidates = keep & (y > 0) & (solar_reference > solar_threshold) |
| 108 | + ratios = y[ratio_candidates] / solar_reference[ratio_candidates] |
| 109 | + ratio_outliers = _robust_ratio_outlier_mask(ratios) |
| 110 | + diagnostics.removed_ratio_outlier_count = int(ratio_outliers.sum()) |
| 111 | + keep.loc[ratio_outliers[ratio_outliers].index] = False |
| 112 | + |
| 113 | + cleaned = numeric_frame.loc[keep].copy() |
| 114 | + retained_count = len(cleaned) |
| 115 | + removed_count = original_count - retained_count |
| 116 | + |
| 117 | + if retained_count < MINIMUM_RETAINED_ROWS: |
| 118 | + diagnostics.reason = "too few observations retained after filtering" |
| 119 | + return numeric_frame, diagnostics |
| 120 | + |
| 121 | + if retained_count / original_count < MINIMUM_RETAINED_FRACTION: |
| 122 | + diagnostics.reason = "too much source data would be removed" |
| 123 | + return numeric_frame, diagnostics |
| 124 | + |
| 125 | + diagnostics.retained_observation_count = retained_count |
| 126 | + diagnostics.removed_observation_count = removed_count |
| 127 | + diagnostics.applied = removed_count > 0 |
| 128 | + diagnostics.reason = "solar production source-data filtering" |
| 129 | + return cleaned, diagnostics |
0 commit comments