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.22866620252612857,
0.4262301500912308,
0.7174008985325085
],
[
0.3205657811855481,
0.6650795852313316,
0.45388648459309455
],
[
0.49380268195361454,
0.7198426340516233,
0.03931323178435275
],
[
0.1934855389364072,
0.6352434520200382,
0.14537730514805758
],
[
0.31920255869302017,
0.7761925273284254,
0.36339136074660905
]
]
}
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.918947140035338
],
[
0.7296639905822224
],
[
0.862184728858717
],
[
0.843876486608424
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.7122548529277632
],
[
0.34767408245380094
],
[
0.017013081107529193
],
[
0.46120985234722733
]
]
},
{
"version": 1,
"M": 4,
"basis_function": "B3",
"closed": true,
"control_points": [
[
0.30557377210246217
],
[
0.21884594146066183
],
[
0.20825208356072
],
[
0.5699187156427699
]
]
}
]
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.91894714],
[0.72966399],
[0.86218473],
[0.84387649]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.71225485],
[0.34767408],
[0.01701308],
[0.46120985]])), splinebox.spline_curves.Spline(M=4, basis_function=splinebox.basis_functions.B3(), closed=True, control_points=np.array([[0.30557377],
[0.21884594],
[0.20825208],
[0.56991872]]))]
Total running time of the script: (0 minutes 0.005 seconds)