This page was generated from appendix-pickling/pickling.ipynb.
Pickling of NGSolve objects¶
Python objects an be converted to byte-streams, which can be stored to files, and later the Python object can be reconstructed by the inverse process. In general this is known as serialization, in Python it is called pickling, see https://docs.python.org/3/library/pickle.html. Another usecase is parallel computing, where it is used to send whole Python objects across a network.
Many of the NGSolve-objects support pickling.
[1]:
from ngsolve import *
from ngsolve.webgui import Draw
[2]:
mesh = Mesh(unit_square.GenerateMesh(maxh=0.3))
[3]:
import pickle
outfile = open("mesh.pkl", "wb")
pickle.dump(mesh, outfile)
[4]:
infile = open("mesh.pkl", "rb")
mesh2 = pickle.load(infile)
mesh2.nv, mesh2.ne
[4]:
(19, 24)
[5]:
Draw (mesh2);
Pickling expression trees¶
CoefficientFunction
expression trees support pickling as well.
[8]:
func = x*gfu1 + y
print (func)
coef binary operation '+', real
coef binary operation '*', real
coef coordinate x, real
coef N6ngcomp14S_GridFunctionIdEE, real
coef coordinate y, real
[9]:
outfile = open("func.pkl", "wb")
pickle.dump([mesh,func], outfile)
infile = open("func.pkl", "rb")
mesh2,func2 = pickle.load(infile)
print (func2)
Draw (func2, mesh2);
coef binary operation '+', real
coef binary operation '*', real
coef coordinate x, real
coef N6ngcomp14S_GridFunctionIdEE, real
coef coordinate y, real
We were pickling the mesh explicitly to have it available for drawing, it would be contained in the function func
anyway.
[10]:
import os
os.remove("mesh.pkl")
os.remove("gridfunction.pkl")
os.remove("func.pkl")
Implementation of pickling¶
pybind11-pickling supports wrapping of serialization of user-classes.
And then there is ngcore - archive …
[ ]:
[ ]: