added txt, data and scripts

This commit is contained in:
Fiedler
2025-09-24 14:28:18 +02:00
parent a169c66e2b
commit f1a812b800
5 changed files with 296 additions and 0 deletions

View File

@ -0,0 +1,49 @@
import pandas as pd
import numpy as np
from pathlib import Path
def load_csv_with_standard_decimal(file_path):
with open(file_path, 'r') as f:
scene_line = f.readline().strip()
scene_name = scene_line.split(': ')[1].split('_')[0]
df = pd.read_csv(file_path, skiprows=1)
return df, scene_name
def calculate_distance(row):
origin = np.array([row['XR_Origin_X'], row['XR_Origin_Y'], row['XR_Origin_Z']])
tracked = np.array([row['TrackedObject_X'], row['TrackedObject_Y'], row['TrackedObject_Z']])
return np.linalg.norm(tracked - origin)
def process_position_data(data_dir):
data_by_scene = {}
all_distances = []
csv_files = list(Path(data_dir).glob('**/P*_PositionData*.csv'))
for file_path in csv_files:
df, scene_name = load_csv_with_standard_decimal(str(file_path))
df['Distance'] = df.apply(calculate_distance, axis=1)
all_distances.extend(df['Distance'])
if scene_name not in data_by_scene:
data_by_scene[scene_name] = []
data_by_scene[scene_name].extend(df['Distance'])
return all_distances, data_by_scene
def print_stats(distances, label):
distances = np.array(distances)
print(f"\n--- {label} ---")
print(f"Count: {len(distances)}")
print(f"Mean: {np.mean(distances):.4f}")
print(f"Std: {np.std(distances):.4f}")
print(f"Min: {np.min(distances):.4f}")
print(f"Max: {np.max(distances):.4f}")
print(f"25th percentile: {np.percentile(distances, 25):.4f}")
print(f"50th percentile (median): {np.percentile(distances, 50):.4f}")
print(f"75th percentile: {np.percentile(distances, 75):.4f}")
def main():
all_distances, data_by_scene = process_position_data('Recordings')
print_stats(all_distances, 'All Scenes Combined')
for scene, distances in data_by_scene.items():
print_stats(distances, f'Scene: {scene}')
if __name__ == "__main__":
main()

View File

@ -0,0 +1,38 @@
import sys
import csv
from pathlib import Path
def fix_decimal_csv(input_path, output_path):
with open(input_path, 'r', newline='', encoding='utf-8') as infile, \
open(output_path, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
# Write the first line (scene name) as is
scene_line = next(reader)
writer.writerow(scene_line)
# Write the header as is (if present)
header = next(reader)
writer.writerow(header)
for row in reader:
# Keep first two columns as is
fixed_row = row[:2]
# Join every pair of columns from the third onward
for i in range(2, len(row), 2):
if i+1 < len(row):
fixed_val = f'{row[i]}.{row[i+1]}'
fixed_row.append(fixed_val)
writer.writerow(fixed_row)
if __name__ == '__main__':
# Find all matching CSVs recursively
root = Path('.')
out_root = root / 'Recordings'
out_root.mkdir(exist_ok=True)
csv_files = list(root.rglob('P*_PositionData*.csv'))
for csv_file in csv_files:
# Compute output path in Recordings dir, preserving subdirs
rel_path = csv_file.relative_to(root)
out_path = out_root / rel_path
out_path.parent.mkdir(parents=True, exist_ok=True)
fix_decimal_csv(csv_file, out_path)
print(f'Corrected file written to: {out_path}')

View File

@ -0,0 +1,75 @@
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
plt.rcParams.update({
'font.size': 16,
'font.family': 'serif',
'axes.labelsize': 18,
'axes.titlesize': 20,
'xtick.labelsize': 14,
'ytick.labelsize': 14,
'legend.fontsize': 14,
'figure.dpi': 300,
'axes.linewidth': 1.5,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.major.size': 6,
'ytick.major.size': 6,
'xtick.minor.size': 3,
'ytick.minor.size': 3,
})
def load_csv_with_standard_decimal(file_path):
with open(file_path, 'r') as f:
scene_line = f.readline().strip()
scene_name = scene_line.split(': ')[1].split('_')[0]
df = pd.read_csv(file_path, skiprows=1)
return df, scene_name
def calculate_distance(row):
origin = np.array([row['XR_Origin_X'], row['XR_Origin_Y'], row['XR_Origin_Z']])
tracked = np.array([row['TrackedObject_X'], row['TrackedObject_Y'], row['TrackedObject_Z']])
return np.linalg.norm(tracked - origin)
def process_position_data(data_dir):
data_by_scene = {}
all_distances = []
csv_files = list(Path(data_dir).glob('**/P*_PositionData*.csv'))
for file_path in csv_files:
df, scene_name = load_csv_with_standard_decimal(str(file_path))
df['Distance'] = df.apply(calculate_distance, axis=1)
all_distances.extend(df['Distance'])
if scene_name not in data_by_scene:
data_by_scene[scene_name] = []
data_by_scene[scene_name].extend(df['Distance'])
return all_distances, data_by_scene
def plot_boxplots(all_distances, data_by_scene):
plt.figure(figsize=(10, 7))
data = [distances for _, distances in sorted(data_by_scene.items())]
labels = [scene for scene in sorted(data_by_scene.keys())]
data = [all_distances] + data
labels = ['All Scenes'] + labels
box = plt.boxplot(
data, labels=labels, showmeans=True, meanline=True, showfliers=False,
boxprops=dict(linewidth=2), whiskerprops=dict(linewidth=2), capprops=dict(linewidth=2),
medianprops=dict(linewidth=2, color='black'), meanprops=dict(linewidth=2, color='C1')
)
plt.ylabel('Distance to Tracked Object (units)')
plt.xlabel('Scene')
plt.title('Distribution of Distances to Tracked Objects by Scene')
plt.xticks(rotation=20)
plt.grid(axis='y', linestyle='--', linewidth=1, alpha=0.7)
plt.tight_layout()
plt.savefig('boxplot_distances.png', dpi=600)
plt.close()
def main():
all_distances, data_by_scene = process_position_data('Recordings')
plot_boxplots(all_distances, data_by_scene)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,76 @@
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
def load_csv_with_standard_decimal(file_path):
with open(file_path, 'r') as f:
scene_line = f.readline().strip()
scene_name = scene_line.split(': ')[1].split('_')[0]
df = pd.read_csv(file_path, skiprows=1)
return df, scene_name
def process_position_data(data_dir):
# Group by scene
scene_data = {}
csv_files = list(Path(data_dir).glob('**/P*_PositionData*.csv'))
for file_path in csv_files:
df, scene_name = load_csv_with_standard_decimal(str(file_path))
if scene_name not in scene_data:
scene_data[scene_name] = []
scene_data[scene_name].append(df)
return scene_data
def plot_relative_positions(scene_data):
scenes = list(scene_data.keys())
# Create one figure with 4 subplots
fig, axes = plt.subplots(2, 2, figsize=(16, 14))
axes = axes.flatten()
for idx, (scene, recordings) in enumerate(scene_data.items()):
all_rel_x = []
all_rel_z = []
avg_obj_xs = []
avg_obj_zs = []
for df in recordings:
obj_x = df['TrackedObject_X'].values
obj_z = df['TrackedObject_Z'].values
avg_obj_x = np.mean(obj_x)
avg_obj_z = np.mean(obj_z)
avg_obj_xs.append(avg_obj_x)
avg_obj_zs.append(avg_obj_z)
rel_x = df['XR_Origin_X'].values - avg_obj_x
rel_z = df['XR_Origin_Z'].values - avg_obj_z
all_rel_x.extend(rel_x)
all_rel_z.extend(rel_z)
ax = axes[idx]
ax.scatter(all_rel_x, all_rel_z, alpha=0.2, c='blue', label='Player Positions (relative)')
ax.scatter(0, 0, c='red', s=800, marker='*', label='Agent', edgecolor='black', linewidths=2, zorder=10)
ax.set_title(f'Scene: {scene}')
ax.set_xlabel('X Position (relative to Agent)')
ax.set_ylabel('Z Position (relative to Agent)')
ax.legend()
ax.axis('equal')
ax.grid(True, linestyle='--', alpha=0.7)
# Also save individual images
plt.figure(figsize=(8, 8))
plt.scatter(all_rel_x, all_rel_z, alpha=0.2, c='blue', label='Player Positions (relative)')
plt.scatter(0, 0, c='red', s=800, marker='*', label='Agent', edgecolor='black', linewidths=2, zorder=10)
plt.title(f'Player Positions Relative to Agent\nScene: {scene}')
plt.xlabel('X Position (relative to Agent)')
plt.ylabel('Z Position (relative to Agent)')
plt.legend()
plt.axis('equal')
plt.grid(True, linestyle='--', alpha=0.7)
plt.tight_layout()
plt.savefig(f'room_layout_{scene}.png', dpi=300)
plt.close()
plt.tight_layout()
plt.savefig('room_layout_all_scenes.png', dpi=300)
plt.close()
def main():
scene_data = process_position_data('Recordings')
plot_relative_positions(scene_data)
if __name__ == "__main__":
main()