1
0

update.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #define _USE_MATH_DEFINES
  2. #include <cmath>
  3. #include "../matplotlibcpp.h"
  4. #include <chrono>
  5. namespace plt = matplotlibcpp;
  6. void update_window(const double x, const double y, const double t,
  7. std::vector<double> &xt, std::vector<double> &yt)
  8. {
  9. const double target_length = 300;
  10. const double half_win = (target_length/(2.*sqrt(1.+t*t)));
  11. xt[0] = x - half_win;
  12. xt[1] = x + half_win;
  13. yt[0] = y - half_win*t;
  14. yt[1] = y + half_win*t;
  15. }
  16. int main()
  17. {
  18. bool use_dynamic_plot = false;
  19. bool timeit = true;
  20. size_t n = 1000;
  21. std::vector<double> x, y;
  22. const double w = 0.05;
  23. const double a = n/2;
  24. for(size_t i=0; i<n; i++) {
  25. x.push_back(i);
  26. y.push_back(a*sin(w*i));
  27. }
  28. std::vector<double> xt(2), yt(2);
  29. plt::title("Sample figure");
  30. std::chrono::time_point<std::chrono::system_clock> start, end;
  31. start = std::chrono::system_clock::now();
  32. if(use_dynamic_plot)
  33. {
  34. plt::xlim(x.front(), x.back());
  35. plt::ylim(-a,a);
  36. plt::axis("equal");
  37. // plot sin once and for all
  38. plt::named_plot("sin", x, y);
  39. // prepare plotting the tangent
  40. plt::Plot plot("tangent");
  41. plt::legend();
  42. for(size_t i=0; i<n; i++) {
  43. if (i % 10 == 0) {
  44. {
  45. update_window(x[i], y[i], a*w*cos(w*x[i]), xt, yt);
  46. // just update data for this plot
  47. plot.update(xt, yt);
  48. }
  49. // Display plot continuously
  50. if(!timeit)
  51. plt::pause(0.1);
  52. }
  53. }
  54. }
  55. else
  56. {
  57. for(size_t i=0; i<n; i++) {
  58. if (i % 10 == 0) {
  59. {
  60. plt::clf();
  61. plt::named_plot("sin", x, y);
  62. update_window(x[i], y[i], a*w*cos(w*i), xt, yt);
  63. plt::named_plot("tangent", xt, yt);
  64. // we have to control axis size
  65. plt::xlim(x.front(), x.back());
  66. plt::ylim(-a,a);
  67. plt::axis("equal");
  68. plt::legend();
  69. }
  70. // Display plot continuously
  71. if(!timeit)
  72. plt::pause(0.1);
  73. }
  74. }
  75. }
  76. end = std::chrono::system_clock::now();
  77. double elapsed_seconds = std::chrono::duration_cast<std::chrono::microseconds>
  78. (end-start).count();
  79. if(use_dynamic_plot)
  80. std::cout << "dynamic";
  81. else
  82. std::cout << "static";
  83. std::cout << " : " << elapsed_seconds/1000 << " ms\n";
  84. }