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.0902350965979708,
0.8587298792667244,
0.26328837232186675
],
[
0.776651622431395,
0.8526353972457055,
0.8829989463739728
],
[
0.6094372101879096,
0.9010921596429333,
0.3227110944337114
],
[
0.14870037987343854,
0.2720037891539161,
0.1943816595072786
],
[
0.3383776571414806,
0.2795369394522912,
0.6561813549837233
]
]
}
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.8856146403186085
],
[
0.7474087112120849
],
[
0.22604111044819997
],
[
0.11227376157806124
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.6567724333626876
],
[
0.5062940867519186
],
[
0.2808374280718251
],
[
0.12432462310167369
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.7363118703189538
],
[
0.458812963056637
],
[
0.8302801018471271
],
[
0.18246584178939151
]
]
}
]
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.88561464],
[0.74740871],
[0.22604111],
[0.11227376]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.65677243],
[0.50629409],
[0.28083743],
[0.12432462]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.73631187],
[0.45881296],
[0.8302801 ],
[0.18246584]]))]
Total running time of the script: (0 minutes 0.005 seconds)