File size: 8,476 Bytes
78c4d08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
"""Validation functions for ALICE Engine training data (ISO 5259).

ISO Compliance:
- ISO/IEC 5259:2024 - Data Quality for ML (Lineage, Validation)
- ISO/IEC 42001:2023 - AI Management System
"""

from typing import Any

import pandas as pd
import pandera as pa

from schemas.training_constants import (
    ECHIQUIER_JEUNES_HIGH_BOARDS,
    ECHIQUIER_MIN,
    ELO_MAX_N4_PLUS,
    MAX_SAMPLE_VALUES,
    NIVEAU_HIERARCHY_MAX,
    NIVEAU_N4,
    VALID_GAME_SCORES_ADULTES,
    VALID_GAME_SCORES_JEUNES_HIGH,
    VALID_GAME_SCORES_JEUNES_LOW,
)
from schemas.training_types import (
    DataLineage,
    ErrorSeverity,
    QualityMetrics,
    ValidationError,
    ValidationReport,
)


def validate_training_data(
    df: pd.DataFrame,
    strict: bool = False,
    lazy: bool = True,
) -> pa.errors.SchemaErrors | None:
    """Validate training DataFrame against FFE regulatory schema.

    Args:
    ----
        df: DataFrame to validate
        strict: Use strict FFE constraints
        lazy: If True, collect all errors; if False, fail on first error

    Returns:
    -------
        None if valid, SchemaErrors if invalid (when lazy=True)

    """
    from schemas.training_schemas import TrainingSchemaPermissive, TrainingSchemaStrict

    schema = TrainingSchemaStrict if strict else TrainingSchemaPermissive
    try:
        schema.validate(df, lazy=lazy)
        return None
    except pa.errors.SchemaErrors as err:
        return err


def validate_with_report(
    df: pd.DataFrame,
    source_path: str = "unknown",
    strict: bool = False,
) -> ValidationReport:
    """Validate DataFrame and return ISO 5259 compliant report.

    Args:
    ----
        df: DataFrame to validate
        source_path: Path to source file for lineage
        strict: Use strict FFE constraints

    Returns:
    -------
        ValidationReport with lineage, metrics, and errors

    """
    from schemas.training_schemas import TrainingSchemaPermissive, TrainingSchemaStrict

    lineage = DataLineage.from_dataframe(df, source_path)
    schema = TrainingSchemaStrict if strict else TrainingSchemaPermissive

    is_valid, raw_errors = _run_schema_validation(schema, df)
    aggregated_errors = _aggregate_errors(raw_errors)
    metrics = _compute_quality_metrics(df, aggregated_errors)

    return ValidationReport(
        lineage=lineage,
        metrics=metrics,
        errors=aggregated_errors,
        is_valid=is_valid,
        schema_mode="strict" if strict else "permissive",
    )


def _run_schema_validation(
    schema: pa.DataFrameSchema, df: pd.DataFrame
) -> tuple[bool, list[ValidationError]]:
    """Run schema validation and parse errors into structured format."""
    try:
        schema.validate(df, lazy=True)
        return True, []
    except pa.errors.SchemaErrors as err:
        errors = []
        for _, row in err.failure_cases.iterrows():
            severity = _classify_error_severity(row["check"], row["column"])
            errors.append(
                ValidationError(
                    column=str(row["column"]) if pd.notna(row["column"]) else "schema",
                    check=str(row["check"]),
                    failure_count=1,
                    severity=severity,
                    sample_values=[row.get("failure_case")],
                    recommendation=_get_recommendation(row["check"]),
                )
            )
        return False, errors


def _compute_quality_metrics(df: pd.DataFrame, errors: list[ValidationError]) -> QualityMetrics:
    """Compute quality metrics from validation errors."""
    error_rows = sum(e.failure_count for e in errors)
    valid_rows = max(0, len(df) - error_rows)
    severity_counts = _count_by_severity(errors)

    return QualityMetrics(
        total_rows=len(df),
        valid_rows=valid_rows,
        null_percentages={col: df[col].isna().mean() for col in df.columns},
        validation_rate=valid_rows / len(df) if len(df) > 0 else 1.0,
        **severity_counts,
    )


def _count_by_severity(errors: list[ValidationError]) -> dict[str, int]:
    """Count errors by severity level."""
    counts = dict.fromkeys(ErrorSeverity, 0)
    for e in errors:
        counts[e.severity] += 1
    return {
        "critical_errors": counts[ErrorSeverity.CRITICAL],
        "high_errors": counts[ErrorSeverity.HIGH],
        "medium_errors": counts[ErrorSeverity.MEDIUM],
        "warnings": counts[ErrorSeverity.WARNING],
    }


_CRITICAL_COLUMNS = frozenset({"resultat_blanc", "resultat_noir", "blanc_elo", "noir_elo"})
_SEVERITY_KEYWORDS: list[tuple[frozenset[str], ErrorSeverity]] = [
    (frozenset({"dtype", "coerce"}), ErrorSeverity.CRITICAL),
    (frozenset({"diff_elo", "equipe", "resultat"}), ErrorSeverity.HIGH),
    (frozenset({"niveau", "competition"}), ErrorSeverity.MEDIUM),
]


def _classify_error_severity(check: str, column: str) -> ErrorSeverity:
    """Classify error severity based on check type."""
    if column in _CRITICAL_COLUMNS:
        return ErrorSeverity.CRITICAL
    check_str = str(check).lower()
    for keywords, severity in _SEVERITY_KEYWORDS:
        if any(k in check_str for k in keywords):
            return severity
    return ErrorSeverity.WARNING


def _get_recommendation(check: str) -> str:
    """Get remediation recommendation for check failure."""
    check_str = str(check).lower()

    if "diff_elo" in check_str:
        return "Recalculate diff_elo as blanc_elo - noir_elo"
    if "equipe" in check_str:
        return "Verify player team assignment matches match teams"
    if "resultat" in check_str:
        return "Check game result encoding matches FFE regulations"
    if "elo" in check_str:
        return "Verify Elo rating is within valid range [799, 2900]"
    if "niveau" in check_str:
        return "Check competition level encoding"

    return "Review data against FFE regulations"


def _aggregate_errors(errors: list[ValidationError]) -> list[ValidationError]:
    """Aggregate errors by column and check."""
    aggregated: dict[tuple[str, str], ValidationError] = {}

    for error in errors:
        key = (error.column, error.check)
        if key in aggregated:
            aggregated[key].failure_count += 1
            if len(aggregated[key].sample_values) < MAX_SAMPLE_VALUES:
                aggregated[key].sample_values.extend(error.sample_values)
        else:
            aggregated[key] = ValidationError(
                column=error.column,
                check=error.check,
                failure_count=1,
                severity=error.severity,
                sample_values=error.sample_values[:5],
                recommendation=error.recommendation,
            )

    return list(aggregated.values())


# =============================================================================
# HELPER FUNCTIONS
# =============================================================================


def get_expected_score_range(type_competition: str, echiquier: int) -> list[float]:
    """Get valid score range based on competition type and board number."""
    if type_competition == "national_jeunes":
        if ECHIQUIER_MIN <= echiquier <= ECHIQUIER_JEUNES_HIGH_BOARDS:
            return VALID_GAME_SCORES_JEUNES_HIGH  # victoire=2 for boards 1-6
        return VALID_GAME_SCORES_JEUNES_LOW  # echiquiers 7-8: victoire=1
    elif type_competition == "scolaire":
        return VALID_GAME_SCORES_JEUNES_LOW
    return VALID_GAME_SCORES_ADULTES  # FIDE standard


def is_valid_niveau_for_elo(niveau: int, elo: int) -> bool:
    """Check if Elo is valid for given competition level.

    A02 Art. 3.7.j: Elo > 2400 interdit en N4 et divisions inferieures.
    """
    if niveau >= NIVEAU_N4 and niveau <= NIVEAU_HIERARCHY_MAX and elo > ELO_MAX_N4_PLUS:
        return False
    return True


def compute_quality_summary(df: pd.DataFrame) -> dict[str, Any]:
    """Compute data quality summary for monitoring.

    Returns dict with key metrics for dashboards/logging.
    """
    return {
        "row_count": len(df),
        "column_count": len(df.columns),
        "null_percentage": df.isna().mean().mean() * 100,
        "duplicate_rows": df.duplicated().sum(),
        "saison_range": [int(df["saison"].min()), int(df["saison"].max())],
        "elo_range": [
            int(min(df["blanc_elo"].min(), df["noir_elo"].min())),
            int(max(df["blanc_elo"].max(), df["noir_elo"].max())),
        ],
        "competition_types": df["type_competition"].unique().tolist(),
    }