rheon.polars.ModelBank.write_json

ModelBank.write_json(file: None = None, *, pretty: bool = True) → str[source]
ModelBank.write_json(file: str | PathLike[str] | IO[str] | IO[bytes], *, pretty: bool = True) → None

Write the bank’s state as JSON, which can be read without this library.

Use it to look at a state, to compare two states, or to hand one to a program that is not Python. It is an export, not a second form of state file: load() reads only what save() writes.

Parameters

file

Where to write: a path, or a file object, text or binary (the bytes are UTF-8). None, the default, returns the text, as Polars’ DataFrame.write_json() does. A path is written directly, without save()’s safe replacement: an export of a state kept elsewhere is mended by writing it again.

pretty

Whether to indent the JSON over several lines. True by default. False writes it on one line.

Returns

The JSON text when file is None, and otherwise None. It holds everything save() writes, every value included: NaN and the infinities, which JSON has no literal for, are written as the strings "nan", "inf" and "-inf", the spellings a spec’s half_life takes.

Raises

ValueError

The export, read back, does not give the state’s MessagePack byte for byte (see Notes), or a refused chunk left the bank unable to go on.

TypeError

file is neither a path, a file object nor None.

OSError

A path cannot be written, such as FileNotFoundError for a folder that does not exist.

RuntimeError

A call that learns is in flight on another thread.

UnstableWarning

Under RHEON_WARN_UNSTABLE=1, for a formula target, as save() says. The export carries the same written form.

Examples

This code reads df from Example data:

import json

spec = rp.spec.ewridge("ridge", targets=["y"], features=["x0", "x1"], half_life=100.0)
bank = rp.ModelBank([spec])
bank.fit_predict(df)
state = json.loads(bank.write_json())     # the state, as Python objects
bank.write_json("bank.json")               # the same text, in a file
print(state["rows_fed"], [s["name"] for s in state["specs"]])
400 ['ridge']

See also

Notes

Every export is read back and converted to MessagePack, which must match the state’s byte for byte. One that does not raises ValueError naming the problem, so the export is never a file that is wrong without saying so.