fit_polynomial2.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """A polynomial fit of degree="""
  2. from vedo import np, precision, Text3D, DashedLine, show
  3. from vedo.pyplot import plot, fit, histogram
  4. # np.random.seed(0)
  5. n = 25 # nr of data points to generate
  6. deg = 3 # degree of the fitting polynomial
  7. # Generate some noisy data points
  8. x = np.linspace(0, 12, n)
  9. y = (x-6)**3 /50 + 6 # the "truth" is a cubic function!
  10. xerrs = np.linspace(0.4, 1.0, n) # make last points less precise
  11. yerrs = np.linspace(1.0, 0.4, n) # make first points less precise
  12. noise = np.random.randn(n)
  13. # Plot the noisy points with their error bars
  14. fig1 = plot(
  15. x, y+noise,
  16. ".k",
  17. title=__doc__+str(deg),
  18. xerrors=xerrs,
  19. yerrors=yerrs,
  20. aspect=4/5,
  21. xlim=(-3,15),
  22. ylim=(-3,15),
  23. padding=0,
  24. )
  25. fig1 += DashedLine(x, y, c='r')
  26. # Fit points and evaluate, with a bootstrap and Monte-Carlo technique,
  27. # the correct errors and error bands. Return a Line object:
  28. pfit = fit(
  29. [x, y+noise],
  30. deg=deg, # degree of the polynomial
  31. niter=500, # nr. of MC iterations to compute error bands
  32. nstd=2, # nr. of std deviations to display
  33. xerrors=xerrs, # optional array of errors on x
  34. yerrors=yerrs, # optional array of errors on y
  35. vrange=(-3,15), # specify the domain of fit
  36. )
  37. fig1 += [pfit, pfit.error_band, pfit.error_lines] # add these objects to Figure
  38. # Add some text too
  39. txt = "fit coefficients:\n " + precision(pfit.coefficients, 2) \
  40. + "\n:pm" + precision(pfit.coefficient_errors, 2) \
  41. + "\n:Chi^2_:nu = " + precision(pfit.reduced_chi2, 3)
  42. fig1 += Text3D(txt, s=0.42, font='VictorMono').pos(4,-2).c('k')
  43. # Create a 2D histo to show the correlation of fit parameters
  44. fig2 = histogram(
  45. pfit.monte_carlo_coefficients[:,0],
  46. pfit.monte_carlo_coefficients[:,1],
  47. title="parameters correlation",
  48. xtitle='coeff_0', ytitle='coeff_1',
  49. cmap='ocean_r',
  50. scalarbar=True,
  51. )
  52. show(fig1, fig2, N=2, sharecam=False, zoom='tight').close()