Skip to content

Commit c932181

Browse files
author
Victor Garcia Reolid
committed
support pickling a linopy model
Signed-off-by: Victor Garcia Reolid <victor@seita.nl>
1 parent a57d24b commit c932181

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

linopy/constraints.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,9 @@ def __getattr__(self, name: str) -> Constraint:
755755
raise AttributeError(
756756
f"Constraints has no attribute `{name}` or the attribute is not accessible, e.g. raises an error."
757757
)
758+
759+
def __getstate__(self): return self.__dict__
760+
def __setstate__(self, d): return self.__dict__.update(d)
758761

759762
def __dir__(self) -> list[str]:
760763
base_attributes = list(super().__dir__())

linopy/variables.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,6 +1181,9 @@ def __getattr__(self, name: str) -> Variable:
11811181
raise AttributeError(
11821182
f"Variables has no attribute `{name}` or the attribute is not accessible / raises an error."
11831183
)
1184+
1185+
def __getstate__(self): return self.__dict__
1186+
def __setstate__(self, d): return self.__dict__.update(d)
11841187

11851188
def __dir__(self) -> list[str]:
11861189
base_attributes = list(super().__dir__())

test/test_io.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import pandas as pd
1212
import pytest
1313
import xarray as xr
14+
import pickle
1415

1516
from linopy import LESS_EQUAL, Model, available_solvers, read_netcdf
1617
from linopy.testing import assert_model_equal
@@ -108,6 +109,20 @@ def test_model_to_netcdf_with_status_and_condition(
108109

109110
assert_model_equal(m, p)
110111

112+
def test_pickle_model(model_with_dash_names: Model, tmp_path: Path):
113+
m = model_with_dash_names
114+
fn = tmp_path / "test.nc"
115+
m._status = "ok"
116+
m._termination_condition = "optimal"
117+
118+
with open(fn, 'wb') as f:
119+
pickle.dump(m, f)
120+
121+
with open(fn, 'rb') as f:
122+
p = pickle.load(f)
123+
124+
assert_model_equal(m, p)
125+
111126

112127
# skip it xarray version is 2024.01.0 due to issue https://github.com/pydata/xarray/issues/8628
113128
@pytest.mark.skipif(

0 commit comments

Comments
 (0)