Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23247

Compute and plot rotation angles from coordinates

$
0
0

I'm working on a code that should plot the rotation around x, y and z axis. The angles are to be computed from positional data, which is given for 4 markers, each having x, y and z coordinates. The positions are measured over time with a motion capture system and are then extracted into a csv file.I'm trying to get this to work with mostly Chat GPT, but I've got a basic understanding.The data is compared to an already computed and ploted dataset, measured with a different system which gives angle velocities as output.Current problem is basically, that 2 out of 3 angles seem to be quite precise, whilst the 3rd is around 30° off.

How am I able to provide my data? Currently not sure where/how to upload. Thanks!

Here is my code so far:Working velocity ploting:

import pandas as pdimport matplotlib.pyplot as plt#from mpl_toolkits.mplot3d import Axes3Dimport numpy as np# load datadata = pd.read_csv('path_to_file', delimiter=';')#%%# extract time datazeit = pd.to_numeric(data['time'].str.replace(',', '.'), errors='coerce')#%%# extract each velocitywinkelgeschwindigkeit_x = pd.to_numeric(data['wx (rad/s)'].str.replace(',', '.'), errors='coerce')winkelgeschwindigkeit_y = pd.to_numeric(data['wy (rad/s)'].str.replace(',', '.'), errors='coerce')winkelgeschwindigkeit_z = pd.to_numeric(data['wz (rad/s)'].str.replace(',', '.'), errors='coerce')#%%# compute orientationorientierung_x = np.zeros_like(zeit)orientierung_y = np.zeros_like(zeit)orientierung_z = np.zeros_like(zeit)#%%for i in range(1, len(zeit)):    dt = zeit.iloc[i] - zeit.iloc[i-1]    orientierung_x[i] = orientierung_x[i-1] + winkelgeschwindigkeit_x.iloc[i] * dt    orientierung_y[i] = orientierung_y[i-1] + winkelgeschwindigkeit_y.iloc[i] * dt    orientierung_z[i] = orientierung_z[i-1] + winkelgeschwindigkeit_z.iloc[i] * dtorientierung_x = orientierung_x * (180/3.1415)orientierung_y = orientierung_y * (180/3.1415)orientierung_z = orientierung_z * (180/3.1415)#%%# Initialise the subplot function using number of rows and columns figure, axis = plt.subplots(2, 2) # For Sine Function axis[0, 0].plot(zeit, orientierung_x) axis[0, 0].set_title("x over t") # For Cosine Function axis[0, 1].plot(zeit, orientierung_y) axis[0, 1].set_title("y over t") # For Tangent Function axis[1, 0].plot(zeit, orientierung_z) axis[1, 0].set_title("z over t") # For Tanh Function axis[1, 1].plot() axis[1, 1].set_title("spare square") # Combine all the operations and display plt.show()# Plot der Bewegung in 3Dfig = plt.figure()ax = fig.add_subplot(111, projection='3d')ax.plot(orientierung_x, orientierung_y, orientierung_z)ax.set_xlabel('X-Achse')ax.set_ylabel('Y-Achse')ax.set_zlabel('Z-Achse')ax.set_title('Bewegung des Handys in 3D')plt.show()

And here my best shot at the positional computing:

import pandas as pdimport numpy as npimport matplotlib.pyplot as plt# read datadfraw = pd.read_csv('path_to_file, skiprows = [0,1,2,3,4,6,7], delimiter=',')df = dfrawdf.rename(columns = {'Time':'time','LASI':'x1','Unnamed: 2':'y1','Unnamed: 3':'z1','RASI':'x2','Unnamed: 5':'y2','Unnamed: 6':'z2','LPSI':'x3','Unnamed: 8':'y3','Unnamed: 9':'z3','RPSI':'x4','Unnamed: 11':'y4','Unnamed: 12':'z4'},            inplace=True)#%%# naming datazeit = df[["time"]].to_numpy()Marker1 = df[["x1", "y1", "z1"]].to_numpy()Marker2 = df[["x2", "y2", "z2"]].to_numpy()Marker3 = df[["x3", "y3", "z3"]].to_numpy()Marker4 = df[["x4", "y4", "y4"]].to_numpy()import numpy as npimport matplotlib.pyplot as plt# function to compute vectorsdef compute_normal_vectors(marker_coordinates):    normal_vectors = []    for i in range(len(marker_coordinates[0])):        # Extracting coordinates for each marker at the current time point        marker1 = marker_coordinates[0][i]        marker2 = marker_coordinates[1][i]        marker3 = marker_coordinates[2][i]        marker4 = marker_coordinates[3][i]        # Computing vectors between the markers        vector1 = np.array(marker4) - np.array(marker1)        vector2 = np.array(marker3) - np.array(marker2)        # Computing the cross product to get the normal vector        normal_vector = np.cross(vector1, vector2)        # Normalizing the normal vector        normal_vector /= np.linalg.norm(normal_vector)        normal_vectors.append(normal_vector)    return normal_vectors# function to compute normal anglesdef compute_normal_angles(normal_vectors):    angles = []    for normal_vector in normal_vectors:        # Calculate angles with x, y, and z axes        z_angle = np.degrees(np.arccos(np.dot(normal_vector, [0, 0, 1])))        y_angle = np.degrees(np.arccos(np.dot(normal_vector, [0, 1, 0])))        x_angle = np.degrees(np.arccos(np.dot(normal_vector, [1, 0, 0])))        angles.append((x_angle, y_angle, z_angle))    return angles# function to plotdef plot_angle_over_time(angle, time_points, title):    time_points = np.array(time_points)    angle = np.array(angle)    # Subtracting angle at time point 0 from all other time points    angle_at_t0 = angle[0]    angle = angle - angle_at_t0    plt.figure(figsize=(10, 6))    plt.plot(time_points, angle)    plt.title(title)    plt.xlabel('Zeitpunkt')    plt.ylabel('Winkel (in Grad)')    plt.xticks(time_points[::2])      plt.grid(True)    plt.show()# adding coordinatesmarker_coordinates = [Marker1, Marker2, Marker3, Marker4]# time stepstime_points = zeit# computing normal vectorsnormal_vectors = compute_normal_vectors(marker_coordinates)# Computing anglesangles = compute_normal_angles(normal_vectors)# Plotting angles over timefor i, axis_name in enumerate(['X-Achse', 'Y-Achse', 'Z-Achse']):    plot_angle_over_time([angle[i] for angle in angles], time_points, f'Winkel zur {axis_name} über der Zeit')

Viewing all articles
Browse latest Browse all 23247

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>