Trajectories serialization
Main author: Simon Rohou
Importing CSV data
A SampledTraj can be filled from the following data.csv file:
t;value
0;1.5
1;2.
2;2.5
Read its time/value columns and insert the samples using set(value,time). The examples locate data.csv alongside the source file.
import csv
from pathlib import Path
measurements = SampledTraj_Scalar()
with (Path(__file__).parent / 'data.csv').open(newline='') as file:
# The header is parsed automatically.
for row in csv.DictReader(file, delimiter=';'):
measurements.set(float(row['value']), float(row['t']))
SampledTraj<double> measurements;
std::ifstream csv(std::filesystem::path(__FILE__).parent_path() / "data.csv");
std::string line;
std::getline(csv, line); // skip header
while(std::getline(csv, line))
{
double t, value;
if(std::sscanf(line.c_str(), "%lf;%lf", &t, &value) == 2)
measurements.set(value, t);
}
NumPy archives
In Python, load a .npz file with numpy.load and pass its time and value arrays to SampledTraj. The trajectory type is inferred from the values.
import numpy as np
from codac import SampledTraj
data = np.load("traj_vec.npz")
traj = SampledTraj(data["t"], data["x"])
In the above example, if x is a 2D array of shape (N,n), then traj is a SampledTraj_Vector.
Another example:
import numpy as np
from codac import *
t = np.array([0.0, 0.5, 1.0, 1.5])
x = np.array([
[0.0, 1.0],
[0.5, 1.5],
[1.0, 2.0],
[1.5, 2.5],
])
traj = SampledTraj(t, x)
print(traj) # outputs: SampledTraj. [0, 1.5]↦[[0, 1.5][1, 2.5]], 4 pts
Binary serialization
serialize and deserialize save and restore SampledTraj objects in binary form. The .cdc extension is conventional. An AnalyticTraj can be sampled before saving, but the symbolic expression itself is not serialized.
input_traj = SampledTraj({0.:1, 1.:1.5, 2.:2})
with open('trajectory_python.cdc', 'wb') as f:
serialize(f, input_traj)
restored = SampledTraj_Scalar()
with open('trajectory_python.cdc', 'rb') as f:
deserialize(f, restored)
SampledTraj<double> input({{0.,1}, {1.,1.5}, {2.,2}});
{
std::ofstream out("trajectory.cdc", std::ios::binary);
serialize(out, input);
}
SampledTraj<double> restored;
{
std::ifstream in("trajectory.cdc", std::ios::binary);
deserialize(in, restored);
}
See Binary serialization for details about the binary format.
Visualization
Use Figure2D.plot_trajectory for scalar time series and Figure2D.plot_trajectories for vector time series. Spatial trajectories can be displayed with DefaultFigure.draw_trajectory. See 2D drawing functions.