neck_ring_merge.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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. // WeeklyUpdateActiveHabit 时间点周平均值计算
  315. func (e *Entry) WeeklyUpdateActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  316. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  317. if err = e.DB.Model(new(model.NeckActiveHabit)).
  318. Where("id IN (?)", processIds).
  319. Order("heat_date,neck_ring_number,frameid").
  320. Find(&newNeckActiveHabitList).Error; err != nil {
  321. return xerr.WithStack(err)
  322. }
  323. for _, v := range newNeckActiveHabitList {
  324. // 前七天的
  325. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  326. // 更新过滤值
  327. if err = e.DB.Model(new(model.NeckActiveHabit)).
  328. Select("week_high_habit", "week_rumina_habit", "week_chew_habit", "week_intake_habit", "week_inactive_habit").
  329. Where("id = ?", v.Id).
  330. Updates(map[string]interface{}{
  331. "week_high_habit": weekHabitData.WeekHighHabit,
  332. "week_rumina_habit": weekHabitData.WeekRuminaHabit,
  333. "week_chew_habit": weekHabitData.WeekChewHabit,
  334. "week_intake_habit": weekHabitData.WeekIntakeHabit,
  335. "week_inactive_habit": weekHabitData.WeekInactiveHabit,
  336. }).Error; err != nil {
  337. zaplog.Error("WeeklyUpdateActiveHabit",
  338. zap.Error(err),
  339. zap.Any("NeckActiveHabit", v),
  340. zap.Any("pastureId", pastureId),
  341. )
  342. }
  343. }
  344. if err = e.SumUpdateActiveHabit(pastureId, newNeckActiveHabitList, xToDay); err != nil {
  345. zaplog.Error("WeeklyUpdateActiveHabit",
  346. zap.Any("SumUpdateActiveHabit", err),
  347. zap.Any("newNeckActiveHabitList", newNeckActiveHabitList),
  348. zap.Any("pastureId", pastureId),
  349. )
  350. }
  351. if err = e.ActiveChange(pastureId, processIds, xToDay); err != nil {
  352. zaplog.Error("WeeklyUpdateActiveHabit",
  353. zap.Any("ActiveChange", err),
  354. zap.Any("processIds", processIds),
  355. zap.Any("xToDay", xToDay),
  356. zap.Any("pastureId", pastureId),
  357. )
  358. }
  359. return nil
  360. }
  361. // SumUpdateActiveHabit -- 累计24小时数值
  362. func (e *Entry) SumUpdateActiveHabit(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) (err error) {
  363. for _, v := range newNeckActiveHabitList {
  364. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  365. // 更新过滤值
  366. if err = e.DB.Model(new(model.NeckActiveHabit)).
  367. Select("sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew").
  368. Where("id = ?", v.Id).
  369. Updates(map[string]interface{}{
  370. "sum_rumina": sumHabitData.SumRumina,
  371. "sum_intake": sumHabitData.SumIntake,
  372. "sum_inactive": sumHabitData.SumInactive,
  373. "sum_active": sumHabitData.SumActive,
  374. "sum_max_high": sumHabitData.SumMaxHigh,
  375. "sum_min_high": sumHabitData.SumMinHigh,
  376. "sum_min_chew": sumHabitData.SumMinChew,
  377. }).Error; err != nil {
  378. zaplog.Error("WeeklyUpdateActiveHabit",
  379. zap.Any("err", err),
  380. zap.Any("NeckActiveHabit", v),
  381. zap.Any("pastureId", pastureId),
  382. )
  383. }
  384. }
  385. return err
  386. }
  387. // ActiveChange -- 变化百分比
  388. func (e *Entry) ActiveChange(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  389. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  390. if err = e.DB.Model(new(model.NeckActiveHabit)).
  391. Where("id IN (?)", processIds).
  392. Where("week_high_habit > ?", 0).
  393. Where(e.DB.Where("high >= ?", xToDay.High).Or("rumina >= ?", xToDay.Rumina)).
  394. Find(&newNeckActiveHabitList).Error; err != nil {
  395. return xerr.WithStack(err)
  396. }
  397. for _, v := range newNeckActiveHabitList {
  398. highDiff := v.FilterHigh - v.WeekHighHabit
  399. denominator := float64(v.WeekHigh)*0.6 + float64(v.WeekHighHabit)*0.2 + float64(xToDay.WeeklyActive)*0.2
  400. if highDiff > 0 {
  401. v.ChangeHigh = int32(math.Round((float64(highDiff) / denominator / float64(v.WeekHighHabit)) * 100))
  402. } else {
  403. v.ChangeHigh = int32(math.Round(float64(highDiff) / float64(v.WeekHighHabit) * 100))
  404. }
  405. if v.WeekRuminaHabit != 0 {
  406. v.ChangeRumina = int32(math.Round(float64(v.FilterRumina-v.WeekRuminaHabit) / float64(v.WeekRuminaHabit) * 100))
  407. }
  408. if v.WeekChewHabit != 0 {
  409. v.ChangeChew = int32(math.Round(float64(v.FilterChew-v.WeekChewHabit) / float64(v.WeekChewHabit) * 100))
  410. }
  411. // 更新过滤值
  412. if err = e.DB.Model(new(model.NeckActiveHabit)).
  413. Select("change_high", "change_rumina", "change_chew").
  414. Where("id = ?", v.Id).
  415. Updates(map[string]interface{}{
  416. "change_high": v.ChangeHigh,
  417. "change_rumina": v.ChangeRumina,
  418. "change_chew": v.ChangeChew,
  419. }).Error; err != nil {
  420. zaplog.Error("WeeklyUpdateActiveHabit",
  421. zap.Error(err),
  422. zap.Any("NeckActiveHabit", v),
  423. zap.Any("pastureId", pastureId),
  424. )
  425. }
  426. }
  427. return err
  428. }
  429. func (e *Entry) WeeklyUpdateActiveHabitOld(pastureId int64, newNeckActiveHabitList []*model.NeckActiveHabit, xToDay *XToday) (err error) {
  430. for _, v := range newNeckActiveHabitList {
  431. // 前七天的
  432. weekHabitData := e.FindWeekHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  433. highDiff := v.FilterHigh - weekHabitData.WeekHighHabit
  434. denominator := float64(v.WeekHigh)*0.6 + float64(weekHabitData.WeekHighHabit)*0.2 + float64(xToDay.WeeklyActive)*0.2
  435. if highDiff > 0 {
  436. v.ChangeHigh = int32(math.Round((float64(highDiff) / denominator) * 100))
  437. } else {
  438. v.ChangeHigh = int32(math.Round(float64(highDiff) / denominator * 100))
  439. }
  440. if weekHabitData.WeekRuminaHabit != 0 {
  441. v.ChangeRumina = int32(math.Round(float64(v.FilterRumina-weekHabitData.WeekRuminaHabit) / float64(weekHabitData.WeekRuminaHabit) * 100))
  442. } else {
  443. v.ChangeRumina = 0
  444. }
  445. if weekHabitData.WeekChewHabit != 0 {
  446. v.ChangeChew = int32(math.Round(float64(v.FilterChew-weekHabitData.WeekChewHabit) / float64(weekHabitData.WeekChewHabit) * 100))
  447. } else {
  448. v.ChangeChew = 0
  449. }
  450. sumHabitData := e.FindSumHabitData(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid, xToDay)
  451. // 更新过滤值
  452. if err = e.DB.Model(new(model.NeckActiveHabit)).
  453. Select(
  454. "week_high_habit", "week_rumina_habit", "week_chew_habit", "week_intake_habit", "week_inactive_habit",
  455. "sum_rumina", "sum_intake", "sum_inactive", "sum_active", "sum_max_high", "sum_min_high", "sum_min_chew",
  456. "change_high", "change_rumina", "change_chew", "before_three_sum_rumina", "before_three_sum_intake",
  457. ).Where("id = ?", v.Id).
  458. Updates(map[string]interface{}{
  459. "week_high_habit": weekHabitData.WeekHighHabit,
  460. "week_rumina_habit": weekHabitData.WeekRuminaHabit,
  461. "week_chew_habit": weekHabitData.WeekChewHabit,
  462. "week_intake_habit": weekHabitData.WeekIntakeHabit,
  463. "week_inactive_habit": weekHabitData.WeekInactiveHabit,
  464. "sum_rumina": sumHabitData.SumRumina,
  465. "sum_intake": sumHabitData.SumIntake,
  466. "sum_inactive": sumHabitData.SumInactive,
  467. "sum_active": sumHabitData.SumActive,
  468. "sum_max_high": sumHabitData.SumMaxHigh,
  469. "sum_min_high": sumHabitData.SumMinHigh,
  470. "sum_min_chew": sumHabitData.SumMinChew,
  471. "change_high": v.ChangeHigh,
  472. "change_rumina": v.ChangeRumina,
  473. "change_chew": v.ChangeChew,
  474. }).Error; err != nil {
  475. zaplog.Error("WeeklyUpdateActiveHabit",
  476. zap.Error(err),
  477. zap.Any("NeckActiveHabit", v),
  478. zap.Any("pastureId", pastureId),
  479. )
  480. }
  481. }
  482. return err
  483. }
  484. func (e *Entry) Before3DaysNeckActiveHabit(pastureId int64, processIds []int64, xToDay *XToday) (err error) {
  485. newNeckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  486. if err = e.DB.Model(new(model.NeckActiveHabit)).
  487. Where("id IN (?)", processIds).
  488. Order("heat_date,neck_ring_number,frameid").
  489. Find(&newNeckActiveHabitList).Error; err != nil {
  490. return xerr.WithStack(err)
  491. }
  492. for _, v := range newNeckActiveHabitList {
  493. before3DaysNeckActiveHabit := e.FindBefore3DaysNeckActiveHabit(pastureId, v.NeckRingNumber, v.HeatDate, v.Frameid)
  494. // 更新过滤值
  495. if err = e.DB.Model(new(model.NeckActiveHabit)).
  496. Select("before_three_sum_rumina", "before_three_sum_intake").
  497. Where("id = ?", v.Id).
  498. Updates(map[string]interface{}{
  499. "before_three_sum_rumina": before3DaysNeckActiveHabit.SumRumina,
  500. "before_three_sum_intake": before3DaysNeckActiveHabit.SumIntake,
  501. }).Error; err != nil {
  502. zaplog.Error("Before3DaysNeckActiveHabit",
  503. zap.Error(err),
  504. zap.Any("NeckActiveHabit", v),
  505. zap.Any("pastureId", pastureId),
  506. )
  507. }
  508. }
  509. return nil
  510. }
  511. // SecondUpdateChangeFilter 第二次更新变化趋势滤波
  512. func (e *Entry) SecondUpdateChangeFilter(pastureId int64, xToday *XToday) (err error) {
  513. newChangeFilterList := make([]*ChangeFilterData, 0)
  514. if err = e.DB.Model(new(model.NeckActiveHabit)).
  515. Select("id", "neck_ring_number", "change_high", "change_filter", "rumina_filter", "change_rumina",
  516. "chew_filter", "change_chew", "heat_date", "frameid", "IF(lact = 0, 0.8, 1) as xlc_dis_count").
  517. Where("heat_date >= ?", time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)).
  518. Where("pasture_id = ?", pastureId).
  519. Where("change_filter = ?", model.InitChangeFilter).
  520. Where("change_high > ?", MinChangeHigh).
  521. Order("neck_ring_number,heat_date,frameid").
  522. Find(&newChangeFilterList).Error; err != nil {
  523. return xerr.WithStack(err)
  524. }
  525. for _, v := range newChangeFilterList {
  526. secondFilterData := &SecondFilterData{}
  527. frameId := v.FrameId
  528. heatDate := v.HeatDate
  529. if v.FrameId == 0 {
  530. frameId = 11
  531. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  532. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  533. }
  534. if err = e.DB.Model(new(model.NeckActiveHabit)).
  535. Select("neck_ring_number", "filter_high", "filter_rumina", "filter_chew").
  536. Where("neck_ring_number = ?", v.NeckRingNumber).
  537. Where("heat_date = ?", heatDate).
  538. Where("frameid = ?", frameId).
  539. First(&secondFilterData).Error; err != nil {
  540. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err))
  541. }
  542. if v.ChangeFilter > MinChangeFilter {
  543. secondFilterData.ChangeFilter = float64(v.ChangeFilter)
  544. } else {
  545. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  546. secondFilterData.ChangeFilter = secondFilterData.ChangeFilter*(1-(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount) +
  547. math.Min(float64(v.ChangeHigh), secondFilterData.ChangeFilter+135)*(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount
  548. } else {
  549. secondFilterData.ChangeFilter = 0
  550. }
  551. }
  552. if v.RuminaFilter > MinRuminaFilter {
  553. secondFilterData.RuminaFilter = float64(v.ChangeFilter)
  554. } else {
  555. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  556. discount := float64(xToday.XRuminaDisc) / 10 * v.XlcDisCount
  557. if math.Abs(float64(v.ChangeRumina)) > 60 {
  558. discount *= 0.5
  559. }
  560. secondFilterData.RuminaFilter = secondFilterData.RuminaFilter*(1-discount) + float64(v.ChangeRumina)*discount
  561. } else {
  562. secondFilterData.RuminaFilter = 0
  563. }
  564. }
  565. secondFilterData.RuminaFilter = math.Min(50, secondFilterData.RuminaFilter)
  566. if v.ChewFilter > MinChewFilter {
  567. secondFilterData.ChewFilter = float64(v.ChangeChew)
  568. } else {
  569. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  570. discount := float64(xToday.XRuminaDisc) / 10
  571. if math.Abs(float64(v.ChangeChew)) > 60 {
  572. discount *= 0.5
  573. }
  574. secondFilterData.ChewFilter = secondFilterData.ChewFilter*(1-discount) + float64(v.ChangeChew)*discount
  575. } else {
  576. secondFilterData.ChewFilter = 0
  577. }
  578. }
  579. secondFilterData.ChewFilter = math.Min(50, secondFilterData.ChewFilter)
  580. if err = e.DB.Model(new(model.NeckActiveHabit)).
  581. Select("change_filter", "rumina_filter", "chew_filter").
  582. Where("id = ?", v.Id).
  583. Updates(map[string]interface{}{
  584. "change_filter": secondFilterData.ChangeFilter,
  585. "rumina_filter": secondFilterData.RuminaFilter,
  586. "chew_filter": secondFilterData.ChewFilter,
  587. }).Error; err != nil {
  588. zaplog.Error("SecondUpdateChangeFilter-1", zap.Any("error", err), zap.Any("xToday", xToday))
  589. }
  590. }
  591. return nil
  592. }
  593. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  594. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, xToday *XToday) error {
  595. beginDayDate := time.Now()
  596. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  597. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  598. activityVolumeList := make([]*ActivityVolume, 0)
  599. activityVolumeMap := make(map[string]*ActivityVolume)
  600. if err := e.DB.Model(new(model.NeckActiveHabit)).
  601. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  602. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  603. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  604. Where("pasture_id = ?", pastureId).
  605. Where(e.DB.Where("high > ?", xToday.High).Or("rumina >= ?", xToday.Rumina)).
  606. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  607. Where("change_filter > ?", MinChangeFilter).
  608. Having("nb > ?", DefaultNb).
  609. Group("neck_ring_number").
  610. Find(&activityVolumeList).Error; err != nil {
  611. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  612. }
  613. if len(activityVolumeList) > 0 {
  614. for _, v := range activityVolumeList {
  615. activityVolumeMap[v.NeckRingNumber] = v
  616. }
  617. }
  618. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  619. if err := e.DB.Model(new(model.NeckActiveHabit)).
  620. Where("id <= ?", xToday.CurrMaxHabitId).
  621. Where("heat_date >= ?", before1DayDate).
  622. Where("pasture_id = ?", pastureId).
  623. Where(e.DB.Where("high > ?", xToday.High).Or("rumina > ?", xToday.Rumina)).
  624. Find(&neckActiveHabitList).Error; err != nil {
  625. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  626. return xerr.WithStack(err)
  627. }
  628. for _, v := range neckActiveHabitList {
  629. if filterCorrectMap, ok := activityVolumeMap[v.NeckRingNumber]; ok {
  630. filterCorrect := model.DefaultFilterCorrect - int(math.Floor(filterCorrectMap.AvgFilter/3+float64(filterCorrectMap.StdFilter)/2))
  631. // 活动量校正系数
  632. if err := e.DB.Model(new(model.NeckActiveHabit)).
  633. Where("id = ?", v.Id).
  634. Where("neck_ring_number = ?", v.NeckRingNumber).
  635. Update("filter_correct", filterCorrect).Error; err != nil {
  636. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  637. continue
  638. }
  639. }
  640. cowScore := calculateScore(v)
  641. if err := e.DB.Model(new(model.NeckActiveHabit)).
  642. Where("id = ?", v.Id).
  643. Update("score", cowScore).Error; err != nil {
  644. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  645. continue
  646. }
  647. }
  648. return nil
  649. }
  650. // UpdateChangeAdJust 更新群体校正数据
  651. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) error {
  652. /*-- 插入群体校正表
  653. INSERT INTO data_bar_change(heatdate, frameid, intCurBar, intCurBarName, nb, highchange, changefilter)
  654. SELECT h.heatdate, h.frameid, c.intCurBar, c.intCurBarName, COUNT(*) nb, ROUND(AVG(h.highchange)) highchange, ROUND(AVG(h.changefilter) ) changefilter
  655. FROM h_activehabit h JOIN cow c ON h.intCowId=c.intCowId
  656. WHERE h.heatdate>=(CURDATE() -INTERVAL 1 DAY )
  657. GROUP BY h.heatdate, h.frameid, c.intCurBar
  658. ORDER BY h.heatdate, h.frameid, c.intCurBarName
  659. ON DUPLICATE KEY UPDATE nb = VALUES(nb), highchange = VALUES(highchange), changefilter = VALUES(changefilter);
  660. UPDATE h_activehabit h
  661. JOIN cow c ON h.intCowId=c.intCowId
  662. JOIN data_bar_change cg ON h.heatdate=cg.heatdate AND h.frameid=cg.frameid AND c.intCurBar=cg.intCurBar
  663. SET h.changeadjust=cg.changefilter
  664. WHERE h.id>xBeg_update_act_Id AND h.heatdate>=CURRENT_DATE() - INTERVAL 1 DAY AND ABS(cg.changefilter)>=10;
  665. */
  666. res := make([]*model.NeckRingBarChange, 0)
  667. oneDayAgo := time.Now().AddDate(0, 0, -1).Format(model.LayoutDate2)
  668. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  669. 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").
  670. Joins("JOIN cow as c ON h.neck_ring_number = c.neck_ring_number").
  671. Where("h.pasture_id = ?", pastureId).
  672. Where("h.heat_date >= ?", oneDayAgo).
  673. Where("h.cow_id >= ?", 0).
  674. Where("h.cow_id >= ?", 0).
  675. Group("h.heat_date, h.frameid, c.pen_id").
  676. Order("h.heat_date, h.frameid, c.pen_name").
  677. Find(&res).Error; err != nil {
  678. return xerr.WithStack(err)
  679. }
  680. // todo ABS(cg.changefilter)>=10;
  681. for _, v := range res {
  682. if err := e.DB.Model(new(model.NeckActiveHabit)).
  683. Where("id > ?", xToday.LastMaxHabitId).
  684. Where("heat_date = ?", v.HeatDate).
  685. Where("frameid = ?", v.FrameId).
  686. Where("neck_ring_number = ?", v.NeckRingNumber).
  687. Update("change_adjust", v.ChangeHigh).Error; err != nil {
  688. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  689. }
  690. }
  691. // 更新所有的显示状态为否的记录为是
  692. if err := e.DB.Model(new(model.NeckActiveHabit)).
  693. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  694. Where("pasture_id = ?", pastureId).
  695. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  696. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err), zap.Any("xToday", xToday))
  697. }
  698. return nil
  699. }
  700. func (e *Entry) UpdateNeckRingOriginalIsShow(habit *model.NeckActiveHabit) error {
  701. if err := e.DB.Model(new(model.NeckRingOriginal)).
  702. Where("pasture_id = ?", habit.PastureId).
  703. Where("neck_ring_number = ?", habit.NeckRingNumber).
  704. Where("active_date = ?", habit.HeatDate).
  705. Where("frameid IN (?)", util.FrameIds(habit.Frameid)).
  706. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  707. return xerr.WithStack(err)
  708. }
  709. return nil
  710. }
  711. // RemoveDuplicates 清洗一下数据,去掉重复的,如果有重复的,取最新的一条数据
  712. func RemoveDuplicates(records []*model.NeckRingOriginal) []*model.NeckRingOriginal {
  713. uniqueRecords := make(map[string]*model.NeckRingOriginal)
  714. // 遍历原始数组
  715. for _, record := range records {
  716. 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
  717. if existing, exists := uniqueRecords[mapKey]; exists {
  718. if record.CreatedAt > existing.CreatedAt {
  719. uniqueRecords[mapKey] = record
  720. }
  721. } else {
  722. uniqueRecords[mapKey] = record
  723. }
  724. }
  725. // 将 map 中的记录转换为切片
  726. result := make([]*model.NeckRingOriginal, 0, len(uniqueRecords))
  727. for _, record := range uniqueRecords {
  728. result = append(result, record)
  729. }
  730. return result
  731. }
  732. // Recalculate 合并计算
  733. func Recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  734. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  735. // 合并成2个小时的
  736. for _, v := range neckRingList {
  737. xframeId := util.XFrameId(v.Frameid)
  738. 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
  739. if originalMapData[mapKey] == nil {
  740. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  741. }
  742. originalMapData[mapKey].IsMageData(v, xframeId)
  743. }
  744. currTime := time.Now()
  745. res := make([]*model.NeckActiveHabit, 0)
  746. // 算平均值
  747. for k, v := range originalMapData {
  748. // 过滤掉合并后<6条数据,如果时间太短就晚点再算
  749. if v.RecordCount < model.DefaultRecordCount {
  750. currMaxXframeId := util.FrameIdMapReverse[int32(currTime.Hour())]
  751. activeDateString := fmt.Sprintf("%s %02d:00:00", v.ActiveDate, v.XframeId*2+1)
  752. activeDate, _ := time.Parse(model.LayoutTime, activeDateString)
  753. if currMaxXframeId-v.XframeId <= 1 && currTime.Add(-1*time.Hour).Unix() < activeDate.Unix() {
  754. delete(originalMapData, k)
  755. continue
  756. }
  757. }
  758. v.SumAvg()
  759. }
  760. if len(originalMapData) <= 0 {
  761. return res
  762. }
  763. res = model.NeckRingOriginalMap(originalMapData).ForMatData()
  764. sort.Sort(model.NeckActiveHabitSlice(res))
  765. return res
  766. }
  767. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  768. originalList := make([]*model.NeckRingOriginal, 0)
  769. frameIds := util.FrameIds(data.Frameid)
  770. sql := ""
  771. for _, frameId := range frameIds {
  772. 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)
  773. }
  774. if len(sql) > 0 {
  775. sql = strings.TrimSuffix(sql, "UNION ALL ")
  776. }
  777. if err := e.DB.Raw(sql).Find(&originalList).Error; err != nil {
  778. return nil
  779. }
  780. /*if err := e.DB.Model(new(model.NeckRingOriginal)).
  781. Where("pasture_id = ?", data.PastureId).
  782. Where("neck_ring_number = ?", data.NeckRingNumber).
  783. Where("active_date = ?", data.HeatDate).
  784. Where("frameid IN (?)", frameIds).
  785. Find(&originalList).Error; err != nil {
  786. return nil
  787. }*/
  788. originalList = RemoveDuplicates(originalList)
  789. newDataList := Recalculate(originalList)
  790. if len(newDataList) != 1 {
  791. return nil
  792. }
  793. res := newDataList[0]
  794. res.IsShow = pasturePb.IsShow_No
  795. return res
  796. }
  797. // computeIfPositiveElse 辅助函数来计算过滤值
  798. func computeIfPositiveElse(newValue, prevFilterValue float64, weightPrev, weightNew float64) float64 {
  799. return math.Ceil((prevFilterValue * weightPrev) + (weightNew * newValue))
  800. }
  801. // 计算 score 的逻辑
  802. func calculateScore(habit *model.NeckActiveHabit) int {
  803. // 第一部分逻辑
  804. var part1 float64
  805. switch {
  806. case (habit.CalvingAge <= 1 && habit.Lact >= 1) ||
  807. (habit.CalvingAge >= 2 && habit.CalvingAge <= 13 && (habit.SumRumina+habit.SumIntake) == 0) ||
  808. ((habit.Lact == 0 || habit.CalvingAge >= 14) && habit.ChangeFilter == -99):
  809. part1 = -199
  810. case habit.CalvingAge >= 2 && habit.CalvingAge <= 13:
  811. part1 = math.Min((float64(habit.SumRumina+habit.SumIntake)-(100+math.Min(7, float64(habit.CalvingAge))*60))/10*2, 0)
  812. case habit.ChangeFilter > -99:
  813. part1 = math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinHigh), 0)))*0.2 +
  814. math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinChew), 0)))*0.2 +
  815. getRuminaSumIntakeSumScore(float64(habit.SumRumina+habit.SumIntake)) + getAdditionalScore(habit)
  816. default:
  817. part1 = -299
  818. }
  819. // 第二部分逻辑
  820. var part2 float64
  821. switch {
  822. case habit.FirmwareVersion%100 >= 52:
  823. part2 = 1
  824. case habit.FirmwareVersion%100 >= 30 && habit.FirmwareVersion%100 <= 43:
  825. part2 = 0.8
  826. default:
  827. part2 = 0.6
  828. }
  829. // 最终 score
  830. return DefaultScore + int(math.Floor(part1*part2))
  831. }
  832. // 获取值或默认值
  833. func getValueOrDefault(value, defaultValue float64) float64 {
  834. if value > -99 {
  835. return value
  836. }
  837. return defaultValue
  838. }
  839. // 计算累计反刍得分
  840. func getRuminaSumIntakeSumScore(sum float64) float64 {
  841. switch {
  842. case sum < 80:
  843. return -30
  844. case sum < 180:
  845. return -20
  846. case sum < 280:
  847. return -10
  848. default:
  849. return 0
  850. }
  851. }
  852. // 计算额外得分
  853. func getAdditionalScore(habit *model.NeckActiveHabit) float64 {
  854. var score float64
  855. if (habit.SumRumina+habit.SumIntake < 280 || habit.SumMinHigh+habit.SumMinChew < -50) && habit.SumMaxHigh > 50 {
  856. score += 10
  857. }
  858. if habit.ChangeFilter < -30 && habit.ChangeFilter <= habit.SumMinHigh && habit.ChewFilter < -30 && habit.ChewFilter <= habit.SumMinChew {
  859. score -= 5
  860. }
  861. return score
  862. }