Skip to content

Commit

Permalink
feat(optimizers): Enable pickling of MIOSR optimizer (#458)
Browse files Browse the repository at this point in the history
Fixes #456

Implement __setstate__ and __getstate__ methods for MIOSR
AFAIK, we don't need to mess with __reduce__
Add a new test for the pickle-ability of optimizers
  • Loading branch information
Jacob-Stevens-Haas committed Jan 16, 2024
1 parent 4c7f02b commit a7eb890
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pysindy/optimizers/miosr.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,12 @@ def _reduce(self, x, y):
def complexity(self):
check_is_fitted(self)
return np.count_nonzero(self.coef_)

def __getstate__(self):
state = self.__dict__.copy()
del state["model"]
return state

def __setstate__(self, state):
self.__dict__.update(state)
self.model = None
12 changes: 12 additions & 0 deletions test/test_optimizers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
Unit tests for optimizers.
"""
import pickle

import numpy as np
import pytest
from numpy.linalg import norm
Expand Down Expand Up @@ -1129,3 +1131,13 @@ def test_remove_and_decrement():
existing_vals=existing_vals, vals_to_remove=vals_to_remove
)
np.testing.assert_array_equal(expected, result)


def test_pickle(data_lorenz):
x, t = data_lorenz
y = PolynomialLibrary(degree=2).fit_transform(x)
opt = MIOSR(target_sparsity=7).fit(x, y)
expected = opt.coef_
new_opt = pickle.loads(pickle.dumps(opt))
result = new_opt.coef_
np.testing.assert_array_equal(result, expected)

0 comments on commit a7eb890

Please sign in to comment.