forked from jvail/dairy.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dairy.py
1755 lines (1755 loc) · 49.4 KB
/
dairy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Dairy cow grouping.
#
# It creates groups a such that the total deviation of energy and protein requirements relative to the cow's intake
# capacity from the groups average is minimized (similar to McGilliard 1983). In the resulting groups animals in each
# group require a "similar" energy and protein density of the ration. The results of each run slightly defer depending on
# the inital guess of k-means. Therefore it runs several times and returns the best result.
#
# REFERENCES
#
# McGilliard, M.L., Swisher, J.M. and James, R.E. 1983. Grouping lactating cows by nutritional requirements for feeding.
# Journal of Dairy Science 66(5):1084-1093.
#
# k-means.js implementation from https://github.com/cmtt/kmeans-js
#
# LICENSE
#
# Copyright 2014 Jan Vaillant <[email protected]>
# Copyright 2014 Lisa Baldinger <[email protected]>
#
# Distributed under the MIT License. See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT
#
# Any publication for which this file or a derived work is used must include an a reference to:
#
# Vaillant, J. and Baldinger, L. 2016.
# Application note: An open-source JavaScript library to simulate dairy cows and young stock,
# their growth, requirements and diets.
# Computers and Electronics in Agriculture, Volume 120, January 2016, Pages 7–9
#
# TODO
#
# - implement different strategies e.g. (req. intake capacity-1, absolute requirements, days in milk)
# */
#
# dairy = dairy ||:}
#
# dairy.group = (function ():
#
# round = math.round
# , floor = math.floor
# , random = math.random
# , log = math.log
# , pow = math.pow
# , sqrt = math.sqrt
# , distance = function(a, b):
# return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2))
# }
# # TODO: refactor original code from cmtt kmeans.. */
# , sortBy = function (a, b, c):
# c = a.slice()
# return c.sort(function (d, e):
# d = b(d)
# e = b(e)
# return (d < e ? -1: d > e ? 1: 0)
# })
# }
#
#
#
# # returns total of squared differences */
#
# sumSquaredDifferences = function (points, centroids):
#
# sum = 0
# , ps = points.length
#
#
# for (p = 0 p < ps p++):
# point = points[p]
# , centroid = centroids[point.k]
# , dif_x = pow(point.x - centroid.x, 2)
# , dif_y = pow(point.y - centroid.y, 2)
#
# sum += dif_x + dif_y
# }
#
# return sum
#
# }
#
# # nomalize (0-1) data. Coordinates in original data are altered */
#
# doNormalize = function (points):
#
# ps = points.length
#
# # get minimum and maximum x */
# points.sort(function (a, b):
# return a.x - b.x
# })
#
# x_min = points[0].x
# x_max = points[ps - 1].x
#
# # get minimum and maximum y */
# points.sort(function (a, b):
# return a.y - b.y
# })
#
# y_min = points[0].y
# y_max = points[ps - 1].y
#
# # normalize */
# for (p = 0 p < ps p++):
# point = points[p]
# point.x = (point.x - x_min) / (x_max - x_min)
# point.y = (point.y - y_min) / (y_max - y_min)
# }
#
# }
#
# # k-means++ initialization from https://github.com/cmtt/kmeans-js */
#
# kmeansplusplus = function (points, ks):
#
# ps = points.length
#
# # determine the amount of tries */
# D = []
# , ntries = 2 + round(log(ks))
# , centroids = []
#
#
# # Choose one center uniformly at random from the data points. */
# p0 = points[floor(random() * ps)]
#
# centroids.push({
# x: p0.x
# , y: p0.y
# , k: 0
# })
#
# # For each data point x, compute D(x), the distance between x and the nearest center that has already been chosen. */
# for (i = 0 i < ps ++i)
# D[i] = pow(distance(p0, points[i]), 2)
#
# Dsum = D.reduce(function(a, b):
# return a + b
# })
#
# # Choose one new data point at random as a new center, using a weighted probability distribution where a point x is
# chosen with probability proportional to D(x)2. (Repeated until k centers have been chosen.) */
# for (k = 1 k < ks ++k):
#
# bestDsum = -1, bestIdx = -1
#
# for (i = 0 i < ntries ++i):
# rndVal = floor(random() * Dsum)
#
# for (n = 0 n < ps ++n):
# if (rndVal <= D[n]):
# break
# } else:
# rndVal -= D[n]
# }
# }
#
# tmpD = []
# for (m = 0 m < ps ++m):
# cmp1 = D[m]
# cmp2 = pow(distance(points[m], points[n]), 2)
# tmpD[m] = cmp1 > cmp2 ? cmp2: cmp1
# }
#
# tmpDsum = tmpD.reduce(function(a, b):
# return a + b
# })
#
# if (bestDsum < 0 || tmpDsum < bestDsum):
# bestDsum = tmpDsum, bestIdx = n
# }
# }
#
# Dsum = bestDsum
#
# centroid =:
# x: points[bestIdx].x
# , y: points[bestIdx].y
# , k: k
# }
#
# centroids.push(centroid)
#
# for (i = 0 i < ps ++i):
# cmp1 = D[i]
# cmp2 = pow(distance(points[bestIdx], points[i]), 2)
# D[i] = cmp1 > cmp2 ? cmp2: cmp1
# }
# }
#
# # sort descending if x is energy density */
# centroids.sort(function (a, b):
# return b.x - a.x
# })
#
# # set k === index */
# for (c = 0, cs = centroids.length c < cs c++)
# centroids[c].k = c
#
# return centroids
#
# }
#
# kmeans = function (points, centroids):
#
# converged = false
# , ks = centroids.length
# , ps = points.length
#
#
# while (!converged):
#
# i
# converged = true
#
# # Prepares the array of sums. */
# sums = []
# for (k = 0 k < ks k++)
# sums[k] =: x: 0, y: 0, items: 0 }
#
# # Find the closest centroid for each point. */
# for (p = 0 p < ps ++p):
#
# distances = sortBy(centroids, function (centroid):
# return distance(centroid, points[p])
# })
#
# closestItem = distances[0]
# k = closestItem.k
#
# # When the point is not attached to a centroid or the point was attached to some other centroid before,
# the result differs from the previous iteration. */
# if (typeof points[p].k !== 'number' || points[p].k !== k)
# converged = false
#
# # Attach the point to the centroid */
# points[p].k = k
#
# # Add the points' coordinates to the sum of its centroid */
# sums[k].x += points[p].x
# sums[k].y += points[p].y
#
# ++sums[k].items
# }
#
# # Re-calculate the center of the centroid. */
# for (k = 0 k < ks ++k):
# if (sums[k].items > 0):
# centroids[k].x = sums[k].x / sums[k].items
# centroids[k].y = sums[k].y / sums[k].items
# }
# centroids[k].items = sums[k].items
# }
# }
#
# }
#
# get = function (data, options):
#
# ks = options.k
# , runs = options.runs
# , normalize = options.normalize
# , xAttribute = options.xAttribute
# , yAttribute = options.yAttribute
# , points = data
# , result = []
#
#
# if (typeof xAttribute === 'string' && xAttribute.length > 0
# && typeof yAttribute === 'string' && yAttribute.length > 0):
# # prepare data: add x, y property */
# for (p = 0, ps = data.length p < ps p++):
# points[p].x = data[p][xAttribute]
# points[p].y = data[p][yAttribute]
# }
# }
#
# if (normalize)
# doNormalize(points)
#
# for (run = 0 run < runs run++):
#
# # stores result of each run */
# result[run] =: centroids: [], sum: Infinity }
#
# # inital guess */
# centroids = kmeansplusplus(points, ks)
#
# # store initial centroids from kmeans++ in order to re-run */
# for(k = 0 k < ks k++):
# result[run].centroids[k] =:
# x: centroids[k].x,
# y: centroids[k].y
# }
# }
#
# # run kmeans */
# kmeans(points, centroids)
#
# # calculate differences */
# result[run].sum = sumSquaredDifferences(points, centroids)
#
# }
#
# # find best result */
# result.sort(function (a, b):
# return a.sum - b.sum
# })
#
# # re-use initial centroids produced by kmeans++ from best run */
# centroids = []
# for (k = 0 k < ks k++):
# centroid =:
# x: result[0].centroids[k].x
# , y: result[0].centroids[k].y
# , k: k
# }
# centroids[k] = centroid
# }
#
# # run again with best initial centroids */
# kmeans(points, centroids)
#
# return sumSquaredDifferences(points, centroids)
#
# }
#
# return:
# get: get
# }
#
# }())
#
#
# #
# Simple, deterministic herd structure model
#
# LICENSE
#
# Copyright 2014 Jan Vaillant <[email protected]>
# Copyright 2014 Lisa Baldinger <[email protected]>
#
# Distributed under the MIT License. See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT
#
# Any publication for which this file or a derived work is used must include an a reference to:
#
# Vaillant, J. and Baldinger, L. 2016.
# Application note: An open-source JavaScript library to simulate dairy cows and young stock,
# their growth, requirements and diets.
# Computers and Electronics in Agriculture, Volume 120, January 2016, Pages 7–9
#
# TODO
#
# - add calving pattern option (seasonal)
# - add parity 4 (>3) to output
# */
#
# dairy = dairy ||:}
#
# dairy.herd = (function ():
#
# pow = math.pow
# , round = math.round
# , floor = math.floor
# , ceil = math.ceil
# , IT_MIN = 1e2 # min iterations */
# , IT_MAX = 1e6 # max. iterations */
# , WEEKS_IN_MONTH = 30.5 / 7
#
#
# # constant parameters with default values */
# cons =:
# ageFirstCalving: 24
# , femaleCalfRate: 0.47
# , stillBirthRate: 0.07
# , youngStockCullRate: 0.155
# , replacementRate: 0.30
# , calvingInterval: 12.0
# , herdSize: 100
# , gestationPeriod: 9.0
# , dryPeriode: 2.0
# }
#
# # variables */
# vars =:
# # stores cow object of cows of same age in month per index
# age is month after first calving
# :
# no: no. of cows
# , lac: lactation no.
# , dry: if cow is dry
# , WG: week of gestation
# , WL: week of lactation
# } */
# cows: []
# # no. of young stock per age month since birth */
# , young: []
# # no. of cows */
# , noCows: 0
# , heifersBought: []
# , heifersSold: []
# , lac: []
# , sim: []
# }
#
# #
# run simulation until herd structure does not change anymore (or no. cows equals zero)
# returns an array of with young stock count per age month and cows with
#
# lac [#] lactation no.
# dry [bool] if cow is dry
# WG [#] week of gestation
# WL [#] week of lactation
# age [month]
#
# initialize parameters (object)
#
# ageFirstCalving [month]
# femaleCalfRate [-] fraction female calfes of all calves born
# stillBirthRate [-] fraction of dead born calves
# youngStockCullRate [-] fraction of young stock that do not make it to 1st lactation
# replacementRate [-] fraction of cows replaced each year
# calvingInterval [month] month inbetween clavings
# herdSize [#] no. of cows in herd
# gestationPeriod [month] length gestation period
# dryPeriode [month] length dry period
# */
#
# get = function (options):
#
# # overwrite default default values if provided and valid */
# for (prop in options):
# if (options.hasOwnProperty(prop))
# cons[prop] = (typeof options[prop] === 'number' && !isNaN(options[prop])) ? options[prop]: cons[prop]
# }
#
# # reset values */
# vars.cows = []
# vars.young = []
# vars.noCows = 0
# vars.heifersBought = []
# vars.heifersSold = []
# vars.sim = []
#
# # varriable shortcuts */
# ci = cons.calvingInterval
# , hs = cons.herdSize
# , dp = cons.dryPeriode
# , gp = cons.gestationPeriod
# , sb = cons.stillBirthRate
# , yc = cons.youngStockCullRate
# , fc = cons.femaleCalfRate
# , ac = cons.ageFirstCalving
# , rr = cons.replacementRate
# , cows = vars.cows
# , young = vars.young
# , converged = false
# , its = 0 # no. iterations */
#
#
# # initialize cow array with some meaningfull values to have a starting point
# cows at age ageFirstCalving + m within calving interval. eqal distribution of status througout calvingInterval */
# l = 0
# while (l < 4): # just set cows up to lactation 4 (could be any) */
#
# for (m = 0 m < ci m++):
# cows[m + l * (ci - 1)] =:
# no: (hs / ci) / 4 # devide by 4 because we only initialize for cows till fourth lactation */
# , lac: l + 1
# , dry: (m >= ci - dp) ? true: false
# , WG: (m >= ci - gp) ? (ci - gp) * WEEKS_IN_MONTH: 0
# , WL: (m >= ci - dp) ? 0: m * WEEKS_IN_MONTH
# , age: ac + ci * (l - 1) + m
# }
# vars.noCows += (hs / ci) / 4
# }
#
# l++
# }
#
# # Initialize young stock array. Apply death rate equally distributed as compound interest:
# K_interest = K_start * (1 + p / 100)^n <=> p / 100 = (K_interest / K_start)^(1/n) - 1
# K_start = (hs / ci) * (1 - sb) * fc */
# young[0] = (hs / ci) * (1 - sb) * fc * pow(1 - yc, 1 / ac)
# for (m = 1 m < ac m++)
# young[m] = young[m - 1] * pow(1 - yc, 1 / ac) # no. young stock per age month */
#
# # loop until converged i.e. avg. lactation within herd with no. cows equals herd size does not change anymore.
# Each iteration step equals one month */
# while (!converged):
#
# # remove culled young stock */
# for (y = 0, ys = young.length y < ys y++)
# young[y] = young[y] * pow(1 - yc, 1 / ac)
#
# # replacement per month add newly replaced animals to the beginning of the array
# all age classes within herd are equally replaced */
#
# newFemaleCalves = 0
# if (young[young.length - 1] > 0 ): // heifers available
# # add new calves to young cattle */
# # from heifers */
# newFemaleCalves += young[ac - 1] * (1 - sb) * fc
# # from cows */
# }
#
# vars.noCows = 0
# # start at age group previously c = 0 */
# for (c = 0, cs = cows.length c < cs c++):
#
# cow = cows[c]
#
# if (cow.no > 0):
#
# # replacement */
# cow.no = cow.no * (1 - (rr / 12)) // avg monthly replacement
# cow.age++
#
# // update pregnancy, dry ...
# if (!cow.dry):
# cow.WL += WEEKS_IN_MONTH
# if (cow.WG > 0):
# cow.WG += WEEKS_IN_MONTH
# } else:
# if (cow.WL > (ci - gp) * WEEKS_IN_MONTH)
# cow.WG = WEEKS_IN_MONTH
# }
# # check if now dry */
# if (cow.WL > (ci - dp) * WEEKS_IN_MONTH):
# cow.WL = 0
# cow.dry = true
# }
# } else: // dry cows
# cow.WG += WEEKS_IN_MONTH
# # check if cow calved */
# if (cow.WG > gp * WEEKS_IN_MONTH):
# newFemaleCalves += cow.no * (1 - sb) * fc
# cow.lac += 1
# cow.dry = false
# cow.WG = 0
# cow.WL = 0
# }
# }
#
# }
#
# vars.noCows += cow.no
#
# } // cows loop
#
# # no. available heifers form young stock */
# noHeifers = young.pop()
# # move only the no. of heifers that are needed to keep/reach total herdSize */
# noHeifersToHerd = (vars.noCows < hs) ? ((hs - vars.noCows < noHeifers) ? (hs - vars.noCows): noHeifers): 0
# vars.heifersSold.unshift(noHeifers - noHeifersToHerd)
#
# noHeifersBought = 0
# if (noHeifersToHerd < hs - vars.noCows):
# noHeifersToHerd = hs - vars.noCows
# noHeifersBought = hs - vars.noCows + noHeifersToHerd
# }
# vars.heifersBought.unshift(noHeifersBought)
#
# cows.unshift({
# no: noHeifersToHerd
# , lac: 1
# , dry: false
# , WG: 0
# , WL: 0
# , age: ac
# })
#
# vars.noCows += noHeifersToHerd
#
# # add new female calves at beginning of array and apply culling rate */
# young.unshift(newFemaleCalves * pow(1 - yc, 1 / ac))
#
# # calculate cows per lactation */
# vars.lac = []
# for (c = 0, cs = cows.length c < cs c++):
# if (!vars.lac[cows[c].lac - 1])
# vars.lac[cows[c].lac - 1] = 0
# vars.lac[cows[c].lac - 1] += cows[c].no
# }
#
# lacSum = 0
# # calculate avg. lactation */
# for (l = 0, ls = vars.lac.length l < ls l++):
# lacSum += vars.lac[l] * (l + 1)
# }
#
# # debug max. lac 20 */
# for (l = 0 l < 20 l++):
# if (!vars.sim[l])
# vars.sim[l] = []
# no = vars.lac[l]
# vars.sim[l].push(no ? no: 0)
# }
#
# if ((its > IT_MIN && round(vars.noCows) === hs && math.round(avg_lac * 1e6) === round(lacSum / vars.noCows * 1e6))
# || its > IT_MAX || round(vars.noCows) === 0 || isNaN(vars.noCows)):
# converged = true
# }
#
# avg_lac = lacSum / vars.noCows
# its++
#
# } # simulation loop */
#
# herd =:
# cowsPerLac: []
# , cows: []
# , sim: vars.sim
# , heifersBought: round(vars.heifersBought[0])
# , heifersSold: round(vars.heifersSold[0])
# , young: []
# }
#
# # add young stock */
# for (i = 0, is = vars.young.length i < is i++)
# herd.young.push({ age: i + 1, no: round(vars.young[i]) })
#
# # we need only cows of parity 1, 2 or >2. Code below as option? */
# // sum = 0
# // for (l = 0, ls = vars.lac.length l < ls l++):
# // if (sum === hs)
# // break
# // if (sum + ceil(vars.lac[l]) > hs)
# // herd.cowsPerLac[l] = hs - sum
# // else
# // herd.cowsPerLac[l] = ceil(vars.lac[l])
# // sum += herd.cowsPerLac[l]
# // }
#
# herd.cowsPerLac[0] = round(vars.lac[0])
# herd.cowsPerLac[1] = round(vars.lac[1])
# herd.cowsPerLac[2] = hs - (herd.cowsPerLac[0] + herd.cowsPerLac[1])
#
# for (l = 0, ls = herd.cowsPerLac.length l < ls l++):
#
# DPP_increment = ci * 30.5 / ((herd.cowsPerLac[l] === 1) ? math.random() * ci: herd.cowsPerLac[l])
# DPP = DPP_increment * 0.5
#
# for (c = 0, cs = herd.cowsPerLac[l] c < cs c++):
#
# herd.cows.push({
# DPP: round(DPP)
# , isDry: (DPP > 30.5 * (ci - dp)) ? true: false
# , DIM: (DPP > 30.5 * (ci - dp)) ? 0: round(DPP)
# , DG: (DPP - 30.5 * (ci - gp) > 0) ? round(DPP - 30.5 * (ci - gp)): 0
# , AGE: round(ac + l * ci + DPP / 30.5)
# , AGE_days: round((ac + l * ci) * 30.5 + DPP)
# , P: l + 1
# })
#
# DPP += DPP_increment
#
# }
#
# }
#
# return herd
#
# }
#
# return:
# get: get
# }
#
# }())
#
#
# #
# Feed intake of cows and young stock is predicted according to the French fill value system described in Agabriel (2010).
#
# The general functional principal of the INRA fill value system is as follows: The sum of all fill values of the feeds
# equals the intake capacity of the animal. While the intake capacity of the animals is based on animal-related
# parameters, the fill values of the feeds are based on feed-related parameters.
#
# Although not mentioned in Delagarde et al. (2011), we assume that the feed intake restrictions that apply for
# grazing dairy cows also apply for grazing heifers, because they are based on non-nutritional factors linked to sward
# availability and grazing management, not on nutritional factors linked to animal characteristics.
#
# The prediction of feed intake at grazing uses a simplified GrazeIn algorithm.
#
# GrazeMore, "Improving sustainability of milk production systems in the European Union through increasing reliance on
# grazed pasture" was an EU research project that ran from 2000-2004. It involved the development of a grazing decision
# support system to assist farmers in improving the use of grazed grass for milk production. In order to build the DSS,
# a European herbage growth prediction model and a European herbage intake prediction model were produced. Therefore
# GrazeIn is the only currently available intake prediction for grazing cows that is based on European data.
#
# The feed intake prediction in GrazeIn is based on the French INRA fill unit system and adapted to grazing dairy cows.
# The authors argue that because European cows don´t graze all year long and are often supplemented, a general model of
# intake is needed rather than one specialized on indoor feeding or grazing.
#
# Because GrazeIn in based on the INRA fill value system, in some cases equations from Agabriel (2010) are used.
#
# Fill values (FV) for cows are expressed in the unit LFU, lactating fill unit (UEL, unite encombrement lait) and CFU,
# cattle fill unit (UEB, unite encombrement bovin) for young stock.
#
# REFERENCES
#
# Faverdin, P., Baratte, C., Delagarde, R. and Peyraud, J.L. 2011. GrazeIn: a model of herbage intake and milk production
# for grazing dairy cows. 1. Prediction of intake capacity, voluntary intake and milk production during lactation. Grass
# and Forage Science 66(1):29-44.
#
# Delagarde, R., Faverdin, P., Baratte, C. and Peyraud, J.L. 2011a. GrazeIn: A model of herbage intake and milk production
# for grazing dairy cows. 2. Prediction of intake under rotational and continuously stocked grazing management. Grass and
# Forage Science 66(1):45–60.
#
# Agabriel, J. (2010). Alimentation des bovins, ovins et caprins. Besoins des animaux - Valeurs des aliments. Tables INRA
# 2010. Editions Quae, France.
#
# LICENSE
#
# Copyright 2014 Jan Vaillant <[email protected]>
# Copyright 2014 Lisa Baldinger <[email protected]>
#
# Distributed under the MIT License. See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT
#
# Any publication for which this file or a derived work is used must include an a reference to:
#
# Vaillant, J. and Baldinger, L. 2016.
# Application note: An open-source JavaScript library to simulate dairy cows and young stock,
# their growth, requirements and diets.
# Computers and Electronics in Agriculture, Volume 120, January 2016, Pages 7–9
#
# TODO
#
# - PLPOT in IC and GSR: is it zero for dry cows or still PLPOT?
# */
#
# dairy = dairy ||:}
#
# dairy.intake = (function ():
#
# exp = math.exp
# , log = math.log
# , pow = math.pow
# , min = math.min
# , Σ = function (a):
# sum = 0
# for (i = 0, is = a[0].length i < is i++)
# sum += a[0][i] * a[1][i]
# return sum
# }
#
#
# function is_null_or_undefined (x):
# return x === null || x === undefined
# }
#
#
# #
# TODO: Funktion rätselhaft, da DMI = Fs + Cs + HI_g
#
# DMI [kg] dry matter intake
# Fs [kg] array of feeds
# FVs_f [LFU] array of forage fill values
# Cs [kg] array of concentrates
# Cs_f [LFU] array of concentrate fill values
# FV_h [LFU] herbage fill value
# HI_r [-] relative herbage intake (0-1)
# HI_g [kg] herbage intake at grazing
# */
#
# DMI = function (Fs, FVs_f, Cs, FVs_c, FV_h, HI_r, HI_g):
#
# DMI = 0
# , DMI_f = Σ([Fs, FVs_f])
# , DMI_c = Σ([Cs, FVs_c])
#
#
# DMI = DMI_f + DMI_c + (FV_h/HI_r * HI_g)
#
# return DMI
#
# }
#
# #
# Agabriel (2010), eqs. 2.3 & 4.5
#
# Equation to calculate the intake capacity.
#
# The intake capacity of the cow is not calculated acc. to Faverdin et al. (2011), because the appearance of MPprot
# (potential milk production modified by protein intake) is problematic since protein intake is unkown at the time of
# feed intake prediction. Instead, the previous Agabriel (2010) version is used:
#
# In GrazeIn, Pl_pot represents the potential milk yield of a cow, not the actual milk yield. This is done in order
# to avoid milk yield driving feed intake (pull-situation). In SOLID-DSS, values for milk yield are taken from the
# lactation curves modelled within the herd model. These lactation curves are based on input by the user, and thereby
# represent average milk yields instead of actual ones, so they can be interpreted as a potential under the given
# circumstances.
#
# IC [LFU or CFU] intake capacity ~ DMI @ FV = 1
# BW [kg] body weight
# PLPOT [kg day-1] milk yield, potential
# BCS [-] body condition score (1-5)
# WL [week] week of lactation
# WG [week] week of gestation (0-40)
# AGE [month] age in month
# p [#] parity
# */
#
# IC = function (BW, PLPOT, BCS, WL, WG, AGE, p):
#
# IC = 0
#
# if (p > 0): # cows */
#
# IC = (13.9 + (BW - 600) * 0.015 + PLPOT * 0.15 + (3 - BCS) * 1.5) * IL(p, WL) * IG(WG) * IM(AGE)
#
# } elif (p === 0): # young stock */
#
# if (BW <= 150)
# IC = 0.039 * pow(BW, 0.9) + 0.2
# elif (150 < BW <= 290)
# IC = 0.039 * pow(BW, 0.9) + 0.1
# else
# IC = 0.039 * pow(BW, 0.9)
#
# }
#
# return IC
#
# }
#
# #
# Agabriel (2010) eq. 2.3f
#
# The equation for the index of lactation. .
#
# IL [-] index lactation (0-1)
# p [#] parity
# WL [week] week of lactation
# */
#
# IL = function IL(p, WL):
#
# # if cow is dry IL = 1 */
# IL = 1
#
# if (p === 1 && WL > 0)
# IL = 0.6 + (1 - 0.6) * (1 - exp(-0.16 * WL))
# elif (p > 1 && WL > 0)
# IL = 0.7 + (1 - 0.7) * (1 - exp(-0.16 * WL))
#
# return IL
#
# }
#
# #
# Agabriel (2010) eq. 2.3f
#
# The equation for the index of gestation.
#
# IG [-] index gestation (0-1)
# WG [week] week of gestation (0-40)
# */
#
# IG = function (WG):
#
# return 0.8 + 0.2 * (1 - exp(-0.25 * (40 - WG)))
#
# }
#
# #
# Agabriel (2010) eq. 2.3f
#
# The equation for the index of maturity.
#
# IM [-] index maturity (0-1)
# AGE [month] month
# */
#
# IM = function (AGE):
#
# return -0.1 + 1.1 * (1 - exp(-0.08 * AGE))
#
# }
#
# #
# Agabriel (2010), Table 8.1.
#
# The general equation for calculating forage fill values.
#
# The QIL and QIB values are calculated in feed.evaluation, details see there.
#
# FV_f [LFU or CFU kg-1 (DM)] forage fill value (is LFU for cows and CFU for young stock)
# QIX [g kg-1] ingestibility in g per kg metabolic live weight (is QIL for cows and QIB for young stock)
# p [#] parity
# */
#
# FV_f = function (QIX, p):
#
# if (p > 0) # cows */
# return 140 / QIX
# else # young stock */
# return 95 / QIX
#
# }
#
# #
# Faverdin et al. (2011) eq. 11
#
# Equation for calculating concentrate fill value.
#
# One of the factors influencing the concentrate fill value is the fill value of the forage base.
# Because the total diet is unknown prior to the allocation of feeds, the weighted mean of the FV of all available
# forages for the group of cows and the time period in question is used for FV_fr.
#
# FV_c [LFU or CFU kg-1 (DM)] concentrate fill value (lactating fill unit, unite encombrement lait)
# FV_fs [LFU] weighted FV of forages in ration
# GSR [-] global substitution rate (0-1)
# */
#
# FV_c = function (FV_fs, GSR):
#
# return FV_fs * GSR
#
# }
#
# #
# Equation to estimate the fill value of forages in a diet from the cow's requirements prior to ration optimization.
# This is based on the fact that on average a feed's fill value will descrease with increasing energy content. The
# estimated FV_fs is used to calculate a concentrate fill value (see FV_cs). We need it if we what to keep the diet LP
# linear.
# The regression was calculated from all forages available in Agabriel 2010. Details and R script in ../doc/FV_f.
#
# FV_fs_diet [LFU or CFU kg-1 (DM)] Estimated fill value of forages in diet
# E_fs [UFL] Total energy content of forages in diet
# FV_fs [LFU] Total fill values of forages in diet
# p [#] parity
# */
#
# FV_fs_diet = function (E_fs, FV_fs, p):
#
# if (p > 0)
# return -0.489 * E_fs / FV_fs + 1.433
# else
# return -0.783 * E_fs / FV_fs + 1.688
#
# }
#
# #
# Estimate an average concentrate fill value. We assume that requirements are met i.e. cows with BWC >= 0 have a zero
# energy balance.
#
# TODO:
# - simplify to an equation?
# - use this as a better estimate of DMI instead of DMI = IC (FV ~ 1)?
#
# FV_cs_diet [LFU kg-1 (DM)] estimated fill value of concentrates in diet
# E_req [UFL] Energy requirements of a cow (in UFL!)
# IC [LFU] Intake capacity of a cow
# c_mx [kg kg-1] Maximum fraction (DM) of concentrates in diet (optional, defaults to 0.5 which is the
# range the INRA system is applicable)
# PLPOT [kg day-1] milk yield, potential
# p [#] parity
# BWC [kg] body weight change
# */
#
# FV_cs_diet = function (E_req, IC, c_mx, PLPOT, p, BWC):
#
# FV_cs_diet = 0
#
# if (is_null_or_undefined(c_mx) || c_mx > 0.5)
# c_mx = 0.5
#
# c = 0 # fraction of conc. in diet [kg (DM) kg-1 (DM)] */
# , c_kg = 0 # kg conc. in diet */
# , E_f = E_req # energy requirements covered by forage */
# , IC_f = IC # IC covered by forage */
# , c_fvs = [] # store conc. fill values */
# , c_fv = 0 # estimated conc. fill value */
# , f_fv = 0 # estimated forage fill value */
# , s = 0 # substitution rate */
#
#
# # fixed to a max. UFL / UEL value observed in feeds */
# if (E_f / IC_f > 1.15)
# E_f = E_req = IC_f * 1.15
#
# while (true):
#
# # staring from a diet with zero kg conc. we add conc. till we reach c_mx */
# f_fv = FV_fs_diet(E_f, IC_f, p)
# s = GSR(c_kg, DEF(E_f, IC_f), PLPOT, p, BWC, f_fv)
# c_fv = f_fv * s
# c = c_kg / (IC_f / f_fv + c_kg)
#
# if (c >= c_mx)
# break
#
# c_fvs.push(c_fv)
#
# # add concentrate to the diet */
# c_kg += 0.5
# # we assume the concentrate's UFL content is 1.05. In fact the result is not very sensitive to UFL of conc. */
# E_f = E_req - c_kg * 1.05
# IC_f = IC - c_kg * c_fv