Skip to content

Commit

Permalink
pyproject, data_models: Add pandera & example for index data validation
Browse files Browse the repository at this point in the history
  • Loading branch information
stroitzsch committed Oct 9, 2023
1 parent 6236317 commit 938cb6a
Show file tree
Hide file tree
Showing 8 changed files with 194 additions and 1 deletion.
8 changes: 8 additions & 0 deletions mesmo/data_models/base_model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""Custom pydantic base model."""

from typing import Callable

import numpy as np
import pandas as pd
import pandera as pa
import pydantic as pyd
from pydantic.json import timedelta_isoformat

Expand All @@ -19,3 +22,8 @@ class BaseModel(pyd.BaseModel):
np.bool_: bool,
},
)


def check_index(schema: pa.Index) -> Callable[[pd.Index], pd.Index]:
"""Create pydantic validation function for pandas.Index based on given pandera.Index schema."""
return lambda v: schema.validate(pd.Series(index=v)).index
9 changes: 9 additions & 0 deletions mesmo/data_models/model_index.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
"""Model index set data models."""

from typing import Annotated

import pandas as pd
import pandera as pa
import pydantic as pyd

from mesmo.data_models import base_model


class SampleModelIndex(base_model.BaseModel):
timesteps: Annotated[pd.Index, pyd.AfterValidator(base_model.check_index(pa.Index(pd.Timestamp)))]
names: Annotated[pd.Index, pyd.AfterValidator(base_model.check_index(pa.Index(str, unique=True)))]


class ElectricGridModelIndex(base_model.BaseModel):
timesteps: pd.Index
phases: pd.Index
Expand Down
165 changes: 164 additions & 1 deletion poetry.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pyyaml = "^6.0.1"
requests = "^2.31.0" # For HiGHS installation.
scipy = "^1.11.3"
tqdm = "^4.66.1"
pandera = "^0.17.2"

[tool.poetry.group.test.dependencies]
coverage = { extras = ["toml"], version = "^7.3.2" }
Expand Down
Empty file added tests/__init__.py
Empty file.
Empty file added tests/mesmo/__init__.py
Empty file.
Empty file.
12 changes: 12 additions & 0 deletions tests/mesmo/data_models/model_index_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import pandas as pd
import pytest

from mesmo.data_models import model_index


class TestSampleModelIndex:
def test_init(self):
timesteps = pd.Index([pd.Timestamp("now"), pd.Timestamp("now")])
names = pd.Index(["a", "b", "c"])

model_index.SampleModelIndex(timesteps=timesteps, names=names)

0 comments on commit 938cb6a

Please sign in to comment.