compute.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. import base64
  3. from io import BytesIO
  4. from numpy import exp, cos, linspace
  5. from matplotlib.figure import Figure
  6. import os, time, glob
  7. import matplotlib.style
  8. import matplotlib as mpl
  9. mpl.use("Agg")
  10. mpl.style.use("classic")
  11. mpl.rc("text", usetex="True")
  12. mpl.rc("figure", titlesize=12)
  13. mpl.rc("pgf", texsystem="pdflatex")
  14. mpl.rc("axes", labelsize=14, titlesize=14)
  15. mpl.rc("font", family="serif", weight="normal", size=12)
  16. def damped_vibrations(t, A, b, w):
  17. return A * exp(-b * t) * cos(w * t)
  18. def compute(A, b, w, T, resolution):
  19. t = linspace(0, T, resolution + 1)
  20. u = damped_vibrations(t, A, b, w)
  21. fig = Figure() # needed to avoid adding curves in plot
  22. ax = fig.subplots()
  23. ax.plot(t, u, "r", lw=1)
  24. ax.grid(True, which="both")
  25. ax.set(xlim=(0, T), ylim=(-A, A))
  26. ax.set(xlabel="$t$", ylabel="$u(t)$")
  27. ax.set_title(f"$A = {A}\,m, b = {b}\,kg{{\cdot}}s^{{-1}}, w = {w:.2f}\,s^{{-1}}$")
  28. return fig
  29. def compute_png(A, b, w, T, resolution=1000):
  30. """return filename of plot of the damped_vibrations function"""
  31. fig = compute(A, b, w, T, resolution)
  32. # make Matplotlib write to BytesIO file object
  33. # and grab return the object's string
  34. figfile = BytesIO() # save it to a temporary buffer file
  35. fig.savefig(figfile, format="png")
  36. figdata_png = base64.b64encode(figfile.getvalue()).decode()
  37. return figdata_png
  38. def compute_svg(A, b, w, T, resolution=1000):
  39. """return filename of plot of the damped_vibrations function"""
  40. fig = compute(A, b, w, T, resolution)
  41. # make Matplotlib write to BytesIO file object
  42. # and grab return the object's string
  43. figfile = BytesIO() # save it to a temporary buffer file
  44. fig.savefig(figfile, format="svg")
  45. figdata_svg = "<svg" + figfile.getvalue().decode().split("<svg")[1]
  46. return figdata_svg