diff --git a/pygmt/src/binstats.py b/pygmt/src/binstats.py index e629303b17c..4926bdf89e4 100644 --- a/pygmt/src/binstats.py +++ b/pygmt/src/binstats.py @@ -9,6 +9,7 @@ from pygmt._typing import PathLike, TableLike from pygmt.alias import Alias, AliasSystem from pygmt.clib import Session +from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import build_arg_list, fmt_docstring, use_alias @@ -166,7 +167,15 @@ def binstats( ) aliasdict.merge(kwargs) if statistic == "quantile": - aliasdict["C"] += f"{quantile_value}" + quantile_error_message = "quantile_value must be a value between 0 and 100." + try: + quantile_value_float = float(quantile_value) + except (ValueError, TypeError): + raise GMTInvalidInput(quantile_error_message) from None + if 0 <= quantile_value_float <= 100: + aliasdict["C"] += f"{quantile_value_float}" + else: + raise GMTInvalidInput(quantile_error_message) from None with Session() as lib: with ( diff --git a/pygmt/tests/test_binstats.py b/pygmt/tests/test_binstats.py index 91848b6e1c1..79ee554f680 100644 --- a/pygmt/tests/test_binstats.py +++ b/pygmt/tests/test_binstats.py @@ -8,6 +8,7 @@ import pytest from pygmt import binstats from pygmt.enums import GridRegistration, GridType +from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import GMTTempFile @@ -51,6 +52,38 @@ def test_binstats_no_outgrid(): npt.assert_allclose(temp_grid.mean(), 4227489) +def test_binstats_quantile_range_validation(): + """ + Tests the input validation that quantile is between 0 and 100. + """ + with pytest.raises(GMTInvalidInput): + binstats( + data="@capitals.gmt", + spacing=5, + statistic="quantile", + quantile_value=175, + search_radius="1000k", + aspatial="2=population", + region="g", + ) + + +def test_binstats_quantile_int_validation(): + """ + Tests the input validation that quantile has a numeric value. + """ + with pytest.raises(GMTInvalidInput): + binstats( + data="@capitals.gmt", + spacing=5, + statistic="quantile", + quantile_value="test", + search_radius="1000k", + aspatial="2=population", + region="g", + ) + + def test_binstats_quantile(): """ Test binstats quantile statistic functionality. @@ -59,7 +92,7 @@ def test_binstats_quantile(): data="@capitals.gmt", spacing=5, statistic="quantile", - quantile_value=75, + quantile_value="75", search_radius="1000k", aspatial="2=population", region="g",