neck_ring_handle.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. package crontab
  2. import (
  3. "fmt"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "math"
  7. "sort"
  8. "time"
  9. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  10. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  11. "gitee.com/xuyiping_admin/pkg/xerr"
  12. "go.uber.org/zap"
  13. )
  14. const (
  15. MinChangeFilter = -99
  16. MinRuminaFilter = -99
  17. MinChewFilter = -99
  18. MinChangeHigh = -99
  19. DefaultNb = 30
  20. DefaultScore = 100
  21. )
  22. var (
  23. defaultLimit = int32(1000)
  24. isDelete bool
  25. )
  26. // NeckRingOriginalMergeData 把脖环数据合并成2个小时的
  27. func (e *Entry) NeckRingOriginalMergeData() error {
  28. var (
  29. err error
  30. )
  31. limit := e.Cfg.NeckRingLimit
  32. if limit <= 0 {
  33. limit = defaultLimit
  34. }
  35. newTime := time.Now()
  36. //createdAt := newTime.Add(-1 * time.Hour)
  37. neckRingNumber := []string{"10026", "10027", "10028", "10029", "10030", "10031", "10032", "10033", "10034", "10035"}
  38. neckRingList := make([]*model.NeckRingOriginal, 0)
  39. if err = e.DB.Model(new(model.NeckRingOriginal)).
  40. Where("is_show = ?", pasturePb.IsShow_No).
  41. Where("neck_ring_number IN (?)", neckRingNumber).
  42. //Where("created_at <= ?", createdAt.Unix()).
  43. Order("active_date,frameid,neck_ring_number").
  44. Limit(int(limit)).Find(&neckRingList).Error; err != nil {
  45. return xerr.WithStack(err)
  46. }
  47. if len(neckRingList) <= 0 {
  48. return nil
  49. }
  50. defer func() {
  51. if newTime.Day()%15 == 0 && !isDelete {
  52. // 原始数据删除15天前的
  53. e.DB.Model(new(model.NeckRingOriginal)).
  54. Where("created_at < ?", newTime.AddDate(0, 0, -15).Unix()).
  55. Delete(new(model.NeckRingOriginal))
  56. e.DB.Model(new(model.NeckRingProcess)).
  57. Where("created_at < ?", newTime.AddDate(0, 0, -15).Unix()).
  58. Delete(new(model.NeckRingProcess))
  59. // 活动数据删除6个月前的数据
  60. e.DB.Model(new(model.NeckActiveHabit)).
  61. Where("created_at < ?", newTime.AddDate(0, -6, 0).Unix()).
  62. Delete(new(model.NeckActiveHabit))
  63. isDelete = true
  64. }
  65. }()
  66. // 计算合并
  67. neckActiveHabitList := e.recalculate(neckRingList)
  68. if len(neckActiveHabitList) <= 0 {
  69. return nil
  70. }
  71. for _, habit := range neckActiveHabitList {
  72. //更新脖环牛只相关信息 新数据直接插入
  73. historyNeckActiveHabit, ct := e.IsExistNeckActiveHabit(habit.NeckRingNumber, habit.HeatDate, habit.Frameid)
  74. if ct <= 0 {
  75. if err = e.DB.Create(habit).Error; err != nil {
  76. zaplog.Info("NeckRingOriginalMergeData-1",
  77. zap.Any("err", err),
  78. zap.Any("neckActiveHabit", habit),
  79. )
  80. }
  81. if err = e.UpdateNeckRingOriginalIsShow(habit); err != nil {
  82. zaplog.Error("NeckRingOriginalMergeData-2",
  83. zap.Any("err", err),
  84. zap.Any("neckActiveHabit", habit),
  85. )
  86. }
  87. continue
  88. }
  89. if historyNeckActiveHabit == nil || historyNeckActiveHabit.Id <= 0 {
  90. zaplog.Error("NeckRingOriginalMergeData-3",
  91. zap.Any("ct", ct),
  92. zap.Any("historyNeckActiveHabit", historyNeckActiveHabit),
  93. zap.Any("neckActiveHabit", habit),
  94. )
  95. continue
  96. }
  97. // 重新计算
  98. newNeckActiveHabit := e.againRecalculate(historyNeckActiveHabit)
  99. if newNeckActiveHabit != nil {
  100. if err = e.DB.Model(new(model.NeckActiveHabit)).
  101. Select("rumina", "intake", "inactive", "gasp", "other", "high", "active").
  102. Where("id = ?", historyNeckActiveHabit.Id).
  103. Updates(newNeckActiveHabit).Error; err != nil {
  104. zaplog.Error("NeckRingOriginalMergeData-5",
  105. zap.Any("err", err),
  106. zap.Any("ct", ct),
  107. zap.Any("historyNeckActiveHabit", historyNeckActiveHabit),
  108. zap.Any("newNeckActiveHabit", newNeckActiveHabit),
  109. )
  110. }
  111. }
  112. }
  113. return nil
  114. }
  115. func (e *Entry) NeckRingCalculate() error {
  116. pastureList := e.FindPastureList()
  117. if pastureList == nil || len(pastureList) == 0 {
  118. return nil
  119. }
  120. for _, pasture := range pastureList {
  121. if err := e.EntryUpdateActiveHabit(pasture.Id); err != nil {
  122. zaplog.Error("PastureUpdateActiveHabit", zap.Any("err", err), zap.Any("pasture", pasture))
  123. }
  124. zaplog.Info(fmt.Sprintf("PastureUpdateActiveHabit Success %d", pasture.Id))
  125. }
  126. return nil
  127. }
  128. // recalculate 合并计算
  129. func (e *Entry) recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  130. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  131. // 合并成2个小时的
  132. for _, v := range neckRingList {
  133. xframeId := util.XFrameId(v.Frameid)
  134. 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
  135. if originalMapData[mapKey] == nil {
  136. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  137. }
  138. originalMapData[mapKey].IsMageData(v, xframeId)
  139. }
  140. currTime := time.Now()
  141. // 算平均值
  142. for k, v := range originalMapData {
  143. // 过滤掉合并后不满6条数据
  144. if v.RecordCount < 6 {
  145. currMaxXframeId := util.FrameIdMapReverse[int32(currTime.Hour())]
  146. activeDateString := fmt.Sprintf("%s %02d:00:00", v.ActiveDate, v.XframeId*2+1)
  147. activeDate, _ := time.Parse(model.LayoutTime, activeDateString)
  148. if currMaxXframeId-v.XframeId <= 1 && currTime.Add(-1*time.Hour).Unix() < activeDate.Unix() {
  149. delete(originalMapData, k)
  150. }
  151. }
  152. if v.RecordCount > 6 {
  153. zaplog.Error("recalculate", zap.Any("k", k), zap.Any("v", v))
  154. delete(originalMapData, k)
  155. }
  156. v.SumAvg()
  157. }
  158. dataList := model.NeckRingOriginalMap(originalMapData).ForMatData()
  159. sort.Sort(model.NeckActiveHabitSlice(dataList))
  160. return dataList
  161. }
  162. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  163. originalList := make([]*model.NeckRingOriginal, 0)
  164. frameIds := util.FrameIds(data.Frameid)
  165. if err := e.DB.Model(new(model.NeckRingOriginal)).
  166. Where("neck_ring_number = ?", data.NeckRingNumber).
  167. Where("active_date = ?", data.HeatDate).
  168. Where("frameid IN (?)", frameIds).
  169. Find(&originalList).Error; err != nil {
  170. return nil
  171. }
  172. newDataList := e.recalculate(originalList)
  173. if len(newDataList) != 1 {
  174. return nil
  175. }
  176. return newDataList[0]
  177. }
  178. func (e *Entry) EntryUpdateActiveHabit(pastureId int64) (err error) {
  179. // 获取这段执行数据内最大日期和最小日期
  180. xToday := &XToday{}
  181. systemConfigureList, err := e.GetSystemConfigure(pastureId)
  182. if err != nil {
  183. return xerr.WithStack(err)
  184. }
  185. for _, v := range systemConfigureList {
  186. switch v.Name {
  187. case model.MaxHabit:
  188. xToday.LastMaxHabitId = v.Value
  189. case model.High:
  190. xToday.High = int32(v.Value)
  191. case model.Rumina:
  192. xToday.Rumina = int32(v.Value)
  193. case model.XRuminaDisc:
  194. xToday.XRuminaDisc = int32(v.Value)
  195. case model.XChangeDiscount:
  196. xToday.XChangeDiscount = int32(v.Value)
  197. case model.WeeklyActive:
  198. xToday.WeeklyActive = int32(v.Value)
  199. }
  200. }
  201. currMaxHabit := &model.NeckActiveHabit{}
  202. if err = e.DB.Model(new(model.NeckActiveHabit)).
  203. Where("id > ?", xToday.LastMaxHabitId).
  204. Where("pasture_id = ?", pastureId).
  205. Where("is_show = ?", pasturePb.IsShow_No).
  206. Order("id desc").First(currMaxHabit).Error; err != nil {
  207. return xerr.WithStack(err)
  208. }
  209. if currMaxHabit.Id <= 0 || currMaxHabit.Id <= xToday.LastMaxHabitId {
  210. return nil
  211. }
  212. xToday.CurrMaxHabitId = currMaxHabit.Id
  213. defer func() {
  214. // 更新最后一次执行的id值
  215. if err == nil {
  216. e.DB.Model(new(model.SystemConfigure)).
  217. Where("name = ?", model.MaxHabit).
  218. Where("pasture_id = ?", pastureId).
  219. Update("value", currMaxHabit.Id)
  220. }
  221. }()
  222. // 更新活动滤波
  223. if err = e.FirstFilterUpdate(pastureId, xToday); err != nil {
  224. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  225. }
  226. // 二次更新滤波
  227. if err = e.SecondUpdateChangeFilter(pastureId, xToday); err != nil {
  228. zaplog.Error("EntryUpdateActiveHabit", zap.Any("SecondUpdateChangeFilter", err), zap.Any("xToday", xToday))
  229. }
  230. // 活动量校正系数和健康评分
  231. if err = e.FilterCorrectAndScoreUpdate(pastureId, xToday); err != nil {
  232. zaplog.Error("EntryUpdateActiveHabit", zap.Any("ActivityVolumeChanges", err), zap.Any("xToday", xToday))
  233. }
  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("change_filter = ?", model.InitChangeFilter).
  239. Updates(map[string]interface{}{
  240. "change_filter": model.DefaultChangeFilter,
  241. "rumina_filter": model.DefaultRuminaFilter,
  242. "chew_filter": model.DefaultChewFilter,
  243. }).Error; err != nil {
  244. zaplog.Error("EntryUpdateActiveHabit", zap.Any("change_filter", err), zap.Any("xToday", xToday))
  245. }
  246. if err = e.DB.Model(new(model.NeckActiveHabit)).
  247. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  248. Where("pasture_id = ?", pastureId).
  249. Where("is_show = ?", pasturePb.IsShow_No).
  250. Where("change_filter < ?", 0).
  251. Where("filter_correct < ?", model.DefaultFilterCorrect).
  252. Updates(map[string]interface{}{
  253. "filter_correct": model.DefaultFilterCorrect,
  254. "is_show": pasturePb.IsShow_Ok,
  255. }).Error; err != nil {
  256. zaplog.Error("EntryUpdateActiveHabit", zap.Any("filter_correct", err), zap.Any("xToday", xToday))
  257. }
  258. // 插入群体校正表
  259. if err = e.UpdateChangeAdJust(pastureId, xToday); err != nil {
  260. zaplog.Error("EntryUpdateActiveHabit", zap.Any("UpdateChangeAdJust", err), zap.Any("xToday", xToday))
  261. }
  262. return nil
  263. }
  264. // FirstFilterUpdate 首次更新活动滤波
  265. func (e *Entry) FirstFilterUpdate(pastureId int64, xToDay *XToday) (err error) {
  266. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  267. if err = e.DB.Model(new(model.NeckActiveHabit)).
  268. Where("id BETWEEN ? AND ?", xToDay.LastMaxHabitId, xToDay.CurrMaxHabitId).
  269. Where("pasture_id = ?", pastureId).
  270. Where("is_show = ?", pasturePb.IsShow_No).
  271. Where("change_filter = ?", model.InitChangeFilter).
  272. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  273. Order("heat_date,neck_ring_number,frameid").
  274. Limit(int(defaultLimit)).Find(&newNeckActiveHabitList).Error; err != nil {
  275. return xerr.WithStack(err)
  276. }
  277. // 活动量滤波
  278. for _, v := range newNeckActiveHabitList {
  279. // 过滤牛只未绑定的脖环的数据
  280. cowInfo := e.GetCowInfoByNeckRingNumber(v.PastureId, v.NeckRingNumber)
  281. if cowInfo == nil || cowInfo.Id <= 0 {
  282. continue
  283. }
  284. frameId := v.Frameid
  285. heatDate := v.HeatDate
  286. if v.Frameid == 0 {
  287. frameId = 11
  288. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  289. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  290. }
  291. firstFilterData := e.FindFirstFilter(pastureId, v.NeckRingNumber, heatDate, frameId)
  292. if v.FilterHigh > 0 {
  293. firstFilterData.FilterHigh = v.FilterHigh
  294. } else {
  295. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  296. firstFilterData.FilterHigh = int32(computeIfPositiveElse(float64(v.High), float64(firstFilterData.FilterHigh), 0.23, 0.77))
  297. } else {
  298. firstFilterData.FilterHigh = v.High
  299. }
  300. }
  301. if v.FilterRumina > 0 {
  302. firstFilterData.FilterRumina = v.FilterRumina
  303. } else {
  304. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  305. firstFilterData.FilterRumina = int32(computeIfPositiveElse(float64(v.Rumina), float64(firstFilterData.FilterRumina), 0.33, 0.67))
  306. } else {
  307. firstFilterData.FilterRumina = v.Rumina
  308. }
  309. }
  310. if v.FilterChew > 0 {
  311. firstFilterData.FilterChew = v.FilterChew
  312. } else {
  313. if v.NeckRingNumber == firstFilterData.NeckRingNumber {
  314. firstFilterData.FilterChew = int32(computeIfPositiveElse(float64(v.Rumina+v.Intake), float64(firstFilterData.FilterChew), 0.33, 0.67))
  315. } else {
  316. firstFilterData.FilterChew = v.Rumina + v.Intake
  317. }
  318. }
  319. // 前七天的
  320. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  321. highDiff := v.FilterHigh - weekHabitData.WeekHighHabit
  322. denominator := float64(v.WeekHigh)*0.6 + float64(weekHabitData.WeekHighHabit)*0.2 + float64(xToDay.WeeklyActive)*0.2
  323. if highDiff > 0 {
  324. v.ChangeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  325. } else {
  326. v.ChangeHigh = int32(math.Round(float64(highDiff) / denominator * 100))
  327. }
  328. if weekHabitData.WeekRuminaHabit != 0 {
  329. v.ChangeRumina = int32(math.Round(float64(v.FilterRumina-weekHabitData.WeekRuminaHabit) / float64(weekHabitData.WeekRuminaHabit) * 100))
  330. } else {
  331. v.ChangeRumina = 0
  332. }
  333. if weekHabitData.WeekChewHabit != 0 {
  334. v.ChangeChew = int32(math.Round(float64(v.FilterChew-weekHabitData.WeekChewHabit) / float64(weekHabitData.WeekChewHabit) * 100))
  335. } else {
  336. v.ChangeChew = 0
  337. }
  338. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  339. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  340. // 更新过滤值
  341. if err = e.DB.Model(new(model.NeckActiveHabit)).
  342. Select(
  343. "filter_high", "filter_rumina", "filter_chew", "cow_id", "lact", "calving_age",
  344. "week_high_habit", "week_rumina_habit", "week_chew_habit", "week_intake_habit", "week_inactive_habit",
  345. "sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew",
  346. "change_high", "change_rumina", "change_chew", "before_three_sum_rumina", "before_three_sum_intake",
  347. ).Where("id = ?", v.Id).
  348. Updates(map[string]interface{}{
  349. "filter_high": firstFilterData.FilterHigh,
  350. "filter_rumina": firstFilterData.FilterRumina,
  351. "filter_chew": firstFilterData.FilterChew,
  352. "cow_id": cowInfo.Id,
  353. "lact": cowInfo.Lact,
  354. "calving_age": cowInfo.CalvingAge,
  355. "week_high_habit": weekHabitData.WeekHighHabit,
  356. "week_rumina_habit": weekHabitData.WeekRuminaHabit,
  357. "week_chew_habit": weekHabitData.WeekChewHabit,
  358. "week_intake_habit": weekHabitData.WeekIntakeHabit,
  359. "week_inactive_habit": weekHabitData.WeekIntakeHabit,
  360. "sum_rumina": sumHabitData.SumRumina,
  361. "sum_intake": sumHabitData.SumIntake,
  362. "sum_inactive": sumHabitData.SumInactive,
  363. "sum_active": sumHabitData.SumActive,
  364. "sum_max_high": sumHabitData.SumMaxHigh,
  365. "sum_min_high": sumHabitData.SumMinHigh,
  366. "sum_min_chew": sumHabitData.SumMinChew,
  367. "change_high": v.ChangeHigh,
  368. "change_rumina": v.ChangeRumina,
  369. "change_chew": v.ChangeChew,
  370. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  371. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  372. }).Error; err != nil {
  373. return xerr.WithStack(err)
  374. }
  375. }
  376. zaplog.Info("EntryUpdateActiveHabit-FilterUpdate-Success")
  377. return nil
  378. }
  379. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  380. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, xToday *XToday) (err error) {
  381. newChangeFilterList := make([]*ChangeFilterData, 0)
  382. if err = e.DB.Model(new(model.NeckActiveHabit)).
  383. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  384. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  385. Where("heat_date >= ?", time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)).
  386. Where("pasture_id = ?", pastureId).
  387. Where("change_filter = ?", model.InitChangeFilter).
  388. Where("change_high > ?", MinChangeHigh).
  389. Order("neck_ring_number,heat_date,frameid").
  390. Find(&newChangeFilterList).Error; err != nil {
  391. return xerr.WithStack(err)
  392. }
  393. for _, v := range newChangeFilterList {
  394. secondFilterData := &SecondFilterData{}
  395. frameId := v.FrameId
  396. heatDate := v.HeatDate
  397. if v.FrameId == 0 {
  398. frameId = 11
  399. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  400. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  401. }
  402. if err = e.DB.Model(new(model.NeckActiveHabit)).
  403. Select("neck_ring_number", "filter_high", "filter_rumina", "filter_chew").
  404. Where("neck_ring_number = ?", v.NeckRingNumber).
  405. Where("heat_date = ?", heatDate).
  406. Where("frameid = ?", frameId).
  407. First(&secondFilterData).Error; err != nil {
  408. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err))
  409. }
  410. if v.ChangeFilter > MinChangeFilter {
  411. secondFilterData.ChangeFilter = float64(v.ChangeFilter)
  412. } else {
  413. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  414. secondFilterData.ChangeFilter = secondFilterData.ChangeFilter*(1-(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount) +
  415. math.Min(float64(v.ChangeHigh), secondFilterData.ChangeFilter+135)*(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount
  416. } else {
  417. secondFilterData.ChangeFilter = 0
  418. }
  419. }
  420. if v.RuminaFilter > MinRuminaFilter {
  421. secondFilterData.RuminaFilter = float64(v.ChangeFilter)
  422. } else {
  423. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  424. discount := float64(xToday.XRuminaDisc) / 10 * v.XlcDisCount
  425. if math.Abs(float64(v.ChangeRumina)) > 60 {
  426. discount *= 0.5
  427. }
  428. secondFilterData.RuminaFilter = secondFilterData.RuminaFilter*(1-discount) + float64(v.ChangeRumina)*discount
  429. } else {
  430. secondFilterData.RuminaFilter = 0
  431. }
  432. }
  433. secondFilterData.RuminaFilter = math.Min(50, secondFilterData.RuminaFilter)
  434. if v.ChewFilter > MinChewFilter {
  435. secondFilterData.ChewFilter = float64(v.ChangeChew)
  436. } else {
  437. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  438. discount := float64(xToday.XRuminaDisc) / 10
  439. if math.Abs(float64(v.ChangeChew)) > 60 {
  440. discount *= 0.5
  441. }
  442. secondFilterData.ChewFilter = secondFilterData.ChewFilter*(1-discount) + float64(v.ChangeChew)*discount
  443. } else {
  444. secondFilterData.ChewFilter = 0
  445. }
  446. }
  447. secondFilterData.ChewFilter = math.Min(50, secondFilterData.ChewFilter)
  448. if err = e.DB.Model(new(model.NeckActiveHabit)).
  449. Select("change_filter", "rumina_filter", "chew_filter").
  450. Where("id = ?", v.Id).
  451. Updates(map[string]interface{}{
  452. "change_filter": secondFilterData.ChangeFilter,
  453. "rumina_filter": secondFilterData.RuminaFilter,
  454. "chew_filter": secondFilterData.ChewFilter,
  455. }).Error; err != nil {
  456. zaplog.Error("SecondUpdateChangeFilter-1", zap.Any("error", err), zap.Any("xToday", xToday))
  457. }
  458. }
  459. return nil
  460. }
  461. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  462. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, xToday *XToday) error {
  463. beginDayDate := time.Now()
  464. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  465. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  466. activityVolumeList := make([]*ActivityVolume, 0)
  467. activityVolumeMap := make(map[string]*ActivityVolume)
  468. if err := e.DB.Model(new(model.NeckActiveHabit)).
  469. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  470. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  471. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  472. Where("pasture_id = ?", pastureId).
  473. Where(e.DB.Where("high > ?", xToday.High).Or("rumina >= ?", xToday.Rumina)).
  474. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  475. Where("change_filter > ?", MinChangeFilter).
  476. Having("nb > ?", DefaultNb).
  477. Group("neck_ring_number").
  478. Find(&activityVolumeList).Error; err != nil {
  479. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  480. }
  481. if len(activityVolumeList) > 0 {
  482. for _, v := range activityVolumeList {
  483. activityVolumeMap[v.NeckRingNumber] = v
  484. }
  485. }
  486. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  487. if err := e.DB.Model(new(model.NeckActiveHabit)).
  488. Where("id <= ?", xToday.CurrMaxHabitId).
  489. Where("heat_date >= ?", before1DayDate).
  490. Where("pasture_id = ?", pastureId).
  491. Where(e.DB.Where("high > ?", xToday.High).Or("rumina > ?", xToday.Rumina)).
  492. Find(&neckActiveHabitList).Error; err != nil {
  493. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  494. return xerr.WithStack(err)
  495. }
  496. for _, v := range neckActiveHabitList {
  497. if filterCorrectMap, ok := activityVolumeMap[v.NeckRingNumber]; ok {
  498. filterCorrect := model.DefaultFilterCorrect - int(math.Floor(filterCorrectMap.AvgFilter/3+float64(filterCorrectMap.StdFilter)/2))
  499. // 活动量校正系数
  500. if err := e.DB.Model(new(model.NeckActiveHabit)).
  501. Where("id = ?", v.Id).
  502. Where("neck_ring_number = ?", v.NeckRingNumber).
  503. Update("filter_correct", filterCorrect).Error; err != nil {
  504. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  505. continue
  506. }
  507. }
  508. cowScore := calculateScore(v)
  509. if err := e.DB.Model(new(model.NeckActiveHabit)).
  510. Where("id = ?", v.Id).
  511. Update("score", cowScore).Error; err != nil {
  512. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  513. continue
  514. }
  515. }
  516. return nil
  517. }
  518. // UpdateChangeAdJust 更新群体校正数据
  519. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) error {
  520. res := make([]*model.NeckRingBarChange, 0)
  521. oneDayAgo := time.Now().AddDate(0, 0, -1).Format(model.LayoutDate2)
  522. //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,
  523. //ROUND(AVG(h.change_filter)) as change_filter F
  524. //ROM neck_active_habit as h JOIN cow as c ON h.neck_ring_number = c.neck_ring_number
  525. //WHERE h.pasture_id = 1 AND h.heat_date >= '2025-01-16' AND h.cow_id >= 0
  526. //GROUP BY h.heat_date, h.frameid, c.pen_id ORDER BY h.heat_date, h.frameid, c.pen_name
  527. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  528. 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").
  529. Joins("JOIN cow as c ON h.neck_ring_number = c.neck_ring_number").
  530. Where("h.pasture_id = ?", pastureId).
  531. Where("h.heat_date >= ?", oneDayAgo).
  532. Where("h.cow_id >= ?", 0).
  533. Group("h.heat_date, h.frameid, c.pen_id").
  534. Order("h.heat_date, h.frameid, c.pen_name").
  535. Find(&res).Error; err != nil {
  536. return xerr.WithStack(err)
  537. }
  538. for _, v := range res {
  539. if err := e.DB.Model(new(model.NeckActiveHabit)).
  540. Where("id > ?", xToday.LastMaxHabitId).
  541. Where("heat_date = ?", v.HeatDate).
  542. Where("frameid = ?", v.FrameId).
  543. Where("neck_ring_number = ?", v.NeckRingNumber).
  544. Update("change_adjust", v.ChangeHigh).Error; err != nil {
  545. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  546. }
  547. }
  548. return nil
  549. }
  550. func (e *Entry) UpdateNeckRingOriginalIsShow(neckRingList *model.NeckActiveHabit) error {
  551. if err := e.DB.Model(new(model.NeckRingOriginal)).
  552. Where("neck_ring_number = ?", neckRingList.NeckRingNumber).
  553. Where("active_date = ?", neckRingList.HeatDate).
  554. Where("frameid IN (?)", util.FrameIds(neckRingList.Frameid)).
  555. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  556. return xerr.WithStack(err)
  557. }
  558. return nil
  559. }
  560. // computeIfPositiveElse 辅助函数来计算过滤值
  561. func computeIfPositiveElse(newValue, prevFilterValue float64, weightPrev, weightNew float64) float64 {
  562. return math.Ceil((prevFilterValue * weightPrev) + (weightNew * newValue))
  563. }
  564. // 计算 score 的逻辑
  565. func calculateScore(habit *model.NeckActiveHabit) int {
  566. // 第一部分逻辑
  567. var part1 float64
  568. switch {
  569. case (habit.CalvingAge <= 1 && habit.Lact >= 1) ||
  570. (habit.CalvingAge >= 2 && habit.CalvingAge <= 13 && (habit.SumRumina+habit.SumIntake) == 0) ||
  571. ((habit.Lact == 0 || habit.CalvingAge >= 14) && habit.ChangeFilter == -99):
  572. part1 = -199
  573. case habit.CalvingAge >= 2 && habit.CalvingAge <= 13:
  574. part1 = math.Min((float64(habit.SumRumina+habit.SumIntake)-(100+math.Min(7, float64(habit.CalvingAge))*60))/10*2, 0)
  575. case habit.ChangeFilter > -99:
  576. part1 = math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinHigh), 0)))*0.2 +
  577. math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinChew), 0)))*0.2 +
  578. getRuminaSumIntakeSumScore(float64(habit.SumRumina+habit.SumIntake)) + getAdditionalScore(habit)
  579. default:
  580. part1 = -299
  581. }
  582. // 第二部分逻辑
  583. var part2 float64
  584. switch {
  585. case habit.FirmwareVersion%100 >= 52:
  586. part2 = 1
  587. case habit.FirmwareVersion%100 >= 30 && habit.FirmwareVersion%100 <= 43:
  588. part2 = 0.8
  589. default:
  590. part2 = 0.6
  591. }
  592. // 最终 score
  593. return DefaultScore + int(math.Floor(part1*part2))
  594. }
  595. // 获取值或默认值
  596. func getValueOrDefault(value, defaultValue float64) float64 {
  597. if value > -99 {
  598. return value
  599. }
  600. return defaultValue
  601. }
  602. // 计算累计反刍得分
  603. func getRuminaSumIntakeSumScore(sum float64) float64 {
  604. switch {
  605. case sum < 80:
  606. return -30
  607. case sum < 180:
  608. return -20
  609. case sum < 280:
  610. return -10
  611. default:
  612. return 0
  613. }
  614. }
  615. // 计算额外得分
  616. func getAdditionalScore(habit *model.NeckActiveHabit) float64 {
  617. var score float64
  618. if (habit.SumRumina+habit.SumIntake < 280 || habit.SumMinHigh+habit.SumMinChew < -50) && habit.SumMaxHigh > 50 {
  619. score += 10
  620. }
  621. if habit.ChangeFilter < -30 && habit.ChangeFilter <= habit.SumMinHigh && habit.ChewFilter < -30 && habit.ChewFilter <= habit.SumMinChew {
  622. score -= 5
  623. }
  624. return score
  625. }