Note
Go to the end to download the full example code.
Saving and loading splines#
import sys
import numpy as np
import splinebox.basis_functions
import splinebox.spline_curves
We start by creating a random spline.
spline = splinebox.spline_curves.Spline(
M=5, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.random.rand(5, 3)
)
Let’s save the spline:
spline.to_json("spline.json")
Here is what the json file looks like:
with open("spline.json") as f:
sys.stdout.write(f.read())
{
"version": 1,
"M": 5,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.7518855799812371,
0.14624305379137237,
0.5227480488120114
],
[
0.76731021458696,
0.29074678440683366,
0.187150524052905
],
[
0.2432162331242278,
0.3810103639216561,
0.2601062418481568
],
[
0.21700541754778768,
0.15259706884422186,
0.05744503757972086
],
[
0.5441443577750936,
0.5807235949788219,
0.013093073103979669
]
]
}
Next, we will create a new spline based on the json file.
loaded_spline = splinebox.spline_curves.Spline.from_json("spline.json")
You can also save multiple splines in a single json file.
splines = []
for _ in range(3):
spline = splinebox.spline_curves.Spline(
M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.random.rand(4, 1)
)
splines.append(spline)
splinebox.spline_curves.splines_to_json("splines.json", splines)
Here is what a json file with multiple splines looks like:
with open("splines.json") as f:
sys.stdout.write(f.read())
[
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.5168885403932835
],
[
0.4757337842724021
],
[
0.4399155615237992
],
[
0.7302655593505906
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.23005540688789583
],
[
0.19432031594688104
],
[
0.589946188688903
],
[
0.2769184885987399
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.5385217691646141
],
[
0.8103622788420788
],
[
0.4609927718961655
],
[
0.6475933135192288
]
]
}
]
Lastly, we load multiple splines from a single json file.
splines = splinebox.spline_curves.splines_from_json("splines.json")
print(splines)
[splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.51688854],
[0.47573378],
[0.43991556],
[0.73026556]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.23005541],
[0.19432032],
[0.58994619],
[0.27691849]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.53852177],
[0.81036228],
[0.46099277],
[0.64759331]]))]
Total running time of the script: (0 minutes 0.005 seconds)