Skip to content

Commit

Permalink
test: check array (#1238 #1276 #1277)
Browse files Browse the repository at this point in the history
  • Loading branch information
bonjourmauko committed Oct 16, 2024
1 parent bc8c166 commit 81e93c7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
33 changes: 30 additions & 3 deletions openfisca_core/populations/_core_population.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from openfisca_core import holders, periods

from . import types as t
from ._errors import InvalidArraySizeError
from ._errors import PeriodValidityError
from ._errors import InvalidArraySizeError, PeriodValidityError

#: Type variable for a covariant data type.
_DT_co = TypeVar("_DT_co", covariant=True, bound=t.VarDType)
Expand Down Expand Up @@ -160,7 +159,35 @@ def get_index(self, id: str) -> int:

# Calculations

def check_array_compatible_with_entity(self, array: t.FloatArray) -> None:
def check_array_compatible_with_entity(self, array: t.VarArray) -> None:
"""Check if an array is compatible with the population.
Args:
array: The array to check.
Raises:
InvalidArraySizeError: If the array is not compatible.
Examples:
>>> import numpy
>>> from openfisca_core import entities, populations
>>> class Person(entities.SingleEntity): ...
>>> person = Person("person", "people", "", "")
>>> population = populations.CorePopulation(person)
>>> population.count = 3
>>> array = numpy.array([1, 2, 3])
>>> population.check_array_compatible_with_entity(array)
>>> array = numpy.array([1, 2, 3, 4])
>>> population.check_array_compatible_with_entity(array)
Traceback (most recent call last):
InvalidArraySizeError: Input [1 2 3 4] is not a valid value for t...
"""
if self.count == array.size:
return
raise InvalidArraySizeError(array, self.entity.key, self.count)
Expand Down
2 changes: 1 addition & 1 deletion openfisca_core/populations/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class InvalidArraySizeError(ValueError):
"""Raised when an array has an invalid size."""

def __init__(self, array: t.FloatArray, entity: t.EntityKey, count: int) -> None:
def __init__(self, array: t.VarArray, entity: t.EntityKey, count: int) -> None:
msg = (
f"Input {array} is not a valid value for the entity {entity} "
f"(size = {array.size} != {count} = count)."
Expand Down
3 changes: 3 additions & 0 deletions openfisca_core/populations/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
#: Type alias for an array of floats.
FloatArray: TypeAlias = Array[FloatDType]

#: Type alias for an array of generic objects.
VarArray: TypeAlias = Array[VarDType]

# Periods

#: New type for a period integer.
Expand Down

0 comments on commit 81e93c7

Please sign in to comment.