From bf3d08c00e3443a281b0e18e224b493f06c3b558 Mon Sep 17 00:00:00 2001 From: Leila Y-Farsani <108967493+leilafarsani@users.noreply.github.com> Date: Tue, 3 Dec 2024 12:41:04 +0000 Subject: [PATCH] Add country percentage normalisation --- .../iati_activity.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/iati_activity_details_split_by_fields/iati_activity.py b/iati_activity_details_split_by_fields/iati_activity.py index 525cc8f..1278760 100644 --- a/iati_activity_details_split_by_fields/iati_activity.py +++ b/iati_activity_details_split_by_fields/iati_activity.py @@ -72,8 +72,23 @@ def get_transactions_split_as_json(self): return [x.get_as_json() for x in self.get_transactions_split()] def _get_recipient_countries_with_normalised_percentages(self): - # TODO - return self.recipient_countries + """Normalise country percentages to ensure they sum to 100%""" + if not self.recipient_countries: + return [] + total_percentage = sum( + country.percentage or 0 + for country in self.recipient_countries + ) + if total_percentage == 0: + return self.recipient_countries + + normalized_countries = copy.deepcopy(self.recipient_countries) + + for country in normalized_countries: + if country.percentage: + country.percentage = (country.percentage / total_percentage) * 100 + + return normalized_countries def _get_sectors_grouped_by_vocab_with_normalised_percentages(self) -> dict: output: dict = {}