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.5144201630727383,
0.6837616758929493,
0.37639459594499336
],
[
0.628020510946427,
0.019957841398765885,
0.8635382481704144
],
[
0.42195905847912507,
0.8974321758328678,
0.6346325161260943
],
[
0.7400365415483713,
0.2624120256978184,
0.6911393994980407
],
[
0.22352311073390785,
0.698768384315137,
0.5694585198357389
]
]
}
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.09628988553057571
],
[
0.2582941867684798
],
[
0.2547254311149839
],
[
0.2199104892862188
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.1278901570169949
],
[
0.6145707429150035
],
[
0.19691739565588706
],
[
0.8833503881032535
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.6449590718016677
],
[
0.8443034834196623
],
[
0.5898649561139061
],
[
0.5601493699786311
]
]
}
]
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.09628989],
[0.25829419],
[0.25472543],
[0.21991049]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.12789016],
[0.61457074],
[0.1969174 ],
[0.88335039]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.64495907],
[0.84430348],
[0.58986496],
[0.56014937]]))]
Total running time of the script: (0 minutes 0.005 seconds)