Skip to content

Commit

Permalink
fix: use the new naming conventoin
Browse files Browse the repository at this point in the history
  • Loading branch information
12rambau committed Dec 22, 2023
1 parent 807ae81 commit c4f5e53
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 74 deletions.
77 changes: 30 additions & 47 deletions pygaul/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def _df() -> pd.DataFrame:
return pd.read_parquet(__gaul_data__)


@versionadded(version="0.3.0", reason="Add a Names object to handle names")
class AdmNames(pd.DataFrame):
@versionadded(version="0.3.1", reason="Add a Names object to handle names")
class Names(pd.DataFrame):
def __init__(
self,
name: str = "",
Expand Down Expand Up @@ -135,31 +135,8 @@ def __init__(
super().__init__(final_df)


@deprecated(version="0.3.0", reason="Use the Names object instead")
def get_names(
name: str = "", admin: str = "", content_level: int = -1, complete: bool = False
) -> pd.DataFrame:
"""
Return the list of names available in a administrative layer using the name or the administrative code.
Return a pandas DataFrame of the names as FAO GAUL codes of and administrative region. The region can be requested either by its "name" or its "admin", the lib will identify the corresponding level on the fly. The user can also request for a specific level for its content e.g. get all admin level 1 of a country. If nothing is set we will infer the level of the item and if the level is higher than the found item, it will be ignored. If Nothing is found the method will raise an error.
Args:
name: The name of a administrative area. Cannot be set along with :code:`admin`.
admin: The id of an administrative area in the FAO GAUL nomenclature. Cannot be set along with :code:`name`.
content_level: The level to use in the final dataset. Default to -1 (use level of the selected area).
complete: If True, the method will return all the names of the higher administrative areas. Default to False.
Returns:
The list of all the available names.
"""
return AdmNames(name, admin, content_level, complete)


@versionadded(
version="0.3.0", reason="Add an AdmItems object to handle administrative items"
)
class AdmItems(ee.FeatureCollection):
@versionadded(version="0.3.1", reason="Add an Items class to handle admin items")
class Items(ee.FeatureCollection):
def __init__(
self,
name: Union[str, List[str]] = "",
Expand Down Expand Up @@ -215,22 +192,22 @@ def _items(
Returns:
The FeatureCollection of the requested area with all the GAUL attributes.
"""
# call to get_names without level to raise an error if the requested level won't work
df = get_names(name, admin)
# call to Names without level to raise an error if the requested level won't work
df = Names(name, admin)
if len(df) > 1:
raise ValueError(
f'The requested name ("{name}") is not unique ({len(df)} results). '
f"To retrieve it, please use the `admin` parameter instead. "
f"If you don't know the GAUL code, use the following code, "
f'it will return the GAUL codes as well:\n`get_names(name="{name}")`'
f'it will return the GAUL codes as well:\n`Names(name="{name}")`'
)
df.columns[0][3]

# now load the useful one to get content_level
df = get_names(name, admin, content_level)
df = Names(name, admin, content_level)
content_level = df.columns[1][3]

# checks have already been performed in get_names and there should
# checks have already been performed in Names and there should
# be one single result
ids = [int(v) for v in df[f"ADM{content_level}_CODE"].to_list()]

Expand All @@ -242,23 +219,29 @@ def _items(
return feature_collection


@deprecated(version="0.3.0", reason="Use the AdmItems object instead")
@deprecated(version="0.3.1", reason="Use the Names object instead")
class AdmNames(Names):
pass


@deprecated(version="0.3.1", reason="Use the Items class instead")
class AdmItems(Items):
pass


@deprecated(version="0.3.0", reason="Use the Names object instead")
def get_names(
name: str = "", admin: str = "", content_level: int = -1, complete: bool = False
) -> pd.DataFrame:
"""Return the list of names available in a administrative layer using the name or the administrative code."""
return Names(name, admin, content_level, complete)


@deprecated(version="0.3.0", reason="Use the Items class instead")
def get_items(
name: Union[str, List[str]] = "",
admin: Union[str, List[str]] = "",
content_level: int = -1,
) -> ee.FeatureCollection:
"""
Return the requested administrative boundaries using the name or the administrative code.
Return an ee.FeatureCollection representing an administrative region. The region can be requested either by its "name" or its "admin", the lib will identify the area level on the fly. The user can also request for a specific level for the GeoDataFrame features e.g. get all admin level 1 of a country. If nothing is set we will infer the level of the item and if the level is higher than the found item, it will be ignored. If Nothing is found the method will return an error.
Args:
name: The name of an administrative area. Cannot be set along with :code:`admin`. it can be a list or a single name.
admin: The id of an administrative area in the GADM nomenclature. Cannot be set along with :code:`name`. It can be a list or a single admin code.
content_level: The level to use in the final dataset. Default to -1 (use level from the area).
Returns:
The FeatureCollection of the requested area with all the GADM attributes.
"""
return AdmItems(name, admin, content_level)
"""Return the requested administrative boundaries using the name or the administrative code."""
return Items(name, admin, content_level)
2 changes: 1 addition & 1 deletion tests/test_continent.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def test_file():

def test_continent(data_regression):
"""Check that the continent are working."""
fc = pygaul.AdmItems(name="antartica")
fc = pygaul.Items(name="antartica")
data_regression.check(fc.aggregate_array("ADM0_CODE").getInfo())


Expand Down
37 changes: 24 additions & 13 deletions tests/test_get_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,44 @@
def test_empty():
"""Empty request."""
with pytest.raises(Exception):
pygaul.AdmItems()
pygaul.Items()


def test_duplicate_intput():
"""Request with too many parameters."""
# request with too many things
with pytest.raises(Exception):
pygaul.AdmItems(name="Singapore", admin="222")
pygaul.Items(name="Singapore", admin="222")


def test_non_existing():
"""Request non existing area."""
with pytest.raises(Exception):
pygaul.AdmItems(name="t0t0")
pygaul.Items(name="t0t0")

with pytest.raises(Exception):
pygaul.AdmItems(admin="t0t0")
pygaul.Items(admin="t0t0")


def test_area(data_regression):
"""Request a known geometry."""
fc = pygaul.AdmItems(name="Singapore")
fc = pygaul.Items(name="Singapore")
assert fc.size().getInfo() == 1
assert fc.first().get("ADM0_CODE").getInfo() == 222
data_regression.check(fc.geometry().bounds().coordinates().get(0).getInfo())


def test_sub_content(data_regression):
"""Request a sublevel."""
fc = pygaul.AdmItems(name="Singapore", content_level=1)
fc = pygaul.Items(name="Singapore", content_level=1)
assert all([i == 222 for i in fc.aggregate_array("ADM0_CODE").getInfo()])
data_regression.check(fc.aggregate_array("ADM1_CODE").getInfo())


def test_too_high():
"""Request a sublevel higher than available in the area."""
with pytest.warns(UserWarning):
fc = pygaul.AdmItems(admin="2658", content_level=0)
fc = pygaul.Items(admin="2658", content_level=0)
assert fc.size().getInfo() == 1
assert fc.aggregate_array("ADM1_CODE").getInfo() == [2658]

Expand All @@ -55,15 +55,15 @@ def test_too_low():
"""Request a sublevel lower than available in the area."""
# request a level too low
with pytest.warns(UserWarning):
fc = pygaul.AdmItems(admin="2658", content_level=3)
fc = pygaul.Items(admin="2658", content_level=3)
assert fc.size().getInfo() == 1
assert fc.aggregate_array("ADM1_CODE").getInfo() == [2658]


def test_case_insensitive():
"""Request an area without respecting the case."""
fc1 = pygaul.AdmItems(name="Singapore")
fc2 = pygaul.AdmItems(name="singaPORE")
fc1 = pygaul.Items(name="Singapore")
fc2 = pygaul.Items(name="singaPORE")

# just check that all ids of the fgeatures are the same as they all come from the same
# initial ee.FeatureCollection
Expand All @@ -75,20 +75,31 @@ def test_case_insensitive():

def test_multiple_input(data_regression):
"""Test when several geometries are requested at once."""
fc1 = pygaul.AdmItems(name=["france", "germany"])
fc1 = pygaul.Items(name=["france", "germany"])
data_regression.check(fc1.getInfo())

# just check that all ids of the fgeatures are the same as they all come from the same
# initial ee.FeatureCollection
fc2 = pygaul.AdmItems(admin=["85", "93"])
fc2 = pygaul.Items(admin=["85", "93"])
ids1 = fc1.aggregate_array("system:index").sort()
ids2 = fc2.aggregate_array("system:index").sort()
assert ids1.equals(ids2).getInfo()


def test_get_items():
"""Test that get_items still works."""
fc1 = pygaul.AdmItems(name="Singapore")
fc1 = pygaul.Items(name="Singapore")
ids1 = fc1.aggregate_array("system:index").sort()

with pytest.warns(DeprecationWarning):
fc2 = pygaul.get_items(name="Singapore")
ids2 = fc2.aggregate_array("system:index").sort()
assert ids1.equals(ids2).getInfo()


def test_adm_items():
"""Test that AdmItems still works."""
fc1 = pygaul.Items(name="Singapore")
ids1 = fc1.aggregate_array("system:index").sort()

with pytest.warns(DeprecationWarning):
Expand Down
35 changes: 22 additions & 13 deletions tests/test_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,61 +7,61 @@

def test_empty(dataframe_regression):
"""Empty request, should list the countries."""
df = pygaul.AdmNames()
df = pygaul.Names()
dataframe_regression.check(df)


def test_duplicate_input():
"""Request with too many parameters."""
with pytest.raises(Exception):
pygaul.AdmNames(name="Singapore", admin="222")
pygaul.Names(name="Singapore", admin="222")


def test_non_existing():
"""Request non existing area."""
with pytest.raises(Exception):
pygaul.AdmNames(name="t0t0")
pygaul.Names(name="t0t0")

with pytest.raises(Exception):
pygaul.AdmNames(admin="t0t0")
pygaul.Names(admin="t0t0")


def test_area(dataframe_regression):
"""Request a known."""
df = pygaul.AdmNames(name="Singapore")
df = pygaul.Names(name="Singapore")
dataframe_regression.check(df)


def test_sub_content(dataframe_regression):
"""Request a sublevel."""
df = pygaul.AdmNames(name="Singapore", content_level=1)
df = pygaul.Names(name="Singapore", content_level=1)
dataframe_regression.check(df)


def test_complete_content(dataframe_regression):
"""Request the complete hierarchy of an area."""
df = pygaul.AdmNames(name="Singapore", content_level=1, complete=True)
df = pygaul.Names(name="Singapore", content_level=1, complete=True)
dataframe_regression.check(df)


def test_too_high(dataframe_regression):
"""Request a sublevel higher than available in the area."""
with pytest.warns(UserWarning):
df = pygaul.AdmNames(admin="2658", content_level=0)
df = pygaul.Names(admin="2658", content_level=0)
dataframe_regression.check(df)


def test_too_low(dataframe_regression):
"""Request a sublevel lower than available in the area."""
with pytest.warns(UserWarning):
df = pygaul.AdmNames(admin="2658", content_level=4)
df = pygaul.Names(admin="2658", content_level=4)
dataframe_regression.check(df)


def test_case_insensitive():
"""Request an area without respecting the case."""
df1 = pygaul.AdmNames(name="Singapore")
df2 = pygaul.AdmNames(name="singaPORE")
df1 = pygaul.Names(name="Singapore")
df2 = pygaul.Names(name="singaPORE")

assert df1.equals(df2)

Expand All @@ -70,13 +70,22 @@ def test_suggestions():
"""Test that when a wrong name is given 5 options are proposed in the error message."""
expected_error = 'The requested "Franc" is not part of FAO GAUL 2015. The closest matches are: France, Franca, Ranco, Rancul, Ranchi.'
with pytest.raises(ValueError, match=expected_error):
pygaul.AdmNames(name="Franc")
pygaul.Names(name="Franc")


def test_get_names():
"""Test that get_names still works."""
df1 = pygaul.AdmNames(name="Singapore")
df1 = pygaul.Names(name="Singapore")

with pytest.warns(DeprecationWarning):
df2 = pygaul.get_names(name="Singapore")
assert df1.equals(df2)


def test_adm_names():
"""Test that AdmNames still works."""
df1 = pygaul.Names(name="Singapore")

with pytest.warns(DeprecationWarning):
df2 = pygaul.AdmNames(name="Singapore")
assert df1.equals(df2)

1 comment on commit c4f5e53

@12rambau
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix #47

Please sign in to comment.