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