neck_ring_merge.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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").
  160. First(currMaxHabit).Error; err != nil {
  161. return xerr.WithStack(err)
  162. }
  163. if currMaxHabit.Id <= 0 || currMaxHabit.Id <= xToday.LastMaxHabitId {
  164. return nil
  165. }
  166. xToday.CurrMaxHabitId = currMaxHabit.Id
  167. var processIds []int64
  168. // 更新活动滤波
  169. processIds, err = e.FirstFilterUpdate(pastureId, xToday)
  170. if err != nil {
  171. zaplog.Error("NeckRingCalculate", zap.Any("FirstFilterUpdate", err), zap.Any("xToday", xToday))
  172. }
  173. zaplog.Info("NeckRingCalculate", zap.Any("xToday", xToday), zap.Any("processIds", processIds))
  174. if len(processIds) > 0 {
  175. if err = e.WeeklyUpdateActiveHabit(pastureId, processIds, xToday); err != nil {
  176. zaplog.Error("NeckRingCalculate", zap.Any("WeeklyUpdateActiveHabit", err), zap.Any("xToday", xToday))
  177. }
  178. if err = e.Before3DaysNeckActiveHabit(pastureId, processIds, xToday); err != nil {
  179. zaplog.Error("NeckRingCalculate", zap.Any("Before3DaysNeckActiveHabit", err), zap.Any("xToday", xToday))
  180. }
  181. // 二次更新滤波
  182. if err = e.SecondUpdateChangeFilter(pastureId, xToday); err != nil {
  183. zaplog.Error("NeckRingCalculate", zap.Any("SecondUpdateChangeFilter", err), zap.Any("xToday", xToday))
  184. }
  185. // 更新日志
  186. if err = e.DB.Model(new(model.NeckRingConfigure)).
  187. Where("name = ?", model.MaxHabit).
  188. Where("pasture_id = ?", pastureId).
  189. Update("value", processIds[len(processIds)-1]).Error; err != nil {
  190. zaplog.Error("NeckRingCalculate", zap.Any("MaxHabit", 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 > ?", xToDay.LastMaxHabitId).
  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("id > ?", xToday.LastMaxHabitId).
  518. Where("heat_date >= ?", time.Now().AddDate(0, 0, -2).Format(model.LayoutDate2)).
  519. Where("pasture_id = ?", pastureId).
  520. Where("change_filter = ?", model.InitChangeFilter).
  521. Where("change_high > ?", MinChangeHigh).
  522. Order("neck_ring_number,heat_date,frameid").
  523. Limit(int(defaultLimit)).
  524. Find(&newChangeFilterList).Error; err != nil {
  525. return xerr.WithStack(err)
  526. }
  527. for _, v := range newChangeFilterList {
  528. secondFilterData := &SecondFilterData{}
  529. frameId := v.FrameId
  530. heatDate := v.HeatDate
  531. if v.FrameId == 0 {
  532. frameId = 11
  533. heatDateParse, _ := time.Parse(model.LayoutDate2, heatDate)
  534. heatDate = heatDateParse.AddDate(0, 0, -1).Format(model.LayoutDate2)
  535. }
  536. if err = e.DB.Model(new(model.NeckActiveHabit)).
  537. Select("neck_ring_number", "filter_high", "filter_rumina", "filter_chew").
  538. Where("neck_ring_number = ?", v.NeckRingNumber).
  539. Where("heat_date = ?", heatDate).
  540. Where("frameid = ?", frameId).
  541. First(&secondFilterData).Error; err != nil {
  542. zaplog.Error("EntryUpdateActiveHabit", zap.Any("FirstFilterUpdate", err))
  543. }
  544. if v.ChangeFilter > MinChangeFilter {
  545. secondFilterData.ChangeFilter = float64(v.ChangeFilter)
  546. } else {
  547. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  548. secondFilterData.ChangeFilter = secondFilterData.ChangeFilter*(1-(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount) +
  549. math.Min(float64(v.ChangeHigh), secondFilterData.ChangeFilter+135)*(float64(xToday.XChangeDiscount)/10)*v.XlcDisCount
  550. } else {
  551. secondFilterData.ChangeFilter = 0
  552. }
  553. }
  554. if v.RuminaFilter > MinRuminaFilter {
  555. secondFilterData.RuminaFilter = float64(v.ChangeFilter)
  556. } else {
  557. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  558. discount := float64(xToday.XRuminaDisc) / 10 * v.XlcDisCount
  559. if math.Abs(float64(v.ChangeRumina)) > 60 {
  560. discount *= 0.5
  561. }
  562. secondFilterData.RuminaFilter = secondFilterData.RuminaFilter*(1-discount) + float64(v.ChangeRumina)*discount
  563. } else {
  564. secondFilterData.RuminaFilter = 0
  565. }
  566. }
  567. secondFilterData.RuminaFilter = math.Min(50, secondFilterData.RuminaFilter)
  568. if v.ChewFilter > MinChewFilter {
  569. secondFilterData.ChewFilter = float64(v.ChangeChew)
  570. } else {
  571. if v.NeckRingNumber == secondFilterData.NeckRingNumber {
  572. discount := float64(xToday.XRuminaDisc) / 10
  573. if math.Abs(float64(v.ChangeChew)) > 60 {
  574. discount *= 0.5
  575. }
  576. secondFilterData.ChewFilter = secondFilterData.ChewFilter*(1-discount) + float64(v.ChangeChew)*discount
  577. } else {
  578. secondFilterData.ChewFilter = 0
  579. }
  580. }
  581. secondFilterData.ChewFilter = math.Min(50, secondFilterData.ChewFilter)
  582. if err = e.DB.Model(new(model.NeckActiveHabit)).
  583. Select("change_filter", "rumina_filter", "chew_filter").
  584. Where("id = ?", v.Id).
  585. Updates(map[string]interface{}{
  586. "change_filter": secondFilterData.ChangeFilter,
  587. "rumina_filter": secondFilterData.RuminaFilter,
  588. "chew_filter": secondFilterData.ChewFilter,
  589. }).Error; err != nil {
  590. zaplog.Error("SecondUpdateChangeFilter-1", zap.Any("error", err), zap.Any("xToday", xToday))
  591. }
  592. }
  593. return nil
  594. }
  595. // FilterCorrectAndScoreUpdate 计算活动量变化趋势校正值(活跃度校正)和健康评分
  596. func (e *Entry) FilterCorrectAndScoreUpdate(pastureId int64, xToday *XToday) error {
  597. beginDayDate := time.Now()
  598. before7DayDate := beginDayDate.AddDate(0, 0, -7).Format(model.LayoutDate2)
  599. before1DayDate := beginDayDate.AddDate(0, 0, -1).Format(model.LayoutDate2)
  600. activityVolumeList := make([]*ActivityVolume, 0)
  601. activityVolumeMap := make(map[string]*ActivityVolume)
  602. if err := e.DB.Model(new(model.NeckActiveHabit)).
  603. Select("neck_ring_number", "AVG(IF(change_filter>=60, 60, change_filter)) as avg_filter",
  604. "ROUND(STD(IF(change_filter>=60, 60, change_filter))) as std_filter", "COUNT(1) as nb").
  605. Where("heat_date BETWEEN ? AND ?", before7DayDate, before1DayDate).
  606. Where("pasture_id = ?", pastureId).
  607. Where(e.DB.Where("high > ?", xToday.High).Or("rumina >= ?", xToday.Rumina)).
  608. Where("active_time <= ?", beginDayDate.Add(-12*time.Hour).Format(model.LayoutTime)).
  609. Where("change_filter > ?", MinChangeFilter).
  610. Having("nb > ?", DefaultNb).
  611. Group("neck_ring_number").
  612. Find(&activityVolumeList).Error; err != nil {
  613. zaplog.Error("ActivityVolumeChanges-0", zap.Any("error", err), zap.Any("xToday", xToday))
  614. }
  615. if len(activityVolumeList) > 0 {
  616. for _, v := range activityVolumeList {
  617. activityVolumeMap[v.NeckRingNumber] = v
  618. }
  619. }
  620. neckActiveHabitList := make([]*model.NeckActiveHabit, 0)
  621. if err := e.DB.Model(new(model.NeckActiveHabit)).
  622. Where("id <= ?", xToday.CurrMaxHabitId).
  623. Where("heat_date >= ?", before1DayDate).
  624. Where("pasture_id = ?", pastureId).
  625. Where(e.DB.Where("high > ?", xToday.High).Or("rumina > ?", xToday.Rumina)).
  626. Find(&neckActiveHabitList).Error; err != nil {
  627. zaplog.Error("ActivityVolumeChanges-1", zap.Any("error", err), zap.Any("xToday", xToday))
  628. return xerr.WithStack(err)
  629. }
  630. for _, v := range neckActiveHabitList {
  631. if filterCorrectMap, ok := activityVolumeMap[v.NeckRingNumber]; ok {
  632. filterCorrect := model.DefaultFilterCorrect - int(math.Floor(filterCorrectMap.AvgFilter/3+float64(filterCorrectMap.StdFilter)/2))
  633. // 活动量校正系数
  634. if err := e.DB.Model(new(model.NeckActiveHabit)).
  635. Where("id = ?", v.Id).
  636. Where("neck_ring_number = ?", v.NeckRingNumber).
  637. Update("filter_correct", filterCorrect).Error; err != nil {
  638. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  639. continue
  640. }
  641. }
  642. cowScore := calculateScore(v)
  643. if err := e.DB.Model(new(model.NeckActiveHabit)).
  644. Where("id = ?", v.Id).
  645. Update("score", cowScore).Error; err != nil {
  646. zaplog.Error("ActivityVolumeChanges-2", zap.Any("error", err), zap.Any("xToday", xToday))
  647. continue
  648. }
  649. }
  650. return nil
  651. }
  652. // UpdateChangeAdJust 更新群体校正数据
  653. func (e *Entry) UpdateChangeAdJust(pastureId int64, xToday *XToday) error {
  654. /*-- 插入群体校正表
  655. INSERT INTO data_bar_change(heatdate, frameid, intCurBar, intCurBarName, nb, highchange, changefilter)
  656. SELECT h.heatdate, h.frameid, c.intCurBar, c.intCurBarName, COUNT(*) nb, ROUND(AVG(h.highchange)) highchange, ROUND(AVG(h.changefilter) ) changefilter
  657. FROM h_activehabit h JOIN cow c ON h.intCowId=c.intCowId
  658. WHERE h.heatdate>=(CURDATE() -INTERVAL 1 DAY )
  659. GROUP BY h.heatdate, h.frameid, c.intCurBar
  660. ORDER BY h.heatdate, h.frameid, c.intCurBarName
  661. ON DUPLICATE KEY UPDATE nb = VALUES(nb), highchange = VALUES(highchange), changefilter = VALUES(changefilter);
  662. UPDATE h_activehabit h
  663. JOIN cow c ON h.intCowId=c.intCowId
  664. JOIN data_bar_change cg ON h.heatdate=cg.heatdate AND h.frameid=cg.frameid AND c.intCurBar=cg.intCurBar
  665. SET h.changeadjust=cg.changefilter
  666. WHERE h.id>xBeg_update_act_Id AND h.heatdate>=CURRENT_DATE() - INTERVAL 1 DAY AND ABS(cg.changefilter)>=10;
  667. */
  668. res := make([]*model.NeckRingBarChange, 0)
  669. oneDayAgo := time.Now().AddDate(0, 0, -1).Format(model.LayoutDate2)
  670. if err := e.DB.Table(fmt.Sprintf("%s as h", new(model.NeckActiveHabit).TableName())).
  671. 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").
  672. Joins("JOIN cow as c ON h.neck_ring_number = c.neck_ring_number").
  673. Where("h.pasture_id = ?", pastureId).
  674. Where("h.heat_date >= ?", oneDayAgo).
  675. Where("h.cow_id >= ?", 0).
  676. Where("h.cow_id >= ?", 0).
  677. Group("h.heat_date, h.frameid, c.pen_id").
  678. Order("h.heat_date, h.frameid, c.pen_name").
  679. Find(&res).Error; err != nil {
  680. return xerr.WithStack(err)
  681. }
  682. // todo ABS(cg.changefilter)>=10;
  683. for _, v := range res {
  684. if err := e.DB.Model(new(model.NeckActiveHabit)).
  685. Where("id > ?", xToday.LastMaxHabitId).
  686. Where("heat_date = ?", v.HeatDate).
  687. Where("frameid = ?", v.FrameId).
  688. Where("neck_ring_number = ?", v.NeckRingNumber).
  689. Update("change_adjust", v.ChangeHigh).Error; err != nil {
  690. zaplog.Error("UpdateChangeAdJust-1", zap.Any("error", err), zap.Any("xToday", xToday))
  691. }
  692. }
  693. // 更新所有的显示状态为否的记录为是
  694. if err := e.DB.Model(new(model.NeckActiveHabit)).
  695. Where("id BETWEEN ? AND ?", xToday.LastMaxHabitId, xToday.CurrMaxHabitId).
  696. Where("pasture_id = ?", pastureId).
  697. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  698. zaplog.Error("UpdateChangeAdJust-2", zap.Any("error", err), zap.Any("xToday", xToday))
  699. }
  700. return nil
  701. }
  702. func (e *Entry) UpdateNeckRingOriginalIsShow(habit *model.NeckActiveHabit) error {
  703. if err := e.DB.Model(new(model.NeckRingOriginal)).
  704. Where("pasture_id = ?", habit.PastureId).
  705. Where("neck_ring_number = ?", habit.NeckRingNumber).
  706. Where("active_date = ?", habit.HeatDate).
  707. Where("frameid IN (?)", util.FrameIds(habit.Frameid)).
  708. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  709. return xerr.WithStack(err)
  710. }
  711. return nil
  712. }
  713. // RemoveDuplicates 清洗一下数据,去掉重复的,如果有重复的,取最新的一条数据
  714. func RemoveDuplicates(records []*model.NeckRingOriginal) []*model.NeckRingOriginal {
  715. uniqueRecords := make(map[string]*model.NeckRingOriginal)
  716. // 遍历原始数组
  717. for _, record := range records {
  718. 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
  719. if existing, exists := uniqueRecords[mapKey]; exists {
  720. if record.CreatedAt > existing.CreatedAt {
  721. uniqueRecords[mapKey] = record
  722. }
  723. } else {
  724. uniqueRecords[mapKey] = record
  725. }
  726. }
  727. // 将 map 中的记录转换为切片
  728. result := make([]*model.NeckRingOriginal, 0, len(uniqueRecords))
  729. for _, record := range uniqueRecords {
  730. result = append(result, record)
  731. }
  732. return result
  733. }
  734. // Recalculate 合并计算
  735. func Recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  736. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  737. // 合并成2个小时的
  738. for _, v := range neckRingList {
  739. xframeId := util.XFrameId(v.Frameid)
  740. 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
  741. if originalMapData[mapKey] == nil {
  742. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  743. }
  744. originalMapData[mapKey].IsMageData(v, xframeId)
  745. }
  746. currTime := time.Now()
  747. res := make([]*model.NeckActiveHabit, 0)
  748. // 算平均值
  749. for k, v := range originalMapData {
  750. // 过滤掉合并后<6条数据,如果时间太短就晚点再算
  751. if v.RecordCount < model.DefaultRecordCount {
  752. currMaxXframeId := util.FrameIdMapReverse[int32(currTime.Hour())]
  753. activeDateString := fmt.Sprintf("%s %02d:00:00", v.ActiveDate, v.XframeId*2+1)
  754. activeDate, _ := time.Parse(model.LayoutTime, activeDateString)
  755. if currMaxXframeId-v.XframeId <= 1 && currTime.Add(-1*time.Hour).Unix() < activeDate.Unix() {
  756. delete(originalMapData, k)
  757. continue
  758. }
  759. }
  760. v.SumAvg()
  761. }
  762. if len(originalMapData) <= 0 {
  763. return res
  764. }
  765. res = model.NeckRingOriginalMap(originalMapData).ForMatData()
  766. sort.Sort(model.NeckActiveHabitSlice(res))
  767. return res
  768. }
  769. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  770. originalList := make([]*model.NeckRingOriginal, 0)
  771. frameIds := util.FrameIds(data.Frameid)
  772. sql := ""
  773. for _, frameId := range frameIds {
  774. 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)
  775. }
  776. if len(sql) > 0 {
  777. sql = strings.TrimSuffix(sql, "UNION ALL ")
  778. }
  779. if err := e.DB.Raw(sql).Find(&originalList).Error; err != nil {
  780. return nil
  781. }
  782. /*if err := e.DB.Model(new(model.NeckRingOriginal)).
  783. Where("pasture_id = ?", data.PastureId).
  784. Where("neck_ring_number = ?", data.NeckRingNumber).
  785. Where("active_date = ?", data.HeatDate).
  786. Where("frameid IN (?)", frameIds).
  787. Find(&originalList).Error; err != nil {
  788. return nil
  789. }*/
  790. originalList = RemoveDuplicates(originalList)
  791. newDataList := Recalculate(originalList)
  792. if len(newDataList) != 1 {
  793. return nil
  794. }
  795. res := newDataList[0]
  796. res.IsShow = pasturePb.IsShow_No
  797. return res
  798. }
  799. // computeIfPositiveElse 辅助函数来计算过滤值
  800. func computeIfPositiveElse(newValue, prevFilterValue float64, weightPrev, weightNew float64) float64 {
  801. return math.Ceil((prevFilterValue * weightPrev) + (weightNew * newValue))
  802. }
  803. // 计算 score 的逻辑
  804. func calculateScore(habit *model.NeckActiveHabit) int {
  805. // 第一部分逻辑
  806. var part1 float64
  807. switch {
  808. case (habit.CalvingAge <= 1 && habit.Lact >= 1) ||
  809. (habit.CalvingAge >= 2 && habit.CalvingAge <= 13 && (habit.SumRumina+habit.SumIntake) == 0) ||
  810. ((habit.Lact == 0 || habit.CalvingAge >= 14) && habit.ChangeFilter == -99):
  811. part1 = -199
  812. case habit.CalvingAge >= 2 && habit.CalvingAge <= 13:
  813. part1 = math.Min((float64(habit.SumRumina+habit.SumIntake)-(100+math.Min(7, float64(habit.CalvingAge))*60))/10*2, 0)
  814. case habit.ChangeFilter > -99:
  815. part1 = math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinHigh), 0)))*0.2 +
  816. math.Min(0, math.Min(getValueOrDefault(float64(habit.ChangeFilter), 0), getValueOrDefault(float64(habit.SumMinChew), 0)))*0.2 +
  817. getRuminaSumIntakeSumScore(float64(habit.SumRumina+habit.SumIntake)) + getAdditionalScore(habit)
  818. default:
  819. part1 = -299
  820. }
  821. // 第二部分逻辑
  822. var part2 float64
  823. switch {
  824. case habit.FirmwareVersion%100 >= 52:
  825. part2 = 1
  826. case habit.FirmwareVersion%100 >= 30 && habit.FirmwareVersion%100 <= 43:
  827. part2 = 0.8
  828. default:
  829. part2 = 0.6
  830. }
  831. // 最终 score
  832. return DefaultScore + int(math.Floor(part1*part2))
  833. }
  834. // 获取值或默认值
  835. func getValueOrDefault(value, defaultValue float64) float64 {
  836. if value > -99 {
  837. return value
  838. }
  839. return defaultValue
  840. }
  841. // 计算累计反刍得分
  842. func getRuminaSumIntakeSumScore(sum float64) float64 {
  843. switch {
  844. case sum < 80:
  845. return -30
  846. case sum < 180:
  847. return -20
  848. case sum < 280:
  849. return -10
  850. default:
  851. return 0
  852. }
  853. }
  854. // 计算额外得分
  855. func getAdditionalScore(habit *model.NeckActiveHabit) float64 {
  856. var score float64
  857. if (habit.SumRumina+habit.SumIntake < 280 || habit.SumMinHigh+habit.SumMinChew < -50) && habit.SumMaxHigh > 50 {
  858. score += 10
  859. }
  860. if habit.ChangeFilter < -30 && habit.ChangeFilter <= habit.SumMinHigh && habit.ChewFilter < -30 && habit.ChewFilter <= habit.SumMinChew {
  861. score -= 5
  862. }
  863. return score
  864. }