blob: 48cc8bc9cdba25d813881615d6182b8da1e9819f [file] [log] [blame]
Austin Schuhd1b28992014-10-26 20:55:06 -07001#!/usr/bin/python3
Philipp Schrader7861dce2015-02-23 00:27:59 +00002import matplotlib
3from matplotlib import pylab
Philipp Schrader0db60452015-03-15 07:32:38 +00004from matplotlib.font_manager import FontProperties
Philipp Schrader7861dce2015-02-23 00:27:59 +00005
6class Dataset(object):
7 def __init__(self):
8 self.time = []
9 self.data = []
10
11 def Add(self, time, data):
12 self.time.append(time)
13 self.data.append(data)
14
15
16class Plotter(object):
17 def __init__(self):
18 self.signal = dict()
19
20 def Add(self, binary, struct_instance_name, *data_search_path):
21 """
22 Specifies a specific piece of data to plot
23
24 Args:
25 binary: str, The name of the executable that generated the log.
26 struct_instance_name: str, The name of the struct instance whose data
27 contents should be plotted.
28 data_search_path: [str], The path into the struct of the exact piece of
29 data to plot.
30
31 Returns:
32 None
33 """
34 self.signal[(binary, struct_instance_name, data_search_path)] = Dataset()
35
36 def HandleLine(self, line):
37 """
38 Parses a line from a log file and adds the data to the plot data.
39
40 Args:
41 line: str, The line from the log file to parse
42
43 Returns:
44 None
45 """
46 pline = ParseLine(line)
Dave Smithbf4c9902016-02-18 14:30:55 -080047 pline_data = None
48
Philipp Schrader7861dce2015-02-23 00:27:59 +000049 for key in self.signal:
50 value = self.signal[key]
51 binary = key[0]
52 struct_instance_name = key[1]
53 data_search_path = key[2]
Philipp Schrader26681bc2015-04-02 04:25:30 +000054 boolean_multiplier = None
55
56 # If the plot definition line ends with a "-b X" where X is a number then
57 # that number gets drawn when the value is True. Zero gets drawn when the
58 # value is False.
59 if len(data_search_path) >= 2 and data_search_path[-2] == '-b':
60 boolean_multiplier = float(data_search_path[-1])
61 data_search_path = data_search_path[:-2]
Philipp Schrader7861dce2015-02-23 00:27:59 +000062
63 # Make sure that we're looking at the right binary structure instance.
64 if binary == pline.name:
65 if pline.msg.startswith(struct_instance_name + ': '):
Dave Smithbf4c9902016-02-18 14:30:55 -080066 # Parse the structure once.
67 if pline_data is None:
68 _, _, pline_data = pline.ParseStruct()
69 # Traverse the structure as specified in `data_search_path`.
70 # This lets the user access very deeply nested structures.
71 data = pline_data
Philipp Schrader7861dce2015-02-23 00:27:59 +000072 for path in data_search_path:
73 data = data[path]
74
Philipp Schrader26681bc2015-04-02 04:25:30 +000075 if boolean_multiplier is not None:
76 if data == 'T':
77 value.Add(pline.time, boolean_multiplier)
78 else:
79 value.Add(pline.time, 0)
80 else:
81 value.Add(pline.time, data)
Philipp Schrader7861dce2015-02-23 00:27:59 +000082
Philipp Schrader0db60452015-03-15 07:32:38 +000083 def Plot(self, no_binary_in_legend):
Philipp Schrader7861dce2015-02-23 00:27:59 +000084 """
85 Plots all the data after it's parsed.
86
87 This should only be called after `HandleFile` has been called so that there
88 is actual data to plot.
89 """
90 for key in self.signal:
91 value = self.signal[key]
Philipp Schrader0db60452015-03-15 07:32:38 +000092
93 # Create a legend label using the binary name (optional), the structure
94 # name and the data search path.
95 label = key[1] + '.' + '.'.join(key[2])
96 if not no_binary_in_legend:
97 label = key[0] + ' ' + label
98
99 pylab.plot(value.time, value.data, label=label)
100
101 # Set legend font size to small and move it to the top center.
102 fontP = FontProperties()
103 fontP.set_size('small')
104 pylab.legend(bbox_to_anchor=(0.5, 1.05), prop=fontP)
105
Philipp Schrader7861dce2015-02-23 00:27:59 +0000106 pylab.show()
107
Philipp Schrader0db60452015-03-15 07:32:38 +0000108 def PlotFile(self, f, no_binary_in_legend=False):
Philipp Schrader7861dce2015-02-23 00:27:59 +0000109 """
110 Parses and plots all the data.
111
112 Args:
113 f: str, The filename of the log whose data to parse and plot.
114
115 Returns:
116 None
117 """
118 self.HandleFile(f)
Philipp Schrader0db60452015-03-15 07:32:38 +0000119 self.Plot(no_binary_in_legend)
Philipp Schrader7861dce2015-02-23 00:27:59 +0000120
121 def HandleFile(self, f):
122 """
123 Parses the specified log file.
124
125 Args:
126 f: str, The filename of the log whose data to parse.
127
128 Returns:
129 None
130 """
131 with open(f, 'r') as fd:
132 for line in fd:
133 self.HandleLine(line)
134
Austin Schuhd1b28992014-10-26 20:55:06 -0700135
136class LogEntry:
137 """This class provides a way to parse log entries."""
138
139 def __init__(self, line):
140 """Creates a LogEntry from a line."""
141 name_index = line.find('(')
142 self.name = line[0:name_index]
143
144 pid_index = line.find(')', name_index + 1)
145 self.pid = int(line[name_index + 1:pid_index])
146
147 msg_index_index = line.find(')', pid_index + 1)
148 self.msg_index = int(line[pid_index + 2:msg_index_index])
149
150 level_index = line.find(' ', msg_index_index + 3)
151 self.level = line[msg_index_index + 3:level_index]
152
153 time_index_start = line.find(' at ', level_index) + 4
154 time_index_end = line.find('s:', level_index)
155 self.time = float(line[time_index_start:time_index_end])
156
157 filename_end = line.find(':', time_index_end + 3)
158 self.filename = line[time_index_end + 3:filename_end]
159
160 linenumber_end = line.find(':', filename_end + 2)
161 self.linenumber = int(line[filename_end + 2:linenumber_end])
162
163 self.msg = line[linenumber_end+2:]
164
165 def __str__(self):
166 """Formats the data cleanly."""
167 return '%s(%d)(%d): %s at %fs: %s: %d: %s' % (self.name, self.pid, self.msg_index, self.level, self.time, self.filename, self.linenumber, self.msg)
168
169 def __JsonizeTokenArray(self, sub_array, tokens, token_index):
170 """Parses an array from the provided tokens.
171
172 Args:
173 sub_array: list, The list to stick the elements in.
174 tokens: list of strings, The list with all the tokens in it.
175 token_index: int, Where to start in the token list.
176
177 Returns:
178 int, The last token used.
179 """
180 # Make sure the data starts with a '['
181 if tokens[token_index] != '[':
182 print(tokens)
183 print('Expected [ at beginning, found', tokens[token_index + 1])
184 return None
185
186 # Eat the '['
187 token_index += 1
188
189 # Loop through the tokens.
190 while token_index < len(tokens):
191 if tokens[token_index + 1] == ',':
192 # Next item is a comma, so we should just add the element.
193 sub_array.append(tokens[token_index])
194 token_index += 2
195 elif tokens[token_index + 1] == ']':
196 # Next item is a ']', so we should just add the element and finish.
197 sub_array.append(tokens[token_index])
198 token_index += 1
199 return token_index
200 else:
201 # Otherwise, it must be a sub-message.
202 sub_json = dict()
203 token_index = self.JsonizeTokens(sub_json, tokens, token_index + 1)
204 sub_array.append(sub_json)
205 if tokens[token_index] == ',':
206 # Handle there either being another data element.
207 token_index += 1
208 elif tokens[token_index] == ']':
209 # Handle the end of the array.
210 return token_index
211 else:
212 print('Unexpected ', tokens[token_index])
213 return None
214
215 print('Unexpected end')
216 return None
217
218 def JsonizeTokens(self, json, tokens, token_index):
219 """Creates a json-like dictionary from the provided tokens.
220
221 Args:
222 json: dict, The dict to stick the elements in.
223 tokens: list of strings, The list with all the tokens in it.
224 token_index: int, Where to start in the token list.
225
226 Returns:
227 int, The last token used.
228 """
229 # Check that the message starts with a {
230 if tokens[token_index] != '{':
231 print(tokens)
232 print('Expected { at beginning, found', tokens[token_index])
233 return None
234
235 # Eat the {
236 token_index += 1
237
238 # States and state variable for parsing elements.
239 STATE_INIT = 'init'
240 STATE_HAS_NAME = 'name'
241 STATE_HAS_COLON = 'colon'
242 STATE_EXPECTING_SUBMSG = 'submsg'
243 STATE_EXPECTING_COMMA = 'comma'
244 parser_state = STATE_INIT
245
246 while token_index < len(tokens):
247 if tokens[token_index] == '}':
248 # Finish if there is a }
249 return token_index + 1
250 elif tokens[token_index] == '{':
251 if parser_state != STATE_EXPECTING_SUBMSG:
252 print(tokens)
253 print(parser_state)
254 print('Bad input, was not expecting {')
255 return None
256 # Found a submessage, parse it.
257 sub_json = dict()
258 token_index = self.JsonizeTokens(sub_json, tokens, token_index)
259 json[token_name] = sub_json
260 parser_state = STATE_EXPECTING_COMMA
261 else:
262 if parser_state == STATE_INIT:
263 # This token is the name.
264 token_name = tokens[token_index]
265 parser_state = STATE_HAS_NAME
266 elif parser_state == STATE_HAS_NAME:
267 if tokens[token_index] != ':':
268 print(tokens)
269 print(parser_state)
270 print('Bad input, found', tokens[token_index], 'expected :')
271 return None
272 # After a name, comes a :
273 parser_state = STATE_HAS_COLON
274 elif parser_state == STATE_HAS_COLON:
275 # After the colon, figure out what is next.
276 if tokens[token_index] == '[':
277 # Found a sub-array!
278 sub_array = []
279 token_index = self.__JsonizeTokenArray(sub_array, tokens, token_index)
280 json[token_name] = sub_array
281 parser_state = STATE_EXPECTING_COMMA
282 elif tokens[token_index + 1] == '{':
283 # Found a sub-message, trigger parsing it.
284 parser_state = STATE_EXPECTING_SUBMSG
285 else:
286 # This is just an element, move on.
287 json[token_name] = tokens[token_index]
288 parser_state = STATE_EXPECTING_COMMA
289 elif parser_state == STATE_EXPECTING_COMMA:
290 # Complain if there isn't a comma here.
291 if tokens[token_index] != ',':
292 print(tokens)
293 print(parser_state)
294 print('Bad input, found', tokens[token_index], 'expected ,')
295 return None
296 parser_state = STATE_INIT
297 else:
298 print('Bad parser state')
299 return None
300 token_index += 1
301
302 print('Unexpected end')
303 return None
304
305 def ParseStruct(self):
306 """Parses the message as a structure.
307
308 Returns:
309 struct_name, struct_type, json dict.
310 """
311 struct_name_index = self.msg.find(':')
312 struct_name = self.msg[0:struct_name_index]
313
314 struct_body = self.msg[struct_name_index+2:]
315 tokens = []
316 this_token = ''
317 # For the various deliminators, append what we have found so far to the
318 # list and the token.
319 for char in struct_body:
320 if char == '{':
321 if this_token:
322 tokens.append(this_token)
323 this_token = ''
324 tokens.append('{')
325 elif char == '}':
326 if this_token:
327 tokens.append(this_token)
328 this_token = ''
329 tokens.append('}')
330 elif char == '[':
331 if this_token:
332 tokens.append(this_token)
333 this_token = ''
334 tokens.append('[')
335 elif char == ']':
336 if this_token:
337 tokens.append(this_token)
338 this_token = ''
339 tokens.append(']')
340 elif char == ':':
341 if this_token:
342 tokens.append(this_token)
343 this_token = ''
344 tokens.append(':')
345 elif char == ',':
346 if this_token:
347 tokens.append(this_token)
348 this_token = ''
349 tokens.append(',')
350 elif char == ' ':
351 if this_token:
352 tokens.append(this_token)
353 this_token = ''
354 else:
355 this_token += char
356 if this_token:
357 tokens.append(this_token)
358
359 struct_type = tokens[0]
360 json = dict()
361 # Now that we have tokens, parse them.
362 self.JsonizeTokens(json, tokens, 1)
363
364 return (struct_name, struct_type, json)
365
366
367def ParseLine(line):
368 return LogEntry(line)
369
370if __name__ == '__main__':
371 print('motor_writer(2240)(07421): DEBUG at 0000000819.99620s: ../../frc971/output/motor_writer.cc: 105: sending: .aos.controls.OutputCheck{pwm_value:221, pulse_length:2.233333}')
372 line = ParseLine('motor_writer(2240)(07421): DEBUG at 0000000819.99620s: ../../frc971/output/motor_writer.cc: 105: sending: .aos.controls.OutputCheck{pwm_value:221, pulse_length:2.233333}')
373 if '.aos.controls.OutputCheck' in line.msg:
374 print(line)
375 print(line.ParseStruct())
376
377 line = ParseLine('claw(2263)(19404): DEBUG at 0000000820.00000s: ../../aos/common/controls/control_loop-tmpl.h: 104: position: .frc971.control_loops.ClawGroup.Position{top:.frc971.control_loops.HalfClawPosition{position:1.672153, front:.frc971.HallEffectStruct{current:f, posedge_count:0, negedge_count:52}, calibration:.frc971.HallEffectStruct{current:f, posedge_count:6, negedge_count:13}, back:.frc971.HallEffectStruct{current:f, posedge_count:0, negedge_count:62}, posedge_value:0.642681, negedge_value:0.922207}, bottom:.frc971.control_loops.HalfClawPosition{position:1.353539, front:.frc971.HallEffectStruct{current:f, posedge_count:2, negedge_count:150}, calibration:.frc971.HallEffectStruct{current:f, posedge_count:8, negedge_count:18}, back:.frc971.HallEffectStruct{current:f, posedge_count:0, negedge_count:6}, posedge_value:0.434514, negedge_value:0.759491}}')
378 print(line.ParseStruct())
379
380 line = ParseLine('joystick_proxy(2255)(39560): DEBUG at 0000000820.00730s: ../../aos/prime/input/joystick_input.cc: 61: sending: .aos.RobotState{joysticks:[.aos.Joystick{buttons:0, axis:[0.000000, 1.000000, 1.000000, 0.000000]}, .aos.Joystick{buttons:0, axis:[-0.401575, 1.000000, -1.007874, 0.000000]}, .aos.Joystick{buttons:0, axis:[0.007874, 0.000000, 1.000000, -1.007874]}, .aos.Joystick{buttons:0, axis:[0.000000, 0.000000, 0.000000, 0.000000]}], test_mode:f, fms_attached:f, enabled:T, autonomous:f, team_id:971, fake:f}')
381 print(line.ParseStruct())