stl.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. package stl
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_api/models/data_manage"
  6. "eta/eta_api/models/data_manage/stl"
  7. "eta/eta_api/models/data_manage/stl/request"
  8. "eta/eta_api/models/data_manage/stl/response"
  9. "eta/eta_api/services/data"
  10. "eta/eta_api/services/data/data_manage_permission"
  11. "eta/eta_api/services/elastic"
  12. "eta/eta_api/utils"
  13. "fmt"
  14. "os"
  15. "os/exec"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/rdlucklib/rdluck_tools/paging"
  21. "github.com/shopspring/decimal"
  22. "github.com/tealeg/xlsx"
  23. )
  24. const (
  25. ALL_DATE = iota + 1
  26. LAST_N_YEARS
  27. RANGE_DATE
  28. RANGE_DATE_TO_NOW
  29. )
  30. var EDB_DATA_CALCULATE_STL_TREND_CACHE = `eta:stl_decompose:trend:config_id:`
  31. var EDB_DATA_CALCULATE_STL_SEASONAL_CACHE = `eta:stl_decompose:seasonal:config_id:`
  32. var EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE = `eta:stl_decompose:residual:config_id:`
  33. func GenerateStlEdbData(req *request.StlConfigReq, adminId int) (resp *response.StlPreviewResp, msg string, err error) {
  34. config, err := stl.GetCalculateStlConfigById(req.CalculateStlConfigId)
  35. if err != nil {
  36. if err.Error() == utils.ErrNoRow() {
  37. msg = "配置信息不存在,请重新计算"
  38. return
  39. }
  40. msg = "获取配置信息失败"
  41. return
  42. }
  43. var confReq request.StlConfigReq
  44. if err = json.Unmarshal([]byte(config.Config), &confReq); err != nil {
  45. msg = "预览失败"
  46. err = fmt.Errorf("配置信息解析失败, err:%s", err.Error())
  47. return
  48. }
  49. edbInfo, err := data_manage.GetEdbInfoById(confReq.EdbInfoId)
  50. if err != nil {
  51. if err.Error() == utils.ErrNoRow() {
  52. msg = "指标不存在"
  53. return
  54. }
  55. msg = "获取指标信息失败"
  56. return
  57. }
  58. var condition string
  59. var pars []interface{}
  60. switch confReq.DataRangeType {
  61. case ALL_DATE:
  62. case LAST_N_YEARS:
  63. condition += " AND data_time >=?"
  64. year := time.Now().Year()
  65. lastNyear, er := strconv.Atoi(req.LastNYear)
  66. if er != nil {
  67. msg = "最近N年输入不合法"
  68. err = er
  69. return
  70. }
  71. if lastNyear <= 0 {
  72. msg = "最近N年输入不合法"
  73. err = fmt.Errorf("最近N年输入不合法")
  74. return
  75. }
  76. lastNyear = lastNyear - 1
  77. lastDate := time.Date(year-lastNyear, 1, 1, 0, 0, 0, 0, time.Local)
  78. pars = append(pars, lastDate)
  79. case RANGE_DATE:
  80. condition = " AND data_time >=? AND data_time <=?"
  81. pars = append(pars, confReq.StartDate, confReq.EndDate)
  82. case RANGE_DATE_TO_NOW:
  83. condition = " AND data_time >=?"
  84. pars = append(pars, confReq.StartDate)
  85. }
  86. condition += " AND edb_code =?"
  87. pars = append(pars, edbInfo.EdbCode)
  88. edbData, err := data_manage.GetAllEdbDataListByCondition(condition, pars, edbInfo.Source, edbInfo.SubSource)
  89. if err != nil {
  90. msg = "获取指标数据失败"
  91. return
  92. }
  93. if len(edbData) <= 0 {
  94. msg = "所选指标时间序列不存在数据,请重新选择"
  95. return
  96. }
  97. var condMsg string
  98. if confReq.Period < 2 || confReq.Period > len(edbData) {
  99. condMsg += "period必须是一个大于等于2的正整数,且必须小于时间序列的长度"
  100. }
  101. if confReq.Seasonal < 3 || confReq.Seasonal%2 == 0 || confReq.Seasonal <= confReq.Period {
  102. if condMsg != "" {
  103. condMsg += "\n"
  104. }
  105. condMsg += "seasonal必须是一个大于等于3的奇整数,且必须大于period"
  106. }
  107. if confReq.Trend < 3 || confReq.Trend%2 == 0 || confReq.Trend <= confReq.Period {
  108. if condMsg != "" {
  109. condMsg += "\n"
  110. }
  111. condMsg += "trend必须是一个大于等于3的奇整数,且必须大于period"
  112. }
  113. if confReq.Fraction < 0 || confReq.Fraction > 1 {
  114. if condMsg != "" {
  115. condMsg += "\n"
  116. }
  117. condMsg += "fraction必须是一个介于[0-1]之间"
  118. }
  119. if 1 > confReq.TrendDeg || confReq.TrendDeg > 5 {
  120. if condMsg != "" {
  121. condMsg += "\n"
  122. }
  123. condMsg += "trend_deg请设置成1-5的整数"
  124. }
  125. if 1 > confReq.SeasonalDeg || confReq.SeasonalDeg > 5 {
  126. if condMsg != "" {
  127. condMsg += "\n"
  128. }
  129. condMsg += "seasonal_deg请设置成1-5的整数"
  130. }
  131. if 1 > confReq.LowPassDeg || confReq.LowPassDeg > 5 {
  132. if condMsg != "" {
  133. condMsg += "\n"
  134. }
  135. condMsg += "low_pass_deg请设置成1-5的整数"
  136. }
  137. if condMsg != "" {
  138. msg = condMsg
  139. err = fmt.Errorf("参数错误")
  140. return
  141. }
  142. dir, _ := os.Executable()
  143. exPath := filepath.Dir(dir) + "/static/stl_tmp"
  144. err = CheckOsPathAndMake(exPath)
  145. if err != nil {
  146. msg = "计算失败"
  147. return
  148. }
  149. loadFilePath := exPath + "/" + strconv.Itoa(adminId) + "_" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  150. err = SaveToExcel(edbData, loadFilePath)
  151. if err != nil {
  152. msg = "保存数据到Excel失败"
  153. return
  154. }
  155. defer os.Remove(loadFilePath)
  156. saveFilePath := exPath + "/" + strconv.Itoa(adminId) + "_" + time.Now().Format(utils.FormatDateTimeUnSpace) + "_res" + ".xlsx"
  157. result, err := execStlPythonCode(loadFilePath, saveFilePath, confReq.Period, confReq.Seasonal, confReq.Trend, confReq.TrendDeg, confReq.SeasonalDeg, confReq.LowPassDeg, confReq.Fraction, confReq.Robust)
  158. if err != nil {
  159. msg = "计算失败,请重新选择指标和参数后计算"
  160. return
  161. }
  162. trendChart, seasonalChart, residualChart, err := ParseStlExcel(saveFilePath)
  163. if err != nil {
  164. msg = "解析Excel失败"
  165. return
  166. }
  167. defer os.Remove(saveFilePath)
  168. resp = new(response.StlPreviewResp)
  169. resp.OriginEdbInfo.EdbInfoId = edbInfo.EdbInfoId
  170. resp.OriginEdbInfo.Title = edbInfo.EdbName
  171. resp.OriginEdbInfo.ClassifyId = edbInfo.ClassifyId
  172. resp.OriginEdbInfo.MaxData = edbInfo.MaxValue
  173. resp.OriginEdbInfo.MinData = edbInfo.MinValue
  174. resp.OriginEdbInfo.Frequency = edbInfo.Frequency
  175. resp.OriginEdbInfo.Unit = edbInfo.Unit
  176. resp.OriginEdbInfo.DataList = formatEdbData(edbData)
  177. resp.TrendChartInfo.DataList = trendChart.DataList
  178. resp.TrendChartInfo.MaxData = trendChart.MaxData
  179. resp.TrendChartInfo.MinData = trendChart.MinData
  180. resp.TrendChartInfo.Title = edbInfo.EdbName + "Trend"
  181. resp.TrendChartInfo.ClassifyId = edbInfo.ClassifyId
  182. resp.TrendChartInfo.Frequency = edbInfo.Frequency
  183. resp.TrendChartInfo.Unit = edbInfo.Unit
  184. resp.SeasonalChartInfo.DataList = seasonalChart.DataList
  185. resp.SeasonalChartInfo.MaxData = seasonalChart.MaxData
  186. resp.SeasonalChartInfo.MinData = seasonalChart.MinData
  187. resp.SeasonalChartInfo.ClassifyId = edbInfo.ClassifyId
  188. resp.SeasonalChartInfo.Title = edbInfo.EdbName + "Seasonal"
  189. resp.SeasonalChartInfo.Frequency = edbInfo.Frequency
  190. resp.SeasonalChartInfo.Unit = edbInfo.Unit
  191. resp.ResidualChartInfo.DataList = residualChart.DataList
  192. resp.ResidualChartInfo.MaxData = residualChart.MaxData
  193. resp.ResidualChartInfo.MinData = residualChart.MinData
  194. resp.ResidualChartInfo.ClassifyId = edbInfo.ClassifyId
  195. resp.ResidualChartInfo.Title = edbInfo.EdbName + "Residual"
  196. resp.ResidualChartInfo.Frequency = edbInfo.Frequency
  197. resp.ResidualChartInfo.Unit = edbInfo.Unit
  198. resp.EvaluationResult.Mean = strconv.FormatFloat(result.ResidualMean, 'f', 4, 64)
  199. resp.EvaluationResult.Std = strconv.FormatFloat(result.ResidualVar, 'f', 4, 64)
  200. resp.EvaluationResult.AdfPValue = strconv.FormatFloat(result.AdfPValue, 'f', -1, 64)
  201. resp.EvaluationResult.LjungBoxPValue = strconv.FormatFloat(result.LbTestPValue, 'f', -1, 64)
  202. confMapping, err := stl.GetCalculateStlConfigMappingByConfigId(req.CalculateStlConfigId)
  203. if err != nil {
  204. msg = "获取配置信息失败"
  205. return
  206. }
  207. var relationEdbInfoId []int
  208. for _, mapping := range confMapping {
  209. switch mapping.StlEdbType {
  210. case 1:
  211. resp.TrendChartInfo.EdbInfoId = mapping.EdbInfoId
  212. relationEdbInfoId = append(relationEdbInfoId, mapping.EdbInfoId)
  213. case 2:
  214. resp.SeasonalChartInfo.EdbInfoId = mapping.EdbInfoId
  215. relationEdbInfoId = append(relationEdbInfoId, mapping.EdbInfoId)
  216. case 3:
  217. resp.ResidualChartInfo.EdbInfoId = mapping.EdbInfoId
  218. relationEdbInfoId = append(relationEdbInfoId, mapping.EdbInfoId)
  219. }
  220. }
  221. relationEdbInfo, err := data_manage.GetEdbInfoByIdList(relationEdbInfoId)
  222. if err != nil {
  223. msg = "获取关联指标信息失败"
  224. return
  225. }
  226. for _, info := range relationEdbInfo {
  227. switch info.EdbInfoId {
  228. case resp.TrendChartInfo.EdbInfoId:
  229. resp.TrendChartInfo.Title = info.EdbName
  230. resp.TrendChartInfo.ClassifyId = info.ClassifyId
  231. resp.TrendChartInfo.Frequency = info.Frequency
  232. resp.TrendChartInfo.Unit = info.Unit
  233. case resp.SeasonalChartInfo.EdbInfoId:
  234. resp.SeasonalChartInfo.Title = info.EdbName
  235. resp.SeasonalChartInfo.ClassifyId = info.ClassifyId
  236. resp.SeasonalChartInfo.Frequency = info.Frequency
  237. resp.SeasonalChartInfo.Unit = info.Unit
  238. case resp.ResidualChartInfo.EdbInfoId:
  239. resp.ResidualChartInfo.Title = info.EdbName
  240. resp.ResidualChartInfo.ClassifyId = info.ClassifyId
  241. resp.ResidualChartInfo.Frequency = info.Frequency
  242. resp.ResidualChartInfo.Unit = info.Unit
  243. }
  244. }
  245. bTrend, _ := json.Marshal(trendChart.DataList)
  246. bSeasonal, _ := json.Marshal(seasonalChart.DataList)
  247. bResidual, _ := json.Marshal(residualChart.DataList)
  248. err = utils.Rc.Put(EDB_DATA_CALCULATE_STL_TREND_CACHE+strconv.Itoa(config.CalculateStlConfigId), bTrend, time.Hour*2)
  249. if err != nil {
  250. msg = "计算失败,请重新计算"
  251. return
  252. }
  253. err = utils.Rc.Put(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE+strconv.Itoa(config.CalculateStlConfigId), bSeasonal, time.Hour*2)
  254. if err != nil {
  255. msg = "计算失败,请重新计算"
  256. return
  257. }
  258. utils.Rc.Put(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE+strconv.Itoa(config.CalculateStlConfigId), bResidual, time.Hour*2)
  259. if err != nil {
  260. msg = "计算失败,请重新计算"
  261. }
  262. return
  263. }
  264. func formatEdbData(items []*data_manage.EdbData) []*response.EdbData {
  265. res := make([]*response.EdbData, 0, len(items))
  266. for _, item := range items {
  267. t, _ := time.Parse(utils.FormatDate, item.DataTime)
  268. res = append(res, &response.EdbData{
  269. DataTime: item.DataTime,
  270. Value: item.Value,
  271. DataTimestamp: t.UnixMilli(),
  272. })
  273. }
  274. return res
  275. }
  276. func CheckOsPathAndMake(path string) (err error) {
  277. if _, er := os.Stat(path); os.IsNotExist(er) {
  278. err = os.MkdirAll(path, os.ModePerm)
  279. }
  280. return
  281. }
  282. func ParseStlExcel(excelPath string) (TrendChart, SeasonalChart, ResidualChart response.ChartEdbInfo, err error) {
  283. file, err := xlsx.OpenFile(excelPath)
  284. if err != nil {
  285. return
  286. }
  287. for _, sheet := range file.Sheets {
  288. switch sheet.Name {
  289. case "季节":
  290. var MinData, MaxData float64
  291. for i, row := range sheet.Rows {
  292. if i == 0 {
  293. continue
  294. }
  295. var date string
  296. var dataTimestamp int64
  297. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  298. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  299. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  300. date = tmpTime.Format(utils.FormatDate)
  301. dataTimestamp = tmpTime.UnixMilli()
  302. } else {
  303. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  304. date = timeDate.Format(utils.FormatDate)
  305. dataTimestamp = timeDate.UnixMilli()
  306. }
  307. fv, _ := row.Cells[1].Float()
  308. if MinData == 0 || fv < MinData {
  309. MinData = fv
  310. }
  311. if MaxData == 0 || fv > MaxData {
  312. MaxData = fv
  313. }
  314. fv, _ = decimal.NewFromFloat(fv).Round(4).Float64()
  315. SeasonalChart.DataList = append(SeasonalChart.DataList, &response.EdbData{DataTime: date, Value: fv, DataTimestamp: dataTimestamp})
  316. }
  317. SeasonalChart.MinData = MinData
  318. SeasonalChart.MaxData = MaxData
  319. case "趋势":
  320. var MinData, MaxData float64
  321. for i, row := range sheet.Rows {
  322. if i == 0 {
  323. continue
  324. }
  325. var date string
  326. var dataTimestamp int64
  327. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  328. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  329. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  330. date = tmpTime.Format(utils.FormatDate)
  331. dataTimestamp = tmpTime.UnixMilli()
  332. } else {
  333. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  334. date = timeDate.Format(utils.FormatDate)
  335. dataTimestamp = timeDate.UnixMilli()
  336. }
  337. fv, _ := row.Cells[1].Float()
  338. if MinData == 0 || fv < MinData {
  339. MinData = fv
  340. }
  341. if MaxData == 0 || fv > MaxData {
  342. MaxData = fv
  343. }
  344. fv, _ = decimal.NewFromFloat(fv).Round(4).Float64()
  345. TrendChart.DataList = append(TrendChart.DataList, &response.EdbData{DataTime: date, Value: fv, DataTimestamp: dataTimestamp})
  346. }
  347. TrendChart.MaxData = MaxData
  348. TrendChart.MinData = MinData
  349. case "残差":
  350. var MinData, MaxData float64
  351. for i, row := range sheet.Rows {
  352. if i == 0 {
  353. continue
  354. }
  355. var date string
  356. var dataTimestamp int64
  357. if row.Cells[0].Type() == xlsx.CellTypeNumeric {
  358. dataNum, _ := strconv.ParseFloat(row.Cells[0].Value, 64)
  359. tmpTime := xlsx.TimeFromExcelTime(dataNum, false)
  360. date = tmpTime.Format(utils.FormatDate)
  361. dataTimestamp = tmpTime.UnixMilli()
  362. } else {
  363. timeDate, _ := time.Parse(utils.FormatDateTime, date)
  364. date = timeDate.Format(utils.FormatDate)
  365. dataTimestamp = timeDate.UnixMilli()
  366. }
  367. fv, _ := row.Cells[1].Float()
  368. if MinData == 0 || fv < MinData {
  369. MinData = fv
  370. }
  371. if MaxData == 0 || fv > MaxData {
  372. MaxData = fv
  373. }
  374. fv, _ = decimal.NewFromFloat(fv).Round(4).Float64()
  375. ResidualChart.DataList = append(ResidualChart.DataList, &response.EdbData{DataTime: date, Value: fv, DataTimestamp: dataTimestamp})
  376. }
  377. ResidualChart.MaxData = MaxData
  378. ResidualChart.MinData = MinData
  379. }
  380. }
  381. return
  382. }
  383. func SaveToExcel(data []*data_manage.EdbData, filePath string) (err error) {
  384. xlsxFile := xlsx.NewFile()
  385. sheetNew, err := xlsxFile.AddSheet("Tmp")
  386. if err != nil {
  387. return
  388. }
  389. titleRow := sheetNew.AddRow()
  390. titleRow.AddCell().SetString("日期")
  391. titleRow.AddCell().SetString("值")
  392. for i, d := range data {
  393. row := sheetNew.Row(i + 1)
  394. row.AddCell().SetString(d.DataTime)
  395. row.AddCell().SetFloat(d.Value)
  396. }
  397. err = xlsxFile.Save(filePath)
  398. if err != nil {
  399. return
  400. }
  401. return
  402. }
  403. type STLResult struct {
  404. ResidualMean float64 `json:"residual_mean"`
  405. ResidualVar float64 `json:"residual_var"`
  406. AdfPValue float64 `json:"adf_p_value"`
  407. LbTestPValue float64 `json:"lb_test_p_value"`
  408. LbTestStat float64 `json:"lb_test_stat"`
  409. }
  410. func execStlPythonCode(path, toPath string, period, seasonal, trend, trendDeg, seasonalDeg, lowPassDeg int, fraction float64, robust bool) (stlResult *STLResult, err error) {
  411. pythonCode := `
  412. import json
  413. import warnings
  414. warnings.filterwarnings('ignore')
  415. import pandas as pd
  416. from statsmodels.tsa.seasonal import STL
  417. from statsmodels.nonparametric.smoothers_lowess import lowess
  418. from statsmodels.tsa.stattools import adfuller
  419. from statsmodels.stats.diagnostic import acorr_ljungbox
  420. import numpy as np
  421. file_path = r"%s"
  422. df = pd.read_excel(file_path, parse_dates=['日期'], engine='openpyxl')
  423. df.set_index('日期', inplace=True)
  424. df = df[df.index.notna()]
  425. period = %d
  426. seasonal = %d
  427. trend = %d
  428. fraction = %g
  429. seasonal_deg = %d
  430. trend_deg = %d
  431. low_pass_deg = %d
  432. robust = %s
  433. stl = STL(
  434. df['值'],
  435. period=period,
  436. seasonal=seasonal,
  437. trend=trend,
  438. low_pass=None,
  439. seasonal_deg=seasonal_deg,
  440. trend_deg=trend_deg,
  441. low_pass_deg=low_pass_deg,
  442. seasonal_jump=1,
  443. trend_jump=1,
  444. low_pass_jump=1,
  445. robust=robust
  446. )
  447. result = stl.fit()
  448. smoothed = lowess(df['值'], np.arange(len(df)), frac=fraction)
  449. trend_lowess = smoothed[:, 1]
  450. # 季节图
  451. seasonal_component = result.seasonal
  452. # 趋势图
  453. trend_lowess_series = pd.Series(trend_lowess, index=df.index)
  454. # 残差图
  455. residual_component = df['值'] - trend_lowess - seasonal_component
  456. # 计算打印残差的均值
  457. residual_mean = np.mean(residual_component)
  458. # 计算打印残差的方差
  459. residual_var = np.std(residual_component)
  460. # 计算打印残差的ADF检验结果, 输出p-value
  461. adf_result = adfuller(residual_component)
  462. # 根据p-value判断是否平稳
  463. lb_test = acorr_ljungbox(residual_component, lags=period, return_df=True)
  464. output_file = r"%s"
  465. with pd.ExcelWriter(output_file) as writer:
  466. # 保存季节图
  467. pd.Series(seasonal_component, index=df.index, name='值').to_frame().reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='季节', index=False)
  468. # 保存趋势图
  469. trend_lowess_series.to_frame(name='值').reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='趋势', index=False)
  470. # 保存残差图
  471. pd.Series(residual_component, index=df.index, name='值').to_frame().reset_index().rename(columns={'index': '日期'}).to_excel(writer, sheet_name='残差', index=False)
  472. output = json.dumps({
  473. 'residual_mean': residual_mean,
  474. 'residual_var': residual_var,
  475. 'adf_p_value': adf_result[1],
  476. 'lb_test_p_value': lb_test['lb_pvalue'].values[0],
  477. 'lb_test_stat': lb_test['lb_stat'].values[0]
  478. })
  479. print(output)
  480. `
  481. robustStr := "True"
  482. if !robust {
  483. robustStr = "False"
  484. }
  485. pythonCode = fmt.Sprintf(pythonCode, path, period, seasonal, trend, fraction, seasonalDeg, trendDeg, lowPassDeg, robustStr, toPath)
  486. utils.FileLog.Info("stl exec python code:%s", pythonCode)
  487. cmd := exec.Command(`python3`, "-c", pythonCode)
  488. output, err := cmd.CombinedOutput()
  489. if err != nil {
  490. utils.FileLog.Info(`execStlPythonCode error:%s, input: path:%s, toPath:%s, period:%d, seasonal:%d, trend:%d, trendDeg:%d, seasonalDeg:%d, lowPassDeg:%d, fraction:%g, robust:%s, output:%s`, err.Error(), path, toPath, period, seasonal, trend, trendDeg, seasonalDeg, lowPassDeg, fraction, robustStr, string(output))
  491. return
  492. }
  493. defer cmd.Process.Kill()
  494. if err = json.Unmarshal(output, &stlResult); err != nil {
  495. utils.FileLog.Info(`execStlPythonCode Unmarshal error:%s, input: path:%s, toPath:%s, period:%d, seasonal:%d, trend:%d, trendDeg:%d, seasonalDeg:%d, lowPassDeg:%d, fraction:%g, robust:%s, output:%s`, err.Error(), path, toPath, period, seasonal, trend, trendDeg, seasonalDeg, lowPassDeg, fraction, robustStr, string(output))
  496. return
  497. }
  498. return
  499. }
  500. func SaveStlConfig(req *request.StlConfigReq, adminId int) (configId int64, msg string, err error) {
  501. edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
  502. if err != nil {
  503. if err.Error() == utils.ErrNoRow() {
  504. msg = "指标不存在"
  505. return
  506. }
  507. msg = "获取指标信息失败"
  508. return
  509. }
  510. var condition string
  511. var pars []interface{}
  512. switch req.DataRangeType {
  513. case ALL_DATE:
  514. case LAST_N_YEARS:
  515. condition += " AND data_time >=?"
  516. year := time.Now().Year()
  517. lastNyear, er := strconv.Atoi(req.LastNYear)
  518. if er != nil {
  519. msg = "最近N年输入不合法"
  520. err = er
  521. return
  522. }
  523. lastDate := time.Date(year-lastNyear, 1, 1, 0, 0, 0, 0, time.Local)
  524. pars = append(pars, lastDate)
  525. case RANGE_DATE:
  526. condition = " AND data_time >=? AND data_time <=?"
  527. pars = append(pars, req.StartDate, req.EndDate)
  528. case RANGE_DATE_TO_NOW:
  529. condition = " AND data_time >=?"
  530. pars = append(pars, req.StartDate)
  531. }
  532. condition += " AND edb_code =?"
  533. pars = append(pars, edbInfo.EdbCode)
  534. edbData, err := data_manage.GetAllEdbDataListByCondition(condition, pars, edbInfo.Source, edbInfo.SubSource)
  535. if err != nil {
  536. msg = "获取指标数据失败"
  537. return
  538. }
  539. var condMsg string
  540. if req.Period < 2 || req.Period > len(edbData) {
  541. condMsg += "period必须是一个大于等于2的正整数,且必须小于时间序列的长度"
  542. }
  543. if req.Seasonal < 3 || req.Seasonal%2 == 0 || req.Seasonal <= req.Period {
  544. if condMsg != "" {
  545. condMsg += "\n"
  546. }
  547. condMsg += "seasonal必须是一个大于等于3的奇整数,且必须大于period"
  548. }
  549. if req.Trend < 3 || req.Trend%2 == 0 || req.Trend <= req.Period {
  550. if condMsg != "" {
  551. condMsg += "\n"
  552. }
  553. condMsg += "trend必须是一个大于等于3的奇整数,且必须大于period"
  554. }
  555. if req.Fraction < 0 || req.Fraction > 1 {
  556. if condMsg != "" {
  557. condMsg += "\n"
  558. }
  559. condMsg += "fraction必须是一个介于[0-1]之间"
  560. }
  561. if 1 > req.TrendDeg || req.TrendDeg > 5 {
  562. if condMsg != "" {
  563. condMsg += "\n"
  564. }
  565. condMsg += "trend_deg请设置成1-5的整数"
  566. }
  567. if 1 > req.SeasonalDeg || req.SeasonalDeg > 5 {
  568. if condMsg != "" {
  569. condMsg += "\n"
  570. }
  571. condMsg += "seasonal_deg请设置成1-5的整数"
  572. }
  573. if 1 > req.LowPassDeg || req.LowPassDeg > 5 {
  574. if condMsg != "" {
  575. condMsg += "\n"
  576. }
  577. condMsg += "low_pass_deg请设置成1-5的整数"
  578. }
  579. if condMsg != "" {
  580. msg = condMsg
  581. err = fmt.Errorf("参数错误")
  582. return
  583. }
  584. b, err := json.Marshal(req)
  585. if err != nil {
  586. return
  587. }
  588. conf := new(stl.CalculateStlConfig)
  589. if req.CalculateStlConfigId > 0 {
  590. conf.CalculateStlConfigId = req.CalculateStlConfigId
  591. conf.Config = string(b)
  592. conf.ModifyTime = time.Now()
  593. err = conf.Update([]string{"Config", "ModifyTime"})
  594. configId = int64(req.CalculateStlConfigId)
  595. } else {
  596. conf.Config = string(b)
  597. conf.SysUserId = adminId
  598. conf.CreateTime = time.Now()
  599. conf.ModifyTime = time.Now()
  600. configId, err = conf.Insert()
  601. }
  602. return
  603. }
  604. func SearchEdbInfoWithStl(adminId int, keyWord string, currentIndex, pageSize int, lang string) (resp data_manage.EdbInfoFilterDataResp, msg string, err error) {
  605. var edbInfoList []*data_manage.EdbInfoList
  606. noPermissionEdbInfoIdList := make([]int, 0) //无权限指标
  607. // 获取当前账号的不可见指标
  608. {
  609. obj := data_manage.EdbInfoNoPermissionAdmin{}
  610. confList, er := obj.GetAllListByAdminId(adminId)
  611. if er != nil && er.Error() != utils.ErrNoRow() {
  612. msg = "获取失败"
  613. err = fmt.Errorf("获取不可见指标配置数据失败,Err:" + er.Error())
  614. return
  615. }
  616. for _, v := range confList {
  617. noPermissionEdbInfoIdList = append(noPermissionEdbInfoIdList, v.EdbInfoId)
  618. }
  619. }
  620. if currentIndex <= 0 {
  621. currentIndex = 1
  622. }
  623. startSize := utils.StartIndex(currentIndex, pageSize)
  624. // 是否走ES
  625. isEs := false
  626. var total int64
  627. if keyWord != "" {
  628. frequencyList := []string{"日度", "周度", "旬度", "月度", "季度"}
  629. // 普通的搜索
  630. total, edbInfoList, err = elastic.SearchEdbInfoDataByfrequency(utils.DATA_INDEX_NAME, keyWord, startSize, pageSize, 0, frequencyList, noPermissionEdbInfoIdList)
  631. isEs = true
  632. } else {
  633. var condition string
  634. var pars []interface{}
  635. // 普通指标
  636. condition += ` AND edb_info_type = ? `
  637. pars = append(pars, 0)
  638. // 无权限指标id
  639. lenNoPermissionEdbInfoIdList := len(noPermissionEdbInfoIdList)
  640. if lenNoPermissionEdbInfoIdList > 0 {
  641. condition += ` AND edb_info_id not in (` + utils.GetOrmInReplace(lenNoPermissionEdbInfoIdList) + `) `
  642. pars = append(pars, noPermissionEdbInfoIdList)
  643. }
  644. //频度
  645. condition += ` AND frequency IN ('日度', '周度', '旬度', '月度', '季度') `
  646. total, edbInfoList, err = data_manage.GetEdbInfoFilterList(condition, pars, startSize, pageSize)
  647. }
  648. if err != nil {
  649. edbInfoList = make([]*data_manage.EdbInfoList, 0)
  650. }
  651. page := paging.GetPaging(currentIndex, pageSize, int(total))
  652. edbInfoListLen := len(edbInfoList)
  653. classifyIdList := make([]int, 0)
  654. for i := 0; i < edbInfoListLen; i++ {
  655. edbInfoList[i].EdbNameAlias = edbInfoList[i].EdbName
  656. classifyIdList = append(classifyIdList, edbInfoList[i].ClassifyId)
  657. // 如果没有关键词,那么搜索结果字段取指标名,前端已统一用该字段显示搜索的列表内容
  658. if keyWord == "" {
  659. if lang == utils.ZhLangVersion {
  660. edbInfoList[i].SearchText = edbInfoList[i].EdbName
  661. }
  662. if lang == utils.EnLangVersion {
  663. edbInfoList[i].SearchText = edbInfoList[i].EdbNameEn
  664. }
  665. }
  666. }
  667. // 当前列表中的分类map
  668. classifyMap := make(map[int]*data_manage.EdbClassify)
  669. if edbInfoListLen > 0 {
  670. classifyList, er := data_manage.GetEdbClassifyByIdList(classifyIdList)
  671. if er != nil {
  672. msg = "获取失败"
  673. err = fmt.Errorf("获取分类列表失败,Err:" + er.Error())
  674. return
  675. }
  676. for _, v := range classifyList {
  677. classifyMap[v.ClassifyId] = v
  678. }
  679. // 获取所有有权限的指标和分类
  680. permissionEdbIdList, permissionClassifyIdList, er := data_manage_permission.GetUserEdbAndClassifyPermissionList(adminId, 0, 0)
  681. if er != nil {
  682. msg = "获取失败"
  683. err = fmt.Errorf("获取所有有权限的指标和分类失败,Err:" + er.Error())
  684. return
  685. }
  686. // 如果是ES的话,需要重新查一下指标的信息,主要是为了把是否授权字段找出来
  687. if isEs {
  688. edbInfoIdList := make([]int, 0)
  689. for i := 0; i < edbInfoListLen; i++ {
  690. edbInfoIdList = append(edbInfoIdList, edbInfoList[i].EdbInfoId)
  691. tmpEdbInfo := edbInfoList[i]
  692. if currClassify, ok := classifyMap[tmpEdbInfo.ClassifyId]; ok {
  693. edbInfoList[i].HaveOperaAuth = data_manage_permission.CheckEdbPermissionByPermissionIdList(tmpEdbInfo.IsJoinPermission, currClassify.IsJoinPermission, tmpEdbInfo.EdbInfoId, tmpEdbInfo.ClassifyId, permissionEdbIdList, permissionClassifyIdList)
  694. }
  695. }
  696. tmpEdbList, er := data_manage.GetEdbInfoByIdList(edbInfoIdList)
  697. if er != nil {
  698. msg = "获取失败"
  699. err = fmt.Errorf("获取所有有权限的指标失败,Err:" + er.Error())
  700. return
  701. }
  702. edbInfoMap := make(map[int]*data_manage.EdbInfo)
  703. for _, v := range tmpEdbList {
  704. edbInfoMap[v.EdbInfoId] = v
  705. }
  706. for i := 0; i < edbInfoListLen; i++ {
  707. tmpEdbInfo, ok := edbInfoMap[edbInfoList[i].EdbInfoId]
  708. if !ok {
  709. continue
  710. }
  711. edbInfoList[i].IsJoinPermission = tmpEdbInfo.IsJoinPermission
  712. }
  713. }
  714. // 权限校验
  715. for i := 0; i < edbInfoListLen; i++ {
  716. tmpEdbInfoItem := edbInfoList[i]
  717. if currClassify, ok := classifyMap[tmpEdbInfoItem.ClassifyId]; ok {
  718. edbInfoList[i].HaveOperaAuth = data_manage_permission.CheckEdbPermissionByPermissionIdList(tmpEdbInfoItem.IsJoinPermission, currClassify.IsJoinPermission, tmpEdbInfoItem.EdbInfoId, tmpEdbInfoItem.ClassifyId, permissionEdbIdList, permissionClassifyIdList)
  719. }
  720. }
  721. }
  722. for i := 0; i < edbInfoListLen; i++ {
  723. for j := 0; j < edbInfoListLen; j++ {
  724. if (edbInfoList[i].EdbNameAlias == edbInfoList[j].EdbNameAlias) &&
  725. (edbInfoList[i].EdbInfoId != edbInfoList[j].EdbInfoId) &&
  726. !(strings.Contains(edbInfoList[i].EdbName, edbInfoList[i].SourceName)) {
  727. edbInfoList[i].EdbName = edbInfoList[i].EdbName + "(" + edbInfoList[i].SourceName + ")"
  728. }
  729. }
  730. }
  731. //新增搜索词记录
  732. {
  733. searchKeyword := new(data_manage.SearchKeyword)
  734. searchKeyword.KeyWord = keyWord
  735. searchKeyword.CreateTime = time.Now()
  736. go data_manage.AddSearchKeyword(searchKeyword)
  737. }
  738. resp = data_manage.EdbInfoFilterDataResp{
  739. Paging: page,
  740. List: edbInfoList,
  741. }
  742. return
  743. }
  744. func SaveStlEdbInfo(req *request.SaveStlEdbInfoReq, adminId int, adminRealName, lang string) (addEdbInfoId int, isSendEmail bool, msg string, err error) {
  745. if req.EdbName == "" {
  746. msg = "指标名称不能为空"
  747. return
  748. }
  749. if req.Unit == "" {
  750. msg = "指标单位不能为空"
  751. return
  752. }
  753. if req.ClassifyId <= 0 {
  754. msg = "请选择分类"
  755. return
  756. }
  757. if req.Frequency == "" {
  758. msg = "指标频度不能为空"
  759. return
  760. }
  761. conf, err := stl.GetCalculateStlConfigById(req.CalculateStlConfigId)
  762. if err != nil {
  763. if err.Error() == utils.ErrNoRow() {
  764. msg = "未找到配置,请先进行计算"
  765. err = fmt.Errorf("配置不存在")
  766. return
  767. }
  768. msg = "获取失败"
  769. return
  770. }
  771. var stlConfig request.StlConfigReq
  772. if err = json.Unmarshal([]byte(conf.Config), &stlConfig); err != nil {
  773. msg = "获取失败"
  774. return
  775. }
  776. var edbInfoData []*response.EdbData
  777. switch req.StlEdbType {
  778. case 1:
  779. // 趋势指标
  780. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  781. msg = "计算已过期,请重新计算"
  782. err = fmt.Errorf("not found")
  783. return
  784. }
  785. trendData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  786. if er != nil {
  787. msg = "获取失败"
  788. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  789. return
  790. }
  791. if er := json.Unmarshal(trendData, &edbInfoData); er != nil {
  792. msg = "获取失败"
  793. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  794. return
  795. }
  796. case 2:
  797. // 季节性指标
  798. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  799. msg = "计算已过期,请重新计算"
  800. err = fmt.Errorf("not found")
  801. return
  802. }
  803. seasonalData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  804. if er != nil {
  805. msg = "获取失败"
  806. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  807. return
  808. }
  809. if er := json.Unmarshal(seasonalData, &edbInfoData); er != nil {
  810. msg = "获取失败"
  811. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  812. return
  813. }
  814. case 3:
  815. // 残差性指标
  816. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(req.CalculateStlConfigId)); !ok {
  817. msg = "计算已过期,请重新计算"
  818. err = fmt.Errorf("not found")
  819. return
  820. }
  821. residualData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(req.CalculateStlConfigId))
  822. if er != nil {
  823. msg = "获取失败"
  824. err = fmt.Errorf("获取redis数据失败,Err:" + er.Error())
  825. return
  826. }
  827. if er := json.Unmarshal(residualData, &edbInfoData); er != nil {
  828. msg = "获取失败"
  829. err = fmt.Errorf("json解析失败,Err:" + er.Error())
  830. return
  831. }
  832. default:
  833. msg = "获取失败"
  834. err = fmt.Errorf("未知的计算类型")
  835. return
  836. }
  837. var opEdbInfoId int
  838. if req.EdbInfoId > 0 {
  839. opEdbInfoId = req.EdbInfoId
  840. // 检查指标名称是否存在
  841. var condition string
  842. var pars []interface{}
  843. switch lang {
  844. case utils.EnLangVersion:
  845. condition += " AND edb_name_en = ? "
  846. default:
  847. condition += " AND edb_name=? "
  848. }
  849. pars = append(pars, req.EdbName)
  850. existEdbInfo, er := data_manage.GetEdbInfoByCondition(condition, pars)
  851. if er != nil && er.Error() != utils.ErrNoRow() {
  852. msg = "获取失败"
  853. return
  854. }
  855. switch lang {
  856. case utils.EnLangVersion:
  857. if existEdbInfo != nil && existEdbInfo.EdbNameEn == req.EdbName && req.EdbInfoId != existEdbInfo.EdbInfoId {
  858. msg = "指标名称已存在"
  859. err = fmt.Errorf("指标名称已存在")
  860. return
  861. }
  862. default:
  863. if existEdbInfo != nil && existEdbInfo.EdbName == req.EdbName && req.EdbInfoId != existEdbInfo.EdbInfoId {
  864. msg = "指标名称已存在"
  865. err = fmt.Errorf("指标名称已存在")
  866. return
  867. }
  868. }
  869. // 更新指标
  870. edbInfo, er := data_manage.GetEdbInfoById(req.EdbInfoId)
  871. if er != nil {
  872. if er.Error() == utils.ErrNoRow() {
  873. msg = "未找到指标,请刷新后重试"
  874. err = er
  875. return
  876. }
  877. msg = "获取失败"
  878. err = er
  879. return
  880. }
  881. var updateCols []string
  882. switch lang {
  883. case utils.EnLangVersion:
  884. if edbInfo.EdbName != req.EdbName {
  885. edbInfo.EdbNameEn = req.EdbName
  886. updateCols = append(updateCols, "edb_name_en")
  887. }
  888. default:
  889. if edbInfo.EdbName != req.EdbName {
  890. edbInfo.EdbName = req.EdbName
  891. updateCols = append(updateCols, "edb_name")
  892. }
  893. }
  894. if edbInfo.ClassifyId != req.ClassifyId {
  895. // 更新分类
  896. maxSort, er := data.GetEdbClassifyMaxSort(req.ClassifyId, 0)
  897. if er != nil {
  898. msg = "获取失败"
  899. err = fmt.Errorf("获取最大排序失败,Err:" + er.Error())
  900. return
  901. }
  902. edbInfo.ClassifyId = req.ClassifyId
  903. edbInfo.Sort = maxSort + 1
  904. updateCols = append(updateCols, "classify_id", "sort")
  905. }
  906. if edbInfo.Frequency != req.Frequency {
  907. edbInfo.Frequency = req.Frequency
  908. updateCols = append(updateCols, "frequency")
  909. }
  910. if edbInfo.Unit != req.Unit {
  911. edbInfo.Unit = req.Unit
  912. updateCols = append(updateCols, "unit")
  913. }
  914. edbInfo.CalculateFormula = conf.Config
  915. updateCols = append(updateCols, "calculate_formula")
  916. if len(updateCols) > 0 {
  917. edbInfo.ModifyTime = time.Now()
  918. updateCols = append(updateCols, "modify_time")
  919. err = edbInfo.Update(updateCols)
  920. if err != nil {
  921. msg = "保存失败"
  922. return
  923. }
  924. }
  925. var dataList []*stl.EdbDataCalculateStl
  926. for _, v := range edbInfoData {
  927. dataTime, _ := time.Parse(utils.FormatDate, v.DataTime)
  928. dataList = append(dataList, &stl.EdbDataCalculateStl{
  929. EdbInfoId: edbInfo.EdbInfoId,
  930. EdbCode: edbInfo.EdbCode,
  931. DataTime: dataTime,
  932. Value: v.Value,
  933. CreateTime: time.Now(),
  934. ModifyTime: time.Now(),
  935. DataTimestamp: dataTime.UnixMilli(),
  936. })
  937. }
  938. err = stl.DeleteAndInsertEdbDataCalculateStl(edbInfo.EdbCode, dataList)
  939. if err != nil {
  940. msg = "保存失败"
  941. return
  942. }
  943. data_manage.ModifyEdbInfoDataStatus(int64(edbInfo.EdbInfoId), edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  944. maxAndMinItem, _ := data_manage.GetEdbInfoMaxAndMinInfo(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  945. if maxAndMinItem != nil {
  946. err = data_manage.ModifyEdbInfoMaxAndMinInfo(edbInfo.EdbInfoId, maxAndMinItem)
  947. if err != nil {
  948. msg = "保存失败"
  949. err = errors.New("保存失败,Err:" + err.Error())
  950. return
  951. }
  952. }
  953. } else {
  954. indexObj := new(stl.EdbDataCalculateStl)
  955. edbCode, er := utils.GenerateEdbCode(1, "stl")
  956. if er != nil {
  957. msg = "生成指标代码失败"
  958. err = fmt.Errorf("生成指标代码失败,Err:" + er.Error())
  959. return
  960. }
  961. //判断指标名称是否存在
  962. ok, er := CheckDulplicateEdbInfoName(req.EdbName, lang)
  963. if er != nil {
  964. msg = "保存失败"
  965. err = fmt.Errorf("检查指标名称是否存在失败,Err:" + er.Error())
  966. return
  967. }
  968. if ok {
  969. msg = "指标名称已存在"
  970. err = fmt.Errorf("指标名称已存在")
  971. return
  972. }
  973. source := utils.DATA_SOURCE_CALCULATE_STL
  974. subSource := utils.DATA_SUB_SOURCE_EDB
  975. edbInfo := new(data_manage.EdbInfo)
  976. //获取该层级下最大的排序数
  977. maxSort, er := data.GetEdbClassifyMaxSort(req.ClassifyId, 0)
  978. if er != nil {
  979. msg = "获取失败"
  980. err = fmt.Errorf("获取最大排序失败,Err:" + er.Error())
  981. return
  982. }
  983. edbInfo.EdbCode = edbCode
  984. edbInfo.EdbName = req.EdbName
  985. edbInfo.EdbNameEn = req.EdbName
  986. edbInfo.EdbNameSource = req.EdbName
  987. edbInfo.Frequency = req.Frequency
  988. edbInfo.Unit = req.Unit
  989. edbInfo.UnitEn = req.Unit
  990. edbInfo.CalculateFormula = conf.Config
  991. edbInfo.ClassifyId = req.ClassifyId
  992. edbInfo.SysUserId = adminId
  993. edbInfo.SysUserRealName = adminRealName
  994. edbInfo.CreateTime = time.Now()
  995. edbInfo.ModifyTime = time.Now()
  996. edbInfo.Sort = maxSort + 1
  997. edbInfo.DataDateType = `交易日`
  998. timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
  999. edbInfo.UniqueCode = utils.MD5(utils.DATA_PREFIX + "_" + timestamp)
  1000. itemVal, er := data_manage.GetEdbInfoMaxAndMinInfo(source, subSource, edbCode)
  1001. if itemVal != nil && er == nil {
  1002. edbInfo.MaxValue = itemVal.MaxValue
  1003. edbInfo.MinValue = itemVal.MinValue
  1004. }
  1005. edbInfo.EdbType = 2
  1006. edbInfo.Source = source
  1007. edbInfo.SubSource = subSource
  1008. edbInfo.SourceName = "STL趋势分解"
  1009. extra, _ := json.Marshal(req)
  1010. edbInfo.Extra = string(extra)
  1011. edbInfoId, er := data_manage.AddEdbInfo(edbInfo)
  1012. if er != nil {
  1013. msg = "保存失败"
  1014. err = errors.New("保存失败,Err:" + er.Error())
  1015. return
  1016. }
  1017. edbInfo.EdbInfoId = int(edbInfoId)
  1018. var dataList []*stl.EdbDataCalculateStl
  1019. for _, v := range edbInfoData {
  1020. dataTime, _ := time.Parse(utils.FormatDate, v.DataTime)
  1021. dataList = append(dataList, &stl.EdbDataCalculateStl{
  1022. EdbInfoId: int(edbInfoId),
  1023. EdbCode: edbCode,
  1024. DataTime: dataTime,
  1025. Value: v.Value,
  1026. CreateTime: time.Now(),
  1027. ModifyTime: time.Now(),
  1028. DataTimestamp: dataTime.UnixMilli(),
  1029. })
  1030. }
  1031. err = indexObj.BatchInsert(dataList)
  1032. if err != nil {
  1033. msg = "保存失败"
  1034. return
  1035. }
  1036. //保存数据
  1037. data_manage.ModifyEdbInfoDataStatus(edbInfoId, source, subSource, edbCode)
  1038. maxAndMinItem, _ := data_manage.GetEdbInfoMaxAndMinInfo(source, subSource, edbCode)
  1039. if maxAndMinItem != nil {
  1040. err = data_manage.ModifyEdbInfoMaxAndMinInfo(int(edbInfoId), maxAndMinItem)
  1041. if err != nil {
  1042. msg = "保存失败"
  1043. err = errors.New("保存失败,Err:" + err.Error())
  1044. return
  1045. }
  1046. }
  1047. // 保存配置映射
  1048. {
  1049. stlMapping := new(stl.CalculateStlConfigMapping)
  1050. stlMapping.EdbInfoId = int(edbInfoId)
  1051. stlMapping.CalculateStlConfigId = req.CalculateStlConfigId
  1052. stlMapping.StlEdbType = req.StlEdbType
  1053. stlMapping.CreateTime = time.Now()
  1054. stlMapping.ModifyTime = time.Now()
  1055. _, err = stlMapping.Insert()
  1056. if err != nil {
  1057. msg = "保存失败"
  1058. err = errors.New("保存配置映射失败,Err:" + err.Error())
  1059. return
  1060. }
  1061. }
  1062. // 保存溯源信息
  1063. {
  1064. fromEdbInfo, er := data_manage.GetEdbInfoById(stlConfig.EdbInfoId)
  1065. if er != nil {
  1066. if er.Error() == utils.ErrNoRow() {
  1067. msg = "未找到指标,请刷新后重试"
  1068. err = fmt.Errorf("指标不存在,err:" + er.Error())
  1069. return
  1070. }
  1071. msg = "获取失败"
  1072. err = er
  1073. return
  1074. }
  1075. edbCalculateMappingInfo := new(data_manage.EdbInfoCalculateMapping)
  1076. edbCalculateMappingInfo.EdbInfoId = int(edbInfoId)
  1077. edbCalculateMappingInfo.Source = source
  1078. edbCalculateMappingInfo.SourceName = "STL趋势分解"
  1079. edbCalculateMappingInfo.EdbCode = edbCode
  1080. edbCalculateMappingInfo.FromEdbInfoId = fromEdbInfo.EdbInfoId
  1081. edbCalculateMappingInfo.FromEdbCode = fromEdbInfo.EdbCode
  1082. edbCalculateMappingInfo.FromEdbName = fromEdbInfo.EdbName
  1083. edbCalculateMappingInfo.FromSource = fromEdbInfo.Source
  1084. edbCalculateMappingInfo.FromSourceName = fromEdbInfo.SourceName
  1085. edbCalculateMappingInfo.CreateTime = time.Now()
  1086. edbCalculateMappingInfo.ModifyTime = time.Now()
  1087. err = edbCalculateMappingInfo.Insert()
  1088. if err != nil {
  1089. msg = "保存失败"
  1090. err = errors.New("保存溯源信息失败,Err:" + err.Error())
  1091. return
  1092. }
  1093. }
  1094. //添加es
  1095. data.AddOrEditEdbInfoToEs(int(edbInfoId))
  1096. opEdbInfoId = int(edbInfoId)
  1097. }
  1098. // 更新关联的同配置的指标
  1099. err = SyncUpdateRelationEdbInfo(req.CalculateStlConfigId, opEdbInfoId)
  1100. if err != nil {
  1101. msg = "更新关联的同配置的指标失败"
  1102. return
  1103. }
  1104. addEdbInfoId = opEdbInfoId
  1105. return
  1106. }
  1107. func SyncUpdateRelationEdbInfo(configId int, excludeId int) (err error) {
  1108. mappingList, err := stl.GetCalculateStlConfigMappingByConfigId(configId)
  1109. if err != nil {
  1110. return
  1111. }
  1112. conf, err := stl.GetCalculateStlConfigById(configId)
  1113. if err != nil {
  1114. return
  1115. }
  1116. for _, v := range mappingList {
  1117. edbInfo, er := data_manage.GetEdbInfoById(v.EdbInfoId)
  1118. if er != nil {
  1119. continue
  1120. }
  1121. if v.EdbInfoId == excludeId {
  1122. continue
  1123. }
  1124. var edbInfoData []*response.EdbData
  1125. switch v.StlEdbType {
  1126. case 1:
  1127. // 趋势指标
  1128. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(v.CalculateStlConfigId)); !ok {
  1129. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "指标数据不存在")
  1130. continue
  1131. }
  1132. trendData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(v.CalculateStlConfigId))
  1133. if er != nil {
  1134. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_TREND_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "redis获取失败,err:" + er.Error())
  1135. continue
  1136. }
  1137. if er := json.Unmarshal(trendData, &edbInfoData); er != nil {
  1138. utils.FileLog.Info("redis获取解析, body:%s,err:%s", string(trendData), er.Error())
  1139. continue
  1140. }
  1141. case 2:
  1142. // 季节性指标
  1143. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(v.CalculateStlConfigId)); !ok {
  1144. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "指标数据不存在")
  1145. continue
  1146. }
  1147. seasonalData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(v.CalculateStlConfigId))
  1148. if er != nil {
  1149. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_SEASONAL_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "redis获取失败,err:" + er.Error())
  1150. continue
  1151. }
  1152. if er := json.Unmarshal(seasonalData, &edbInfoData); er != nil {
  1153. utils.FileLog.Info("redis数据解析失败, body:%s,err:%s", string(seasonalData), er.Error())
  1154. continue
  1155. }
  1156. case 3:
  1157. // 残差性指标
  1158. if ok := utils.Rc.IsExist(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(v.CalculateStlConfigId)); !ok {
  1159. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "指标数据不存在")
  1160. continue
  1161. }
  1162. residualData, er := utils.Rc.RedisBytes(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(v.CalculateStlConfigId))
  1163. if er != nil {
  1164. utils.FileLog.Info(EDB_DATA_CALCULATE_STL_RESIDUAL_CACHE + strconv.Itoa(v.CalculateStlConfigId) + "redis获取失败,err:" + er.Error())
  1165. continue
  1166. }
  1167. if er := json.Unmarshal(residualData, &edbInfoData); er != nil {
  1168. utils.FileLog.Info("redis数据解析失败, body:%s,err:%s", string(residualData), er.Error())
  1169. continue
  1170. }
  1171. default:
  1172. utils.FileLog.Info("未知的stlEdbType类型, mapping:%v", v)
  1173. continue
  1174. }
  1175. var dataList []*stl.EdbDataCalculateStl
  1176. for _, v := range edbInfoData {
  1177. dataTime, _ := time.Parse(utils.FormatDate, v.DataTime)
  1178. dataList = append(dataList, &stl.EdbDataCalculateStl{
  1179. EdbInfoId: edbInfo.EdbInfoId,
  1180. EdbCode: edbInfo.EdbCode,
  1181. DataTime: dataTime,
  1182. Value: v.Value,
  1183. CreateTime: time.Now(),
  1184. ModifyTime: time.Now(),
  1185. DataTimestamp: dataTime.UnixMilli(),
  1186. })
  1187. }
  1188. err = stl.DeleteAndInsertEdbDataCalculateStl(edbInfo.EdbCode, dataList)
  1189. if err != nil {
  1190. return
  1191. }
  1192. data_manage.ModifyEdbInfoDataStatus(int64(edbInfo.EdbInfoId), edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  1193. maxAndMinItem, _ := data_manage.GetEdbInfoMaxAndMinInfo(edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode)
  1194. if maxAndMinItem != nil {
  1195. err = data_manage.ModifyEdbInfoMaxAndMinInfo(edbInfo.EdbInfoId, maxAndMinItem)
  1196. if err != nil {
  1197. return
  1198. }
  1199. }
  1200. edbInfo.CalculateFormula = conf.Config
  1201. edbInfo.ModifyTime = time.Now()
  1202. err = edbInfo.Update([]string{"calculate_formula", "modify_time"})
  1203. if err != nil {
  1204. return
  1205. }
  1206. }
  1207. return
  1208. }
  1209. func GetStlConfig(edbInfoId int) (resp *response.StlConfigResp, msg string, err error) {
  1210. configId, err := stl.GetCalculateStlConfigMappingIdByEdbInfoId(edbInfoId)
  1211. if err != nil {
  1212. if err.Error() == utils.ErrNoRow() {
  1213. msg = "未找到指标信息, 请选择其他指标"
  1214. return
  1215. }
  1216. msg = "查询失败"
  1217. return
  1218. }
  1219. queryEdbInfo, err := data_manage.GetEdbInfoById(edbInfoId)
  1220. if err != nil {
  1221. if err.Error() == utils.ErrNoRow() {
  1222. msg = "未找到指标,请刷新后重试"
  1223. return
  1224. }
  1225. msg = "获取失败"
  1226. return
  1227. }
  1228. var req request.StlConfigReq
  1229. if err = json.Unmarshal([]byte(queryEdbInfo.CalculateFormula), &req); err != nil {
  1230. msg = "获取失败"
  1231. return
  1232. }
  1233. edbInfo, err := data_manage.GetEdbInfoById(req.EdbInfoId)
  1234. if err != nil {
  1235. if err.Error() == utils.ErrNoRow() {
  1236. msg = "未找到指标,请刷新后重试"
  1237. return
  1238. }
  1239. msg = "获取失败"
  1240. return
  1241. }
  1242. resp = &response.StlConfigResp{
  1243. CalculateStlConfigId: configId,
  1244. EdbInfoId: req.EdbInfoId,
  1245. EdbInfoName: edbInfo.EdbName,
  1246. DataRangeType: req.DataRangeType,
  1247. StartDate: req.StartDate,
  1248. EndDate: req.EndDate,
  1249. LastNYear: req.LastNYear,
  1250. Period: req.Period,
  1251. Seasonal: req.Seasonal,
  1252. Trend: req.Trend,
  1253. Fraction: req.Fraction,
  1254. Robust: req.Robust,
  1255. TrendDeg: req.TrendDeg,
  1256. SeasonalDeg: req.SeasonalDeg,
  1257. LowPassDeg: req.LowPassDeg,
  1258. }
  1259. return
  1260. }
  1261. func CheckDulplicateEdbInfoName(edbName, lang string) (ok bool, err error) {
  1262. var count int
  1263. var condition string
  1264. var pars []interface{}
  1265. switch lang {
  1266. case utils.EnLangVersion:
  1267. condition += " AND edb_name_en = ? "
  1268. default:
  1269. condition += " AND edb_name=? "
  1270. }
  1271. pars = append(pars, edbName)
  1272. count, err = data_manage.GetEdbInfoCountByCondition(condition, pars)
  1273. if err != nil {
  1274. return
  1275. }
  1276. if count > 0 {
  1277. ok = true
  1278. return
  1279. }
  1280. return
  1281. }