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