neck_ring_merge.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "sort"
  8. "strings"
  9. "time"
  10. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. "go.uber.org/zap"
  14. )
  15. const (
  16. MinChangeFilter = -99
  17. MinRuminaFilter = -99
  18. MinChewFilter = -99
  19. MinChangeHigh = -99
  20. DefaultNb = 30
  21. DefaultScore = 100
  22. )
  23. var (
  24. defaultLimit = int32(1000)
  25. calculateIsRunning bool
  26. )
  27. // NeckRingOriginalMerge 把脖环数据合并成2个小时的
  28. func (e *Entry) NeckRingOriginalMerge() (err error) {
  29. if ok := e.IsExistCrontabLog(NeckRingOriginal); !ok {
  30. newTime := time.Now()
  31. e.CreateCrontabLog(NeckRingOriginal)
  32. // 原始数据删除15天前的
  33. e.DB.Model(new(model.NeckRingOriginal)).
  34. Where("created_at < ?", newTime.AddDate(0, 0, -7).Unix()).
  35. Delete(new(model.NeckRingOriginal))
  36. // 活动数据删除6个月前的数据
  37. e.DB.Model(new(model.NeckActiveHabit)).
  38. Where("created_at < ?", newTime.AddDate(0, -2, 0).Unix()).
  39. Delete(new(model.NeckActiveHabit))
  40. }
  41. pastureList := e.FindPastureList()
  42. if pastureList == nil || len(pastureList) == 0 {
  43. return nil
  44. }
  45. for _, pasture := range pastureList {
  46. if err = e.OriginalMergeData(pasture.Id); err != nil {
  47. zaplog.Error("NeckRingOriginalMerge", zap.Any("OriginalMergeData", err), zap.Any("pasture", pasture))
  48. }
  49. }
  50. return nil
  51. }
  52. func (e *Entry) OriginalMergeData(pastureId int64) error {
  53. limit := e.Cfg.NeckRingLimit
  54. if limit <= 0 {
  55. limit = defaultLimit
  56. }
  57. neckRingList := make([]*model.NeckRingOriginal, 0)
  58. if err := e.DB.Model(new(model.NeckRingOriginal)).
  59. Where("is_show = ?", pasturePb.IsShow_No).
  60. Where("pasture_id = ?", pastureId).
  61. Limit(int(limit)).Find(&neckRingList).Error; err != nil {
  62. return xerr.WithStack(err)
  63. }
  64. if len(neckRingList) <= 0 {
  65. return nil
  66. }
  67. // 去重
  68. neckRingList = RemoveDuplicates(neckRingList)
  69. // 计算合并
  70. neckActiveHabitList := Recalculate(neckRingList)
  71. if len(neckActiveHabitList) <= 0 {
  72. return nil
  73. }
  74. for _, habit := range neckActiveHabitList {
  75. //更新脖环牛只相关信息 新数据直接插入
  76. historyNeckActiveHabit, ct := e.IsExistNeckActiveHabit(pastureId, habit.NeckRingNumber, habit.HeatDate, habit.Frameid)
  77. if ct <= 0 {
  78. if err := e.DB.Create(habit).Error; err != nil {
  79. zaplog.Info("NeckRingOriginalMergeData-1",
  80. zap.Any("err", err),
  81. zap.Any("neckActiveHabit", habit),
  82. )
  83. }
  84. } else {
  85. // 重新计算
  86. newNeckActiveHabit := e.againRecalculate(historyNeckActiveHabit)
  87. if newNeckActiveHabit == nil {
  88. continue
  89. }
  90. if err := e.DB.Model(new(model.NeckActiveHabit)).
  91. Select("rumina", "intake", "inactive", "gasp", "other", "high", "active", "is_show", "record_count").
  92. Where("id = ?", historyNeckActiveHabit.Id).
  93. Updates(newNeckActiveHabit).Error; err != nil {
  94. zaplog.Error("NeckRingOriginalMergeData-2",
  95. zap.Any("err", err),
  96. zap.Any("ct", ct),
  97. zap.Any("historyNeckActiveHabit", historyNeckActiveHabit),
  98. zap.Any("newNeckActiveHabit", newNeckActiveHabit),
  99. )
  100. }
  101. }
  102. if err := e.UpdateNeckRingOriginalIsShow(habit); err != nil {
  103. zaplog.Error("NeckRingOriginalMergeData-4",
  104. zap.Any("err", err),
  105. zap.Any("neckActiveHabit", habit),
  106. )
  107. }
  108. }
  109. return nil
  110. }
  111. func (e *Entry) NeckRingCalculate() error {
  112. pastureList := e.FindPastureList()
  113. if pastureList == nil || len(pastureList) == 0 {
  114. return nil
  115. }
  116. if calculateIsRunning {
  117. return nil
  118. }
  119. defer func() {
  120. calculateIsRunning = false
  121. }()
  122. calculateIsRunning = true
  123. for _, pasture := range pastureList {
  124. if err := e.EntryUpdateActiveHabit(pasture.Id); err != nil {
  125. zaplog.Error("NeckRingCalculate", zap.Any("err", err), zap.Any("pasture", pasture))
  126. }
  127. zaplog.Info(fmt.Sprintf("NeckRingCalculate Success %d", pasture.Id))
  128. }
  129. return nil
  130. }
  131. func (e *Entry) EntryUpdateActiveHabit(pastureId int64) (err error) {
  132. // 获取这段执行数据内最大日期和最小日期
  133. xToday := &XToday{}
  134. systemConfigureList, err := e.GetSystemNeckRingConfigure(pastureId)
  135. if err != nil {
  136. return xerr.WithStack(err)
  137. }
  138. for _, v := range systemConfigureList {
  139. switch v.Name {
  140. case model.MaxHabit:
  141. xToday.LastMaxHabitId = v.Value
  142. case model.High:
  143. xToday.High = int32(v.Value)
  144. case model.Rumina:
  145. xToday.Rumina = int32(v.Value)
  146. case model.XRuminaDisc:
  147. xToday.XRuminaDisc = int32(v.Value)
  148. case model.XChangeDiscount:
  149. xToday.XChangeDiscount = int32(v.Value)
  150. case model.WeeklyActive:
  151. xToday.WeeklyActive = int32(v.Value)
  152. }
  153. }
  154. currMaxHabit := &model.NeckActiveHabit{}
  155. if err = e.DB.Model(new(model.NeckActiveHabit)).
  156. Where("id > ?", xToday.LastMaxHabitId).
  157. Where("pasture_id = ?", pastureId).
  158. Where("is_show = ?", pasturePb.IsShow_No).
  159. Order("id desc").First(currMaxHabit).Error; err != nil {
  160. return xerr.WithStack(err)
  161. }
  162. if currMaxHabit.Id <= 0 || currMaxHabit.Id <= xToday.LastMaxHabitId {
  163. return nil
  164. }
  165. xToday.CurrMaxHabitId = currMaxHabit.Id
  166. defer func() {
  167. // 更新最后一次执行的id值
  168. if err == nil {
  169. e.DB.Model(new(model.NeckRingConfigure)).
  170. Where("name = ?", model.MaxHabit).
  171. Where("pasture_id = ?", pastureId).
  172. Update("value", currMaxHabit.Id)
  173. }
  174. }()
  175. var processIds []int64
  176. // 更新活动滤波
  177. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  178. if err != nil {
  179. zaplog.Error("NeckRingCalculate", zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  180. }
  181. if len(processIds) > 0 {
  182. if err = e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday); err != nil {
  183. zaplog.Error("NeckRingCalculate", zap.Any("WeeklyUpdateActiveHabit", err), zap.Any("xToday", xToday))
  184. }
  185. if err = e.Before3DaysNeckActiveHabit(pastureId, processIds, xToday); err != nil {
  186. zaplog.Error("NeckRingCalculate", zap.Any("Before3DaysNeckActiveHabit", err), zap.Any("xToday", xToday))
  187. }
  188. // 二次更新滤波
  189. if err = e.SecondUpdateChangeFilter(pastureId, xToday); err != nil {
  190. zaplog.Error("NeckRingCalculate", zap.Any("SecondUpdateChangeFilter", err), zap.Any("xToday", xToday))
  191. }
  192. }
  193. // 活动量校正系数和健康评分
  194. if err = e.FilterCorrectAndScoreUpdate(pastureId, xToday); err != nil {
  195. zaplog.Error("NeckRingCalculate", zap.Any("ActivityVolumeChanges", err), zap.Any("xToday", xToday))
  196. }
  197. if err = e.DB.Model(new(model.NeckActiveHabit)).
  198. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  199. Where("pasture_id = ?", pastureId).
  200. Where("is_show = ?", pasturePb.IsShow_No).
  201. Where("change_filter = ?", model.InitChangeFilter).
  202. Updates(map[string]interface{}{
  203. "change_filter": model.DefaultChangeFilter,
  204. "rumina_filter": model.DefaultRuminaFilter,
  205. "chew_filter": model.DefaultChewFilter,
  206. }).Error; err != nil {
  207. zaplog.Error("EntryUpdateActiveHabit", zap.Any("change_filter", err), zap.Any("xToday", xToday))
  208. }
  209. if err = e.DB.Model(new(model.NeckActiveHabit)).
  210. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  211. Where("pasture_id = ?", pastureId).
  212. Where("change_filter < ?", 0).
  213. Where("filter_correct < ?", model.DefaultFilterCorrect).
  214. Updates(map[string]interface{}{
  215. "filter_correct": model.DefaultFilterCorrect,
  216. }).Error; err != nil {
  217. zaplog.Error("EntryUpdateActiveHabit", zap.Any("filter_correct", err), zap.Any("xToday", xToday))
  218. }
  219. // 插入群体校正表
  220. if err = e.UpdateChangeAdJust(pastureId, xToday); err != nil {
  221. zaplog.Error("EntryUpdateActiveHabit", zap.Any("UpdateChangeAdJust", err), zap.Any("xToday", xToday))
  222. }
  223. // 健康预警
  224. if len(processIds) > 0 {
  225. if err = e.HealthWarning(pastureId, processIds); err != nil {
  226. zaplog.Error("EntryUpdateActiveHabit", zap.Any("HealthWarning", err))
  227. }
  228. }
  229. return nil
  230. }
  231. // FirstFilterUpdate 首次更新活动滤波
  232. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (processIds []int64, err error) {
  233. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  234. if err = e.DB.Model(new(model.NeckActiveHabit)).
  235. Where("id BETWEEN ? AND ?", xToDay.LastMaxHabitId, xToDay.CurrMaxHabitId).
  236. Where("pasture_id = ?", pastureId).
  237. Where("is_show = ?", pasturePb.IsShow_No).
  238. Where("record_count = ?", model.DefaultRecordCount).
  239. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  240. Order("heat_date,neck_ring_number,frameid").
  241. Limit(int(defaultLimit)).
  242. Find(&newNeckActiveHabitList).Error; err != nil {
  243. return nil, xerr.WithStack(err)
  244. }
  245. // 活动量滤波
  246. for _, v := range newNeckActiveHabitList {
  247. // 过滤牛只未绑定的脖环的数据
  248. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  249. if cowInfo == nil || cowInfo.Id <= 0 {
  250. continue
  251. }
  252. frameId := v.Frameid
  253. heatDate := v.HeatDate
  254. if v.Frameid == 0 {
  255. frameId = 11
  256. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  257. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  258. } else {
  259. frameId -= 1
  260. }
  261. firstFilterData := e.FindFirstFilter(pastureId, v.NeckRingNumber, heatDate, frameId)
  262. if v.FilterHigh > 0 {
  263. firstFilterData.FilterHigh = v.FilterHigh
  264. } else {
  265. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  266. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  267. } else {
  268. firstFilterData.FilterHigh = v.High
  269. }
  270. }
  271. if v.FilterRumina > 0 {
  272. firstFilterData.FilterRumina = v.FilterRumina
  273. } else {
  274. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  275. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  276. } else {
  277. firstFilterData.FilterRumina = v.Rumina
  278. }
  279. }
  280. if v.FilterChew > 0 {
  281. firstFilterData.FilterChew = v.FilterChew
  282. } else {
  283. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  284. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  285. } else {
  286. firstFilterData.FilterChew = v.Rumina + v.Intake
  287. }
  288. }
  289. processIds = append(processIds, v.Id)
  290. // 更新过滤值 // todo 记得更新胎次为牛只胎次,现在为了测试特意改成0
  291. if err = e.DB.Model(new(model.NeckActiveHabit)).
  292. Select("filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age", "ear_number").
  293. Where("id = ?", v.Id).
  294. Updates(map[string]interface{}{
  295. "filter_high": firstFilterData.FilterHigh,
  296. "filter_rumina": firstFilterData.FilterRumina,
  297. "filter_chew": firstFilterData.FilterChew,
  298. "cow_id": cowInfo.Id,
  299. "lact": 0,
  300. "calving_age": cowInfo.CalvingAge,
  301. "ear_number": cowInfo.EarNumber,
  302. }).Error; err != nil {
  303. zaplog.Error("FirstFilterUpdate",
  304. zap.Any("error", err),
  305. zap.Any("firstFilterData", firstFilterData),
  306. zap.Any("NeckActiveHabit", v),
  307. zap.Any("cowInfo", cowInfo),
  308. zap.Any("xToday", xToDay),
  309. )
  310. }
  311. }
  312. return processIds, nil
  313. }
  314. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  315. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  316. if err = e.DB.Model(new(model.NeckActiveHabit)).
  317. Where("id IN (?)", processIds).
  318. Order("heat_date,neck_ring_number,frameid").
  319. Find(&newNeckActiveHabitList).Error; err != nil {
  320. return xerr.WithStack(err)
  321. }
  322. for _, v := range newNeckActiveHabitList {
  323. // 前七天的
  324. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  325. highDiff := v.FilterHigh - weekHabitData.WeekHighHabit
  326. denominator := float64(v.WeekHigh)*0.6 + float64(weekHabitData.WeekHighHabit)*0.2 + float64(xToDay.WeeklyActive)*0.2
  327. if highDiff > 0 {
  328. v.ChangeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  329. } else {
  330. v.ChangeHigh = int32(math.Round(float64(highDiff) / denominator * 100))
  331. }
  332. if weekHabitData.WeekRuminaHabit != 0 {
  333. v.ChangeRumina = int32(math.Round(float64(v.FilterRumina-weekHabitData.WeekRuminaHabit) / float64(weekHabitData.WeekRuminaHabit) * 100))
  334. } else {
  335. v.ChangeRumina = 0
  336. }
  337. if weekHabitData.WeekChewHabit != 0 {
  338. v.ChangeChew = int32(math.Round(float64(v.FilterChew-weekHabitData.WeekChewHabit) / float64(weekHabitData.WeekChewHabit) * 100))
  339. } else {
  340. v.ChangeChew = 0
  341. }
  342. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  343. // 更新过滤值
  344. if err = e.DB.Model(new(model.NeckActiveHabit)).
  345. Select(
  346. "week_high_habit", "week_rumina_habit", "week_chew_habit", "week_intake_habit", "week_inactive_habit",
  347. "sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew",
  348. "change_high", "change_rumina", "change_chew", "before_three_sum_rumina", "before_three_sum_intake",
  349. ).Where("id = ?", v.Id).
  350. Updates(map[string]interface{}{
  351. "week_high_habit": weekHabitData.WeekHighHabit,
  352. "week_rumina_habit": weekHabitData.WeekRuminaHabit,
  353. "week_chew_habit": weekHabitData.WeekChewHabit,
  354. "week_intake_habit": weekHabitData.WeekIntakeHabit,
  355. "week_inactive_habit": weekHabitData.WeekIntakeHabit,
  356. "sum_rumina": sumHabitData.SumRumina,
  357. "sum_intake": sumHabitData.SumIntake,
  358. "sum_inactive": sumHabitData.SumInactive,
  359. "sum_active": sumHabitData.SumActive,
  360. "sum_max_high": sumHabitData.SumMaxHigh,
  361. "sum_min_high": sumHabitData.SumMinHigh,
  362. "sum_min_chew": sumHabitData.SumMinChew,
  363. "change_high": v.ChangeHigh,
  364. "change_rumina": v.ChangeRumina,
  365. "change_chew": v.ChangeChew,
  366. }).Error; err != nil {
  367. zaplog.Error("WeeklyUpdateActiveHabit",
  368. zap.Error(err),
  369. zap.Any("NeckActiveHabit", v),
  370. zap.Any("pastureId", pastureId),
  371. )
  372. }
  373. }
  374. return err
  375. }
  376. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  377. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  378. if err = e.DB.Model(new(model.NeckActiveHabit)).
  379. Where("id IN (?)", processIds).
  380. Order("heat_date,neck_ring_number,frameid").
  381. Find(&newNeckActiveHabitList).Error; err != nil {
  382. return xerr.WithStack(err)
  383. }
  384. for _, v := range newNeckActiveHabitList {
  385. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  386. // 更新过滤值
  387. if err = e.DB.Model(new(model.NeckActiveHabit)).
  388. Select("before_three_sum_rumina", "before_three_sum_intake").
  389. Where("id = ?", v.Id).
  390. Updates(map[string]interface{}{
  391. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  392. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  393. }).Error; err != nil {
  394. zaplog.Error("Before3DaysNeckActiveHabit",
  395. zap.Error(err),
  396. zap.Any("NeckActiveHabit", v),
  397. zap.Any("pastureId", pastureId),
  398. )
  399. }
  400. }
  401. return nil
  402. }
  403. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  404. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, xToday *XToday) (err error) {
  405. newChangeFilterList := make([]*ChangeFilterData, 0)
  406. if err = e.DB.Model(new(model.NeckActiveHabit)).
  407. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  408. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  409. Where("heat_date >= ?", time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)).
  410. Where("pasture_id = ?", pastureId).
  411. Where("change_filter = ?", model.InitChangeFilter).
  412. Where("change_high > ?", MinChangeHigh).
  413. Order("neck_ring_number,heat_date,frameid").
  414. Find(&newChangeFilterList).Error; err != nil {
  415. return xerr.WithStack(err)
  416. }
  417. for _, v := range newChangeFilterList {
  418. secondFilterData := &SecondFilterData{}
  419. frameId := v.FrameId
  420. heatDate := v.HeatDate
  421. if v.FrameId == 0 {
  422. frameId = 11
  423. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  424. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  425. }
  426. if err = e.DB.Model(new(model.NeckActiveHabit)).
  427. Select("neck_ring_number", "filter_high", "filter_rumina", "filter_chew").
  428. Where("neck_ring_number = ?", v.NeckRingNumber).
  429. Where("heat_date = ?", heatDate).
  430. Where("frameid = ?", frameId).
  431. First(&secondFilterData).Error; err != nil {
  432. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err))
  433. }
  434. if v.ChangeFilter > MinChangeFilter {
  435. secondFilterData.ChangeFilter = float64(v.ChangeFilter)
  436. } else {
  437. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  438. secondFilterData.ChangeFilter = secondFilterData.ChangeFilter*(1-(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount) +
  439. math.Min(float64(v.ChangeHigh), secondFilterData.ChangeFilter+135)*(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount
  440. } else {
  441. secondFilterData.ChangeFilter = 0
  442. }
  443. }
  444. if v.RuminaFilter > MinRuminaFilter {
  445. secondFilterData.RuminaFilter = float64(v.ChangeFilter)
  446. } else {
  447. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  448. discount := float64(xToday.XRuminaDisc) / 10 * v.XlcDisCount
  449. if math.Abs(float64(v.ChangeRumina)) > 60 {
  450. discount *= 0.5
  451. }
  452. secondFilterData.RuminaFilter = secondFilterData.RuminaFilter*(1-discount) + float64(v.ChangeRumina)*discount
  453. } else {
  454. secondFilterData.RuminaFilter = 0
  455. }
  456. }
  457. secondFilterData.RuminaFilter = math.Min(50, secondFilterData.RuminaFilter)
  458. if v.ChewFilter > MinChewFilter {
  459. secondFilterData.ChewFilter = float64(v.ChangeChew)
  460. } else {
  461. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  462. discount := float64(xToday.XRuminaDisc) / 10
  463. if math.Abs(float64(v.ChangeChew)) > 60 {
  464. discount *= 0.5
  465. }
  466. secondFilterData.ChewFilter = secondFilterData.ChewFilter*(1-discount) + float64(v.ChangeChew)*discount
  467. } else {
  468. secondFilterData.ChewFilter = 0
  469. }
  470. }
  471. secondFilterData.ChewFilter = math.Min(50, secondFilterData.ChewFilter)
  472. if err = e.DB.Model(new(model.NeckActiveHabit)).
  473. Select("change_filter", "rumina_filter", "chew_filter").
  474. Where("id = ?", v.Id).
  475. Updates(map[string]interface{}{
  476. "change_filter": secondFilterData.ChangeFilter,
  477. "rumina_filter": secondFilterData.RuminaFilter,
  478. "chew_filter": secondFilterData.ChewFilter,
  479. }).Error; err != nil {
  480. zaplog.Error("SecondUpdateChangeFilter-1", zap.Any("error", err), zap.Any("xToday", xToday))
  481. }
  482. }
  483. return nil
  484. }
  485. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  486. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, xToday *XToday) error {
  487. beginDayDate := time.Now()
  488. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  489. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  490. activityVolumeList := make([]*ActivityVolume, 0)
  491. activityVolumeMap := make(map[string]*ActivityVolume)
  492. if err := e.DB.Model(new(model.NeckActiveHabit)).
  493. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  494. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  495. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  496. Where("pasture_id = ?", pastureId).
  497. Where(e.DB.Where("high > ?", xToday.High).Or("rumina >= ?", xToday.Rumina)).
  498. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  499. Where("change_filter > ?", MinChangeFilter).
  500. Having("nb > ?", DefaultNb).
  501. Group("neck_ring_number").
  502. Find(&activityVolumeList).Error; err != nil {
  503. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  504. }
  505. if len(activityVolumeList) > 0 {
  506. for _, v := range activityVolumeList {
  507. activityVolumeMap[v.NeckRingNumber] = v
  508. }
  509. }
  510. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  511. if err := e.DB.Model(new(model.NeckActiveHabit)).
  512. Where("id <= ?", xToday.CurrMaxHabitId).
  513. Where("heat_date >= ?", before1DayDate).
  514. Where("pasture_id = ?", pastureId).
  515. Where(e.DB.Where("high > ?", xToday.High).Or("rumina > ?", xToday.Rumina)).
  516. Find(&neckActiveHabitList).Error; err != nil {
  517. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  518. return xerr.WithStack(err)
  519. }
  520. for _, v := range neckActiveHabitList {
  521. if filterCorrectMap, ok := activityVolumeMap[v.NeckRingNumber]; ok {
  522. filterCorrect := model.DefaultFilterCorrect - int(math.Floor(filterCorrectMap.AvgFilter/3+float64(filterCorrectMap.StdFilter)/2))
  523. // 活动量校正系数
  524. if err := e.DB.Model(new(model.NeckActiveHabit)).
  525. Where("id = ?", v.Id).
  526. Where("neck_ring_number = ?", v.NeckRingNumber).
  527. Update("filter_correct", filterCorrect).Error; err != nil {
  528. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  529. continue
  530. }
  531. }
  532. cowScore := calculateScore(v)
  533. if err := e.DB.Model(new(model.NeckActiveHabit)).
  534. Where("id = ?", v.Id).
  535. Update("score", cowScore).Error; err != nil {
  536. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  537. continue
  538. }
  539. }
  540. return nil
  541. }
  542. // UpdateChangeAdJust 更新群体校正数据
  543. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) error {
  544. /*-- 插入群体校正表
  545. INSERT INTO data_bar_change(heatdate, frameid, intCurBar, intCurBarName, nb, highchange, changefilter)
  546. SELECT h.heatdate, h.frameid, c.intCurBar, c.intCurBarName, COUNT(*) nb, ROUND(AVG(h.highchange)) highchange, ROUND(AVG(h.changefilter) ) changefilter
  547. FROM h_activehabit h JOIN cow c ON h.intCowId=c.intCowId
  548. WHERE h.heatdate>=(CURDATE() -INTERVAL 1 DAY )
  549. GROUP BY h.heatdate, h.frameid, c.intCurBar
  550. ORDER BY h.heatdate, h.frameid, c.intCurBarName
  551. ON DUPLICATE KEY UPDATE nb = VALUES(nb), highchange = VALUES(highchange), changefilter = VALUES(changefilter);
  552. UPDATE h_activehabit h
  553. JOIN cow c ON h.intCowId=c.intCowId
  554. JOIN data_bar_change cg ON h.heatdate=cg.heatdate AND h.frameid=cg.frameid AND c.intCurBar=cg.intCurBar
  555. SET h.changeadjust=cg.changefilter
  556. WHERE h.id>xBeg_update_act_Id AND h.heatdate>=CURRENT_DATE() - INTERVAL 1 DAY AND ABS(cg.changefilter)>=10;
  557. */
  558. res := make([]*model.NeckRingBarChange, 0)
  559. oneDayAgo := time.Now().AddDate(0, 0, -1).Format(model.LayoutDate2)
  560. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  561. Select("h.neck_ring_number,h.heat_date, h.frameid, c.pen_id, c.pen_name, COUNT(*) as nb, ROUND(AVG(h.change_high)) as change_high, ROUND(AVG(h.change_filter)) as change_filter").
  562. Joins("JOIN cow as c ON h.neck_ring_number = c.neck_ring_number").
  563. Where("h.pasture_id = ?", pastureId).
  564. Where("h.heat_date >= ?", oneDayAgo).
  565. Where("h.cow_id >= ?", 0).
  566. Where("h.cow_id >= ?", 0).
  567. Group("h.heat_date, h.frameid, c.pen_id").
  568. Order("h.heat_date, h.frameid, c.pen_name").
  569. Find(&res).Error; err != nil {
  570. return xerr.WithStack(err)
  571. }
  572. // todo ABS(cg.changefilter)>=10;
  573. for _, v := range res {
  574. if err := e.DB.Model(new(model.NeckActiveHabit)).
  575. Where("id > ?", xToday.LastMaxHabitId).
  576. Where("heat_date = ?", v.HeatDate).
  577. Where("frameid = ?", v.FrameId).
  578. Where("neck_ring_number = ?", v.NeckRingNumber).
  579. Update("change_adjust", v.ChangeHigh).Error; err != nil {
  580. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  581. }
  582. }
  583. // 更新所有的显示状态为否的记录为是
  584. if err := e.DB.Model(new(model.NeckActiveHabit)).
  585. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  586. Where("pasture_id = ?", pastureId).
  587. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  588. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err), zap.Any("xToday", xToday))
  589. }
  590. return nil
  591. }
  592. func (e *Entry) UpdateNeckRingOriginalIsShow(habit *model.NeckActiveHabit) error {
  593. if err := e.DB.Model(new(model.NeckRingOriginal)).
  594. Where("pasture_id = ?", habit.PastureId).
  595. Where("neck_ring_number = ?", habit.NeckRingNumber).
  596. Where("active_date = ?", habit.HeatDate).
  597. Where("frameid IN (?)", util.FrameIds(habit.Frameid)).
  598. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  599. return xerr.WithStack(err)
  600. }
  601. return nil
  602. }
  603. // RemoveDuplicates 清洗一下数据,去掉重复的,如果有重复的,取最新的一条数据
  604. func RemoveDuplicates(records []*model.NeckRingOriginal) []*model.NeckRingOriginal {
  605. uniqueRecords := make(map[string]*model.NeckRingOriginal)
  606. // 遍历原始数组
  607. for _, record := range records {
  608. mapKey := fmt.Sprintf("%s%s%s%s%d", record.NeckRingNumber, model.JoinKey, record.ActiveDate, model.JoinKey, record.Frameid) // 0001/2023-12-04/0 0001/2023-12-03/4
  609. if existing, exists := uniqueRecords[mapKey]; exists {
  610. if record.CreatedAt > existing.CreatedAt {
  611. uniqueRecords[mapKey] = record
  612. }
  613. } else {
  614. uniqueRecords[mapKey] = record
  615. }
  616. }
  617. // 将 map 中的记录转换为切片
  618. result := make([]*model.NeckRingOriginal, 0, len(uniqueRecords))
  619. for _, record := range uniqueRecords {
  620. result = append(result, record)
  621. }
  622. return result
  623. }
  624. // Recalculate 合并计算
  625. func Recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  626. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  627. // 合并成2个小时的
  628. for _, v := range neckRingList {
  629. xframeId := util.XFrameId(v.Frameid)
  630. mapKey := fmt.Sprintf("%s%s%s%s%d", v.NeckRingNumber, model.JoinKey, v.ActiveDate, model.JoinKey, xframeId) // 0001/2023-12-04/0 0001/2023-12-03/4
  631. if originalMapData[mapKey] == nil {
  632. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  633. }
  634. originalMapData[mapKey].IsMageData(v, xframeId)
  635. }
  636. currTime := time.Now()
  637. res := make([]*model.NeckActiveHabit, 0)
  638. // 算平均值
  639. for k, v := range originalMapData {
  640. // 过滤掉合并后<6条数据,如果时间太短就晚点再算
  641. if v.RecordCount < model.DefaultRecordCount {
  642. currMaxXframeId := util.FrameIdMapReverse[int32(currTime.Hour())]
  643. activeDateString := fmt.Sprintf("%s %02d:00:00", v.ActiveDate, v.XframeId*2+1)
  644. activeDate, _ := time.Parse(model.LayoutTime, activeDateString)
  645. if currMaxXframeId-v.XframeId <= 1 && currTime.Add(-1*time.Hour).Unix() < activeDate.Unix() {
  646. delete(originalMapData, k)
  647. continue
  648. }
  649. }
  650. v.SumAvg()
  651. }
  652. if len(originalMapData) <= 0 {
  653. return res
  654. }
  655. res = model.NeckRingOriginalMap(originalMapData).ForMatData()
  656. sort.Sort(model.NeckActiveHabitSlice(res))
  657. return res
  658. }
  659. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  660. originalList := make([]*model.NeckRingOriginal, 0)
  661. frameIds := util.FrameIds(data.Frameid)
  662. sql := ""
  663. for _, frameId := range frameIds {
  664. sql += fmt.Sprintf(`SELECT * FROM neck_ring_original WHERE pasture_id = %d AND neck_ring_number = '%s' AND active_date = '%s' AND frameid = %d UNION ALL `, data.PastureId, data.NeckRingNumber, data.HeatDate, frameId)
  665. }
  666. if len(sql) > 0 {
  667. sql = strings.TrimSuffix(sql, "UNION ALL ")
  668. }
  669. if err := e.DB.Raw(sql).Find(&originalList).Error; err != nil {
  670. return nil
  671. }
  672. /*if err := e.DB.Model(new(model.NeckRingOriginal)).
  673. Where("pasture_id = ?", data.PastureId).
  674. Where("neck_ring_number = ?", data.NeckRingNumber).
  675. Where("active_date = ?", data.HeatDate).
  676. Where("frameid IN (?)", frameIds).
  677. Find(&originalList).Error; err != nil {
  678. return nil
  679. }*/
  680. originalList = RemoveDuplicates(originalList)
  681. newDataList := Recalculate(originalList)
  682. if len(newDataList) != 1 {
  683. return nil
  684. }
  685. res := newDataList[0]
  686. res.IsShow = pasturePb.IsShow_No
  687. return res
  688. }
  689. // computeIfPositiveElse 辅助函数来计算过滤值
  690. func computeIfPositiveElse(newValue, prevFilterValue float64, weightPrev, weightNew float64) float64 {
  691. return math.Ceil((prevFilterValue * weightPrev) + (weightNew * newValue))
  692. }
  693. // 计算 score 的逻辑
  694. func calculateScore(habit *model.NeckActiveHabit) int {
  695. // 第一部分逻辑
  696. var part1 float64
  697. switch {
  698. case (habit.CalvingAge <= 1 && habit.Lact >= 1) ||
  699. (habit.CalvingAge >= 2 && habit.CalvingAge <= 13 && (habit.SumRumina+habit.SumIntake) == 0) ||
  700. ((habit.Lact == 0 || habit.CalvingAge >= 14) && habit.ChangeFilter == -99):
  701. part1 = -199
  702. case habit.CalvingAge >= 2 && habit.CalvingAge <= 13:
  703. part1 = math.Min((float64(habit.SumRumina+habit.SumIntake)-(100+math.Min(7, float64(habit.CalvingAge))*60))/10*2, 0)
  704. case habit.ChangeFilter > -99:
  705. part1 = math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinHigh), 0)))*0.2 +
  706. math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinChew), 0)))*0.2 +
  707. getRuminaSumIntakeSumScore(float64(habit.SumRumina+habit.SumIntake)) + getAdditionalScore(habit)
  708. default:
  709. part1 = -299
  710. }
  711. // 第二部分逻辑
  712. var part2 float64
  713. switch {
  714. case habit.FirmwareVersion%100 >= 52:
  715. part2 = 1
  716. case habit.FirmwareVersion%100 >= 30 && habit.FirmwareVersion%100 <= 43:
  717. part2 = 0.8
  718. default:
  719. part2 = 0.6
  720. }
  721. // 最终 score
  722. return DefaultScore + int(math.Floor(part1*part2))
  723. }
  724. // 获取值或默认值
  725. func getValueOrDefault(value, defaultValue float64) float64 {
  726. if value > -99 {
  727. return value
  728. }
  729. return defaultValue
  730. }
  731. // 计算累计反刍得分
  732. func getRuminaSumIntakeSumScore(sum float64) float64 {
  733. switch {
  734. case sum < 80:
  735. return -30
  736. case sum < 180:
  737. return -20
  738. case sum < 280:
  739. return -10
  740. default:
  741. return 0
  742. }
  743. }
  744. // 计算额外得分
  745. func getAdditionalScore(habit *model.NeckActiveHabit) float64 {
  746. var score float64
  747. if (habit.SumRumina+habit.SumIntake < 280 || habit.SumMinHigh+habit.SumMinChew < -50) && habit.SumMaxHigh > 50 {
  748. score += 10
  749. }
  750. if habit.ChangeFilter < -30 && habit.ChangeFilter <= habit.SumMinHigh && habit.ChewFilter < -30 && habit.ChewFilter <= habit.SumMinChew {
  751. score -= 5
  752. }
  753. return score
  754. }