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.49053197557926065,
0.10765603351018949,
0.9647843304731141
],
[
0.21645602683801257,
0.06716763273942628,
0.22421048641878727
],
[
0.6436510045048892,
0.3518983429697824,
0.3722745635088399
],
[
0.025054069498858356,
0.09957575005626185,
0.9069446686347781
],
[
0.7394955121252277,
0.5675679479051441,
0.24983936222157566
]
]
}
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.7381678974519859
],
[
0.5394629555325402
],
[
0.27135898430030236
],
[
0.8485531627816226
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.7842041215336754
],
[
0.29202708138612876
],
[
0.029241591373653564
],
[
0.786772350266552
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.7198331117456962
],
[
0.26891928917412167
],
[
0.2710133187982756
],
[
0.5925872767436073
]
]
}
]
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.7381679 ],
[0.53946296],
[0.27135898],
[0.84855316]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.78420412],
[0.29202708],
[0.02924159],
[0.78677235]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.71983311],
[0.26891929],
[0.27101332],
[0.59258728]]))]
Total running time of the script: (0 minutes 0.012 seconds)