Motion Analysis and Visualization Script

A Python script that reads motion data from CSV files, computes spatial metrics like the center of position and average distance from the center over time, performs Lomb-Scargle periodogram analysis, and saves analyzed results as Numpy arrays. It utilizes libraries such as Pandas for data manipulation, Matplotlib and mplEasyAnimate for visualization, and Scipy for signal processing.

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from tqdm import tqdm
import numpy as np
from mplEasyAnimate import animation
from scipy.signal import lombscargle
import os
 
def frameToArray(frame):
    start = 1
    vecs = np.zeros(shape=(int((frame.shape[0]-1)/3), 3))
    for itr, end in enumerate(range(4, frame.shape[0]+3, 3)):
        vecs[itr] = np.array(frame[start:end])
        start = end
    return vecs
 
def CalcCenterOfPos(frame):
    vecs = frameToArray(frame)
    return vecs.mean(axis=0)
 
def CenterOfPosEvolution(df):
    COPs = np.zeros(shape=(df.shape[0], 3))
    times = df['Time'].values
    for itr, frame in tqdm(df.iterrows(), total=df.shape[0]):
        COPs[itr] = CalcCenterOfPos(frame)
    return COPs, times
 
def getAvgPosFromCenter(frame):
    COP = CalcCenterOfPos(frame)
    vecs = frameToArray(frame)
    return np.abs(vecs-COP).mean(axis=0)
 
def getAvgDistFromCenter(frame):
    COP = CalcCenterOfPos(frame)
    vecs = frameToArray(frame)
    return np.mean(np.sqrt(np.sum(np.power(np.subtract(COP, vecs), 2), axis=1)))
 
def evolveAvgPosFromCenter(df):
    SEPs = np.zeros(shape=(df.shape[0], 3))
    times = df['Time'].values
    for itr, frame in tqdm(df.iterrows(), total=df.shape[0]):
        SEPs[itr] = getAvgPosFromCenter(frame)
    return SEPs, times
 
def evolveAvgDistFromCenter(df):
    SEPs = np.zeros(shape=(df.shape[0],))
    times = df['Time'].values
    for itr, frame in tqdm(df.iterrows(), total=df.shape[0]):
        SEPs[itr] = getAvgDistFromCenter(frame)
    return SEPs, times
 
def genLSP(t, y, s=None):
    nyquist = 1/(2*(t[1]-t[0]))
    res = (t[1]-t[0])/t.shape[0]
    if not s:
        s = int(1/res)
    f = 2*np.pi*np.linspace(res/10, 0.5, s)
    pgram = lombscargle(t, y, f, normalize=True)
    return f, pgram
 
if __name__ == "__main__":
    root = "Downloaded_Data/CSVs"
    files = os.listdir(root)
    files = [x for x in files if x[0] != '.']
 
    for file in tqdm(files):
        df = pd.read_csv('{}/{}'.format(root, file), header=6)
        df = df.rename(columns={ df.columns[0]: "Time" })
        SEPs, times = evolveAvgDistFromCenter(df)
 
        name = file.split('.')[0]
        np.save('AnalyzedData/AvgDistFromCenter_{}.npy'.format(name), np.vstack([times, SEPs]))