blob: 66a4dd44f50a6341dfd29e293a7dff4c9e85d066 [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)
47 for key in self.signal:
48 value = self.signal[key]
49 binary = key[0]
50 struct_instance_name = key[1]
51 data_search_path = key[2]
52
53 # Make sure that we're looking at the right binary structure instance.
54 if binary == pline.name:
55 if pline.msg.startswith(struct_instance_name + ': '):
56 # Parse the structure and traverse it as specified in
57 # `data_search_path`. This lets the user access very deeply nested
58 # structures.
59 _, _, data = pline.ParseStruct()
60 for path in data_search_path:
61 data = data[path]
62
63 value.Add(pline.time, data)
64
Philipp Schrader0db60452015-03-15 07:32:38 +000065 def Plot(self, no_binary_in_legend):
Philipp Schrader7861dce2015-02-23 00:27:59 +000066 """
67 Plots all the data after it's parsed.
68
69 This should only be called after `HandleFile` has been called so that there
70 is actual data to plot.
71 """
72 for key in self.signal:
73 value = self.signal[key]
Philipp Schrader0db60452015-03-15 07:32:38 +000074
75 # Create a legend label using the binary name (optional), the structure
76 # name and the data search path.
77 label = key[1] + '.' + '.'.join(key[2])
78 if not no_binary_in_legend:
79 label = key[0] + ' ' + label
80
81 pylab.plot(value.time, value.data, label=label)
82
83 # Set legend font size to small and move it to the top center.
84 fontP = FontProperties()
85 fontP.set_size('small')
86 pylab.legend(bbox_to_anchor=(0.5, 1.05), prop=fontP)
87
Philipp Schrader7861dce2015-02-23 00:27:59 +000088 pylab.show()
89
Philipp Schrader0db60452015-03-15 07:32:38 +000090 def PlotFile(self, f, no_binary_in_legend=False):
Philipp Schrader7861dce2015-02-23 00:27:59 +000091 """
92 Parses and plots all the data.
93
94 Args:
95 f: str, The filename of the log whose data to parse and plot.
96
97 Returns:
98 None
99 """
100 self.HandleFile(f)
Philipp Schrader0db60452015-03-15 07:32:38 +0000101 self.Plot(no_binary_in_legend)
Philipp Schrader7861dce2015-02-23 00:27:59 +0000102
103 def HandleFile(self, f):
104 """
105 Parses the specified log file.
106
107 Args:
108 f: str, The filename of the log whose data to parse.
109
110 Returns:
111 None
112 """
113 with open(f, 'r') as fd:
114 for line in fd:
115 self.HandleLine(line)
116
Austin Schuhd1b28992014-10-26 20:55:06 -0700117
118class LogEntry:
119 """This class provides a way to parse log entries."""
120
121 def __init__(self, line):
122 """Creates a LogEntry from a line."""
123 name_index = line.find('(')
124 self.name = line[0:name_index]
125
126 pid_index = line.find(')', name_index + 1)
127 self.pid = int(line[name_index + 1:pid_index])
128
129 msg_index_index = line.find(')', pid_index + 1)
130 self.msg_index = int(line[pid_index + 2:msg_index_index])
131
132 level_index = line.find(' ', msg_index_index + 3)
133 self.level = line[msg_index_index + 3:level_index]
134
135 time_index_start = line.find(' at ', level_index) + 4
136 time_index_end = line.find('s:', level_index)
137 self.time = float(line[time_index_start:time_index_end])
138
139 filename_end = line.find(':', time_index_end + 3)
140 self.filename = line[time_index_end + 3:filename_end]
141
142 linenumber_end = line.find(':', filename_end + 2)
143 self.linenumber = int(line[filename_end + 2:linenumber_end])
144
145 self.msg = line[linenumber_end+2:]
146
147 def __str__(self):
148 """Formats the data cleanly."""
149 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)
150
151 def __JsonizeTokenArray(self, sub_array, tokens, token_index):
152 """Parses an array from the provided tokens.
153
154 Args:
155 sub_array: list, The list to stick the elements in.
156 tokens: list of strings, The list with all the tokens in it.
157 token_index: int, Where to start in the token list.
158
159 Returns:
160 int, The last token used.
161 """
162 # Make sure the data starts with a '['
163 if tokens[token_index] != '[':
164 print(tokens)
165 print('Expected [ at beginning, found', tokens[token_index + 1])
166 return None
167
168 # Eat the '['
169 token_index += 1
170
171 # Loop through the tokens.
172 while token_index < len(tokens):
173 if tokens[token_index + 1] == ',':
174 # Next item is a comma, so we should just add the element.
175 sub_array.append(tokens[token_index])
176 token_index += 2
177 elif tokens[token_index + 1] == ']':
178 # Next item is a ']', so we should just add the element and finish.
179 sub_array.append(tokens[token_index])
180 token_index += 1
181 return token_index
182 else:
183 # Otherwise, it must be a sub-message.
184 sub_json = dict()
185 token_index = self.JsonizeTokens(sub_json, tokens, token_index + 1)
186 sub_array.append(sub_json)
187 if tokens[token_index] == ',':
188 # Handle there either being another data element.
189 token_index += 1
190 elif tokens[token_index] == ']':
191 # Handle the end of the array.
192 return token_index
193 else:
194 print('Unexpected ', tokens[token_index])
195 return None
196
197 print('Unexpected end')
198 return None
199
200 def JsonizeTokens(self, json, tokens, token_index):
201 """Creates a json-like dictionary from the provided tokens.
202
203 Args:
204 json: dict, The dict to stick the elements in.
205 tokens: list of strings, The list with all the tokens in it.
206 token_index: int, Where to start in the token list.
207
208 Returns:
209 int, The last token used.
210 """
211 # Check that the message starts with a {
212 if tokens[token_index] != '{':
213 print(tokens)
214 print('Expected { at beginning, found', tokens[token_index])
215 return None
216
217 # Eat the {
218 token_index += 1
219
220 # States and state variable for parsing elements.
221 STATE_INIT = 'init'
222 STATE_HAS_NAME = 'name'
223 STATE_HAS_COLON = 'colon'
224 STATE_EXPECTING_SUBMSG = 'submsg'
225 STATE_EXPECTING_COMMA = 'comma'
226 parser_state = STATE_INIT
227
228 while token_index < len(tokens):
229 if tokens[token_index] == '}':
230 # Finish if there is a }
231 return token_index + 1
232 elif tokens[token_index] == '{':
233 if parser_state != STATE_EXPECTING_SUBMSG:
234 print(tokens)
235 print(parser_state)
236 print('Bad input, was not expecting {')
237 return None
238 # Found a submessage, parse it.
239 sub_json = dict()
240 token_index = self.JsonizeTokens(sub_json, tokens, token_index)
241 json[token_name] = sub_json
242 parser_state = STATE_EXPECTING_COMMA
243 else:
244 if parser_state == STATE_INIT:
245 # This token is the name.
246 token_name = tokens[token_index]
247 parser_state = STATE_HAS_NAME
248 elif parser_state == STATE_HAS_NAME:
249 if tokens[token_index] != ':':
250 print(tokens)
251 print(parser_state)
252 print('Bad input, found', tokens[token_index], 'expected :')
253 return None
254 # After a name, comes a :
255 parser_state = STATE_HAS_COLON
256 elif parser_state == STATE_HAS_COLON:
257 # After the colon, figure out what is next.
258 if tokens[token_index] == '[':
259 # Found a sub-array!
260 sub_array = []
261 token_index = self.__JsonizeTokenArray(sub_array, tokens, token_index)
262 json[token_name] = sub_array
263 parser_state = STATE_EXPECTING_COMMA
264 elif tokens[token_index + 1] == '{':
265 # Found a sub-message, trigger parsing it.
266 parser_state = STATE_EXPECTING_SUBMSG
267 else:
268 # This is just an element, move on.
269 json[token_name] = tokens[token_index]
270 parser_state = STATE_EXPECTING_COMMA
271 elif parser_state == STATE_EXPECTING_COMMA:
272 # Complain if there isn't a comma here.
273 if tokens[token_index] != ',':
274 print(tokens)
275 print(parser_state)
276 print('Bad input, found', tokens[token_index], 'expected ,')
277 return None
278 parser_state = STATE_INIT
279 else:
280 print('Bad parser state')
281 return None
282 token_index += 1
283
284 print('Unexpected end')
285 return None
286
287 def ParseStruct(self):
288 """Parses the message as a structure.
289
290 Returns:
291 struct_name, struct_type, json dict.
292 """
293 struct_name_index = self.msg.find(':')
294 struct_name = self.msg[0:struct_name_index]
295
296 struct_body = self.msg[struct_name_index+2:]
297 tokens = []
298 this_token = ''
299 # For the various deliminators, append what we have found so far to the
300 # list and the token.
301 for char in struct_body:
302 if char == '{':
303 if this_token:
304 tokens.append(this_token)
305 this_token = ''
306 tokens.append('{')
307 elif char == '}':
308 if this_token:
309 tokens.append(this_token)
310 this_token = ''
311 tokens.append('}')
312 elif char == '[':
313 if this_token:
314 tokens.append(this_token)
315 this_token = ''
316 tokens.append('[')
317 elif char == ']':
318 if this_token:
319 tokens.append(this_token)
320 this_token = ''
321 tokens.append(']')
322 elif char == ':':
323 if this_token:
324 tokens.append(this_token)
325 this_token = ''
326 tokens.append(':')
327 elif char == ',':
328 if this_token:
329 tokens.append(this_token)
330 this_token = ''
331 tokens.append(',')
332 elif char == ' ':
333 if this_token:
334 tokens.append(this_token)
335 this_token = ''
336 else:
337 this_token += char
338 if this_token:
339 tokens.append(this_token)
340
341 struct_type = tokens[0]
342 json = dict()
343 # Now that we have tokens, parse them.
344 self.JsonizeTokens(json, tokens, 1)
345
346 return (struct_name, struct_type, json)
347
348
349def ParseLine(line):
350 return LogEntry(line)
351
352if __name__ == '__main__':
353 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}')
354 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}')
355 if '.aos.controls.OutputCheck' in line.msg:
356 print(line)
357 print(line.ParseStruct())
358
359 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}}')
360 print(line.ParseStruct())
361
362 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}')
363 print(line.ParseStruct())