1 /*
2  *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "rtc_tools/rtc_event_log_visualizer/plot_base.h"
12 
13 #include <algorithm>
14 #include <memory>
15 
16 #include "rtc_base/checks.h"
17 
18 namespace webrtc {
19 
SetXAxis(float min_value,float max_value,std::string label,float left_margin,float right_margin)20 void Plot::SetXAxis(float min_value,
21                     float max_value,
22                     std::string label,
23                     float left_margin,
24                     float right_margin) {
25   RTC_DCHECK_LE(min_value, max_value);
26   xaxis_min_ = min_value - left_margin * (max_value - min_value);
27   xaxis_max_ = max_value + right_margin * (max_value - min_value);
28   xaxis_label_ = label;
29 }
30 
SetSuggestedXAxis(float min_value,float max_value,std::string label,float left_margin,float right_margin)31 void Plot::SetSuggestedXAxis(float min_value,
32                              float max_value,
33                              std::string label,
34                              float left_margin,
35                              float right_margin) {
36   for (const auto& series : series_list_) {
37     for (const auto& point : series.points) {
38       min_value = std::min(min_value, point.x);
39       max_value = std::max(max_value, point.x);
40     }
41   }
42   SetXAxis(min_value, max_value, label, left_margin, right_margin);
43 }
44 
SetYAxis(float min_value,float max_value,std::string label,float bottom_margin,float top_margin)45 void Plot::SetYAxis(float min_value,
46                     float max_value,
47                     std::string label,
48                     float bottom_margin,
49                     float top_margin) {
50   RTC_DCHECK_LE(min_value, max_value);
51   yaxis_min_ = min_value - bottom_margin * (max_value - min_value);
52   yaxis_max_ = max_value + top_margin * (max_value - min_value);
53   yaxis_label_ = label;
54 }
55 
SetSuggestedYAxis(float min_value,float max_value,std::string label,float bottom_margin,float top_margin)56 void Plot::SetSuggestedYAxis(float min_value,
57                              float max_value,
58                              std::string label,
59                              float bottom_margin,
60                              float top_margin) {
61   for (const auto& series : series_list_) {
62     for (const auto& point : series.points) {
63       min_value = std::min(min_value, point.y);
64       max_value = std::max(max_value, point.y);
65     }
66   }
67   SetYAxis(min_value, max_value, label, bottom_margin, top_margin);
68 }
69 
SetYAxisTickLabels(const std::vector<std::pair<float,std::string>> & labels)70 void Plot::SetYAxisTickLabels(
71     const std::vector<std::pair<float, std::string>>& labels) {
72   yaxis_tick_labels_ = labels;
73 }
74 
SetTitle(const std::string & title)75 void Plot::SetTitle(const std::string& title) {
76   title_ = title;
77 }
78 
SetId(const std::string & id)79 void Plot::SetId(const std::string& id) {
80   id_ = id;
81 }
82 
AppendTimeSeries(TimeSeries && time_series)83 void Plot::AppendTimeSeries(TimeSeries&& time_series) {
84   series_list_.emplace_back(std::move(time_series));
85 }
86 
AppendIntervalSeries(IntervalSeries && interval_series)87 void Plot::AppendIntervalSeries(IntervalSeries&& interval_series) {
88   interval_list_.emplace_back(std::move(interval_series));
89 }
90 
AppendTimeSeriesIfNotEmpty(TimeSeries && time_series)91 void Plot::AppendTimeSeriesIfNotEmpty(TimeSeries&& time_series) {
92   if (!time_series.points.empty()) {
93     series_list_.emplace_back(std::move(time_series));
94   }
95 }
96 
PrintPythonCode() const97 void Plot::PrintPythonCode() const {
98   // Write python commands to stdout. Intended program usage is
99   // ./event_log_visualizer event_log160330.dump | python
100 
101   if (!series_list_.empty()) {
102     printf("color_count = %zu\n", series_list_.size());
103     printf(
104         "hls_colors = [(i*1.0/color_count, 0.25+i*0.5/color_count, 0.8) for i "
105         "in range(color_count)]\n");
106     printf("colors = [colorsys.hls_to_rgb(*hls) for hls in hls_colors]\n");
107 
108     for (size_t i = 0; i < series_list_.size(); i++) {
109       printf("\n# === Series: %s ===\n", series_list_[i].label.c_str());
110       // List x coordinates
111       printf("x%zu = [", i);
112       if (!series_list_[i].points.empty())
113         printf("%.3f", series_list_[i].points[0].x);
114       for (size_t j = 1; j < series_list_[i].points.size(); j++)
115         printf(", %.3f", series_list_[i].points[j].x);
116       printf("]\n");
117 
118       // List y coordinates
119       printf("y%zu = [", i);
120       if (!series_list_[i].points.empty())
121         printf("%G", series_list_[i].points[0].y);
122       for (size_t j = 1; j < series_list_[i].points.size(); j++)
123         printf(", %G", series_list_[i].points[j].y);
124       printf("]\n");
125 
126       if (series_list_[i].line_style == LineStyle::kBar) {
127         // There is a plt.bar function that draws bar plots,
128         // but it is *way* too slow to be useful.
129         printf(
130             "plt.vlines(x%zu, map(lambda t: min(t,0), y%zu), map(lambda t: "
131             "max(t,0), y%zu), color=colors[%zu], "
132             "label=\'%s\')\n",
133             i, i, i, i, series_list_[i].label.c_str());
134         if (series_list_[i].point_style == PointStyle::kHighlight) {
135           printf(
136               "plt.plot(x%zu, y%zu, color=colors[%zu], "
137               "marker='.', ls=' ')\n",
138               i, i, i);
139         }
140       } else if (series_list_[i].line_style == LineStyle::kLine) {
141         if (series_list_[i].point_style == PointStyle::kHighlight) {
142           printf(
143               "plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\', "
144               "marker='.')\n",
145               i, i, i, series_list_[i].label.c_str());
146         } else {
147           printf("plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\')\n", i,
148                  i, i, series_list_[i].label.c_str());
149         }
150       } else if (series_list_[i].line_style == LineStyle::kStep) {
151         // Draw lines from (x[0],y[0]) to (x[1],y[0]) to (x[1],y[1]) and so on
152         // to illustrate the "steps". This can be expressed by duplicating all
153         // elements except the first in x and the last in y.
154         printf("xd%zu = [dup for v in x%zu for dup in [v, v]]\n", i, i);
155         printf("yd%zu = [dup for v in y%zu for dup in [v, v]]\n", i, i);
156         printf(
157             "plt.plot(xd%zu[1:], yd%zu[:-1], color=colors[%zu], "
158             "label=\'%s\')\n",
159             i, i, i, series_list_[i].label.c_str());
160         if (series_list_[i].point_style == PointStyle::kHighlight) {
161           printf(
162               "plt.plot(x%zu, y%zu, color=colors[%zu], "
163               "marker='.', ls=' ')\n",
164               i, i, i);
165         }
166       } else if (series_list_[i].line_style == LineStyle::kNone) {
167         printf(
168             "plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\', "
169             "marker='o', ls=' ')\n",
170             i, i, i, series_list_[i].label.c_str());
171       } else {
172         printf("raise Exception(\"Unknown graph type\")\n");
173       }
174     }
175 
176     // IntervalSeries
177     printf("interval_colors = ['#ff8e82','#5092fc','#c4ffc4','#aaaaaa']\n");
178     RTC_CHECK_LE(interval_list_.size(), 4);
179     // To get the intervals to show up in the legend we have to create patches
180     // for them.
181     printf("legend_patches = []\n");
182     for (size_t i = 0; i < interval_list_.size(); i++) {
183       // List intervals
184       printf("\n# === IntervalSeries: %s ===\n",
185              interval_list_[i].label.c_str());
186       printf("ival%zu = [", i);
187       if (!interval_list_[i].intervals.empty()) {
188         printf("(%G, %G)", interval_list_[i].intervals[0].begin,
189                interval_list_[i].intervals[0].end);
190       }
191       for (size_t j = 1; j < interval_list_[i].intervals.size(); j++) {
192         printf(", (%G, %G)", interval_list_[i].intervals[j].begin,
193                interval_list_[i].intervals[j].end);
194       }
195       printf("]\n");
196 
197       printf("for i in range(0, %zu):\n", interval_list_[i].intervals.size());
198       if (interval_list_[i].orientation == IntervalSeries::kVertical) {
199         printf(
200             "  plt.axhspan(ival%zu[i][0], ival%zu[i][1], "
201             "facecolor=interval_colors[%zu], "
202             "alpha=0.3)\n",
203             i, i, i);
204       } else {
205         printf(
206             "  plt.axvspan(ival%zu[i][0], ival%zu[i][1], "
207             "facecolor=interval_colors[%zu], "
208             "alpha=0.3)\n",
209             i, i, i);
210       }
211       printf(
212           "legend_patches.append(mpatches.Patch(ec=\'black\', "
213           "fc=interval_colors[%zu], label='%s'))\n",
214           i, interval_list_[i].label.c_str());
215     }
216   }
217 
218   printf("plt.xlim(%f, %f)\n", xaxis_min_, xaxis_max_);
219   printf("plt.ylim(%f, %f)\n", yaxis_min_, yaxis_max_);
220   printf("plt.xlabel(\'%s\')\n", xaxis_label_.c_str());
221   printf("plt.ylabel(\'%s\')\n", yaxis_label_.c_str());
222   printf("plt.title(\'%s\')\n", title_.c_str());
223   printf("fig = plt.gcf()\n");
224   printf("fig.canvas.set_window_title(\'%s\')\n", id_.c_str());
225   if (!yaxis_tick_labels_.empty()) {
226     printf("yaxis_tick_labels = [");
227     for (const auto& kv : yaxis_tick_labels_) {
228       printf("(%f,\"%s\"),", kv.first, kv.second.c_str());
229     }
230     printf("]\n");
231     printf("yaxis_tick_labels = list(zip(*yaxis_tick_labels))\n");
232     printf("plt.yticks(*yaxis_tick_labels)\n");
233   }
234   if (!series_list_.empty() || !interval_list_.empty()) {
235     printf("handles, labels = plt.gca().get_legend_handles_labels()\n");
236     printf("for lp in legend_patches:\n");
237     printf("   handles.append(lp)\n");
238     printf("   labels.append(lp.get_label())\n");
239     printf("plt.legend(handles, labels, loc=\'best\', fontsize=\'small\')\n");
240   }
241 }
242 
ExportProtobuf(webrtc::analytics::Chart * chart) const243 void Plot::ExportProtobuf(webrtc::analytics::Chart* chart) const {
244   for (size_t i = 0; i < series_list_.size(); i++) {
245     webrtc::analytics::DataSet* data_set = chart->add_data_sets();
246     for (const auto& point : series_list_[i].points) {
247       data_set->add_x_values(point.x);
248     }
249     for (const auto& point : series_list_[i].points) {
250       data_set->add_y_values(point.y);
251     }
252 
253     if (series_list_[i].line_style == LineStyle::kBar) {
254       data_set->set_style(webrtc::analytics::ChartStyle::BAR_CHART);
255     } else if (series_list_[i].line_style == LineStyle::kLine) {
256       data_set->set_style(webrtc::analytics::ChartStyle::LINE_CHART);
257     } else if (series_list_[i].line_style == LineStyle::kStep) {
258       data_set->set_style(webrtc::analytics::ChartStyle::LINE_STEP_CHART);
259     } else if (series_list_[i].line_style == LineStyle::kNone) {
260       data_set->set_style(webrtc::analytics::ChartStyle::SCATTER_CHART);
261     } else {
262       data_set->set_style(webrtc::analytics::ChartStyle::UNDEFINED);
263     }
264 
265     if (series_list_[i].point_style == PointStyle::kHighlight)
266       data_set->set_highlight_points(true);
267 
268     data_set->set_label(series_list_[i].label);
269   }
270 
271   chart->set_xaxis_min(xaxis_min_);
272   chart->set_xaxis_max(xaxis_max_);
273   chart->set_yaxis_min(yaxis_min_);
274   chart->set_yaxis_max(yaxis_max_);
275   chart->set_xaxis_label(xaxis_label_);
276   chart->set_yaxis_label(yaxis_label_);
277   chart->set_title(title_);
278   chart->set_id(id_);
279 
280   for (const auto& kv : yaxis_tick_labels_) {
281     webrtc::analytics::TickLabel* tick = chart->add_yaxis_tick_labels();
282     tick->set_value(kv.first);
283     tick->set_label(kv.second);
284   }
285 }
286 
PrintPythonCode(bool shared_xaxis) const287 void PlotCollection::PrintPythonCode(bool shared_xaxis) const {
288   printf("import matplotlib.pyplot as plt\n");
289   printf("plt.rcParams.update({'figure.max_open_warning': 0})\n");
290   printf("import matplotlib.patches as mpatches\n");
291   printf("import matplotlib.patheffects as pe\n");
292   printf("import colorsys\n");
293   for (size_t i = 0; i < plots_.size(); i++) {
294     printf("plt.figure(%zu)\n", i);
295     if (shared_xaxis) {
296       // Link x-axes across all figures for synchronized zooming.
297       if (i == 0) {
298         printf("axis0 = plt.subplot(111)\n");
299       } else {
300         printf("plt.subplot(111, sharex=axis0)\n");
301       }
302     }
303     plots_[i]->PrintPythonCode();
304   }
305   printf("plt.show()\n");
306 }
307 
ExportProtobuf(webrtc::analytics::ChartCollection * collection) const308 void PlotCollection::ExportProtobuf(
309     webrtc::analytics::ChartCollection* collection) const {
310   for (const auto& plot : plots_) {
311     // TODO(terelius): Ensure that there is no way to insert plots other than
312     // ProtobufPlots in a ProtobufPlotCollection. Needed to safely static_cast
313     // here.
314     webrtc::analytics::Chart* protobuf_representation =
315         collection->add_charts();
316     plot->ExportProtobuf(protobuf_representation);
317   }
318 }
319 
AppendNewPlot()320 Plot* PlotCollection::AppendNewPlot() {
321   plots_.push_back(std::make_unique<Plot>());
322   return plots_.back().get();
323 }
324 
325 }  // namespace webrtc
326