Skip to content

Commit 67e13a1

Browse files
Support pickling a linopy model (#438)
1 parent a57d24b commit 67e13a1

File tree

4 files changed

+32
-0
lines changed

4 files changed

+32
-0
lines changed

doc/release_notes.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ Version 0.5.2
1313
This is mainly affecting operations where single numerical items from pandas objects
1414
are selected and used for multiplication.
1515

16+
**Feature**
17+
18+
* Support pickling models.
19+
1620
Version 0.5.1
1721
--------------
1822

linopy/constraints.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,12 @@ def __getattr__(self, name: str) -> Constraint:
756756
f"Constraints has no attribute `{name}` or the attribute is not accessible, e.g. raises an error."
757757
)
758758

759+
def __getstate__(self) -> dict:
760+
return self.__dict__
761+
762+
def __setstate__(self, d: dict) -> None:
763+
self.__dict__.update(d)
764+
759765
def __dir__(self) -> list[str]:
760766
base_attributes = list(super().__dir__())
761767
formatted_names = [

linopy/variables.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,12 @@ def __getattr__(self, name: str) -> Variable:
11821182
f"Variables has no attribute `{name}` or the attribute is not accessible / raises an error."
11831183
)
11841184

1185+
def __getstate__(self) -> dict:
1186+
return self.__dict__
1187+
1188+
def __setstate__(self, d: dict) -> None:
1189+
self.__dict__.update(d)
1190+
11851191
def __dir__(self) -> list[str]:
11861192
base_attributes = list(super().__dir__())
11871193
formatted_names = [

test/test_io.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
@author: fabian
66
"""
77

8+
import pickle
89
from pathlib import Path
910
from typing import Union
1011

@@ -109,6 +110,21 @@ def test_model_to_netcdf_with_status_and_condition(
109110
assert_model_equal(m, p)
110111

111112

113+
def test_pickle_model(model_with_dash_names: Model, tmp_path: Path) -> None:
114+
m = model_with_dash_names
115+
fn = tmp_path / "test.nc"
116+
m._status = "ok"
117+
m._termination_condition = "optimal"
118+
119+
with open(fn, "wb") as f:
120+
pickle.dump(m, f)
121+
122+
with open(fn, "rb") as f:
123+
p = pickle.load(f)
124+
125+
assert_model_equal(m, p)
126+
127+
112128
# skip it xarray version is 2024.01.0 due to issue https://github.com/pydata/xarray/issues/8628
113129
@pytest.mark.skipif(
114130
xr.__version__ in ["2024.1.0", "2024.1.1"],

0 commit comments

Comments
 (0)