Skip to content

Commit

Permalink
Test adding data to scalar variable raises
Browse files Browse the repository at this point in the history
  • Loading branch information
glatterf42 committed Nov 29, 2024
1 parent dc2a021 commit 90938a2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
13 changes: 8 additions & 5 deletions ixmp4/data/db/optimization/variable/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,14 @@ def add_data(self, variable_id: int, data: dict[str, Any] | pd.DataFrame) -> Non

index_list = [column.name for column in variable.columns]
existing_data = pd.DataFrame(variable.data)
if not existing_data.empty:
existing_data.set_index(index_list, inplace=True)
variable.data = (
data.set_index(index_list).combine_first(existing_data).reset_index()
).to_dict(orient="list") # type: ignore[assignment]
if index_list:
data = data.set_index(index_list)
if not existing_data.empty:
existing_data.set_index(index_list, inplace=True)
data = data.combine_first(existing_data)
if index_list:
data = data.reset_index()
variable.data = data.to_dict(orient="list") # type: ignore[assignment]

self.session.commit()

Expand Down
8 changes: 8 additions & 0 deletions tests/core/test_optimization_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,14 @@ def test_variable_add_data(self, platform: ixmp4.Platform) -> None:
)
assert_unordered_equality(expected, pd.DataFrame(variable_4.data))

# Test adding to scalar variable raises
with pytest.raises(
OptimizationDataValidationError,
match="Trying to add data to unknown Columns!",
):
variable_5 = run.optimization.variables.create("Variable 5")
variable_5.add(data={"foo": ["bar"], "levels": [1], "marginals": [0]})

def test_variable_remove_data(self, platform: ixmp4.Platform) -> None:
run = platform.runs.create("Model", "Scenario")
indexset = run.optimization.indexsets.create("Indexset")
Expand Down

0 comments on commit 90938a2

Please sign in to comment.