• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, [min(t,0) for t in y%zu], [max(t,0) for t in "
131             "y%zu], color=colors[%zu], label=\'%s\')\n",
132             i, i, i, i, series_list_[i].label.c_str());
133         if (series_list_[i].point_style == PointStyle::kHighlight) {
134           printf(
135               "plt.plot(x%zu, y%zu, color=colors[%zu], "
136               "marker='.', ls=' ')\n",
137               i, i, i);
138         }
139       } else if (series_list_[i].line_style == LineStyle::kLine) {
140         if (series_list_[i].point_style == PointStyle::kHighlight) {
141           printf(
142               "plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\', "
143               "marker='.')\n",
144               i, i, i, series_list_[i].label.c_str());
145         } else {
146           printf("plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\')\n", i,
147                  i, i, series_list_[i].label.c_str());
148         }
149       } else if (series_list_[i].line_style == LineStyle::kStep) {
150         // Draw lines from (x[0],y[0]) to (x[1],y[0]) to (x[1],y[1]) and so on
151         // to illustrate the "steps". This can be expressed by duplicating all
152         // elements except the first in x and the last in y.
153         printf("xd%zu = [dup for v in x%zu for dup in [v, v]]\n", i, i);
154         printf("yd%zu = [dup for v in y%zu for dup in [v, v]]\n", i, i);
155         printf(
156             "plt.plot(xd%zu[1:], yd%zu[:-1], color=colors[%zu], "
157             "label=\'%s\')\n",
158             i, i, i, series_list_[i].label.c_str());
159         if (series_list_[i].point_style == PointStyle::kHighlight) {
160           printf(
161               "plt.plot(x%zu, y%zu, color=colors[%zu], "
162               "marker='.', ls=' ')\n",
163               i, i, i);
164         }
165       } else if (series_list_[i].line_style == LineStyle::kNone) {
166         printf(
167             "plt.plot(x%zu, y%zu, color=colors[%zu], label=\'%s\', "
168             "marker='o', ls=' ')\n",
169             i, i, i, series_list_[i].label.c_str());
170       } else {
171         printf("raise Exception(\"Unknown graph type\")\n");
172       }
173     }
174 
175     // IntervalSeries
176     printf("interval_colors = ['#ff8e82','#5092fc','#c4ffc4','#aaaaaa']\n");
177     RTC_CHECK_LE(interval_list_.size(), 4);
178     // To get the intervals to show up in the legend we have to create patches
179     // for them.
180     printf("legend_patches = []\n");
181     for (size_t i = 0; i < interval_list_.size(); i++) {
182       // List intervals
183       printf("\n# === IntervalSeries: %s ===\n",
184              interval_list_[i].label.c_str());
185       printf("ival%zu = [", i);
186       if (!interval_list_[i].intervals.empty()) {
187         printf("(%G, %G)", interval_list_[i].intervals[0].begin,
188                interval_list_[i].intervals[0].end);
189       }
190       for (size_t j = 1; j < interval_list_[i].intervals.size(); j++) {
191         printf(", (%G, %G)", interval_list_[i].intervals[j].begin,
192                interval_list_[i].intervals[j].end);
193       }
194       printf("]\n");
195 
196       printf("for i in range(0, %zu):\n", interval_list_[i].intervals.size());
197       if (interval_list_[i].orientation == IntervalSeries::kVertical) {
198         printf(
199             "  plt.axhspan(ival%zu[i][0], ival%zu[i][1], "
200             "facecolor=interval_colors[%zu], "
201             "alpha=0.3)\n",
202             i, i, i);
203       } else {
204         printf(
205             "  plt.axvspan(ival%zu[i][0], ival%zu[i][1], "
206             "facecolor=interval_colors[%zu], "
207             "alpha=0.3)\n",
208             i, i, i);
209       }
210       printf(
211           "legend_patches.append(mpatches.Patch(ec=\'black\', "
212           "fc=interval_colors[%zu], label='%s'))\n",
213           i, interval_list_[i].label.c_str());
214     }
215   }
216 
217   printf("plt.xlim(%f, %f)\n", xaxis_min_, xaxis_max_);
218   printf("plt.ylim(%f, %f)\n", yaxis_min_, yaxis_max_);
219   printf("plt.xlabel(\'%s\')\n", xaxis_label_.c_str());
220   printf("plt.ylabel(\'%s\')\n", yaxis_label_.c_str());
221   printf("plt.title(\'%s\')\n", title_.c_str());
222   printf("fig = plt.gcf()\n");
223   printf("fig.canvas.manager.set_window_title(\'%s\')\n", id_.c_str());
224   if (!yaxis_tick_labels_.empty()) {
225     printf("yaxis_tick_labels = [");
226     for (const auto& kv : yaxis_tick_labels_) {
227       printf("(%f,\"%s\"),", kv.first, kv.second.c_str());
228     }
229     printf("]\n");
230     printf("yaxis_tick_labels = list(zip(*yaxis_tick_labels))\n");
231     printf("plt.yticks(*yaxis_tick_labels)\n");
232   }
233   if (!series_list_.empty() || !interval_list_.empty()) {
234     printf("handles, labels = plt.gca().get_legend_handles_labels()\n");
235     printf("for lp in legend_patches:\n");
236     printf("   handles.append(lp)\n");
237     printf("   labels.append(lp.get_label())\n");
238     printf("plt.legend(handles, labels, loc=\'best\', fontsize=\'small\')\n");
239   }
240 }
241 
ExportProtobuf(webrtc::analytics::Chart * chart) const242 void Plot::ExportProtobuf(webrtc::analytics::Chart* chart) const {
243   for (size_t i = 0; i < series_list_.size(); i++) {
244     webrtc::analytics::DataSet* data_set = chart->add_data_sets();
245     for (const auto& point : series_list_[i].points) {
246       data_set->add_x_values(point.x);
247     }
248     for (const auto& point : series_list_[i].points) {
249       data_set->add_y_values(point.y);
250     }
251 
252     if (series_list_[i].line_style == LineStyle::kBar) {
253       data_set->set_style(webrtc::analytics::ChartStyle::BAR_CHART);
254     } else if (series_list_[i].line_style == LineStyle::kLine) {
255       data_set->set_style(webrtc::analytics::ChartStyle::LINE_CHART);
256     } else if (series_list_[i].line_style == LineStyle::kStep) {
257       data_set->set_style(webrtc::analytics::ChartStyle::LINE_STEP_CHART);
258     } else if (series_list_[i].line_style == LineStyle::kNone) {
259       data_set->set_style(webrtc::analytics::ChartStyle::SCATTER_CHART);
260     } else {
261       data_set->set_style(webrtc::analytics::ChartStyle::UNDEFINED);
262     }
263 
264     if (series_list_[i].point_style == PointStyle::kHighlight)
265       data_set->set_highlight_points(true);
266 
267     data_set->set_label(series_list_[i].label);
268   }
269 
270   chart->set_xaxis_min(xaxis_min_);
271   chart->set_xaxis_max(xaxis_max_);
272   chart->set_yaxis_min(yaxis_min_);
273   chart->set_yaxis_max(yaxis_max_);
274   chart->set_xaxis_label(xaxis_label_);
275   chart->set_yaxis_label(yaxis_label_);
276   chart->set_title(title_);
277   chart->set_id(id_);
278 
279   for (const auto& kv : yaxis_tick_labels_) {
280     webrtc::analytics::TickLabel* tick = chart->add_yaxis_tick_labels();
281     tick->set_value(kv.first);
282     tick->set_label(kv.second);
283   }
284 }
285 
PrintPythonCode(bool shared_xaxis) const286 void PlotCollection::PrintPythonCode(bool shared_xaxis) const {
287   printf("import matplotlib.pyplot as plt\n");
288   printf("plt.rcParams.update({'figure.max_open_warning': 0})\n");
289   printf("import matplotlib.patches as mpatches\n");
290   printf("import matplotlib.patheffects as pe\n");
291   printf("import colorsys\n");
292   for (size_t i = 0; i < plots_.size(); i++) {
293     printf("plt.figure(%zu)\n", i);
294     if (shared_xaxis) {
295       // Link x-axes across all figures for synchronized zooming.
296       if (i == 0) {
297         printf("axis0 = plt.subplot(111)\n");
298       } else {
299         printf("plt.subplot(111, sharex=axis0)\n");
300       }
301     }
302     plots_[i]->PrintPythonCode();
303   }
304   printf("plt.show()\n");
305 }
306 
ExportProtobuf(webrtc::analytics::ChartCollection * collection) const307 void PlotCollection::ExportProtobuf(
308     webrtc::analytics::ChartCollection* collection) const {
309   for (const auto& plot : plots_) {
310     webrtc::analytics::Chart* protobuf_representation =
311         collection->add_charts();
312     plot->ExportProtobuf(protobuf_representation);
313   }
314   if (calltime_to_utc_ms_) {
315     collection->set_calltime_to_utc_ms(*calltime_to_utc_ms_);
316   }
317 }
318 
AppendNewPlot()319 Plot* PlotCollection::AppendNewPlot() {
320   plots_.push_back(std::make_unique<Plot>());
321   return plots_.back().get();
322 }
323 
324 }  // namespace webrtc
325