handle_data.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package data
  2. import (
  3. "errors"
  4. "eta_gn/eta_chart_lib/models"
  5. "eta_gn/eta_chart_lib/utils"
  6. "github.com/shopspring/decimal"
  7. "math"
  8. "time"
  9. )
  10. // HandleDataByLinearRegression 插值法补充数据(线性方程式)
  11. func HandleDataByLinearRegression(edbInfoDataList []*models.EdbDataList, handleDataMap map[string]float64) (err error) {
  12. if len(edbInfoDataList) < 2 {
  13. return
  14. }
  15. var startEdbInfoData *models.EdbDataList
  16. for _, v := range edbInfoDataList {
  17. handleDataMap[v.DataTime] = v.Value
  18. // 第一个数据就给过滤了,给后面的试用
  19. if startEdbInfoData == nil {
  20. startEdbInfoData = v
  21. continue
  22. }
  23. // 获取两条数据之间相差的天数
  24. startDataTime, _ := time.ParseInLocation(utils.FormatDate, startEdbInfoData.DataTime, time.Local)
  25. currDataTime, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  26. betweenHour := int(currDataTime.Sub(startDataTime).Hours())
  27. betweenDay := betweenHour / 24
  28. // 如果相差一天,那么过滤
  29. if betweenDay <= 1 {
  30. startEdbInfoData = v
  31. continue
  32. }
  33. // 生成线性方程式
  34. var a, b float64
  35. {
  36. coordinateData := make([]utils.Coordinate, 0)
  37. tmpCoordinate1 := utils.Coordinate{
  38. X: 1,
  39. Y: startEdbInfoData.Value,
  40. }
  41. coordinateData = append(coordinateData, tmpCoordinate1)
  42. tmpCoordinate2 := utils.Coordinate{
  43. X: float64(betweenDay) + 1,
  44. Y: v.Value,
  45. }
  46. coordinateData = append(coordinateData, tmpCoordinate2)
  47. a, b = utils.GetLinearResult(coordinateData)
  48. if math.IsNaN(a) || math.IsNaN(b) {
  49. err = errors.New("线性方程公式生成失败")
  50. return
  51. }
  52. }
  53. // 生成对应的值
  54. {
  55. for i := 1; i < betweenDay; i++ {
  56. tmpDataTime := startDataTime.AddDate(0, 0, i)
  57. aDecimal := decimal.NewFromFloat(a)
  58. xDecimal := decimal.NewFromInt(int64(i) + 1)
  59. bDecimal := decimal.NewFromFloat(b)
  60. val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).Round(4).Float64()
  61. handleDataMap[tmpDataTime.Format(utils.FormatDate)] = val
  62. }
  63. }
  64. startEdbInfoData = v
  65. }
  66. return
  67. }