predict_edb.go 12 KB

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