predict_edb.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_index_lib/utils"
  6. "fmt"
  7. "github.com/beego/beego/v2/client/orm"
  8. "github.com/shopspring/decimal"
  9. "github.com/yidane/formula"
  10. "strings"
  11. "time"
  12. )
  13. // CalculateRule 预测指标 规则 计算
  14. type CalculateRule struct {
  15. EdbInfoId int `description:"指标id"`
  16. ConfigId int `description:"配置id"`
  17. TrendsCalculateMappingList []*PredictEdbConfCalculateMapping
  18. EdbInfoList []*EdbInfo
  19. EdbInfoIdBytes []string
  20. Formula string
  21. RuleType int `description:"预测规则,1:最新,2:固定值,3:同比,4:同差,5:环比,6:环差,7:N期移动均值,8:N期段线性外推值,9:动态环差"`
  22. EndDate string `description:"截止日期"`
  23. EdbInfoIdArr []EdbInfoFromTag `description:"指标信息"`
  24. }
  25. // RefreshCalculateByRuleBy9 刷新计算
  26. func RefreshCalculateByRuleBy9(rule CalculateRule) (resultDataList []*EdbInfoSearchData, err error) {
  27. o := orm.NewOrm()
  28. to, err := o.Begin()
  29. if err != nil {
  30. return
  31. }
  32. defer func() {
  33. if err != nil {
  34. to.Rollback()
  35. } else {
  36. err = to.Commit()
  37. }
  38. }()
  39. resultDataList, err = CalculateByRuleBy9(to, rule)
  40. return
  41. }
  42. // CalculateByRuleBy9 动态环差规则计算入库
  43. func CalculateByRuleBy9(to orm.TxOrmer, rule CalculateRule) (resultDataList []*EdbInfoSearchData, err error) {
  44. realSaveDataMap := make(map[string]map[int]float64)
  45. saveDataMap := make(map[string]map[int]float64)
  46. dateList := make([]string, 0)
  47. formulaStr := strings.ToUpper(rule.Formula)
  48. // 获取关联指标数据
  49. for edbInfoIndex, v := range rule.EdbInfoList {
  50. dataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  51. if tmpErr != nil {
  52. err = tmpErr
  53. return
  54. }
  55. dataMap := make(map[string]float64)
  56. for _, dv := range dataList {
  57. // 现有实际数据
  58. if val, ok := realSaveDataMap[dv.DataTime]; ok {
  59. if _, ok := val[v.EdbInfoId]; !ok {
  60. val[v.EdbInfoId] = dv.Value
  61. }
  62. } else {
  63. temp := make(map[int]float64)
  64. temp[v.EdbInfoId] = dv.Value
  65. realSaveDataMap[dv.DataTime] = temp
  66. }
  67. // 待处理的数据
  68. if val, ok := saveDataMap[dv.DataTime]; ok {
  69. if _, ok := val[v.EdbInfoId]; !ok {
  70. val[v.EdbInfoId] = dv.Value
  71. }
  72. } else {
  73. temp := make(map[int]float64)
  74. temp[v.EdbInfoId] = dv.Value
  75. saveDataMap[dv.DataTime] = temp
  76. }
  77. // 以第一个指标的日期作为基准日期
  78. if edbInfoIndex == 0 {
  79. dateList = append(dateList, dv.DataTime)
  80. }
  81. }
  82. item := new(CalculateItems)
  83. item.EdbInfoId = v.EdbInfoId
  84. item.DataMap = dataMap
  85. }
  86. //数据处理,将日期内不全的数据做补全
  87. handleDateSaveDataMap(dateList, realSaveDataMap, saveDataMap, rule.EdbInfoList)
  88. // 添加数据
  89. addDataList := make([]*PredictEdbRuleData, 0)
  90. // 计算规则
  91. formulaMap := utils.CheckFormula(formulaStr)
  92. //获取指标所有数据
  93. dataList := make([]*PredictEdbRuleData, 0)
  94. sql := `SELECT * FROM predict_edb_rule_data WHERE config_id = ?`
  95. _, err = to.Raw(sql, rule.ConfigId).QueryRows(&dataList)
  96. if err != nil {
  97. return
  98. }
  99. dataMap := make(map[string]*PredictEdbRuleData)
  100. for _, v := range dataList {
  101. dataMap[v.DataTime] = v
  102. }
  103. existDataMap := make(map[string]string)
  104. removeDateList := make([]string, 0) //需要移除的日期
  105. for sk, sv := range saveDataMap {
  106. //fmt.Println(sk, sv)
  107. formulaFormStr := ReplaceFormula(rule.EdbInfoList, sv, formulaMap, formulaStr, rule.EdbInfoIdBytes)
  108. //计算公式异常,那么就移除该指标
  109. if formulaFormStr == "" {
  110. removeDateList = append(removeDateList, sk)
  111. continue
  112. }
  113. //utils.FileLog.Info(fmt.Sprintf("formulaFormStr:%s", formulaFormStr))
  114. expression := formula.NewExpression(formulaFormStr)
  115. calResult, tmpErr := expression.Evaluate()
  116. if tmpErr != nil {
  117. // 分母为0的报错
  118. if strings.Contains(tmpErr.Error(), "divide by zero") {
  119. removeDateList = append(removeDateList, sk)
  120. continue
  121. }
  122. err = errors.New("计算失败:Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  123. //fmt.Println(err)
  124. return
  125. }
  126. calVal, tmpErr := calResult.Float64()
  127. if tmpErr != nil {
  128. err = errors.New("计算失败:获取计算值失败 Err:" + tmpErr.Error() + ";formulaStr:" + formulaFormStr)
  129. //fmt.Println(err)
  130. return
  131. }
  132. nanCheck := fmt.Sprintf("%0.f", calVal)
  133. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  134. removeDateList = append(removeDateList, sk)
  135. continue
  136. }
  137. saveValue := decimal.NewFromFloat(calVal).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  138. existPredictEdbRuleData, ok := dataMap[sk]
  139. if !ok {
  140. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  141. timestamp := dataTime.UnixNano() / 1e6
  142. if _, existOk := existDataMap[sk]; !existOk {
  143. tmpPredictEdbRuleData := &PredictEdbRuleData{
  144. //PredictEdbRuleDataId: 0,
  145. EdbInfoId: rule.EdbInfoId,
  146. ConfigId: rule.ConfigId,
  147. DataTime: sk,
  148. Value: saveValue,
  149. CreateTime: time.Now(),
  150. ModifyTime: time.Now(),
  151. DataTimestamp: timestamp,
  152. }
  153. addDataList = append(addDataList, tmpPredictEdbRuleData)
  154. }
  155. existDataMap[sk] = sk
  156. } else {
  157. existValDecimal, tmpErr := decimal.NewFromString(existPredictEdbRuleData.Value)
  158. if tmpErr != nil {
  159. err = tmpErr
  160. return
  161. }
  162. existStr := existValDecimal.String()
  163. if existStr != saveValue {
  164. existPredictEdbRuleData.Value = saveValue
  165. existPredictEdbRuleData.ModifyTime = time.Now()
  166. _, err = to.Update(existPredictEdbRuleData, "Value", "ModifyTime")
  167. if err != nil {
  168. return
  169. }
  170. }
  171. }
  172. // 计算出来的结果集
  173. resultDataList = append(resultDataList, &EdbInfoSearchData{
  174. //EdbDataId: 0,
  175. DataTime: sk,
  176. Value: calVal,
  177. })
  178. }
  179. // 添加计算出来的值入库
  180. lenAddDataList := len(addDataList)
  181. if lenAddDataList > 0 {
  182. _, err = to.InsertMulti(lenAddDataList, addDataList)
  183. if err != nil {
  184. return
  185. }
  186. }
  187. //删除多余的值
  188. lenRemoveDateList := len(removeDateList)
  189. if lenRemoveDateList > 0 {
  190. //如果拼接指标变更了,那么需要删除所有的指标数据
  191. sql := ` DELETE FROM predict_edb_rule_data WHERE config_id = ? and data_time in (` + utils.GetOrmInReplace(lenRemoveDateList) + `) `
  192. _, err = to.Raw(sql, rule.ConfigId, removeDateList).Exec()
  193. if err != nil {
  194. err = fmt.Errorf("删除计算失败的预测规则计算指标数据失败,Err:" + err.Error())
  195. return
  196. }
  197. }
  198. return
  199. }
  200. // RefreshCalculateByRuleByLineNh 刷新动态结果计算(线性拟合)
  201. func RefreshCalculateByRuleByLineNh(predictEdbInfo EdbInfo, predictEdbConfAndDataList []*PredictEdbConfAndData, rule PredictEdbConf) (err error, errMsg string) {
  202. o := orm.NewOrm()
  203. to, err := o.Begin()
  204. if err != nil {
  205. return
  206. }
  207. defer func() {
  208. if err != nil {
  209. to.Rollback()
  210. } else {
  211. err = to.Commit()
  212. }
  213. }()
  214. err, errMsg = CalculateByRuleByRuleLineNh(to, predictEdbInfo, predictEdbConfAndDataList, rule)
  215. return
  216. }
  217. // CalculateByRuleByRuleLineNh 一元线性拟合规则计算入库
  218. func CalculateByRuleByRuleLineNh(to orm.TxOrmer, predictEdbInfo EdbInfo, predictEdbConfAndDataList []*PredictEdbConfAndData, rule PredictEdbConf) (err error, errMsg string) {
  219. var secondDataList []*EdbInfoSearchData
  220. predictEdbInfoId := predictEdbInfo.EdbInfoId // 预测指标id
  221. // 规则
  222. var ruleConf RuleLineNhConf
  223. tmpErr := json.Unmarshal([]byte(rule.Value), &ruleConf)
  224. if tmpErr != nil {
  225. errMsg = `季节性配置信息异常`
  226. err = errors.New("季节性配置信息异常:" + tmpErr.Error())
  227. return
  228. }
  229. // 获取自身指标的数据
  230. {
  231. // 来源指标
  232. var sourceEdbInfoItem *EdbInfo
  233. sql := ` SELECT * FROM edb_info WHERE edb_info_id=? `
  234. err = to.Raw(sql, rule.SourceEdbInfoId).QueryRow(&sourceEdbInfoItem)
  235. if err != nil {
  236. return
  237. }
  238. predictEdbInfo.EdbInfoId = 0
  239. secondDataList, err, _ = GetPredictDataListByPredictEdbConfList(&predictEdbInfo, sourceEdbInfoItem, predictEdbConfAndDataList, 1, ``)
  240. if err != nil {
  241. return
  242. }
  243. }
  244. lenSecondData := len(secondDataList)
  245. if lenSecondData <= 0 {
  246. return
  247. }
  248. newNhccDataMap, err, errMsg := getCalculateNhccData(secondDataList, ruleConf)
  249. if err != nil {
  250. return
  251. }
  252. //将最后计算出来的结果数据处理(新增入库、编辑日期的值、删除日期)
  253. {
  254. // 获取需要预测的日期
  255. startDateStr := secondDataList[lenSecondData-1].DataTime
  256. startDate, _ := time.ParseInLocation(utils.FormatDate, startDateStr, time.Local)
  257. //endDate, _ := time.ParseInLocation(utils.FormatDate, ruleConf.EndDate, time.Local)
  258. endDate := rule.EndDate
  259. dayList := getPredictEdbDayList(startDate, endDate, predictEdbInfo.Frequency, predictEdbInfo.DataDateType)
  260. if len(dayList) <= 0 { // 如果未来没有日期的话,那么就退出当前循环,进入下一个循环
  261. return
  262. }
  263. //获取该配置的所有数据
  264. dataList := make([]*PredictEdbRuleData, 0)
  265. sql := `SELECT * FROM predict_edb_rule_data WHERE config_id = ?`
  266. _, err = to.Raw(sql, rule.ConfigId).QueryRows(&dataList)
  267. if err != nil {
  268. return
  269. }
  270. dataMap := make(map[string]*PredictEdbRuleData)
  271. for _, v := range dataList {
  272. dataMap[v.DataTime] = v
  273. }
  274. //需要移除的日期
  275. removeDateList := make([]string, 0)
  276. // 已经操作过的日期
  277. existDataMap := make(map[string]string)
  278. // 添加数据
  279. addDataList := make([]*PredictEdbRuleData, 0)
  280. for _, currentDate := range dayList {
  281. // 动态拟合残差值数据
  282. currentDateStr := currentDate.Format(utils.FormatDate)
  283. val, ok := newNhccDataMap[currentDateStr]
  284. // 找不到数据,那么就移除该日期的数据
  285. if !ok {
  286. removeDateList = append(removeDateList, currentDateStr)
  287. continue
  288. }
  289. saveValue := decimal.NewFromFloat(val).RoundCeil(4).String() //utils.SubFloatToString(calVal, 4)
  290. existPredictEdbRuleData, ok := dataMap[currentDateStr]
  291. if !ok {
  292. timestamp := currentDate.UnixNano() / 1e6
  293. if _, existOk := existDataMap[currentDateStr]; !existOk {
  294. tmpPredictEdbRuleData := &PredictEdbRuleData{
  295. //PredictEdbRuleDataId: 0,
  296. EdbInfoId: predictEdbInfoId,
  297. ConfigId: rule.ConfigId,
  298. DataTime: currentDateStr,
  299. Value: saveValue,
  300. CreateTime: time.Now(),
  301. ModifyTime: time.Now(),
  302. DataTimestamp: timestamp,
  303. }
  304. addDataList = append(addDataList, tmpPredictEdbRuleData)
  305. }
  306. existDataMap[currentDateStr] = currentDateStr
  307. } else {
  308. existValDecimal, tmpErr := decimal.NewFromString(existPredictEdbRuleData.Value)
  309. if tmpErr != nil {
  310. err = tmpErr
  311. return
  312. }
  313. existStr := existValDecimal.String()
  314. if existStr != saveValue {
  315. existPredictEdbRuleData.Value = saveValue
  316. existPredictEdbRuleData.ModifyTime = time.Now()
  317. _, err = to.Update(existPredictEdbRuleData, "Value", "ModifyTime")
  318. if err != nil {
  319. return
  320. }
  321. }
  322. }
  323. }
  324. // 添加计算出来的值入库
  325. lenAddDataList := len(addDataList)
  326. if lenAddDataList > 0 {
  327. _, err = to.InsertMulti(lenAddDataList, addDataList)
  328. if err != nil {
  329. return
  330. }
  331. }
  332. //删除多余的值
  333. lenRemoveDateList := len(removeDateList)
  334. if lenRemoveDateList > 0 {
  335. //如果拼接指标变更了,那么需要删除所有的指标数据
  336. sql := ` DELETE FROM predict_edb_rule_data WHERE config_id = ? and data_time in (` + utils.GetOrmInReplace(lenRemoveDateList) + `) `
  337. _, err = to.Raw(sql, rule.ConfigId, removeDateList).Exec()
  338. if err != nil {
  339. err = fmt.Errorf("删除计算失败的预测规则计算指标数据失败,Err:" + err.Error())
  340. return
  341. }
  342. }
  343. }
  344. return
  345. }