bestpred 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bestpred/__init__.py +13 -0
- bestpred/__main__.py +5 -0
- bestpred/adjust.py +152 -0
- bestpred/cli.py +51 -0
- bestpred/core.py +537 -0
- bestpred/curves.py +231 -0
- bestpred/data/adjust.scs +755 -0
- bestpred/data/tables.json +1 -0
- bestpred/format4.py +141 -0
- bestpred/tables.py +121 -0
- bestpred-0.2.1.dist-info/METADATA +168 -0
- bestpred-0.2.1.dist-info/RECORD +16 -0
- bestpred-0.2.1.dist-info/WHEEL +4 -0
- bestpred-0.2.1.dist-info/entry_points.txt +2 -0
- bestpred-0.2.1.dist-info/licenses/LICENSE +202 -0
- bestpred-0.2.1.dist-info/licenses/NOTICE +65 -0
bestpred/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""bestpred: USDA's best prediction of lactation yields and persistency (BESTPRED 2.0rc7), in Python.
|
|
2
|
+
|
|
3
|
+
A port of the public-domain Fortran and C programs by Paul VanRaden and John Cole (USDA-ARS Animal Genomics and
|
|
4
|
+
Improvement Laboratory), checked against the original. Not affiliated with or endorsed by USDA.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .adjust import adjscs, age_factors, aiplage, pday
|
|
8
|
+
from .core import Result, Settings, TestDay, bestpred
|
|
9
|
+
from .format4 import Format4, results_line, run_format4
|
|
10
|
+
|
|
11
|
+
__all__ = ['Format4', 'Result', 'Settings', 'TestDay', 'adjscs', 'age_factors', 'aiplage', 'bestpred', 'pday',
|
|
12
|
+
'results_line', 'run_format4']
|
|
13
|
+
__version__ = '0.2.1'
|
bestpred/__main__.py
ADDED
bestpred/adjust.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Mature-equivalent factors: aiplage.c (milk, fat, protein) and adjscs.c (SCS), and the date arithmetic they need.
|
|
2
|
+
|
|
3
|
+
C's float arithmetic is kept where it changes the last digits: a float times an int stays a float in C.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from .tables import F32, scs_factors, table
|
|
9
|
+
|
|
10
|
+
AGELIM = ((16, 36), (28, 56), (40, 74), (52, 86), (64, 98), (76, 165)) # age limits (months) by parity 1..6+
|
|
11
|
+
REGDOT = (0, 0, 1, 4, 4, 1, 3, 2, 3, 5, 5, 6) # Holstein region -> previous-days-open region
|
|
12
|
+
BREEDS7 = 'ABGHJMW'
|
|
13
|
+
REGBRD = (0, 0, 0, 1, 2, 3, 2) # breed -> column of the region table (Ayr, Hol, Jer, MS)
|
|
14
|
+
DOMEAN = 120
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _ctrunc(a: int, b: int) -> int:
|
|
18
|
+
"""C integer division (truncates toward zero)."""
|
|
19
|
+
q = abs(a) // abs(b)
|
|
20
|
+
return q if (a >= 0) == (b >= 0) else -q
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _pdo_effect(coef: np.ndarray, pdo: int) -> float:
|
|
24
|
+
"""Previous-days-open effect: c0 + c1*pdo (float) + c2*pdo^2 (double), plus c3*(pdo-150)^2 past 150 days."""
|
|
25
|
+
doprev2 = float(pdo * pdo)
|
|
26
|
+
eff = float(F32(coef[0] + F32(coef[1] * F32(pdo)))) + float(coef[2]) * doprev2
|
|
27
|
+
if pdo > 150:
|
|
28
|
+
eff += float(coef[3]) * float((pdo - 150) * (pdo - 150))
|
|
29
|
+
return eff
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def aiplage(breed: str, age: int, fresh_year: int, fresh_month: int, parity: int, state: int, doprev: int,
|
|
33
|
+
agebase: int = 0) -> tuple[float, float, float]:
|
|
34
|
+
"""Factors that standardize 305-d milk, fat and protein for age, month of calving and previous days open.
|
|
35
|
+
|
|
36
|
+
agebase 0 adjusts to mature equivalent, 36 to 36 months (and so on). `state` is the 2-digit USDA state code."""
|
|
37
|
+
brd = BREEDS7.find(breed[:1]) if breed else -1
|
|
38
|
+
if brd < 0:
|
|
39
|
+
brd = 3
|
|
40
|
+
if brd == 6:
|
|
41
|
+
raise ValueError("breed code 'W' has no age factors in aiplage")
|
|
42
|
+
if not 0 <= state <= 96:
|
|
43
|
+
raise ValueError(f'state code {state} is outside the table (0-96)')
|
|
44
|
+
reg = int(table('region')[state, REGBRD[brd]]) - 1
|
|
45
|
+
if reg < 0 and brd != 5:
|
|
46
|
+
raise ValueError(f'state code {state} has no region in the age-factor tables')
|
|
47
|
+
if parity == 0:
|
|
48
|
+
raise ValueError('parity must be at least 1')
|
|
49
|
+
lac = min(parity - 1, 5)
|
|
50
|
+
a = age
|
|
51
|
+
lo, hi = AGELIM[lac]
|
|
52
|
+
a = lo if a < lo else hi if a > hi else a
|
|
53
|
+
mo = fresh_month - 1
|
|
54
|
+
pdo = doprev
|
|
55
|
+
if (parity > 1 and pdo < 20) or pdo > 305:
|
|
56
|
+
pdo = DOMEAN
|
|
57
|
+
if fresh_year >= 1987:
|
|
58
|
+
yrgp, yrgpp = 4, 1
|
|
59
|
+
else:
|
|
60
|
+
yrgp = _ctrunc(fresh_year - 1963, 6) if fresh_year >= 1969 else 0
|
|
61
|
+
yrgpp = 0
|
|
62
|
+
|
|
63
|
+
def factors(a, lac, pdo, mo):
|
|
64
|
+
if lac > 0:
|
|
65
|
+
lacdo = min(lac, 2) - 1
|
|
66
|
+
if brd == 3:
|
|
67
|
+
regdo = REGDOT[reg]
|
|
68
|
+
eff = [_pdo_effect(table(f'h{t}dop')[regdo, lacdo], pdo) for t in 'mfp']
|
|
69
|
+
else:
|
|
70
|
+
brddo = brd if brd < 3 else brd - 1
|
|
71
|
+
eff = [_pdo_effect(table(f'{t}dop')[brddo, lacdo], pdo) for t in 'mfp']
|
|
72
|
+
else:
|
|
73
|
+
eff = [0., 0., 0.]
|
|
74
|
+
age2 = float(a * a)
|
|
75
|
+
out = []
|
|
76
|
+
prefix = 'abghjm'[brd]
|
|
77
|
+
for t, (trait, yg) in enumerate((('m', yrgp), ('f', yrgp), ('p', yrgpp))):
|
|
78
|
+
name = prefix + trait
|
|
79
|
+
if brd == 5: # Milking Shorthorn: no regions
|
|
80
|
+
regtm = float(table(name + 'regtm')[yg])
|
|
81
|
+
equ0 = float(table(name + 'equ0')[yg, lac, mo])
|
|
82
|
+
equ = table(name + 'equ')[yg, lac]
|
|
83
|
+
else:
|
|
84
|
+
regtm = float(table(name + 'regtm')[reg, yg])
|
|
85
|
+
equ0 = float(table(name + 'equ0')[yg, reg, lac, mo])
|
|
86
|
+
equ = table(name + 'equ')[yg, reg, lac]
|
|
87
|
+
denom = regtm + eff[t] + equ0 + float(F32(equ[0] * F32(a))) + float(equ[1]) * age2
|
|
88
|
+
out.append(regtm / denom)
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
fac = factors(a, lac, pdo, mo)
|
|
92
|
+
if agebase > 0:
|
|
93
|
+
base_lac = _ctrunc(agebase - 18, 13)
|
|
94
|
+
avg = np.zeros(3)
|
|
95
|
+
for month in range(12):
|
|
96
|
+
avg += np.array(factors(agebase, base_lac, 90, month)) / 12
|
|
97
|
+
fac = [f / v for f, v in zip(fac, avg)]
|
|
98
|
+
return fac[0], fac[1], fac[2]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def adjscs(breed: str, parity: int, fresh_month: int, state: int, age: int, dim: int = 305, scs: int = 329) -> int:
|
|
102
|
+
"""Adjusted 100 x SCS for days in milk, age and month of calving (additive factors, 2009 on)."""
|
|
103
|
+
dimfac, agefac, monfac = scs_factors()
|
|
104
|
+
lact = 0 if parity == 1 else 1
|
|
105
|
+
facbrd = 1 if breed[:1] in ('J', 'G') else 0
|
|
106
|
+
age = min(max(age, 18), 120)
|
|
107
|
+
reg = 0 if state <= 23 else 1 if state <= 48 else 2 if state <= 74 else 3
|
|
108
|
+
dim = min(max(dim, 15), 305)
|
|
109
|
+
value = np.rint(scs - dimfac[dim, lact, facbrd] - monfac[fresh_month, reg, facbrd]
|
|
110
|
+
+ (agefac[age, facbrd] - 1) * 300)
|
|
111
|
+
return int(min(max(value, 1), 999))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def age_factors(breed: str, age: int, fresh_year: int, fresh_month: int, parity: int, state: int, doprev: int,
|
|
115
|
+
agebase: int = 0) -> np.ndarray:
|
|
116
|
+
"""agefac(1:4) as bestpred_fmt4 builds it: milk, fat, protein from aiplage, SCS from adjscs (305 d, SCS 3.29)."""
|
|
117
|
+
m, f, p = aiplage(breed, age, fresh_year, fresh_month, parity, state, doprev, agebase)
|
|
118
|
+
s = adjscs(breed, parity, fresh_month, state, age, 305, 329) / 329.
|
|
119
|
+
return np.array([m, f, p, s])
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
MODAYS = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def pday(date8: str) -> int:
|
|
126
|
+
"""Days since 1 Jan 1960 (function pday, by Chris Schanefelter), for a YYYYMMDD date."""
|
|
127
|
+
def num(text):
|
|
128
|
+
text = text.strip()
|
|
129
|
+
return int(text) if text else 0
|
|
130
|
+
year, month, day = num(date8[0:4]) - 1900, num(date8[4:6]), num(date8[6:8])
|
|
131
|
+
if year <= 0:
|
|
132
|
+
return -21916
|
|
133
|
+
leap = year // 4
|
|
134
|
+
number_of_years = year - 60
|
|
135
|
+
year_groups = abs(number_of_years) // 4
|
|
136
|
+
balance_years = abs(number_of_years) - year_groups * 4
|
|
137
|
+
leap = 2 if year == leap * 4 else 1
|
|
138
|
+
month = min(max(month, 1), 12)
|
|
139
|
+
if day == 0:
|
|
140
|
+
day = 1
|
|
141
|
+
days_in = MODAYS[leap - 1]
|
|
142
|
+
if day > days_in[month - 1]:
|
|
143
|
+
day = days_in[month - 1]
|
|
144
|
+
day += sum(days_in[:month - 1])
|
|
145
|
+
if number_of_years <= -1:
|
|
146
|
+
day = 365 - day
|
|
147
|
+
result = -((year_groups * 1461) + day + (balance_years - 1) * 365)
|
|
148
|
+
else:
|
|
149
|
+
if balance_years > 0:
|
|
150
|
+
balance_years = (balance_years - 1) * 365 + 366
|
|
151
|
+
result = year_groups * 1461 + day + balance_years
|
|
152
|
+
return result - 1
|
bestpred/cli.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""bestpred FILE: run Format 4 records (one lactation per line) and print results_v2.dcr lines, as USDA's program does."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .core import TRAITS, Settings
|
|
8
|
+
from .format4 import Format4, results_line, run_format4, with_length_from_tests
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv=None) -> int:
|
|
12
|
+
ap = argparse.ArgumentParser(prog='bestpred', description=__doc__)
|
|
13
|
+
ap.add_argument('file', help='Format 4 records, one per line ("-" for standard input)')
|
|
14
|
+
ap.add_argument('--json', action='store_true', help='print one JSON object per lactation instead')
|
|
15
|
+
ap.add_argument('--mtrait', type=int, default=3, choices=(1, 3, 4))
|
|
16
|
+
ap.add_argument('--use3x', type=int, default=3, choices=(0, 1, 2, 3))
|
|
17
|
+
ap.add_argument('--laclen', type=int, default=305)
|
|
18
|
+
ap.add_argument('--method', default='W', choices=tuple('LWRCT'))
|
|
19
|
+
ap.add_argument('--method-scs', default='G', choices=tuple('LGSDU'))
|
|
20
|
+
ap.add_argument('--units', default='P', choices=('P', 'K'), help='pounds or kilograms, in and out')
|
|
21
|
+
ap.add_argument('--keep-length', action='store_true',
|
|
22
|
+
help="use the record's own length (USDA's program replaces it with the last test day)")
|
|
23
|
+
args = ap.parse_args(argv)
|
|
24
|
+
settings = Settings(mtrait=args.mtrait, use3X=args.use3x, laclen=args.laclen, method=args.method,
|
|
25
|
+
method_scs=args.method_scs, units_in=args.units, units_out=args.units)
|
|
26
|
+
stream = sys.stdin if args.file == '-' else open(args.file)
|
|
27
|
+
with stream:
|
|
28
|
+
for line in stream:
|
|
29
|
+
if not line.strip():
|
|
30
|
+
continue
|
|
31
|
+
rec = Format4.parse(line)
|
|
32
|
+
if not args.keep_length:
|
|
33
|
+
rec = with_length_from_tests(rec)
|
|
34
|
+
res = run_format4(rec, settings)
|
|
35
|
+
if args.json:
|
|
36
|
+
print(json.dumps({
|
|
37
|
+
'cowid': rec.cowid.strip(), 'fresh': rec.fresh, 'parity': rec.lacno,
|
|
38
|
+
'actual': res.yields('actual'), 'mature_equivalent': res.yields('me'),
|
|
39
|
+
'persistency': dict(zip(TRAITS, res.persistency.tolist())),
|
|
40
|
+
'reliability': dict(zip(TRAITS, res.rel_yield.tolist())),
|
|
41
|
+
'persistency_reliability': dict(zip(TRAITS, res.rel_persistency.tolist())),
|
|
42
|
+
'dcr': {'milk': res.dcr_milk, 'components': res.dcr_components, 'scs': res.dcr_scs},
|
|
43
|
+
'tests': dict(zip(TRAITS, res.ntests.tolist())),
|
|
44
|
+
}, default=float))
|
|
45
|
+
else:
|
|
46
|
+
print(results_line(rec, res))
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == '__main__':
|
|
51
|
+
sys.exit(main())
|