diff --git a/pysr/sr.py b/pysr/sr.py index 0054ce50..60268fa3 100644 --- a/pysr/sr.py +++ b/pysr/sr.py @@ -51,7 +51,9 @@ from .utils import ( ArrayLike, PathLike, + _CrossPlatformPathUnpickler, _csv_filename_to_pkl_filename, + _path_to_str, _preprocess_julia_floats, _safe_check_feature_names_in, _subscriptify, @@ -1007,11 +1009,10 @@ def from_file( assert unary_operators is None assert n_features_in is None with open(pkl_filename, "rb") as f: - model = pkl.load(f) - # Change equation_file_ to be in the same dir as the pickle file - base_dir = os.path.dirname(pkl_filename) - base_equation_file = os.path.basename(model.equation_file_) - model.equation_file_ = os.path.join(base_dir, base_equation_file) + unpickler = _CrossPlatformPathUnpickler(f) + model = unpickler.load() + # Convert equation_file_ to string to ensure cross-platform compatibility + model.equation_file_ = _path_to_str(model.equation_file_) # Update any parameters if necessary, such as # extra_sympy_mappings: diff --git a/pysr/utils.py b/pysr/utils.py index de7faf16..40c5c58c 100644 --- a/pysr/utils.py +++ b/pysr/utils.py @@ -1,8 +1,9 @@ import difflib import inspect import os +import pickle as pkl import re -from pathlib import Path +from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any, List, TypeVar, Union from numpy import ndarray @@ -73,3 +74,19 @@ def _suggest_keywords(cls, k: str) -> List[str]: ] suggestions = difflib.get_close_matches(k, valid_keywords, n=3) return suggestions + + +class _CrossPlatformPathUnpickler(pkl.Unpickler): + def find_class(self, module, name): + if module == "pathlib": + if name == "PosixPath": + return PurePosixPath + elif name == "WindowsPath": + return PureWindowsPath + return super().find_class(module, name) + + +def _path_to_str(path): + if isinstance(path, (PurePosixPath, PureWindowsPath)): + return str(path) + return path