-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Data Validation Framework: Source + Product data #1241
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
373c91e
Add pandera package (#1362)
sf-dcp e015a84
`models.dataset` module:
sf-dcp d261204
Create `pandera_utils.create_check` fn and test it
sf-dcp 631ee02
Create `pandera_utils.create_column_with_checks` fn
sf-dcp dfb3370
Add a test to compare `pa.Check` against `dataset.CheckAttributes`
sf-dcp 38b7afc
Create `pandera_utils.run_data_checks` and test it
sf-dcp 95a360d
Create `validate.run` module
sf-dcp 49ed0a4
Add custom data check and test it
sf-dcp 3fbf77a
POST REVIEW: rename a variable in `create_check()`. Add a comment
sf-dcp 999d7e8
POST REVIEW: rename `validate/run.py` -> `validate/data.py`
sf-dcp 727426f
POST REVIEW: add attributes to `dataset.CheckAttributes` model
sf-dcp f874c8c
POST REVIEW: appease mypy
sf-dcp 3c5d0e7
POST REVIEW: Appease mypy (socrata/metadata files)
sf-dcp 4227bdf
POST REVIEW: format with new ruff
sf-dcp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,6 +27,7 @@ openpyxl | |
openpyxl-stubs | ||
pandas | ||
pandas-stubs | ||
pandera | ||
plotly | ||
pre-commit | ||
psycopg2-binary | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from . import pandera_custom_checks | ||
|
||
# from .data import run |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
from pathlib import Path | ||
|
||
|
||
def run( | ||
dataset_id: str, | ||
input_path: Path, | ||
): | ||
# TODO: read in data from input_path to pandas dataframe | ||
|
||
# TODO: get dataset template | ||
|
||
# TODO: run data checks | ||
|
||
raise NotImplementedError | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
from pandera import extensions | ||
|
||
|
||
@extensions.register_check_method(check_type="element_wise") | ||
def is_geom_point(s): | ||
try: | ||
return s.geom_type == "Point" | ||
except ValueError: | ||
return False | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import pandera as pa | ||
import pandas as pd | ||
import geopandas as gpd | ||
from inspect import ( | ||
signature, | ||
) # used for checking expected attributes in a class signuture | ||
|
||
from dcpy.models.dataset import Column, CheckAttributes, Checks | ||
|
||
|
||
def create_check(check: str | dict[str, CheckAttributes]) -> pa.Check: | ||
""" | ||
Creates a Pandera `Check` object from a given check definition. | ||
|
||
Args: | ||
check: | ||
A string representing the name of the check or a dictionary with the | ||
check name as the key and check attibutes as the value. | ||
Returns: | ||
pa.Check: | ||
A Pandera `Check` object constructed with the specified parameters. | ||
Raises: | ||
AssertionError: | ||
If the `check` dictionary does not contain exactly one key-value pair. | ||
ValueError: | ||
If the check name is not registered or if attributes cannot be parsed | ||
or used to create a valid `Check`. | ||
""" | ||
allowed_check_names = { | ||
**pa.Check.CHECK_FUNCTION_REGISTRY, | ||
**pa.Check.REGISTERED_CUSTOM_CHECKS, | ||
} | ||
|
||
if isinstance(check, str): | ||
check_name = check | ||
check_args = None | ||
elif isinstance(check, dict): | ||
assert len(check) == 1, ( | ||
"`utils.create_pa_check` expects exactly 1 key-value pair in `check` param." | ||
) | ||
check_name, check_args = next(iter(check.items())) | ||
|
||
if check_name not in allowed_check_names: | ||
raise ValueError(f"Unregistered check name: '{check_name}'.") | ||
|
||
# Retrieve constructor for the specified check name from pandera. | ||
# The constructor requires check-specific parameters and also accepts **kwargs | ||
# for generic parameters shared across all Check objects like "description" attribute | ||
check_constructor = getattr(pa.Check, check_name) | ||
|
||
if check_args: | ||
check_expected_params = signature(check_constructor).parameters | ||
invalid_check_keys = set(check_args.args.keys()) - set( | ||
check_expected_params.keys() | ||
) | ||
if invalid_check_keys: | ||
alexrichey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
raise ValueError( | ||
f"Invalid argument keys found for check '{check_name}': {invalid_check_keys}. " | ||
f"Valid argument keys are: {sorted(check_expected_params.keys())}." | ||
) | ||
|
||
try: | ||
check_obj = ( | ||
check_constructor( | ||
**check_args.args, | ||
raise_warning=check_args.warn_only, | ||
description=check_args.description, | ||
name=check_args.name, | ||
title=check_args.title, | ||
n_failure_cases=check_args.n_failure_cases, | ||
groups=check_args.groups, | ||
groupby=check_args.groupby, | ||
ignore_na=check_args.ignore_na, | ||
) | ||
if check_args | ||
else check_constructor() | ||
) | ||
except Exception as e: | ||
raise ValueError( | ||
f"Check '{check_name}' couldn't be created. Error message: {e}" | ||
) | ||
|
||
return check_obj | ||
|
||
|
||
def create_checks(checks: list[str | dict[str, CheckAttributes]]) -> list[pa.Check]: | ||
"""Create Pandera checks.""" | ||
pandera_checks = [create_check(check) for check in checks] | ||
return pandera_checks | ||
|
||
|
||
def create_column_with_checks(column: Column) -> pa.Column: | ||
"""Create Pandera column validator object.""" | ||
if isinstance(column.checks, Checks): | ||
raise NotImplementedError( | ||
"Pandera checks are not implemented for old Column.checks format" | ||
) | ||
data_checks = create_checks(column.checks) if column.checks else None | ||
return pa.Column( | ||
# TODO: implement `dtype` param | ||
coerce=True, # coerce column to defined data type. This decision is up for debate | ||
checks=data_checks, | ||
required=column.is_required, | ||
description=column.description, | ||
nullable=True, # TODO: temp solution. Need to figure out what to do with this (equivalent to can be null) | ||
) | ||
|
||
|
||
def run_data_checks( | ||
df: pd.DataFrame | gpd.GeoDataFrame, columns: list[Column] | ||
) -> pd.DataFrame | gpd.GeoDataFrame: | ||
""" | ||
Validate a DataFrame or GeoDataFrame against a schema defined by a list of columns with Pandera. | ||
|
||
Args: | ||
df (pd.DataFrame | gpd.GeoDataFrame): The input DataFrame to validate. | ||
columns (list[Column]): List of column definitions specifying validation rules. | ||
|
||
Raises: | ||
AssertionError: If column names in `columns` are not unique. | ||
""" | ||
|
||
column_names = [column.id for column in columns] | ||
assert len(column_names) == len(set(column_names)), ( | ||
"Columns should have unique names" | ||
) | ||
|
||
dataframe_checks = {} | ||
for column in columns: | ||
dataframe_checks[column.id] = create_column_with_checks(column) | ||
|
||
return pa.DataFrameSchema(dataframe_checks).validate(df) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if you want to make use of it, you could call
dcpy.utils.introspect.validate_kwargs
here - it would validate types of arguments as well. You'd still need to raise the error based on the returned object