yincheng.zhong
3 天以前 26db5e14522173c274ac954c867d2ebe5d8ca3ac
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""
viz.py
 
读取 sim_log.csv(由 test.py 生成)并用 matplotlib 动画显示:
- 主图:路径点(`example_path.json`)和割草机当前位置/航向箭头
- 下方两个子图:forward_sig 与 turn_sig 随时间的曲线,当前帧用竖线标示
 
运行:
    python viz.py
 
如果没有 `sim_log.csv`,脚本会提示先运行 `test.py` 生成数据。
"""
import os
import json
import csv
import sys
from math import cos, sin
import numpy as np
 
try:
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
except Exception as e:
    print('matplotlib required. Install with: pip install matplotlib')
    raise
 
 
SIM_CSV = 'sim_log.csv'
PATH_FILE = 'example_path.json'
 
 
def load_sim(csv_path=SIM_CSV):
    if not os.path.exists(csv_path):
        print(f"Sim log '{csv_path}' not found. Run test.py first to generate it.")
        sys.exit(1)
    t, xs, ys, headings, forward_sig, turn_sig = [], [], [], [], [], []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            t.append(float(row['t']))
            xs.append(float(row['x']))
            ys.append(float(row['y']))
            headings.append(float(row['heading']))
            forward_sig.append(int(row['forward_sig']))
            turn_sig.append(int(row['turn_sig']))
    return {'t': t, 'x': xs, 'y': ys, 'heading': headings, 'forward': forward_sig, 'turn': turn_sig}
 
 
def load_path(pth=PATH_FILE):
    if not os.path.exists(pth):
        return []
    with open(pth, 'r') as f:
        return json.load(f)
 
 
def animate_sim(simdata, path):
    t = simdata['t']
    x = simdata['x']
    y = simdata['y']
    h = simdata['heading']
    fwd = simdata['forward']
    trn = simdata['turn']
 
    fig = plt.figure(figsize=(10, 8))
    gs = fig.add_gridspec(3, 1, height_ratios=[3, 1, 1])
 
    ax_map = fig.add_subplot(gs[0])
    ax_f = fig.add_subplot(gs[1])
    ax_t = fig.add_subplot(gs[2])
 
    # map plot
    if path:
        px = [p[0] for p in path]
        py = [p[1] for p in path]
        ax_map.plot(px, py, '-k', lw=1, label='planned path')
        ax_map.scatter(px, py, c='k', s=10)
 
    line_pos, = ax_map.plot([], [], '-r', lw=2, label='actual')
    point_pos, = ax_map.plot([], [], 'ro')
    # heading arrow using quiver (initialize at first pose if available)
    if len(x) > 0 and len(h) > 0:
        quiv = ax_map.quiver([x[0]], [y[0]], [cos(h[0])], [sin(h[0])], angles='xy', scale_units='xy', scale=4, color='b')
    else:
        quiv = ax_map.quiver([0], [0], [1], [0], angles='xy', scale_units='xy', scale=4, color='b')
 
    ax_map.set_aspect('equal', 'box')
    ax_map.set_title('Mower path and pose')
    ax_map.legend()
 
    # forward subplot
    ax_f.plot(t, fwd, color='gray', alpha=0.5)
    f_line = ax_f.axvline(t[0], color='r')
    ax_f.set_ylabel('forward_sig')
 
    # turn subplot
    ax_t.plot(t, trn, color='gray', alpha=0.5)
    t_line = ax_t.axvline(t[0], color='r')
    ax_t.set_ylabel('turn_sig')
    ax_t.set_xlabel('time (s)')
 
    # set map limits
    margin = 1.0
    all_x = x + ( [p[0] for p in path] if path else [] )
    all_y = y + ( [p[1] for p in path] if path else [] )
    if all_x and all_y:
        ax_map.set_xlim(min(all_x)-margin, max(all_x)+margin)
        ax_map.set_ylim(min(all_y)-margin, max(all_y)+margin)
 
    def init():
        line_pos.set_data([], [])
        point_pos.set_data([], [])
        return line_pos, point_pos, quiv, f_line, t_line
 
    def update(i):
        # i is frame index
        xi = x[:i+1]
        yi = y[:i+1]
        line_pos.set_data(xi, yi)
        point_pos.set_data([x[i]], [y[i]])
 
        # update quiver in-place
        hx = cos(h[i])
        hy = sin(h[i])
        # set new offset and vector
        quiv.set_offsets(np.array([[x[i], y[i]]]))
        quiv.set_UVC(np.array([hx]), np.array([hy]))
 
        # update vertical lines
        f_line.set_xdata(t[i])
        t_line.set_xdata(t[i])
 
        return line_pos, point_pos, quiv, f_line, t_line
 
    interval_ms = max(10, int(1000.0 / 74.0))
    ani = FuncAnimation(fig, update, frames=len(t), init_func=init, blit=False, interval=interval_ms)
    plt.tight_layout()
    plt.show()
 
 
def main():
    sim = load_sim()
    path = load_path()
    animate_sim(sim, path)
 
 
if __name__ == '__main__':
    main()