Dataset Validation References¶
A check tests one rule on one dataset and returns a CheckResult. A DatasetValidator runs a set of checks and returns a ValidationReport.
from mesqual.validation import ConstraintCheck, DatasetValidator
validator = DatasetValidator([
ConstraintCheck('Line.Constraints.capacity_up', min_value=0),
ConstraintCheck('Generator.Results.generation', min_value=0, isna_ok=False),
])
report = validator.run(dataset)
report.failed # the FAIL results
report.to_markdown('validation.md')
validation
¶
Checks on datasets that return results, and a validator that collects them in a report.
DatasetCheck
¶
Bases: ABC
Base class of a check: a rule on one dataset, run by run(dataset) -> CheckResult.
A subclass implements _run. It declares the flags it reads in FLAGS, or
overrides flags when they depend on the instance. Settings, for example
tolerances, are constructor arguments. A subclass can be a dataclass.
A subclass keeps no state between runs: run gives the same result for
the same dataset and settings.
run returns SKIP when a declared flag is accepted but not available on
the dataset (Dataset.availability). A flag with unknown availability
counts as available: only a fetch tells. A FlagUnavailableError raised in
_run also gives SKIP. A declared flag that the dataset does not accept
raises UnknownFlagError, so a typo in a flag name is an ERROR in the
validator, not a SKIP. A subclass with more needs, for example a dataset
class or a model input, overrides the hook _unmet(dataset) and calls
super()._unmet(dataset).
Examples:
>>> from mesqual.validation import CheckStatus, Comparison
>>> class PricesNotNegative(DatasetCheck):
... FLAGS = ('Node.Results.price',)
...
... def _run(self, dataset):
... prices = Comparison.long(dataset.fetch('Node.Results.price'))
... negative = prices[prices < 0].rename('price').reset_index()
... if len(negative):
... return self.result(CheckStatus.FAIL, f'{len(negative)} negative node prices.', negative)
... return self.result(CheckStatus.PASS, f'{len(prices)} node prices, none negative.')
>>> result = PricesNotNegative().run(dataset)
>>> result.status.name, result.summary
('PASS', '1328 node prices, none negative.')
Attributes:
| Name | Type | Description |
|---|---|---|
FLAGS |
tuple[FlagType, ...]
|
The flags the check reads. |
Source code in src/mesqual/validation/check.py
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 | |
run
¶
run(dataset: Dataset) -> CheckResult
Run the check on a dataset.
Returns:
| Type | Description |
|---|---|
CheckResult
|
The result. |
Raises:
| Type | Description |
|---|---|
UnknownFlagError
|
The dataset does not accept a flag of |
Source code in src/mesqual/validation/check.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
result
¶
result(status: CheckStatus, summary: str, details: DataFrame | None = None) -> CheckResult
Return a result of this check.
Source code in src/mesqual/validation/check.py
104 105 106 | |
skip
¶
skip(reason: str, details: DataFrame | None = None) -> CheckResult
Return a SKIP result with the reason.
Source code in src/mesqual/validation/check.py
108 109 110 | |
compared
¶
compared(comparison: Comparison, what: str) -> CheckResult
Return PASS or FAIL for a comparison, SKIP when it compared nothing.
The summary is '<violations> of <compared> <what>.'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comparison
|
Comparison
|
The comparison. |
required |
what
|
str
|
The noun phrase of a violation, for example |
required |
Source code in src/mesqual/validation/check.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
has_flags
classmethod
¶
Return True if every flag counts as available on the dataset (see the class docstring).
Raises:
| Type | Description |
|---|---|
UnknownFlagError
|
The dataset does not accept a flag. |
Source code in src/mesqual/validation/check.py
127 128 129 130 131 132 133 134 135 | |
Comparison
dataclass
¶
Values of two frames compared where both have a value.
Attributes:
| Name | Type | Description |
|---|---|---|
compared |
int
|
Number of compared values. |
violations |
DataFrame
|
One row per value off by more than the tolerance: the index
levels and column levels of the frames as columns (see |
Examples:
>>> actual = pd.DataFrame({'N1': [10.0, 20.0], 'N2': [30.0, 41.0]})
>>> expected = pd.DataFrame({'N1': [10.0, 20.0], 'N2': [30.0, 40.0]})
>>> comparison = Comparison.of(actual, expected, tol=0.5)
>>> comparison.compared, len(comparison.violations)
(4, 1)
Source code in src/mesqual/validation/comparison.py
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 | |
of
classmethod
¶
of(actual: DataFrame | Series, expected: DataFrame | Series, tol: float = 0.0, rel_tol: float = 0.0, empty_is_off: bool = False) -> Comparison
Compare actual with expected on the index and columns they share.
A value fits when |actual - expected| <= tol + rel_tol * max(|actual|, |expected|),
as in math.isclose. A cell with NaN on either side is not compared,
unless empty_is_off: then an empty actual cell with an expected value
is a violation.
The index levels and column levels of both sides are matched by name
when all levels on both sides have unique names; expected takes the
level order of actual. Else they are matched by position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
actual
|
DataFrame | Series
|
The values to test. |
required |
expected
|
DataFrame | Series
|
The values they must equal. |
required |
tol
|
float
|
Absolute tolerance. |
0.0
|
rel_tol
|
float
|
Relative tolerance, a share of the larger absolute value. |
0.0
|
empty_is_off
|
bool
|
Count an empty actual cell with an expected value as a violation. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The level names of both sides differ (all levels named),
or the number of levels differs (matched by position); a level
is named |
Source code in src/mesqual/validation/comparison.py
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 | |
combine
classmethod
¶
combine(parts: Mapping[str, Comparison], label: str) -> Comparison
Join comparisons into one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parts
|
Mapping[str, Comparison]
|
The comparisons by key. |
required |
label
|
str
|
Name of the first column of the violations, which holds the key of their part. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/mesqual/validation/comparison.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
long
classmethod
¶
long(values: DataFrame | Series) -> Series
Return the values as one float series, with all column levels of a frame moved into the index.
An unnamed index level gets the name index (index_<i> for level i
of several), an unnamed column level column (column_<i>).
Source code in src/mesqual/validation/comparison.py
102 103 104 105 106 107 108 109 | |
ConstraintCheck
¶
Bases: DatasetCheck
Checks that the values of one flag are within bounds.
The check fetches the flag and tests each value: it must be at least
min_value and at most max_value. For an exact value, use equal.
An empty value (NaN) is a violation unless isna_ok; it is not tested
against the bounds. Without values to test, the result is SKIP.
A bound is a number, a Series or a DataFrame:
- A number applies to every value.
- A
DataFramealigns to the flag data by index and columns. - A
Serieson a frame flag applies per object when it matches the columns, per timestep when it matches the index. It has all levels of that axis; a bound on one level of aMultiIndexaxis is not supported. The level names decide first: the bound index names equal the column level names (per object) or the index names (per timestep). Else the labels decide: the bound labels overlap the columns and not the index (per object), or the other way round (per timestep). Extra labels are allowed. - A
Serieson a series flag aligns to its index.
A value without a bound (its label is not in the bound, or the bound is
NaN) is not tested against that bound. A Series or DataFrame bound that
covers no value of the data, for example a tz-naive bound on a tz-aware
index, raises ValueError in the run. So do a Series bound that matches
neither axis or both, an empty or a duplicate bound label, a DataFrame
bound on a series flag, a data level named value, min_value or
max_value, and an index level and a column level with the same name. The
validator reports these as ERROR.
FAIL lists one row per violation: the index levels and column levels of
the flag data, value, then min_value and max_value for the bounds
that are set.
Examples:
>>> loading = ConstraintCheck('Line.Results.loading', min_value=0, max_value=1, isna_ok=False)
>>> generation = ConstraintCheck( # per object: a Series by generator id
... 'Generator.Results.generation', min_value=0, max_value=dataset.fetch('Generator.Model')['capacity'],
... )
>>> flow = ConstraintCheck( # per value: a DataFrame like the flag data
... 'Line.Results.flow_sent_up', max_value=dataset.fetch('Line.Constraints.capacity_up'),
... )
>>> [check.run(dataset).status.name for check in (loading, generation, flow)]
['PASS', 'PASS', 'PASS']
>>> generation.run(dataset).summary
'1660 values of Generator.Results.generation meet the rule >= 0, <= max_value per object, empty allowed.'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flag
|
FlagType
|
The flag to check. |
required |
min_value
|
float | Series | DataFrame | None
|
Lowest allowed value, or |
None
|
max_value
|
float | Series | DataFrame | None
|
Highest allowed value, or |
None
|
isna_ok
|
bool
|
An empty value is not a violation. |
True
|
object_subset
|
list[int | str] | None
|
Columns of a frame flag to check, for example line ids.
|
None
|
name
|
str | None
|
The check name. Default: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Attributes:
| Name | Type | Description |
|---|---|---|
flag |
The flag to check. |
|
min_value |
Lowest allowed value, or |
|
max_value |
Highest allowed value, or |
|
isna_ok |
An empty value is not a violation. |
|
object_subset |
Columns of the flag data to check, or |
Source code in src/mesqual/validation/constraint_check.py
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
equal
classmethod
¶
equal(flag: FlagType, value: float | Series | DataFrame, *, isna_ok: bool = True, object_subset: list[int | str] | None = None, name: str | None = None) -> ConstraintCheck
Return a check that the values of flag equal value: min_value and max_value are both value.
value is a number, a Series or a DataFrame, aligned as a bound
(see the class docstring). The other arguments are those of the
constructor. Example: ConstraintCheck.equal('Line.Results.flow_sent_up', capacities, isna_ok=False).
Source code in src/mesqual/validation/constraint_check.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
ValidationReport
dataclass
¶
The results of the checks of one validation run, in run order.
Attributes:
| Name | Type | Description |
|---|---|---|
dataset |
str
|
Name of the dataset. |
results |
Sequence[CheckResult]
|
One result per check. |
Source code in src/mesqual/validation/report.py
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 | |
errors
property
¶
errors: tuple[CheckResult, ...]
The results with status ERROR: the checks that raised an exception.
__getitem__
¶
__getitem__(check: str) -> CheckResult
Return the result of the check with this name.
Raises:
| Type | Description |
|---|---|
KeyError
|
No result has the name. |
Source code in src/mesqual/validation/report.py
26 27 28 29 30 31 32 33 34 35 | |
to_frame
¶
to_frame() -> DataFrame
Return one row per check: check, status, summary and the number of detail rows details.
Source code in src/mesqual/validation/report.py
55 56 57 58 | |
to_markdown
¶
to_markdown(path: Path | str | None = None, max_rows: int = 20) -> str
Return the report as Markdown and write it to path if given.
The report has one table with the status and summary of every check,
then one section per check with details: the first max_rows detail
rows and the number of rows left out. A details index other than the
default range index becomes columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | str | None
|
File to write, or |
None
|
max_rows
|
int
|
Detail rows per check. |
20
|
Source code in src/mesqual/validation/report.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
CheckResult
dataclass
¶
The result of one check on one dataset.
Attributes:
| Name | Type | Description |
|---|---|---|
check |
str
|
Name of the check. |
status |
CheckStatus
|
The status. |
summary |
str
|
One line on the result. |
details |
DataFrame
|
One row per violation or finding; empty if there is none. Equality of two results does not compare the details. |
Source code in src/mesqual/validation/result.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
CheckStatus
¶
Bases: str, Enum
Status of a check.
Attributes:
| Name | Type | Description |
|---|---|---|
PASS |
The rule holds. |
|
FAIL |
The rule does not hold. The details list the violations. |
|
INFO |
A finding to read, not a failure. |
|
SKIP |
The check did not run, for example because a flag is not available. |
|
ERROR |
The check raised an exception. The summary gives its type and text. |
Source code in src/mesqual/validation/result.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
DatasetValidator
¶
Holds checks by name and runs them on a dataset.
Check names are unique. A platform package subclasses the validator to
give a default set of checks or extra constructor inputs. It passes the
default checks to super().__init__(checks). A subclass that binds a
dataset at construction overrides run(self, dataset=None) and falls back
to the bound dataset: return super().run(self.dataset if dataset is None else dataset).
Examples:
>>> from mesqual.validation import ConstraintCheck
>>> validator = DatasetValidator([
... ConstraintCheck('Line.Constraints.capacity_up', min_value=0),
... ConstraintCheck('Generator.Results.generation', min_value=0, isna_ok=False),
... ])
>>> validator.remove('ConstraintCheck[Line.Constraints.capacity_up]')
>>> report = validator.run(dataset)
>>> report.passed
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checks
|
Iterable[DatasetCheck]
|
The checks, in run order. |
()
|
Raises:
| Type | Description |
|---|---|
TypeError
|
A check is not a |
ValueError
|
Two checks have the same name. |
Source code in src/mesqual/validation/validator.py
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 | |
add
¶
add(check: DatasetCheck, *, replace: bool = False) -> None
Add a check at the end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
check
|
DatasetCheck
|
The check. |
required |
replace
|
bool
|
Replace a check with the same name in place. A check with a new name is added at the end. |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
The check is not a |
ValueError
|
The validator has a check with the same name and |
Source code in src/mesqual/validation/validator.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
remove
¶
remove(name: str) -> None
Remove the check with this name.
Raises:
| Type | Description |
|---|---|
KeyError
|
No check has the name. |
Source code in src/mesqual/validation/validator.py
72 73 74 75 76 77 78 79 80 | |
run
¶
run(dataset: Dataset) -> ValidationReport
Run every check on the dataset and return the report.
A check that raises an exception gets the status ERROR with
"Type: text" of the exception as summary, and the other checks still
run. The traceback goes to the log at level WARNING.
Source code in src/mesqual/validation/validator.py
82 83 84 85 86 87 88 89 | |