edb_data_calculate_nhcc.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. package models
  2. import (
  3. "errors"
  4. "eta/eta_index_lib/utils"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/shopspring/decimal"
  8. "math"
  9. "strings"
  10. "time"
  11. )
  12. // EdbDataCalculateNhcc 拟合残差数据结构体
  13. type EdbDataCalculateNhcc struct {
  14. EdbDataId int `orm:"column(edb_data_id);pk"`
  15. EdbInfoId int
  16. EdbCode string
  17. DataTime string
  18. Value float64
  19. Status int
  20. CreateTime time.Time
  21. ModifyTime time.Time
  22. DataTimestamp int64
  23. }
  24. // NhccDate 拟合残差的开始、结束日期
  25. type NhccDate struct {
  26. StartDate time.Time
  27. EndDate time.Time
  28. }
  29. // AddCalculateNhcc 新增拟合残差数据
  30. func AddCalculateNhcc(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, edbCode, uniqueCode string, nhccDate NhccDate, sysUserId int, sysUserRealName string) (edbInfo *EdbInfo, err error, errMsg string) {
  31. o := orm.NewOrm()
  32. to, err := o.Begin()
  33. if err != nil {
  34. return
  35. }
  36. defer func() {
  37. if err != nil {
  38. fmt.Println("AddCalculateNhcc,Err:" + err.Error())
  39. _ = to.Rollback()
  40. } else {
  41. _ = to.Commit()
  42. }
  43. }()
  44. if req.EdbInfoId <= 0 {
  45. edbInfo = &EdbInfo{
  46. SourceName: "拟合残差",
  47. Source: utils.DATA_SOURCE_CALCULATE_NHCC,
  48. EdbCode: edbCode,
  49. EdbName: req.EdbName,
  50. EdbNameSource: req.EdbName,
  51. Frequency: req.Frequency,
  52. Unit: req.Unit,
  53. StartDate: firstEdbInfo.StartDate,
  54. EndDate: firstEdbInfo.EndDate,
  55. ClassifyId: req.ClassifyId,
  56. SysUserId: sysUserId,
  57. SysUserRealName: sysUserRealName,
  58. UniqueCode: uniqueCode,
  59. CreateTime: time.Now(),
  60. ModifyTime: time.Now(),
  61. CalculateFormula: req.Formula,
  62. EdbType: 2,
  63. }
  64. newEdbInfoId, tmpErr := to.Insert(edbInfo)
  65. if tmpErr != nil {
  66. err = tmpErr
  67. return
  68. }
  69. edbInfo.EdbInfoId = int(newEdbInfoId)
  70. } else {
  71. edbInfo, err = GetEdbInfoById(req.EdbInfoId)
  72. if err != nil {
  73. return
  74. }
  75. //查询
  76. tmpEdbInfo, tmpErr := GetEdbInfoById(edbInfo.EdbInfoId)
  77. if tmpErr != nil {
  78. err = tmpErr
  79. return
  80. }
  81. tmpEdbInfo.EdbName = req.EdbName
  82. tmpEdbInfo.ClassifyId = req.ClassifyId
  83. tmpEdbInfo.Frequency = req.Frequency
  84. tmpEdbInfo.Unit = req.Unit
  85. tmpEdbInfo.CalculateFormula = req.Formula
  86. edbInfo = tmpEdbInfo
  87. //删除指标数据
  88. dataTableName := GetEdbDataTableName(utils.DATA_SOURCE_CALCULATE_NHCC, utils.DATA_SUB_SOURCE_EDB)
  89. fmt.Println("dataTableName:" + dataTableName)
  90. deleteSql := ` DELETE FROM %s WHERE edb_info_id=? `
  91. deleteSql = fmt.Sprintf(deleteSql, dataTableName)
  92. _, err = to.Raw(deleteSql, req.EdbInfoId).Exec()
  93. if err != nil {
  94. return
  95. }
  96. //删除指标关系
  97. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id=? `
  98. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  99. }
  100. //关联关系
  101. var existItemA, existItemB *EdbInfoCalculateMapping
  102. //第一个指标
  103. {
  104. existItemA = &EdbInfoCalculateMapping{
  105. EdbInfoCalculateMappingId: 0,
  106. EdbInfoId: edbInfo.EdbInfoId,
  107. Source: edbInfo.Source,
  108. SourceName: edbInfo.SourceName,
  109. EdbCode: edbInfo.EdbCode,
  110. FromEdbInfoId: firstEdbInfo.EdbInfoId,
  111. FromEdbCode: firstEdbInfo.EdbCode,
  112. FromEdbName: firstEdbInfo.EdbName,
  113. FromSource: firstEdbInfo.Source,
  114. FromSourceName: firstEdbInfo.SourceName,
  115. FromTag: "A",
  116. MoveValue: req.EdbInfoIdArr[0].MoveValue,
  117. Sort: 1,
  118. CreateTime: time.Now(),
  119. ModifyTime: time.Now(),
  120. FromSubSource: firstEdbInfo.SubSource,
  121. }
  122. insertId, tmpErr := to.Insert(existItemA)
  123. if tmpErr != nil {
  124. err = tmpErr
  125. return
  126. }
  127. existItemA.EdbInfoCalculateMappingId = int(insertId)
  128. }
  129. //第二个指标
  130. {
  131. existItemB = &EdbInfoCalculateMapping{
  132. EdbInfoCalculateMappingId: 0,
  133. EdbInfoId: edbInfo.EdbInfoId,
  134. Source: edbInfo.Source,
  135. SourceName: edbInfo.SourceName,
  136. EdbCode: edbInfo.EdbCode,
  137. FromEdbInfoId: secondEdbInfo.EdbInfoId,
  138. FromEdbCode: secondEdbInfo.EdbCode,
  139. FromEdbName: secondEdbInfo.EdbName,
  140. FromSource: secondEdbInfo.Source,
  141. FromSourceName: secondEdbInfo.SourceName,
  142. FromTag: "B",
  143. MoveValue: req.EdbInfoIdArr[1].MoveValue,
  144. Sort: 1,
  145. CreateTime: time.Now(),
  146. ModifyTime: time.Now(),
  147. FromSubSource: secondEdbInfo.SubSource,
  148. }
  149. insertId, tmpErr := to.Insert(existItemB)
  150. if tmpErr != nil {
  151. err = tmpErr
  152. return
  153. }
  154. existItemB.EdbInfoCalculateMappingId = int(insertId)
  155. }
  156. //拼接数据
  157. err, errMsg = refreshAllCalculateNhcc(to, edbInfo, existItemA, existItemB, nhccDate)
  158. return
  159. }
  160. // EditCalculateNhcc 编辑拟合残差数据
  161. func EditCalculateNhcc(req *EdbInfoCalculateBatchEditReq, edbInfo, firstEdbInfo, secondEdbInfo *EdbInfo, nhccDate NhccDate) (err error, errMsg string) {
  162. o := orm.NewOrm()
  163. to, err := o.Begin()
  164. if err != nil {
  165. return
  166. }
  167. defer func() {
  168. if err != nil {
  169. fmt.Println("EditCalculateNhcc,Err:" + err.Error())
  170. _ = to.Rollback()
  171. } else {
  172. _ = to.Commit()
  173. }
  174. }()
  175. nowEdbInfo := *edbInfo // 现在的指标信息
  176. //修改指标信息
  177. edbInfo.EdbName = req.EdbName
  178. edbInfo.EdbNameSource = req.EdbName
  179. edbInfo.Frequency = req.Frequency
  180. edbInfo.Unit = req.Unit
  181. edbInfo.ClassifyId = req.ClassifyId
  182. edbInfo.CalculateFormula = req.Formula
  183. edbInfo.ModifyTime = time.Now()
  184. _, err = to.Update(edbInfo, "EdbName", "EdbNameSource", "Frequency", "Unit", "ClassifyId", "CalculateFormula", "ModifyTime")
  185. if err != nil {
  186. return
  187. }
  188. var existCondition string
  189. var existPars []interface{}
  190. existCondition += " AND edb_info_id=? "
  191. existPars = append(existPars, edbInfo.EdbInfoId)
  192. //查询出所有的关联指标
  193. existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
  194. if err != nil {
  195. err = fmt.Errorf("判断指标是否改变失败,Err:" + err.Error())
  196. return
  197. }
  198. var existItemA, existItemB *EdbInfoCalculateMapping
  199. for _, existItem := range existList {
  200. if existItem.FromTag == "A" {
  201. existItemA = existItem
  202. } else if existItem.FromTag == "B" {
  203. existItemB = existItem
  204. }
  205. }
  206. // 是否需要删除数据重新计算
  207. isNeedCalculateData := false
  208. // 如果截止日期变更,那么需要重新计算
  209. if req.Formula != nowEdbInfo.CalculateFormula {
  210. isNeedCalculateData = true
  211. }
  212. var isDeleteA, isDeleteB bool
  213. // 如果指标变了,那么需要删除关系
  214. {
  215. if existItemA.FromEdbInfoId != firstEdbInfo.EdbInfoId {
  216. //删除之前的A指标关联关系
  217. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
  218. _, err = to.Raw(sql, edbInfo.EdbInfoId, existItemA.FromEdbInfoId).Exec()
  219. if err != nil {
  220. err = fmt.Errorf("删除指标A关联关系失败,Err:" + err.Error())
  221. return
  222. }
  223. isDeleteA = true
  224. }
  225. //并重新计算
  226. if existItemB.FromEdbInfoId != secondEdbInfo.EdbInfoId {
  227. //删除之前的B指标关联关系
  228. sql := ` DELETE FROM edb_info_calculate_mapping WHERE edb_info_id = ? and from_edb_info_id = ?`
  229. _, err = to.Raw(sql, edbInfo.EdbInfoId, existItemB.FromEdbInfoId).Exec()
  230. if err != nil {
  231. err = fmt.Errorf("删除指标B关联关系失败,Err:" + err.Error())
  232. return
  233. }
  234. isDeleteB = true
  235. }
  236. }
  237. //第一个指标数据
  238. {
  239. // 如果指标变了,那么需要删除关系,并重新计算
  240. if isDeleteA {
  241. //添加新的指标关系
  242. {
  243. existItemA = &EdbInfoCalculateMapping{
  244. EdbInfoCalculateMappingId: 0,
  245. EdbInfoId: edbInfo.EdbInfoId,
  246. Source: edbInfo.Source,
  247. SourceName: edbInfo.SourceName,
  248. EdbCode: edbInfo.EdbCode,
  249. FromEdbInfoId: firstEdbInfo.EdbInfoId,
  250. FromEdbCode: firstEdbInfo.EdbCode,
  251. FromEdbName: firstEdbInfo.EdbName,
  252. FromSource: firstEdbInfo.Source,
  253. FromSourceName: firstEdbInfo.SourceName,
  254. FromTag: "A",
  255. MoveValue: req.EdbInfoIdArr[0].MoveValue,
  256. Sort: 1,
  257. CreateTime: time.Now(),
  258. ModifyTime: time.Now(),
  259. FromSubSource: firstEdbInfo.SubSource,
  260. }
  261. insertId, tmpErr := to.Insert(existItemA)
  262. if tmpErr != nil {
  263. err = tmpErr
  264. return
  265. }
  266. existItemA.EdbInfoCalculateMappingId = int(insertId)
  267. isNeedCalculateData = true
  268. }
  269. } else if existItemA.MoveValue != req.EdbInfoIdArr[0].MoveValue {
  270. // 如果平移天数不一致的话,
  271. existItemA.ModifyTime = time.Now()
  272. existItemA.MoveValue = req.EdbInfoIdArr[0].MoveValue
  273. _, err = to.Update(existItemA, "ModifyTime", "MoveValue")
  274. if err != nil {
  275. return
  276. }
  277. isNeedCalculateData = true
  278. }
  279. }
  280. //第二个指标数据
  281. {
  282. // 如果指标变了,那么需要删除关系,并重新计算
  283. if isDeleteB {
  284. // 添加新的指标关联关系
  285. existItemB = &EdbInfoCalculateMapping{
  286. EdbInfoCalculateMappingId: 0,
  287. EdbInfoId: edbInfo.EdbInfoId,
  288. Source: edbInfo.Source,
  289. SourceName: edbInfo.SourceName,
  290. EdbCode: edbInfo.EdbCode,
  291. FromEdbInfoId: secondEdbInfo.EdbInfoId,
  292. FromEdbCode: secondEdbInfo.EdbCode,
  293. FromEdbName: secondEdbInfo.EdbName,
  294. FromSource: secondEdbInfo.Source,
  295. FromSourceName: secondEdbInfo.SourceName,
  296. FromTag: "B",
  297. MoveValue: req.EdbInfoIdArr[1].MoveValue,
  298. Sort: 2,
  299. CreateTime: time.Now(),
  300. ModifyTime: time.Now(),
  301. FromSubSource: secondEdbInfo.SubSource,
  302. }
  303. insertId, tmpErr := to.Insert(existItemB)
  304. if tmpErr != nil {
  305. err = tmpErr
  306. return
  307. }
  308. existItemB.EdbInfoCalculateMappingId = int(insertId)
  309. isNeedCalculateData = true
  310. } else if existItemB.MoveValue != req.EdbInfoIdArr[1].MoveValue {
  311. // 如果平移天数不一致的话,
  312. existItemB.ModifyTime = time.Now()
  313. existItemB.MoveValue = req.EdbInfoIdArr[1].MoveValue
  314. _, err = to.Update(existItemB, "ModifyTime", "MoveValue")
  315. if err != nil {
  316. return
  317. }
  318. isNeedCalculateData = true
  319. }
  320. }
  321. // 如果需要重新计算,那么先删除所有的指标数据,然后再重新计算
  322. if isNeedCalculateData {
  323. // 删除之前所有的指标数据
  324. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  325. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? `, tableName)
  326. _, err = to.Raw(sql, edbInfo.EdbInfoId).Exec()
  327. if err != nil {
  328. err = fmt.Errorf("删除历史数据失败,Err:" + err.Error())
  329. return
  330. }
  331. err, errMsg = refreshAllCalculateNhcc(to, edbInfo, existItemA, existItemB, nhccDate)
  332. }
  333. return
  334. }
  335. // RefreshAllCalculateNhcc 刷新所有 拟合残差 数据
  336. func RefreshAllCalculateNhcc(edbInfo *EdbInfo) (err error) {
  337. o := orm.NewOrm()
  338. to, err := o.Begin()
  339. defer func() {
  340. if err != nil {
  341. fmt.Println("RefreshAllCalculateNhcc,Err:" + err.Error())
  342. _ = to.Rollback()
  343. } else {
  344. _ = to.Commit()
  345. }
  346. }()
  347. //查询关联指标信息
  348. var existCondition string
  349. var existPars []interface{}
  350. existCondition += " AND edb_info_id=? "
  351. existPars = append(existPars, edbInfo.EdbInfoId)
  352. existList, err := GetEdbInfoCalculateListByCondition(existCondition, existPars)
  353. if err != nil {
  354. err = fmt.Errorf("判断指标是否改变失败,Err:" + err.Error())
  355. return
  356. }
  357. var existItemA, existItemB *EdbInfoCalculateMapping
  358. for _, existItem := range existList {
  359. if existItem.FromTag == "A" {
  360. existItemA = existItem
  361. } else if existItem.FromTag == "B" {
  362. existItemB = existItem
  363. }
  364. }
  365. timeList := strings.Split(edbInfo.CalculateFormula, ",")
  366. startDate, err := time.ParseInLocation(utils.FormatDate, timeList[0], time.Local)
  367. if err != nil {
  368. return
  369. }
  370. endDate, err := time.ParseInLocation(utils.FormatDate, timeList[1], time.Local)
  371. if err != nil {
  372. return
  373. }
  374. if endDate.Sub(startDate).Hours() < 48 {
  375. return
  376. }
  377. nhccDate := NhccDate{
  378. StartDate: startDate,
  379. EndDate: endDate,
  380. }
  381. // 刷新数据
  382. err, _ = refreshAllCalculateNhcc(to, edbInfo, existItemA, existItemB, nhccDate)
  383. return
  384. }
  385. // refreshAllCalculateNhcc 刷新所有 拟合残差 数据
  386. func refreshAllCalculateNhcc(to orm.TxOrmer, edbInfo *EdbInfo, existItemA, existItemB *EdbInfoCalculateMapping, nhccDate NhccDate) (err error, errMsg string) {
  387. //查询当前指标现有的数据
  388. var condition string
  389. var pars []interface{}
  390. condition += " AND edb_info_id=? "
  391. pars = append(pars, edbInfo.EdbInfoId)
  392. var dataList []*EdbDataCalculateNhcc
  393. sql := ` SELECT * FROM edb_data_calculate_nhcc WHERE edb_info_id=? ORDER BY data_time DESC `
  394. _, err = to.Raw(sql, edbInfo.EdbInfoId).QueryRows(&dataList)
  395. if err != nil {
  396. return
  397. }
  398. var dateArr []string
  399. dataMap := make(map[string]*EdbDataCalculateNhcc)
  400. removeDataTimeMap := make(map[string]int) //需要移除的日期数据
  401. for _, v := range dataList {
  402. dateArr = append(dateArr, v.DataTime)
  403. dataMap[v.DataTime] = v
  404. removeDataTimeMap[v.DataTime] = 1
  405. }
  406. addDataList := make([]*EdbDataCalculateNhcc, 0)
  407. ////第一个指标
  408. //aDataList := make([]EdbInfoSearchData, 0)
  409. //aDataMap := make(map[string]float64)
  410. //{
  411. // var condition string
  412. // var pars []interface{}
  413. //
  414. // condition += " AND edb_info_id=? "
  415. // pars = append(pars, existItemA.FromEdbInfoId)
  416. //
  417. // //第一个指标的数据列表
  418. // firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemA.FromSource, 0)
  419. // if tmpErr != nil {
  420. // return tmpErr
  421. // }
  422. // aDataList, aDataMap = handleNhccData(firstDataList, existItemA.MoveValue)
  423. //
  424. //}
  425. //
  426. ////第二个指标
  427. //bDataList := make([]EdbInfoSearchData, 0)
  428. //secondDataList := make([]*EdbInfoSearchData, 0)
  429. //bDataMap := make(map[string]float64)
  430. //{
  431. // condition = ``
  432. // pars = make([]interface{}, 0)
  433. //
  434. // condition += " AND edb_info_id = ? "
  435. // pars = append(pars, existItemB.FromEdbInfoId)
  436. //
  437. // //第二个指标的数据列表
  438. // secondDataList, err = GetEdbDataListAllByTo(to, condition, pars, existItemB.FromSource, 0)
  439. // if err != nil {
  440. // return
  441. // }
  442. // bDataList, bDataMap = handleNhccData(secondDataList, existItemB.MoveValue)
  443. //}
  444. //
  445. //if len(aDataList) <= 0 {
  446. // err = errors.New("指标A没有数据")
  447. // return
  448. //}
  449. //if len(bDataList) <= 0 {
  450. // err = errors.New("指标B没有数据")
  451. // return
  452. //}
  453. //// 拟合残差计算的结束日期判断
  454. //{
  455. // endAData := aDataList[len(aDataList)-1]
  456. // tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, endAData.DataTime, time.Local)
  457. // if tmpErr != nil {
  458. // err = tmpErr
  459. // return
  460. // }
  461. // // 如果A指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  462. // if tmpEndDate.Before(nhccDate.EndDate) {
  463. // nhccDate.EndDate = tmpEndDate
  464. // }
  465. // endBData := bDataList[len(bDataList)-1]
  466. // tmpEndDate, tmpErr = time.ParseInLocation(utils.FormatDate, endBData.DataTime, time.Local)
  467. // if tmpErr != nil {
  468. // err = tmpErr
  469. // return
  470. // }
  471. // // 如果B指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  472. // if tmpEndDate.Before(nhccDate.EndDate) {
  473. // nhccDate.EndDate = tmpEndDate
  474. // }
  475. //}
  476. aDataList, secondDataList, aDataMap, bDataMap, nhccDate, err, errMsg := getNhccData(to, existItemA, existItemB, nhccDate)
  477. if err != nil {
  478. return
  479. }
  480. // 计算线性方程公式
  481. var a, b float64
  482. {
  483. coordinateData := make([]utils.Coordinate, 0)
  484. for i := nhccDate.StartDate; i.Before(nhccDate.EndDate) || i.Equal(nhccDate.EndDate); i = i.AddDate(0, 0, 1) {
  485. dateStr := i.Format(utils.FormatDate)
  486. xValue, ok := aDataMap[dateStr]
  487. if !ok {
  488. errMsg = "指标A日期:" + dateStr + "数据异常,导致计算线性方程公式失败"
  489. err = errors.New(errMsg)
  490. return
  491. }
  492. yValue, ok := bDataMap[dateStr]
  493. if !ok {
  494. errMsg = "指标B日期:" + dateStr + "数据异常,导致计算线性方程公式失败"
  495. err = errors.New(errMsg)
  496. return
  497. }
  498. tmpCoordinate := utils.Coordinate{
  499. X: xValue,
  500. Y: yValue,
  501. }
  502. coordinateData = append(coordinateData, tmpCoordinate)
  503. }
  504. a, b = utils.GetLinearResult(coordinateData)
  505. }
  506. if math.IsNaN(a) || math.IsNaN(b) {
  507. errMsg = "线性方程公式生成失败"
  508. err = errors.New(errMsg)
  509. return
  510. }
  511. //fmt.Println("a:", a, ";======b:", b)
  512. //计算B’
  513. newBDataMap := make(map[string]float64)
  514. {
  515. //B’=aA+b
  516. aDecimal := decimal.NewFromFloat(a)
  517. bDecimal := decimal.NewFromFloat(b)
  518. for _, aData := range aDataList {
  519. xDecimal := decimal.NewFromFloat(aData.Value)
  520. val, _ := aDecimal.Mul(xDecimal).Add(bDecimal).RoundCeil(4).Float64()
  521. newBDataMap[aData.DataTime] = val
  522. }
  523. }
  524. // Delta=B-B‘
  525. for _, bData := range secondDataList {
  526. currDate := bData.DataTime
  527. //校验待删除日期数据里面是否存在该元素,如果存在的话,那么移除该元素
  528. if _, ok := removeDataTimeMap[currDate]; ok {
  529. delete(removeDataTimeMap, currDate)
  530. }
  531. b2Val, ok := newBDataMap[currDate]
  532. if !ok {
  533. // 如果B`不存在数据,那么就退出当前循环
  534. continue
  535. }
  536. bDecimal := decimal.NewFromFloat(bData.Value)
  537. b2Decimal := decimal.NewFromFloat(b2Val)
  538. val, _ := bDecimal.Sub(b2Decimal).RoundCeil(4).Float64()
  539. // 判断之前有没有该数据
  540. existData, ok := dataMap[currDate]
  541. if !ok { //不存在那么就添加吧
  542. currentDate, _ := time.ParseInLocation(utils.FormatDate, currDate, time.Local)
  543. timestamp := currentDate.UnixNano() / 1e6
  544. edbDataNhcc := &EdbDataCalculateNhcc{
  545. EdbInfoId: edbInfo.EdbInfoId,
  546. EdbCode: edbInfo.EdbCode,
  547. DataTime: currDate,
  548. Value: val,
  549. Status: 1,
  550. CreateTime: time.Now(),
  551. ModifyTime: time.Now(),
  552. DataTimestamp: timestamp,
  553. }
  554. addDataList = append(addDataList, edbDataNhcc)
  555. } else {
  556. // 如果有的话,还需要判断值是否一致,一致则不处理,不一致则修改
  557. if existData.Value != val {
  558. existData.Value = val
  559. _, err = to.Update(existData, "Value")
  560. if err != nil {
  561. return
  562. }
  563. }
  564. }
  565. }
  566. //删除已经不存在的拟合残差指标数据(由于该指标当日的数据删除了)
  567. {
  568. removeDateList := make([]string, 0)
  569. for dateTime := range removeDataTimeMap {
  570. removeDateList = append(removeDateList, dateTime)
  571. }
  572. removeNum := len(removeDateList)
  573. if removeNum > 0 {
  574. //如果拼接指标变更了,那么需要删除所有的指标数据
  575. tableName := GetEdbDataTableName(edbInfo.Source, edbInfo.SubSource)
  576. sql := fmt.Sprintf(` DELETE FROM %s WHERE edb_info_id = ? and data_time in (`+utils.GetOrmInReplace(removeNum)+`) `, tableName)
  577. _, err = to.Raw(sql, edbInfo.EdbInfoId, removeDateList).Exec()
  578. if err != nil {
  579. err = fmt.Errorf("删除不存在的拟合残差指标数据失败,Err:" + err.Error())
  580. return
  581. }
  582. }
  583. }
  584. //数据入库
  585. if len(addDataList) > 0 {
  586. tmpAddDataList := make([]*EdbDataCalculateNhcc, 0)
  587. i := 0
  588. for _, v := range addDataList {
  589. tmpAddDataList = append(tmpAddDataList, v)
  590. i++
  591. if i >= 500 {
  592. _, err = to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
  593. if err != nil {
  594. return
  595. }
  596. i = 0
  597. tmpAddDataList = make([]*EdbDataCalculateNhcc, 0)
  598. }
  599. }
  600. if len(tmpAddDataList) > 0 {
  601. _, err = to.InsertMulti(len(tmpAddDataList), tmpAddDataList)
  602. if err != nil {
  603. return
  604. }
  605. }
  606. }
  607. return
  608. }
  609. // CalculateComputeCorrelation 计算相关性结果
  610. func CalculateComputeCorrelation(req *EdbInfoCalculateBatchSaveReq, firstEdbInfo, secondEdbInfo *EdbInfo, nhccDate NhccDate) (a, b, r float64, err error, errMsg string) {
  611. var existItemA, existItemB *EdbInfoCalculateMapping
  612. //第一个指标
  613. {
  614. existItemA = &EdbInfoCalculateMapping{
  615. EdbInfoCalculateMappingId: 0,
  616. FromEdbInfoId: firstEdbInfo.EdbInfoId,
  617. FromEdbCode: firstEdbInfo.EdbCode,
  618. FromEdbName: firstEdbInfo.EdbName,
  619. FromSource: firstEdbInfo.Source,
  620. FromSourceName: firstEdbInfo.SourceName,
  621. FromTag: "A",
  622. MoveValue: req.EdbInfoIdArr[0].MoveValue,
  623. Sort: 1,
  624. CreateTime: time.Now(),
  625. ModifyTime: time.Now(),
  626. FromSubSource: firstEdbInfo.SubSource,
  627. }
  628. }
  629. //第二个指标
  630. {
  631. existItemB = &EdbInfoCalculateMapping{
  632. EdbInfoCalculateMappingId: 0,
  633. FromEdbInfoId: secondEdbInfo.EdbInfoId,
  634. FromEdbCode: secondEdbInfo.EdbCode,
  635. FromEdbName: secondEdbInfo.EdbName,
  636. FromSource: secondEdbInfo.Source,
  637. FromSourceName: secondEdbInfo.SourceName,
  638. FromTag: "B",
  639. MoveValue: req.EdbInfoIdArr[1].MoveValue,
  640. Sort: 1,
  641. CreateTime: time.Now(),
  642. ModifyTime: time.Now(),
  643. FromSubSource: secondEdbInfo.SubSource,
  644. }
  645. }
  646. o := orm.NewOrm()
  647. to, err := o.Begin()
  648. defer func() {
  649. if err != nil {
  650. fmt.Println("RefreshAllCalculateNhcc,Err:" + err.Error())
  651. _ = to.Rollback()
  652. } else {
  653. _ = to.Commit()
  654. }
  655. }()
  656. // 获取相关数据
  657. _, _, aDataMap, bDataMap, nhccDate, err, errMsg := getNhccData(to, existItemA, existItemB, nhccDate)
  658. if err != nil {
  659. return
  660. }
  661. // 计算相关性
  662. coordinateData := make([]utils.Coordinate, 0)
  663. for i := nhccDate.StartDate; i.Before(nhccDate.EndDate) || i.Equal(nhccDate.EndDate); i = i.AddDate(0, 0, 1) {
  664. dateStr := i.Format(utils.FormatDate)
  665. xValue, ok := aDataMap[dateStr]
  666. if !ok {
  667. errMsg = "指标A日期:" + dateStr + "数据异常,导致计算线性方程公式失败"
  668. err = errors.New(errMsg)
  669. return
  670. }
  671. yValue, ok := bDataMap[dateStr]
  672. if !ok {
  673. errMsg = "指标B日期:" + dateStr + "数据异常,导致计算线性方程公式失败"
  674. err = errors.New(errMsg)
  675. return
  676. }
  677. tmpCoordinate := utils.Coordinate{
  678. X: xValue,
  679. Y: yValue,
  680. }
  681. coordinateData = append(coordinateData, tmpCoordinate)
  682. }
  683. // 计算线性方程公式
  684. a, b = utils.GetLinearResult(coordinateData)
  685. // 计算相关性
  686. r = utils.ComputeCorrelation(coordinateData)
  687. return
  688. }
  689. // getNhccData 获取拟合残差需要的数据
  690. func getNhccData(to orm.TxOrmer, existItemA, existItemB *EdbInfoCalculateMapping, nhccDate NhccDate) (aDataList []EdbInfoSearchData, secondDataList []*EdbInfoSearchData, aDataMap, bDataMap map[string]float64, newNhccDate NhccDate, err error, errMsg string) {
  691. newNhccDate = nhccDate
  692. //第一个指标
  693. aDataList = make([]EdbInfoSearchData, 0)
  694. aDataMap = make(map[string]float64)
  695. {
  696. var condition string
  697. var pars []interface{}
  698. condition += " AND edb_info_id=? "
  699. pars = append(pars, existItemA.FromEdbInfoId)
  700. //第一个指标的数据列表
  701. firstDataList, tmpErr := GetEdbDataListAllByTo(to, condition, pars, existItemA.FromSource, existItemA.FromSubSource, 0)
  702. if tmpErr != nil {
  703. err = tmpErr
  704. return
  705. }
  706. aDataList, aDataMap = handleNhccData(firstDataList, existItemA.MoveValue)
  707. }
  708. //第二个指标
  709. bDataList := make([]EdbInfoSearchData, 0)
  710. secondDataList = make([]*EdbInfoSearchData, 0)
  711. bDataMap = make(map[string]float64)
  712. {
  713. condition := ``
  714. pars := make([]interface{}, 0)
  715. condition += " AND edb_info_id = ? "
  716. pars = append(pars, existItemB.FromEdbInfoId)
  717. //第二个指标的数据列表
  718. secondDataList, err = GetEdbDataListAllByTo(to, condition, pars, existItemB.FromSource, existItemB.FromSubSource, 0)
  719. if err != nil {
  720. return
  721. }
  722. bDataList, bDataMap = handleNhccData(secondDataList, existItemB.MoveValue)
  723. }
  724. if len(aDataList) <= 0 {
  725. errMsg = "指标A没有数据"
  726. err = errors.New(errMsg)
  727. return
  728. }
  729. if len(bDataList) <= 0 {
  730. errMsg = "指标B没有数据"
  731. err = errors.New(errMsg)
  732. return
  733. }
  734. // 拟合残差计算的开始日期判断
  735. {
  736. startAData := aDataList[0]
  737. tmpStartDate, tmpErr := time.ParseInLocation(utils.FormatDate, startAData.DataTime, time.Local)
  738. if tmpErr != nil {
  739. err = tmpErr
  740. return
  741. }
  742. // 如果A指标的最新数据日期晚于拟合残差的结束日期,那么就用A指标的最新数据日期
  743. if tmpStartDate.After(newNhccDate.StartDate) {
  744. newNhccDate.StartDate = tmpStartDate
  745. }
  746. startBData := bDataList[0]
  747. tmpStartDate, tmpErr = time.ParseInLocation(utils.FormatDate, startBData.DataTime, time.Local)
  748. if tmpErr != nil {
  749. err = tmpErr
  750. return
  751. }
  752. // 如果B指标的最新数据日期晚于拟合残差的结束日期,那么就用A指标的最新数据日期
  753. if tmpStartDate.After(newNhccDate.StartDate) {
  754. newNhccDate.StartDate = tmpStartDate
  755. }
  756. }
  757. // 拟合残差计算的结束日期判断
  758. {
  759. endAData := aDataList[len(aDataList)-1]
  760. tmpEndDate, tmpErr := time.ParseInLocation(utils.FormatDate, endAData.DataTime, time.Local)
  761. if tmpErr != nil {
  762. err = tmpErr
  763. return
  764. }
  765. // 如果A指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  766. if tmpEndDate.Before(newNhccDate.EndDate) {
  767. newNhccDate.EndDate = tmpEndDate
  768. }
  769. endBData := bDataList[len(bDataList)-1]
  770. tmpEndDate, tmpErr = time.ParseInLocation(utils.FormatDate, endBData.DataTime, time.Local)
  771. if tmpErr != nil {
  772. err = tmpErr
  773. return
  774. }
  775. // 如果B指标的最新数据日期早于拟合残差的结束日期,那么就用A指标的最新数据日期
  776. if tmpEndDate.Before(newNhccDate.EndDate) {
  777. newNhccDate.EndDate = tmpEndDate
  778. }
  779. }
  780. return
  781. }
  782. // handleNhccData 处理拟合残差需要的数据
  783. func handleNhccData(dataList []*EdbInfoSearchData, moveDay int) (newDataList []EdbInfoSearchData, dateDataMap map[string]float64) {
  784. dateMap := make(map[time.Time]float64)
  785. var minDate, maxDate time.Time
  786. dateDataMap = make(map[string]float64)
  787. for _, v := range dataList {
  788. currDate, _ := time.ParseInLocation(utils.FormatDate, v.DataTime, time.Local)
  789. if minDate.IsZero() || currDate.Before(minDate) {
  790. minDate = currDate
  791. }
  792. if maxDate.IsZero() || currDate.After(maxDate) {
  793. maxDate = currDate
  794. }
  795. dateMap[currDate] = v.Value
  796. }
  797. // 处理领先、滞后数据
  798. newDateMap := make(map[time.Time]float64)
  799. for currDate, value := range dateMap {
  800. newDate := currDate.AddDate(0, 0, moveDay)
  801. newDateMap[newDate] = value
  802. }
  803. // 开始平移天数
  804. minDate = minDate.AddDate(0, 0, moveDay)
  805. maxDate = maxDate.AddDate(0, 0, moveDay)
  806. // 计算最早日期与最晚日期之间的相差天数
  807. dayNum := utils.GetTimeSubDay(minDate, maxDate)
  808. // 将最早日期与最晚日期之间不存在的日期进行数据补全(按前一期数据补充)
  809. for i := 0; i <= dayNum; i++ {
  810. currDate := minDate.AddDate(0, 0, i)
  811. tmpValue, ok := newDateMap[currDate]
  812. if !ok {
  813. // 万一没有数据,那么就过滤当次循环
  814. if len(newDataList) <= 0 {
  815. continue
  816. }
  817. //找不到数据,那么就用前面的数据吧
  818. tmpValue = newDataList[len(newDataList)-1].Value
  819. }
  820. tmpData := EdbInfoSearchData{
  821. //EdbDataId: 0,
  822. DataTime: currDate.Format(utils.FormatDate),
  823. Value: tmpValue,
  824. }
  825. dateDataMap[tmpData.DataTime] = tmpData.Value
  826. newDataList = append(newDataList, tmpData)
  827. }
  828. return
  829. }