rheon.polars.ModelBank.save

ModelBank.save(file: str | PathLike[str] | IO[bytes]) → None[source]

Write the bank’s state to a file that load() reads on any supported OS.

Use it to keep what a bank has learned, to resume it later or to serve from it. For the bytes without a file, use save_bytes(), and to read a state outside this library, use write_json().

The file loads in this release and every later one, a spec’s formula target (an expression in targets holding a window operator of rheon.polars.ops that looks ahead) and the rows its windows hold included: the file names its version, and each later layout ships a loader for the one before.

Parameters

file

A path, or a file object opened for binary writing, such as open(..., "wb") or an io.BytesIO, as Polars’ write_* methods take either. A path is replaced safely: an interrupted save leaves the file that was there before (see Notes). A file object is handed the bytes in one write, and whether that write can be interrupted is up to whoever opened it.

Raises

OSError

The file cannot be written, with the path in the message: FileNotFoundError for a folder that does not exist, PermissionError for one that cannot be written. A file that was there is left untouched.

TypeError

file is neither a path nor a binary file object, such as a file opened for text or an io.StringIO.

ValueError

A refused chunk left the bank unable to go on (fit_predict(), Notes).

RuntimeError

A call that learns is in flight on another thread.

Examples

This code reads df from Example data:

spec = rp.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0)
bank = rp.ModelBank([spec])
bank.fit_predict(df)
bank.save("bank.state")                       # a path, replaced safely
print(rp.ModelBank.load("bank.state").rows_fed)
400

See also

Notes

The state is versioned MessagePack. A path is written to a temporary file beside it, synced to the disk, and renamed into place, so a power loss cannot leave an empty file where a good state was. The sync takes about 4 ms on macOS, against about 0.1 ms to write a state of 396 KiB. In the same measurement, on a Mac, a whole save of 500 groups (encoding the state, writing it and renaming it) took 5.0 ms with the sync and 0.5 ms without it. A save after every chunk is dominated by the sync, and a save after every hundredth chunk is not.