blob: 124968f9efa4493a4d7d9d1506684ffd8fd34f09 [file] [log] [blame]
James Kuszmaul61a971f2020-01-01 15:06:18 -08001#!/usr/bin/python3
2# Sample usage:
3# bazel run -c opt //frc971/analysis:plot -- --logfile /tmp/log.fbs --config gyro.pb
4import argparse
5import json
6import os.path
7from pathlib import Path
8import sys
9
10from frc971.analysis.py_log_reader import LogReader
11from frc971.analysis.plot_config_pb2 import PlotConfig, Signal
12from google.protobuf import text_format
13
14import matplotlib
15from matplotlib import pyplot as plt
16
17
18class Plotter:
19 def __init__(self, plot_config: PlotConfig, reader: LogReader):
20 self.config = plot_config
21 self.reader = reader
22 # Data streams, indexed by alias.
23 self.data = {}
24
25 def process_logfile(self):
26 aliases = set()
27 for channel in self.config.channel:
28 if channel.alias in aliases:
29 raise ValueError("Duplicate alias " + channel.alias)
30 aliases.add(channel.alias)
31 if not self.reader.subscribe(channel.name, channel.type):
32 raise ValueError("No such channel with name " + channel.name +
33 " and type " + channel.type)
34
35 self.reader.process()
36
37 for channel in self.config.channel:
38 self.data[channel.alias] = []
39 for message in self.reader.get_data_for_channel(
40 channel.name, channel.type):
41 valid_json = message[2].replace('nan', '"nan"')
42 parsed_json = json.loads(valid_json)
43 self.data[channel.alias].append((message[0], message[1],
44 parsed_json))
45
46 def plot_signal(self, axes: matplotlib.axes.Axes, signal: Signal):
47 if not signal.channel in self.data:
48 raise ValueError("No channel alias " + signal.channel)
49 field_path = signal.field.split('.')
50 monotonic_time = []
51 signal_data = []
52 for entry in self.data[signal.channel]:
53 monotonic_time.append(entry[0] * 1e-9)
54 value = entry[2]
55 for name in field_path:
56 value = value[name]
57 # Catch NaNs and convert them to floats.
58 value = float(value)
59 signal_data.append(value)
60 label_name = signal.channel + "." + signal.field
James Kuszmaul440ee252020-01-03 20:03:52 -080061 axes.plot(monotonic_time, signal_data, marker='o', label=label_name)
James Kuszmaul61a971f2020-01-01 15:06:18 -080062
63 def plot(self):
James Kuszmaul440ee252020-01-03 20:03:52 -080064 shared_axis = None
James Kuszmaul61a971f2020-01-01 15:06:18 -080065 for figure_config in self.config.figure:
66 fig = plt.figure()
67 num_subplots = len(figure_config.axes)
68 for ii in range(num_subplots):
James Kuszmaul440ee252020-01-03 20:03:52 -080069 axes = fig.add_subplot(num_subplots, 1, ii + 1, sharex=shared_axis)
70 shared_axis = shared_axis or axes
James Kuszmaul61a971f2020-01-01 15:06:18 -080071 axes_config = figure_config.axes[ii]
72 for signal in axes_config.signal:
73 self.plot_signal(axes, signal)
James Kuszmaul440ee252020-01-03 20:03:52 -080074 # Make the legend transparent so we can see behind it.
75 legend = axes.legend(framealpha=0.5)
James Kuszmaul61a971f2020-01-01 15:06:18 -080076 axes.set_xlabel("Monotonic Time (sec)")
James Kuszmaul440ee252020-01-03 20:03:52 -080077 axes.grid(True)
James Kuszmaul61a971f2020-01-01 15:06:18 -080078 if axes_config.HasField("ylabel"):
79 axes.set_ylabel(axes_config.ylabel)
80
81
82def main(argv):
83 parser = argparse.ArgumentParser(
84 description="Plot data from an aos logfile.")
85 parser.add_argument(
86 "--logfile",
87 type=str,
88 required=True,
89 help="Path to the logfile to parse.")
90 parser.add_argument(
91 "--config",
92 type=str,
93 required=True,
94 help="Name of the plot config to use.")
95 parser.add_argument(
96 "--config_dir",
97 type=str,
98 default="frc971/analysis/plot_configs",
99 help="Directory to look for plot configs in.")
100 args = parser.parse_args(argv[1:])
101
102 if not os.path.isdir(args.config_dir):
103 print(args.config_dir + " is not a directory.")
104 return 1
105 config_path = os.path.join(args.config_dir, args.config)
106 if not os.path.isfile(config_path):
107 print(config_path +
108 " does not exist or is not a file--available configs are")
109 for file_name in os.listdir(args.config_dir):
110 print(os.path.basename(file_name))
111 return 1
112
113 config = PlotConfig()
114 with open(config_path) as config_file:
115 text_format.Merge(config_file.read(), config)
116
117 if not os.path.isfile(args.logfile):
118 print(args.logfile + " is not a file.")
119 return 1
120
121 reader = LogReader(args.logfile)
122
123 plotter = Plotter(config, reader)
124 plotter.process_logfile()
125 plotter.plot()
126 plt.show()
127
128 return 0
129
130
131if __name__ == '__main__':
132 sys.exit(main(sys.argv))