Skip to content

Commit

Permalink
Merge pull request #386 from gro-intelligence/GAIA-29324
Browse files Browse the repository at this point in the history
add new parameters to `get_area_weighted_series()`
  • Loading branch information
John-Desmond authored Dec 18, 2023
2 parents b89fdf9 + 4e2b12f commit c64f473
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 20 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ dist/
docs/_build/

.coverage
.DS_Store

2 changes: 1 addition & 1 deletion docs/authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ To work with the Gro API, you need an authentication token. This token needs to
Retrieving a token
==================

Note that your account needs to be activated for API access before you will be able to retrieve a token. See https://gro-intelligence.com/products/gro-api for more info regarding unlocking API access for your account.
Note that your account needs to be activated for API access before you will be able to retrieve a token. Please contact your sale rep or Customer Success to activate your account for API access. If you have any questions, please email [email protected].
Once you have API access enabled for your account, you may retrieve your token by following the steps below:


Expand Down
2 changes: 1 addition & 1 deletion docs/faq.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ You must get an `authentication token <authentication#retrieving-a-token>`_ from
Why am I getting a 401 Unauthorized error when I try to use my Gro username and login?
--------------------------------------------------------------------------------------

A Gro account gives you access to the web application at app.gro-intelligence.com. API access is sold as an add-on product you need to be activated for. To learn more about getting an API account, contact our sales team using the link at `gro-intelligence.com/products/gro-api <https://www.gro-intelligence.com/products/gro-api>`_
A Gro account gives you access to the web application at app.gro-intelligence.com. API access is sold as an add-on product you need to be activated for. To learn more about getting an API account, contact our sales team at support@gro-intelligence.com

Gro Models
==========
Expand Down
50 changes: 40 additions & 10 deletions groclient/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
import time

from typing import List, Union
from typing import Dict, List, Optional, Union

# Python3 support
try:
Expand Down Expand Up @@ -1813,10 +1813,15 @@ def get_area_weighted_series(
series_name: str,
weight_names: List[str],
region_id: Union[int, List[int]],
aggregation: Optional[str] = None,
start_date: Optional[str] = None,
end_date: Optional[str] = None,
limit: Optional[Union[int, str]] = "all",
level: Optional[int] = None,
method: str = "sum",
latest_date_only: bool = False,
metadata: bool = False
):
metadata: bool = False,
) -> Dict[str, float]:
"""Compute weighted average on selected series with the given weights.
Returns a dictionary mapping dates to weighted values.
Expand All @@ -1832,13 +1837,33 @@ def get_area_weighted_series(
region_id: integer or list of integers
The region or regions for which the weighted series will be computed
Supported region levels are (1, 2, 3, 4, 5, 8)
method: str, optional
'sum' by default. Multi-crop weights can be calculated with either 'sum' or 'normalize' method.
latest_date_only: bool, optional
False by default. If True, will return a single key-value pair where the key is the latested date.
aggregation: str, optional
A string that can be parsed into components used to do the aggregation.
Format: {type}-{data_points/start_doy}
e.g. "total-7" returns 7 data point trailing totals
e.g. "ytd" returns year to date rolling cumulative totals for each year
in the series.
e.g. "ytd-5" returns the rolling cumulative totals for each year starting from
the 5th day of the year to the 4th day of the following year.
start_date: str, optional
A timestamp of the format 'YYYY-MM-DD', e.g. '2023-01-01'
end_date: str, optional
A timestamp of the format 'YYYY-MM-DD', e.g. '2023-01-01'
limit: Union[int, str], optional, default="all"
Will return the x latest data points within a given range. Example usage: `limit=1` returns
the latest data point.
A value of 'all' indicates returning all data within the specified range.
level: int, optional
The region level to which data will be aggregated before being returned.
If level not provided, the endpoint will aggregate to the level of each specified
region id.
method: str, optional, default="sum"
Multi-crop weights can be calculated with either 'sum' or 'normalize' method.
latest_date_only: bool, optional, default=False
If True, will return a single key-value pair where the key is the latested date.
e.g. {'2000-03-12': 0.221}
metadata: bool, optional
False by default. If True, will return the metadata for the given series and weights.
metadata: bool, optional, default=False
If True, will return the metadata for the given series and weights.
Returns
-------
Expand All @@ -1853,9 +1878,14 @@ def get_area_weighted_series(
series_name,
weight_names,
region_id,
aggregation,
start_date,
end_date,
limit,
level,
method,
latest_date_only,
metadata
metadata,
)

def get_area_weighting_weight_metadata(
Expand Down
9 changes: 6 additions & 3 deletions groclient/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ def mock_get_descendant(
childs = list(mock_entities["regions"].values())

if not include_historical or include_details:

if not include_historical:
childs = [child for child in childs if not child["historical"]]

Expand Down Expand Up @@ -182,7 +181,6 @@ def mock_get_ancestor(
childs = list(mock_entities["regions"].values())

if not include_historical or include_details:

if not include_historical:
childs = [child for child in childs if not child["historical"]]

Expand Down Expand Up @@ -273,9 +271,14 @@ def mock_get_area_weighted_series(
series_name,
weight_names,
region_id,
aggregation,
start_date,
end_date,
limit,
level,
method,
latest_date_only,
metadata
metadata,
):
return {"2022-07-11": 0.715615, "2022-07-19": 0.733129, "2022-07-27": 0.748822}

Expand Down
26 changes: 21 additions & 5 deletions groclient/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import warnings

from pkg_resources import get_distribution, DistributionNotFound
from typing import List, Union
from typing import Dict, List, Optional, Union

try:
# functools are native in Python 3.2.3+
Expand Down Expand Up @@ -111,7 +111,11 @@ def get_access_token(api_host, user_email, user_password, logger=None):
accessToken : string
"""
warnings.warn(f'get_access_token() is deprecated and will be removed on November 1, 2023.', DeprecationWarning, 2)
warnings.warn(
f"get_access_token() is deprecated and will be removed on November 1, 2023.",
DeprecationWarning,
2,
)
retry_count = 0
if not logger:
logger = get_default_logger()
Expand Down Expand Up @@ -312,7 +316,9 @@ def lookup(access_token, api_host, entity_type, entity_ids):
try: # Convert iterable types like numpy arrays or tuples into plain lists
entity_ids = list(entity_ids)
return lookup_batch(access_token, api_host, entity_type, entity_ids)
except TypeError: # Convert anything else, like strings or numpy integers, into plain integers
except (
TypeError
): # Convert anything else, like strings or numpy integers, into plain integers
entity_id = int(entity_ids)
# If an integer is given, return only the dict with that id
return lookup_single(access_token, api_host, entity_type, entity_id)
Expand Down Expand Up @@ -845,10 +851,15 @@ def get_area_weighted_series(
series_name: str,
weight_names: List[str],
region_id: Union[int, List[int]],
aggregation: Optional[str],
start_date: Optional[str],
end_date: Optional[str],
limit: Optional[Union[int, str]],
level: Optional[int],
method: str,
latest_date_only: bool,
metadata: bool,
):
) -> Dict[str, float]:
url = f"https://{api_host}/area-weighting"
headers = {"authorization": "Bearer " + access_token}
if isinstance(region_id, int):
Expand All @@ -857,9 +868,14 @@ def get_area_weighted_series(
"seriesName": series_name,
"weightNames": weight_names,
"regionIds": region_id,
"aggregation": aggregation,
"startDate": start_date,
"endDate": end_date,
"limit": limit,
"level": level,
"method": method,
"latestDateOnly": latest_date_only,
"metadata": metadata
"metadata": metadata,
}
resp = get_data(url, headers, params=params)
return resp.json()
Expand Down
10 changes: 10 additions & 0 deletions groclient/lib_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1149,6 +1149,11 @@ def test_get_area_weighted_series(mock_requests_get):
"NDVI_8day",
["Barley (ha)", "Corn (ha)"],
1215,
None,
None,
None,
"all",
None,
"sum",
False,
False
Expand All @@ -1163,6 +1168,11 @@ def test_get_area_weighted_series(mock_requests_get):
"NDVI_8day",
["Barley (ha)", "Corn (ha)"],
[1215],
None,
None,
None,
"all",
None,
"sum",
False,
True
Expand Down

0 comments on commit c64f473

Please sign in to comment.