Here's a Python implementation of the idea you described, using NumPy for efficient array operations.
import numpy as np
from dataclasses import dataclass
@dataclass
class Angle:
sin: float
cos: float
def to_numpy(self):
return np.array([self.sin, self.cos])
def build_normales(segment_angles_list, invalid=np.nan):
N = len(segment_angles_list)
k = len(segment_angles_list[0].to_numpy()) # assuming all segments have the same length
# Pre-allocate the matrix with the invalid value
normales = np.full((N + 1, 2 * k), invalid)
# Fill in the values
for i, seg_angles in enumerate(segment_angles_list):
# For the first row, write invalid on the left and the current segment on the right
if i == 0:
normales[i, k:] = seg_angles.to_numpy()
# For the last row, write the last segment on the left and invalid on the right
if i == N - 1:
normales[i + 1, :k] = seg_angles.to_numpy()
# For all other rows, write the previous segment on the left and the current segment on the right
else:
normales[i + 1, :k] = segment_angles_list[i].to_numpy()
normales[i + 1, k:] = segment_angles_list[i + 1].to_numpy()
return normales
# Example usage
segment_angles_list = [
Angle(1.0, 1.1),
Angle(2.0, 2.2),
Angle(3.0, 3.3),
Angle(4.0, 4.4),
Angle(5.0, 5.5)
]
normales = build_normales(segment_angles_list, invalid=-1)
print(normales)
This will output:
[[-1. -1. 1. 1.1]
[ 1. 1.1 2. 2.2]
[ 2. 2.2 3. 3.3]
[ 3. 3.3 4. 4.4]
[ 4. 4.4 5. 5.5]
[ 5. 5.5 -1. -1. ]]
The code works as follows:
- Pre-allocate a matrix
normales with shape (N + 1, 2 * k), where N is the number of segments and k is the length of each segment.
- Iterate over the
segment_angles_list and fill in the values in normales according to the specified pattern.
- For the first row, write the first segment on the right half.
- For the last row, write the last segment on the left half.
- For all other rows, write the previous segment on the left half and the current segment on the right half.
The result is a matrix where each row represents a node, and the left and right halves of each row contain the corresponding segment values.