Skip to content

Commit

Permalink
method to read conversion from csv
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Busch committed Oct 16, 2024
1 parent 6e7b698 commit 3634389
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
33 changes: 28 additions & 5 deletions climate_categories/_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ def hydrate(
auxiliary_categories_hydrated = {}
for aux_categorization_name, categories in self.auxiliary_categories.items():
aux_categorization = cats[aux_categorization_name]
auxiliary_categories_hydrated[aux_categorization] = (
self._hydrate_handle_errors(categories, aux_categorization)
)
auxiliary_categories_hydrated[
aux_categorization
] = self._hydrate_handle_errors(categories, aux_categorization)

return ConversionRule(
factors_categories_a=self._hydrate_handle_errors(
Expand All @@ -87,12 +87,14 @@ def hydrate(
@typing.overload
def _hydrate_handle_errors(
self, to_hydrate: dict[str, int], categorization: "Categorization"
) -> dict["Category", int]: ...
) -> dict["Category", int]:
...

@typing.overload
def _hydrate_handle_errors(
self, to_hydrate: set[str], categorization: "Categorization"
) -> set["Category"]: ...
) -> set["Category"]:
...

def _hydrate_handle_errors(
self,
Expand Down Expand Up @@ -897,6 +899,27 @@ def __init__(
self.rules = rules
self.auxiliary_categorizations = auxiliary_categorizations

@classmethod
def from_csv(cls, filepath):
conv = ConversionSpec.from_csv(filepath)

def get_cats(cat_names):
import climate_categories

return {
cat_name: climate_categories.cats[cat_name] for cat_name in cat_names
}

cat_names = [
conv.categorization_a_name,
conv.categorization_b_name,
*conv.auxiliary_categorizations_names,
]

cats = get_cats(cat_names)

return conv.hydrate(cats=cats)

def reversed(self) -> "Conversion":
"""Returns the Conversion with categorization_a and categorization_b swapped."""
return Conversion(
Expand Down
13 changes: 13 additions & 0 deletions climate_categories/tests/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,3 +426,16 @@ def test_relevant_rules():
assert len(conv.relevant_rules({C96["4.D"]})) == 1
assert len(conv.relevant_rules({C96["4.B.10"]}, simple_sums_only=True)) == 1
assert conv.relevant_rules(set()) == []


def test_read_csv_in_conversion_class():
filepath = importlib.resources.files("climate_categories.data").joinpath(
"conversion.IPCC1996.IPCC2006.csv"
)
conv = conversions.Conversion.from_csv(filepath)

assert conv.categorization_a_name == "IPCC1996"
assert conv.categorization_b_name == "IPCC2006"

# make sure hydrate() added all the rules
assert len(conv.rules) == 153

0 comments on commit 3634389

Please sign in to comment.