edb_data_calculate_nhcc.go 25 KB

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