BouncingBall_experiment.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from BouncingBall import *
  2. from CBD.realtime.plotting import PlotManager, LinePlot
  3. from CBD.simulator import Simulator
  4. import matplotlib.pyplot as plt
  5. bb = BouncingBall()
  6. DELTA = 0.1
  7. TIME = 15.0
  8. fig = plt.figure(figsize=(5, 5), dpi=100)
  9. ax1 = fig.add_subplot(121)
  10. ax2 = fig.add_subplot(122)
  11. ax1.set_xlim((0, TIME))
  12. ax1.set_ylim((-1, 105))
  13. ax1.set_ylabel("height")
  14. ax2.set_xlim((0, TIME))
  15. ax2.set_ylim((-50, 50))
  16. ax2.set_ylabel("velocity")
  17. plot1 = fig, ax1
  18. plot2 = fig, ax2
  19. ax1.plot((0, TIME+DELTA), (0, 0), c='purple', ls='--', lw=0.1)
  20. manager = PlotManager()
  21. manager.register("height", bb.getBlockByName('plot1'), plot1, LinePlot(color='red'))
  22. manager.register("velocity", bb.getBlockByName('plot2'), plot2, LinePlot(color='blue'))
  23. from CBD.state_events import StateEvent, Direction
  24. from CBD.state_events.locators import *
  25. def bounce(e, t, model):
  26. if e.output_name == "height":
  27. model.bounce()
  28. print("BOUNCE AT:", t)
  29. else:
  30. y = model.getSignalHistory("height")[-1].value
  31. model.getBlockByName("y0").setValue(y)
  32. model.getBlockByName("v0").setValue(-41)
  33. lengs = []
  34. times = []
  35. def poststep(o, t, st):
  36. times.append(st)
  37. lengs.append(t - o)
  38. sim = Simulator(bb)
  39. sim.setStateEventLocator(ITPStateEventLocator())
  40. sim.registerStateEvent(StateEvent("height", direction=Direction.FROM_ABOVE, event=bounce))
  41. sim.registerStateEvent(StateEvent("velocity", direction=Direction.FROM_ABOVE, level=-40.0, event=bounce))
  42. sim.connect("poststep", poststep)
  43. sim.setRealTime()
  44. sim.setDeltaT(DELTA)
  45. sim.run(TIME)
  46. # import time
  47. # while sim.is_running():
  48. # time.sleep(0.1)
  49. plt.show()
  50. import numpy as np
  51. fig = plt.figure(figsize=(5, 5), dpi=100)
  52. ax = fig.add_subplot(111)
  53. ax.set_xticks(np.arange(0, TIME, DELTA), minor=True)
  54. ax.set_xlim((0, TIME+DELTA))
  55. ax.bar(times, lengs, width=0.05, color='green', label='duration')
  56. # ax.plot((0, TIME+DELTA), (DELTA, DELTA), c='red', ls='--')
  57. ax2 = ax.twinx()
  58. ax2.set_ylim((0, 105))
  59. ax2.plot(*bb.getBlockByName('plot1').data_xy, c='blue', label='simulation')
  60. handles, labels = ax.get_legend_handles_labels()
  61. handles2, labels2 = ax2.get_legend_handles_labels()
  62. ax.legend(handles + handles2, labels + labels2)
  63. plt.show()