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.9968825081062371,
0.03794235554933434,
0.3192220425345669
],
[
0.39137010900821956,
0.41328549358889843,
0.7895119422658325
],
[
0.8868419791976561,
0.15472032511365008,
0.477087684545067
],
[
0.6819968988926697,
0.6984765805326295,
0.1570127727788574
],
[
0.5924394481308163,
0.48173718872518334,
0.2520381171841275
]
]
}
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.3025477615480596
],
[
0.7542100155185272
],
[
0.22041016749746345
],
[
0.30273800694331965
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.954899863687714
],
[
0.3152836480786152
],
[
0.15743166310401469
],
[
0.3454637849566269
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.21857872700631287
],
[
0.4435889346709041
],
[
0.2981979141658898
],
[
0.4026871330443029
]
]
}
]
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.30254776],
[0.75421002],
[0.22041017],
[0.30273801]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.95489986],
[0.31528365],
[0.15743166],
[0.34546378]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.21857873],
[0.44358893],
[0.29819791],
[0.40268713]]))]
Total running time of the script: (0 minutes 0.005 seconds)