test_compare_fit1.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import numpy as np
  2. from scipy.optimize import curve_fit
  3. ############################################# Define fit function
  4. def fit_function(x, A, beta, B, mu, sigma):
  5. return A * np.exp(-x / beta) + B * np.exp(-((x - mu) ** 2) / (2 * sigma**2))
  6. # Generate exponential and gaussian data
  7. data1 = np.random.exponential(scale=2.0, size=4000)
  8. data2 = np.random.normal(loc=3.0, scale=0.3, size=1000)
  9. # Fit the function to the histogram data
  10. bins = np.linspace(0, 6, 61)
  11. data_entries_1, bins_1 = np.histogram(data1, bins=bins)
  12. data_entries_2, bins_2 = np.histogram(data2, bins=bins)
  13. data_entries = data_entries_1 + data_entries_2 # sum the two sets
  14. binscenters = np.array([0.5 * (bins[i] + bins[i + 1]) for i in range(len(bins) - 1)])
  15. popt, pcov = curve_fit(
  16. fit_function, xdata=binscenters, ydata=data_entries, p0=[200, 2.0, 200, 3.0, 0.3]
  17. )
  18. # Generate enough x values to make the curves look smooth.
  19. xspace = np.linspace(0, 6, 100)
  20. ############################################# vedo
  21. # Plot the histogram and the fitted function.
  22. from vedo import settings
  23. from vedo.pyplot import histogram, plot
  24. settings.default_font = "ComicMono"
  25. settings.remember_last_figure_format = True
  26. h = histogram(
  27. data1.tolist() + data2.tolist(),
  28. xlim=(0, 6),
  29. bins=60,
  30. title="Exponential decay with gaussian peak",
  31. xtitle="x axis",
  32. ytitle="Number of entries",
  33. label="Histogram entries",
  34. c='green3',
  35. )
  36. h += plot(
  37. xspace,
  38. fit_function(xspace, *popt),
  39. lc="darkorange",
  40. lw=3,
  41. label="Fit function",
  42. )
  43. h.add_legend()
  44. h.show(zoom="tight", interactive=False)
  45. if settings.dry_run_mode:
  46. exit(0)
  47. ############################################# matplotlib
  48. # Plot the histogram and the fitted function.
  49. import matplotlib.pyplot as plt
  50. plt.bar(
  51. binscenters,
  52. data_entries,
  53. width=bins[1] - bins[0],
  54. color="g",
  55. label=r"Histogram entries",
  56. )
  57. plt.plot(
  58. xspace,
  59. fit_function(xspace, *popt),
  60. color="darkorange",
  61. linewidth=2.5,
  62. label=r"Fit function",
  63. )
  64. plt.xlim(0, 6)
  65. plt.xlabel(r"x axis")
  66. plt.ylabel(r"Number of entries")
  67. plt.title(r"Exponential decay with gaussian peak")
  68. plt.legend(loc="best")
  69. plt.show()