predict_edb.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_index_lib/global"
  6. "eta_gn/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/dengsgo/math-engine/engine"
  9. "github.com/shopspring/decimal"
  10. "gorm.io/gorm"
  11. "strings"
  12. "time"
  13. )
  14. // CalculateRule 预测指标 规则 计算
  15. type CalculateRule struct {
  16. EdbInfoId int `description:"指标id"`
  17. ConfigId int `description:"配置id"`
  18. TrendsCalculateMappingList []*PredictEdbConfCalculateMapping
  19. EdbInfoList []*EdbInfo
  20. EdbInfoIdBytes []string
  21. Formula string
  22. RuleType int `description:"预测规则,1:最新,2:固定值,3:同比,4:同差,5:环比,6:环差,7:N期移动均值,8:N期段线性外推值,9:动态环差"`
  23. EndDate string `description:"截止日期"`
  24. EdbInfoIdArr []EdbInfoFromTag `description:"指标信息"`
  25. EmptyType int `description:"空值处理类型(0查找前后35天,1不计算,2前值填充,3后值填充,4等于0)"`
  26. MaxEmptyType int `description:"MAX、MIN公式空值处理类型(1、等于0;2、跳过空值)"`
  27. }
  28. // RefreshCalculateByRuleBy9 刷新计算
  29. func RefreshCalculateByRuleBy9(rule CalculateRule) (resultDataList []*EdbInfoSearchData, err error) {
  30. to := global.DEFAULT_DmSQL.Begin()
  31. defer func() {
  32. if err != nil {
  33. to.Rollback()
  34. } else {
  35. to.Commit()
  36. }
  37. }()
  38. resultDataList, err = CalculateByRuleBy9(to, rule)
  39. return
  40. }
  41. // CalculateByRuleBy9 动态环差规则计算入库
  42. func CalculateByRuleBy9(to *gorm.DB, rule CalculateRule) (resultDataList []*EdbInfoSearchData, err error) {
  43. realSaveDataMap := make(map[string]map[int]float64)
  44. saveDataMap := make(map[string]map[int]float64)
  45. // 最小的结束日期 , 最晚的数据开始日期
  46. var minLatestDate, maxStartDate time.Time
  47. dateList := make([]string, 0) // 第一个指标的日期数据
  48. formulaStr := strings.ToUpper(rule.Formula)
  49. // 获取关联指标数据
  50. for edbInfoIndex, v := range rule.EdbInfoList {
  51. dataList, tmpErr := GetPredictEdbDataListAll(v, 1)
  52. if tmpErr != nil {
  53. err = tmpErr
  54. return
  55. }
  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. tmpDate, _ := time.ParseInLocation(utils.FormatDate, dv.DataTime, time.Local)
  81. if minLatestDate.IsZero() || tmpDate.After(minLatestDate) {
  82. minLatestDate = tmpDate
  83. }
  84. if maxStartDate.IsZero() || tmpDate.Before(maxStartDate) {
  85. maxStartDate = tmpDate
  86. }
  87. }
  88. }
  89. }
  90. // todo 数据处理,将日期内不全的数据做填补
  91. HandleDateSaveDataMap(dateList, maxStartDate, minLatestDate, realSaveDataMap, saveDataMap, rule.EdbInfoList, rule.EmptyType)
  92. // 添加数据
  93. addDataList := make([]*PredictEdbRuleData, 0)
  94. // 计算规则
  95. formulaDateSlice, formulaDateMap, err := utils.HandleFormulaJson(formulaStr, minLatestDate)
  96. if err != nil {
  97. return
  98. }
  99. //获取指标所有数据
  100. dataList := make([]*PredictEdbRuleData, 0)
  101. sql := `SELECT * FROM predict_edb_rule_data WHERE config_id = ?`
  102. err = to.Raw(sql, rule.ConfigId).Scan(&dataList).Error
  103. if err != nil {
  104. return
  105. }
  106. dataMap := make(map[string]*PredictEdbRuleData)
  107. removeDateMap := make(map[string]*PredictEdbRuleData) //需要移除的日期
  108. for _, v := range dataList {
  109. dataMap[v.DataTime] = v
  110. removeDateMap[v.DataTime] = v
  111. }
  112. existDataMap := make(map[string]string)
  113. // 判断是否特殊处理max和min函数
  114. maxDealFlag := false
  115. if rule.EmptyType == 4 && rule.MaxEmptyType == 2 {
  116. maxDealFlag = true
  117. }
  118. for sk, sv := range saveDataMap {
  119. // 当空值处理类型选择了不计算时,只要有一个指标在某个日期没有值(即空值),则计算指标在该日期没有值
  120. if rule.EmptyType == 1 {
  121. if len(sv) != len(rule.EdbInfoList) {
  122. continue
  123. }
  124. }
  125. //fmt.Println(sk, sv)
  126. // 根据时间范围,选择对应的公式
  127. formulaMap := make(map[string]string)
  128. formulaStr = ""
  129. for _, fv := range formulaDateSlice {
  130. if sk < fv {
  131. if f, ok := formulaDateMap[fv]; ok {
  132. formulaStr = f
  133. formulaMap, err = utils.CheckFormula(formulaStr)
  134. if err != nil {
  135. err = fmt.Errorf("公式错误,请重新填写")
  136. return
  137. }
  138. }
  139. break
  140. }
  141. }
  142. if formulaStr == "" {
  143. continue
  144. }
  145. svMax := make(map[int]float64)
  146. if maxDealFlag {
  147. // 特殊处理max和min函数,如果原本的值为空,则选择空值参与运算
  148. if svMaxData, ok := realSaveDataMap[sk]; ok {
  149. svMax = svMaxData
  150. }
  151. }
  152. formulaStr = strings.ToUpper(formulaStr)
  153. //fmt.Println(sk, sv)
  154. formulaFormStr := ReplaceFormula(rule.EdbInfoList, sv, svMax, formulaMap, formulaStr, rule.EdbInfoIdBytes, maxDealFlag)
  155. //计算公式异常,那么就移除该指标
  156. if formulaFormStr == "" {
  157. continue
  158. }
  159. calVal, err := engine.ParseAndExec(formulaFormStr)
  160. if err != nil {
  161. // 分母为0的报错,忽略该循环
  162. if utils.IsDivideZero(err) {
  163. continue
  164. }
  165. err = errors.New("计算失败:获取计算值失败 Err:" + err.Error() + ";formulaStr:" + formulaFormStr)
  166. fmt.Println(err)
  167. return nil, err
  168. }
  169. nanCheck := fmt.Sprintf("%0.f", calVal)
  170. if nanCheck == "NaN" || nanCheck == "+Inf" || nanCheck == "-Inf" {
  171. continue
  172. }
  173. // 移除不存在的日期
  174. delete(removeDateMap, sk)
  175. saveValue := decimal.NewFromFloat(calVal).Round(4).String() //utils.SubFloatToString(calVal, 4)
  176. existPredictEdbRuleData, ok := dataMap[sk]
  177. if !ok {
  178. dataTime, _ := time.ParseInLocation(utils.FormatDate, sk, time.Local)
  179. timestamp := dataTime.UnixNano() / 1e6
  180. if _, existOk := existDataMap[sk]; !existOk {
  181. tmpPredictEdbRuleData := &PredictEdbRuleData{
  182. //PredictEdbRuleDataId: 0,
  183. EdbInfoId: rule.EdbInfoId,
  184. ConfigId: rule.ConfigId,
  185. DataTime: sk,
  186. Value: saveValue,
  187. CreateTime: time.Now(),
  188. ModifyTime: time.Now(),
  189. DataTimestamp: timestamp,
  190. }
  191. addDataList = append(addDataList, tmpPredictEdbRuleData)
  192. }
  193. existDataMap[sk] = sk
  194. } else {
  195. existValDecimal, tmpErr := decimal.NewFromString(existPredictEdbRuleData.Value)
  196. if tmpErr != nil {
  197. err = tmpErr
  198. return nil, tmpErr
  199. }
  200. existStr := existValDecimal.String()
  201. if existStr != saveValue {
  202. existPredictEdbRuleData.Value = saveValue
  203. existPredictEdbRuleData.ModifyTime = time.Now()
  204. err = to.Model(existPredictEdbRuleData).Select([]string{"Value", "ModifyTime"}).Updates(existPredictEdbRuleData).Error
  205. if err != nil {
  206. return nil, err
  207. }
  208. }
  209. }
  210. // 计算出来的结果集
  211. resultDataList = append(resultDataList, &EdbInfoSearchData{
  212. //EdbDataId: 0,
  213. DataTime: sk,
  214. Value: calVal,
  215. })
  216. }
  217. // 添加计算出来的值入库
  218. lenAddDataList := len(addDataList)
  219. if lenAddDataList > 0 {
  220. err = to.CreateInBatches(addDataList, 500).Error
  221. if err != nil {
  222. return
  223. }
  224. }
  225. //删除多余的值
  226. lenRemoveDateList := len(removeDateMap)
  227. if lenRemoveDateList > 0 {
  228. removeDateList := make([]string, 0) //需要移除的日期
  229. for date, _ := range removeDateMap {
  230. removeDateList = append(removeDateList, date)
  231. }
  232. //如果拼接指标变更了,那么需要删除所有的指标数据
  233. sql := ` DELETE FROM predict_edb_rule_data WHERE config_id = ? and data_time in (` + utils.GetOrmInReplace(lenRemoveDateList) + `) `
  234. err = to.Exec(sql, rule.ConfigId, removeDateList).Error
  235. if err != nil {
  236. err = fmt.Errorf("删除计算失败的预测规则计算指标数据失败,Err:" + err.Error())
  237. return
  238. }
  239. }
  240. return
  241. }
  242. // RefreshCalculateByRuleByLineNh 刷新动态结果计算(线性拟合)
  243. func RefreshCalculateByRuleByLineNh(predictEdbInfo EdbInfo, predictEdbConfAndDataList []*PredictEdbConfAndData, rule PredictEdbConf) (err error, errMsg string) {
  244. to := global.DEFAULT_DmSQL.Begin()
  245. defer func() {
  246. if err != nil {
  247. to.Rollback()
  248. } else {
  249. to.Commit()
  250. }
  251. }()
  252. err, errMsg = CalculateByRuleByRuleLineNh(to, predictEdbInfo, predictEdbConfAndDataList, rule)
  253. return
  254. }
  255. // CalculateByRuleByRuleLineNh 一元线性拟合规则计算入库
  256. func CalculateByRuleByRuleLineNh(to *gorm.DB, predictEdbInfo EdbInfo, predictEdbConfAndDataList []*PredictEdbConfAndData, rule PredictEdbConf) (err error, errMsg string) {
  257. var secondDataList []*EdbInfoSearchData
  258. predictEdbInfoId := predictEdbInfo.EdbInfoId // 预测指标id
  259. // 规则
  260. var ruleConf RuleLineNhConf
  261. tmpErr := json.Unmarshal([]byte(rule.Value), &ruleConf)
  262. if tmpErr != nil {
  263. errMsg = `季节性配置信息异常`
  264. err = errors.New("季节性配置信息异常:" + tmpErr.Error())
  265. return
  266. }
  267. // 获取自身指标的数据
  268. {
  269. // 来源指标
  270. var sourceEdbInfoItem *EdbInfo
  271. sql := ` SELECT * FROM edb_info WHERE edb_info_id=? `
  272. err = to.Raw(sql, rule.SourceEdbInfoId).First(&sourceEdbInfoItem).Error
  273. if err != nil {
  274. return
  275. }
  276. predictEdbInfo.EdbInfoId = 0
  277. secondDataList, err, _ = GetPredictDataListByPredictEdbConfList(&predictEdbInfo, sourceEdbInfoItem, predictEdbConfAndDataList, 1, ``)
  278. if err != nil {
  279. return
  280. }
  281. }
  282. lenSecondData := len(secondDataList)
  283. if lenSecondData <= 0 {
  284. return
  285. }
  286. newNhccDataMap, err, errMsg := getCalculateNhccData(secondDataList, ruleConf)
  287. if err != nil {
  288. return
  289. }
  290. //将最后计算出来的结果数据处理(新增入库、编辑日期的值、删除日期)
  291. {
  292. // 获取需要预测的日期
  293. startDateStr := secondDataList[lenSecondData-1].DataTime
  294. startDate, _ := time.ParseInLocation(utils.FormatDate, startDateStr, time.Local)
  295. //endDate, _ := time.ParseInLocation(utils.FormatDate, ruleConf.EndDate, time.Local)
  296. endDate := rule.EndDate
  297. dayList := getPredictEdbDayList(startDate, endDate, predictEdbInfo.Frequency, predictEdbInfo.DataDateType)
  298. if len(dayList) <= 0 { // 如果未来没有日期的话,那么就退出当前循环,进入下一个循环
  299. return
  300. }
  301. //获取该配置的所有数据
  302. dataList := make([]*PredictEdbRuleData, 0)
  303. sql := `SELECT * FROM predict_edb_rule_data WHERE config_id = ?`
  304. err = to.Raw(sql, rule.ConfigId).Scan(&dataList).Error
  305. if err != nil {
  306. return
  307. }
  308. dataMap := make(map[string]*PredictEdbRuleData)
  309. for _, v := range dataList {
  310. dataMap[v.DataTime] = v
  311. }
  312. //需要移除的日期
  313. removeDateList := make([]string, 0)
  314. // 已经操作过的日期
  315. existDataMap := make(map[string]string)
  316. // 添加数据
  317. addDataList := make([]*PredictEdbRuleData, 0)
  318. for _, currentDate := range dayList {
  319. // 动态拟合残差值数据
  320. currentDateStr := currentDate.Format(utils.FormatDate)
  321. val, ok := newNhccDataMap[currentDateStr]
  322. // 找不到数据,那么就移除该日期的数据
  323. if !ok {
  324. removeDateList = append(removeDateList, currentDateStr)
  325. continue
  326. }
  327. saveValue := decimal.NewFromFloat(val).Round(4).String() //utils.SubFloatToString(calVal, 4)
  328. existPredictEdbRuleData, ok := dataMap[currentDateStr]
  329. if !ok {
  330. timestamp := currentDate.UnixNano() / 1e6
  331. if _, existOk := existDataMap[currentDateStr]; !existOk {
  332. tmpPredictEdbRuleData := &PredictEdbRuleData{
  333. //PredictEdbRuleDataId: 0,
  334. EdbInfoId: predictEdbInfoId,
  335. ConfigId: rule.ConfigId,
  336. DataTime: currentDateStr,
  337. Value: saveValue,
  338. CreateTime: time.Now(),
  339. ModifyTime: time.Now(),
  340. DataTimestamp: timestamp,
  341. }
  342. addDataList = append(addDataList, tmpPredictEdbRuleData)
  343. }
  344. existDataMap[currentDateStr] = currentDateStr
  345. } else {
  346. existValDecimal, tmpErr := decimal.NewFromString(existPredictEdbRuleData.Value)
  347. if tmpErr != nil {
  348. err = tmpErr
  349. return
  350. }
  351. existStr := existValDecimal.String()
  352. if existStr != saveValue {
  353. existPredictEdbRuleData.Value = saveValue
  354. existPredictEdbRuleData.ModifyTime = time.Now()
  355. err = to.Model(existPredictEdbRuleData).Select([]string{"Value", "ModifyTime"}).Updates(existPredictEdbRuleData).Error
  356. if err != nil {
  357. return
  358. }
  359. }
  360. }
  361. }
  362. // 添加计算出来的值入库
  363. lenAddDataList := len(addDataList)
  364. if lenAddDataList > 0 {
  365. err = to.CreateInBatches(addDataList, 500).Error
  366. if err != nil {
  367. return
  368. }
  369. }
  370. //删除多余的值
  371. lenRemoveDateList := len(removeDateList)
  372. if lenRemoveDateList > 0 {
  373. //如果拼接指标变更了,那么需要删除所有的指标数据
  374. sql := ` DELETE FROM predict_edb_rule_data WHERE config_id = ? and data_time in (` + utils.GetOrmInReplace(lenRemoveDateList) + `) `
  375. err = to.Exec(sql, rule.ConfigId, removeDateList).Error
  376. if err != nil {
  377. err = fmt.Errorf("删除计算失败的预测规则计算指标数据失败,Err:" + err.Error())
  378. return
  379. }
  380. }
  381. }
  382. return
  383. }