Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return OSeMOSYS data as an xarray.DataSet #184

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ pandas
pydantic
pydot
pyyaml
xarray
xlrd
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ install_requires =
flatten_dict
openpyxl
pydantic
xarray
[options.packages.find]
where = src
exclude =
Expand Down
32 changes: 32 additions & 0 deletions src/otoole/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from typing import Any, Dict, List, Optional, TextIO, Tuple, Union

import pandas as pd
import xarray as xr

from otoole.exceptions import OtooleIndexError, OtooleNameMismatchError

Expand Down Expand Up @@ -593,3 +594,34 @@ def read(
self, filepath: Union[str, TextIO], **kwargs
) -> Tuple[Dict[str, pd.DataFrame], Dict[str, Any]]:
raise NotImplementedError()

def to_xarray(self, filepath) -> xr.Dataset:
"""Returns input data as an xarray.Dataset

Arguments
---------
filepath: Union[str, TextIO]

"""

model, defaults = self.read(filepath)
config = self.input_config

data_vars = {
x: y.VALUE.to_xarray()
for x, y in model.items()
if config[x]["type"] == "param"
}
coords = {
x: y.values.T[0] for x, y in model.items() if config[x]["type"] == "set"
}
ds = xr.Dataset(data_vars=data_vars, coords=coords)
# ds = ds.assign_coords({'_REGION': model['REGION'].values.T[0]})

for param, default in defaults.items():
if param in config and param in model and config[param]["type"] == "param":
ds[param].attrs["default"] = default
if default != 0:
ds[param] = ds[param].fillna(default)

return ds
20 changes: 20 additions & 0 deletions tests/test_input.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from typing import Any, Dict, TextIO, Tuple, Union

import pandas as pd
import xarray as xr
from pandas.testing import assert_frame_equal
from pytest import fixture, mark, raises

from otoole.exceptions import OtooleIndexError, OtooleNameMismatchError
from otoole.input import ReadStrategy, WriteStrategy
from otoole.read_strategies import ReadMemory


@fixture
Expand Down Expand Up @@ -533,3 +535,21 @@ def test_compare_read_to_expected_exception(self, simple_user_config, expected):
reader = DummyReadStrategy(simple_user_config)
with raises(OtooleNameMismatchError):
reader._compare_read_to_expected(names=expected)


class TestXarray:
def test_xarray(self, user_config):
"""Test that xarray can be imported"""

data = [
["SIMPLICITY", "ETH", 2014, 1.0],
["SIMPLICITY", "RAWSUG", 2014, 0.5],
["SIMPLICITY", "ETH", 2015, 1.03],
["SIMPLICITY", "RAWSUG", 2015, 0.51],
]
df = pd.DataFrame(data=data, columns=["REGION", "FUEL", "YEAR", "VALUE"])
parameters = {"AccumulatedAnnualDemand": df}

reader = ReadMemory(parameters, user_config)
actual = reader.to_xarray("")
assert isinstance(actual, xr.Dataset)