edb_data_calculate_nhcc.go 27 KB

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