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.6482332700676897,
0.6219790425278798,
0.6402812948349823
],
[
0.3474754414536124,
0.8873718303900037,
0.758105176439606
],
[
0.7638183052289742,
0.14387029477108992,
0.08608177147253715
],
[
0.15435784797203222,
0.9770239843520149,
0.6392729372020461
],
[
0.4550373627182125,
0.7373554517392681,
0.023833299095512794
]
]
}
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.8830180891072925
],
[
0.5073507813658725
],
[
0.04069425045657815
],
[
0.16518186963706172
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.8661653835014783
],
[
0.48644274926755404
],
[
0.7979819406923181
],
[
0.35395702090370795
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.17272652503663666
],
[
0.1953362691364916
],
[
0.07310620008138724
],
[
0.19270424813793552
]
]
}
]
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.88301809],
[0.50735078],
[0.04069425],
[0.16518187]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.86616538],
[0.48644275],
[0.79798194],
[0.35395702]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.17272653],
[0.19533627],
[0.0731062 ],
[0.19270425]]))]
Total running time of the script: (0 minutes 0.005 seconds)