From 7c754858a0054f1da1e35d01f5a8075f6196698d Mon Sep 17 00:00:00 2001 From: =?utf8?q?Luk=C3=A1=C5=A1=20Ji=C5=99i=C5=A1t=C4=9B?= Date: Fri, 5 Dec 2025 09:33:26 +0100 Subject: [PATCH] Add a convenient way to show simulation results --- animate_result.py | 73 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100755 animate_result.py diff --git a/animate_result.py b/animate_result.py new file mode 100755 index 0000000..2052ef4 --- /dev/null +++ b/animate_result.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 + +import matplotlib.pyplot as plt +import numpy as np +import matplotlib.animation as animation +import scipy as scp + +class ExtLine: + + def __init__(self, line, name_x, name_y): + self.line = line; + self.name_x = name_x; + self.name_y = name_y; + +class MatAnimation: + + def __init__(self, data_dict = dict()): + self.data = data_dict; + self.lines = []; + self.fig, self.axes = plt.subplots(); + + def plot(self, name_x, name_y): + self.lines.append( + ExtLine( + self.axes.plot(self.data[name_x], self.data[name_y])[0], + name_x, + name_y)); + + def show(self): + self.animation = animation.FuncAnimation( + self.fig, self.update, len(self.data["time"]), + interval = 1); + plt.show(); + + def update(self, frame): + for line in self.lines: + line.line.set_xdata(self.data[line.name_x][:frame]); + line.line.set_ydata(self.data[line.name_y][:frame]); + return [line.line for line in self.lines]; + +def transpose_strings(array): + res_array = [[] for i in range(0, np.strings.str_len(array[0]))]; + for i in range(0, array.size): + row = array[i]; + for j in range(0, np.strings.str_len(row)): + if row[j] != '\x00': + res_array[j].append(row[j]); + for i in range(0, len(res_array)): + res_array[i] = ''.join(res_array[i]); + return (res_array); + +# datadict from global scope +def plot(name_x, name_y): + return (plt.plot(datadict[name_x], datadict[name_y])); + +def update(frame): + line.set_xdata(datadict[name_x][frame]); + line.set_ydata(datadict[name_y][frame]); + + +data = scp.io.loadmat("nbody.System_res.mat"); +names = transpose_strings(data["name"]); +descriptions = transpose_strings(data["description"]); +pure_data = data["data_2"]; +inds = data["dataInfo"][1]; +ani = MatAnimation(); +for i in inds: + ani.data[names[i - 1]] = pure_data[i - 1, :-1]; +ani.plot("p[1].pos[1]", "p[1].pos[2]"); +ani.plot("p[2].pos[1]", "p[2].pos[2]"); +ani.plot("p[3].pos[1]", "p[3].pos[2]"); +ani.plot("p[4].pos[1]", "p[4].pos[2]"); +ani.show(); -- 2.30.2