Serialization¶
All the relevant objects (graphs, factors, Bayesian networks, etc) can be saved/loaded using the pickle format.
These objects can be saved using directly pickle.dump()
and pickle.load()
. For example:
>>> import pickle
>>> from pybnesian.graph import Dag
>>> g = Dag(["a", "b", "c", "d"], [("a", "b")])
>>> with open("saved_graph.pickle", "wb") as f:
... pickle.dump(g, f)
>>> with open("saved_graph.pickle", "rb") as f:
... lg = pickle.load(f)
>>> assert lg.nodes() == ["a", "b", "c", "d"]
>>> assert lg.arcs() == [("a", "b")]
We can reduce some boilerplate code using the save
methods: Factor.save()
,
UndirectedGraph.save()
,
DirectedGraph.save()
,
BayesianNetworkBase.save()
, etc… Also, the pybnesian.load()
can load any saved object:
>>> import pickle
>>> from pybnesian import load
>>> from pybnesian.graph import Dag
>>> g = Dag(["a", "b", "c", "d"], [("a", "b")])
>>> g.save("saved_graph")
>>> lg = load("saved_graph.pickle")
>>> assert lg.nodes() == ["a", "b", "c", "d"]
>>> assert lg.arcs() == [("a", "b")]