12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package data
- import (
- "errors"
- "eta/eta_chart_lib/models"
- "eta/eta_chart_lib/utils"
- "github.com/shopspring/decimal"
- "math"
- "time"
- )
- // HandleDataByLinearRegression 插值法补充数据(线性方程式)
- func HandleDataByLinearRegression(edbInfoDataList []*models.EdbDataList, handleDataMap map[string]float64) (err error) {
- if len(edbInfoDataList) < 2 {
- return
- }
- var startEdbInfoData *models.EdbDataList
- for _, v := range edbInfoDataList {
- handleDataMap[v.DataTime] = v.Value
- // 第一个数据就给过滤了,给后面的试用
- if startEdbInfoData == nil {
- startEdbInfoData = v
- continue
- }
- // 获取两条数据之间相差的天数
- startDataTime, _ := time.ParseInLocation(utils.FormatDate, startEdbInfoData.DataTime, time.Local)
- currDataTime, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
- betweenHour := int(currDataTime.Sub(startDataTime).Hours())
- betweenDay := betweenHour / 24
- // 如果相差一天,那么过滤
- if betweenDay <= 1 {
- startEdbInfoData = v
- continue
- }
- // 生成线性方程式
- var a, b float64
- {
- coordinateData := make([]utils.Coordinate, 0)
- tmpCoordinate1 := utils.Coordinate{
- X: 1,
- Y: startEdbInfoData.Value,
- }
- coordinateData = append(coordinateData, tmpCoordinate1)
- tmpCoordinate2 := utils.Coordinate{
- X: float64(betweenDay) + 1,
- Y: v.Value,
- }
- coordinateData = append(coordinateData, tmpCoordinate2)
- a, b = utils.GetLinearResult(coordinateData)
- if math.IsNaN(a) || math.IsNaN(b) {
- err = errors.New("线性方程公式生成失败")
- return
- }
- }
- // 生成对应的值
- {
- for i := 1; i < betweenDay; i++ {
- tmpDataTime := startDataTime.AddDate(0, 0, i)
- aDecimal := decimal.NewFromFloat(a)
- xDecimal := decimal.NewFromInt(int64(i) + 1)
- bDecimal := decimal.NewFromFloat(b)
- val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).Round(4).Float64()
- handleDataMap[tmpDataTime.Format(utils.FormatDate)] = val
- }
- }
- startEdbInfoData = v
- }
- return
- }
|